New tests.
authorMarek Safar <marek.safar@gmail.com>
Tue, 27 Apr 2010 08:01:17 +0000 (08:01 -0000)
committerMarek Safar <marek.safar@gmail.com>
Tue, 27 Apr 2010 08:01:17 +0000 (08:01 -0000)
svn path=/trunk/mcs/; revision=156162

2032 files changed:
COPYING.LIB
ChangeLog
LICENSE
Makefile.am
README
autogen.sh
build-mingw32.sh
configure.in
data/ChangeLog
data/Makefile.am
data/dotnet.pc.in
data/dotnet35.pc.in
data/mono.pc.in [new file with mode: 0644]
data/net_4_0/machine.config
data/system.web.mvc2.pc.in [new file with mode: 0644]
docs/ChangeLog
docs/Makefile.am
docs/jit-imt
eglib/ChangeLog
eglib/configure.ac
eglib/src/.gitignore
eglib/src/Makefile.am
eglib/src/glib.h
eglib/src/goutput.c
eglib/src/gptrarray.c
eglib/src/gshell.c
eglib/test/.gitignore
eglib/test/Makefile.am
eglib/test/ptrarray.c
eglib/test/shell.c
libgc/ChangeLog
libgc/configure.in
libgc/darwin_stop_world.c
libgc/include/private/gcconfig.h
man/ChangeLog
man/mono.1
man/monolinker.1
man/monop.1
mcs/ChangeLog
mcs/Makefile
mcs/build/ChangeLog
mcs/build/Makefile
mcs/build/common/ChangeLog
mcs/build/common/Consts.cs.in
mcs/build/common/basic-profile-check.cs
mcs/build/config-default.make
mcs/build/gensources.sh [new file with mode: 0644]
mcs/build/library.make
mcs/build/profiles/monotouch_bootstrap.make
mcs/build/profiles/moonlight.make [new file with mode: 0644]
mcs/build/profiles/moonlight_bootstrap.make [new file with mode: 0644]
mcs/build/profiles/moonlight_raw.make [new file with mode: 0644]
mcs/build/profiles/net_2_1.make [deleted file]
mcs/build/profiles/net_2_1_bootstrap.make [deleted file]
mcs/build/profiles/net_2_1_raw.make [deleted file]
mcs/build/profiles/net_4_0_bootstrap.make
mcs/build/rules.make
mcs/class/ChangeLog
mcs/class/Makefile
mcs/class/Managed.Windows.Forms/System.Windows.Forms/ChangeLog
mcs/class/Managed.Windows.Forms/System.Windows.Forms/DataGridView.cs
mcs/class/Managed.Windows.Forms/System.Windows.Forms/DataGridViewCellCollection.cs
mcs/class/Managed.Windows.Forms/System.Windows.Forms/DataGridViewColumn.cs
mcs/class/Managed.Windows.Forms/System.Windows.Forms/DataGridViewColumnCollection.cs
mcs/class/Managed.Windows.Forms/System.Windows.Forms/ListView.cs
mcs/class/Managed.Windows.Forms/System.Windows.Forms/NotifyIcon.cs
mcs/class/Managed.Windows.Forms/System.Windows.Forms/RichTextBox.cs
mcs/class/Managed.Windows.Forms/System.Windows.Forms/Theme.cs
mcs/class/Managed.Windows.Forms/System.Windows.Forms/ThemeWin32Classic.cs
mcs/class/Managed.Windows.Forms/System.Windows.Forms/ToolStrip.cs
mcs/class/Managed.Windows.Forms/System.Windows.Forms/ToolStripDropDownItem.cs
mcs/class/Managed.Windows.Forms/System.Windows.Forms/ToolStripItem.cs
mcs/class/Managed.Windows.Forms/System.Windows.Forms/ToolStripLabel.cs
mcs/class/Managed.Windows.Forms/System.Windows.Forms/ToolStripMenuItem.cs
mcs/class/Managed.Windows.Forms/System.Windows.Forms/ToolStripSplitButton.cs
mcs/class/Managed.Windows.Forms/System.Windows.Forms/ToolTip.cs
mcs/class/Managed.Windows.Forms/System.Windows.Forms/TreeNodeCollection.cs
mcs/class/Managed.Windows.Forms/System.Windows.Forms/TreeView.cs
mcs/class/Managed.Windows.Forms/System.Windows.Forms/XplatUIX11.cs
mcs/class/Managed.Windows.Forms/Test/System.Windows.Forms/ChangeLog
mcs/class/Managed.Windows.Forms/Test/System.Windows.Forms/DataGridViewColumnCollectionTest.cs
mcs/class/Managed.Windows.Forms/Test/System.Windows.Forms/TreeViewTest.cs
mcs/class/Microsoft.Build.Engine/ChangeLog
mcs/class/Microsoft.Build.Engine/Makefile
mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/BuildEngine.cs
mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/BuildTask.cs
mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ChangeLog
mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ConsoleLogger.cs
mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Engine.cs
mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/LogExtensions.cs [new file with mode: 0644]
mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Project.cs
mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/TaskEngine.cs
mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Toolset.cs [new file with mode: 0644]
mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ToolsetCollection.cs [new file with mode: 0644]
mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ToolsetDefinitionLocations.cs [new file with mode: 0644]
mcs/class/Microsoft.Build.Engine/Microsoft.Build.Engine.dll.sources
mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/ChangeLog
mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/Consts.cs
mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/EngineTest.cs
mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/ProjectTest.cs
mcs/class/Microsoft.Build.Engine/Test/test-config-file-net-3.5 [new file with mode: 0644]
mcs/class/Microsoft.Build.Engine/Test/test-config-file-net-4.0 [new file with mode: 0644]
mcs/class/Microsoft.Build.Framework/ChangeLog
mcs/class/Microsoft.Build.Framework/Makefile
mcs/class/Microsoft.Build.Framework/Microsoft.Build.Framework.dll.sources
mcs/class/Microsoft.Build.Framework/Microsoft.Build.Framework/ChangeLog
mcs/class/Microsoft.Build.Framework/Microsoft.Build.Framework/IBuildEngine2.cs [new file with mode: 0644]
mcs/class/Microsoft.Build.Tasks/ChangeLog
mcs/class/Microsoft.Build.Tasks/Makefile
mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/ChangeLog
mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/Copy.cs
mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/Csc.cs
mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/GetFrameworkPath.cs
mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/MSBuild.cs
mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/Vbc.cs
mcs/class/Microsoft.Build.Tasks/Microsoft.Build.Tasks_test.dll.sources
mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/AssignProjectConfigurationTest.cs
mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/ChangeLog
mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/Consts.cs [deleted file]
mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/CreateCSharpManifestResourceNameTest.cs
mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/CreateItemTest.cs
mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/CreateVisualBasicManifestResourceNameTest.cs
mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/FindAppConfigFileTest.cs
mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/RemoveDuplicatesTest.cs
mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/TaskBatchingTest.cs
mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/WriteLinesToFileTest.cs
mcs/class/Microsoft.Build.Tasks/Test/test-config-file-net-3.5 [new file with mode: 0644]
mcs/class/Microsoft.Build.Tasks/Test/test-config-file-net-4.0 [new file with mode: 0644]
mcs/class/Microsoft.Build.Utilities/ChangeLog
mcs/class/Microsoft.Build.Utilities/Makefile
mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ChangeLog
mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/TargetDotNetFrameworkVersion.cs
mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/Task.cs
mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolLocationHelper.cs
mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs
mcs/class/Microsoft.Build.Utilities/Mono.XBuild.Utilities/ReservedNameUtils.cs
mcs/class/Mono.Cecil.Mdb/Makefile
mcs/class/Mono.Cecil/ChangeLog
mcs/class/Mono.Cecil/Mono.Cecil/AssemblyStripper.cs
mcs/class/Mono.Cecil/Mono.Cecil/BaseAssemblyResolver.cs
mcs/class/Mono.Cecil/Mono.Cecil/GenericParameter.cs
mcs/class/Mono.Cecil/Mono.Cecil/NameObjectCollectionBase.cs
mcs/class/Mono.Cecil/Mono.Cecil/ReflectionWriter.cs
mcs/class/Mono.Cecil/Mono.Cecil/StructureReader.cs
mcs/class/Mono.Data.Tds/Mono.Data.Tds.Protocol/ChangeLog
mcs/class/Mono.Data.Tds/Mono.Data.Tds.Protocol/Tds70.cs
mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft.dll.sources
mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/ChangeLog
mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs
mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/IProcess.cs [new file with mode: 0644]
mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/ThreadMirror.cs
mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/VirtualMachine.cs
mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/VirtualMachineManager.cs
mcs/class/Mono.Posix/Mono.Unix/ChangeLog
mcs/class/Mono.Posix/Mono.Unix/UnixSignal.cs
mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/ChangeLog
mcs/class/Mono.Security/Mono.Security.Protocol.Tls.Handshake.Client/TlsServerCertificate.cs
mcs/class/Mono.Security/Mono.Security.Protocol.Tls/ChangeLog
mcs/class/Mono.Security/Mono.Security.Protocol.Tls/Context.cs
mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RecordProtocol.cs
mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslStreamBase.cs
mcs/class/Mono.Security/Mono.Security/ASN1Convert.cs
mcs/class/Mono.Security/Mono.Security/ChangeLog
mcs/class/Mono.Security/Test/Mono.Security.X509.Extensions/ChangeLog
mcs/class/Mono.Security/Test/Mono.Security.X509.Extensions/SubjectAltNameExtensionTest.cs
mcs/class/Mono.Simd/Mono.Simd/ChangeLog
mcs/class/Mono.Simd/Mono.Simd/Vector4f.cs
mcs/class/Moonlight.Build.Tasks/ChangeLog [new file with mode: 0644]
mcs/class/Moonlight.Build.Tasks/Makefile [new file with mode: 0644]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks.dll.sources [new file with mode: 0644]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/ChangeLog [new file with mode: 0644]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/CreateTestPage.cs [new file with mode: 0644]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/GenerateMoonlightManifest.cs [new file with mode: 0644]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/GenerateXap.cs [new file with mode: 0644]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/GetMoonlightFrameworkPath.cs [new file with mode: 0644]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/PreviewTemplate.html [new file with mode: 0644]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/Respack.cs [new file with mode: 0644]
mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/XamlG.cs [new file with mode: 0644]
mcs/class/System.ComponentModel.Composition/src/ComponentModel/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs
mcs/class/System.Core/Assembly/AssemblyInfo.cs
mcs/class/System.Core/Assembly/ChangeLog
mcs/class/System.Core/ChangeLog
mcs/class/System.Core/Makefile
mcs/class/System.Core/System.Collections.Generic/ChangeLog
mcs/class/System.Core/System.Collections.Generic/HashSet.cs
mcs/class/System.Core/System.Core_test.dll.sources
mcs/class/System.Core/System.IO.MemoryMappedFiles/ChangeLog
mcs/class/System.Core/System.IO.MemoryMappedFiles/MemoryMappedFile.cs
mcs/class/System.Core/System.IO.MemoryMappedFiles/MemoryMappedViewAccessor.cs
mcs/class/System.Core/System.IO.MemoryMappedFiles/MemoryMappedViewStream.cs
mcs/class/System.Core/System.Linq/ChangeLog
mcs/class/System.Core/System.Linq/Enumerable.cs
mcs/class/System.Core/System.Linq/EnumerableExecutor.cs
mcs/class/System.Core/System.Linq/EnumerableQuery.cs
mcs/class/System.Core/System.Linq/EnumerableQuery_T.cs
mcs/class/System.Core/System.Linq/Internal/AggregationList.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/ChangeLog [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/ConcurrentGrouping.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/ConcurrentLookup.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/OrderingEnumerator.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/ParallelQuickSort.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/ChangeLog [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryBaseNode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryCastNode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryChildNode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryConcatNode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryDefaultEmptyNode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryGroupByNode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryMuxNode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryOptionNode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryOrderByNode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryOrderGuardNode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryOrderedStreamNode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryReverseNode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/QuerySelectManyNode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/QuerySelectNode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/QuerySetNode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryStartNode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryStreamNode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryWhereNode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryZipNode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/SetInclusion.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/QueryNodes/WrapHelper.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/RangeList.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/RepeatList.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/ReverseList.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/StripPartitioner.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/Visitors/ChangeLog [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/Visitors/INodeVisitor.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/Visitors/IVisitableNode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/Visitors/QueryCheckerVisitor.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Internal/Visitors/QueryOptions.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/OrderedParallelQuery.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/ParallelEnumerable.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/ParallelExecuter.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/ParallelExecutionMode.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/ParallelMergeOptions.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/ParallelPartitioner.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/ParallelQuery.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/ParallelQueryEnumerator.cs [new file with mode: 0644]
mcs/class/System.Core/System.Linq/Queryable.cs
mcs/class/System.Core/System.Linq/QueryableEnumerable.cs
mcs/class/System.Core/System.Linq/QueryableTransformer.cs
mcs/class/System.Core/System.Linq/SortSequenceContext.cs
mcs/class/System.Core/System.Runtime.CompilerServices/DynamicAttribute.cs
mcs/class/System.Core/System.Security.Cryptography/Aes.cs
mcs/class/System.Core/System.Security.Cryptography/ChangeLog
mcs/class/System.Core/System/Actions.cs
mcs/class/System.Core/System/ChangeLog
mcs/class/System.Core/System/Funcs.cs
mcs/class/System.Core/System/InvalidTimeZoneException.cs
mcs/class/System.Core/System/TimeZoneInfo.AdjustmentRule.cs
mcs/class/System.Core/System/TimeZoneInfo.TransitionTime.cs
mcs/class/System.Core/System/TimeZoneInfo.cs
mcs/class/System.Core/System/TimeZoneNotFoundException.cs
mcs/class/System.Core/Test/System.Linq.Expressions/ExpressionTest.cs
mcs/class/System.Core/Test/System.Linq.Expressions/ExpressionTest_AddChecked.cs
mcs/class/System.Core/Test/System.Linq.Expressions/ExpressionTest_AndAlso.cs
mcs/class/System.Core/Test/System.Linq.Expressions/ExpressionTest_Call.cs
mcs/class/System.Core/Test/System.Linq.Expressions/ExpressionTest_Convert.cs
mcs/class/System.Core/Test/System.Linq.Expressions/ExpressionTest_Equal.cs
mcs/class/System.Core/Test/System.Linq.Expressions/ExpressionTest_Lambda.cs
mcs/class/System.Core/Test/System.Linq.Expressions/ExpressionTest_OrElse.cs
mcs/class/System.Core/Test/System.Linq.Expressions/ExpressionTest_Quote.cs
mcs/class/System.Core/Test/System.Linq.Expressions/ExpressionTest_SubtractChecked.cs
mcs/class/System.Core/Test/System.Linq.Expressions/ExpressionTest_TypeIs.cs
mcs/class/System.Core/Test/System.Linq/ChangeLog
mcs/class/System.Core/Test/System.Linq/EnumerableTest.cs
mcs/class/System.Core/Test/System.Linq/ParallelEnumerableTests.cs [new file with mode: 0644]
mcs/class/System.Core/Test/System.Linq/ParallelTestHelper.cs [new file with mode: 0644]
mcs/class/System.Core/Test/System.Threading/ReaderWriterLockSlimTest.cs
mcs/class/System.Core/moonlight_bootstrap_System.Core.dll.sources [new file with mode: 0644]
mcs/class/System.Core/moonlight_raw_System.Core.dll.sources [new file with mode: 0644]
mcs/class/System.Core/net_2_1_bootstrap_System.Core.dll.sources [deleted file]
mcs/class/System.Core/net_2_1_raw_System.Core.dll.sources [deleted file]
mcs/class/System.Core/net_4_0_System.Core.dll.sources
mcs/class/System.Data.DataSetExtensions/System.Data/ChangeLog
mcs/class/System.Data.DataSetExtensions/System.Data/RowEnumerableDataReader.cs
mcs/class/System.Data.Linq/ChangeLog
mcs/class/System.Data.Linq/System.Data.Linq.dll.sources
mcs/class/System.Data.Linq/examples/DbLinq.FbSql.Example/Properties/AssemblyInfo.cs
mcs/class/System.Data.Linq/examples/DbLinq.Mssql.Example/Properties/AssemblyInfo.cs
mcs/class/System.Data.Linq/examples/DbLinq.MySql.Example/Properties/AssemblyInfo.cs
mcs/class/System.Data.Linq/examples/DbLinq.Ora.Example/Properties/AssemblyInfo.cs
mcs/class/System.Data.Linq/examples/DbLinq.Ora.Example/sql/create_Northwind_ora.sql
mcs/class/System.Data.Linq/examples/DbLinq.Ora.Example/sql/drop_Northwind_ora.sql
mcs/class/System.Data.Linq/examples/DbLinq.SQLite.Example/Properties/AssemblyInfo.cs
mcs/class/System.Data.Linq/examples/DbLinq.SQLite.Example/nwind/Northwind.cs
mcs/class/System.Data.Linq/src/DbLinq.Firebird/FirebirdSqlProvider.cs
mcs/class/System.Data.Linq/src/DbLinq.Firebird/Properties/AssemblyInfo.cs
mcs/class/System.Data.Linq/src/DbLinq.Ingres/IngresSqlProvider.cs
mcs/class/System.Data.Linq/src/DbLinq.Ingres/Properties/AssemblyInfo.cs
mcs/class/System.Data.Linq/src/DbLinq.MySql/MySqlSqlProvider.cs
mcs/class/System.Data.Linq/src/DbLinq.MySql/Properties/AssemblyInfo.cs
mcs/class/System.Data.Linq/src/DbLinq.Oracle/OracleSchemaLoader.Constraints.cs
mcs/class/System.Data.Linq/src/DbLinq.Oracle/OracleSchemaLoader.cs
mcs/class/System.Data.Linq/src/DbLinq.Oracle/Properties/AssemblyInfo.cs
mcs/class/System.Data.Linq/src/DbLinq.PostgreSql/PgsqlSchemaLoader.cs
mcs/class/System.Data.Linq/src/DbLinq.PostgreSql/PgsqlSqlProvider.cs
mcs/class/System.Data.Linq/src/DbLinq.PostgreSql/Properties/AssemblyInfo.cs
mcs/class/System.Data.Linq/src/DbLinq.ProductInfo.cs
mcs/class/System.Data.Linq/src/DbLinq.SqlServer/Properties/AssemblyInfo.cs
mcs/class/System.Data.Linq/src/DbLinq.SqlServer/SqlServerVendor.cs
mcs/class/System.Data.Linq/src/DbLinq.Sqlite/Properties/AssemblyInfo.cs
mcs/class/System.Data.Linq/src/DbLinq.Sqlite/SqliteSchemaLoader.Columns.cs
mcs/class/System.Data.Linq/src/DbLinq.Sqlite/SqliteSchemaLoader.Tables.cs
mcs/class/System.Data.Linq/src/DbLinq.Sqlite/SqliteSchemaLoader.cs
mcs/class/System.Data.Linq/src/DbLinq.Sqlite/SqliteSqlProvider.cs
mcs/class/System.Data.Linq/src/DbLinq.sln
mcs/class/System.Data.Linq/src/DbLinq/Data/Linq/DataContext.cs
mcs/class/System.Data.Linq/src/DbLinq/Data/Linq/Database/IDatabaseContext.cs
mcs/class/System.Data.Linq/src/DbLinq/Data/Linq/Database/Implementation/DatabaseContext.cs
mcs/class/System.Data.Linq/src/DbLinq/Data/Linq/Database/Implementation/TransactionalCommand.cs
mcs/class/System.Data.Linq/src/DbLinq/Data/Linq/Mapping/XmlMappingSource.cs
mcs/class/System.Data.Linq/src/DbLinq/Data/Linq/Sugar/Implementation/ExpressionDispatcher.Registrar.cs
mcs/class/System.Data.Linq/src/DbLinq/Data/Linq/Sugar/Implementation/QueryBuilder.cs
mcs/class/System.Data.Linq/src/DbLinq/Data/Linq/Table.Extended.cs
mcs/class/System.Data.Linq/src/DbLinq/DbLinq.csproj
mcs/class/System.Data.Linq/src/DbLinq/Properties/AssemblyInfo.cs
mcs/class/System.Data.Linq/src/DbLinq/Schema/Dbml/DatabaseSerializer.cs [new file with mode: 0644]
mcs/class/System.Data.Linq/src/DbLinq/Schema/Dbml/DbmlSerializer.cs
mcs/class/System.Data.Linq/src/DbLinq/System.Data.Linq.csproj
mcs/class/System.Data.Linq/src/DbLinq/System.Data.Linq/Assembly/AssemblyInfo.cs
mcs/class/System.Data.Linq/src/DbLinq/System.Data.Linq/System.Data.Linq.Mapping/ColumnAttribute.cs
mcs/class/System.Data.Linq/src/DbLinq/Test/AssemblyInfo.cs
mcs/class/System.Data.Linq/src/DbLinq/Test/DbLinq_test_ndb_strict.csproj
mcs/class/System.Data.Linq/src/DbLinq/Test/Properties/AssemblyInfo.cs
mcs/class/System.Data.Linq/src/DbLinq/Test/Providers/Properties/AssemblyInfo.cs
mcs/class/System.Data.Linq/src/DbLinq/Test/Providers/ReadTest.cs
mcs/class/System.Data.Linq/src/DbLinq/Test/System.Data.Linq.Mapping/ColumnAttributeTest.cs [new file with mode: 0755]
mcs/class/System.Data.Linq/src/DbLinq/Vendor/ISchemaLoader.cs
mcs/class/System.Data.Linq/src/DbLinq/Vendor/Implementation/SchemaLoader.ForeignKey.cs
mcs/class/System.Data.Linq/src/DbLinq/Vendor/Implementation/SchemaLoader.Name.cs
mcs/class/System.Data.Linq/src/DbLinq/Vendor/Implementation/SchemaLoader.TypeMapping.cs
mcs/class/System.Data.Linq/src/DbLinq/Vendor/Implementation/SchemaLoader.cs
mcs/class/System.Data.Linq/src/DbLinq/Vendor/Implementation/SqlProvider.cs
mcs/class/System.Data.Linq/src/DbLinq/Vendor/Implementation/Vendor.cs
mcs/class/System.Data.Linq/src/DbMetal/App.config
mcs/class/System.Data.Linq/src/DbMetal/Configuration/ProvidersSection.cs
mcs/class/System.Data.Linq/src/DbMetal/DbMetal.csproj
mcs/class/System.Data.Linq/src/DbMetal/Generator/CodeDomGenerator.cs [new file with mode: 0755]
mcs/class/System.Data.Linq/src/DbMetal/Generator/CodeWriter.cs
mcs/class/System.Data.Linq/src/DbMetal/Generator/ISchemaLoaderFactory.cs
mcs/class/System.Data.Linq/src/DbMetal/Generator/Implementation/CodeTextGenerator/CSCodeGenerator.cs
mcs/class/System.Data.Linq/src/DbMetal/Generator/Implementation/CodeTextGenerator/CodeGenerator.Class.cs
mcs/class/System.Data.Linq/src/DbMetal/Generator/Implementation/CodeTextGenerator/CodeGenerator.cs
mcs/class/System.Data.Linq/src/DbMetal/Generator/Implementation/Processor.cs
mcs/class/System.Data.Linq/src/DbMetal/Generator/Implementation/SchemaLoaderFactory.cs
mcs/class/System.Data.Linq/src/DbMetal/Parameters.cs
mcs/class/System.Data.Linq/src/DbMetal/Properties/AssemblyInfo.cs
mcs/class/System.Data.Linq/src/DbMetal/SqlMetal.csproj
mcs/class/System.Data.Linq/src/DbMetal/Test/AppRunner.cs [new file with mode: 0755]
mcs/class/System.Data.Linq/src/DbMetal/Test/CreateDbmlFromSqliteDbTest.cs [new file with mode: 0755]
mcs/class/System.Data.Linq/src/DbMetal/Test/CreateEntitiesFromSqliteDbTest.cs
mcs/class/System.Data.Linq/src/DbMetal/Test/DbMetal_test_sqlite.csproj
mcs/class/System.Data.Linq/src/DbMetal/Test/SqlMetal_test_sqlite.csproj
mcs/class/System.Data.Linq/src/DbMetal/sqlmetal.exe.config
mcs/class/System.Data.Linq/src/Tools/NUnitRunner/Properties/AssemblyInfo.cs
mcs/class/System.Data.Linq/src/Tools/TestNamespaceWriter/Properties/AssemblyInfo.cs
mcs/class/System.Data.Linq/tests/Northwind.Expected.Sqlite-DbMetal.cs [deleted file]
mcs/class/System.Data.Linq/tests/Northwind.Expected.Sqlite-sqlmetal.cs [deleted file]
mcs/class/System.Data.Linq/tests/expected/Northwind.Sqlite+DbSchemaLoader-DbMetal.cs
mcs/class/System.Data.Linq/tests/expected/Northwind.Sqlite+DbSchemaLoader-DbMetal.dbml [new file with mode: 0755]
mcs/class/System.Data.Linq/tests/expected/Northwind.Sqlite+DbSchemaLoader-sqlmetal.cs
mcs/class/System.Data.Linq/tests/expected/Northwind.Sqlite+DbSchemaLoader-sqlmetal.dbml [new file with mode: 0755]
mcs/class/System.Data.Linq/tests/expected/Northwind.Sqlite-DbMetal.cs [new file with mode: 0755]
mcs/class/System.Data.Linq/tests/expected/Northwind.Sqlite-DbMetal.dbml [new file with mode: 0755]
mcs/class/System.Data.Linq/tests/expected/Northwind.Sqlite-sqlmetal.cs [new file with mode: 0755]
mcs/class/System.Data.Linq/tests/expected/Northwind.Sqlite-sqlmetal.dbml [new file with mode: 0755]
mcs/class/System.Data.Services/ChangeLog
mcs/class/System.Data.Services/Makefile
mcs/class/System.Data/System.Data.Common/ChangeLog
mcs/class/System.Data/System.Data.Common/DbDataAdapter.cs
mcs/class/System.Data/System.Data.SqlClient/ChangeLog
mcs/class/System.Data/System.Data.SqlClient/SqlDataAdapter.cs
mcs/class/System.Data/System.Data/ChangeLog
mcs/class/System.Data/System.Data/DataColumn.cs
mcs/class/System.Data/System.Data/DataSet.cs
mcs/class/System.Data/Test/ProviderTests/System.Data.SqlClient/ChangeLog
mcs/class/System.Data/Test/ProviderTests/System.Data.SqlClient/SqlParameterTest.cs
mcs/class/System.Data/Test/ProviderTests/app-net_2_0.config
mcs/class/System.Json/ChangeLog
mcs/class/System.Json/System.Json/JsonValue.cs
mcs/class/System.Net/ChangeLog
mcs/class/System.Net/System.Net.Policy/BaseDomainPolicy.cs
mcs/class/System.Net/System.Net.Policy/ChangeLog
mcs/class/System.Net/System.Net.Policy/ClientAccessPolicy.cs
mcs/class/System.Net/System.Net.Policy/ClientAccessPolicyParser.cs
mcs/class/System.Net/System.Net.Policy/CrossDomainPolicyManager.cs
mcs/class/System.Net/System.Net.Policy/FlashCrossDomainPolicy.cs
mcs/class/System.Net/System.Net.Policy/FlashCrossDomainPolicyParser.cs
mcs/class/System.Net/System.Net.Sockets/ChangeLog
mcs/class/System.Net/System.Net.Sockets/SocketClientAccessPolicyProtocol.cs [new file with mode: 0644]
mcs/class/System.Net/System.Net.Sockets/SocketException_2_1.cs
mcs/class/System.Net/System.Net/ChangeLog
mcs/class/System.Net/System.Net/HttpWebRequest_2_1.cs
mcs/class/System.Net/System.Net/HttpWebResponse_2_1.cs
mcs/class/System.Net/System.Net/InternalWebResponseStreamWrapper.cs [deleted file]
mcs/class/System.Net/System.Net/WebClient_2_1.cs
mcs/class/System.Net/System.Net/WebHeaderCollection_2_1.cs
mcs/class/System.Net/System.Net/WebRequest_2_1.cs
mcs/class/System.Net/System.Net/WebResponse_2_1.cs
mcs/class/System.Net/moonlight_raw_System.Net.dll.sources [new file with mode: 0644]
mcs/class/System.Net/net_2_1_raw_System.Net.dll.sources [deleted file]
mcs/class/System.Numerics/System.Numerics/ChangeLog
mcs/class/System.Numerics/System.Numerics/Complex.cs
mcs/class/System.Runtime.Caching/Assembly/AssemblyInfo.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/Assembly/ChangeLog [new file with mode: 0644]
mcs/class/System.Runtime.Caching/ChangeLog [new file with mode: 0644]
mcs/class/System.Runtime.Caching/Makefile [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching.Configuration/CachingSectionGroup.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching.Configuration/ChangeLog [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching.Configuration/MemoryCacheElement.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching.Configuration/MemoryCacheSection.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching.Configuration/MemoryCacheSettingsCollection.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching.Hosting/ChangeLog [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching.Hosting/IApplicationIdentifier.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching.Hosting/IFileChangeNotificationSystem.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching.Hosting/IMemoryCacheManager.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching.dll.sources [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheEntryChangeMonitor.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheEntryRemovedArguments.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheEntryRemovedCallback.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheEntryRemovedReason.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheEntryUpdateArguments.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheEntryUpdateCallback.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheItem.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheItemPolicy.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheItemPriority.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/ChangeLog [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/ChangeMonitor.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/DefaultCacheCapabilities.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/FileChangeMonitor.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/FileChangeNotificationSystem.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/FileChangeNotificationSystemEntry.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/Helpers.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/HostFileChangeMonitor.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCache.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCacheContainer.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCacheEntry.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCacheEntryChangeMonitor.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCacheEntryPriorityQueue.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCacheLRU.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCachePerformanceCounters.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/ObjectCache.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/OnChangedCallback.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching/SqlChangeMonitor.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/System.Runtime.Caching_test.dll.sources [new file with mode: 0644]
mcs/class/System.Runtime.Caching/Test/Common/AppDomainTools.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/Test/Common/AssertExtensions.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/Test/Common/ChangeLog [new file with mode: 0644]
mcs/class/System.Runtime.Caching/Test/Common/PokerChangeMonitor.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/Test/Common/PokerMemoryCache.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/Test/Common/PokerObjectCache.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/Test/Common/TestNotificationSystem.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/Test/System.Runtime.Caching/ChangeLog [new file with mode: 0644]
mcs/class/System.Runtime.Caching/Test/System.Runtime.Caching/HostFileChangeMonitorTest.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/Test/System.Runtime.Caching/MemoryCacheTest.cs [new file with mode: 0644]
mcs/class/System.Runtime.Caching/Test/System.Runtime.Caching/ObjectCacheTest.cs [new file with mode: 0644]
mcs/class/System.Runtime.Serialization/ChangeLog
mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/ChangeLog
mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/DataContractSerializer.cs
mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/KnownTypeCollection.cs
mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/SerializationMap.XsdExporter.cs
mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/SerializationMap.cs
mcs/class/System.Runtime.Serialization/System.Runtime.Serialization/XsdDataContractExporter-new.cs
mcs/class/System.Runtime.Serialization/monotouch_System.Runtime.Serialization.dll.sources
mcs/class/System.Runtime.Serialization/moonlight_raw_System.Runtime.Serialization.dll.sources [new file with mode: 0644]
mcs/class/System.Runtime.Serialization/net_2_1_raw_System.Runtime.Serialization.dll.sources [deleted file]
mcs/class/System.Security/ChangeLog
mcs/class/System.Security/Makefile
mcs/class/System.ServiceModel.Discovery/Assembly/AssemblyInfo.cs [new file with mode: 0644]
mcs/class/System.ServiceModel.Discovery/Assembly/ChangeLog [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/ChangeLog [new file with mode: 0644]
mcs/class/System.ServiceModel.Discovery/Makefile [new file with mode: 0644]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/ChangeLog [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/DiscoveryMessageSequenceApril2005.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/EndpointDiscoveryMetadataApril2005.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/FindCriteriaApril2005.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/ResolveCriteriaApril2005.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/ChangeLog [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/DiscoveryMessageSequence11.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/EndpointDiscoveryMetadata11.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/FindCriteria11.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/ResolveCriteria11.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.dll.sources [new file with mode: 0644]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/AnnouncementClient.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/AnnouncementEndpoint.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/AnnouncementEventArgs.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/AnnouncementService.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ChangeLog [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryClient.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryClientBindingElement.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryEndpoint.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryEndpointProvider.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryMessageSequence.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryMessageSequenceGenerator.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryOperationContextExtension.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryProxy.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryService.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryServiceExtension.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryVersion.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DynamicEndpoint.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/EndpointDiscoveryBehavior.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/EndpointDiscoveryMetadata.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/FindCompletedEventArgs.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/FindCriteria.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/FindProgressChangedEventArgs.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/FindRequestContext.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/FindResponse.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ResolveCompletedEventArgs.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ResolveCriteria.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ResolveResponse.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ServiceDiscoveryBehavior.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ServiceDiscoveryMode.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/UdpAnnouncementEndpoint.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/UdpDiscoveryEndpoint.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/UdpTransportSettings.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery_test.dll.sources [new file with mode: 0644]
mcs/class/System.ServiceModel.Discovery/Test/System.ServiceModel.Discovery/ChangeLog [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/Test/System.ServiceModel.Discovery/DiscoveryVersionTest.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Discovery/Test/System.ServiceModel.Discovery/FindCriteriaTest.cs [new file with mode: 0755]
mcs/class/System.ServiceModel.Web/ChangeLog
mcs/class/System.ServiceModel.Web/System.Runtime.Serialization.Json/ChangeLog
mcs/class/System.ServiceModel.Web/System.Runtime.Serialization.Json/DataContractJsonSerializer.cs
mcs/class/System.ServiceModel.Web/System.Runtime.Serialization.Json/JavaScriptReader.cs
mcs/class/System.ServiceModel.Web/System.Runtime.Serialization.Json/JsonSerializationReader.cs
mcs/class/System.ServiceModel.Web/System.ServiceModel.Description/ChangeLog
mcs/class/System.ServiceModel.Web/System.ServiceModel.Description/WebHttpBehavior.cs
mcs/class/System.ServiceModel.Web/System.ServiceModel.Dispatcher/ChangeLog
mcs/class/System.ServiceModel.Web/System.ServiceModel.Dispatcher/WebMessageFormatter.cs
mcs/class/System.ServiceModel.Web/Test/System.Runtime.Serialization.Json/ChangeLog
mcs/class/System.ServiceModel.Web/Test/System.Runtime.Serialization.Json/DataContractJsonSerializerTest.cs
mcs/class/System.ServiceModel.Web/common_System.ServiceModel.Web.dll.sources
mcs/class/System.ServiceModel.Web/moonlight_raw_System.ServiceModel.Web.dll.sources [new file with mode: 0644]
mcs/class/System.ServiceModel.Web/net_2_0_System.ServiceModel.Web.dll.sources
mcs/class/System.ServiceModel.Web/net_2_1_raw_System.ServiceModel.Web.dll.sources [deleted file]
mcs/class/System.ServiceModel/ChangeLog
mcs/class/System.ServiceModel/Dummy_2_1.cs
mcs/class/System.ServiceModel/HTTP_listener_notes.txt
mcs/class/System.ServiceModel/Makefile
mcs/class/System.ServiceModel/System.ServiceModel.Channels/AddressingVersion.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/AspNetReplyChannel.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/AspNetRequestContext.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/BindingContext.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/BodyWriter.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/BufferManager.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/ChangeLog
mcs/class/System.ServiceModel/System.ServiceModel.Channels/ChannelListenerBase.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/ConnectionOrientedTransportBindingElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/FaultConverter.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/HttpChannelListener.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/HttpListenerManager.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/HttpReplyChannel.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/HttpRequestChannel.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/HttpRequestContext.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/HttpTransportBindingElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/HttpsTransportBindingElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/Message.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/MessageFault.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/MessageHeaders.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/MessageImpl.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/PrivacyNoticeBindingElement.cs [new file with mode: 0644]
mcs/class/System.ServiceModel/System.ServiceModel.Channels/ReliableSessionBindingElement.cs [new file with mode: 0644]
mcs/class/System.ServiceModel/System.ServiceModel.Channels/RemoteEndpointMessageProperty.cs [new file with mode: 0644]
mcs/class/System.ServiceModel/System.ServiceModel.Channels/ReplyChannelBase.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/SecureMessageGenerator.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/SvcHttpHandler.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/TcpTransportBindingElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/TransactionFlowBindingElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/WSSecurityMessageHeader.cs
mcs/class/System.ServiceModel/System.ServiceModel.Channels/XmlReaderBodyWriter.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/BaseAddressElementCollection.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/BaseAddressPrefixFilterElement.cs [new file with mode: 0644]
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/BaseAddressPrefixFilterElementCollection.cs [new file with mode: 0644]
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/BasicHttpBindingElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/BinaryMessageEncodingElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/BindingElementExtensionElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/ChangeLog
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/ConfigUtil.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/ConnectionOrientedTransportElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/CustomBindingElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/HostTimeoutsElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/HttpTransportElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/HttpsTransportElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/IssuedTokenClientElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/LocalClientSecuritySettingsElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/LocalServiceSecuritySettingsElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/MexHttpBindingCollectionElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/MexHttpsBindingCollectionElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/MsmqBindingElementBase.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/MsmqElementBase.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/MsmqIntegrationElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/MsmqTransportElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/NamedPipeConnectionPoolSettingsElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/NamedPipeTransportElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/ReliableSessionElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/ServiceDebugElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/ServiceMetadataPublishingElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/StandardBindingCollectionElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/StandardBindingElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/StandardBindingReliableSessionElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/TcpConnectionPoolSettingsElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/TcpTransportElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/TextMessageEncodingElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/TransportElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Configuration/XmlDictionaryReaderQuotasElement.cs
mcs/class/System.ServiceModel/System.ServiceModel.Description/ChangeLog
mcs/class/System.ServiceModel/System.ServiceModel.Description/ClientCredentials.cs
mcs/class/System.ServiceModel/System.ServiceModel.Description/ContractDescription.cs
mcs/class/System.ServiceModel/System.ServiceModel.Description/ContractDescriptionGenerator.cs
mcs/class/System.ServiceModel/System.ServiceModel.Description/FaultDescription.cs
mcs/class/System.ServiceModel/System.ServiceModel.Description/HostedBindingBehavior.cs [deleted file]
mcs/class/System.ServiceModel/System.ServiceModel.Description/IEndpointBehavior.cs
mcs/class/System.ServiceModel/System.ServiceModel.Description/MetadataExchangeBindings.cs
mcs/class/System.ServiceModel/System.ServiceModel.Description/OperationDescription.cs
mcs/class/System.ServiceModel/System.ServiceModel.Description/ServiceEndpointCollection.cs
mcs/class/System.ServiceModel/System.ServiceModel.Description/ServiceMetadataExtension.cs
mcs/class/System.ServiceModel/System.ServiceModel.Description/WsdlExporter.cs
mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/BaseMessagesFormatter.cs
mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/ChangeLog
mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/ChannelDispatcher.cs
mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/ClientOperation.cs
mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/DispatchOperation.cs
mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/EndpointAddressMessageFilter.cs
mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/EndpointDispatcher.cs
mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/ErrorProcessingHandler.cs
mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/FaultContractInfo.cs
mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/OperationInvokerHandler.cs
mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/XPathMessageContext.cs
mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/XPathMessageFilterTable.cs
mcs/class/System.ServiceModel/System.ServiceModel.dll.sources
mcs/class/System.ServiceModel/System.ServiceModel/ChangeLog
mcs/class/System.ServiceModel/System.ServiceModel/ChannelTerminatedException.cs [new file with mode: 0644]
mcs/class/System.ServiceModel/System.ServiceModel/ClientBase.cs
mcs/class/System.ServiceModel/System.ServiceModel/ClientRuntimeChannel.cs
mcs/class/System.ServiceModel/System.ServiceModel/Constants.cs
mcs/class/System.ServiceModel/System.ServiceModel/Dummy.cs
mcs/class/System.ServiceModel/System.ServiceModel/ServiceHostBase.cs
mcs/class/System.ServiceModel/System.ServiceModel/WSHttpBindingBase.cs
mcs/class/System.ServiceModel/System.ServiceModel_test.dll.sources
mcs/class/System.ServiceModel/Test/FeatureBased/Features.Serialization/AsyncCallTest.cs
mcs/class/System.ServiceModel/Test/FeatureBased/Features.Serialization/AsyncPatternTester.cs
mcs/class/System.ServiceModel/Test/FeatureBased/Features.Serialization/ChangeLog
mcs/class/System.ServiceModel/Test/FeatureBased/Features.Serialization/MessageContractTest.cs
mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/ChangeLog
mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/CustomBindingTest.cs
mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/FaultConverterTest.cs
mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/HttpsTransportBindingElementTest.cs
mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/MessageBufferTest.cs
mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/MessageFaultTest.cs
mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/MessageHeaderTest.cs
mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/MessageTest.cs
mcs/class/System.ServiceModel/Test/System.ServiceModel.Channels/TcpTransportBindingElementTest.cs
mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/ChangeLog
mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/FaultDescriptionTest.cs [new file with mode: 0644]
mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/MetadataExchangeBindingsTest.cs [new file with mode: 0644]
mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/MetadataResolverTest.cs
mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/WsdlExporterTest.cs
mcs/class/System.ServiceModel/Test/System.ServiceModel.Dispatcher/ChangeLog
mcs/class/System.ServiceModel/Test/System.ServiceModel.Dispatcher/DispatchOperationTest.cs
mcs/class/System.ServiceModel/Test/System.ServiceModel.Dispatcher/DispatchRuntimeTest.cs
mcs/class/System.ServiceModel/Test/System.ServiceModel.Dispatcher/EndpointAddressMessageFilterTest.cs
mcs/class/System.ServiceModel/Test/System.ServiceModel.Dispatcher/XPathMessageContextTest.cs [new file with mode: 0644]
mcs/class/System.ServiceModel/Test/System.ServiceModel.PeerResolvers/ChangeLog
mcs/class/System.ServiceModel/Test/System.ServiceModel.PeerResolvers/CustomPeerResolverServiceTest.cs
mcs/class/System.ServiceModel/Test/System.ServiceModel.Security/ChangeLog
mcs/class/System.ServiceModel/Test/System.ServiceModel.Security/TransportSecurityBindingElementTest.cs [new file with mode: 0644]
mcs/class/System.ServiceModel/Test/System.ServiceModel/BasicHttpBindingTest.cs
mcs/class/System.ServiceModel/Test/System.ServiceModel/ChangeLog
mcs/class/System.ServiceModel/Test/System.ServiceModel/Constants.cs [new file with mode: 0644]
mcs/class/System.ServiceModel/Test/System.ServiceModel/EndpointAddress10Test.cs
mcs/class/System.ServiceModel/Test/System.ServiceModel/EndpointIdentityTest.cs
mcs/class/System.ServiceModel/Test/System.ServiceModel/FaultContractAttributeTest.cs [new file with mode: 0644]
mcs/class/System.ServiceModel/Test/System.ServiceModel/ServiceHostBaseTest.cs
mcs/class/System.ServiceModel/monotouch_System.ServiceModel.dll.sources
mcs/class/System.ServiceModel/moonlight_raw_System.ServiceModel.dll.sources [new file with mode: 0755]
mcs/class/System.ServiceModel/net_2_1_raw_System.ServiceModel.dll.sources [deleted file]
mcs/class/System.ServiceModel/net_4_0_System.ServiceModel.dll.sources
mcs/class/System.Web.Abstractions/System.Web/ChangeLog
mcs/class/System.Web.Abstractions/System.Web/HttpContextWrapper.cs
mcs/class/System.Web.Mvc/ChangeLog
mcs/class/System.Web.Mvc/Makefile
mcs/class/System.Web.Mvc2/ChangeLog [new file with mode: 0644]
mcs/class/System.Web.Mvc2/GlobalSuppressions.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/Makefile [new file with mode: 0644]
mcs/class/System.Web.Mvc2/Properties/AssemblyInfo.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/Properties/ChangeLog [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc.csproj [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc.dll.sources [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/AcceptVerbsAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionDescriptor.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionExecutedContext.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionExecutingContext.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionFilterAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionMethodDispatcher.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionMethodDispatcherCache.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionMethodSelector.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionMethodSelectorAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionNameAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionNameSelectorAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionResult.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionSelector.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Ajax/AjaxExtensions.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Ajax/AjaxOptions.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Ajax/InsertionMode.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/AjaxHelper.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/AjaxHelper`1.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/AjaxRequestExtensions.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/AntiForgeryData.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/AntiForgeryDataSerializer.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/AreaHelpers.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/AreaRegistration.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/AreaRegistrationContext.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/AssociatedMetadataProvider.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/AssociatedValidatorProvider.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/ActionDescriptorCreator.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncActionDescriptor.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncActionMethodSelector.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncControllerActionInvoker.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncManager.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncResultWrapper.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncUtil.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncVoid.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/BeginInvokeDelegate.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/EndInvokeDelegate.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/EndInvokeDelegate`1.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/IAsyncActionInvoker.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/IAsyncController.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/IAsyncManagerContainer.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/OperationCounter.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/ReflectedAsyncActionDescriptor.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/ReflectedAsyncControllerDescriptor.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/SimpleAsyncResult.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/SingleEntryGate.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/SynchronizationContextUtil.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/SynchronousOperationException.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/Trigger.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/TriggerListener.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/AsyncController.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/AsyncTimeoutAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/AuthorizationContext.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/AuthorizeAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/BindAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/BuildManagerWrapper.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ByteArrayModelBinder.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ChildActionOnlyAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ClientDataTypeModelValidatorProvider.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ContentResult.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Controller.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerActionInvoker.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerBase.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerBuilder.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerContext.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerDescriptor.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerDescriptorCache.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerTypeCache.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/CustomModelBinderAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/DataAnnotationsModelMetadata.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/DataAnnotationsModelMetadataProvider.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/DataAnnotationsModelValidator.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/DataAnnotationsModelValidatorProvider.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/DataAnnotationsModelValidator`1.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/DataErrorInfoModelValidatorProvider.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/DefaultControllerFactory.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/DefaultModelBinder.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/DefaultViewLocationCache.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/DescriptorUtil.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/DictionaryHelpers.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/DictionaryValueProvider`1.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/DynamicTypeGenerator.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/EmptyModelMetadataProvider.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/EmptyModelValidatorProvider.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/EmptyResult.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Error.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ExceptionContext.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionHelper.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/BinaryExpressionFingerprint.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/CachedExpressionCompiler.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/CompiledExpressionDelegate`2.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/ConditionalExpressionFingerprint.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/ConstantExpressionFingerprint.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/ExpressionFingerprint.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/ExpressionParser.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/FastTrack`2.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/HashCodeCombiner.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/MemberExpressionFingerprint.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/MethodCallExpressionFingerprint.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/ParameterExpressionFingerprint.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/ParserContext.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/UnaryExpressionFingerprint.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/FieldValidationMetadata.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/FileContentResult.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/FilePathResult.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/FileResult.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/FileStreamResult.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/FilterAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/FilterInfo.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/FormCollection.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/FormContext.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/FormMethod.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/FormValueProvider.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/FormValueProviderFactory.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/HandleErrorAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/HandleErrorInfo.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/HiddenInputAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/ChildActionExtensions.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/DefaultDisplayTemplates.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/DefaultEditorTemplates.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/DisplayExtensions.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/DisplayTextExtensions.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/EditorExtensions.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/FormExtensions.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/InputExtensions.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/LabelExtensions.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/LinkExtensions.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/MvcForm.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/PartialExtensions.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/RenderPartialExtensions.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/SelectExtensions.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/TemplateHelpers.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/TextAreaExtensions.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/ValidationExtensions.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/HtmlHelper.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/HtmlHelper`1.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpAntiForgeryException.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpDeleteAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpFileCollectionValueProvider.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpFileCollectionValueProviderFactory.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpGetAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpHandlerUtil.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpPostAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpPostedFileBaseModelBinder.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpPutAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpRequestExtensions.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpUnauthorizedResult.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpVerbs.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/IActionFilter.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/IActionInvoker.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/IAuthorizationFilter.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/IBuildManager.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/IController.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/IControllerFactory.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/IExceptionFilter.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/IModelBinder.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/IResultFilter.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/IRouteWithArea.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ITempDataProvider.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/IValueProvider.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/IView.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/IViewDataContainer.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/IViewEngine.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/IViewLocationCache.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/InputType.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/JavaScriptResult.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/JsonRequestBehavior.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/JsonResult.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/LinqBinaryModelBinder.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelBinderAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelBinderDictionary.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelBinders.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelBindingContext.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelClientValidationRangeRule.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelClientValidationRegexRule.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelClientValidationRequiredRule.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelClientValidationRule.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelClientValidationStringLengthRule.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelError.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelErrorCollection.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelMetadata.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelMetadataProvider.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelMetadataProviders.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelState.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelStateDictionary.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelValidationResult.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelValidator.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelValidatorProvider.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelValidatorProviderCollection.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelValidatorProviders.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/MultiSelectList.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/MvcHandler.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/MvcHtmlString.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/MvcHttpHandler.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/MvcRouteHandler.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/NameValueCollectionExtensions.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/NameValueCollectionValueProvider.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/NoAsyncTimeoutAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/NonActionAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/NullViewLocationCache.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/OutputCacheAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ParameterBindingInfo.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ParameterDescriptor.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ParameterInfoUtil.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/PartialViewResult.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/PathHelpers.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/QueryStringValueProvider.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/QueryStringValueProviderFactory.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/RangeAttributeAdapter.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ReaderWriterCache`2.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/RedirectResult.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/RedirectToRouteResult.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ReflectedActionDescriptor.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ReflectedControllerDescriptor.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ReflectedParameterBindingInfo.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ReflectedParameterDescriptor.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/RegularExpressionAttributeAdapter.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/RequireHttpsAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/RequiredAttributeAdapter.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Resources/MvcResources.Designer.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/Resources/MvcResources.resx [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ResultExecutedContext.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ResultExecutingContext.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/RouteCollectionExtensions.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/RouteDataValueProvider.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/RouteDataValueProviderFactory.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/RouteValuesHelpers.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/SelectList.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/SelectListItem.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/SessionStateTempDataProvider.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/StringLengthAttributeAdapter.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/TagBuilder.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/TagRenderMode.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/TempDataDictionary.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/TemplateInfo.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/TryGetValueDelegate.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/TypeCacheSerializer.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/TypeCacheUtil.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/TypeDescriptorHelper.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/TypeHelpers.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/UrlHelper.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/UrlParameter.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ValidateAntiForgeryTokenAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ValidateInputAttribute.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderCollection.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderDictionary.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderFactories.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderFactory.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderFactoryCollection.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderResult.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderUtil.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewContext.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewDataDictionary.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewDataDictionary`1.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewDataInfo.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewEngineCollection.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewEngineResult.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewEngines.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewMasterPage.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewMasterPage`1.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewPage.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewPageControlBuilder.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewPage`1.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewResult.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewResultBase.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewTemplateUserControl.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewTemplateUserControl`1.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewType.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewTypeControlBuilder.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewTypeParserFilter.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewUserControl.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewUserControlControlBuilder.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewUserControl`1.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/VirtualPathProviderViewEngine.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/WebFormView.cs [new file with mode: 0644]
mcs/class/System.Web.Mvc2/System.Web.Mvc/WebFormViewEngine.cs [new file with mode: 0644]
mcs/class/System.Web/ChangeLog
mcs/class/System.Web/Makefile
mcs/class/System.Web/System.Web.Compilation/AspGenerator.cs
mcs/class/System.Web/System.Web.Compilation/AspParser.cs
mcs/class/System.Web/System.Web.Compilation/ChangeLog
mcs/class/System.Web/System.Web.Compilation/PageCompiler.cs
mcs/class/System.Web/System.Web.Compilation/TagType.cs
mcs/class/System.Web/System.Web.Compilation/TemplateControlCompiler.cs
mcs/class/System.Web/System.Web.Configuration_2.0/ChangeLog
mcs/class/System.Web/System.Web.Configuration_2.0/GlobalizationSection.cs
mcs/class/System.Web/System.Web.Configuration_2.0/WebConfigurationManager.cs
mcs/class/System.Web/System.Web.UI.Adapters/ControlAdapter.cs
mcs/class/System.Web/System.Web.UI.Adapters/PageAdapter.cs
mcs/class/System.Web/System.Web.UI.Adapters/WmlPostFieldType.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlAnchor.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlButton.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlContainerControl.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlControl.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlEmptyTagControlBuilder.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlForm.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlHead.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlHeadBuilder.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlImage.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlInputButton.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlInputCheckBox.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlInputControl.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlInputFile.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlInputHidden.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlInputImage.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlInputPassword.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlInputRadioButton.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlInputReset.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlInputSubmit.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlInputText.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlLink.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlMeta.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlSelect.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlSelectBuilder.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlTable.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlTableCell.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlTableRow.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlTextArea.cs
mcs/class/System.Web/System.Web.UI.HtmlControls/HtmlTitle.cs
mcs/class/System.Web/System.Web.UI.WebControls/ChangeLog
mcs/class/System.Web/System.Web.UI.WebControls/CheckBoxField.cs
mcs/class/System.Web/System.Web.UI.WebControls/CookieParameter.cs
mcs/class/System.Web/System.Web.UI.WebControls/FormParameter.cs
mcs/class/System.Web/System.Web.UI.WebControls/FormView.cs
mcs/class/System.Web/System.Web.UI.WebControls/GridView.cs
mcs/class/System.Web/System.Web.UI.WebControls/ImageField.cs
mcs/class/System.Web/System.Web.UI.WebControls/ProfileParameter.cs
mcs/class/System.Web/System.Web.UI.WebControls/QueryStringParameter.cs
mcs/class/System.Web/System.Web.UI.WebControls/SessionParameter.cs
mcs/class/System.Web/System.Web.UI.WebControls/TreeView.cs
mcs/class/System.Web/System.Web.UI/ChangeLog
mcs/class/System.Web/System.Web.UI/CodeRenderBuilder.cs
mcs/class/System.Web/System.Web.UI/Control.cs
mcs/class/System.Web/System.Web.UI/FileLevelControlBuilderAttribute.cs
mcs/class/System.Web/System.Web.UI/Page.cs
mcs/class/System.Web/System.Web.UI/PageParser.cs
mcs/class/System.Web/System.Web/ChangeLog
mcs/class/System.Web/System.Web/HttpApplication.cs
mcs/class/System.Web/System.Web/HttpException.cs
mcs/class/System.Web/System.Web/HttpRequest.cs
mcs/class/System.Web/System.Web/HttpResponseStream.cs
mcs/class/System.Web/System.Web/HttpRuntime.cs
mcs/class/System.Web/System.Web/SiteMapNode.cs
mcs/class/System.Web/System.Web_standalone_test.dll.sources
mcs/class/System.Web/System.Web_test.dll.sources
mcs/class/System.Web/Test/System.Web.Compilation/TemplateControlCompilerTest.cs
mcs/class/System.Web/Test/System.Web.Configuration/GlobalizationSectionTest.cs
mcs/class/System.Web/Test/System.Web.UI.WebControls/ChangeLog
mcs/class/System.Web/Test/System.Web.UI.WebControls/CheckBoxFieldTest.cs
mcs/class/System.Web/Test/System.Web.UI.WebControls/FormViewTest.cs
mcs/class/System.Web/Test/System.Web.UI.WebControls/GridViewTest.cs
mcs/class/System.Web/Test/System.Web.UI/ChangeLog
mcs/class/System.Web/Test/System.Web.UI/ControlTest.cs
mcs/class/System.Web/Test/System.Web.UI/PageParserTest.cs
mcs/class/System.Web/Test/System.Web/ChangeLog
mcs/class/System.Web/Test/System.Web/HttpExceptionTest.cs [new file with mode: 0644]
mcs/class/System.Web/Test/System.Web/XmlSiteMapProviderTest.cs
mcs/class/System.Web/Test/mainsoft/NunitWeb/NunitWeb/ChangeLog
mcs/class/System.Web/Test/mainsoft/NunitWeb/NunitWeb/WebTest.cs
mcs/class/System.Web/Test/mainsoft/NunitWebResources/App_Code/CustomCheckBoxColumn.cs [new file with mode: 0644]
mcs/class/System.Web/Test/mainsoft/NunitWebResources/App_Code/MyContainer.cs [new file with mode: 0644]
mcs/class/System.Web/Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_0.aspx [new file with mode: 0644]
mcs/class/System.Web/Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_1.aspx [new file with mode: 0644]
mcs/class/System.Web/Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_2.aspx [new file with mode: 0644]
mcs/class/System.Web/Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_5.aspx [new file with mode: 0644]
mcs/class/System.Web/Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_6.aspx [new file with mode: 0644]
mcs/class/System.Web/Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_7.aspx [new file with mode: 0644]
mcs/class/System.Web/Test/mainsoft/NunitWebResources/FormViewPagerVisibility.aspx [new file with mode: 0644]
mcs/class/System.Web/Test/mainsoft/NunitWebResources/GlobalizationEncodingName.aspx [new file with mode: 0644]
mcs/class/System.Web/Test/mainsoft/NunitWebResources/GridView_Bug595567.aspx [new file with mode: 0644]
mcs/class/System.Web/Test/mainsoft/NunitWebResources/OverridenControlsPropertyAndPostBack_Bug594238.aspx [new file with mode: 0644]
mcs/class/System.Web/Test/standalone-tests/ChangeLog
mcs/class/System.Web/Test/standalone-tests/Unhandled_Exception_Global_Asax.cs [new file with mode: 0644]
mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_01/default.aspx [new file with mode: 0644]
mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_01/global.asax [new file with mode: 0644]
mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_01/global.asax.cs [new file with mode: 0644]
mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_01/web.config [new file with mode: 0644]
mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_02/default.aspx [new file with mode: 0644]
mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_02/global.asax [new file with mode: 0644]
mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_02/global.asax.cs [new file with mode: 0644]
mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_02/web.config [new file with mode: 0644]
mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_03/default.aspx [new file with mode: 0644]
mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_03/global.asax [new file with mode: 0644]
mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_03/global.asax.cs [new file with mode: 0644]
mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_03/web.config [new file with mode: 0644]
mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_04/default.aspx [new file with mode: 0644]
mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_04/global.asax [new file with mode: 0644]
mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_04/global.asax.cs [new file with mode: 0644]
mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_04/web.config [new file with mode: 0644]
mcs/class/System.XML/ChangeLog
mcs/class/System.XML/Makefile
mcs/class/System.XML/Mono.Xml/ChangeLog
mcs/class/System.XML/Mono.Xml/XmlFilterReader.cs
mcs/class/System.XML/System.Xml.Schema/ChangeLog
mcs/class/System.XML/System.Xml.Schema/XmlSchemaComplexType.cs
mcs/class/System.XML/System.Xml.Serialization/ChangeLog
mcs/class/System.XML/System.Xml.Serialization/SerializationSource.cs
mcs/class/System.XML/System.Xml.Serialization/XmlReflectionImporter.cs
mcs/class/System.XML/System.Xml.Serialization/XmlTypeMapping.cs
mcs/class/System.XML/System.Xml/ChangeLog
mcs/class/System.XML/System.Xml/DTDReader.cs
mcs/class/System.XML/System.Xml/DTDValidatingReader2.cs
mcs/class/System.XML/System.Xml/XmlInputStream.cs
mcs/class/System.XML/System.Xml/XmlNodeReader2.cs
mcs/class/System.XML/System.Xml/XmlNodeReaderImpl.cs
mcs/class/System.XML/System.Xml/XmlQualifiedName.cs
mcs/class/System.XML/System.Xml/XmlReader.cs
mcs/class/System.XML/System.Xml/XmlReaderSettings.cs
mcs/class/System.XML/System.Xml/XmlResolver.cs
mcs/class/System.XML/System.Xml/XmlTextReader.cs
mcs/class/System.XML/System.Xml/XmlTextWriter2.cs
mcs/class/System.XML/System.Xml/XmlWriter.cs
mcs/class/System.XML/System.Xml/XmlWriterSettings.cs
mcs/class/System.XML/Test/System.Xml.Schema/ChangeLog
mcs/class/System.XML/Test/System.Xml.Schema/XmlSchemaValidatorTests.cs
mcs/class/System.XML/Test/System.Xml.Serialization/ChangeLog
mcs/class/System.XML/Test/System.Xml.Serialization/XmlSerializerTests.cs
mcs/class/System.XML/Test/System.Xml/ChangeLog
mcs/class/System.XML/Test/System.Xml/XmlReaderCommonTests.cs
mcs/class/System.XML/Test/XmlFiles/xsd/584664a.xml [new file with mode: 0644]
mcs/class/System.XML/Test/XmlFiles/xsd/584664a.xsd [new file with mode: 0644]
mcs/class/System.XML/Test/XmlFiles/xsd/584664b.xml [new file with mode: 0644]
mcs/class/System.XML/Test/XmlFiles/xsd/584664b.xsd [new file with mode: 0644]
mcs/class/System.XML/Test/XmlFiles/xsd/ChangeLog
mcs/class/System.XML/moonlight_raw_System.Xml.dll.sources [new file with mode: 0644]
mcs/class/System.XML/net_2_1_raw_System.Xml.dll.sources [deleted file]
mcs/class/System.Xaml/Assembly/AssemblyInfo.cs [new file with mode: 0644]
mcs/class/System.Xaml/Assembly/ChangeLog [new file with mode: 0644]
mcs/class/System.Xaml/ChangeLog [new file with mode: 0644]
mcs/class/System.Xaml/Makefile [new file with mode: 0644]
mcs/class/System.Xaml/System.Windows.Markup/AmbientAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/ArrayExtension.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/ChangeLog [new file with mode: 0644]
mcs/class/System.Xaml/System.Windows.Markup/ConstructorArgumentAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/ContentPropertyAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/ContentWrapperAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/DateTimeValueSerializer.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/DependsOnAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/DictionaryKeyPropertyAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/IComponentConnector.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/INameScope.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Windows.Markup/INameScopeDictionary.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/IProvideValueTarget.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/IQueryAmbient.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/IUriContext.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/IValueSerializerContext.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Windows.Markup/IXamlTypeResolver.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/MarkupExtension.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Windows.Markup/MarkupExtensionReturnTypeAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/MemberDefinition.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/NameReferenceConverter.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/NameScopePropertyAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/NullExtension.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/PropertyDefinition.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/Reference.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/RootNamespaceAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/RuntimeNamePropertyAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/StaticExtension.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/StaticExtensionConverter.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Windows.Markup/TrimSurroundingWhitespaceAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/TypeExtension.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/TypeExtensionConverter.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Windows.Markup/UidPropertyAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/UsableDuringInitializationAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/ValueSerializer.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Windows.Markup/ValueSerializerAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/WhitespaceSignificantCollectionAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/XData.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/XamlDeferLoadAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/XamlSetMarkupExtensionAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/XamlSetMarkupExtensionEventArgs.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Windows.Markup/XamlSetTypeConverterAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/XamlSetTypeConverterEventArgs.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Windows.Markup/XamlSetValueEventArgs.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Windows.Markup/XmlLangPropertyAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/XmlnsCompatibleWithAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/XmlnsDefinitionAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Windows.Markup/XmlnsPrefixAttribute.cs [new file with mode: 0755]
mcs/class/System.Xaml/System.Xaml.Permissions/ChangeLog [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml.Permissions/XamlAccessLevel.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml.Permissions/XamlLoadPermission.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml.Schema/AllowedMemberLocations.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml.Schema/ChangeLog [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml.Schema/ShouldSerializeResult.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml.Schema/XamlCollectionKind.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml.Schema/XamlMemberInvoker.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml.Schema/XamlTypeInvoker.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml.Schema/XamlTypeName.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml.Schema/XamlTypeTypeConverter.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml.Schema/XamlValueConverter.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml.dll.sources [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/AmbientPropertyValue.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/AttachableMemberIdentifier.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/AttachablePropertyServices.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/ChangeLog [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/IAmbientProvider.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/IAttachedPropertyStore.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/IDestinationTypeProvider.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/INamespacePrefixLookup.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/IRootObjectProvider.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/IXamlIndexingReader.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/IXamlLineInfo.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/IXamlLineInfoConsumer.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/IXamlNameProvider.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/IXamlNameResolver.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/IXamlNamespaceResolver.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/IXamlObjectWriterFactory.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/IXamlSchemaContextProvider.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/NamespaceDeclaration.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/TypeExtensionMethods.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlBackgroundReader.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlDeferringLoader.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlDirective.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlDuplicateMemberException.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlException.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlInternalException.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlLanguage.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlMember.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlNodeList.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlNodeQueue.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlNodeType.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlObjectEventArgs.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlObjectReader.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlObjectReaderException.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlObjectReaderSettings.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlObjectWriter.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlObjectWriterException.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlObjectWriterSettings.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlParseException.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlReader.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlReaderSettings.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlSchemaContext.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlSchemaContextSettings.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlSchemaException.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlServices.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlType.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlWriter.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlWriterSettings.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlWriterStateManager.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlXmlReader.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlXmlReaderSettings.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlXmlWriter.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlXmlWriterException.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml/XamlXmlWriterSettings.cs [new file with mode: 0644]
mcs/class/System.Xaml/System.Xaml_test.dll.sources [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Windows.Markup/ArrayExtensionTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Windows.Markup/ChangeLog [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Windows.Markup/StaticExtensionTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Windows.Markup/TypeExtensionTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Windows.Markup/ValueSerializerTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Windows.Markup/XDataTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml.Schema/ChangeLog [new file with mode: 0755]
mcs/class/System.Xaml/Test/System.Xaml.Schema/XamlMemberInvokerTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml.Schema/XamlTypeInvokerTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml.Schema/XamlTypeNameTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml.Schema/XamlTypeTypeConverterTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml.Schema/XamlValueConverterTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml/AmbientPropertyValueTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml/AttachableMemberIdentifierTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml/ChangeLog [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml/NamespaceDeclarationTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml/XamlDirectiveTest.cs [new file with mode: 0755]
mcs/class/System.Xaml/Test/System.Xaml/XamlDuplicateMemberExceptionTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml/XamlLanguageTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml/XamlMemberTest.cs [new file with mode: 0755]
mcs/class/System.Xaml/Test/System.Xaml/XamlObjectEventArgsTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml/XamlObjectReaderSettingsTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml/XamlObjectReaderTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml/XamlObjectWriterSettingsTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml/XamlObjectWriterTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml/XamlReaderSettingsTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml/XamlSchemaContextSettingsTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml/XamlSchemaContextTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml/XamlTypeTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml/XamlXmlReaderSettingsTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml/XamlXmlReaderTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml/XamlXmlWriterSettingsTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/System.Xaml/XamlXmlWriterTest.cs [new file with mode: 0644]
mcs/class/System.Xaml/Test/XmlFiles/Array_Int32.xml [new file with mode: 0644]
mcs/class/System.Xaml/Test/XmlFiles/ChangeLog [new file with mode: 0644]
mcs/class/System.Xaml/Test/XmlFiles/DateTime.xml [new file with mode: 0644]
mcs/class/System.Xaml/Test/XmlFiles/Dictionary_Int32_String.xml [new file with mode: 0644]
mcs/class/System.Xaml/Test/XmlFiles/Dictionary_String_Type.xml [new file with mode: 0644]
mcs/class/System.Xaml/Test/XmlFiles/Int32.xml [new file with mode: 0644]
mcs/class/System.Xaml/Test/XmlFiles/List_Int32.xml [new file with mode: 0644]
mcs/class/System.Xaml/Test/XmlFiles/String.xml [new file with mode: 0644]
mcs/class/System.Xaml/Test/XmlFiles/TimeSpan.xml [new file with mode: 0644]
mcs/class/System.Xaml/Test/XmlFiles/Type.xml [new file with mode: 0644]
mcs/class/System.Xml.Linq/System.Xml.Linq/ChangeLog
mcs/class/System.Xml.Linq/System.Xml.Linq/SaveOptions.cs
mcs/class/System.Xml.Linq/System.Xml.Linq/XContainer.cs
mcs/class/System.Xml.Linq/System.Xml.Linq/XDocument.cs
mcs/class/System.Xml.Linq/System.Xml.Linq/XElement.cs
mcs/class/System.Xml.Linq/System.Xml.Linq/XNodeNavigator.cs
mcs/class/System.Xml.Linq/System.Xml.XPath/ChangeLog
mcs/class/System.Xml.Linq/System.Xml.XPath/Extensions.cs
mcs/class/System.Xml.Linq/Test/System.Xml.Linq/ChangeLog
mcs/class/System.Xml.Linq/Test/System.Xml.Linq/XAttributeTest.cs
mcs/class/System.Xml.Linq/Test/System.Xml.Linq/XElementTest.cs
mcs/class/System.Xml.Linq/Test/System.Xml.Linq/XNodeNavigatorTest.cs
mcs/class/System.Xml.Serialization/Assembly/AssemblyInfo.cs [new file with mode: 0644]
mcs/class/System.Xml.Serialization/Assembly/ChangeLog [new file with mode: 0644]
mcs/class/System.Xml.Serialization/ChangeLog [new file with mode: 0644]
mcs/class/System.Xml.Serialization/Makefile [new file with mode: 0644]
mcs/class/System.Xml.Serialization/System.Xml.Serialization.dll.sources [new file with mode: 0644]
mcs/class/System.Xml.Serialization/System.Xml.Serialization/ChangeLog [new file with mode: 0644]
mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlAttributeOverrides.cs [new file with mode: 0644]
mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlAttributes.cs [new file with mode: 0644]
mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlMapping.cs [new file with mode: 0644]
mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlSerializationGeneratedCode.cs [new file with mode: 0644]
mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlSerializationReader.cs [new file with mode: 0644]
mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlSerializationWriter.cs [new file with mode: 0644]
mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlSerializer.cs [new file with mode: 0644]
mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlSerializerNamespaces.cs [new file with mode: 0644]
mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlTypeMapping.cs [new file with mode: 0644]
mcs/class/System.Xml.Serialization/moonlight_raw_System.Xml.Serialization.dll.sources [new file with mode: 0644]
mcs/class/System/ChangeLog
mcs/class/System/Makefile
mcs/class/System/Microsoft.CSharp/CSharpCodeGenerator.cs
mcs/class/System/Microsoft.CSharp/ChangeLog
mcs/class/System/System.CodeDom.Compiler/ChangeLog
mcs/class/System/System.CodeDom.Compiler/CodeDomProvider.cs
mcs/class/System/System.CodeDom.Compiler/CodeGenerator.cs
mcs/class/System/System.CodeDom.Compiler/CompilerInfo.cs
mcs/class/System/System.CodeDom.Compiler/Executor.cs
mcs/class/System/System.CodeDom/CodeMemberMethod.cs
mcs/class/System/System.CodeDom/CodeNamespace.cs
mcs/class/System/System.CodeDom/CodeTypeDeclaration.cs
mcs/class/System/System.CodeDom/CodeTypeReference.cs
mcs/class/System/System.Collections.Concurrent/BlockingCollection.cs
mcs/class/System/System.Collections.Concurrent/ChangeLog
mcs/class/System/System.Collections.Concurrent/ConcurrentBag.cs
mcs/class/System/System.Collections.Generic/ChangeLog
mcs/class/System/System.Collections.Generic/ISet.cs
mcs/class/System/System.Collections.Generic/RBTree.cs
mcs/class/System/System.Collections.Generic/SortedSet.cs [new file with mode: 0644]
mcs/class/System/System.ComponentModel/ChangeLog
mcs/class/System/System.ComponentModel/ComponentCollection.cs
mcs/class/System/System.ComponentModel/PropertyDescriptor.cs
mcs/class/System/System.ComponentModel/TypeConverter_2_1.cs
mcs/class/System/System.ComponentModel/TypeDescriptor.cs
mcs/class/System/System.Configuration/ConfigurationSettings.cs
mcs/class/System/System.Diagnostics.CodeAnalysis/ChangeLog [new file with mode: 0644]
mcs/class/System/System.Diagnostics.CodeAnalysis/ExcludeFromCodeCoverageAttribute.cs [new file with mode: 0644]
mcs/class/System/System.Diagnostics/ChangeLog
mcs/class/System/System.Diagnostics/Debug.cs
mcs/class/System/System.IO.Compression/ChangeLog
mcs/class/System/System.IO.Compression/DeflateStream.cs
mcs/class/System/System.IO.Ports/ChangeLog
mcs/class/System/System.IO.Ports/SerialPort.cs
mcs/class/System/System.Net.Mail/SmtpClient.cs
mcs/class/System/System.Net.NetworkInformation/ChangeLog
mcs/class/System/System.Net.NetworkInformation/IPGlobalProperties.cs
mcs/class/System/System.Net.NetworkInformation/IPInterfaceProperties.cs
mcs/class/System/System.Net.NetworkInformation/IPv4InterfaceStatistics.cs
mcs/class/System/System.Net.NetworkInformation/NetworkInterface.cs
mcs/class/System/System.Net.NetworkInformation/Ping.cs
mcs/class/System/System.Net.Security/RemoteCertificateValidationCallback.cs
mcs/class/System/System.Net.Sockets/ChangeLog
mcs/class/System/System.Net.Sockets/Socket.cs
mcs/class/System/System.Net.Sockets/SocketAsyncEventArgs.cs
mcs/class/System/System.Net.Sockets/Socket_2_1.cs
mcs/class/System/System.Net/AuthenticationManager.cs
mcs/class/System/System.Net/ChangeLog
mcs/class/System/System.Net/ChunkStream.cs
mcs/class/System/System.Net/CookieContainer.cs
mcs/class/System/System.Net/Dns.cs
mcs/class/System/System.Net/FtpDataStream.cs
mcs/class/System/System.Net/FtpWebRequest.cs
mcs/class/System/System.Net/FtpWebResponse.cs
mcs/class/System/System.Net/HttpConnection.cs
mcs/class/System/System.Net/HttpContinueDelegate.cs
mcs/class/System/System.Net/HttpRequestCreator.cs
mcs/class/System/System.Net/HttpStatusCode.cs
mcs/class/System/System.Net/HttpWebRequest.cs
mcs/class/System/System.Net/HttpWebResponse.cs
mcs/class/System/System.Net/IAuthenticationModule.cs
mcs/class/System/System.Net/ICertificatePolicy.cs
mcs/class/System/System.Net/ICredentialPolicy.cs
mcs/class/System/System.Net/IWebRequestCreate.cs
mcs/class/System/System.Net/NtlmClient.cs
mcs/class/System/System.Net/ServicePoint.cs
mcs/class/System/System.Net/ServicePointManager.cs
mcs/class/System/System.Net/WebClient.cs
mcs/class/System/System.Net/WebConnection.cs
mcs/class/System/System.Net/WebConnectionGroup.cs
mcs/class/System/System.Net/WebException.cs
mcs/class/System/System.Net/WebHeaderCollection.cs
mcs/class/System/System.Net/WebRequest.cs
mcs/class/System/System.Net/WebResponse.cs
mcs/class/System/System.Runtime.Versioning/ChangeLog [new file with mode: 0644]
mcs/class/System/System.Runtime.Versioning/FrameworkName.cs [new file with mode: 0644]
mcs/class/System/System.Security.Cryptography.X509Certificates/ChangeLog
mcs/class/System/System.Security.Cryptography.X509Certificates/X509Chain.cs
mcs/class/System/System.Text.RegularExpressions/CILCompiler.cs
mcs/class/System/System.Text.RegularExpressions/ChangeLog
mcs/class/System/System.Text.RegularExpressions/RxInterpreter.cs
mcs/class/System/System.Threading/Barrier.cs
mcs/class/System/System.Threading/ChangeLog
mcs/class/System/System.Threading/SemaphoreFullException.cs
mcs/class/System/System.Timers/ChangeLog
mcs/class/System/System.Timers/Timer.cs
mcs/class/System/System.dll.sources
mcs/class/System/System/ChangeLog
mcs/class/System/System/Uri.cs
mcs/class/System/System/UriTypeConverter.cs
mcs/class/System/System_test.dll.sources
mcs/class/System/Test/Microsoft.CSharp/ChangeLog
mcs/class/System/Test/Microsoft.CSharp/CodeGeneratorFromExpressionTest.cs
mcs/class/System/Test/System.CodeDom.Compiler/ChangeLog
mcs/class/System/Test/System.CodeDom.Compiler/CodeGeneratorTest.cs
mcs/class/System/Test/System.Collections.Concurrent/BlockingCollectionTests.cs
mcs/class/System/Test/System.Collections.Concurrent/ChangeLog
mcs/class/System/Test/System.Collections.Generic/ChangeLog
mcs/class/System/Test/System.Collections.Generic/SortedSetTest.cs [new file with mode: 0644]
mcs/class/System/Test/System.Runtime.Versioning/ChangeLog [new file with mode: 0644]
mcs/class/System/Test/System.Runtime.Versioning/FrameworkNameTest.cs [new file with mode: 0644]
mcs/class/System/Test/System/ChangeLog
mcs/class/System/Test/System/UriTest.cs
mcs/class/System/monotouch_System.dll.sources
mcs/class/System/moonlight_bootstrap_System.dll.sources [new file with mode: 0644]
mcs/class/System/moonlight_raw_System.dll.sources [new file with mode: 0644]
mcs/class/System/net_2_1_bootstrap_System.dll.sources [deleted file]
mcs/class/System/net_2_1_raw_System.dll.sources [deleted file]
mcs/class/corlib/Assembly/AssemblyInfo.cs
mcs/class/corlib/Assembly/ChangeLog
mcs/class/corlib/ChangeLog
mcs/class/corlib/Makefile
mcs/class/corlib/Mono.Globalization.Unicode/ChangeLog
mcs/class/corlib/Mono.Globalization.Unicode/Normalization.cs
mcs/class/corlib/Mono.Security.Authenticode/AuthenticodeBase.cs
mcs/class/corlib/Mono.Security.Authenticode/AuthenticodeDeformatter.cs
mcs/class/corlib/Mono.Security.Authenticode/ChangeLog
mcs/class/corlib/Mono.Security.Cryptography/ChangeLog
mcs/class/corlib/Mono.Security.Cryptography/CryptoTools.cs
mcs/class/corlib/Mono.Security.Cryptography/KeyPairPersistence.cs
mcs/class/corlib/Mono.Security.Cryptography/PKCS1.cs
mcs/class/corlib/Mono.Security.Cryptography/PKCS8.cs
mcs/class/corlib/Mono.Security.Cryptography/SymmetricTransform.cs
mcs/class/corlib/Mono.Security.X509/ChangeLog
mcs/class/corlib/Mono.Security.X509/X509Certificate.cs
mcs/class/corlib/Mono.Security/ASN1Convert.cs
mcs/class/corlib/Mono.Security/ChangeLog
mcs/class/corlib/Mono.Security/StrongName.cs
mcs/class/corlib/Mono/Runtime.cs
mcs/class/corlib/System.Collections.Concurrent/ChangeLog
mcs/class/corlib/System.Collections.Concurrent/ConcurrentDictionary.cs
mcs/class/corlib/System.Collections.Concurrent/ConcurrentSkipList.cs
mcs/class/corlib/System.Collections.Concurrent/OrderablePartitioner.cs
mcs/class/corlib/System.Collections.Concurrent/Partitioner.cs
mcs/class/corlib/System.Collections.Concurrent/Partitioners/ChangeLog [new file with mode: 0644]
mcs/class/corlib/System.Collections.Concurrent/Partitioners/EnumerablePartitioner.cs
mcs/class/corlib/System.Collections.Concurrent/Partitioners/ListPartitioner.cs
mcs/class/corlib/System.Collections.Generic/ChangeLog
mcs/class/corlib/System.Collections.Generic/CollectionDebuggerView.cs
mcs/class/corlib/System.Collections/ChangeLog
mcs/class/corlib/System.Collections/CollectionDebuggerView.cs
mcs/class/corlib/System.Collections/IStructuralComparable.cs
mcs/class/corlib/System.Collections/IStructuralEquatable.cs
mcs/class/corlib/System.Diagnostics/ChangeLog
mcs/class/corlib/System.Diagnostics/StackFrame.cs
mcs/class/corlib/System.Diagnostics/StackTrace.cs
mcs/class/corlib/System.Globalization/Calendar.cs
mcs/class/corlib/System.Globalization/ChangeLog
mcs/class/corlib/System.Globalization/CompareInfo.cs
mcs/class/corlib/System.Globalization/CultureInfo.cs
mcs/class/corlib/System.IO.IsolatedStorage/ChangeLog
mcs/class/corlib/System.IO.IsolatedStorage/IsolatedStorage.cs
mcs/class/corlib/System.IO.IsolatedStorage/IsolatedStorageFile.cs
mcs/class/corlib/System.IO.IsolatedStorage/IsolatedStorageFileEnumerator.cs
mcs/class/corlib/System.IO.IsolatedStorage/IsolatedStorageFileStream.cs
mcs/class/corlib/System.IO.IsolatedStorage/IsolatedStorageScope.cs
mcs/class/corlib/System.IO.IsolatedStorage/MoonIsolatedStorage.cs
mcs/class/corlib/System.IO.IsolatedStorage/MoonIsolatedStorageFile.cs
mcs/class/corlib/System.IO.IsolatedStorage/MoonIsolatedStorageFileStream.cs
mcs/class/corlib/System.IO/ChangeLog
mcs/class/corlib/System.IO/Directory.cs
mcs/class/corlib/System.IO/DirectoryInfo.cs
mcs/class/corlib/System.IO/File.cs
mcs/class/corlib/System.IO/FileInfo.cs
mcs/class/corlib/System.IO/FileStream.cs
mcs/class/corlib/System.IO/FileSystemInfo.cs
mcs/class/corlib/System.IO/Path.cs
mcs/class/corlib/System.IO/SearchOption.cs
mcs/class/corlib/System.IO/Stream.cs
mcs/class/corlib/System.IO/StreamReader.cs
mcs/class/corlib/System.Reflection.Emit/AssemblyBuilder.cs
mcs/class/corlib/System.Reflection.Emit/ChangeLog
mcs/class/corlib/System.Reflection.Emit/CustomAttributeBuilder.cs
mcs/class/corlib/System.Reflection.Emit/DerivedTypes.cs
mcs/class/corlib/System.Reflection.Emit/DynamicMethod.cs
mcs/class/corlib/System.Reflection.Emit/EnumBuilder.cs
mcs/class/corlib/System.Reflection.Emit/GenericTypeParameterBuilder.cs
mcs/class/corlib/System.Reflection.Emit/MethodOnTypeBuilderInst.cs
mcs/class/corlib/System.Reflection.Emit/ModuleBuilder.cs
mcs/class/corlib/System.Reflection.Emit/MonoArrayMethod.cs
mcs/class/corlib/System.Reflection.Emit/TypeBuilder.cs
mcs/class/corlib/System.Reflection/Assembly.cs
mcs/class/corlib/System.Reflection/Binder.cs
mcs/class/corlib/System.Reflection/ChangeLog
mcs/class/corlib/System.Reflection/MethodBase.cs
mcs/class/corlib/System.Reflection/MethodInfo.cs
mcs/class/corlib/System.Reflection/Module.cs
mcs/class/corlib/System.Reflection/MonoAssembly.cs [new file with mode: 0644]
mcs/class/corlib/System.Reflection/MonoField.cs
mcs/class/corlib/System.Reflection/MonoGenericClass.cs
mcs/class/corlib/System.Reflection/MonoMethod.cs
mcs/class/corlib/System.Reflection/MonoModule.cs [new file with mode: 0644]
mcs/class/corlib/System.Resources/ChangeLog
mcs/class/corlib/System.Resources/ResourceManager.cs
mcs/class/corlib/System.Runtime.CompilerServices/ChangeLog
mcs/class/corlib/System.Runtime.CompilerServices/ConditionalWeakTable.cs
mcs/class/corlib/System.Runtime.CompilerServices/ReferenceAssemblyAttribute.cs
mcs/class/corlib/System.Runtime.CompilerServices/TypeForwardedFromAttribute.cs
mcs/class/corlib/System.Runtime.InteropServices/ChangeLog
mcs/class/corlib/System.Runtime.InteropServices/Marshal.cs
mcs/class/corlib/System.Runtime.InteropServices/MarshalAsAttribute.cs
mcs/class/corlib/System.Runtime.InteropServices/SafeHandle.cs
mcs/class/corlib/System.Runtime.Remoting.Channels/CrossAppDomainChannel.cs
mcs/class/corlib/System.Runtime.Remoting.Contexts/ChangeLog
mcs/class/corlib/System.Runtime.Remoting.Contexts/Context.cs
mcs/class/corlib/System.Runtime.Remoting.Messaging/AsyncResult.cs
mcs/class/corlib/System.Runtime.Remoting.Messaging/ChangeLog
mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/BinaryCommon.cs
mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/ChangeLog
mcs/class/corlib/System.Runtime.Serialization/SerializationInfo.cs
mcs/class/corlib/System.Runtime.Versioning/FrameworkName.cs [deleted file]
mcs/class/corlib/System.Security.Cryptography.X509Certificates/ChangeLog
mcs/class/corlib/System.Security.Cryptography.X509Certificates/X509Certificate.cs
mcs/class/corlib/System.Security.Cryptography.X509Certificates/X509Certificate20.cs
mcs/class/corlib/System.Security.Cryptography.X509Certificates/X509ContentType.cs
mcs/class/corlib/System.Security.Cryptography.X509Certificates/X509KeyStorageFlags.cs
mcs/class/corlib/System.Security.Cryptography/ChangeLog
mcs/class/corlib/System.Security.Cryptography/CryptoConfig.cs
mcs/class/corlib/System.Security.Cryptography/CryptoConfig_2_1.cs
mcs/class/corlib/System.Security.Cryptography/DES.cs
mcs/class/corlib/System.Security.Cryptography/DESCryptoServiceProvider.cs
mcs/class/corlib/System.Security.Cryptography/DSACryptoServiceProvider.cs
mcs/class/corlib/System.Security.Cryptography/HMACMD5.cs
mcs/class/corlib/System.Security.Cryptography/HMACRIPEMD160.cs
mcs/class/corlib/System.Security.Cryptography/HMACSHA384.cs
mcs/class/corlib/System.Security.Cryptography/HMACSHA512.cs
mcs/class/corlib/System.Security.Cryptography/MACTripleDES.cs
mcs/class/corlib/System.Security.Cryptography/RC2.cs
mcs/class/corlib/System.Security.Cryptography/RC2CryptoServiceProvider.cs
mcs/class/corlib/System.Security.Cryptography/RIPEMD160.cs
mcs/class/corlib/System.Security.Cryptography/RIPEMD160Managed.cs
mcs/class/corlib/System.Security.Cryptography/RSACryptoServiceProvider.cs
mcs/class/corlib/System.Security.Cryptography/Rijndael.cs
mcs/class/corlib/System.Security.Cryptography/RijndaelManaged.cs
mcs/class/corlib/System.Security.Cryptography/RijndaelManagedTransform.cs
mcs/class/corlib/System.Security.Cryptography/SHA1CryptoServiceProvider.cs
mcs/class/corlib/System.Security.Cryptography/SHA384.cs
mcs/class/corlib/System.Security.Cryptography/SHA384Managed.cs
mcs/class/corlib/System.Security.Cryptography/SHA512.cs
mcs/class/corlib/System.Security.Cryptography/SHA512Managed.cs
mcs/class/corlib/System.Security.Cryptography/SymmetricAlgorithm.cs
mcs/class/corlib/System.Security.Cryptography/TripleDES.cs
mcs/class/corlib/System.Security.Cryptography/TripleDESCryptoServiceProvider.cs
mcs/class/corlib/System.Security.Permissions/ChangeLog
mcs/class/corlib/System.Security.Permissions/PublisherIdentityPermissionAttribute.cs
mcs/class/corlib/System.Security.Policy/ChangeLog
mcs/class/corlib/System.Security.Policy/Evidence.cs
mcs/class/corlib/System.Security.Policy/Hash.cs
mcs/class/corlib/System.Security.Policy/HashMembershipCondition.cs
mcs/class/corlib/System.Security.Policy/PolicyLevel.cs
mcs/class/corlib/System.Security.Policy/PolicyLevel_2_1.cs
mcs/class/corlib/System.Security.Policy/Zone.cs
mcs/class/corlib/System.Security.Policy/ZoneMembershipCondition.cs
mcs/class/corlib/System.Security/ChangeLog
mcs/class/corlib/System.Security/IPermission.cs
mcs/class/corlib/System.Security/SecurityFrame.cs
mcs/class/corlib/System.Security/SecurityManager.cs
mcs/class/corlib/System.Security/SecurityManager_2_1.cs
mcs/class/corlib/System.Security/SecuritySafeCriticalAttribute.cs
mcs/class/corlib/System.Security/SecurityTransparentAttribute.cs
mcs/class/corlib/System.Text/ChangeLog
mcs/class/corlib/System.Text/Encoding.cs
mcs/class/corlib/System.Text/StringBuilder.cs
mcs/class/corlib/System.Threading.Tasks/ChangeLog
mcs/class/corlib/System.Threading.Tasks/Future.cs
mcs/class/corlib/System.Threading.Tasks/Internal/ChangeLog [new file with mode: 0644]
mcs/class/corlib/System.Threading.Tasks/Internal/CyclicDeque.cs
mcs/class/corlib/System.Threading.Tasks/Internal/IScheduler.cs
mcs/class/corlib/System.Threading.Tasks/Internal/Scheduler.cs
mcs/class/corlib/System.Threading.Tasks/Internal/SchedulerProxy.cs
mcs/class/corlib/System.Threading.Tasks/Internal/ThreadWorker.cs
mcs/class/corlib/System.Threading.Tasks/Task.cs
mcs/class/corlib/System.Threading.Tasks/TaskCanceledException.cs
mcs/class/corlib/System.Threading.Tasks/TaskContinuationOptions.cs
mcs/class/corlib/System.Threading.Tasks/TaskCreationOptions.cs
mcs/class/corlib/System.Threading.Tasks/TaskFactory.cs
mcs/class/corlib/System.Threading.Tasks/TaskScheduler.cs
mcs/class/corlib/System.Threading.Tasks/TaskStatus.cs
mcs/class/corlib/System.Threading/AtomicBoolean.cs
mcs/class/corlib/System.Threading/ChangeLog
mcs/class/corlib/System.Threading/CountdownEvent.cs
mcs/class/corlib/System.Threading/ExecutionContext.cs
mcs/class/corlib/System.Threading/LazyThreadSafetyMode.cs
mcs/class/corlib/System.Threading/Monitor.cs
mcs/class/corlib/System.Threading/SpinLock.cs
mcs/class/corlib/System.Threading/Thread.cs
mcs/class/corlib/System.Threading/ThreadPool.cs
mcs/class/corlib/System/Action.cs
mcs/class/corlib/System/Activator.cs
mcs/class/corlib/System/AppDomain.cs
mcs/class/corlib/System/AppDomainSetup.cs
mcs/class/corlib/System/Array.cs
mcs/class/corlib/System/ChangeLog
mcs/class/corlib/System/CharEnumerator.cs
mcs/class/corlib/System/Console.cs
mcs/class/corlib/System/Convert.cs
mcs/class/corlib/System/DateTime.cs
mcs/class/corlib/System/DateTimeOffset.cs
mcs/class/corlib/System/Delegate.cs
mcs/class/corlib/System/Enum.cs
mcs/class/corlib/System/Environment.cs
mcs/class/corlib/System/Exception.cs
mcs/class/corlib/System/Funcs.cs
mcs/class/corlib/System/Guid.cs
mcs/class/corlib/System/Int64.cs
mcs/class/corlib/System/InvalidTimeZoneException.cs
mcs/class/corlib/System/Lazy.cs
mcs/class/corlib/System/MonoAsyncCall.cs
mcs/class/corlib/System/MonoCustomAttrs.cs
mcs/class/corlib/System/MonoType.cs
mcs/class/corlib/System/MulticastDelegate.cs
mcs/class/corlib/System/String.cs
mcs/class/corlib/System/TimeSpan.cs
mcs/class/corlib/System/TimeZoneNotFoundException.cs
mcs/class/corlib/System/Tuple.cs
mcs/class/corlib/System/Tuples.cs
mcs/class/corlib/System/Type.cs
mcs/class/corlib/System/UInt32.cs
mcs/class/corlib/System/UInt64.cs
mcs/class/corlib/Test/System.Collections.Concurrent/ChangeLog
mcs/class/corlib/Test/System.Collections.Concurrent/ConcurrentDictionaryTests.cs
mcs/class/corlib/Test/System.Collections/HashtableTest.cs
mcs/class/corlib/Test/System.Collections/StackTest.cs
mcs/class/corlib/Test/System.IO/ChangeLog
mcs/class/corlib/Test/System.IO/DirectoryTest.cs
mcs/class/corlib/Test/System.IO/StreamReaderTest.cs
mcs/class/corlib/Test/System.Reflection.Emit/AssemblyBuilderTest.cs
mcs/class/corlib/Test/System.Reflection.Emit/ChangeLog
mcs/class/corlib/Test/System.Reflection.Emit/DerivedTypesTest.cs
mcs/class/corlib/Test/System.Reflection.Emit/MethodBuilderTest.cs
mcs/class/corlib/Test/System.Reflection.Emit/MethodOnTypeBuilderInstTest.cs
mcs/class/corlib/Test/System.Reflection.Emit/ModuleBuilderTest.cs
mcs/class/corlib/Test/System.Reflection.Emit/TypeBuilderTest.cs
mcs/class/corlib/Test/System.Reflection/AssemblyNameTest.cs
mcs/class/corlib/Test/System.Reflection/AssemblyTest.cs
mcs/class/corlib/Test/System.Reflection/BinderTests.cs
mcs/class/corlib/Test/System.Reflection/ChangeLog
mcs/class/corlib/Test/System.Reflection/FieldInfoTest.cs
mcs/class/corlib/Test/System.Reflection/MonoGenericClassTest.cs
mcs/class/corlib/Test/System.Resources/ResourceManagerTest.cs
mcs/class/corlib/Test/System.Runtime.InteropServices/SafeHandleTest.cs
mcs/class/corlib/Test/System.Runtime.Versioning/FrameworkNameTest.cs [deleted file]
mcs/class/corlib/Test/System.Threading/ChangeLog
mcs/class/corlib/Test/System.Threading/SpinLockTests.cs
mcs/class/corlib/Test/System/ActivatorTest.cs
mcs/class/corlib/Test/System/ArrayTest.cs
mcs/class/corlib/Test/System/AttributeTest.cs
mcs/class/corlib/Test/System/BufferTest.cs
mcs/class/corlib/Test/System/ChangeLog
mcs/class/corlib/Test/System/CharCategoryTest.cs
mcs/class/corlib/Test/System/CharTest.cs
mcs/class/corlib/Test/System/ConvertTest.cs
mcs/class/corlib/Test/System/DateTimeOffsetTest.cs
mcs/class/corlib/Test/System/GuidTest.cs
mcs/class/corlib/Test/System/Int64Test.cs
mcs/class/corlib/Test/System/StringTest.cs
mcs/class/corlib/Test/System/TimeSpanTest.cs
mcs/class/corlib/Test/System/TypeTest.cs
mcs/class/corlib/Test/System/UInt32Test.cs
mcs/class/corlib/Test/System/UInt64Test.cs
mcs/class/corlib/corlib.dll.sources
mcs/class/corlib/corlib_test.dll.sources
mcs/class/corlib/moonlight_bootstrap_corlib.dll.sources [new file with mode: 0644]
mcs/class/corlib/moonlight_raw_corlib.dll.sources [new file with mode: 0644]
mcs/class/corlib/net_2_1_bootstrap_corlib.dll.sources [deleted file]
mcs/class/corlib/net_2_1_raw_corlib.dll.sources [deleted file]
mcs/class/dlr/ChangeLog
mcs/class/dlr/Runtime/Microsoft.Dynamic/Microsoft.Dynamic.Build.csproj
mcs/class/dlr/Runtime/Microsoft.Dynamic/Microsoft.Dynamic.csproj
mcs/class/dlr/Runtime/Microsoft.Dynamic/Properties/AssemblyInfo.cs
mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/DynamicObject.cs
mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/IInvokeOnGetBinder.cs [new file with mode: 0644]
mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Ast/TypeUtils.cs
mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/ConstantCheck.cs
mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/ILGen.cs
mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Microsoft.Scripting.Core.csproj
mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Microsoft.Scripting.ExtensionAttribute.csproj
mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Properties/AssemblyInfo.cs
mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Properties/ExtensionAssemblyInfo.cs
mcs/class/dlr/Runtime/Microsoft.Scripting.Core/System.Core.csproj
mcs/errors/ChangeLog
mcs/errors/Makefile
mcs/errors/cs0182-10.cs [new file with mode: 0644]
mcs/errors/cs0182-8.cs [new file with mode: 0644]
mcs/errors/cs0182-9.cs [new file with mode: 0644]
mcs/errors/cs0415.cs
mcs/errors/gcs0701-3.cs [deleted file]
mcs/errors/gcs0706.cs [new file with mode: 0644]
mcs/errors/known-issues-dmcs
mcs/ilasm/parser/ChangeLog
mcs/ilasm/parser/ILParser.jay
mcs/jay/ChangeLog
mcs/jay/defs.h
mcs/mcs/ChangeLog
mcs/mcs/Makefile
mcs/mcs/anonymous.cs
mcs/mcs/argument.cs
mcs/mcs/assign.cs
mcs/mcs/attribute.cs
mcs/mcs/cfold.cs
mcs/mcs/class.cs
mcs/mcs/codegen.cs
mcs/mcs/complete.cs
mcs/mcs/const.cs
mcs/mcs/constant.cs
mcs/mcs/context.cs
mcs/mcs/convert.cs
mcs/mcs/cs-parser.jay
mcs/mcs/decl.cs
mcs/mcs/delegate.cs
mcs/mcs/dmcs.exe.config
mcs/mcs/doc.cs
mcs/mcs/driver.cs
mcs/mcs/dynamic.cs
mcs/mcs/ecore.cs
mcs/mcs/enum.cs
mcs/mcs/eval.cs
mcs/mcs/expression.cs
mcs/mcs/field.cs
mcs/mcs/flowanalysis.cs
mcs/mcs/generic.cs
mcs/mcs/import.cs
mcs/mcs/iterators.cs
mcs/mcs/lambda.cs
mcs/mcs/linq.cs
mcs/mcs/literal.cs
mcs/mcs/membercache.cs
mcs/mcs/method.cs
mcs/mcs/modifiers.cs
mcs/mcs/namespace.cs
mcs/mcs/nullable.cs
mcs/mcs/parameter.cs
mcs/mcs/pending.cs
mcs/mcs/property.cs
mcs/mcs/report.cs
mcs/mcs/rootcontext.cs
mcs/mcs/roottypes.cs
mcs/mcs/statement.cs
mcs/mcs/support.cs
mcs/mcs/symbolwriter.cs
mcs/mcs/typemanager.cs
mcs/mcs/typespec.cs
mcs/tests/ChangeLog
mcs/tests/Makefile
mcs/tests/eval-test.cs
mcs/tests/gtest-232.cs [deleted file]
mcs/tests/gtest-262.cs
mcs/tests/gtest-284.cs
mcs/tests/gtest-316.cs
mcs/tests/gtest-473.cs [new file with mode: 0644]
mcs/tests/gtest-474.cs [new file with mode: 0644]
mcs/tests/gtest-475.cs [new file with mode: 0644]
mcs/tests/gtest-476.cs [new file with mode: 0644]
mcs/tests/gtest-477.cs [new file with mode: 0644]
mcs/tests/gtest-478.cs [new file with mode: 0644]
mcs/tests/gtest-479.cs [new file with mode: 0644]
mcs/tests/gtest-480.cs [new file with mode: 0644]
mcs/tests/gtest-481.cs [new file with mode: 0644]
mcs/tests/gtest-anon-11.cs
mcs/tests/gtest-anon-24.cs
mcs/tests/gtest-anon-59.cs [new file with mode: 0644]
mcs/tests/gtest-exmethod-30.cs [new file with mode: 0644]
mcs/tests/gtest-exmethod-31.cs [new file with mode: 0644]
mcs/tests/gtest-iter-12.cs [new file with mode: 0644]
mcs/tests/gtest-iter-13.cs [new file with mode: 0644]
mcs/tests/gtest-optional-08.cs [new file with mode: 0644]
mcs/tests/known-issues-dmcs
mcs/tests/known-issues-gmcs
mcs/tests/test-106.cs
mcs/tests/test-450.cs [deleted file]
mcs/tests/test-733.cs
mcs/tests/test-743-lib.cs [new file with mode: 0644]
mcs/tests/test-743.cs [new file with mode: 0644]
mcs/tests/test-744.cs [new file with mode: 0644]
mcs/tests/test-745.cs [new file with mode: 0644]
mcs/tests/test-746.cs [new file with mode: 0644]
mcs/tests/test-747.cs [new file with mode: 0644]
mcs/tests/test-748-lib.cs [new file with mode: 0644]
mcs/tests/test-748.cs [new file with mode: 0644]
mcs/tests/test-749-lib.cs [new file with mode: 0644]
mcs/tests/test-749.cs [new file with mode: 0644]
mcs/tests/test-750.cs [new file with mode: 0644]
mcs/tests/test-751.cs [new file with mode: 0644]
mcs/tests/test-752-lib.cs [new file with mode: 0644]
mcs/tests/test-752.cs [new file with mode: 0644]
mcs/tests/ver-il-gmcs.xml
mcs/tools/ChangeLog
mcs/tools/Makefile
mcs/tools/compiler-tester/Makefile
mcs/tools/corcompare/ChangeLog
mcs/tools/corcompare/mono-api-diff.cs [new file with mode: 0644]
mcs/tools/gensources.sh [deleted file]
mcs/tools/mdoc/ChangeLog
mcs/tools/mdoc/Makefile
mcs/tools/mdoc/Mono.Documentation/monodocer.cs
mcs/tools/mdoc/Mono.Documentation/webdoc.cs
mcs/tools/mkbundle/ChangeLog
mcs/tools/mkbundle/mkbundle.cs
mcs/tools/monodoc/ChangeLog
mcs/tools/monodoc/Monodoc/ecma-provider.cs
mcs/tools/monop/monop.cs
mcs/tools/monop/options.cs
mcs/tools/monop/outline.cs
mcs/tools/sqlmetal/AssemblyInfo.cs
mcs/tools/sqlmetal/ChangeLog
mcs/tools/sqlmetal/sqlmetal.exe.sources
mcs/tools/xbuild/ChangeLog
mcs/tools/xbuild/Main.cs
mcs/tools/xbuild/Makefile
mcs/tools/xbuild/Parameters.cs
mcs/tools/xbuild/SolutionParser.cs
mcs/tools/xbuild/xbuild/2.0/Microsoft.Common.targets [new file with mode: 0644]
mcs/tools/xbuild/xbuild/2.0/Microsoft.Common.tasks [new file with mode: 0644]
mcs/tools/xbuild/xbuild/3.5/Microsoft.Common.targets [new file with mode: 0644]
mcs/tools/xbuild/xbuild/3.5/Microsoft.Common.tasks [new file with mode: 0644]
mcs/tools/xbuild/xbuild/4.0/Microsoft.Common.targets [new file with mode: 0644]
mcs/tools/xbuild/xbuild/4.0/Microsoft.Common.tasks [new file with mode: 0644]
mcs/tools/xbuild/xbuild/Microsoft.CSharp.targets
mcs/tools/xbuild/xbuild/Microsoft.Common.targets [deleted file]
mcs/tools/xbuild/xbuild/Microsoft.Common.tasks [deleted file]
mcs/tools/xbuild/xbuild/Microsoft.Silverlight.CSharp.targets [new file with mode: 0644]
mcs/tools/xbuild/xbuild/Microsoft.Silverlight.Common.targets [new file with mode: 0644]
mcs/tools/xbuild/xbuild/Microsoft.Silverlight.VisualBasic.targets [new file with mode: 0644]
mcs/tools/xbuild/xbuild/Microsoft.VisualBasic.targets
mcs/tools/xbuild/xbuild_targets.make [new file with mode: 0644]
mono/arch/ChangeLog
mono/arch/arm/.gitignore
mono/arch/arm/dpiops.sh
mono/arch/arm/fpaops.sh
mono/arch/arm/vfpops.sh
mono/arch/s390x/ChangeLog
mono/arch/s390x/s390x-codegen.h
mono/dis/.gitignore
mono/dis/ChangeLog
mono/dis/get.c
mono/dis/main.c
mono/dis/util.c
mono/interpreter/.gitignore
mono/io-layer/.gitignore
mono/io-layer/ChangeLog
mono/io-layer/collection.c
mono/io-layer/mono-mutex.c
mono/io-layer/process-private.h
mono/io-layer/processes.c
mono/io-layer/shared.c
mono/io-layer/sockets.c
mono/io-layer/threads.h
mono/io-layer/wthreads.c
mono/metadata/.gitignore
mono/metadata/ChangeLog
mono/metadata/Makefile.am
mono/metadata/appdomain.c
mono/metadata/boehm-gc.c
mono/metadata/class-internals.h
mono/metadata/class.c
mono/metadata/cominterop.c
mono/metadata/console-unix.c
mono/metadata/culture-info-tables.h
mono/metadata/debug-helpers.c
mono/metadata/domain-internals.h
mono/metadata/domain.c
mono/metadata/exception.c
mono/metadata/file-io.c
mono/metadata/gc-internal.h
mono/metadata/icall-def.h
mono/metadata/icall.c
mono/metadata/loader.c
mono/metadata/locales.c
mono/metadata/marshal.c
mono/metadata/metadata-internals.h
mono/metadata/metadata-verify.c
mono/metadata/metadata.c
mono/metadata/method-builder.c
mono/metadata/mono-config.c
mono/metadata/mono-debug.c
mono/metadata/mono-mlist.c
mono/metadata/mono-mlist.h
mono/metadata/mono-perfcounters-def.h
mono/metadata/mono-perfcounters.c
mono/metadata/mono-wsq.c [new file with mode: 0644]
mono/metadata/mono-wsq.h [new file with mode: 0644]
mono/metadata/null-gc.c
mono/metadata/object-internals.h
mono/metadata/object.c
mono/metadata/object.h
mono/metadata/pedump.c
mono/metadata/process.c
mono/metadata/reflection.c
mono/metadata/security-core-clr.c
mono/metadata/security-core-clr.h
mono/metadata/sgen-archdep.h
mono/metadata/sgen-gc.c
mono/metadata/sgen-gc.h
mono/metadata/sgen-gray.c
mono/metadata/sgen-major-copying.c [new file with mode: 0644]
mono/metadata/sgen-marksweep.c [new file with mode: 0644]
mono/metadata/sgen-pinning-stats.c
mono/metadata/sgen-pinning.c
mono/metadata/sgen-protocol.c
mono/metadata/sgen-protocol.h
mono/metadata/sgen-scan-object.h
mono/metadata/socket-io.c
mono/metadata/threadpool.c
mono/metadata/threadpool.h
mono/metadata/threads-types.h
mono/metadata/threads.c
mono/metadata/threads.h
mono/metadata/verify-internals.h
mono/metadata/verify.c
mono/metadata/verify.h
mono/mini/.gitignore
mono/mini/ChangeLog
mono/mini/Makefile.am
mono/mini/aot-compiler.c
mono/mini/aot-runtime.c
mono/mini/arrays.cs
mono/mini/basic-simd.cs
mono/mini/cpu-s390x.md
mono/mini/debugger-agent.c
mono/mini/decompose.c
mono/mini/driver.c
mono/mini/exceptions-amd64.c
mono/mini/exceptions-arm.c
mono/mini/exceptions-s390x.c
mono/mini/generics.cs
mono/mini/genmdesc.c
mono/mini/helpers.c
mono/mini/iltests.il.in
mono/mini/image-writer.c
mono/mini/ir-emit.h
mono/mini/jit-icalls.c
mono/mini/method-to-ir.c
mono/mini/mini-amd64.c
mono/mini/mini-amd64.h
mono/mini/mini-arm.c
mono/mini/mini-exceptions.c
mono/mini/mini-generic-sharing.c
mono/mini/mini-ia64.c
mono/mini/mini-llvm.c
mono/mini/mini-mips.c
mono/mini/mini-posix.c
mono/mini/mini-ppc.c
mono/mini/mini-s390.c
mono/mini/mini-s390x.c
mono/mini/mini-s390x.h
mono/mini/mini-sparc.c
mono/mini/mini-trampolines.c
mono/mini/mini-x86.c
mono/mini/mini-x86.h
mono/mini/mini.c
mono/mini/mini.h
mono/mini/optflags-def.h
mono/mini/simd-intrinsics.c
mono/mini/tramp-s390x.c
mono/mini/tramp-x86.c
mono/monograph/.gitignore
mono/profiler/.gitignore
mono/profiler/ChangeLog
mono/profiler/mono-profiler-iomap.c
mono/tests/.gitignore
mono/tests/ChangeLog
mono/tests/Makefile.am
mono/tests/appdomain-async-invoke.cs
mono/tests/bug-515884.il [new file with mode: 0644]
mono/tests/bug-575941.cs [new file with mode: 0644]
mono/tests/bug-599469.cs [new file with mode: 0644]
mono/tests/dtest.cs
mono/tests/exit-stress-threadpool.cs [new file with mode: 0644]
mono/tests/interlocked-2.2.cs
mono/tests/libtest.c
mono/tests/metadata-verifier/Changelog
mono/tests/metadata-verifier/Makefile
mono/tests/metadata-verifier/cli-tables-tests.md
mono/tests/test-runner.cs
mono/tests/verifier/ChangeLog
mono/tests/verifier/make_cpobj_test.sh
mono/tests/verifier/make_endfilter_test.sh
mono/tests/verifier/make_endfinally_test.sh
mono/tests/verifier/make_stobj_test.sh
mono/tests/verifier/make_store_test.sh
mono/tests/verifier/make_unary_test.sh
mono/tests/verifier/unverifiable_ginst_dont_reduce_to_gparam_with_constraint.il [new file with mode: 0644]
mono/tests/verifier/valid_call_to_virtual_method_on_sealed_class.il [new file with mode: 0644]
mono/tests/verifier/valid_store_of_uint_to_int_array.il [new file with mode: 0644]
mono/tests/verifier/valid_switch_with_value_on_stack.il [new file with mode: 0644]
mono/utils/.gitignore
mono/utils/ChangeLog
mono/utils/Makefile.am
mono/utils/mono-dl.c
mono/utils/mono-ehash.c [deleted file]
mono/utils/mono-hash.c
mono/utils/mono-logger-internal.h
mono/utils/mono-logger.c
mono/utils/mono-proclib.c
mono/utils/mono-semaphore.c
mono/utils/mono-semaphore.h
mono/utils/mono-sigcontext.h
mono/utils/mono-time.c
msvc/ChangeLog
msvc/libmono.vcproj
msvc/mono.def
msvc/monoposixhelper.def
msvc/scripts/genproj.cs
msvc/scripts/monowrap.cs
msvc/win32.xml
msvc05/ChangeLog
msvc05/setup-solution.bat
runtime/Makefile.am
runtime/monodis-wrapper.in
scripts/mono-heapviz
support/ChangeLog
support/dirent.c
support/grp.c
support/macros.c
support/map.h
support/mph.h
support/old-map.c
support/pwd.c
support/signal.c
support/sys-statvfs.c
support/sys-time.c
support/unistd.c
support/zlib-helper.c
tools/locale-builder/README
tools/locale-builder/supp/ChangeLog
tools/locale-builder/supp/da.xml
tools/sgen/sgen-grep-binprot.c

index ee8f329b8e3abf105bdf9b935c61ee37b2d115af..0247f818a69806e0424645864c19c3cff0aedd68 100644 (file)
@@ -1,6 +1,16 @@
 
 The Mono runtime is licensed under the terms of the GNU 
 Library General Public License, version 2.
+
+The eglib directory is licensed under the terms of the MIT
+X11 license and is a drop-in replacement for Mono's use of
+glib 2.0 (which was LGPL).
+
+The Boehm licensing information is in the libgc directory
+
+The SGen Garbage Collector is under the terms of the MIT X11
+license
+
                  
                GNU LIBRARY GENERAL PUBLIC LICENSE
                       Version 2, June 1991
index 5043ae6eaac63f378b094f28dbb2c19f6dab09fb..74e224a6e6087ce07f1cf442352296766ec08a88 100644 (file)
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,175 @@
+2010-04-26  Geoff Norton  <gnorton@novell.com>
+
+       * configure.in: Allow cross compiling osx for 64-bit
+
+2010-04-26  Zoltan Varga  <vargaz@gmail.com>
+
+       * configure.in: Applied patch from Robert Nagy (robert@openbsd.org). Add
+       sys/param.h dependencies to a few checks.
+
+2010-04-25  Mark Probst  <mark.probst@gmail.com>
+
+       * tools/sgen/sgen-grep-binprot.c: Support for major Mark&Sweep
+       collector.
+
+2010-04-20  Jonathan Pryor  <jpryor@novell.com>
+
+       * configure.in: Check for the asm/sigcontext.h header.
+
+2010-04-20  Andrés G. Aragoneses  <andres@lindenlab.com>
+
+       * README: Replace --with-profile2 with --with-profile4.
+
+2010-04-20  Jonathan Pryor  <jpryor@novell.com>
+
+       * configure.in: On OpenBSD, remove duplicate -pthread options in 
+         libmono_ldflags.  Change from Robert Nagy <robert@openbsd.org>.
+
+2010-04-20  Jonathan Pryor  <jpryor@novell.com>
+
+       * configure.in: For Linux hosts, remove libmono_ldflags="-lpthread".
+         It's unnecessary (for !target_win32, pthreads are checked again 
+         later in configure.in), and it breaks Android (which doesn't have
+         libpthread, but DOES have pthreads in libc).
+
+2010-04-19  Jonathan Pryor  <jpryor@novell.com>
+
+       * configure.in: Disable AC_CHECK_LIB() for pthread, as this breaks
+         autoconf on BSD platforms.  (Why?  Who knows -- it's AutoConf!)
+
+2010-04-19  Jonathan Pryor  <jpryor@novell.com>
+
+       * configure.in: Use AC_CHECK_LIB() to check for pthread instead of
+         just blindly linking to -lpthread, as Android includes pthread
+         support within libc and doesn't provide a separate libpthread.
+         Android's <string.h> pulls in <malloc.h> (unlike glibc), resulting
+         in a build error in mono/utils/mono-codeman.c due to 
+         `struct mallinfo` re-declaration.  Define HAVE_USR_INCLUDE_MALLOC_H 
+         if /usr/include/malloc.h is present to avoid this.
+
+2010-04-19  Jonathan Pryor  <jpryor@novell.com>
+
+       * configure.in: Add header, structure member, and function checks as 
+         Android doesn't provide all the headers, structure members, and 
+         functions that a "full" Linux distro includes.
+
+2010-04-19  Zoltan Varga  <vargaz@gmail.com>
+
+       * configure.in: Add a --enable-minimal=normalization option to disable support
+       for string normalization.
+
+2010-04-16  Marek Habersack  <mhabersack@novell.com>
+
+       * configure.in: added a check for sysconf(3)
+
+2010-04-14  Miguel de Icaza  <miguel@novell.com>
+
+       * configure.in: turn the AC_MSG_ERROR into a AC_MSG_WARN since in
+       Andrew's configuration this aborts the build:
+
+        host=i686-pc-linux-gnu != target=i586-suse-linux
+
+       And I no longer remember why I added that error in the first
+       place (we need to determine perhaps the arch/OS but it is
+       difficult with those strings).
+
+2010-04-08  Andreia Gaita  <avidigal@novell.com>
+
+       * configure.in: Add an extra "only" option to --with-moonlight. This
+       will configure mono to only build moonlight-specific stuff and
+       nothing else. --with-moonlight=yes now just adds the moon profile to
+       the build
+
+       * Makefile.am: Add moonlight-specific rules that only build what
+       moon needs. These are called directly from moon, to do fast
+       moon+mono+mcs builds
+
+       * runtime/Makefile.am: Change the build rules to have a moonlight-only
+       build configuration, as well as a normal build that optionally includes
+       it
+
+2010-04-07  Raja R Harinath  <harinath@hurrynot.org>
+
+       * runtime/Makefile.am ($(tmpinst)/bin/dmcs): Add.
+
+2010-04-06  Andreia Gaita  <avidigal@novell.com>
+
+       * configure.in: add --with-mcs-path option to specify where the mcs
+       source can be found, if not on ./mcs or ../mcs.
+       Only touch the mcs and/or olive dirs and config files if we're
+       actually building them
+
+2010-04-05  Zoltan Varga  <vargaz@gmail.com>
+
+       * configure.in: Append -lgc to libmono_ldflags if using an external libgc.
+
+2010-04-04  Andreas Färber  <andreas.faerber@web.de>
+
+       * configure.in: Fix typo.
+       Set default for with_moonlight to fix "Moon Profile:" output.
+
+       Contributed under MIT/X11 license.
+
+2010-04-03  Zoltan Varga  <vargaz@gmail.com>
+
+       * configure.in: Applied some openbsd changes from Robert Nagy
+       <robert@openbsd.org>.
+
+2010-04-03  Marek Habersack  <mhabersack@novell.com>
+
+       * configure.in: TARGET_WIN32 and MINGW_CROSS_COMPILE are defined
+       when cross-compiling with MinGW 
+
+       * build-mingw32.sh: include the 4.0 profile in the zip.
+       Remove cross-compilation environment bin path from PATH before
+       compiling native Mono.
+       Remove autotools cache directory before each compilation phase.
+
+2010-04-02  Marek Habersack  <mhabersack@novell.com>
+
+       * configure.in: include -lkernel32 in LDFLAGS when cross-compiling
+       with MINGW or compiling on Cygwin.
+
+       * build-mingw32.sh: some changes to make the compilation work
+       better on non-SuSE systems.
+
+2010-04-01  Mark Probst  <mark.probst@gmail.com>
+
+       * scripts/mono-heapviz: Process and output detailed pinning
+       statistics.
+
+2010-03-29  Andreas Färber  <andreas.faerber@web.de>
+
+       * configure.in: Add support for Haiku
+
+       Contributed under MIT/X11 license.
+
+2010-03-26  Zoltan Varga  <vargaz@gmail.com>
+
+       * configure.in: Add a --enable-system-aot option to control the generation of
+       AOT images during the build.
+
+2010-03-26  Zoltan Varga  <vargaz@gmail.com>
+
+       * configure.in: Apply some openbsd changes from openbsd ports.
+
+2010-03-23  Neale Ferguson <neale@sinenomine.net>
+
+       * configure.in: Change ACCESS_UNALINGED to "yes" for s390/s390x.
+
+2010-03-22  Andreia Gaita  <avidigal@gmail.com>
+
+       * configure.in: fix build when doing with-mcs-docs=no on a clean tree
+
+2010-03-19  Zoltan Varga  <vargaz@gmail.com>
+
+       * autogen.sh: Pass -Wno-portability to automake to quiet some warnings.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * runtime/Makefile.am, build-mingw32.sh: rename
+       the net_2_1 profile to moonlight.
+
 2010-03-10  Andrew Jorgensen  <ajorgensen@novell.com>
 
        * configure.in: configure eglib even when we are not building
diff --git a/LICENSE b/LICENSE
index 6177891cdc035bb2b2117d298155ff7394fe2937..e9655394176bfd6b807e12637877b17526b573f5 100644 (file)
--- a/LICENSE
+++ b/LICENSE
@@ -54,6 +54,13 @@ For comments, corrections and updates, please contact mono@novell.com
        the terms of the MIT X11, this means that this code can be
        used for any purposes by anyone.
 
+** mono/metadata/sgen*: Mono's Copying Collector
+
+       This new garbage collector is licensed under the terms of
+       the MIT X11 license, in hopes that the GC could be reused
+       by third party projects, follows the same spirit than the
+       Boehm GC.
+
 ** mcs/mcs, mcs/gmcs
 
        The C# Compilers (1.0 and 2.0)
index 93fcdee32cb75847cb29285bee7670477a4a5790..17c95137b57ed367f4652afa7f9b88487bb4e439 100644 (file)
@@ -1,14 +1,16 @@
 AUTOMAKE_OPTIONS = foreign
 ACLOCAL_AMFLAGS = -I .
 
+MOONLIGHT_SUBDIRS =    $(libgc_dir) $(eglib_dir) mono $(ikvm_native_dir)         data
+
 if CROSS_COMPILING
 SUBDIRS = po $(libgc_dir) $(eglib_dir) mono $(ikvm_native_dir) data runtime scripts man samples web msvc $(docs_dir)
 # Keep in sync with SUBDIRS
 ## 'tools' is not normally built
 DIST_SUBDIRS = po libgc eglib mono ikvm-native         data runtime scripts man samples web tools msvc docs
 else
-if MOONLIGHT
-SUBDIRS =    $(libgc_dir) $(eglib_dir) mono $(ikvm_native_dir)         data runtime
+if ONLY_MOONLIGHT
+SUBDIRS = $(MOONLIGHT_SUBDIRS) runtime
 else
 SUBDIRS = po $(libgc_dir) $(eglib_dir) mono $(ikvm_native_dir) support data runtime scripts man samples web msvc $(docs_dir)
 # Keep in sync with SUBDIRS
@@ -30,12 +32,11 @@ pkgconfigdir = $(libdir)/pkgconfig
 noinst_DATA = mono-uninstalled.pc
 DISTCLEANFILES= mono-uninstalled.pc
 
-.PHONY: get-monolite-latest mcs-do-compiler-tests compiler-tests bootstrap-world
-
 # building with monolite
 mcslib = $(mcs_topdir)/class/lib
 monolite = $(mcslib)/monolite
 monolite_url = http://mono.ximian.com/daily/monolite-latest.tar.gz
+.PHONY: get-monolite-latest 
 get-monolite-latest:
        -rm -fr $(mcslib)/monolite-*
        -mkdir -p $(mcslib)
@@ -44,43 +45,44 @@ get-monolite-latest:
        cd $(mcslib) && { (wget -O- $(monolite_url) || curl $(monolite_url)) | gzip -d | tar xf - ; }
        cd $(mcslib) && mv -f monolite-* monolite
 
-compiler-tests: build-test-mono-mcs-moon
-
-compiler-tests-net_2_0:
-       -rm -f $(mcs_topdir)/build/common/Consts.cs.save
-       -mv -f $(mcs_topdir)/build/common/Consts.cs $(mcs_topdir)/build/common/Consts.cs.save
-       cd $(mcs_topdir) && $(MAKE) PROFILE=net_2_0_bootstrap clean
-       cd $(mcs_topdir) && $(MAKE) PROFILE=net_2_0 clean
-       -mv -f $(mcs_topdir)/build/common/Consts.cs.save $(mcs_topdir)/build/common/Consts.cs
-       $(MAKE) all
-       $(MAKE) test_profiles=net_2_0 mcs-do-compiler-tests
-
-bootstrap-world: compiler-tests
-       $(MAKE) install
-
-bootstrap-world-net_2_0: compiler-tests-net_2_0
-       $(MAKE) install
-
-# internal targets
-.PHONY: build-test-mono-mcs-moon
-build-test-mono-mcs-moon: do-build-moon-maybe
-       $(MAKE) mcs-do-compiler-tests
-
-.PHONY: do-build-mono-mcs
+.PHONY: validate do-build-mono-mcs mcs-do-clean mcs-do-tests
+validate: do-build-mono-mcs
+       $(MAKE) mcs-do-tests
 do-build-mono-mcs: mcs-do-clean
        $(MAKE) all
-
-.PHONY: do-build-moon-maybe
-do-build-moon-maybe: do-build-mono-mcs
-       cd runtime && $(MAKE) moon-do-build
-
 mcs-do-clean:
        cd runtime && $(MAKE) clean-local
        cd mono/tests && $(MAKE) clean
-mcs-do-compiler-tests:
-       cd runtime && $(MAKE) test_select='TEST_SUBDIRS="tests errors"' check-local
+mcs-do-tests:
+       cd runtime && $(MAKE) check-local
        cd mono/tests && $(MAKE) check
 
+.PHONY: compiler-tests mcs-do-compiler-tests
+compiler-tests:
+       $(MAKE) test_select='TEST_SUBDIRS="tests errors"' validate
+mcs-do-compiler-tests:
+       $(MAKE) test_select='TEST_SUBDIRS="tests errors"' mcs-do-tests
+
+.PHONY: bootstrap-world
+bootstrap-world: compiler-tests
+       $(MAKE) install
+
+if MOONLIGHT
+moon-do-build: config.h
+       @list='$(MOONLIGHT_SUBDIRS)'; for subdir in $$list; do \
+         echo "Making all in $$subdir"; \
+         (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) all); \
+        done;
+       cd $(mcs_topdir) && NO_DIR_CHECK=1 $(MAKE) PROFILE=moonlight_raw all
+
+moon-do-clean:
+       @list='$(MOONLIGHT_SUBDIRS)'; for subdir in $$list; do \
+         echo "Making clean in $$subdir"; \
+         (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) clean); \
+        done;
+       cd $(mcs_topdir) && NO_DIR_CHECK=1 $(MAKE) PROFILE=moonlight_raw clean
+endif
+
 win32getdeps:
        wget http://www.go-mono.com/archive/pkgconfig-0.11-20020310.zip
        wget http://www.go-mono.com/archive/glib-2.0.4-20020703.zip 
@@ -98,10 +100,6 @@ win32getdeps:
 win32setup:
        makensis /DMILESTONE=$(VERSION) /DSOURCE_INSTALL_DIR=$(SOURCE_INSTALL_DIR) /DBUILDNUM=$(BUILDNUM) monowiz.win32.nsi
 
-bootstrap: all
-       @echo "*** 'make bootstrap' is obsolete.  Just run 'make' to perform a combined mono+mcs build"
-       exit 1
-
 patch-quiet:
        find mono -name Makefile -exec scripts/patch-quiet.sh {} \;
        find libgc -name Makefile -exec scripts/patch-quiet.sh {} \;
diff --git a/README b/README
index 9115a43498372bbca7ab879e8f117f623c57388c..abb0314418806d7682a0784db26f217583822888 100644 (file)
--- a/README
+++ b/README
@@ -278,10 +278,10 @@ This is Mono.
 
                This defaults to `yes'.
 
-       --with-profile2=yes,no
+       --with-profile4=yes,no
 
-               Whether you want to build the 2.x libraries (support
-               for Generics and the 2.0/3.5 APIS).
+               Whether you want to build the 4.x profile libraries
+               and runtime.
 
                It defaults to `yes'.
 
index eba9274a8fab2ef2c9978ff6bed561f3dabd7ebb..898b2d80beb5bda8afb2db16c0bffe3cf0cbe86d 100755 (executable)
@@ -119,7 +119,7 @@ if grep "^AM_CONFIG_HEADER" configure.in >/dev/null; then
 fi
 
 echo "Running automake --gnu $am_opt ..."
-automake --add-missing --gnu $am_opt ||
+automake --add-missing --gnu -Wno-portability $am_opt ||
   { echo "**Error**: automake failed."; exit 1; }
 echo "Running autoconf ..."
 autoconf || { echo "**Error**: autoconf failed."; exit 1; }
index 200c5fa71881a68495dc6f40f7a7427701ff7c18..16b91cefe6d4cea4eb05cd682b534a9dd132dd07 100755 (executable)
@@ -1,19 +1,32 @@
 #!/bin/bash -e
 CURDIR="`pwd`"
-CROSS_DIR=${1:-/opt/cross/}
-MINGW=${1:-i386-mingw32msvc}
-CROSS_BIN_DIR="$CROSS_DIR/bin"
-CROSS_DLL_DIR="$CROSS_DIR/$MINGW/bin"
-CROSS_PKG_CONFIG_DIR=$CROSS_DIR/$MINGW/lib/pkgconfig
+MINGW=i386-mingw32msvc
+CROSS_DIR=/opt/cross/$MINGW
 COPY_DLLS="libgio*.dll libglib*.dll libgmodule*.dll libgthread*.dll libgobject*.dll"
-PATH=$CROSS_BIN_DIR:$PATH
 INSTALL_DESTDIR="$CURDIR/mono-win32"
-PROFILES="default net_2_0 net_2_1 net_3_5"
+PROFILES="default net_2_0 net_3_5 net_4_0 moonlight"
+TEMPORARY_PKG_CONFIG_DIR=/tmp/$RANDOM-pkg-config-$RANDOM
+ORIGINAL_PATH="$PATH"
 
-export PATH
+export CPPFLAGS_FOR_EGLIB CFLAGS_FOR_EGLIB CPPFLAGS_FOR_LIBGC CFLAGS_FOR_LIBGC
+
+function cleanup ()
+{
+    if [ -d "$TEMPORARY_PKG_CONFIG_DIR" ]; then
+       rm -rf "$TEMPORARY_PKG_CONFIG_DIR"
+    fi
+}
 
 function setup ()
 {
+    local pcname
+
+    CROSS_BIN_DIR="$CROSS_DIR/bin"
+    CROSS_DLL_DIR="$CROSS_DIR/bin"
+    CROSS_PKG_CONFIG_DIR=$CROSS_DIR/lib/pkgconfig
+    PATH=$CROSS_BIN_DIR:$PATH
+
+    export PATH
     if [ -d ./.git/svn ]; then
        SVN_INFO='git svn info'
     elif [ -d ./.svn ]; then
@@ -37,6 +50,15 @@ function setup ()
     NOCONFIGURE=yes
     export NOCONFIGURE
 
+    if [ -d "$CROSS_PKG_CONFIG_DIR" ]; then
+       install -d -m 755 "$TEMPORARY_PKG_CONFIG_DIR"
+       for pc in "$CROSS_PKG_CONFIG_DIR"/*.pc; do
+           pcname="`basename $pc`"
+           sed -e "s;^prefix=.*;prefix=$CROSS_DIR;g" < $pc > "$TEMPORARY_PKG_CONFIG_DIR"/$pcname
+       done
+       CROSS_PKG_CONFIG_DIR="$TEMPORARY_PKG_CONFIG_DIR"
+    fi
+
     echo Mono Win32 installation prefix: $MONO_PREFIX
 }
 
@@ -44,8 +66,11 @@ function build ()
 {
     ./autogen.sh 
 
+    BUILD="`./config.guess`"
+
     if [ -f ./Makefile ]; then
        make distclean
+       rm -rf autom4te.cache
     fi
 
     if [ ! -d "$CURDIR/build-cross-windows" ]; then
@@ -54,13 +79,18 @@ function build ()
 
     cd "$CURDIR/build-cross-windows"
     rm -rf *
-    ../configure --prefix=$MONO_PREFIX --with-crosspkgdir=$CROSS_PKG_CONFIG_DIR --target=$MINGW --host=$MINGW --enable-parallel-mark --program-transform-name=""
+    ../configure --prefix=$MONO_PREFIX --with-crosspkgdir=$CROSS_PKG_CONFIG_DIR --build=$BUILD --target=$MINGW --host=$MINGW --enable-parallel-mark --program-transform-name="" --with-tls=none --disable-mcs-build --disable-embed-check --enable-win32-dllmain=yes --with-libgc-threads=win32 --with-profile4=yes
     make
     cd "$CURDIR"
 
     if [ ! -d "$CURDIR/build-cross-windows-mcs" ]; then
        mkdir "$CURDIR/build-cross-windows-mcs"
     fi
+
+    rm -rf autom4te.cache
+    unset PATH
+    PATH="$ORIGINAL_PATH"
+    export PATH
     cd "$CURDIR/build-cross-windows-mcs"
     rm -rf *
     ../configure --prefix=$MONO_PREFIX --enable-parallel-mark
@@ -101,8 +131,32 @@ function doinstall ()
 
 }
 
+function usage ()
+{
+    cat <<EOF
+Usage: build-mingw32.sh [OPTIONS]
+
+where OPTIONS are:
+
+ -d DIR     Sets the location of directory where MINGW is installed [$CROSS_DIR]
+ -m MINGW   Sets the MINGW target name to be passed to configure [$MINGW]
+EOF
+
+    exit 1
+}
+
+trap cleanup 0
+
 pushd . > /dev/null
 
+while getopts "d:m:h" opt; do
+    case "$opt" in
+       d) CROSS_DIR="$OPTARG" ;;
+       m) MINGW="$OPTARG" ;;
+       *) usage ;;
+    esac
+done
+
 setup
 build
 doinstall
index 723850e1c7656cf627f64cb066a161c5f2052cae..acca772bfd7589ae64166a5679f39acfa5b9bbe3 100644 (file)
@@ -77,7 +77,7 @@ esac
 host_win32=no
 target_win32=no
 case "$host" in
-       *-*-mingw*|*-*-cygwin*)
+       *-mingw*|*-*-cygwin*)
                AC_DEFINE(HOST_WIN32,1,[Host Platform is Win32])
                AC_DEFINE(DISABLE_PORTABILITY,1,[Disable the io-portability layer])
                AC_DEFINE(PLATFORM_NO_SYMLINKS,1,[This platform does not support symlinks])
@@ -92,11 +92,15 @@ case "$host" in
                        # So libgc configure gets -mno-cygwin
                        export CC
                        export CXX
+               else
+                       target_win32=yes
+                       AC_DEFINE(TARGET_WIN32,1,[Target OS is Win32/MinGW])
+                       AC_DEFINE(MINGW_CROSS_COMPILE,1,[Cross-compiling using MinGW])
                fi
                HOST_CC="gcc"
                # Windows 2000 is required that includes Internet Explorer 5.01
                CPPFLAGS="$CPPFLAGS -DWINVER=0x0500 -D_WIN32_WINNT=0x0500 -D_WIN32_IE=0x0501 -D_UNICODE -DUNICODE -DWIN32_THREADS -DFD_SETSIZE=1024"
-               LDFLAGS="$LDFLAGS -lmswsock -lws2_32 -lole32 -loleaut32 -lpsapi -lversion -ladvapi32 -lwinmm"
+               LDFLAGS="$LDFLAGS -lmswsock -lws2_32 -lole32 -loleaut32 -lpsapi -lversion -ladvapi32 -lwinmm -lkernel32"
                libmono_cflags="-mno-cygwin -mms-bitfields -mwindows"
                libmono_ldflags="-mno-cygwin -mms-bitfields -mwindows"
                libdl=
@@ -151,14 +155,18 @@ case "$host" in
                ;;
        *-*-*openbsd*)
                host_win32=no
-               CPPFLAGS="$CPPFLAGS -D_THREAD_SAFE -DGC_FREEBSD_THREADS -DPLATFORM_BSD"
-               libmono_cflags="-D_THREAD_SAFE"
+               CPPFLAGS="$CPPFLAGS -D_THREAD_SAFE -DGC_OPENBSD_THREADS -DPLATFORM_BSD -D_GNU_SOURCE -D_REENTRANT -DUSE_MMAP"
+               if test "x$disable_munmap" != "xyes"; then
+               CPPFLAGS="$CPPFLAGS -DUSE_MUNMAP"
+               fi
+               libmono_cflags="-D_THREAD_SAFE -D_REENTRANT"
                LDFLAGS="$LDFLAGS -pthread"
-               libmono_ldflags="-pthread"
                need_link_unlink=yes
                AC_DEFINE(PTHREAD_POINTER_ID)
                libdl=
+               gc_default=boehm
                libgc_threads=pthreads
+               with_sigaltstack=no
                use_sigposix=yes
                ;;
        *-*-linux*)
@@ -168,7 +176,6 @@ case "$host" in
                        CPPFLAGS="$CPPFLAGS -DUSE_MUNMAP"
                fi
                libmono_cflags="-D_REENTRANT"
-               libmono_ldflags="-lpthread"
                libdl="-ldl"
                libgc_threads=pthreads
                AOT_SUPPORTED="yes"
@@ -228,18 +235,6 @@ case "$host" in
                dnl its gcc defaults to 64-bit mode.  They have also deprecated the usage of ucontext
                dnl we need to set some flags to build our 32-bit binaries on 10.6 properly
                case "$host" in
-                       dnl MacPorts config.guess reports as this
-                       x86_64-*-darwin10*)
-                               BROKEN_DARWIN_FLAGS="-arch i386 -D_XOPEN_SOURCE -mmacosx-version-min=10.5"
-                               CPPFLAGS="$CPPFLAGS $BROKEN_DARWIN_FLAGS"
-                               CFLAGS="$CFLAGS $BROKEN_DARWIN_FLAGS"
-                               CXXFLAGS="$CXXFLAGS $BROKEN_DARWIN_FLAGS"
-                               CCASFLAGS="$CCASFLAGS $BROKEN_DARWIN_FLAGS"
-                               CPPFLAGS_FOR_LIBGC="$CPPFLAGS_FOR_LIBGC $BROKEN_DARWIN_FLAGS"
-                               CFLAGS_FOR_LIBGC="$CFLAGS_FOR_LIBGC $BROKEN_DARWIN_FLAGS"
-                               CPPFLAGS_FOR_EGLIB="$CPPFLAGS_FOR_EGLIB $BROKEN_DARWIN_FLAGS"
-                               CFLAGS_FOR_EGLIB="$CFLAGS_FOR_EGLIB $BROKEN_DARWIN_FLAGS"
-                               ;;
                        dnl Snow Leopard config.guess reports as this
                        i*86-*-darwin10*)
                                BROKEN_DARWIN_FLAGS="-arch i386 -D_XOPEN_SOURCE -mmacosx-version-min=10.5"
@@ -254,6 +249,17 @@ case "$host" in
                                ;;
                esac
                ;;
+       *-*-haiku*)
+               host_win32=no
+               CPPFLAGS="$CPPFLAGS -D_REENTRANT -D_THREAD_SAFE"
+               libmono_cflags="-D_REENTRANT -D_THREAD_SAFE"
+               libdl=
+               LIBS="$LIBS -lnetwork"
+               need_link_unlink=yes
+               AC_DEFINE(PTHREAD_POINTER_ID)
+               libgc_threads=pthreads
+               use_sigposix=yes
+               ;;
        *)
                AC_MSG_WARN([*** Please add $host to configure.in checks!])
                host_win32=no
@@ -344,8 +350,14 @@ fi
 AM_CONDITIONAL(NO_VERSION_SCRIPT, test x$no_version_script = xyes)
 
 AC_CHECK_HEADERS(sys/filio.h sys/sockio.h netdb.h utime.h sys/utime.h semaphore.h sys/un.h linux/rtc.h sys/syscall.h sys/mkdev.h sys/uio.h)
-AC_CHECK_HEADERS(sys/user.h sys/socket.h sys/ipc.h sys/sem.h sys/utsname.h alloca.h ucontext.h pwd.h sys/select.h netinet/tcp.h netinet/in.h unistd.h sys/types.h link.h)
+AC_CHECK_HEADERS(sys/param.h sys/socket.h sys/ipc.h sys/sem.h sys/utsname.h alloca.h ucontext.h pwd.h sys/select.h netinet/tcp.h netinet/in.h unistd.h sys/types.h link.h asm/sigcontext.h)
 
+AC_CHECK_HEADERS(sys/user.h, [], [],
+[
+#ifdef HAVE_SYS_PARAM_H
+# include <sys/param.h>
+#endif
+])
 
 AC_CHECK_HEADER(zlib.h, [have_zlib=yes], [have_zlib=no])
 if test x$have_zlib = xyes; then
@@ -433,6 +445,12 @@ else
   mcsdir=../mcs
 fi
 
+AC_ARG_WITH(mcs-path, [  --with-mcs-path=/path/to/mcs      Specify an alternate mcs source tree],
+       if test x$with_mcs_path != "x" -a -d $with_mcs_path ; then
+               mcsdir=$with_mcs_path
+       fi
+)
+
 #
 # A sanity check to catch cases where the package was unpacked
 # with an ancient tar program (Solaris)
@@ -443,7 +461,7 @@ AC_ARG_ENABLE(solaris-tar-check,
 
 if test x"$do_solaris_tar_check" = xyes -a x"$enable_solaris_tar_check" = xyes; then
        AC_MSG_CHECKING(integrity of package)
-       if test -f $srcdir/$mcsdir/class/System.Runtime.Serialization.Formatters.Soap/System.Runtime.Serialization.Formatters.Soap/SoapTypeMapper.cs
+       if test -f $mcsdir/class/System.Runtime.Serialization.Formatters.Soap/System.Runtime.Serialization.Formatters.Soap/SoapTypeMapper.cs
        then
                AC_MSG_RESULT(ok)
        else
@@ -452,8 +470,13 @@ if test x"$do_solaris_tar_check" = xyes -a x"$enable_solaris_tar_check" = xyes;
        fi
 fi
 
-mcs_topdir='$(top_srcdir)/'$mcsdir
-mcs_topdir_from_srcdir='$(top_builddir)/'$mcsdir
+if test "x$with_mcs_path" != "x"; then
+mcs_topdir=$(cd "$mcsdir" && pwd)
+mcs_topdir_from_srcdir=$mcs_topdir
+else
+mcs_topdir=$(cd "$srcdir/$mcsdir" && pwd)
+mcs_topdir_from_srcdir='$(top_builddir)'/$mcsdir
+fi
 
 ## Maybe should also disable if mcsdir is invalid.  Let's punt the issue for now.
 AM_CONDITIONAL(BUILD_MCS, [test x$cross_compiling = xno && test x$enable_mcs_build != xno])
@@ -496,8 +519,8 @@ yes|sibling) libgdiplus_loc=`cd ../libgdiplus && pwd`/src/libgdiplus.la ;;
 esac
 AC_SUBST([libgdiplus_loc])
 
-AC_PATH_PROG(PKG_CONFIG, pkg-config, no)
-if test "x$PKG_CONFIG" = "xno"; then
+PKG_PROG_PKG_CONFIG()
+if test "x$PKG_CONFIG" = "x"; then
        AC_MSG_ERROR([You need to install pkg-config])
 fi
 
@@ -534,16 +557,10 @@ embedded)
   eglib_dir=eglib
   ;;
 system)
-  if test "x$cross_compiling" = "xyes"; then
-    pkg_config_path="$PKG_CONFIG_PATH"
-    unset PKG_CONFIG_PATH
-  fi
+    echo "PKG_CONFIG_PATH=$PKG_CONFIG_PATH"
+    echo "cross_compiling=$cross_compiling"
   BUILD_GLIB_CFLAGS=`$PKG_CONFIG --cflags glib-2.0 gthread-2.0`
   BUILD_GLIB_LIBS=`$PKG_CONFIG --libs glib-2.0 gthread-2.0`
-  if test "x$cross_compiling" = "xyes"; then
-    PKG_CONFIG_PATH=$pkg_config_path
-    export PKG_CONFIG_PATH
-  fi
   
   ## Versions of dependencies
   GLIB_REQUIRED_VERSION=2.4.0
@@ -644,11 +661,17 @@ if test x$enable_small_config = xyes; then
        CFLAGS_FOR_LIBGC="$CFLAGS_FOR_LIBGC -DSMALL_CONFIG"
 fi
 
+if test x$AOT_SUPPORTED != xyes; then
+   AOT_SUPPORTED=no
+fi
+
+AC_ARG_ENABLE(system-aot, [  --enable-system-aot  Enable the Ahead-Of-Time compilation of system assemblies during the build (on by default on some platforms)], enable_system_aot=$enableval, enable_system_aot=$AOT_SUPPORTED)
+
 DISABLED_FEATURES=none
 
 AC_ARG_ENABLE(minimal, [  --enable-minimal=LIST      drop support for LIST subsystems.
      LIST is a comma-separated list from: aot, profiler, decimal, pinvoke, debug,
-     reflection_emit, reflection_emit_save, large_code, logging, com, ssa, generics, attach, jit, simd,soft_debug.],
+     reflection_emit, reflection_emit_save, large_code, logging, com, ssa, generics, attach, jit, simd, soft_debug, normalization.],
 [
        for feature in `echo "$enable_minimal" | sed -e "s/,/ /g"`; do
                eval "mono_feature_disable_$feature='yes'"
@@ -763,6 +786,11 @@ if test "x$mono_feature_disable_soft_debug" = "xyes"; then
        AC_MSG_NOTICE([Disabled Soft Debugger.])
 fi
 
+if test "x$mono_feature_disable_normalization" = "xyes"; then
+       AC_DEFINE(DISABLE_NORMALIZATION, 1, [Disable String normalization support.])
+       AC_MSG_NOTICE([Disabled String normalization support.])
+fi
+
 AC_MSG_CHECKING(for visibility __attribute__)
 AC_TRY_COMPILE([], [
    void __attribute__ ((visibility ("hidden"))) doit (void) {}
@@ -814,6 +842,7 @@ case "x$gc" in
                AC_SUBST(HAVE_BOEHM_GC)
                LIBGC_LIBS="-lgc $libdl"
                LIBGC_STATIC_LIBS="$LIBGC_LIBS"
+               libmono_ldflags="$libmono_ldflags -lgc"
 
                # AC_CHECK_FUNCS does not work for some reason...
                AC_CHECK_LIB(gc, GC_gcj_malloc, found_gcj_malloc="yes",,$libdl)
@@ -978,6 +1007,7 @@ if test x$target_win32 = xno; then
        AC_CHECK_FUNCS(getpriority)
        AC_CHECK_FUNCS(setpriority)
        AC_CHECK_FUNCS(dl_iterate_phdr)
+       AC_CHECK_FUNCS(sysconf)
 
        AC_CHECK_FUNCS(sched_setaffinity)
 
@@ -1279,6 +1309,9 @@ if test x$target_win32 = xno; then
                *-*-*freebsd*)
                        AC_CHECK_LIB(pthread, main, LIBS="$LIBS -pthread")
                ;;
+               *-*-*openbsd*)
+                       AC_CHECK_LIB(pthread, main, LIBS="$LIBS -pthread")
+               ;;
                *)
                        AC_CHECK_LIB(pthread, main, LIBS="$LIBS -lpthread")
                ;;
@@ -1539,7 +1572,15 @@ if test x$target_win32 = xno; then
        dnl *** Checks for SIOCGIFCONF ***
        dnl ******************************
        AC_CHECK_HEADERS(sys/ioctl.h)
-       AC_CHECK_HEADERS(net/if.h)
+       AC_CHECK_HEADERS(net/if.h, [], [],
+          [
+          #ifdef HAVE_SYS_TYPES_H
+          # include <sys/types.h>
+          #endif
+          #ifdef HAVE_SYS_SOCKET_H
+          # include <sys/socket.h>
+          #endif
+          ])
        AC_MSG_CHECKING(for ifreq)
        AC_TRY_COMPILE([
                #include <stdio.h>
@@ -1592,6 +1633,7 @@ if test x$target_win32 = xno; then
        dnl *** Checks for MonoPosixHelper ***
        dnl **********************************
        AC_CHECK_HEADERS(checklist.h)
+       AC_CHECK_HEADERS(pathconf.h)
        AC_CHECK_HEADERS(fstab.h)
        AC_CHECK_HEADERS(attr/xattr.h)
        AC_CHECK_HEADERS(sys/extattr.h)
@@ -1602,14 +1644,22 @@ if test x$target_win32 = xno; then
        AC_CHECK_HEADERS(sys/xattr.h)
        AC_CHECK_HEADERS(sys/mman.h)
        AC_CHECK_HEADERS(sys/param.h)
+       AC_CHECK_HEADERS(sys/mount.h, [], [],
+               [
+               #ifdef HAVE_SYS_PARAM_H
+               # include <sys/param.h>
+               #endif
+               ])
        AC_CHECK_HEADERS(sys/mount.h)
+       AC_CHECK_FUNCS(confstr)
+       AC_CHECK_FUNCS(seekdir telldir)
        AC_CHECK_FUNCS(getdomainname)
        AC_CHECK_FUNCS(setdomainname)
-       AC_CHECK_FUNCS(fgetgrent)
-       AC_CHECK_FUNCS(fgetpwent)
-       AC_CHECK_FUNCS(fgetpwent)
+       AC_CHECK_FUNCS(endgrent getgrent fgetgrent setgrent)
+       AC_CHECK_FUNCS(setgroups)
+       AC_CHECK_FUNCS(endpwent getpwent fgetpwent setpwent)
        AC_CHECK_FUNCS(getfsstat)
-       AC_CHECK_FUNCS(lutimes)
+       AC_CHECK_FUNCS(lutimes futimes)
        AC_CHECK_FUNCS(mremap)
        AC_CHECK_FUNCS(remap_file_pages)
        AC_CHECK_FUNCS(posix_fadvise)
@@ -1617,7 +1667,8 @@ if test x$target_win32 = xno; then
        AC_CHECK_FUNCS(posix_madvise)
        AC_CHECK_FUNCS(vsnprintf)
        AC_CHECK_FUNCS(sendfile)
-       AC_CHECK_FUNCS(sethostid)
+       AC_CHECK_FUNCS(gethostid sethostid)
+       AC_CHECK_FUNCS(sethostname)
        AC_CHECK_FUNCS(statfs)
        AC_CHECK_FUNCS(fstatfs)
        AC_CHECK_FUNCS(statvfs)
@@ -1625,6 +1676,11 @@ if test x$target_win32 = xno; then
        AC_CHECK_FUNCS(stime)
        AC_CHECK_FUNCS(strerror_r)
        AC_CHECK_FUNCS(ttyname_r)
+       AC_CHECK_FUNCS(psignal)
+       AC_CHECK_FUNCS(getlogin_r)
+       AC_CHECK_FUNCS(lockf)
+       AC_CHECK_FUNCS(swab)
+       AC_CHECK_FUNCS(setusershell endusershell)
        AC_CHECK_SIZEOF(size_t)
        AC_CHECK_TYPES([blksize_t], [AC_DEFINE(HAVE_BLKSIZE_T)], , 
                [#include <sys/types.h>
@@ -1660,6 +1716,14 @@ if test x$target_win32 = xno; then
                [struct dirent.d_off, struct dirent.d_reclen, struct dirent.d_type],,, 
                [#include <sys/types.h>
                 #include <dirent.h>])
+       AC_CHECK_MEMBERS(
+               [struct passwd.pw_gecos],,, 
+               [#include <sys/types.h>
+                #include <pwd.h>])
+       AC_CHECK_MEMBERS(
+               [struct statfs.f_flags],,, 
+               [#include <sys/types.h>
+                #include <sys/vfs.h>])
 
        dnl Favour xattr through glibc, but use libattr if we have to
        AC_CHECK_FUNC(lsetxattr, ,
@@ -1671,6 +1735,7 @@ if test x$target_win32 = xno; then
        AC_CHECK_MEMBERS(
                [struct kinfo_proc.kp_proc],,, 
                [#include <sys/types.h>
+                #include <sys/param.h>
                 #include <sys/sysctl.h>
                 #include <sys/proc.h>
                 ])
@@ -1751,7 +1816,7 @@ ac_cv_c_socklen_t=yes
        AC_MSG_RESULT(no)
 ])
 
-AC_MSG_CHECKING(for array element initalizer support)
+AC_MSG_CHECKING(for array element initializer support)
 AC_TRY_COMPILE([#include <sys/socket.h>], [
        const int array[] = {[1] = 2,};
 ], [
@@ -1799,7 +1864,7 @@ case "{$target}" in
 
 dnl Win32 does not have /dev/random, they have their own method...
 
-    *-*-mingw*|*-*-cygwin*)
+    *-mingw*|*-*-cygwin*)
     ac_cv_have_dev_random=no
     ;;
 
@@ -2041,6 +2106,10 @@ case "$host" in
                        ;;
                  cygwin*)
                        have_visibility_hidden=no                 
+                       ;;
+                 haiku*)
+                       LIBC=libroot.so
+                       ;;
                esac
                ;;
        x86_64-*-* | amd64-*-*)
@@ -2097,7 +2166,7 @@ case "$host" in
                        INTL="libc.so.6.1"
                esac
               ;;
-       *-*-mingw*|*-*-cygwin*)
+       *-mingw*|*-*-cygwin*)
                # When this is enabled, it leads to very strange crashes at runtime (gcc-3.4.4)
                have_visibility_hidden=no
                INTL="intl"
@@ -2149,7 +2218,7 @@ case "$host" in
        s390-*-linux*)
                TARGET=S390;
                arch_target=s390;
-               ACCESS_UNALIGNED="no"
+               ACCESS_UNALIGNED="yes"
                JIT_SUPPORTED=yes
                jit_wanted=true
                # Required CFLAGS for s390[x].  USE_STRING_INLINES is automatic with gcc 4.1
@@ -2158,7 +2227,7 @@ case "$host" in
        s390x-*-linux*)
                TARGET=S390x;
                arch_target=s390x;
-               ACCESS_UNALIGNED="no"
+               ACCESS_UNALIGNED="yes"
                JIT_SUPPORTED=yes
                jit_wanted=true
                CFLAGS="$CFLAGS -mbackchain -D__USE_STRING_INLINES"
@@ -2191,7 +2260,7 @@ if test "x$host" != "x$target"; then
                target_byte_order=G_BIG_ENDIAN
                ;;
        *)
-               AC_MSG_ERROR([Cross compiling is only supported for targets matching 'powerpc64-{ps3,xbox360}-linux-gnu'])
+               AC_MSG_WARN([Cross compiling is only supported for targets matching 'powerpc64-{ps3,xbox360}-linux-gnu'])
        esac
 fi
 
@@ -2454,21 +2523,28 @@ AC_ARG_WITH(mcs_docs,[  --with-mcs-docs=yes,no         If you want to build the
        fi
 ])
 
-MOONLIGHT=no
-AC_ARG_WITH(moonlight, [  --with-moonlight=yes,no         If you want to build Mono for Moonlight (defaults to no - the resulting mono build is useless for anything but moonlight)],[
-       if test x$with_moonlight = xyes; then
-               MOONLIGHT=yes
+AC_ARG_WITH(moonlight, [  --with-moonlight=yes|no|only         If you want to build Mono for Moonlight (defaults to no)],[
+       if test "x$with_moonlight" = "xyes"; then
+               AC_DEFINE(MOONLIGHT,1,[Building for Moonlight])
+       elif test "x$with_moonlight" = "xonly"; then
                AC_DEFINE(MOONLIGHT,1,[Building for Moonlight])
        fi
-])
+], [with_moonlight=no])
 
 
 
+AC_CHECK_HEADER([malloc.h], 
+               [AC_DEFINE([HAVE_USR_INCLUDE_MALLOC_H], [1], 
+                       [Define to 1 if you have /usr/include/malloc.h.])],,)
+
 dnl
 dnl Consistency settings
 dnl
 if test x$cross_compiling = xyes -o x$enable_mcs_build = xno; then
    DISABLE_MCS_DOCS=yes
+fi
+
+if test x$DISABLE_MCS_DOCS = xyes; then
    docs_dir=""
 else
    docs_dir=docs
@@ -2481,7 +2557,8 @@ AC_SUBST(OPROFILE_LIBS)
 
 libmono_ldflags="$libmono_ldflags $LIBS"
 
-AM_CONDITIONAL(MOONLIGHT, [test "x$with_moonlight" = xyes])
+AM_CONDITIONAL(MOONLIGHT, [test "x$with_moonlight" != "xno"])
+AM_CONDITIONAL(ONLY_MOONLIGHT, [test "x$with_moonlight" = "xonly"])
 AM_CONDITIONAL(INSTALL_4_0, [test "x$with_profile4" = xyes])
 AM_CONDITIONAL(INSTALL_MONOTOUCH, [test "x$with_monotouch" = xyes])
 
@@ -2696,6 +2773,7 @@ data/net_4_0/Makefile
 data/net_2_0/Browsers/Makefile
 data/mint.pc
 data/mono-2.pc
+data/mono.pc
 data/mono-cairo.pc
 data/mono-nunit.pc
 data/mono-options.pc
@@ -2709,6 +2787,7 @@ data/cecil.pc
 data/system.web.extensions_1.0.pc
 data/system.web.extensions.design_1.0.pc
 data/system.web.mvc.pc
+data/system.web.mvc2.pc
 samples/Makefile
 support/Makefile
 data/config
@@ -2737,28 +2816,30 @@ fi
   NONE) exec_prefix='${prefix}' ;;
   esac
 
-  test -w $srcdir/$mcsdir/build || chmod +w $srcdir/$mcsdir/build
-
   #
   # If we are cross compiling, we don't build in the mcs/ tree.  Let us not clobber
   # any existing config.make.  This allows people to share the same source tree
   # with different build directories, one native and one cross
   #
   if test x$cross_compiling = xno && test x$enable_mcs_build != xno; then
-    echo "prefix=$prefix" > $srcdir/$mcsdir/build/config.make
-    echo "exec_prefix=$exec_prefix" >> $srcdir/$mcsdir/build/config.make
-    echo "sysconfdir=$sysconfdir" >> $srcdir/$mcsdir/build/config.make
-    echo 'mono_libdir=${exec_prefix}/lib' >> $srcdir/$mcsdir/build/config.make
-    echo 'MCS_FLAGS = $(PLATFORM_DEBUG_FLAGS)' >> $srcdir/$mcsdir/build/config.make
-    echo 'IL_FLAGS = /debug' >> $srcdir/$mcsdir/build/config.make
-    echo "RUNTIME = $mono_build_root/runtime/mono-wrapper" >> $srcdir/$mcsdir/build/config.make
-    echo "ILDISASM = $mono_build_root/runtime/monodis-wrapper" >> $srcdir/$mcsdir/build/config.make
+
+    test -w $mcs_topdir/build || chmod +w $mcs_topdir/build
+
+    echo "prefix=$prefix" > $mcs_topdir/build/config.make
+    echo "exec_prefix=$exec_prefix" >> $mcs_topdir/build/config.make
+    echo "sysconfdir=$sysconfdir" >> $mcs_topdir/build/config.make
+    echo 'mono_libdir=${exec_prefix}/lib' >> $mcs_topdir/build/config.make
+    echo 'MCS_FLAGS = $(PLATFORM_DEBUG_FLAGS)' >> $mcs_topdir/build/config.make
+    echo 'IL_FLAGS = /debug' >> $mcs_topdir/build/config.make
+    echo "RUNTIME = $mono_build_root/runtime/mono-wrapper" >> $mcs_topdir/build/config.make
+    echo "ILDISASM = $mono_build_root/runtime/monodis-wrapper" >> $mcs_topdir/build/config.make
+
     case $INSTALL in
     [[\\/$]]* | ?:[[\\/]]* ) mcs_INSTALL=$INSTALL ;;
     *) mcs_INSTALL=$mono_build_root/$INSTALL ;;
     esac
 
-    echo "INSTALL = $mcs_INSTALL" >> $srcdir/$mcsdir/build/config.make
+    echo "INSTALL = $mcs_INSTALL" >> $mcs_topdir/build/config.make
 
     export VERSION
     [myver=$($AWK 'BEGIN {
@@ -2769,23 +2850,33 @@ fi
       print vsplit [1] "." vsplit [2] "." vsplit [3] "." vsplit [4]
     }')]
 
-    echo "MONO_VERSION = $myver" >> $srcdir/$mcsdir/build/config.make
-  fi
+    echo "MONO_VERSION = $myver" >> $mcs_topdir/build/config.make
 
-  if test x$platform_darwin = xyes; then
-       echo "PLATFORM = darwin" >> $srcdir/$mcsdir/build/config.make
-  fi
+    if test x$platform_darwin = xyes; then
+      echo "PLATFORM = darwin" >> $mcs_topdir/build/config.make
+    fi
+
+    if test x$TARGET = xAMD64 -a x$host_win32 = xno -a "x$AOT_SUPPORTED" = "xyes" -a x$enable_system_aot = xyes; then
+      echo "ENABLE_AOT = 1" >> $mcs_topdir/build/config.make
+    fi
+
+    if test x$DISABLE_MCS_DOCS = xyes; then
+      echo "DISABLE_MCS_DOCS = yes" >> $mcs_topdir/build/config.make
+    fi
+
+    if test x$with_moonlight != xno; then
+      echo "MOONLIGHT = 1" >> $srcdir/$mcsdir/build/config.make
+    fi
 
-  if test x$TARGET = xAMD64 -a x$host_win32 = xno -a "x$AOT_SUPPORTED" = "xyes"; then
-        echo "ENABLE_AOT = 1" >> $srcdir/$mcsdir/build/config.make
   fi
 
   # if we have an olive folder, override the default settings
   if test -d $olivedir; then
 
-    test -w $srcdir/$olivedir/build || chmod +w $srcdir/$olivedir/build
-
     if test x$cross_compiling = xno && test x$enable_olive_build != xno; then
+
+      test -w $srcdir/$olivedir/build || chmod +w $srcdir/$olivedir/build
+
       echo "prefix=$prefix" > $srcdir/$olivedir/build/config.make
       echo "exec_prefix=$exec_prefix" >> $srcdir/$olivedir/build/config.make
       echo 'mono_libdir=${exec_prefix}/lib' >> $srcdir/$olivedir/build/config.make
@@ -2795,19 +2886,12 @@ fi
     fi
   fi
 
-  if test x$DISABLE_MCS_DOCS = xyes; then
-       echo "DISABLE_MCS_DOCS = yes" >> $srcdir/$mcsdir/build/config.make
-  fi
-
-  if test x$with_moonlight = xyes; then
-       echo "MOONLIGHT = 1" >> $srcdir/$mcsdir/build/config.make
-  fi
 )
 
 libgdiplus_msg=${libgdiplus_loc:-assumed to be installed}
 
 echo "
-        mcs source:    $mcs_topdir
+        mcs source:    $mcsdir
         olive source:  $olive_topdir
 
    Engine:
index 9401dba58091164bdcabf0a8a4fdfc8c075b8520..0fcb14f40c3c7f0ada949ad93ab08c1456abeee7 100644 (file)
@@ -1,3 +1,7 @@
+2010-04-02  Jb Evain  <jbevain@novell.com>
+
+       * dotnet35.pc.in: add System.Data.Services.dll.
+
 2010-03-08  Rodrigo Kumpera  <rkumpera@novell.com>
 
        * mono.supp: Add hazard pointers supressions.
index 3ae35a43747c34385a60cb5fc043fd821e20ed14..14ef47b9d9aa058bdb7cfa38aa0833ae43cd1cb7 100644 (file)
@@ -9,10 +9,10 @@ monodir = $(sysconfdir)/mono
 EXTRA_DIST =   \
        config.in \
        browscap.ini mono.supp mono.d README ChangeLog \
-       mono-2.pc.in mint.pc.in dotnet.pc.in dotnet35.pc.in wcf.pc.in monodoc.pc.in \
+       mono.pc.in mono-2.pc.in mint.pc.in dotnet.pc.in dotnet35.pc.in wcf.pc.in monodoc.pc.in \
        mono-nunit.pc.in mono-cairo.pc.in mono-options.pc.in cecil.pc.in \
        mono-lineeditor.pc.in system.web.extensions_1.0.pc.in system.web.extensions.design_1.0.pc.in\
-       dtrace-prelink.sh mono.web.pc.in system.web.mvc.pc.in \
+       dtrace-prelink.sh mono.web.pc.in system.web.mvc.pc.in system.web.mvc2.pc.in \
        net_1_1/machine.config \
        gdb/mono-gdb.py \
        gdb/gdb-python.diff
@@ -21,18 +21,18 @@ pkgconfigdir = $(libdir)/pkgconfig
 
 if JIT_SUPPORTED
 if INTERP_SUPPORTED
-pkgconfig_DATA= mono-2.pc mint.pc dotnet.pc dotnet35.pc wcf.pc mono-nunit.pc mono-cairo.pc mono-options.pc cecil.pc monodoc.pc mono-lineeditor.pc system.web.extensions_1.0.pc \
-               system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc
+pkgconfig_DATA= mono.pc mono-2.pc mint.pc dotnet.pc dotnet35.pc wcf.pc mono-nunit.pc mono-cairo.pc mono-options.pc cecil.pc monodoc.pc mono-lineeditor.pc system.web.extensions_1.0.pc \
+               system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc system.web.mvc2.pc
 else
-pkgconfig_DATA= mono-2.pc dotnet.pc dotnet35.pc wcf.pc mono-nunit.pc mono-cairo.pc mono-options.pc cecil.pc monodoc.pc mono-lineeditor.pc system.web.extensions_1.0.pc \
-               system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc
+pkgconfig_DATA= mono.pc mono-2.pc dotnet.pc dotnet35.pc wcf.pc mono-nunit.pc mono-cairo.pc mono-options.pc cecil.pc monodoc.pc mono-lineeditor.pc system.web.extensions_1.0.pc \
+               system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc system.web.mvc2.pc
 endif
 else
 pkgconfig_DATA= mint.pc mono-nunit.pc mono-cairo.pc mono-options.pc cecil.pc monodoc.pc mono-lineeditor.pc
 endif
 
-DISTCLEANFILES= mono-2.pc mint.pc dotnet.pc dotnet35.pc wcf.pc mono-nunit.pc mono-cairo.pc mono-options.pc cecil.pc monodoc.pc mono-lineeditor.pc system.web.extensions_1.0.pc \
-               system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc
+DISTCLEANFILES= mono-2.pc mono.pc mint.pc dotnet.pc dotnet35.pc wcf.pc mono-nunit.pc mono-cairo.pc mono-options.pc cecil.pc monodoc.pc mono-lineeditor.pc system.web.extensions_1.0.pc \
+               system.web.extensions.design_1.0.pc mono.web.pc system.web.mvc.pc system.web.mvc2.pc
 
 mono_DATA =  config \
             browscap.ini
index e9b2b76dfc71d3f927aa4c7176279f1a5503abf0..0983102bffdbf91194e45d8a61a429cebc0d60be 100644 (file)
@@ -2,4 +2,4 @@
 Name: Standard libraries in a .NET setup
 Description: References all the standard .NET libraries for compilation
 Version: @VERSION@
-Libs: -r:Accessibility.dll -r:cscompmgd.dll -r:Microsoft.JScript.dll -r:Microsoft.VisualC.dll -r:Microsoft.Vsa.dll -r:System.Configuration.Install.dll -r:System.Data.dll -r:System.Data.OracleClient.dll -r:System.Design.dll -r:System.DirectoryServices.dll -r:System.dll -r:System.Drawing.Design.dll -r:System.Drawing.dll -r:System.EnterpriseServices.dll -r:System.Management.dll -r:System.Messaging.dll -r:System.Runtime.Remoting.dll -r:System.Runtime.Serialization.Formatters.Soap.dll -r:System.Security.dll -r:System.ServiceProcess.dll -r:System.Web.dll -r:System.Web.Services.dll -r:System.Windows.Forms.dll -r:System.Xml.dll
+Libs: -r:Accessibility.dll -r:cscompmgd.dll -r:Microsoft.VisualC.dll -r:System.Configuration.Install.dll -r:System.Data.dll -r:System.Data.OracleClient.dll -r:System.Design.dll -r:System.DirectoryServices.dll -r:System.dll -r:System.Drawing.Design.dll -r:System.Drawing.dll -r:System.EnterpriseServices.dll -r:System.Management.dll -r:System.Messaging.dll -r:System.Runtime.Remoting.dll -r:System.Runtime.Serialization.Formatters.Soap.dll -r:System.Security.dll -r:System.ServiceProcess.dll -r:System.Web.dll -r:System.Web.Services.dll -r:System.Windows.Forms.dll -r:System.Xml.dll
index 7e2f6e1641bb2982c0da93b6634ebc0a48301676..9db3647aafb7aade4e716aa00b9e8506768b9f11 100644 (file)
@@ -2,4 +2,4 @@
 Name: Standard libraries in a .NET setup
 Description: References all the standard .NET libraries for compilation (.NET Framework 3.5 compatibility)
 Version: @VERSION@
-Libs: -r:Accessibility.dll -r:cscompmgd.dll -r:Microsoft.JScript.dll -r:Microsoft.VisualC.dll -r:Microsoft.Vsa.dll -r:System.Configuration.Install.dll -r:System.Data.dll -r:System.Data.OracleClient.dll -r:System.Design.dll -r:System.DirectoryServices.dll -r:System.dll -r:System.Drawing.Design.dll -r:System.Drawing.dll -r:System.EnterpriseServices.dll -r:System.Management.dll -r:System.Messaging.dll -r:System.Runtime.Remoting.dll -r:System.Runtime.Serialization.Formatters.Soap.dll -r:System.Security.dll -r:System.ServiceProcess.dll -r:System.Web.dll -r:System.Web.Services.dll -r:System.Windows.Forms.dll -r:System.Xml.dll -r:System.Configuration.dll -r:System.Core.dll -r:System.Xml.Linq.dll -r:System.Data.DataSetExtensions.dll -r:System.Data.Linq.dll -r:System.Web.Abstractions.dll -r:System.Web.Routing.dll -r:System.Web.DynamicData.dll -r:System.ComponentModel.DataAnnotations.dll
+Libs: -r:Accessibility.dll -r:cscompmgd.dll -r:Microsoft.JScript.dll -r:Microsoft.VisualC.dll -r:Microsoft.Vsa.dll -r:System.Configuration.Install.dll -r:System.Data.dll -r:System.Data.OracleClient.dll -r:System.Design.dll -r:System.DirectoryServices.dll -r:System.dll -r:System.Drawing.Design.dll -r:System.Drawing.dll -r:System.EnterpriseServices.dll -r:System.Management.dll -r:System.Messaging.dll -r:System.Runtime.Remoting.dll -r:System.Runtime.Serialization.Formatters.Soap.dll -r:System.Security.dll -r:System.ServiceProcess.dll -r:System.Web.dll -r:System.Web.Services.dll -r:System.Windows.Forms.dll -r:System.Xml.dll -r:System.Configuration.dll -r:System.Core.dll -r:System.Xml.Linq.dll -r:System.Data.DataSetExtensions.dll -r:System.Data.Linq.dll -r:System.Data.Services.dll -r:System.Web.Abstractions.dll -r:System.Web.Routing.dll -r:System.Web.DynamicData.dll -r:System.ComponentModel.DataAnnotations.dll
diff --git a/data/mono.pc.in b/data/mono.pc.in
new file mode 100644 (file)
index 0000000..0e8727e
--- /dev/null
@@ -0,0 +1,9 @@
+prefix=${pcfiledir}/../..
+exec_prefix=${pcfiledir}/../..
+libdir=${prefix}/@reloc_libdir@
+includedir=${prefix}/include/mono-@API_VER@
+sysconfdir=@sysconfdir@
+
+Name: Mono
+Description: Mono Runtime
+Version: @VERSION@
index 550068cf109048ac4104328964687c8b2942c7b1..f007af7bdb7050b741702dc7b014488abf833c8a 100644 (file)
@@ -86,6 +86,9 @@
                </sectionGroup>
                <section name="system.webServer" type="System.Configuration.IgnoreSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
                <section name="uri" type="System.Configuration.UriSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
+               <sectionGroup name="system.runtime.caching" type="System.Runtime.Caching.Configuration.CachingSectionGroup, System.Runtime.Caching, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
+                 <section name="memoryCache" type="System.Runtime.Caching.Configuration.MemoryCacheSection, System.Runtime.Caching, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowDefinition="MachineToApplication"/>
+                </sectionGroup>
        </configSections>
 
        <connectionStrings>
diff --git a/data/system.web.mvc2.pc.in b/data/system.web.mvc2.pc.in
new file mode 100644 (file)
index 0000000..8b17369
--- /dev/null
@@ -0,0 +1,4 @@
+Name: System.Web.Mvc2
+Description: System.Web.Mvc - ASP.NET MVC v2
+Version: 2.0.0.0
+Libs: -r:@prefix@/lib/mono/gac/System.Web.Mvc/2.0.0.0__31bf3856ad364e35/System.Web.Mvc.dll
index b78903a7cb403b404f4ace0438deeabbfd95cbce..04f9755dd274f6f49bc25331a82be4c38ab2d0b4 100644 (file)
@@ -1,3 +1,9 @@
+2010-04-06  Andreia Gaita  <avidigal@novell.com>
+
+       * Makefile.am: fix distcheck - several targets get built on the
+       srcdir, which has no write permissions on make distcheck, so make
+       sure permissions are set
+
 2009-12-22  Jo Shields  <directhex@apebox.org>
        * HtmlAgilityPack/LICENSE: Include upstream license (Ms-PL) since the
          file headers don't specify it
index 639b7537d26de211d12c295fbbdfc96af5a39398..c0450027cfd9498e0990bdfe2dd93d483c5329a5 100644 (file)
@@ -79,21 +79,21 @@ clean-local:
 
 monoapi.zip: monoapi.tree
        @test -f $@ || { rm -f $(srcdir)/monoapi.tree && $(MAKE) monoapi.tree; }
-monoapi.tree: docs.make Makefile.am toc.xml $(srcdir)/deploy/.stamp
-       cd $(srcdir) && cp api-style.css deploy
+monoapi.tree: docs.make Makefile.am toc.xml $(srcdir)/deploy/.stamp perms
+       cd $(srcdir) && cp -f api-style.css deploy
        cd $(srcdir) && $(MAKE) -f docs.make topdir=$(mcs_topdir_from_srcdir) $@
 
 mono-tools.zip: mono-tools.tree
        @test -f $@ || { rm -f $(srcdir)/mono-tools.tree && $(MAKE) mono-tools.tree; }
-mono-tools.tree: docs.make Makefile.am $(srcdir)/deploy/.stamp
+mono-tools.tree: docs.make Makefile.am $(srcdir)/deploy/.stamp perms
        cd $(srcdir) && $(MAKE) -f docs.make topdir=$(mcs_topdir_from_srcdir) $@
 
-mono-file-formats.zip: mono-file-formats.tree
+mono-file-formats.zip: mono-file-formats.tree perms
        @test -f $@ || { rm -f $(srcdir)/mono-file-formats.tree && $(MAKE) mono-file-formats.tree; }
 mono-file-formats.tree: docs.make Makefile.am $(srcdir)/deploy/.stamp
        cd $(srcdir) && $(MAKE) -f docs.make topdir=$(mcs_topdir_from_srcdir) $@
 
-$(srcdir)/deploy/.stamp: convert.exe Makefile.am
+$(srcdir)/deploy/.stamp: convert.exe Makefile.am perms
        $(mkdir_p) $(srcdir)/html
        runtimedir=`cd ../runtime && pwd`; export runtimedir; \
        cd $(srcdir) && MONO_PATH=$(mcs_topdir_from_srcdir)/class/lib/net_2_0 perl ./exdoc -h . ../mono/*/*.c
@@ -101,8 +101,13 @@ $(srcdir)/deploy/.stamp: convert.exe Makefile.am
 
 extract: $(srcdir)/deploy/.stamp
 
-convert.exe: convert.cs AgilityPack.dll
+convert.exe: convert.cs AgilityPack.dll perms
        cd $(srcdir) && $(MAKE) PROFILE=net_2_0 -f docs.make topdir=$(mcs_topdir_from_srcdir) convert.exe
 
-AgilityPack.dll:
+AgilityPack.dll: perms
        cd $(srcdir) && $(MAKE) PROFILE=net_2_0 -f docs.make topdir=$(mcs_topdir_from_srcdir) AgilityPack.dll
+
+.PHONY: perms
+perms:
+       -@test -w $(srcdir) || chmod a+w $(srcdir)
+
index 1a2f51733cda0835177bfb6a90b14b7820f5f920..f7751e2e3b6f804a0437e442ccf82bad944bb75d 100644 (file)
@@ -24,7 +24,7 @@ A small note on the choice of magic_reg for different JIT backends: the IMT
 method identifier doesn't necessarily need to be stored in a register, though
 doing so is fast and the JIT code has already the infrastructure to handle this
 case in an arch-independent way. A JIT porter just needs to #define
-MONO_ARCH_IMT_REG to the choosen register. Note that this register should be
+MONO_ARCH_IMT_REG to the chosen register. Note that this register should be
 part of the MONO_ARCH_CALLEE_REGS set as it will be handled by the local register
 allocator (see mini/inssel.brg) and it must not be part of the registers used for
 argument passing as you'd overwrite an argument in that case.
@@ -72,7 +72,7 @@ the IMT slot was asked to execute an interface method that the type doesn't impl
 In the future we might want to handle this case not with a breakpoint or assert, but
 by either throwing an InvalidCast exception or by going into the runtime and
 adding support for the interface automagically to the type/vtable: this could be used
-both for tranparent proxies and for the implicit interfaces that vectors in 2.0
+both for transparent proxies and for the implicit interfaces that vectors in 2.0
 provide.
 
 For a bisect check the code is even simpler:
@@ -131,7 +131,7 @@ called the magic trampoline will fill-in the IMT slot with the proper thunk or
 trampoline, so later calls will use the fast path.
 This single-instance trampoline will use MONO_FAKE_IMT_METHOD as the method
 it's asking to be compiled and executed: the trampoline code does recognize
-this special value and retrives the interface method to call from the usual
+this special value and retrieves the interface method to call from the usual
 MONO_ARCH_IMT_REG saved by the trampoline code.
 Given that only the IMT slots that are actually used will be initialized, this saves
 quite a bit of memory, as it's unlikely that all the interface methods are called on
index 5db80e94e36f1b8883b196135cb390e54213c80f..60bdd94f906bf35ed5979fd786fa87974c14e16e 100644 (file)
@@ -1,3 +1,35 @@
+2010-04-25  Andreas Faerber  <andreas.faerber@web.de>
+
+       * configure.ac: The iconv function may be libiconv_open.
+       Fixes linking with GNU libiconv.
+
+       Contributed under MIT/X11 license.
+
+2010-04-23  Geoff Norton  <gnorton@novell.com>
+
+       * configure.ac: The iconv function is iconv_open.
+
+2010-04-19  Jonathan Pryor  <jpryor@novell.com>
+
+       * src/glib.h: Rebase g_return_if_fail(), g_return_val_if_fail() in
+         terms of g_critical() instead of printf, and turn g_printerr() into
+         an actual function instead of a macro.
+       * src/goutput.c: Add Android support, sending g_print(), g_printerr(),
+         and g_log() messages to the Android system log.
+
+2010-04-16 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * test/ptrarray.c: new tests
+       * src/gptrarray.c: implemented g_ptr_array_remove_fast().
+
+2010-04-10  Andreas Faerber  <andreas.faerber@web.de>
+
+       * configure.ac: Add checks for libm and libdl.
+       * {src,test}/Makefile.am: Remove hardcoded library dependencies.
+       Fixes compilation on Haiku.
+
+       Contributed under MIT/X11 license.
+
 2010-03-05  Zoltan Varga  <vargaz@gmail.com>
 
        * test/test.c (_GNU_SOURCE): Fix compilation if _GNU_SOURCE is already defined.
index f075d785747e93c8e5cf8e6004dea02282fc9067..3014d264690f85e01f5008a3d13430b3ae344b94 100644 (file)
@@ -69,7 +69,10 @@ AM_CONDITIONAL(TARGET_WIN32, test x$OS = xWIN32)
 AC_CHECK_SIZEOF(int)
 AC_CHECK_SIZEOF(void *)
 AC_CHECK_FUNCS(strndup strlcpy getpwent_r strtok_r rewinddir)
+AC_CHECK_LIB(iconv, iconv_open, LIBS="$LIBS -liconv")
 AC_CHECK_LIB(iconv, libiconv_open, LIBS="$LIBS -liconv")
+AC_SEARCH_LIBS(sqrtf, m)
+AC_SEARCH_LIBS(dlopen, dl)
 old_ldflags="${LDFLAGS}"
 LDFLAGS="${LDFLAGS} -Wl,-export-dynamic"
 AC_TRY_LINK(, [int i;], found_export_dynamic=yes, found_export_dynamic=no)
index 53dec7825ac9917a6b848b158d55689959384db9..8d7d614d5ead80e31ade18cb1d6e66b2c01a4c71 100644 (file)
@@ -1,6 +1,10 @@
-/
 /Makefile
 /Makefile.in
 /.libs
 /.deps
-/eglib-config.h
+/*.lo
+/*.la
+/*.o
+/semantic.cache
+/.project
+/.cproject
index 337c9886c08fb4765c96760ab7791039b9cf51cb..8cd29dc293b085d6280f93aef93bff15c063060d 100644 (file)
@@ -51,8 +51,6 @@ INCLUDES = -I$(srcdir)
 
 if HOST_WIN32
 libeglib_la_LIBADD = -lm -liconv -lpsapi
-else
-libeglib_la_LIBADD = -lm -ldl
 endif
 
 libeglib_static_la_LIBADD = $(libeglib_la_LIBADD)
index ec78f6d2d080e532b74d1c81b6fe8a8e97e97353..8920d18f26b42a7f7ae46a617b774c1aab37eb07 100644 (file)
@@ -164,8 +164,8 @@ gchar*           g_win32_getlocale(void);
 /*
  * Precondition macros
  */
-#define g_return_if_fail(x)  G_STMT_START { if (!(x)) { printf ("%s:%d: assertion '%s' failed", __FILE__, __LINE__, #x); return; } } G_STMT_END
-#define g_return_val_if_fail(x,e)  G_STMT_START { if (!(x)) { printf ("%s:%d: assertion '%s' failed", __FILE__, __LINE__, #x); return (e); } } G_STMT_END
+#define g_return_if_fail(x)  G_STMT_START { if (!(x)) { g_critical ("%s:%d: assertion '%s' failed", __FILE__, __LINE__, #x); return; } } G_STMT_END
+#define g_return_val_if_fail(x,e)  G_STMT_START { if (!(x)) { g_critical ("%s:%d: assertion '%s' failed", __FILE__, __LINE__, #x); return (e); } } G_STMT_END
 
 /*
  * Hashtables
@@ -510,6 +510,7 @@ typedef enum {
 } GLogLevelFlags;
 
 void           g_print                (const gchar *format, ...);
+void           g_printerr             (const gchar *format, ...);
 GLogLevelFlags g_log_set_always_fatal (GLogLevelFlags fatal_mask);
 GLogLevelFlags g_log_set_fatal_mask   (const gchar *log_domain, GLogLevelFlags fatal_mask);
 void           g_logv                 (const gchar *log_domain, GLogLevelFlags log_level, const gchar *format, va_list args);
@@ -522,17 +523,13 @@ void           g_assertion_message    (const gchar *format, ...) G_GNUC_NORETURN
 #define g_warning(format, ...)  g_log (G_LOG_DOMAIN, G_LOG_LEVEL_WARNING, format, __VA_ARGS__)
 #define g_message(format, ...)  g_log (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, format, __VA_ARGS__)
 #define g_debug(format, ...)    g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, format, __VA_ARGS__)
-
-#define g_printerr(format, ...) fprintf (stderr, format, __VA_ARGS__)
-#else
+#else   /* HAVE_C99_SUPPORT */
 #define g_error(...)    g_log (G_LOG_DOMAIN, G_LOG_LEVEL_ERROR, __VA_ARGS__)
 #define g_critical(...) g_log (G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL, __VA_ARGS__)
 #define g_warning(...)  g_log (G_LOG_DOMAIN, G_LOG_LEVEL_WARNING, __VA_ARGS__)
 #define g_message(...)  g_log (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, __VA_ARGS__)
 #define g_debug(...)    g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, __VA_ARGS__)
-
-#define g_printerr(...) fprintf (stderr, __VA_ARGS__)
-#endif
+#endif  /* ndef HAVE_C99_SUPPORT */
 #define g_log_set_handler(a,b,c,d)
 
 /*
index 3a12201735eaf0970bb52da4f23c730955a47c97..3ed6c91a27597811d457fea67a87642a7c6b301f 100644 (file)
 /* The current fatal levels, error is always fatal */
 static GLogLevelFlags fatal = G_LOG_LEVEL_ERROR;
 
+#if PLATFORM_ANDROID
+#include <android/log.h>
+
+static android_LogPriority
+to_android_priority (GLogLevelFlags log_level)
+{
+       switch (log_level & G_LOG_LEVEL_MASK)
+       {
+               case G_LOG_LEVEL_ERROR:     return ANDROID_LOG_FATAL;
+               case G_LOG_LEVEL_CRITICAL:  return ANDROID_LOG_ERROR;
+               case G_LOG_LEVEL_WARNING:   return ANDROID_LOG_WARN;
+               case G_LOG_LEVEL_MESSAGE:   return ANDROID_LOG_INFO;
+               case G_LOG_LEVEL_INFO:      return ANDROID_LOG_DEBUG;
+               case G_LOG_LEVEL_DEBUG:     return ANDROID_LOG_VERBOSE;
+       }
+       return ANDROID_LOG_UNKNOWN;
+}
+
+static void 
+out_vfprintf (FILE *ignore, const gchar *format, va_list args)
+{
+       /* TODO: provide a proper app name */
+       __android_log_vprint (ANDROID_LOG_ERROR, "mono", format, args);
+}
+#else
+static void 
+out_vfprintf (FILE *file, const gchar *format, va_list args)
+{
+       vfprintf (file, format, args);
+}
+#endif
+
 void
 g_print (const gchar *format, ...)
 {
        va_list args;
 
        va_start (args, format);
-       vprintf (format, args);
+
+       out_vfprintf (stdout, format, args);
+
+       va_end (args);
+}
+
+void
+g_printerr (const gchar *format, ...)
+{
+       va_list args;
+
+       va_start (args, format);
+
+       out_vfprintf (stderr, format, args);
+
        va_end (args);
 }
 
@@ -68,10 +114,19 @@ g_logv (const gchar *log_domain, GLogLevelFlags log_level, const gchar *format,
        char *msg;
        
        vasprintf (&msg, format, args);
+#if PLATFORM_ANDROID
+       __android_log_print (to_android_priority (log_level), 
+               /* TODO: provide a proper app name */
+               "mono", "%s%s%s",
+               log_domain != NULL ? log_domain : "",
+               log_domain != NULL ? ": " : "",
+               msg);
+#else
        printf ("%s%s%s",
                log_domain != NULL ? log_domain : "",
                log_domain != NULL ? ": " : "",
                msg);
+#endif
        free (msg);
        if (log_level & fatal){
                fflush (stdout);
index 656c78840666ff28fd6179685e7806395ee207d7..bfde715225590fdc0477c19ca86cf2792924cb63 100644 (file)
@@ -177,6 +177,27 @@ g_ptr_array_remove(GPtrArray *array, gpointer data)
        return FALSE;
 }
 
+gboolean
+g_ptr_array_remove_fast(GPtrArray *array, gpointer data)
+{
+       guint i;
+
+       g_return_val_if_fail(array != NULL, FALSE);
+
+       for(i = 0; i < array->len; i++) {
+               if(array->pdata[i] == data) {
+                       array->len--;
+                       if (array->len > 0)
+                               array->pdata [i] = array->pdata [array->len];
+                       else
+                               array->pdata [i] = NULL;
+                       return TRUE;
+               }
+       }
+
+       return FALSE;
+}
+
 void 
 g_ptr_array_foreach(GPtrArray *array, GFunc func, gpointer user_data)
 {
index f2ccf94093a2b6662538ee98cb7f7e948c84610d..1d0c956d17d3fab14b63f70677c27cc4a38f0d90 100644 (file)
@@ -136,15 +136,145 @@ g_shell_parse_argv (const gchar *command_line, gint *argcp, gchar ***argvp, GErr
 gchar *
 g_shell_quote (const gchar *unquoted_string)
 {
-       //g_error ("%s", "Not implemented");
-       return g_strdup (unquoted_string);
-//     return NULL;
+       GString *result = g_string_new ("'");
+       const gchar *p;
+       
+       for (p = unquoted_string; *p; p++){
+               if (*p == '\'')
+                       g_string_append (result, "'\\'");
+               g_string_append_c (result, *p);
+       }
+       g_string_append_c (result, '\'');
+       return g_string_free (result, FALSE);
 }
 
 gchar *
 g_shell_unquote (const gchar *quoted_string, GError **error)
 {
-//     g_error ("%s", "Not implemented");
-       return g_strdup (quoted_string);
-//     return NULL;
+       GString *result;
+       const char *p;
+       int do_unquote = 0;
+
+       if (quoted_string == NULL)
+               return NULL;
+       
+       /* Quickly try to determine if we need to unquote or not */
+       for (p = quoted_string; *p; p++){
+               if (*p == '\'' || *p == '"' || *p == '\\'){
+                       do_unquote = 1;
+                       break;
+               }
+       }
+       
+       if (!do_unquote)
+               return g_strdup (quoted_string);
+
+       /* We do need to unquote */
+       result = g_string_new ("");
+       for (p = quoted_string; *p; p++){
+
+               if (*p == '\''){
+                       /* Process single quote, not even \ is processed by glib's version */
+                       for (p++; *p; p++){
+                               if (*p == '\'')
+                                       break;
+                               g_string_append_c (result, *p);
+                       }
+                       if (!*p){
+                               g_set_error (error, 0, 0, "Open quote");
+                               return NULL;
+                       }
+               } else if (*p == '"'){
+                       /* Process double quote, allows some escaping */
+                       for (p++; *p; p++){
+                               if (*p == '"')
+                                       break;
+                               if (*p == '\\'){
+                                       p++;
+                                       if (*p == 0){
+                                               g_set_error (error, 0, 0, "Open quote");
+                                               return NULL;
+                                       }
+                                       switch (*p){
+                                       case '$':
+                                       case '"':
+                                       case '\\':
+                                       case '`':
+                                               break;
+                                       default:
+                                               g_string_append_c (result, '\\');
+                                               break;
+                                       }
+                               } 
+                               g_string_append_c (result, *p);
+                       }
+                       if (!*p){
+                               g_set_error (error, 0, 0, "Open quote");
+                               return NULL;
+                       }
+               } else if (*p == '\\'){
+                       char c = *(++p);
+                       if (!(c == '$' || c == '"' || c == '\\' || c == '`' || c == 0))
+                               g_string_append_c (result, '\\');
+                       if (c == 0)
+                               break;
+                       else
+                               g_string_append_c (result, c);
+               } else
+                       g_string_append_c (result, *p);
+       }
+       return g_string_free (result, FALSE);
+}
+
+#if JOINT_TEST
+/*
+ * This test is designed to be built with the 2 glib/eglib to compare
+ */
+
+char *args [] = {
+       "\\",
+       "\"Foo'bar\"",
+       "'foo'",
+       "'fo\'b'",
+       "'foo\"bar'",
+       "'foo' dingus bar",
+       "'foo' 'bar' 'baz'",
+       "\"foo\" 'bar' \"baz\"",
+       "\"f\\$\\\'",
+       "\"\\",
+       "\\\\",
+       "'\\\\'",
+       "\"f\\$\"\\\"\\\\", //  /\\\"\\\\"
+       "'f\\$'\\\"\\\\", 
+       "'f\\$\\\\'", 
+       NULL
+};
+
+
+int
+main ()
+{
+       char **s = args;
+       int i;
+       
+       while (*s){
+               char *r1 = g_shell_unquote (*s, NULL);
+               char *r2 = g2_shell_unquote (*s, NULL);
+               char *ok = r1 == r2 ? "ok" : (r1 != NULL && r2 != NULL && strcmp (r1, r2) == 0) ? "ok" : "fail";
+               
+               printf ("%s [%s] -> [%s] - [%s]\n", ok, *s, r1, r2);
+               s++;
+       }
+       return;
+       char buffer [10];
+       buffer [0] = '\"';
+       buffer [1] = '\\';
+       buffer [3] = '\"';
+       buffer [4] = 0;
+       
+       for (i = 32; i < 255; i++){
+               buffer [2] = i;
+               printf ("%d [%s] -> [%s]\n", i, buffer, g_shell_unquote (buffer, NULL));
+       }
 }
+#endif
index 39e5739e7e27e0c0d3c5b83b4d8937685f41fcc4..8d7d614d5ead80e31ade18cb1d6e66b2c01a4c71 100644 (file)
@@ -1,17 +1,10 @@
-/
-/Makefile.in
-/configure
-/libtool
-/aclocal.m4
 /Makefile
-/config.h
-/config.h.in
-/config.status
-/stamp-h1
-/autom4te.cache
+/Makefile.in
 /.libs
 /.deps
-/test-glib
-/test-eglib
-/test-glib.exe
-/test-eglib.exe
+/*.lo
+/*.la
+/*.o
+/semantic.cache
+/.project
+/.cproject
index 4f825b3cc611707cbbad83279739e51811ccadd8..3411ef90b4afa7c0c2592ab28c0384c1c2a8669a 100644 (file)
@@ -30,7 +30,7 @@ SOURCES = \
 test_eglib_SOURCES = $(SOURCES)
 
 test_eglib_CFLAGS = -Wall -Werror -D_FORTIFY_SOURCE=2 -I$(srcdir)/../src -I../src -DDRIVER_NAME=\"EGlib\"
-test_eglib_LDADD = ../src/libeglib.la -ldl
+test_eglib_LDADD = ../src/libeglib.la
 
 run-eglib: all
        ./test-eglib
index 1b2cc58c35463333f5a06dea09af177fd8867dff..a823dd7655517d64f1ff115631f1bf62acbb674c 100644 (file)
@@ -253,6 +253,46 @@ RESULT ptrarray_sort()
        return OK;
 }
 
+RESULT ptrarray_remove_fast()
+{
+       GPtrArray *array = g_ptr_array_new();
+       gchar *letters [] = { "A", "B", "C", "D", "E" };
+       
+       if (g_ptr_array_remove_fast (array, NULL))
+               return FAILED ("Removing NULL succeeded");
+
+       g_ptr_array_add(array, letters[0]);
+       if (!g_ptr_array_remove_fast (array, letters[0]) || array->len != 0)
+               return FAILED ("Removing last element failed");
+
+       g_ptr_array_add(array, letters[0]);
+       g_ptr_array_add(array, letters[1]);
+       g_ptr_array_add(array, letters[2]);
+       g_ptr_array_add(array, letters[3]);
+       g_ptr_array_add(array, letters[4]);
+
+       if (!g_ptr_array_remove_fast (array, letters[0]) || array->len != 4)
+               return FAILED ("Removing first element failed");
+
+       if (array->pdata [0] != letters [4])
+               return FAILED ("First element wasn't replaced with last upon removal");
+
+       if (g_ptr_array_remove_fast (array, letters[0]))
+               return FAILED ("Succedeed removing a non-existing element");
+
+       if (!g_ptr_array_remove_fast (array, letters[3]) || array->len != 3)
+               return FAILED ("Failed removing \"D\"");
+
+       if (!g_ptr_array_remove_fast (array, letters[1]) || array->len != 2)
+               return FAILED ("Failed removing \"B\"");
+
+       if (array->pdata [0] != letters [4] || array->pdata [1] != letters [2])
+               return FAILED ("Last two elements are wrong");
+       g_ptr_array_free(array, TRUE);
+       
+       return OK;
+}
+
 static Test ptrarray_tests [] = {
        {"alloc", ptrarray_alloc},
        {"for_iterate", ptrarray_for_iterate},
@@ -262,6 +302,7 @@ static Test ptrarray_tests [] = {
        {"remove_index_fast", ptrarray_remove_index_fast},
        {"remove", ptrarray_remove},
        {"sort", ptrarray_sort},
+       {"remove_fast", ptrarray_remove_fast},
        {NULL, NULL}
 };
 
index 9178625397b14cf304a9a607fa59e39f924b7a3b..38252cd2e0e196db8ddd90c53d435fa5ec0829bd 100644 (file)
@@ -226,10 +226,25 @@ test_shell_argv3 ()
        return OK;
 }
 
+RESULT
+test_quote ()
+{
+       if (strcmp (g_shell_quote ("foo"), "'foo'"))
+               return FAILED ("Should return 'foo'");
+
+       if (strcmp (g_shell_quote ("foo'bar"), "'foo'\\''bar'"))
+               return FAILED ("Should return 'foo'\\''bar'");
+
+       if (strcmp (g_shell_quote ("foo bar"), "'foo bar'"))
+               return FAILED ("Should return 'foo bar'");
+       return OK;
+}
+
 static Test shell_tests [] = {
        {"g_shell_parse_argv1", test_shell_argv1},
        {"g_shell_parse_argv2", test_shell_argv2},
        {"g_shell_parse_argv3", test_shell_argv3},
+       {"g_shell_quote", test_quote},
        {NULL, NULL}
 };
 
index b6235a2838919710f08c7b8696c992cd28585606..114a3b27551cc3e680cbccce59a7238950e25b93 100644 (file)
@@ -1,3 +1,16 @@
+2010-04-23  Geoff Norton  <gnorton@novell.com>
+
+       * include/private/gcconfig.h: Darwin x86-64 bit support.
+       * darwin_stop_world.c: Ditto
+
+2010-04-19  Jonathan Pryor  <jpryor@novell.com>
+
+       * include/private/gcconfig.h: Android platforms are built atop Linux,
+         don't use glibc, and uses `environ` instead of `__environ`.
+       * configure.in: Use AC_CHECK_LIB() to check for pthread instead of
+         just blindly linking to -lpthread, as Android includes pthread
+         support within libc and doesn't provide a separate libpthread.
+
 2010-03-09  Zoltan Varga  <vargaz@gmail.com>
 
        * include/private/gc_locks.h: Fix amd64 build with newer gcc's.
index 2749d08b13b96bbe437111f70bdfe617602b3ea3..2f7e173189b28e73b847343718fbfe356f6e6963 100644 (file)
@@ -84,7 +84,7 @@ case "$THREADS" in
     ;;
  posix | pthreads)
     THREADS=posix
-    THREADDLLIBS=-lpthread
+    AC_CHECK_LIB(pthread, pthread_self, THREADDLLIBS="-lpthread",,)
     case "$host" in
      x86-*-linux* | ia64-*-linux* | i386-*-linux* | i486-*-linux* | i586-*-linux* | i686-*-linux* | x86_64-*-linux* | alpha*-*-linux* | s390*-*-linux* | sparc*-*-linux* | powerpc-*-linux*)
        AC_DEFINE(GC_LINUX_THREADS)
index 0c85c00572953ec063036bb3dbdcf0a641f3ad28..7e60fe790f53931eb85e99611c71f86a0a02757a 100644 (file)
@@ -89,6 +89,9 @@ void GC_push_all_stacks() {
 #elif defined(ARM)
   arm_thread_state_t state;
   mach_msg_type_number_t thread_state_count = ARM_THREAD_STATE_COUNT;
+#elif defined(X86_64)
+  x86_thread_state64_t state;
+  mach_msg_type_number_t thread_state_count = x86_THREAD_STATE64_COUNT;
 #else
 # error FIXME for non-x86 || ppc architectures
   mach_msg_type_number_t thread_state_count = MACHINE_THREAD_STATE_COUNT;
@@ -109,7 +112,7 @@ void GC_push_all_stacks() {
                             GC_MACH_THREAD_STATE_FLAVOR,
                             (natural_t*)&state,
                             &thread_state_count);
-       if(r != KERN_SUCCESS) ABORT("thread_get_state failed");
+       if(r != KERN_SUCCESS) continue;
        
 #if defined(I386)
 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
@@ -134,6 +137,29 @@ void GC_push_all_stacks() {
        GC_push_one(state.esi); 
        GC_push_one(state.ebp); 
 #endif
+#elif defined(X86_64)
+          lo = state.__rsp;
+          GC_push_one(state.__rax);
+          GC_push_one(state.__rbx);
+          GC_push_one(state.__rcx);
+          GC_push_one(state.__rdx);
+          GC_push_one(state.__rdi);
+          GC_push_one(state.__rsi);
+          GC_push_one(state.__rbp);
+          GC_push_one(state.__rsp);
+          GC_push_one(state.__r8);
+          GC_push_one(state.__r9);
+          GC_push_one(state.__r10);
+          GC_push_one(state.__r11);
+          GC_push_one(state.__r12);
+          GC_push_one(state.__r13);
+          GC_push_one(state.__r14);
+          GC_push_one(state.__r15);
+          GC_push_one(state.__rip);
+          GC_push_one(state.__rflags);
+          GC_push_one(state.__cs);
+          GC_push_one(state.__fs);
+          GC_push_one(state.__gs);
 #elif defined(POWERPC)
 #if defined(_STRUCT_PPC_EXCEPTION_STATE)
        lo = (void*)(state.__r1 - PPC_RED_ZONE_SIZE);
index 860195c857f07c7aaf9ed6f6c5c43cccf3807794..10ffed637556ea6f90622b0e06e26b33eca7105f 100644 (file)
 #    define mach_type_known
 #    define DARWIN_DONT_PARSE_STACK
 #    define GC_DONT_REGISTER_MAIN_STATIC_DATA
+#   elif defined(__x86_64)
+#    define X86_64
+#    define mach_type_known
 #   endif
 # endif
 # if defined(NeXT) && defined(mc68000)
 #           if defined(__GLIBC__)&& __GLIBC__>=2
 #              define SEARCH_FOR_DATA_START
 #           else /* !GLIBC2 */
+#              if defined(PLATFORM_ANDROID)
+#                      define __environ environ
+#              endif
                extern char **__environ;
 #              define DATASTART ((ptr_t)(&__environ))
                              /* hideous kludge: __environ is the first */
 #          define PREFETCH_FOR_WRITE(x) __builtin_prefetch((x), 1)
 #      endif
 #   endif
+#   ifdef DARWIN
+#     define OS_TYPE "DARWIN"
+#     define DARWIN_DONT_PARSE_STACK
+#     define DYNAMIC_LOADING
+      /* XXX: see get_end(3), get_etext() and get_end() should not be used.
+         These aren't used when dyld support is enabled (it is by default) */
+#     define DATASTART ((ptr_t) get_etext())
+#     define DATAEND    ((ptr_t) get_end())
+#     define STACKBOTTOM ((ptr_t) 0x7fff5fc00000)
+#     ifndef USE_MMAP
+#       define USE_MMAP
+#     endif
+#     define USE_MMAP_ANON
+#     ifdef GC_DARWIN_THREADS
+#       define MPROTECT_VDB
+#     endif
+#     include <unistd.h>
+#     define GETPAGESIZE() getpagesize()
+      /* There seems to be some issues with trylock hanging on darwin. This
+         should be looked into some more */
+#   endif
 #   ifdef FREEBSD
 #      define OS_TYPE "FREEBSD"
 #      ifndef GC_FREEBSD_THREADS
index e0a3ab437ab7bcbcb984b1cad0e89389aa19b822..f5feb5061a7f65e996baf49f07ff971bd3daf3bf 100644 (file)
@@ -1,3 +1,19 @@
+2010-04-23  Miguel de Icaza  <miguel@novell.com>
+
+       * mono.1: Sort environment variables, update a couple of docs.
+
+2010-04-07  Andrés G. Aragoneses  <andres@lindenlab.com>
+
+       * monolinker.1: Fix typo.
+
+2010-04-01  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * mono.1: Document the new "security" option for logging
+
+2010-03-26  Zoltan Varga  <vargaz@gmail.com>
+
+       * mono.1: Document the MONO_ENABLE_SHM env variable.
+
 2010-03-03  Rolf Bjarne Kvinge  <RKvinge@novell.com>
 
        * mono.1: Document exception tracing.
index ea99ab88a703c647f55b1e62bdf61efc244be39f..dca52985d3f8ae37990c73bec38295cd4c88ca05 100644 (file)
@@ -237,6 +237,14 @@ collection a bit.
 \fB--help\fR, \fB-h\fR
 Displays usage instructions.
 .TP
+\fB--llvm\fR
+If the Mono runtime has been compiled with LLVM support (not available
+in all configurations), Mono will use the LLVM optimization and code
+generation engine to JIT or AOT compile.     You can also use the
+\fBMONO_USE_LLVM\fR environment variable to turn this on
+.Sp
+For more information, consult: http://www.mono-project.com/Mono_LLVM
+.TP
 \fB--optimize=MODE\fR, \fB-O=MODE\fR
 MODE is a comma separated list of optimizations.  They also allow
 optimizations to be turned off by prefixing the optimization name with
@@ -1131,7 +1139,8 @@ Use the
 environment variable to limit the extent of the messages you get: 
 If set, the log mask is changed to the set value. Possible values are
 "asm" (assembly loader), "type", "dll" (native library loader), "gc"
-(garbage collector), "cfg" (config file loader), "aot" (precompiler) and "all". 
+(garbage collector), "cfg" (config file loader), "aot" (precompiler),
+"security" (e.g. Moonlight CoreCLR support) and "all". 
 The default value is "all". Changing the mask value allows you to display only 
 messages for a certain component. You can use multiple masks by comma 
 separating them. For example to see config file messages and assembly loader
@@ -1186,6 +1195,16 @@ If set, this variable will instruct Mono to ahead-of-time compile new
 assemblies on demand and store the result into a cache in
 ~/.mono/aot-cache. 
 .TP
+\fBMONO_ASPNET_INHIBIT_SETTINGSMAP\fR
+Mono contains a feature which allows modifying settings in the .config files shipped
+with Mono by using config section mappers. The mappers and the mapping rules are
+defined in the $prefix/etc/mono/2.0/settings.map file and, optionally, in the
+settings.map file found in the top-level directory of your ASP.NET application.
+Both files are read by System.Web on application startup, if they are found at the
+above locations. If you don't want the mapping to be performed you can set this
+variable in your environment before starting the application and no action will
+be taken.
+.TP
 \fBMONO_CFG_DIR\fR
 If set, this variable overrides the default system configuration directory
 ($PREFIX/etc). It's used to locate machine.config file.
@@ -1201,61 +1220,21 @@ If set, this variable overrides the default runtime configuration file
 ($PREFIX/etc/mono/config). The --config command line options overrides the
 environment variable.
 .TP
-\fBMONO_DEBUG\fR
-If set, enables some features of the runtime useful for debugging.
-This variable should contain a comma separated list of debugging options.
-Currently, the following options are supported:
-.RS
-.ne 8
-.TP
-\fBbreak-on-unverified\fR
-If this variable is set, when the Mono VM runs into a verification
-problem, instead of throwing an exception it will break into the
-debugger.  This is useful when debugging verifier problems
-.TP
-\fBcollect-pagefault-stats\fR
-Collects information about pagefaults.   This is used internally to
-track the number of page faults produced to load metadata.  To display
-this information you must use this option with "--stats" command line
-option.
-.TP
-\fBdont-free-domains\fR
-This is an Optimization for multi-AppDomain applications (most
-commonly ASP.NET applications).  Due to internal limitations Mono,
-Mono by default does not use typed allocations on multi-appDomain
-applications as they could leak memory when a domain is unloaded. 
-.Sp
-Although this is a fine default, for applications that use more than
-on AppDomain heavily (for example, ASP.NET applications) it is worth
-trading off the small leaks for the increased performance
-(additionally, since ASP.NET applications are not likely going to
-unload the application domains on production systems, it is worth
-using this feature). 
-.TP
-\fBhandle-sigint\fR
-Captures the interrupt signal (Control-C) and displays a stack trace
-when pressed.  Useful to find out where the program is executing at a
-given point.  This only displays the stack trace of a single thread. 
-.TP
-\fBkeep-delegates\fR
-This option will leak delegate trampolines that are no longer
-referenced as to present the user with more information about a
-delegate misuse.  Basically a delegate instance might be created,
-passed to unmanaged code, and no references kept in managed code,
-which will garbage collect the code.  With this option it is possible
-to track down the source of the problems. 
-.TP
-\fBno-gdb-backtrace\fR
-This option will disable the GDB backtrace emitted by the runtime
-after a SIGSEGV or SIGABRT in unmanaged code.
-.TP
-\fBsuspend-on-sigsegv\fR
+\fBMONO_CPU_ARCH\fR
+Override the automatic cpu detection mechanism. Currently used only on arm.
+The format of the value is as follows:
+.nf
 
-This option will suspend the program when a native SIGSEGV is received.
-This is useful for debugging crashes which do not happen under gdb,
-since a live process contains more information than a core file.
-.ne
-.RE
+       "armvV [thumb]"
+
+.fi
+where V is the architecture number 4, 5, 6, 7 and the options can be currently be
+"thunb". Example:
+.nf
+
+       MONO_CPU_ARCH="armv4 thumb" mono ...
+
+.fi
 .TP
 \fBMONO_DISABLE_AIO\fR
 If set, tells mono NOT to attempt using native asynchronous I/O services. In
@@ -1269,11 +1248,28 @@ internally disables managed collation functionality invoked via the
 members of System.Globalization.CompareInfo class. Collation is
 enabled by default.
 .TP
+\fBMONO_DISABLE_SHM\fR
+Unix only: If set, disables the shared memory files used for
+cross-process handles: process have only private handles.  This means
+that process and thread handles are not available to other processes,
+and named mutexes, named events and named semaphores are not visible
+between processes.
+.Sp
+This is can also be enabled by default by passing the
+"--disable-shared-handles" option to configure.
+.Sp
+This is the default from mono 2.8 onwards.
+.TP
 \fBMONO_EGD_SOCKET\fR
 For platforms that do not otherwise have a way of obtaining random bytes
 this can be set to the name of a file system socket on which an egd or
 prngd daemon is listening.
 .TP
+\fBMONO_ENABLE_SHM\fR
+Unix only: Enable support for cross-process handles.  Cross-process
+handles are used to expose process handles, thread handles, named
+mutexes, named events and named semaphores across Unix processes.
+.TP
 \fBMONO_EVENTLOG_TYPE\fR
 Sets the type of event log provider to use (for System.Diagnostics.EventLog).
 .Sp
@@ -1393,10 +1389,24 @@ managed implementation (slow). If unset, mono will try to use inotify, FAM,
 Gamin, kevent under Unix systems and native API calls on Windows, falling 
 back to the managed implementation on error.
 .TP
+\fBMONO_MESSAGING_PROVIDER\fR
+Mono supports a plugin model for its implementation of System.Messaging making
+it possible to support a variety of messaging implementations (e.g. AMQP, ActiveMQ).
+To specify which messaging implementation is to be used the evironement variable
+needs to be set to the full class name for the provider.  E.g. to use the RabbitMQ based
+AMQP implementation the variable should be set to:
+
+.nf
+Mono.Messaging.RabbitMQ.RabbitMQMessagingProvider,Mono.Messaging.RabbitMQ
+.TP
 \fBMONO_NO_SMP\fR
 If set causes the mono process to be bound to a single processor. This may be
 useful when debugging or working around race conditions.
 .TP
+\fBMONO_NO_TLS\fR
+Disable inlining of thread local accesses. Try setting this if you get a segfault
+early on in the execution of mono.
+.TP
 \fBMONO_PATH\fR
 Provides a search path to the runtime where to look for library
 files.   This is a tool convenient for debugging applications, but
@@ -1430,26 +1440,6 @@ For example:
 
        MONO_RTC=4096 mono --profiler=default:stat program.exe
 
-.fi
-.TP
-\fBMONO_NO_TLS\fR
-Disable inlining of thread local accesses. Try setting this if you get a segfault
-early on in the execution of mono.
-.TP
-\fBMONO_CPU_ARCH\fR
-Override the automatic cpu detection mechanism. Currently used only on arm.
-The format of the value is as follows:
-.nf
-
-       "armvV [thumb]"
-
-.fi
-where V is the architecture number 4, 5, 6, 7 and the options can be currently be
-"thunb". Example:
-.nf
-
-       MONO_CPU_ARCH="armv4 thumb" mono ...
-
 .fi
 .TP 
 \fBMONO_SHARED_DIR\fR
@@ -1472,16 +1462,6 @@ home directories that might be shared over the network.
 If set, extra checks are made during IO operations.  Currently, this
 includes only advisory locks around file writes.
 .TP
-\fBMONO_DISABLE_SHM\fR
-If set, disables the shared memory files used for cross-process
-handles: process have only private handles.  This means that process
-and thread handles are not available to other processes, and named
-mutexes, named events and named semaphores are not visible between
-processes.
-.Sp
-This is can also be enabled by default by passing the
-"--disable-shared-handles" option to configure.
-.TP
 \fBMONO_THEME\fR
 The name of the theme to be used by Windows.Forms.   Available themes today
 include "clearlooks", "nice" and "win32".
@@ -1501,6 +1481,13 @@ The maximum number of threads in the general threadpool will be
 20 + (MONO_THREADS_PER_CPU * number of CPUs). The default value for this
 variable is 10.
 .TP
+\fBMONO_USE_LLVM\fR
+If the Mono runtime has been compiled with LLVM support (not available
+in all configurations), Mono will use the LLVM optimization and code
+generation engine to JIT or AOT compile.     This is equivalent to
+using the \-\-llvm command line option, but is useful for global
+configurations. 
+.TP
 \fBMONO_XMLSERIALIZER_THS\fR
 Controls the threshold for the XmlSerializer to produce a custom
 serializer for a given class instead of using the Reflection-based
@@ -1508,31 +1495,6 @@ interpreter.  The possible values are `no' to disable the use of a
 custom serializer or a number to indicate when the XmlSerializer
 should start serializing.   The default value is 50, which means that
 the a custom serializer will be produced on the 50th use.
-.TP
-\fBMONO_XMLSERIALIZER_DEBUG\fR
-Set this value to 1 to prevent the serializer from removing the
-temporary files that are created for fast serialization;  This might
-be useful when debugging.
-.TP
-\fBMONO_ASPNET_INHIBIT_SETTINGSMAP\fR
-Mono contains a feature which allows modifying settings in the .config files shipped
-with Mono by using config section mappers. The mappers and the mapping rules are
-defined in the $prefix/etc/mono/2.0/settings.map file and, optionally, in the
-settings.map file found in the top-level directory of your ASP.NET application.
-Both files are read by System.Web on application startup, if they are found at the
-above locations. If you don't want the mapping to be performed you can set this
-variable in your environment before starting the application and no action will
-be taken.
-.TP
-\fBMONO_MESSAGING_PROVIDER\fR
-Mono supports a plugin model for its implementation of System.Messaging making
-it possible to support a variety of messaging implementations (e.g. AMQP, ActiveMQ).
-To specify which messaging implementation is to be used the evironement variable
-needs to be set to the full class name for the provider.  E.g. to use the RabbitMQ based
-AMQP implementation the variable should be set to:
-
-.nf
-Mono.Messaging.RabbitMQ.RabbitMQMessagingProvider,Mono.Messaging.RabbitMQ
 .SH ENVIRONMENT VARIABLES FOR DEBUGGING
 .TP
 \fBMONO_ASPNET_NODELETE\fR
@@ -1540,6 +1502,62 @@ If set to any value, temporary source files generated by ASP.NET support
 classes will not be removed. They will be kept in the user's temporary
 directory.
 .TP
+\fBMONO_DEBUG\fR
+If set, enables some features of the runtime useful for debugging.
+This variable should contain a comma separated list of debugging options.
+Currently, the following options are supported:
+.RS
+.ne 8
+.TP
+\fBbreak-on-unverified\fR
+If this variable is set, when the Mono VM runs into a verification
+problem, instead of throwing an exception it will break into the
+debugger.  This is useful when debugging verifier problems
+.TP
+\fBcollect-pagefault-stats\fR
+Collects information about pagefaults.   This is used internally to
+track the number of page faults produced to load metadata.  To display
+this information you must use this option with "--stats" command line
+option.
+.TP
+\fBdont-free-domains\fR
+This is an Optimization for multi-AppDomain applications (most
+commonly ASP.NET applications).  Due to internal limitations Mono,
+Mono by default does not use typed allocations on multi-appDomain
+applications as they could leak memory when a domain is unloaded. 
+.Sp
+Although this is a fine default, for applications that use more than
+on AppDomain heavily (for example, ASP.NET applications) it is worth
+trading off the small leaks for the increased performance
+(additionally, since ASP.NET applications are not likely going to
+unload the application domains on production systems, it is worth
+using this feature). 
+.TP
+\fBhandle-sigint\fR
+Captures the interrupt signal (Control-C) and displays a stack trace
+when pressed.  Useful to find out where the program is executing at a
+given point.  This only displays the stack trace of a single thread. 
+.TP
+\fBkeep-delegates\fR
+This option will leak delegate trampolines that are no longer
+referenced as to present the user with more information about a
+delegate misuse.  Basically a delegate instance might be created,
+passed to unmanaged code, and no references kept in managed code,
+which will garbage collect the code.  With this option it is possible
+to track down the source of the problems. 
+.TP
+\fBno-gdb-backtrace\fR
+This option will disable the GDB backtrace emitted by the runtime
+after a SIGSEGV or SIGABRT in unmanaged code.
+.TP
+\fBsuspend-on-sigsegv\fR
+
+This option will suspend the program when a native SIGSEGV is received.
+This is useful for debugging crashes which do not happen under gdb,
+since a live process contains more information than a core file.
+.ne
+.RE
+.TP
 \fBMONO_LOG_LEVEL\fR
 The logging level, possible values are `error', `critical', `warning',
 `message', `info' and `debug'.  See the DEBUGGING section for more
@@ -1549,7 +1567,8 @@ details.
 Controls the domain of the Mono runtime that logging will apply to. 
 If set, the log mask is changed to the set value. Possible values are
 "asm" (assembly loader), "type", "dll" (native library loader), "gc"
-(garbage collector), "cfg" (config file loader), "aot" (precompiler) and "all". 
+(garbage collector), "cfg" (config file loader), "aot" (precompiler),
+"security" (e.g. Moonlight CoreCLR support) and "all". 
 The default value is "all". Changing the mask value allows you to display only 
 messages for a certain component. You can use multiple masks by comma 
 separating them. For example to see config file messages and assembly loader
@@ -1584,6 +1603,11 @@ information.
 This throws an exception when a X11 error is encountered; by default a
 message is displayed but execution continues
 .TP
+\fBMONO_XMLSERIALIZER_DEBUG\fR
+Set this value to 1 to prevent the serializer from removing the
+temporary files that are created for fast serialization;  This might
+be useful when debugging.
+.TP
 \fBMONO_XSYNC\fR
 This is used in the System.Windows.Forms implementation when running
 with the X11 backend.  This is used to debug problems in Windows.Forms
index ed207770aa96b2a02be77d5b0fc2d26a90fb3f40..f8baa8b38199a7171e2bb25740964dc7651ff295 100644 (file)
@@ -142,7 +142,7 @@ is necessary for this assembly to run.
 use a .info xml file as a source for the linker.
 .Sp
 An info file is a file produced by the tool mono-api-info. The linker will use it to
-generate an assembly that contains only what the public API defined in he info file
+generate an assembly that contains only what the public API defined in the info file
 needs.
 .TP
 .I "-s [StepBefore:]StepFullName,StepAssembly[:StepAfter]"
index 2d7df2093ed1fc59f2b590327a27d2900794b9ce..fa913978dc0ea59b7c8ab6b61dab70331f43d1fe 100644 (file)
@@ -9,6 +9,9 @@ monop, monop2 \- Mono Class Outline Viewer
 .I \-r:assembly
 Specifies the assembly to use for looking up the type
 .TP
+.I \-a
+Renders all of the types in the specified assembly.
+.TP
 .I \-\-search, \-s, \-k
 Searches through all known assemblies for types containing `class'.
 .TP
index e4e31b255d435219d05397a30479a7dad97561a4..3111e81a8d643265b464ce0ea8be332afd6c3084 100644 (file)
@@ -1,3 +1,11 @@
+2010-04-03  Ankit Jain  <jankit@novell.com>
+
+       * Makefile: Process tools/xbuild for 3.5 also.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * Makefile: rename the net_2_1 profile to moonlight.
+
 2010-03-03  Rolf Bjarne Kvinge  <RKvinge@novell.com>
 
        * Makefile: Make basic the bootstrapping profile for net_2_1_bootstrap.
index b30f44ec5df9b14914ef0d62b7ecb746c7c37c0e..3c04be99c3d083b017afd505be89e47c9648e85a 100644 (file)
@@ -5,12 +5,12 @@ SUBDIRS := build jay mcs class nunit24 ilasm tools tests errors docs
 basic_SUBDIRS := build jay mcs class tools
 net_2_0_bootstrap_SUBDIRS := build tools
 net_2_0_SUBDIRS := build mcs class nunit24 ilasm tools tests errors 
-net_2_1_bootstrap_SUBDIRS := build mcs class
-net_2_1_raw_SUBDIRS := build mcs class tools
-net_2_1_SUBDIRS := tools tests errors
+moonlight_bootstrap_SUBDIRS := build mcs class
+moonlight_raw_SUBDIRS := build mcs class tools
+moonlight_SUBDIRS := tools tests errors
 monotouch_SUBDIRS := build mcs class
 monotouch_bootstrap_SUBDIRS := build mcs class
-net_3_5_SUBDIRS := build class
+net_3_5_SUBDIRS := build class tools/xbuild
 net_4_0_bootstrap_SUBDIRS := build mcs class tools 
 net_4_0_SUBDIRS := build mcs class nunit24 ilasm tools tests errors docs
 
@@ -106,11 +106,11 @@ _boot_ = all clean install
 $(_boot_:%=profile-do--net_4_0--%):           profile-do--net_4_0--%:           profile-do--net_4_0_bootstrap--%
 $(_boot_:%=profile-do--net_4_0_bootstrap--%): profile-do--net_4_0_bootstrap--%: profile-do--net_2_0--%
 $(_boot_:%=profile-do--net_3_5--%):           profile-do--net_3_5--%:           profile-do--net_2_0--%
-$(_boot_:%=profile-do--net_2_1--%):           profile-do--net_2_1--%:           profile-do--net_2_1_raw--%
+$(_boot_:%=profile-do--moonlight--%):           profile-do--moonlight--%:           profile-do--moonlight_raw--%
 $(_boot_:%=profile-do--monotouch--%):         profile-do--monotouch--%:         profile-do--monotouch_bootstrap--%
 $(_boot_:%=profile-do--monotouch_bootstrap--%): profile-do--monotouch_bootstrap--%: profile-do--net_2_0--%
-$(_boot_:%=profile-do--net_2_1_raw--%):       profile-do--net_2_1_raw--%:       profile-do--net_2_1_bootstrap--%
-$(_boot_:%=profile-do--net_2_1_bootstrap--%): profile-do--net_2_1_bootstrap--%: profile-do--basic--%
+$(_boot_:%=profile-do--moonlight_raw--%):       profile-do--moonlight_raw--%:       profile-do--moonlight_bootstrap--%
+$(_boot_:%=profile-do--moonlight_bootstrap--%): profile-do--moonlight_bootstrap--%: profile-do--basic--%
 $(_boot_:%=profile-do--net_2_0--%):           profile-do--net_2_0--%:           profile-do--net_2_0_bootstrap--%
 $(_boot_:%=profile-do--net_2_0_bootstrap--%): profile-do--net_2_0_bootstrap--%: profile-do--basic--%
 
index 2b6610dd9757a85de2a4fa951255d17b98c3a7a1..c60dbb3aa179203a82add1a183ebef32ec3802b3 100644 (file)
@@ -1,3 +1,39 @@
+2010-04-16  Raja R Harinath  <harinath@hurrynot.org>
+
+       * profiles/net_4_0_bootstrap.make (PROFILE_MCS_HAS_BOOTSTRAP_FALLBACK):
+       New.  Can be set if we have BOOTSTRAP_PROFILE listed in the
+       MONO_PATH of MCS, and the profile's System.dll depends features
+       the profile's mscorlib.dll.
+
+2010-04-07  Raja R Harinath  <harinath@hurrynot.org>
+
+       * Makefile (DISTFILES): Add gensources.sh.
+       * gensources.sh: New, improved version of tools/gensources.sh.
+       * library.make ($(sourcefile)): Use the new gensources.sh.
+       ($(makefrag)): Update to handle the optional makefrag generated by
+       gensources.sh.
+
+2010-04-01  Zoltan Varga  <vargaz@gmail.com>
+
+       * config-default.make (LIBRARY_FLAGS): Applied patch from Laurent Etiemble
+       (laurent.etiemble@gmail.com). Use CFLAGS in the environment if defined.
+
+2010-03-31  Zoltan Varga  <vargaz@gmail.com>
+
+       * library.make ($(the_lib)$(PLATFORM_AOT_SUFFIX)): Pass --debug to the aot
+       compiler. Fixes #592545.
+
+2010-03-16  Jonathan Pryor  <jpryor@novell.com>
+
+       * library.make (MDOC_UP): Set MONO_PATH to find monodoc.dll.
+       * rules.make (MDOC): MONO_PATH needs to include 
+         $(topdir)/class/lib/net_2_0 so that monodoc.dll can be found.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * profiles/net_2_1_*.make: rename to moonlight_*.make and
+       define the MOONLIGHT symbol.
+
 2010-03-03  Jonathan Pryor <jpryor@novell.com>
 
        * library.make: Add the generated per-profile .source file to
index 08640a9f4acbd8fc1937a514e1ff6a3c496ff539..69721f73b689fbdff8d9c4bb0ef2d67cf4e4f1cc 100644 (file)
@@ -19,9 +19,9 @@ PROFILES = \
        basic \
        net_2_0_bootstrap \
        net_2_0 \
-       net_2_1_bootstrap \
-       net_2_1_raw \
-       net_2_1 \
+       moonlight_bootstrap \
+       moonlight_raw \
+       moonlight \
        net_3_5 \
        net_4_0_bootstrap \
        net_4_0 
@@ -40,6 +40,7 @@ DISTFILES = \
        corcompare.make                 \
        corcompare-api.xsl              \
        executable.make                 \
+       gensources.sh                   \
        library.make                    \
        nunit-summary.xsl               \
        rules.make                      \
index 6f4b0776438ed47ba37082d98506f3835d2c248a..df647834d2e0534f55626b413fd33898e574f1af 100644 (file)
@@ -1,3 +1,17 @@
+2010-04-16  Raja R Harinath  <harinath@hurrynot.org>
+
+       * basic-profile-check.cs: Add use of 'var' keyword.
+
+2010-04-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * Consts.cs.in : Add AssemblyWindowsBase, AssemblyPresentationCore_3_5
+         and AssemblyPresentationFramework_3_5.
+
+2010-04-06  Jb Evain  <jbevain@novell.com>
+
+       * Consts.cs.in: define Assembly_System_2_0 for TypeForwardedFrom
+       attributes in NET_4_0.
+
 2010-01-07  Sebastien Pouliot  <sebastien@ximian.com>
 
        * Consts.cs.in: Update FX version for SL3 latest released version
index 31750ed2f9c26e75b3df93f5d0ec91e277062eba..671043b9cd149ac63be0a839600b02d151ec9cf9 100644 (file)
@@ -41,7 +41,7 @@ static class Consts
 
 #if NET_4_0 || BOOTSTRAP_NET_4_0
        public const string FxVersion = "4.0.0.0";
-       public const string FxFileVersion = "4.0.21006.1";
+       public const string FxFileVersion = "4.0.30319.1";
        
        public const string VsVersion = "0.0.0.0"; // Useless ?
        public const string VsFileVersion = "10.0.0.0"; // TODO:
@@ -103,9 +103,13 @@ static class Consts
        public const string AssemblySystem_Web = "System.Web, Version=" + FxVersion + ", Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
        public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=" + FxVersion + ", Culture=neutral, PublicKeyToken=b77a5c561934e089";
 #if NET_4_0 || BOOTSTRAP_NET_4_0
+       public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
        public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
        public const string AssemblySystem_Core = "System.Core, Version=" + FxVersion + ", Culture=neutral, PublicKeyToken=b77a5c561934e089";
        public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";
+       public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
+       public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
+       public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
 #elif NET_2_1
        public const string AssemblySystem_Core = "System.Core, Version=" + FxVersion + ", Culture=neutral, PublicKeyToken=b77a5c561934e089";
 #elif NET_2_0
index dd104e32fa3fd67a3ac0c01570564eef25368490..a945efb220d98bea5a64edf335bbc048f17315e1 100644 (file)
@@ -1,6 +1,10 @@
 class X {
        // Check installed compiler
-       static void Generic<T> () { }
+       static void Generic<T> ()
+       {
+               // we use 'var' all around in the compiler sources
+               var x = new X ();
+       }
 
        static int Main ()
        {
index c556006cfc562e3b3149beb5690575e684a05da4..a6969592c55791c5f00906baf0121f9c08eb0577 100644 (file)
@@ -14,7 +14,9 @@ TEST_HARNESS = $(topdir)/class/lib/$(PROFILE)/nunit-console.exe
 MCS_FLAGS = $(PLATFORM_DEBUG_FLAGS)
 MBAS_FLAGS = $(PLATFORM_DEBUG_FLAGS)
 LIBRARY_FLAGS = /noconfig
+ifndef CFLAGS
 CFLAGS = -g -O2
+endif
 prefix = /usr/local
 exec_prefix = $(prefix)
 mono_libdir = $(exec_prefix)/lib
diff --git a/mcs/build/gensources.sh b/mcs/build/gensources.sh
new file mode 100644 (file)
index 0000000..61639e5
--- /dev/null
@@ -0,0 +1,49 @@
+#! /bin/sh
+
+outfile=$1
+incfile=$2
+excfile=$3
+
+process_includes_1() {
+    sed -e '/^[ \t]*$/d' -e '/^[ \t]*#/d' $1 > $2
+    if cmp -s $1 $2; then
+       false
+    else
+       sed -n 's,^[ \t]*#include ,,p' $1 |
+       while read inc; do
+           cat $inc >> $2
+           echo $outfile: $inc >> $outfile.makefrag
+           echo $inc: >> $outfile.makefrag
+       done
+    fi
+}
+
+process_includes() {
+    i=$1; o=$2; t=${2}.tmp
+    while process_includes_1 $i $o; do
+       mv $o $t
+       i=$t
+    done
+    rm -f $t
+}
+
+rm -f $outfile.makefrag
+
+process_includes $incfile $outfile.inc
+
+sort -u $outfile.inc > $outfile.inc_s
+rm -f $outfile.inc
+
+if test -z "$excfile"; then
+    mv $outfile.inc_s $outfile
+else
+    process_includes $excfile $outfile.exc
+
+    sort -u $outfile.exc > $outfile.exc_s
+    rm -f $outfile.exc
+
+    sort -m $outfile.inc_s $outfile.exc_s | uniq -u > $outfile
+    rm -f $outfile.inc_s $outfile.exc_s
+fi
+
+
index f5844153850f730857c12bbc8ac87999bac3d64c..7bf697ed1c7d09b90f46b735edb2ef41b1c5fc07 100644 (file)
 sourcefile = $(LIBRARY).sources
 
 # If the directory contains the per profile include file, generate list file.
-PROFILE_sources = $(PROFILE)_$(LIBRARY).sources
-ifeq ($(wildcard $(PROFILE_sources)), $(PROFILE_sources))
+PROFILE_sources := $(wildcard $(PROFILE)_$(LIBRARY).sources)
+ifdef PROFILE_sources
 PROFILE_excludes = $(wildcard $(PROFILE)_$(LIBRARY).exclude.sources)
-COMMON_sourcefile := $(sourcefile)
 sourcefile = $(depsdir)/$(PROFILE)_$(LIBRARY).sources
-$(sourcefile): $(PROFILE_sources) $(PROFILE_excludes) $(COMMON_sourcefile)
-       @echo Creating the per profile list $@ ...
-       $(topdir)/tools/gensources.sh $(PROFILE_sources) $(PROFILE_excludes) > $@
 library_CLEAN_FILES += $(sourcefile)
+
+# Note, gensources.sh can create a $(sourcefile).makefrag if it sees any '#include's
+# We don't include it in the dependencies since it isn't always created
+$(sourcefile): $(PROFILE_sources) $(PROFILE_excludes) $(topdir)/build/gensources.sh
+       @echo Creating the per profile list $@ ...
+       $(SHELL) $(topdir)/build/gensources.sh $@ $(PROFILE_sources) $(PROFILE_excludes)
 endif
 
 PLATFORM_excludes := $(wildcard $(LIBRARY).$(PLATFORM)-excludes)
@@ -32,7 +34,7 @@ endif
 
 ifndef response
 response = $(depsdir)/$(PROFILE)_$(LIBRARY).response
-library_CLEAN_FILES += $(response) $(LIBRARY).mdb $(BUILT_SOURCES)
+library_CLEAN_FILES += $(response)
 endif
 
 ifndef LIBRARY_NAME
@@ -45,13 +47,7 @@ else
 lib_dir = lib
 endif
 
-makefrag = $(depsdir)/$(PROFILE)_$(LIBRARY).makefrag
 the_libdir = $(topdir)/class/$(lib_dir)/$(PROFILE)/
-the_lib = $(the_libdir)$(LIBRARY_NAME)
-the_pdb = $(the_lib:.dll=.pdb)
-the_mdb = $(the_lib).mdb
-library_CLEAN_FILES += $(makefrag) $(the_lib) $(the_lib).so $(the_pdb) $(the_mdb)
-
 ifdef LIBRARY_NEEDS_POSTPROCESSING
 build_libdir = fixup/$(PROFILE)/
 else
@@ -62,8 +58,10 @@ build_libdir = $(the_libdir)
 endif
 endif
 
+the_lib   = $(the_libdir)$(LIBRARY_NAME)
 build_lib = $(build_libdir)$(LIBRARY_NAME)
-library_CLEAN_FILES += $(build_lib) $(build_lib:.dll=.pdb)
+library_CLEAN_FILES += $(the_lib)   $(the_lib).so   $(the_lib).mdb   $(the_lib:.dll=.pdb)
+library_CLEAN_FILES += $(build_lib) $(build_lib).so $(build_lib).mdb $(build_lib:.dll=.pdb)
 
 ifdef NO_SIGN_ASSEMBLY
 SN = :
@@ -211,6 +209,7 @@ LIBRARY_SNK = $(topdir)/class/mono.snk
 endif
 
 ifdef BUILT_SOURCES
+library_CLEAN_FILES += $(BUILT_SOURCES)
 ifeq (cat, $(PLATFORM_CHANGE_SEPARATOR_CMD))
 BUILT_SOURCES_cmdline = $(BUILT_SOURCES)
 else
@@ -237,7 +236,7 @@ endif
 ifdef PLATFORM_AOT_SUFFIX
 Q_AOT=$(if $(V),,@echo "AOT [$(PROFILE)] $(notdir $(@))";)
 $(the_lib)$(PLATFORM_AOT_SUFFIX): $(the_lib)
-       $(Q_AOT) MONO_PATH='$(the_libdir)' > $(PROFILE)_aot.log 2>&1 $(RUNTIME) --aot=bind-to-runtime-version $(the_lib)
+       $(Q_AOT) MONO_PATH='$(the_libdir)' > $(PROFILE)_aot.log 2>&1 $(RUNTIME) --aot=bind-to-runtime-version --debug $(the_lib)
 endif
 
 ifdef ENABLE_AOT
@@ -248,9 +247,15 @@ all-local: $(the_lib)$(PLATFORM_AOT_SUFFIX)
 endif
 endif
 
+makefrag = $(depsdir)/$(PROFILE)_$(LIBRARY).makefrag
+library_CLEAN_FILES += $(makefrag)
 $(makefrag): $(sourcefile)
        @echo Creating $@ ...
        @sed 's,^,$(build_lib): ,' $< >$@
+       @if test ! -f $(sourcefile).makefrag; then :; else \
+          cat $(sourcefile).makefrag >> $@ ; \
+          echo '$@: $(sourcefile).makefrag' >> $@; \
+          echo '$(sourcefile).makefrag:' >> $@; fi
 
 ifneq ($(response),$(sourcefile))
 $(response): $(sourcefile) $(PLATFORM_excludes)
@@ -276,6 +281,7 @@ $(makefrag) $(test_response) $(test_makefrag) $(btest_response) $(btest_makefrag
 
 Q_MDOC_UP=$(if $(V),,@echo "MDOC-UP [$(PROFILE)] $(notdir $(@))";)
 MDOC_UP  =$(Q_MDOC_UP) \
+               MONO_PATH="$(topdir)/class/lib/net_4_0$(PLATFORM_PATH_SEPARATOR)$(topdir)/class/lib/net_2_0$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" \
                $(RUNTIME) $(topdir)/tools/mdoc/mdoc.exe update --delete            \
                        -o Documentation/en $(the_lib)
 
index 1ac6af0ef583e1b1bf44e0fd925d04b161d45ce9..a280c2bf5136b39a3c1ee045cca75bc7de1f55f8 100644 (file)
@@ -6,6 +6,9 @@ BOOTSTRAP_PROFILE = net_2_0
 BOOTSTRAP_MCS = MONO_PATH="$(topdir)/class/lib/$(BOOTSTRAP_PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(INTERNAL_GMCS)
 MCS = MONO_PATH="$(topdir)/class/lib/$(PROFILE)$(PLATFORM_PATH_SEPARATOR)$(topdir)/class/lib/$(BOOTSTRAP_PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(INTERNAL_SMCS)
 
+# We can enable this if System.dll depends on features of the mscorlib.dll from this profile
+#PROFILE_MCS_HAS_BOOTSTRAP_FALLBACK = yes
+
 profile-check:
        @:
 
diff --git a/mcs/build/profiles/moonlight.make b/mcs/build/profiles/moonlight.make
new file mode 100644 (file)
index 0000000..f3aba43
--- /dev/null
@@ -0,0 +1,19 @@
+#! -*- makefile -*-
+
+my_runtime = $(RUNTIME) $(RUNTIME_FLAGS) --security=temporary-smcs-hack
+INTERNAL_SMCS = $(my_runtime) $(topdir)/class/lib/$(PROFILE)/smcs.exe
+
+BOOTSTRAP_PROFILE = moonlight_bootstrap
+
+BOOTSTRAP_MCS = MONO_PATH="$(topdir)/class/lib/$(BOOTSTRAP_PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(my_runtime) $(topdir)/class/lib/$(BOOTSTRAP_PROFILE)/smcs.exe
+MCS = MONO_PATH="$(topdir)/class/lib/$(PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(INTERNAL_SMCS)
+
+profile-check:
+       @:
+
+PROFILE_MCS_FLAGS = -d:NET_1_1 -d:NET_2_0 -d:NET_2_1 -d:MOONLIGHT
+FRAMEWORK_VERSION = 2.1
+NO_TEST = yes
+
+# the tuner takes care of the install
+NO_INSTALL = yes
diff --git a/mcs/build/profiles/moonlight_bootstrap.make b/mcs/build/profiles/moonlight_bootstrap.make
new file mode 100644 (file)
index 0000000..243fc65
--- /dev/null
@@ -0,0 +1,20 @@
+#! -*- makefile -*-
+
+INTERNAL_SMCS = $(RUNTIME) $(RUNTIME_FLAGS) --security=temporary-smcs-hack $(topdir)/class/lib/$(PROFILE)/smcs.exe
+
+BOOTSTRAP_PROFILE = basic
+BOOTSTRAP_MCS = MONO_PATH="$(topdir)/class/lib/$(BOOTSTRAP_PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(INTERNAL_GMCS)
+MCS = MONO_PATH="$(topdir)/class/lib/$(PROFILE)$(PLATFORM_PATH_SEPARATOR)$(topdir)/class/lib/$(BOOTSTRAP_PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(INTERNAL_SMCS)
+
+# We can enable this if System.dll depends new features of the mscorlib.dll from this profile
+#PROFILE_MCS_HAS_BOOTSTRAP_FALLBACK = yes
+
+profile-check:
+       @:
+
+PROFILE_MCS_FLAGS = -d:NET_1_1 -d:NET_2_0 -d:NET_2_1 -d:MOONLIGHT
+FRAMEWORK_VERSION = 2.1
+NO_TEST = yes
+
+# the tuner takes care of the install
+NO_INSTALL = yes
diff --git a/mcs/build/profiles/moonlight_raw.make b/mcs/build/profiles/moonlight_raw.make
new file mode 100644 (file)
index 0000000..f3aba43
--- /dev/null
@@ -0,0 +1,19 @@
+#! -*- makefile -*-
+
+my_runtime = $(RUNTIME) $(RUNTIME_FLAGS) --security=temporary-smcs-hack
+INTERNAL_SMCS = $(my_runtime) $(topdir)/class/lib/$(PROFILE)/smcs.exe
+
+BOOTSTRAP_PROFILE = moonlight_bootstrap
+
+BOOTSTRAP_MCS = MONO_PATH="$(topdir)/class/lib/$(BOOTSTRAP_PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(my_runtime) $(topdir)/class/lib/$(BOOTSTRAP_PROFILE)/smcs.exe
+MCS = MONO_PATH="$(topdir)/class/lib/$(PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(INTERNAL_SMCS)
+
+profile-check:
+       @:
+
+PROFILE_MCS_FLAGS = -d:NET_1_1 -d:NET_2_0 -d:NET_2_1 -d:MOONLIGHT
+FRAMEWORK_VERSION = 2.1
+NO_TEST = yes
+
+# the tuner takes care of the install
+NO_INSTALL = yes
diff --git a/mcs/build/profiles/net_2_1.make b/mcs/build/profiles/net_2_1.make
deleted file mode 100644 (file)
index f6a58a5..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-#! -*- makefile -*-
-
-my_runtime = $(RUNTIME) $(RUNTIME_FLAGS) --security=temporary-smcs-hack
-INTERNAL_SMCS = $(my_runtime) $(topdir)/class/lib/$(PROFILE)/smcs.exe
-
-BOOTSTRAP_PROFILE = net_2_1_bootstrap
-
-BOOTSTRAP_MCS = MONO_PATH="$(topdir)/class/lib/$(BOOTSTRAP_PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(my_runtime) $(topdir)/class/lib/$(BOOTSTRAP_PROFILE)/smcs.exe
-MCS = MONO_PATH="$(topdir)/class/lib/$(PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(INTERNAL_SMCS)
-
-profile-check:
-       @:
-
-PROFILE_MCS_FLAGS = -d:NET_1_1 -d:NET_2_0 -d:NET_2_1
-FRAMEWORK_VERSION = 2.1
-NO_TEST = yes
-
-# the tuner takes care of the install
-NO_INSTALL = yes
diff --git a/mcs/build/profiles/net_2_1_bootstrap.make b/mcs/build/profiles/net_2_1_bootstrap.make
deleted file mode 100644 (file)
index 230c391..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-#! -*- makefile -*-
-
-INTERNAL_SMCS = $(RUNTIME) $(RUNTIME_FLAGS) --security=temporary-smcs-hack $(topdir)/class/lib/$(PROFILE)/smcs.exe
-
-BOOTSTRAP_PROFILE = basic
-BOOTSTRAP_MCS = MONO_PATH="$(topdir)/class/lib/$(BOOTSTRAP_PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(INTERNAL_GMCS)
-MCS = MONO_PATH="$(topdir)/class/lib/$(PROFILE)$(PLATFORM_PATH_SEPARATOR)$(topdir)/class/lib/$(BOOTSTRAP_PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(INTERNAL_SMCS)
-
-profile-check:
-       @:
-
-PROFILE_MCS_FLAGS = -d:NET_1_1 -d:NET_2_0 -d:NET_2_1
-FRAMEWORK_VERSION = 2.1
-NO_TEST = yes
-
-# the tuner takes care of the install
-NO_INSTALL = yes
diff --git a/mcs/build/profiles/net_2_1_raw.make b/mcs/build/profiles/net_2_1_raw.make
deleted file mode 100644 (file)
index f6a58a5..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-#! -*- makefile -*-
-
-my_runtime = $(RUNTIME) $(RUNTIME_FLAGS) --security=temporary-smcs-hack
-INTERNAL_SMCS = $(my_runtime) $(topdir)/class/lib/$(PROFILE)/smcs.exe
-
-BOOTSTRAP_PROFILE = net_2_1_bootstrap
-
-BOOTSTRAP_MCS = MONO_PATH="$(topdir)/class/lib/$(BOOTSTRAP_PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(my_runtime) $(topdir)/class/lib/$(BOOTSTRAP_PROFILE)/smcs.exe
-MCS = MONO_PATH="$(topdir)/class/lib/$(PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(INTERNAL_SMCS)
-
-profile-check:
-       @:
-
-PROFILE_MCS_FLAGS = -d:NET_1_1 -d:NET_2_0 -d:NET_2_1
-FRAMEWORK_VERSION = 2.1
-NO_TEST = yes
-
-# the tuner takes care of the install
-NO_INSTALL = yes
index 77645a18d0b70e5aa655ee2a2fba8405aad39cd4..d74036604ebe6cc4a08157df0d27b99ad68476b7 100644 (file)
@@ -4,6 +4,9 @@ BOOTSTRAP_PROFILE = net_2_0
 BOOTSTRAP_MCS = MONO_PATH="$(topdir)/class/lib/$(BOOTSTRAP_PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(RUNTIME) $(RUNTIME_FLAGS) $(topdir)/class/lib/$(BOOTSTRAP_PROFILE)/gmcs.exe
 MCS = MONO_PATH="$(topdir)/class/lib/$(PROFILE)$(PLATFORM_PATH_SEPARATOR)$(topdir)/class/lib/$(BOOTSTRAP_PROFILE)$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(RUNTIME) $(RUNTIME_FLAGS) $(topdir)/class/lib/$(PROFILE)/dmcs.exe
 
+# we have BOOTSTRAP_PROFILE listed in the MONO_PATH of MCS
+PROFILE_MCS_HAS_BOOTSTRAP_FALLBACK = yes
+
 profile-check: 
 
 PROFILE_MCS_FLAGS = -d:NET_1_1 -d:NET_2_0 -d:BOOTSTRAP_NET_4_0
index 5f34ce865d55eab56848a58982c5eacadee95fd5..08bdc227483efca89eb25b519de2b92253c0a5fe 100644 (file)
@@ -205,5 +205,6 @@ withmcs:
 ## Documentation stuff
 
 Q_MDOC =$(if $(V),,@echo "MDOC    [$(PROFILE)] $(notdir $(@))";)
-MDOC   =$(Q_MDOC) MONO_PATH="$(topdir)/class/lib/net_4_0$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" $(RUNTIME) $(topdir)/tools/mdoc/mdoc.exe
+MDOC   =$(Q_MDOC) MONO_PATH="$(topdir)/class/lib/net_4_0$(PLATFORM_PATH_SEPARATOR)$(topdir)/class/lib/net_2_0$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH" \
+       $(RUNTIME) $(topdir)/tools/mdoc/mdoc.exe
 
index 44fb1d7a4a41078b7d7ba0abb72af8754a444f30..c0362ed44eed20b8d8b7065b408e4db7d2eed8dc 100644 (file)
@@ -1,3 +1,25 @@
+2010-04-14  Ankit Jain  <jankit@novell.com>
+
+       * Makefile: Add Moonlight.Build.Tasks to net_2_0_dirs and
+       net_3_5_dirs.
+       * Moonlight.Build.Tasks: New.
+
+2010-04-08  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * Makefile : add 4.0 System.Xaml.
+
+2010-03-16  Rolf Bjarne Kvinge  <RKvinge@novell.com>
+
+       * Makefile: Add System.Xml.Serialization to the Moonlight build.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * Makefile: rename the net_2_1 profile to moonlight.
+
+2010-03-15  Marek Habersack  <mhabersack@novell.com>
+
+       * Makefile (net_2_0_dirs): added System.Web.Mvc2
+
 2010-03-11  Atsushi Enomoto  <atsushi@ximian.com>
 
        * Makefile : build Sys.Json after Sys.SM.Web.
index c61e7fee1321e501a47da195ebc9402d1ea79476..f776bd9af586a24051c0681d9055446c676a52e4 100644 (file)
@@ -106,12 +106,14 @@ net_2_0_dirs := \
        System.Web.DynamicData          \
        System.ServiceModel.Web         \
        System.Web.Mvc                  \
+       System.Web.Mvc2                 \
        Mono.C5                         \
        Mono.Management                 \
        Mono.Options                    \
        Mono.Simd                       \
        Mono.Tasklets                   \
        Mono.CSharp                     \
+       Moonlight.Build.Tasks           \
        WindowsBase                     \
        System.Data.Services
 
@@ -119,7 +121,7 @@ net_2_0_only_dirs := \
        System.Web.Extensions_1.0       \
        System.Web.Extensions.Design_1.0
 
-net_2_1_dirs := \
+moonlight_dirs := \
        corlib                  \
        Mono.CompilerServices.SymbolWriter \
        System.Core             \
@@ -127,6 +129,7 @@ net_2_1_dirs := \
        System.XML              \
        System.Net              \
        System.Xml.Linq \
+       System.Xml.Serialization        \
        System.Runtime.Serialization    \
        System.ServiceModel     \
        System.ServiceModel.Web
@@ -157,6 +160,7 @@ net_3_5_dirs := \
        Microsoft.Build.Utilities       \
        Microsoft.Build.Engine          \
        Microsoft.Build.Tasks           \
+       Moonlight.Build.Tasks           \
        System.Web.Extensions.Design    
 
 net_4_0_dirs := \
@@ -165,12 +169,14 @@ net_4_0_dirs := \
        Microsoft.CSharp        \
        System.Windows.Forms.DataVisualization  \
        System.ComponentModel.Composition \
-       System.ServiceModel.Routing
+       System.Xaml \
+       System.ServiceModel.Routing \
+       System.Runtime.Caching
 
 net_2_0_bootstrap_SUBDIRS := $(bootstrap_dirs)
 net_2_0_SUBDIRS := $(common_dirs) $(net_2_0_dirs) $(net_2_0_only_dirs)
-net_2_1_bootstrap_SUBDIRS := corlib System Mono.CompilerServices.SymbolWriter System.Core
-net_2_1_raw_SUBDIRS := $(net_2_1_dirs)
+moonlight_bootstrap_SUBDIRS := corlib System Mono.CompilerServices.SymbolWriter System.Core
+moonlight_raw_SUBDIRS := $(moonlight_dirs)
 monotouch_bootstrap_SUBDIRS := corlib System Mono.CompilerServices.SymbolWriter System.Core
 monotouch_SUBDIRS := $(monotouch_dirs)
 net_3_5_SUBDIRS := $(net_3_5_dirs)
@@ -179,7 +185,7 @@ net_4_0_SUBDIRS := $(common_dirs) $(net_2_0_dirs) $(net_4_0_dirs)
 
 include ../build/rules.make
 
-SUBDIRS = $(common_dirs) $(net_2_0_dirs) $(net_2_0_only_dirs) $(net_2_1_dirs) $(net_3_5_dirs) $(net_4_0_dirs)
+SUBDIRS = $(common_dirs) $(net_2_0_dirs) $(net_2_0_only_dirs) $(moonlight_dirs) $(monotouch_dirs) $(net_3_5_dirs) $(net_4_0_dirs)
 
 DIST_ONLY_SUBDIRS = dlr
 
index 4b8a485f504aa7496c55f311c2956151836c7c11..828cca2da532065a5b2732450b472e04915e4a49 100644 (file)
@@ -1,3 +1,125 @@
+2010-04-27  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * ToolStripSplitButton.cs:
+       * ToolStripDropDownItem.cs:
+       * ToolStripMenuItem.cs: Update overrides.
+       * ToolStripItem.cs: Pass the number of clicks to HandleClick when
+       firing OnMouseUp, so we can later fire either OnClick or
+       OnDoubleClick.
+
+       Fixes #558632.
+
+2010-04-26  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * RichTextBox.cs: When emitting the complete RTF value escape chars
+       above 0x80, at .Net seems to do. This way we are able to make
+       round-trip assignations between the setter and getter of the
+       RichTextBox.Rtf property.
+       Fixes part of #586901.
+
+2010-04-26  Ivan Zlatev  <ivan@ivanz.com>
+
+       * DataGridView.cs: Handle all possible cases for when a new column is 
+       added and there are existing rows with existing cells both in the 
+       non-databound and the databound scenario.
+       [Fixes bug #583387]
+
+2010-04-26  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * XplatUIX11.cs: When retrieving data from the x11 clipboard and we
+       are using either XA_STRING or OEMTEXT try to detect if we have escaped
+       unicode chars, and unescape them as needed. This us used by some
+       (gnome) applications to pass unicode chars in a non-unicode context.
+       Fixes #596402.
+
+2010-04-25  Ivan Zlatev  <ivan@ivanz.com>
+
+       * DataGridViewCellCollection.cs, DataGridView.cs: 
+       Ensure column cell templates are properly applied.
+       [Fixes bug #583404]
+
+2010-04-24  Ivan Zlatev  <ivan@ivanz.com>
+
+       * DataGridViewColumnCollection.cs: When adding a column also 
+       set the DisplayIndex if its now set by the user already.
+       [Fixes bug #583387]
+
+2010-04-19  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * NotifyIcon.cs: Make BalloonWindow expose the owner's Handle.
+       * Theme.cs:
+       * ThemeWin32Classic.cs: Add a HideBalloonWindow method to force to
+       close an active balloon window.
+       * XplatUIX11.cs: When removing from the system tray try to close
+       the balloon window. This is important when we hide a NotifyIcon and
+       thus need to close its related balloon window as well.
+       Fixes bits of #590093.
+
+2010-04-19  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * XplatUIX11.cs: When adding a NotifyIcon to the system tray, mark its
+       Hwnd.mapped as true, since its handle is going to be mapped later by
+       the tray (not us), but we need to know it's alive and can later properly unmap
+       it.
+       Fixes part of #590093.
+
+2010-04-16  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TreeNodeCollection.cs: When adding/inserting/setting a new node call
+       TreeView.Sort if needed, and update/recalculate this entire
+       collection in that case.
+       * TreeView.cs: Make 'sorted' internal, instead of directly using
+       Sorted, as this one could trigger a complete Sort() operation.
+
+2010-04-14  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TreeView.cs: We must use the comparer supplied by TreeViewNodeSorter
+       *always*, since it is used recursively, so checking for a number of
+       top level nodes is useless. This should fix a case where we were not
+       sorting any node with a single root node.
+
+2010-04-14  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * DataGridView.cs: Call the base Paint impl last, instead of do that
+       at the beginning, to let handlers draw on top of us. 
+       Fixes the remaining bits of #587563.
+
+2010-04-14  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * ToolStripItem.cs: Separate the background rendering from the Paint
+       routine, so we can both make sure the background stuff is done first,
+       and we also let our items fire the OnPaint event handlers before or
+       after their own routines.
+       * ToolStripLabel.cs: Move the base call to OnPaint to the end, so any
+       user's Paint handler can draw on top of us, like .Net does.
+       Fixes #587563.
+
+2010-04-13  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * XplatUIX11.cs: When checking for the values returned by
+       _NET_WORKAREA, use current_desktop+1 instead of current_desktop, since
+       we need the actual value, instead of the index (which is 0 based, and
+       is not working in this case). Patch by Andy Stühr
+       (andysmuell@hammerhartes.de).
+       Fixes #494234.
+
+2010-04-04  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * ToolTip.cs: Make TipState internal.
+       * ToolStrip.cs: Use the same idea of ToolTip'state to have our
+       internal timer close the tooltip window after a delay, instead of
+       waiting for the mouse to move to a different item. Also, hide the
+       tooltip window when the handle is destroyed, and also when the control
+       is getting hidden.
+       Fixes #581273.
+
+2010-03-31  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * ListView.cs: Selection should be available after the first time the
+       handle has been created, even if later the handle is destroyed or
+       temporary invalidated.
+       Fixes #584070.
+
 2010-03-01  Carlos Alberto Cortez <calberto.cortez@gmail.com>
 
        * TreeView.cs: When receiving a double click on a node, toggle it only
index a583d7cb3a8b13043e2587f14faa165cba606df8..6e811bfe84bbc930753ad9b6a8f889cfbb3f4a01 100644 (file)
@@ -3794,8 +3794,16 @@ namespace System.Windows.Forms {
                                //
                                if (!is_autogenerating_columns && columns.Count == 1)
                                        ReBind ();
-                               foreach (DataGridViewRow row in Rows)
-                                       row.Cells.Add ((DataGridViewCell)e.Column.CellTemplate.Clone ());
+
+                               foreach (DataGridViewRow row in Rows) {
+                                       DataGridViewCell newCell = (DataGridViewCell)e.Column.CellTemplate.Clone ();
+                                       if (row.Cells.Count == columns.Count)
+                                               row.Cells.Replace (e.Column.Index, newCell);
+                                       else if (e.Column.Index >= row.Cells.Count)
+                                               row.Cells.Add (newCell);
+                                       else
+                                               row.Cells.Insert (e.Column.Index, newCell);
+                               }
                        }
                        
                        e.Column.DataColumnIndex = FindDataColumnIndex (e.Column);
@@ -4675,8 +4683,6 @@ namespace System.Windows.Forms {
 
                protected override void OnPaint (PaintEventArgs e)
                {
-                       base.OnPaint(e);
-
                        Graphics g = e.Graphics;
                        Rectangle bounds = ClientRectangle;
                        
@@ -4783,6 +4789,9 @@ namespace System.Windows.Forms {
                                        ControlPaint.DrawBorder3D (g, bounds, Border3DStyle.Sunken);
                                        break;
                        }
+
+                       // Call the base impl at the end.
+                       base.OnPaint(e);
                }
 
                private void RefreshScrollBars ()
index 7574f286599b85fa3ac7dbd289c25de5ba62f9b5..eacce0b0ef570ddea8a7e0add028ad6e312e45a2 100644 (file)
@@ -123,6 +123,12 @@ namespace System.Windows.Forms
                        return result;
                }
 
+               internal void Replace (int columnIndex, DataGridViewCell dataGridViewCell)
+               {
+                       RemoveAt (columnIndex);
+                       Insert (columnIndex, dataGridViewCell);
+               }
+
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                public virtual void AddRange (params DataGridViewCell[] dataGridViewCells)
                {
index b7b3295acbaebae2f78d81c64fe8be45eb9d3edd..159714b9e058ec8deba1e39373de1f3a036157e3 100644 (file)
@@ -184,6 +184,11 @@ namespace System.Windows.Forms {
                        }
                }
 
+               internal int DisplayIndexInternal {
+                       get { return DisplayIndex; }
+                       set { displayIndex = value; }
+               }
+
                internal int DataColumnIndex {
                        get { return dataColumnIndex; }
                        set { dataColumnIndex = value; }
index cf5b7929c2706739e5fe1af41425f84aa0f3a146..29bc09dd61e6b10435045430b548972cc9ee85b7 100644 (file)
@@ -78,6 +78,8 @@ namespace System.Windows.Forms
                public virtual int Add (DataGridViewColumn dataGridViewColumn)
                {
                        int result = base.List.Add(dataGridViewColumn);
+                       if (dataGridViewColumn.DisplayIndex == -1)
+                               dataGridViewColumn.DisplayIndexInternal = result;
                        dataGridViewColumn.SetIndex(result);
                        dataGridViewColumn.SetDataGridView(dataGridView);
                        OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, dataGridViewColumn));
@@ -188,6 +190,8 @@ namespace System.Windows.Forms
                public virtual void Insert (int columnIndex, DataGridViewColumn dataGridViewColumn)
                {
                        base.List.Insert (columnIndex, dataGridViewColumn);
+                       if (dataGridViewColumn.DisplayIndex == -1)
+                               dataGridViewColumn.DisplayIndexInternal = columnIndex;
                        dataGridViewColumn.SetIndex (columnIndex);
                        dataGridViewColumn.SetDataGridView (dataGridView);
                        OnCollectionChanged (new CollectionChangeEventArgs (CollectionChangeAction.Add, dataGridViewColumn));
@@ -253,9 +257,8 @@ namespace System.Windows.Forms
                        List<DataGridViewColumn> result = new List<DataGridViewColumn> (array);
 
                        result.Sort (new ColumnDisplayIndexComparator ());
-                       
                        for (int i = 0; i < result.Count; i++)
-                               result[i].DisplayIndex = i;
+                               result[i].DisplayIndexInternal = i;
                        
                        display_index_sorted = result;
                }
@@ -271,7 +274,12 @@ namespace System.Windows.Forms
                {
                        public int Compare (DataGridViewColumn o1, DataGridViewColumn o2)
                        {
-                               return o1.DisplayIndex - o2.DisplayIndex;
+                               if (o1.DisplayIndex == o2.DisplayIndex)
+                                       // Here we avoid the equal value swapping that both Array.Sort and ArrayList.Sort 
+                                       // do occasionally and preserve the user column insertation order.
+                                       return 1;
+                               else
+                                       return o1.DisplayIndex - o2.DisplayIndex;
                        }
                }
        }
index 10e19812c62e1f55d17700c696e7d1e5db96c83d..6a981d6c96390f7c9876d8ce9be4ddf87646c23c 100644 (file)
@@ -113,6 +113,9 @@ namespace System.Windows.Forms
                private int virtual_list_size;
                private bool right_to_left_layout;
 #endif
+               // selection is available after the first time the handle is created, *even* if later
+               // the handle is either recreated or destroyed - so keep this info around.
+               private bool is_selection_available;
 
                // internal variables
                internal ImageList large_image_list;
@@ -1207,7 +1210,7 @@ namespace System.Windows.Forms
 
                internal void OnSelectedIndexChanged ()
                {
-                       if (IsHandleCreated)
+                       if (is_selection_available)
                                OnSelectedIndexChanged (EventArgs.Empty);
                }
 
@@ -3506,6 +3509,7 @@ namespace System.Windows.Forms
                protected override void CreateHandle ()
                {
                        base.CreateHandle ();
+                       is_selection_available = true;
                        for (int i = 0; i < SelectedItems.Count; i++)
                                OnSelectedIndexChanged (EventArgs.Empty);
                }
@@ -5901,7 +5905,7 @@ namespace System.Windows.Forms
                        [Browsable (false)]
                        public int Count {
                                get {
-                                       if (!owner.IsHandleCreated)
+                                       if (!owner.is_selection_available)
                                                return 0;
 
                                        return List.Count;
@@ -5920,7 +5924,7 @@ namespace System.Windows.Forms
 
                        public int this [int index] {
                                get {
-                                       if (!owner.IsHandleCreated || index < 0 || index >= List.Count)
+                                       if (!owner.is_selection_available || index < 0 || index >= List.Count)
                                                throw new ArgumentOutOfRangeException ("index");
 
                                        return (int) List [index];
@@ -5958,12 +5962,12 @@ namespace System.Windows.Forms
                                if (itemIndex < 0 || itemIndex >= owner.Items.Count)
                                        throw new ArgumentOutOfRangeException ("index");
 
-                               if (owner.virtual_mode && !owner.IsHandleCreated)
+                               if (owner.virtual_mode && !owner.is_selection_available)
                                        return -1;
 
                                owner.Items [itemIndex].Selected = true;
 
-                               if (!owner.IsHandleCreated)
+                               if (!owner.is_selection_available)
                                        return 0;
 
                                return List.Count;
@@ -5977,7 +5981,7 @@ namespace System.Windows.Forms
 #endif 
                        void Clear ()
                        {
-                               if (!owner.IsHandleCreated)
+                               if (!owner.is_selection_available)
                                        return;
 
                                int [] indexes = (int []) List.ToArray (typeof (int));
@@ -6041,7 +6045,7 @@ namespace System.Windows.Forms
 
                        public int IndexOf (int selectedIndex)
                        {
-                               if (!owner.IsHandleCreated)
+                               if (!owner.is_selection_available)
                                        return -1;
 
                                return List.IndexOf (selectedIndex);
@@ -6145,7 +6149,7 @@ namespace System.Windows.Forms
 
                        public ListViewItem this [int index] {
                                get {
-                                       if (!owner.IsHandleCreated || index < 0 || index >= Count)
+                                       if (!owner.is_selection_available || index < 0 || index >= Count)
                                                throw new ArgumentOutOfRangeException ("index");
 
                                        int item_index = owner.SelectedIndices [index];
@@ -6203,7 +6207,7 @@ namespace System.Windows.Forms
 
                        public void CopyTo (Array dest, int index)
                        {
-                               if (!owner.IsHandleCreated)
+                               if (!owner.is_selection_available)
                                        return;
                                if (index > Count) // Throws ArgumentException instead of IOOR exception
                                        throw new ArgumentException ("index");
@@ -6214,7 +6218,7 @@ namespace System.Windows.Forms
 
                        public IEnumerator GetEnumerator ()
                        {
-                               if (!owner.IsHandleCreated)
+                               if (!owner.is_selection_available)
                                        return (new ListViewItem [0]).GetEnumerator ();
 
                                ListViewItem [] items = new ListViewItem [Count];
@@ -6260,7 +6264,7 @@ namespace System.Windows.Forms
 
                        public int IndexOf (ListViewItem item)
                        {
-                               if (!owner.IsHandleCreated)
+                               if (!owner.is_selection_available)
                                        return -1;
 
                                for (int i = 0; i < Count; i++)
@@ -6273,7 +6277,7 @@ namespace System.Windows.Forms
 #if NET_2_0
                        public virtual int IndexOfKey (string key)
                        {
-                               if (!owner.IsHandleCreated || key == null || key.Length == 0)
+                               if (!owner.is_selection_available || key == null || key.Length == 0)
                                        return -1;
 
                                for (int i = 0; i < Count; i++) {
index b45922574f143bcb1d63a473a6b9987c5111b51e..0a71465d76203471c8177cd359090bdac832d63f 100644 (file)
@@ -263,6 +263,12 @@ namespace System.Windows.Forms {
                                timer.Enabled = false;
                                timer.Tick += new EventHandler (HandleTimer);
                        }
+
+                       public IntPtr OwnerHandle {
+                               get {
+                                       return owner;
+                               }
+                       }
                        
                        protected override void Dispose (bool disposing)
                        {
index f9842135226e02bf22bcaed859cffdaf56a1e837..1db7f29a519e0819d7696faeb9cff1a41f001da9 100644 (file)
@@ -1950,12 +1950,12 @@ namespace System.Windows.Forms {
 
                static readonly char [] ReservedRTFChars = new char [] { '\\', '{', '}' };
 
-               [MonoInternalNote ("Emit unicode and other special characters properly")]
                private void EmitRTFText(StringBuilder rtf, string text) {
                        int start = rtf.Length;
                        int count = text.Length;
 
-                       rtf.Append(text);
+                       // First emit simple unicode chars as escaped
+                       EmitEscapedUnicode (rtf, text);
 
                        // This method emits user text *only*, so it's safe to escape any reserved rtf chars
                        // Escape '\' first, since it is used later to escape the other chars
@@ -1966,6 +1966,39 @@ namespace System.Windows.Forms {
                        }
                }
 
+               // The chars to be escaped use "\'" + its hexadecimal value.
+               private void EmitEscapedUnicode (StringBuilder sb, string text)
+               {
+                       int pos;
+                       int start = 0;
+
+                       while ((pos = IndexOfNonAscii (text, start)) > -1) {
+                               sb.Append (text, start, pos - start);
+
+                               int n = (int)text [pos];
+                               sb.Append ("\\'");
+                               sb.Append (n.ToString ("X"));
+
+                               start = pos + 1;
+                       }
+
+                       // Append remaining (maybe all) the text value.
+                       if (start < text.Length)
+                               sb.Append (text, start, text.Length - start);
+               }
+
+               // MS seems to be escaping values larger than 0x80
+               private int IndexOfNonAscii (string text, int startIndex)
+               {
+                       for (int i = startIndex; i < text.Length; i++) {
+                               int n = (int)text [i];
+                               if (n < 0 || n >= 0x80)
+                                       return i;
+                       }
+
+                       return -1;
+               }
+
                // start_pos and end_pos are 0-based
                private StringBuilder GenerateRTF(Line start_line, int start_pos, Line end_line, int end_pos) {
                        StringBuilder   sb;
index 599ae0f33b220e7af9f83020ee188b2a931d30c6..e4154e726f197b2595dc28fa8aa0a2ce69a34da2 100644 (file)
@@ -984,6 +984,7 @@ namespace System.Windows.Forms
                #region BalloonWindow
 #if NET_2_0
                public abstract void ShowBalloonWindow (IntPtr handle, int timeout, string title, string text, ToolTipIcon icon);
+               public abstract void HideBalloonWindow (IntPtr handle);
                public abstract void DrawBalloonWindow (Graphics dc, Rectangle clip, NotifyIcon.BalloonWindow control);
                public abstract Rectangle BalloonWindowRect (NotifyIcon.BalloonWindow control);
 #endif
index 0bd84de71b09e1912187f74a8a3ba8434eaac026..42a533043ed860e3d9b2ec27a95307eb9278703e 100644 (file)
@@ -5529,6 +5529,16 @@ namespace System.Windows.Forms
                        balloon_window.Show ();
                }
 
+               public override void HideBalloonWindow (IntPtr handle)
+               {
+                       if (balloon_window == null || balloon_window.OwnerHandle != handle)
+                               return;
+
+                       balloon_window.Close ();
+                       balloon_window.Dispose ();
+                       balloon_window = null;
+               }
+
                private const int balloon_iconsize = 16;
                private const int balloon_bordersize = 8; 
                
index fd6500af68ce3900d8aa4dc977fa125b3e256e7f..d6dc5f19e5e51b0fd54aa0dcd294437062d1a644 100644 (file)
@@ -79,6 +79,10 @@ namespace System.Windows.Forms
                private ToolStripItem mouse_currently_over;
                internal bool menu_selected;
                private ToolStripItem tooltip_currently_showing;
+               private ToolTip.TipState tooltip_state;
+
+               const int InitialToolTipDelay = 500;
+               const int ToolTipDelay = 5000;
                #endregion
 
                #region Public Constructors
@@ -723,6 +727,7 @@ namespace System.Windows.Forms
                protected override void Dispose (bool disposing)
                {
                        if (!IsDisposed) {
+                               CloseToolTip (null);
                                // ToolStripItem.Dispose modifes the collection,
                                // so we iterate it in reverse order
                                for (int i = Items.Count - 1; i >= 0; i--)
@@ -1060,6 +1065,9 @@ namespace System.Windows.Forms
 
                protected override void OnVisibleChanged (EventArgs e)
                {
+                       if (!Visible)
+                               CloseToolTip (null);
+
                        base.OnVisibleChanged (e);
                }
 
@@ -1597,24 +1605,32 @@ namespace System.Windows.Forms
                private void MouseEnteredItem (ToolStripItem item)
                {
                        if (this.show_item_tool_tips && !(item is ToolStripTextBox)) {
+                               ToolTipTimer.Interval = InitialToolTipDelay;
+                               tooltip_state = ToolTip.TipState.Initial;
                                tooltip_currently_showing = item;
                                ToolTipTimer.Start ();
                        }
                }
-               
-               private void MouseLeftItem (ToolStripItem item)
+       
+               private void CloseToolTip (ToolStripItem item)
                {
                        ToolTipTimer.Stop ();
                        ToolTipWindow.Hide (this);
                        tooltip_currently_showing = null;
+                       tooltip_state = ToolTip.TipState.Down;
                }
-               
+
+               private void MouseLeftItem (ToolStripItem item)
+               {
+                       CloseToolTip (item);
+               }
+
                private Timer ToolTipTimer {
                        get {
                                if (tooltip_timer == null) {
                                        tooltip_timer = new Timer ();
                                        tooltip_timer.Enabled = false;
-                                       tooltip_timer.Interval = 500;
+                                       tooltip_timer.Interval = InitialToolTipDelay;
                                        tooltip_timer.Tick += new EventHandler (ToolTipTimer_Tick);
                                }
                                
@@ -1631,16 +1647,32 @@ namespace System.Windows.Forms
                        }
                }
                
-               private void ToolTipTimer_Tick (object o, EventArgs args)
+               private void ShowToolTip ()
                {
                        string tooltip = tooltip_currently_showing.GetToolTip ();
                        
-                       if (!string.IsNullOrEmpty (tooltip))
+                       if (!string.IsNullOrEmpty (tooltip)) {
                                ToolTipWindow.Present (this, tooltip);
+                               ToolTipTimer.Interval = ToolTipDelay;
+                               ToolTipTimer.Start ();
+                               tooltip_state = ToolTip.TipState.Show;
+                       }
 
                        tooltip_currently_showing.FireEvent (EventArgs.Empty, ToolStripItemEventType.MouseHover);
+               }
 
+               private void ToolTipTimer_Tick (object o, EventArgs args)
+               {
                        ToolTipTimer.Stop ();
+
+                       switch (tooltip_state) {
+                               case ToolTip.TipState.Initial:
+                                       ShowToolTip ();
+                                       break;
+                               case ToolTip.TipState.Show:
+                                       CloseToolTip (null);
+                                       break;
+                       }
                }
                #endregion
 
index 5465739ab1ecb14dc7965b857f5814bb701b1b69..3d9a76c2bfb0ae3e38dc6a5f66eaf56664c954cc 100644 (file)
@@ -322,7 +322,7 @@ namespace System.Windows.Forms
                        base.Dismiss (reason);
                }
 
-               internal override void HandleClick (EventArgs e)
+               internal override void HandleClick (int mouse_clicks, EventArgs e)
                {
                        OnClick (e);
                }
index 9ccbff040017da4677c19f249113d7748b754cb7..3e5e051e1f6e1a02f5388643b3fd9c2157a3ffac 100644 (file)
@@ -1015,9 +1015,6 @@ namespace System.Windows.Forms
                        EventHandler eh = (EventHandler)(Events [DoubleClickEvent]);
                        if (eh != null)
                                eh (this, e);
-
-                       if (!double_click_enabled)
-                               OnClick (e);
                }
 
                [EditorBrowsable (EditorBrowsableState.Advanced)]
@@ -1178,12 +1175,18 @@ namespace System.Windows.Forms
                        this.CalculateAutoSize ();
                        OnFontChanged (EventArgs.Empty);
                }
-               
-               protected virtual void OnPaint (PaintEventArgs e)
+
+               void OnPaintInternal (PaintEventArgs e)
                {
+                       // Have the background rendered independently from OnPaint
                        if (this.parent != null)
                                this.parent.Renderer.DrawItemBackground (new ToolStripItemRenderEventArgs (e.Graphics, this));
-                               
+
+                       OnPaint (e);
+               }
+
+               protected virtual void OnPaint (PaintEventArgs e)
+               {
                        PaintEventHandler eh = (PaintEventHandler)(Events [PaintEvent]);
                        if (eh != null)
                                eh (this, e);
@@ -1773,7 +1776,7 @@ namespace System.Windows.Forms
                                
                        switch (met) {
                                case ToolStripItemEventType.MouseUp:
-                                       this.HandleClick (e);
+                                       this.HandleClick (((MouseEventArgs)e).Clicks, e);
                                        this.OnMouseUp ((MouseEventArgs)e);
                                        break;
                                case ToolStripItemEventType.MouseDown:
@@ -1792,18 +1795,21 @@ namespace System.Windows.Forms
                                        this.OnMouseMove ((MouseEventArgs)e);
                                        break;
                                case ToolStripItemEventType.Paint:
-                                       this.OnPaint ((PaintEventArgs)e);
+                                       this.OnPaintInternal ((PaintEventArgs)e);
                                        break;
                                case ToolStripItemEventType.Click:
-                                       this.HandleClick (e);
+                                       this.HandleClick (1, e);
                                        break;
                        }
                }
                
-               internal virtual void HandleClick (EventArgs e)
+               internal virtual void HandleClick (int mouse_clicks, EventArgs e)
                {
                        this.Parent.HandleItemClick (this);
-                       this.OnClick (e);
+                       if (mouse_clicks == 2 && double_click_enabled)
+                               this.OnDoubleClick (e);
+                       else
+                               this.OnClick (e);
                }
                
                internal virtual void SetPlacement (ToolStripItemPlacement placement)
index ff4524fa3ae8e25933458e5733a50ce2aac45db1..59c73bd053242190d0dd43785f7f1c5f52d5a037 100644 (file)
@@ -193,8 +193,6 @@ namespace System.Windows.Forms
                
                protected override void OnPaint (System.Windows.Forms.PaintEventArgs e)
                {
-                       base.OnPaint (e);
-
                        if (this.Owner != null) {
                                Color font_color = this.Enabled ? this.ForeColor : SystemColors.GrayText;
                                Image draw_image = this.Enabled ? this.Image : ToolStripRenderer.CreateDisabledImage (this.Image);
@@ -278,6 +276,9 @@ namespace System.Windows.Forms
                                        } else
                                                this.Owner.Renderer.DrawItemText (new System.Windows.Forms.ToolStripItemTextRenderEventArgs (e.Graphics, this, this.Text, text_layout_rect, font_color, this.Font, this.TextAlign));
                        }
+
+                       // call Paint handlers last.
+                       base.OnPaint (e);
                }
 
                protected internal override bool ProcessMnemonic (char charCode)
index de4a6ff17c56d70c46f5e1bf7df5e3e5f9313d84..326a3c81247288a6d9aa378a6e4464e8f78814b1 100644 (file)
@@ -534,7 +534,7 @@ namespace System.Windows.Forms
                        }
                }
 
-               internal override void HandleClick (EventArgs e)
+               internal override void HandleClick (int mouse_clicks, EventArgs e)
                {
                        this.OnClick (e);
                        
index 832fb2353633e83393d03a9b0d63e4169ddf0ba0..9737dc373671948f5741e110d771de98e33b2beb 100644 (file)
@@ -321,9 +321,9 @@ namespace System.Windows.Forms
                #endregion
 
                #region Internal Methods
-               internal override void HandleClick (EventArgs e)
+               internal override void HandleClick (int mouse_clicks, EventArgs e)
                {
-                       base.HandleClick (e);
+                       base.HandleClick (mouse_clicks, e);
 
                        MouseEventArgs mea = e as MouseEventArgs;
                        
index 1a1c4f51f6ebfed78705ca9ffcce17ef1f0ae9e6..a5d4a7fea118bf6232e8af7ebf8aa4236c905465 100644 (file)
@@ -803,7 +803,7 @@ namespace System.Windows.Forms {
 #endif
                #endregion      // Protected Instance Methods
 
-               enum TipState {
+               internal enum TipState {
                        Initial,
                        Show,
                        Down
index 318a0fcdb10e8907d9fd7784df682da13fd25341..007fb1ef029e4f426ad89f082548df2a0de34c21 100644 (file)
@@ -434,7 +434,14 @@ namespace System.Windows.Forms {
                                tree_view = owner.TreeView;
 
                        if (tree_view != null) {
-                               TreeNode prev = GetPrevNode (node);
+                               bool sorted = false;
+                               if (tree_view.Sorted || tree_view.TreeViewNodeSorter != null) {
+                                       owner.Nodes.Sort (tree_view.TreeViewNodeSorter);
+                                       tree_view.sorted = sorted = true;
+                               }
+
+                               // We may need to invalidate this entire node collection if sorted.
+                               TreeNode prev = sorted ? owner : GetPrevNode (node);
 
                                if (tree_view.IsHandleCreated && node.ArePreviousNodesExpanded)
                                        tree_view.RecalculateVisibleOrder (prev);
index 313d67f5b055360c95a0e2ddabfde17ef842ec17..be73ec2d400fdb058c7c9aac0bb51d83b86a38ba 100644 (file)
@@ -44,7 +44,7 @@ namespace System.Windows.Forms {
                #region Fields
                private string path_separator = "\\";
                private int item_height = -1;
-               private bool sorted;
+               internal bool sorted;
                internal TreeNode root_node;
                internal bool nodes_added;
                private TreeNodeCollection nodes;
@@ -751,7 +751,7 @@ namespace System.Windows.Forms {
 #if NET_2_0
                public  void Sort ()
                {
-                       Sort (Nodes.Count >= 2 ? tree_view_node_sorter : null);
+                       Sort (tree_view_node_sorter);
                }
 #endif
 
index 4b085346c10f3e0edf79a8c67b6a2f64728da6fd..78ae994a6a3d3d82d71c212bce8ecc5b484a5e40 100644 (file)
@@ -1252,13 +1252,15 @@ namespace System.Windows.Forms {
 
                        if ((long)nitems > 0) {
                                if (property == (IntPtr)Atom.XA_STRING) {
-                                       Clipboard.Item = Marshal.PtrToStringAnsi(prop);
+                                       // Some X managers/apps pass unicode chars as escaped strings, so
+                                       // we may need to unescape them.
+                                       Clipboard.Item = UnescapeUnicodeFromAnsi (Marshal.PtrToStringAnsi(prop));
                                } else if (property == (IntPtr)Atom.XA_BITMAP) {
                                        // FIXME - convert bitmap to image
                                } else if (property == (IntPtr)Atom.XA_PIXMAP) {
                                        // FIXME - convert pixmap to image
                                } else if (property == OEMTEXT) {
-                                       Clipboard.Item = Marshal.PtrToStringAnsi(prop);
+                                       Clipboard.Item = UnescapeUnicodeFromAnsi (Marshal.PtrToStringAnsi(prop));
                                } else if (property == UTF8_STRING) {
                                        byte [] buffer = new byte [(int)nitems];
                                        for (int i = 0; i < (int)nitems; i++)
@@ -1285,6 +1287,48 @@ namespace System.Windows.Forms {
                        }
                }
 
+               private string UnescapeUnicodeFromAnsi (string value)
+               {
+                       if (value == null || value.IndexOf ("\\u") == -1)
+                               return value;
+
+                       StringBuilder sb = new StringBuilder (value.Length);
+                       int start, pos;
+
+                       start = pos = 0;
+                       while (start < value.Length) {
+                               pos = value.IndexOf ("\\u", start);
+                               if (pos == -1)
+                                       break;
+
+                               sb.Append (value, start, pos - start);
+                               pos += 2;
+                               start = pos;
+
+                               int length = 0;
+                               while (pos < value.Length) {
+                                       if (!Char.IsLetterOrDigit (value [pos]))
+                                               break;
+                                       length++;
+                                       pos++;
+                               }
+
+                               int res;
+                               if (!Int32.TryParse (value.Substring (start, length), System.Globalization.NumberStyles.HexNumber, 
+                                                       null, out res))
+                                       return value; // Error, return the unescaped original value.
+                               
+                               sb.Append ((char)res);
+                               start = pos;
+                       }
+
+                       // Append any remaining data.
+                       if (start < value.Length)
+                               sb.Append (value, start, value.Length - start);
+
+                       return sb.ToString ();
+               }
+
                private void AddExpose (Hwnd hwnd, bool client, int x, int y, int width, int height) {
                        // Don't waste time
                        if ((hwnd == null) || (x > hwnd.Width) || (y > hwnd.Height) || ((x + width) < 0) || ((y + height) < 0)) {
@@ -2486,7 +2530,7 @@ namespace System.Windows.Forms {
                                XFree(prop);
 
                                XGetWindowProperty(DisplayHandle, RootWindow, _NET_WORKAREA, IntPtr.Zero, new IntPtr (256), false, (IntPtr)Atom.XA_CARDINAL, out actual_atom, out actual_format, out nitems, out bytes_after, ref prop);
-                               if ((long)nitems < 4 * current_desktop) {
+                               if ((long)nitems < 4 * (current_desktop + 1)) {
                                        goto failsafe;
                                }
 
@@ -6017,6 +6061,10 @@ namespace System.Windows.Forms {
                                                hwnd.Queue.Paint.Remove (hwnd);
                                }
 
+                               // We are going to be directly mapped by the system tray, so mark as mapped
+                               // so we can later properly unmap it.
+                               hwnd.mapped = true;
+
                                size_hints = new XSizeHints();
 
                                size_hints.flags = (IntPtr)(XSizeHintsFlags.PMinSize | XSizeHintsFlags.PMaxSize | XSizeHintsFlags.PBaseSize);
@@ -6082,6 +6130,10 @@ namespace System.Windows.Forms {
                                tt.Dispose();
                                tt = null;
                        }
+#if NET_2_0
+                       // Close any balloon window *we* fired.
+                       ThemeEngine.Current.HideBalloonWindow (handle);
+#endif
                }
 
 #if NET_2_0
index 1df2086be2485c13c86f39a249c2cfee6523a8ab..6dc092ebe8350c409b31627f72d92fe2f1818954 100644 (file)
@@ -1,3 +1,19 @@
+2010-04-24  Ivan Zlatev  <ivan@ivanz.com>
+
+       * DataGridViewColumnCollectionTest.cs: Add tests for bug #583387.
+
+2010-04-17  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TreeViewTest.cs: New test for Sorted and BeginUpdate interaction.
+
+2010-04-16  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TreeViewTest.cs: New test for automatical sorting.
+
+2010-04-14  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TreeViewTest.cs: New test for TreeViewNodeSorter used recursively.
+
 2010-01-18  Carlos Alberto Cortez <calberto.cortez@gmail.com>
 
        * RichTextBoxTest.cs: New test for the Modified property.
index aaf87d7db1eb270293e50d570cc7dcff9226a822..e239b5d76780bb58cc275ba7cbe27d19487b6820 100644 (file)
@@ -107,22 +107,31 @@ namespace MonoTests.System.Windows.Forms
 
                        dgv.Columns.Add ("A1", "A1");
                        Assert.AreEqual (0, dgv.Columns[0].Index, "A1");
+                       Assert.AreEqual (0, dgv.Columns[0].DisplayIndex, "B1");
 
                        dgv.Columns.Add ("A2", "A2");
                        Assert.AreEqual (0, dgv.Columns[0].Index, "A2");
+                       Assert.AreEqual (0, dgv.Columns[0].DisplayIndex, "B2");
                        Assert.AreEqual (1, dgv.Columns[1].Index, "A3");
+                       Assert.AreEqual (1, dgv.Columns[1].DisplayIndex, "B3");
 
                        dgv.Columns.Insert (0, new DataGridViewTextBoxColumn ());
                        Assert.AreEqual (0, dgv.Columns[0].Index, "A4");
+                       Assert.AreEqual (0, dgv.Columns[0].DisplayIndex, "B4");
                        Assert.AreEqual (1, dgv.Columns[1].Index, "A5");
+                       Assert.AreEqual (1, dgv.Columns[1].DisplayIndex, "B5");
                        Assert.AreEqual (2, dgv.Columns[2].Index, "A6");
+                       Assert.AreEqual (2, dgv.Columns[2].DisplayIndex, "B6");
 
                        dgv.Columns.RemoveAt (1);
                        Assert.AreEqual (0, dgv.Columns[0].Index, "A7");
+                       Assert.AreEqual (0, dgv.Columns[0].DisplayIndex, "B7");
                        Assert.AreEqual (1, dgv.Columns[1].Index, "A8");
+                       Assert.AreEqual (1, dgv.Columns[1].DisplayIndex, "B8");
 
                        dgv.Columns.RemoveAt (0);
                        Assert.AreEqual (0, dgv.Columns[0].Index, "A9");
+                       Assert.AreEqual (0, dgv.Columns[0].DisplayIndex, "B9");
 
                        f.Close ();
                        f.Dispose ();
index 838126fb33acb1a2f65492998e2fd98c3381cf58..27d4a2673700f70dd45b289c5f41692332dc8571 100644 (file)
@@ -330,6 +330,22 @@ namespace MonoTests.System.Windows.Forms
                        
                        Assert.AreEqual ("aaa", tv.Nodes[0].Text, "A1");
                }
+
+               [Test]
+               public void SortBeginUpdate ()
+               {
+                       TreeView tv = new TreeView ();
+                       tv.Sorted = true;
+                       tv.BeginUpdate ();
+                       tv.Nodes.Add ("x");
+                       tv.Nodes.Add ("f");
+                       tv.Nodes.Add ("a");
+
+                       // Even if BeginUpdate was called, Sort is called.
+                       Assert.AreEqual ("a", tv.Nodes [0].Text, "#A1");
+                       Assert.AreEqual ("f", tv.Nodes [1].Text, "#A2");
+                       Assert.AreEqual ("x", tv.Nodes [2].Text, "#A3");
+               }
 #endif
 
                [Test]
@@ -686,6 +702,124 @@ namespace MonoTests.System.Windows.Forms
                                return ((TreeNode)x).Text == "2" ? -1 : 1;
                        }
                }
+
+               [Test]
+               public void SortedRecursive ()
+               {
+                       TreeView tv = new TreeView ();
+                       tv.TreeViewNodeSorter = new InverseNodeSorter ();
+                       tv.BeginUpdate ();
+                       TreeNode root_node = tv.Nodes.Add ("Root");
+                       for (char c = 'a'; c <= 'f'; c++) {
+                               TreeNode node = new TreeNode (c.ToString ());
+                               for (int i = 0; i < 3; i++)
+                                       node.Nodes.Add (i.ToString ());
+
+                               root_node.Nodes.Add (node);
+                       }
+                       tv.EndUpdate ();
+
+                       // Make sure we are sorted
+                       tv.Sort ();
+
+                       Assert.AreEqual ("f", root_node.Nodes [0].Text, "#A1");
+                       Assert.AreEqual ("e", root_node.Nodes [1].Text, "#A2");
+                       Assert.AreEqual ("d", root_node.Nodes [2].Text, "#A3");
+                       Assert.AreEqual ("c", root_node.Nodes [3].Text, "#A4");
+                       Assert.AreEqual ("b", root_node.Nodes [4].Text, "#A5");
+                       Assert.AreEqual ("a", root_node.Nodes [5].Text, "#A5");
+
+                       foreach (TreeNode n in root_node.Nodes) {
+                               Assert.AreEqual ("2", n.Nodes [0].Text, "#B1");
+                               Assert.AreEqual ("1", n.Nodes [1].Text, "#B2");
+                               Assert.AreEqual ("0", n.Nodes [2].Text, "#B3");
+                       }
+               }
+
+               [Test]
+               public void SortedAutomatically ()
+               {
+                       TreeView tv = new TreeView ();
+                       tv.Nodes.Add ("z");
+                       tv.Nodes.Add ("a");
+                       tv.Nodes.Add ("c");
+
+                       // One way to sort them automatically is to set Sorted to true
+                       // and let the TreeView use the default comparer
+                       tv.Sorted = true;
+                       Assert.AreEqual ("a", tv.Nodes [0].Text, "#A1");
+                       Assert.AreEqual ("c", tv.Nodes [1].Text, "#A2");
+                       Assert.AreEqual ("z", tv.Nodes [2].Text, "#A3");
+                       Assert.AreEqual (true, tv.Sorted, "#A4");
+
+                       tv.Nodes.Add ("d");
+                       Assert.AreEqual ("a", tv.Nodes [0].Text, "#B1");
+                       Assert.AreEqual ("c", tv.Nodes [1].Text, "#B2");
+                       Assert.AreEqual ("d", tv.Nodes [2].Text, "#B3");
+                       Assert.AreEqual ("z", tv.Nodes [3].Text, "#B4");
+
+                       // Another way is to set TreeViewNodeSorter,
+                       // which will set Sorted to true automatically
+                       tv.Sorted = false;
+                       Assert.AreEqual (false, tv.Sorted, "#C0");
+
+                       tv.TreeViewNodeSorter = new InverseNodeSorter ();
+                       Assert.AreEqual ("z", tv.Nodes [0].Text, "#C1");
+                       Assert.AreEqual ("d", tv.Nodes [1].Text, "#C2");
+                       Assert.AreEqual ("c", tv.Nodes [2].Text, "#C3");
+                       Assert.AreEqual ("a", tv.Nodes [3].Text, "#C4");
+                       Assert.AreEqual (true, tv.Sorted, "#C5");
+
+                       tv.Nodes.Add ("i");
+                       Assert.AreEqual ("z", tv.Nodes [0].Text, "#D1");
+                       Assert.AreEqual ("i", tv.Nodes [1].Text, "#D2");
+                       Assert.AreEqual ("d", tv.Nodes [2].Text, "#D3");
+                       Assert.AreEqual ("c", tv.Nodes [3].Text, "#D4");
+                       Assert.AreEqual ("a", tv.Nodes [4].Text, "#D5");
+
+                       tv.Sorted = false;
+                       Assert.AreEqual (false, tv.Sorted, "#E0");
+
+                       // If we have set a TreeViewNodeSorter, 
+                       // it will sort the nodes automatically when adding/inserting a new one,
+                       // setting Sorted to true.
+                       tv.Nodes.Add ("f");
+                       Assert.AreEqual ("z", tv.Nodes [0].Text, "#E1");
+                       Assert.AreEqual ("i", tv.Nodes [1].Text, "#E2");
+                       Assert.AreEqual ("f", tv.Nodes [2].Text, "#E3");
+                       Assert.AreEqual ("d", tv.Nodes [3].Text, "#E4");
+                       Assert.AreEqual ("c", tv.Nodes [4].Text, "#E5");
+                       Assert.AreEqual ("a", tv.Nodes [5].Text, "#E6");
+                       Assert.AreEqual (true, tv.Sorted, "#E7");
+
+                       // After setting the node sorter to null and testing,
+                       // I'm curious about the interaction between Sort and Sorted.
+                       tv.TreeViewNodeSorter = null;
+                       Assert.AreEqual (null, tv.TreeViewNodeSorter, "#F1");
+                       Assert.AreEqual (true, tv.Sorted, "#F2");
+
+                       // Finally, no NodeSorter to automatically set Sorted to true
+                       tv.Sorted = false;
+                       Assert.AreEqual (false, tv.Sorted, "#F0");
+                       tv.Nodes.Add ("k");
+                       Assert.AreEqual ("z", tv.Nodes [0].Text, "#G1");
+                       Assert.AreEqual ("i", tv.Nodes [1].Text, "#G2");
+                       Assert.AreEqual ("f", tv.Nodes [2].Text, "#G3");
+                       Assert.AreEqual ("d", tv.Nodes [3].Text, "#G4");
+                       Assert.AreEqual ("c", tv.Nodes [4].Text, "#G5");
+                       Assert.AreEqual ("a", tv.Nodes [5].Text, "#G6");
+                       Assert.AreEqual ("k", tv.Nodes [6].Text, "#G7");
+               }
+
+               class InverseNodeSorter : IComparer
+               {
+                       public int Compare (object a, object b)
+                       {
+                               TreeNode node_a = (TreeNode)a;
+                               TreeNode node_b = (TreeNode)b;
+                               return String.Compare (node_b.Text, node_a.Text);
+                       }
+               }
        }
 #endif
 }
index 0052a5560ce6d1b85c54ba21978a49cd337e5849..11e68a370628fc9b45c384116563fe0157412d73 100644 (file)
@@ -1,3 +1,20 @@
+2010-04-06  Ankit Jain  <jankit@novell.com>
+
+       * Makefile (EXTRA_DISTFILES): Remove TestTasks.dll.config .
+
+2010-04-03  Ankit Jain  <jankit@novell.com>
+
+       * Makefile: Use the correct assembly name for MS.Build.Utilities*
+       for 3.5 and 4.0 profiles. Copy the .config files for the test
+       assembly.
+       Import tools/xbuild/xbuild_targets.make, which copies the target
+       and tasks file in the correct place, to allow running tests
+       with different toolsversion.
+       * Microsoft.Build.Engine.dll.sources: Add LogExtensions.cs,
+       Toolset.cs, ToolsetDefinitionLocations.cs and ToolsetCollection.cs .
+       * Test/test-config-file-net-3.5: New.
+       * Test/test-config-file-net-4.0: New.
+
 2010-02-19  Ankit Jain  <jankit@novell.com>
 
        * Microsoft.Build.Engine.dll.sources: Add ProjectLoadSettings.cs .
index d46bf87bf1378c9e1bd64edc5e9d27a7161757e7..07f9e6fc299ad34d16e4a4dd2cb0fd500595c58d 100644 (file)
@@ -11,23 +11,56 @@ NO_TEST = yes
 NO_SIGN_ASSEMBLY = yes
 endif
 
+ifeq (3.5, $(FRAMEWORK_VERSION))
+NAME_SUFFIX = .v3.5
+else
+ifeq (4.0, $(FRAMEWORK_VERSION))
+NAME_SUFFIX = .v4.0
+endif
+endif
+
 LIB_MCS_FLAGS = \
        /r:$(corlib)                            \
        /r:System.dll                           \
+       /r:System.Core.dll              \
        /r:System.Xml.dll                       \
        /r:Microsoft.Build.Framework.dll        \
-       /r:Microsoft.Build.Utilities.dll
+       /r:Microsoft.Build.Utilities$(NAME_SUFFIX).dll
 
 TEST_MCS_FLAGS = \
        /r:Microsoft.Build.Framework.dll        \
-       /r:Microsoft.Build.Utilities.dll
+       /r:Microsoft.Build.Utilities$(NAME_SUFFIX).dll
 
 EXTRA_DISTFILES = \\r
        Test/resources/TestTasks.cs             \\r
-       Test/resources/*.*proj
+       Test/resources/*.*proj  \
+       Test/test-config-file*
 
 Test/resources/TestTasks.dll: Test/resources/TestTasks.cs
-       $(CSCOMPILE) Test/resources/TestTasks.cs /r:Microsoft.Build.Framework.dll /r:Microsoft.Build.Utilities.dll /target:library
+       $(CSCOMPILE) Test/resources/TestTasks.cs /r:Microsoft.Build.Framework.dll /r:Microsoft.Build.Utilities$(NAME_SUFFIX).dll /target:library
+
+clean-local: clean-test-tasks
+
+clean-test-tasks:
+       rm -f Test/resources/TestTasks.dll      
+
+test-local: copy-config
+
+ifeq (net_4_0, $(PROFILE))
+copy-config:
+       cp Test/test-config-file-net-4.0 $(test_lib).config
+else
+ifeq (net_3_5, $(PROFILE))
+copy-config:
+       cp Test/test-config-file-net-3.5 $(test_lib).config
+else
+copy-config:
+endif
+endif
+
+export TESTING_MONO=a
+XBUILD_DIR=../../tools/xbuild
+include $(XBUILD_DIR)/xbuild_targets.make
 
 test-local: Test/resources/TestTasks.dll
 
index 0200f6f2a87fc9fb40900f3a78fd75bcefd4b219..1d48f9225010aadade0d0b31318024bfec47bca3 100644 (file)
@@ -32,7 +32,7 @@ using System.Collections;
 using Microsoft.Build.Framework;
 
 namespace Microsoft.Build.BuildEngine {
-       internal class BuildEngine : IBuildEngine {
+       internal class BuildEngine : IBuildEngine2 {
        
                Engine  engine;
                int     columnNumberOfTaskNode;
@@ -59,8 +59,17 @@ namespace Microsoft.Build.BuildEngine {
                                       string[] targetNames,
                                       IDictionary globalProperties,
                                       IDictionary targetOutputs)
+               {
+                       return BuildProjectFile (projectFileName, targetNames, globalProperties, targetOutputs, null);
+               }
+
+               public bool BuildProjectFile (string projectFileName,
+                                      string[] targetNames,
+                                      IDictionary globalProperties,
+                                      IDictionary targetOutputs, string toolsVersion)
                {
                        if (String.IsNullOrEmpty (projectFileName)) {
+                               project.ToolsVersion = toolsVersion;
                                return engine.BuildProject (project, targetNames, targetOutputs,
                                                BuildSettings.DoNotResetPreviouslyBuiltTargets);
                        } else {
@@ -71,10 +80,21 @@ namespace Microsoft.Build.BuildEngine {
                                                        (string) de.Key, (string) de.Value,
                                                        PropertyType.Global));
                                return engine.BuildProjectFile (projectFileName,
-                                       targetNames, bpg, targetOutputs, BuildSettings.DoNotResetPreviouslyBuiltTargets);
+                                       targetNames, bpg, targetOutputs, BuildSettings.DoNotResetPreviouslyBuiltTargets, toolsVersion);
                        }
                }
 
+               public bool BuildProjectFilesInParallel (string[] projectFileNames,
+                                       string [] targetNames,
+                                       IDictionary[] globalProperties,
+                                       IDictionary[] targetOutputsPerProject,
+                                       string[] toolsVersion,
+                                       bool useResultsCache,
+                                       bool unloadProjectsOnCompletion)
+               {
+                       throw new NotImplementedException ();
+               }
+
                // Raises a custom event to all registered loggers.
                public void LogCustomEvent (CustomBuildEventArgs e)
                {
@@ -128,6 +148,10 @@ namespace Microsoft.Build.BuildEngine {
                public string ProjectFileOfTaskNode {
                        get { return taskfile; }
                }
+
+               public bool IsRunningMultipleNodes {
+                       get { return false; }
+               }
                
        }
 }
index 9edeeb5a82094084484716bca040241fc8d2151b..38bdad84bfa5ada09808b58876446175e0e51bd7 100644 (file)
@@ -176,27 +176,31 @@ namespace Microsoft.Build.BuildEngine {
                void LogError (string message,
                                     params object[] messageArgs)
                {
-                       BuildErrorEventArgs beea = new BuildErrorEventArgs (
-                               null, null, null, 0, 0, 0, 0, String.Format (message, messageArgs),
-                               null, null);
-                       parentTarget.Project.ParentEngine.EventSource.FireErrorRaised (this, beea);
+                       parentTarget.Project.ParentEngine.LogError (message, messageArgs);
                }
                
                void LogMessage (MessageImportance importance,
                                        string message,
                                        params object[] messageArgs)
                {
-                       BuildMessageEventArgs bmea = new BuildMessageEventArgs (
-                               String.Format (message, messageArgs), null,
-                               null, importance);
-                       parentTarget.Project.ParentEngine.EventSource.FireMessageRaised (this, bmea);
+                       parentTarget.Project.ParentEngine.LogMessage (importance, message, messageArgs);
                }
 
                ITask InitializeTask ()
                {
                        ITask task;
                        
-                       task = (ITask)Activator.CreateInstance (this.Type);
+                       try {
+                               task = (ITask)Activator.CreateInstance (this.Type);
+                       } catch (InvalidCastException) {
+                               LogMessage (MessageImportance.Low, "InvalidCastException, ITask: {0} Task type: {1}",
+                                               typeof (ITask).AssemblyQualifiedName, this.Type.AssemblyQualifiedName);
+                               throw;
+                       }
+                       parentTarget.Project.ParentEngine.LogMessage (
+                                       MessageImportance.Low,
+                                       "Using task {0} from {1}", Name, this.Type.AssemblyQualifiedName);
+
                        task.BuildEngine = new BuildEngine (parentTarget.Project.ParentEngine, parentTarget.Project,
                                                parentTarget.TargetFile, 0, 0, ContinueOnError);
                        task_logger = new TaskLoggingHelper (task);
index adf15516ddf737e42506be18b39bcc75ff1da944..7b43f792701256ec17cbd045acc091edbe0057cd 100644 (file)
@@ -1,3 +1,55 @@
+2010-04-10  Ankit Jain  <jankit@novell.com>
+
+       * Project.cs (InitializeProperties): Set MSBuildBinPath to the current
+       tools path.
+
+2010-04-10  Ankit Jain  <jankit@novell.com>
+
+       * TaskEngine.cs (Prepare): Throw InvalidProjectFileException instead of a generic
+       Exception.
+
+2010-04-10  Ankit Jain  <jankit@novell.com>
+
+       * ConsoleLogger.cs (EventsToString): If the target being executed is
+       from an imported file, then show that.
+
+2010-04-10  Ankit Jain  <jankit@novell.com>
+
+       * Project.cs: Add property MSBuildExtensionsPath32, used by silverlight
+       projects.
+
+2010-04-07  Ankit Jain  <jankit@novell.com>
+
+       * ConsoleLogger.cs: Dump items and properties when a project starts
+       to build. Useful for debugging.
+       * Engine.cs (LogProjectStarted): Set the properties and items also,
+       for the project started event.
+       * Project.cs (EvaluatedPropertiesAsDictionaryEntries): New.
+       (EvaluatedItemsByNameAsDictionaryEntries): New. Required for
+       ProjectStartedEvent .
+
+2010-04-03  Ankit Jain  <jankit@novell.com>
+
+       * BuildEngine.cs: Implement IBuildEngine2 instead of
+       IBuildEngine.
+       * BuildTasks.cs: Use the new extension methods for logging.
+       (InitializeTask): Emit a message informing about the assembly
+       from which the task is being loaded. Emit a useful debug message
+       incase of a InvalidCastException.
+       * Engine.cs: Add missing methods, constructors and properties related
+       to ToolsVersion support. Setup a default set of Toolsets.
+       Keep separate taskdbs' per ToolsVersion. The common tasks
+       would come from different *.tasks file, and use different
+       task assemblies.
+       (DefaultToolsVersion): Correctly set this based on the profile.
+       * LogExtensions.cs: New. Extension methods on Engine, for logging.
+       * Project.cs: Add missing methods/contructors/properties related
+       to ToolsVersion support. Add reserved properties -
+       MSBuildToolsPath and MSBuildToolsVersion .
+       * Toolset.cs: New.
+       * ToolsetCollection.cs: New.
+       * ToolsetDefinitionLocations.cs: New.
+
 2010-03-04  Ankit Jain  <jankit@novell.com>
 
        * BuildEngine.cs (LogErrorEvent): Log as warning, if
index 8114c79c6c3bb14a01f9ff2e383a402d9bee9204..02d0179fb3fdb2e8a08772a4951ad5ca7d91f70f 100644 (file)
@@ -29,6 +29,7 @@
 
 using System;
 using System.Runtime.InteropServices;
+using System.Collections;
 using System.Collections.Generic;
 using System.IO;
 using System.Security;
@@ -283,6 +284,8 @@ namespace Microsoft.Build.BuildEngine {
                                                String.IsNullOrEmpty (args.TargetNames) ? "default" : args.TargetNames));
                        ResetColor ();
                        WriteLine (String.Empty);
+                       DumpProperties (args.Properties);
+                       DumpItems (args.Items);
                        PushEvent (args);
                }
                
@@ -405,7 +408,7 @@ namespace Microsoft.Build.BuildEngine {
                public void CustomEventHandler (object sender, CustomBuildEventArgs args)
                {
                }
-               
+
                private void WriteLine (string message)
                {
                        if (indent > 0) {
@@ -436,6 +439,7 @@ namespace Microsoft.Build.BuildEngine {
                {
                        StringBuilder sb = new StringBuilder ();
 
+                       string last_imported_target_file = String.Empty;
                        for (int i = 0; i < events.Count; i ++) {
                                BuildStatusEventArgs args = events [i];
                                ProjectStartedEventArgs pargs = args as ProjectStartedEventArgs;
@@ -444,12 +448,20 @@ namespace Microsoft.Build.BuildEngine {
                                                        String.IsNullOrEmpty (pargs.TargetNames) ?
                                                                "default targets" :
                                                                pargs.TargetNames);
+                                       last_imported_target_file = String.Empty;
                                        continue;
                                }
 
                                TargetStartedEventArgs targs = args as TargetStartedEventArgs;
-                               if (targs != null)
+                               if (targs != null) {
+                                       if (targs.TargetFile != targs.ProjectFile && targs.TargetFile != last_imported_target_file)
+                                               // target from an imported file,
+                                               // and it hasn't been mentioned as yet
+                                               sb.AppendFormat ("{0} ", targs.TargetFile);
+
+                                       last_imported_target_file = targs.TargetFile;
                                        sb.AppendFormat ("({0} target) ->\n", targs.TargetName);
+                               }
                        }
 
                        return sb.ToString ();
@@ -572,6 +584,59 @@ namespace Microsoft.Build.BuildEngine {
                                        return false;
                 }
 
+               void DumpProperties (IEnumerable properties)
+               {
+                       if (!IsVerbosityGreaterOrEqual (LoggerVerbosity.Diagnostic))
+                               return;
+
+                       SetColor (eventColor);
+                       WriteLine ("\n");
+                       WriteLine ("Initial Properties:");
+                       ResetColor ();
+
+                       if (properties == null)
+                               return;
+
+                       var dict = new SortedDictionary<string, string> ();
+                       foreach (DictionaryEntry de in properties)
+                               dict [(string)de.Key] = (string)de.Value;
+
+                       foreach (KeyValuePair<string, string> pair in dict)
+                               WriteLine (String.Format ("{0} = {1}", pair.Key, pair.Value));
+                       WriteLine ("\n");
+               }
+
+               void DumpItems (IEnumerable items)
+               {
+                       if (!IsVerbosityGreaterOrEqual (LoggerVerbosity.Diagnostic) || items == null)
+                               return;
+
+                       SetColor (eventColor);
+                       WriteLine ("\n");
+                       WriteLine ("Initial Items:");
+                       ResetColor ();
+                       if (items == null)
+                               return;
+
+                       var items_table = new SortedDictionary<string, List<ITaskItem>> ();
+                       foreach (DictionaryEntry de in items) {
+                               string key = (string)de.Key;
+                               if (!items_table.ContainsKey (key))
+                                       items_table [key] = new List<ITaskItem> ();
+
+                               items_table [key].Add ((ITaskItem) de.Value);
+                       }
+
+                       foreach (string name in items_table.Keys) {
+                               WriteLine (name);
+                               indent ++;
+                               foreach (ITaskItem item in items_table [name])
+                                       WriteLine (item.ItemSpec);
+                               indent--;
+                       }
+                       WriteLine ("\n");
+               }
+
                public string Parameters {
                        get {
                                return parameters;
index a8f6a067a2c9526c00d0f65409dfd6efcb33c315..b6fe05eb2c630e8b14b8098e9403e2f726e860eb 100644 (file)
@@ -40,16 +40,17 @@ namespace Microsoft.Build.BuildEngine {
                
                string                  binPath;
                bool                    buildEnabled;
-               TaskDatabase            defaultTasks;
-               bool                    defaultTasksRegistered;
+               Dictionary<string, TaskDatabase> defaultTasksTableByToolsVersion;
                const string            defaultTasksProjectName = "Microsoft.Common.tasks";
                EventSource             eventSource;
                bool                    buildStarted;
+               ToolsetDefinitionLocations toolsetLocations;
                BuildPropertyGroup      global_properties;
                //IDictionary           importedProjects;
                List <ILogger>          loggers;
                //bool                  onlyLogCriticalEvents;
                Dictionary <string, Project>    projects;
+               string defaultToolsVersion;
 
                // the key here represents the project+target+global_properties set
                Dictionary <string, ITaskItem[]> builtTargetsOutputByName;
@@ -68,6 +69,25 @@ namespace Microsoft.Build.BuildEngine {
                {
                }
 
+               public Engine (ToolsetDefinitionLocations locations)
+                       : this (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20))
+               {
+                       toolsetLocations = locations;
+               }
+               
+               public Engine (BuildPropertyGroup globalProperties)
+                       : this (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20))
+               {
+                       this.global_properties = globalProperties;
+               }
+
+               public Engine (BuildPropertyGroup globalProperties, ToolsetDefinitionLocations locations)
+                       : this (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20))
+               {
+                       this.global_properties = globalProperties;
+                       toolsetLocations = locations;
+               }
+
                // engine should be invoked with path where binary files are
                // to find microsoft.build.tasks
                public Engine (string binPath)
@@ -81,8 +101,25 @@ namespace Microsoft.Build.BuildEngine {
                        this.global_properties = new BuildPropertyGroup ();
                        this.builtTargetsOutputByName = new Dictionary<string, ITaskItem[]> ();
                        this.currentlyBuildingProjectsStack = new Stack<Project> ();
-                       
-                       RegisterDefaultTasks ();
+                       this.Toolsets = new ToolsetCollection ();
+                       LoadDefaultToolsets ();
+                       defaultTasksTableByToolsVersion = new Dictionary<string, TaskDatabase> ();
+                       GetDefaultTasks (DefaultToolsVersion);
+               }
+
+               //FIXME: should be loaded from config file
+               void LoadDefaultToolsets ()
+               {
+                       Toolsets.Add (new Toolset ("2.0",
+                                               ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20)));
+                       Toolsets.Add (new Toolset ("3.0",
+                                               ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version30)));
+                       Toolsets.Add (new Toolset ("3.5",
+                                               ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version35)));
+#if NET_4_0
+                       Toolsets.Add (new Toolset ("4.0",
+                                               ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version40)));
+#endif
                }
                
                [MonoTODO]
@@ -128,27 +165,31 @@ namespace Microsoft.Build.BuildEngine {
                        if (targetNames == null)
                                return false;
 
+                       if (defaultToolsVersion != null)
+                               // it has been explicitly set, xbuild does this..
+                               project.ToolsVersion = defaultToolsVersion;
                        return project.Build (targetNames, targetOutputs, buildFlags);
                }
 
                [MonoTODO]
                public bool BuildProjectFile (string projectFile)
                {
-                       throw new NotImplementedException ();
+                       return BuildProjectFile (projectFile, new string [0]);
                }
                
                [MonoTODO]
                public bool BuildProjectFile (string projectFile,
                                              string targetName)
                {
-                       throw new NotImplementedException ();
+                       return BuildProjectFile (projectFile,
+                                                targetName == null ? new string [0] : new string [] {targetName});
                }
                
                [MonoTODO]
                public bool BuildProjectFile (string projectFile,
                                              string[] targetNames)
                {
-                       throw new NotImplementedException ();
+                       return BuildProjectFile (projectFile, targetNames, null);
                }
                
                [MonoTODO]
@@ -173,6 +214,16 @@ namespace Microsoft.Build.BuildEngine {
                                              BuildPropertyGroup globalProperties,
                                              IDictionary targetOutputs,
                                              BuildSettings buildFlags)
+               {
+                       return BuildProjectFile (projectFile, targetNames, globalProperties, targetOutputs, buildFlags, null);
+               }
+                       
+               //FIXME: add a test for null @toolsVersion
+               public bool BuildProjectFile (string projectFile,
+                                             string[] targetNames,
+                                             BuildPropertyGroup globalProperties,
+                                             IDictionary targetOutputs,
+                                             BuildSettings buildFlags, string toolsVersion)
                {
                        Project project;
 
@@ -197,6 +248,13 @@ namespace Microsoft.Build.BuildEngine {
                        }
 
                        try {
+                               if (String.IsNullOrEmpty (toolsVersion) && defaultToolsVersion != null)
+                                       // it has been explicitly set, xbuild does this..
+                                       //FIXME: should this be cleared after building?
+                                       project.ToolsVersion = defaultToolsVersion;
+                               else
+                                       project.ToolsVersion = toolsVersion;
+
                                return project.Build (targetNames, targetOutputs, buildFlags);
                        } finally {
                                if (globalProperties != null) {
@@ -217,8 +275,6 @@ namespace Microsoft.Build.BuildEngine {
 
                public Project CreateNewProject ()
                {
-                       if (defaultTasksRegistered)
-                               CheckBinPath ();
                        return new Project (this);
                }
 
@@ -328,13 +384,15 @@ namespace Microsoft.Build.BuildEngine {
 
                void LogProjectStarted (Project project, string [] target_names)
                {
-                       ProjectStartedEventArgs psea;
+                       string targets;
                        if (target_names == null || target_names.Length == 0)
-                               psea = new ProjectStartedEventArgs ("Project started.", null, project.FullFileName,
-                                               String.Empty, null, null);
+                               targets = String.Empty;
                        else
-                               psea = new ProjectStartedEventArgs ("Project started.", null, project.FullFileName,
-                                               String.Join (";", target_names), null, null);
+                               targets = String.Join (";", target_names);
+
+                       ProjectStartedEventArgs psea = new ProjectStartedEventArgs ("Project started.", null, project.FullFileName, targets,
+                                       project.EvaluatedPropertiesAsDictionaryEntries, project.EvaluatedItemsByNameAsDictionaryEntries);
+
                        eventSource.FireProjectStarted (this, psea);
                }
 
@@ -358,23 +416,44 @@ namespace Microsoft.Build.BuildEngine {
                        bfea = new BuildFinishedEventArgs ("Build finished.", null, succeeded);
                        eventSource.FireBuildFinished (this, bfea);
                }
+
+               internal TaskDatabase GetDefaultTasks (string toolsVersion)
+               {
+                       TaskDatabase db;
+                       if (defaultTasksTableByToolsVersion.TryGetValue (toolsVersion, out db))
+                               return db;
+
+                       var toolset = Toolsets [toolsVersion];
+                       if (toolset == null)
+                               throw new Exception ("Unknown toolsversion: " + toolsVersion);
+
+                       string toolsPath = toolset.ToolsPath;
+                       string tasksFile = Path.Combine (toolsPath, defaultTasksProjectName);
+                       this.LogMessage (MessageImportance.Low, "Loading default tasks for ToolsVersion: {0} from {1}", toolsVersion, tasksFile);
+
+                       // set a empty taskdb here, because the project loading the tasks
+                       // file will try to get the default task db
+                       defaultTasksTableByToolsVersion [toolsVersion] = new TaskDatabase ();
+
+                       db = defaultTasksTableByToolsVersion [toolsVersion] = RegisterDefaultTasks (tasksFile);
+
+                       return db;
+               }
                
-               void RegisterDefaultTasks ()
+               TaskDatabase RegisterDefaultTasks (string tasksFile)
                {
-                       this.defaultTasksRegistered = false;
-                       
                        Project defaultTasksProject = CreateNewProject ();
+                       TaskDatabase db;
                        
-                       if (binPath != null) {
-                               if (File.Exists (Path.Combine (binPath, defaultTasksProjectName))) {
-                                       defaultTasksProject.Load (Path.Combine (binPath, defaultTasksProjectName));
-                                       defaultTasks = defaultTasksProject.TaskDatabase;
-                               } else
-                                       defaultTasks = new TaskDatabase ();
-                       } else
-                               defaultTasks = new TaskDatabase ();
-                       
-                       this.defaultTasksRegistered = true;
+                       if (File.Exists (tasksFile)) {
+                               defaultTasksProject.Load (tasksFile);
+                               db = defaultTasksProject.TaskDatabase;
+                       } else {
+                               this.LogWarning ("Default tasks file {0} not found, ignoring.", tasksFile);
+                               db = new TaskDatabase ();
+                       }
+
+                       return db;
                }
 
                public string BinPath {
@@ -403,7 +482,31 @@ namespace Microsoft.Build.BuildEngine {
                        get { return global_properties; }
                        set { global_properties = value; }
                }
+               
+               public ToolsetCollection Toolsets {
+                       get; private set;
+               }
 
+               public string DefaultToolsVersion {
+                       get {
+                               if (String.IsNullOrEmpty (defaultToolsVersion))
+#if NET_4_0
+                                       return "4.0";
+#elif NET_3_5
+                                       return "3.5";
+#else
+                                       return "2.0";
+#endif
+                               
+                               return defaultToolsVersion;
+                       }
+                       set { defaultToolsVersion = value; }
+               }
+               
+               public bool IsBuilding {
+                       get { return buildStarted; }
+               }
+               
                public bool OnlyLogCriticalEvents {
                        get { return eventSource.OnlyLogCriticalEvents; }
                        set { eventSource.OnlyLogCriticalEvents = value; }
@@ -413,14 +516,6 @@ namespace Microsoft.Build.BuildEngine {
                        get { return eventSource; }
                }
                
-               internal bool DefaultTasksRegistered {
-                       get { return defaultTasksRegistered; }
-               }
-               
-               internal TaskDatabase DefaultTasks {
-                       get { return defaultTasks; }
-               }
-
                internal Dictionary<string, ITaskItem[]> BuiltTargetsOutputByName {
                        get { return builtTargetsOutputByName; }
                }
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/LogExtensions.cs b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/LogExtensions.cs
new file mode 100644 (file)
index 0000000..030ea8a
--- /dev/null
@@ -0,0 +1,183 @@
+//
+// LogExtensions.cs: Extension methods for logging on Engine
+//
+// Author:
+//     Ankit Jain (jankit@novell.com)
+//
+// Copyright 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+#if NET_2_0
+
+using System;
+using System.IO;
+using System.Text;
+using Microsoft.Build.Framework;
+
+namespace Microsoft.Build.BuildEngine
+{
+       static class LogExtensions
+       {
+               public static string FormatString (string unformatted,
+                                                  params object[] args)
+               {
+                       if (unformatted == null)
+                               throw new ArgumentNullException ("unformatted");
+               
+                       if (args == null || args.Length == 0)
+                               return unformatted;
+                       else
+                               return String.Format (unformatted, args);
+               }
+               
+               public static void LogError (this Engine engine, string message,
+                                    params object[] messageArgs)
+               {
+                       if (message == null)
+                               throw new ArgumentNullException ("message");
+                               
+                       BuildErrorEventArgs beea = new BuildErrorEventArgs (
+                               null, null, null, 0, 0, 0, 0, FormatString (message, messageArgs),
+                               null, null);
+                       engine.EventSource.FireErrorRaised (engine, beea);
+               }
+
+               public static void LogError (this Engine engine, string subcategory, string errorCode,
+                                     string helpKeyword, string file,
+                                     int lineNumber, int columnNumber,
+                                     int endLineNumber, int endColumnNumber,
+                                     string message,
+                                     params object[] messageArgs)
+               {
+                       if (message == null)
+                               throw new ArgumentNullException ("message");
+                       
+                       BuildErrorEventArgs beea = new BuildErrorEventArgs (
+                               subcategory, errorCode, file, lineNumber,
+                               columnNumber, endLineNumber, endColumnNumber,
+                               FormatString (message, messageArgs), helpKeyword /*it's helpKeyword*/,
+                               null /*it's senderName*/);
+
+                       engine.EventSource.FireErrorRaised (engine, beea);
+               }
+
+               public static void LogErrorFromException (this Engine engine, Exception e)
+               {
+                       LogErrorFromException (engine, e, true);
+               }
+
+               public static void LogErrorFromException (this Engine engine, Exception e,
+                                                  bool showStackTrace)
+               {
+                       LogErrorFromException (engine, e, showStackTrace, true, String.Empty);
+               }
+
+               [MonoTODO ("Arguments @showDetail and @file are not honored")]
+               public static void LogErrorFromException (this Engine engine, Exception e,
+                                                  bool showStackTrace, bool showDetail, string file)
+               {
+                       if (e == null)
+                               throw new ArgumentNullException ("e");
+               
+                       StringBuilder sb = new StringBuilder ();
+                       sb.Append (e.Message);
+                       if (showStackTrace == true)
+                               sb.Append (e.StackTrace);
+                       BuildErrorEventArgs beea = new BuildErrorEventArgs (
+                               null, null, null, 0, 0, 0, 0, sb.ToString (),
+                               e.HelpLink, e.Source);
+                       engine.EventSource.FireErrorRaised (engine, beea);
+               }
+
+               public static void LogMessage (this Engine engine, string message,
+                                      params object[] messageArgs)
+               {
+                       LogMessage (engine, MessageImportance.Normal, message, messageArgs); 
+               }
+
+               public static void LogMessage (this Engine engine, MessageImportance importance,
+                                       string message,
+                                       params object[] messageArgs)
+               {
+                       if (message == null)
+                               throw new ArgumentNullException ("message");
+               
+                       LogMessageFromText (engine, FormatString (message, messageArgs), importance);
+               }
+
+               public static bool LogMessageFromText (this Engine engine, string lineOfText,
+                                               MessageImportance importance)
+               {
+                       if (lineOfText == null)
+                               throw new ArgumentNullException ("lineOfText");
+
+                       BuildMessageEventArgs bmea = new BuildMessageEventArgs (
+                               lineOfText, null,
+                               null, importance);
+                       
+                       engine.EventSource.FireMessageRaised (engine, bmea);
+
+                       return true;
+               }
+
+               public static void LogWarning (this Engine engine, string message,
+                                      params object[] messageArgs)
+               {
+                       // FIXME: what about all the parameters?
+                       BuildWarningEventArgs bwea = new BuildWarningEventArgs (
+                               null, null, null, 0, 0, 0, 0, FormatString (message, messageArgs),
+                               null, null);
+                       engine.EventSource.FireWarningRaised (engine, bwea);
+               }
+
+               public static void LogWarning (this Engine engine, string subcategory, string warningCode,
+                                       string helpKeyword, string file,
+                                       int lineNumber, int columnNumber,
+                                       int endLineNumber, int endColumnNumber,
+                                       string message,
+                                       params object[] messageArgs)
+               {
+                       BuildWarningEventArgs bwea = new BuildWarningEventArgs (
+                               subcategory, warningCode, file, lineNumber,
+                               columnNumber, endLineNumber, endColumnNumber,
+                               FormatString (message, messageArgs), helpKeyword, null);
+                       engine.EventSource.FireWarningRaised (engine, bwea);
+               }
+
+               public static void LogWarningFromException (this Engine engine, Exception e)
+               {
+                       LogWarningFromException (engine, e, false);
+               }
+
+               public static void LogWarningFromException (this Engine engine, Exception e,
+                                                    bool showStackTrace)
+               {
+                       StringBuilder sb = new StringBuilder ();
+                       sb.Append (e.Message);
+                       if (showStackTrace)
+                               sb.Append (e.StackTrace);
+                       LogWarning (engine, null, null, null, null, 0, 0, 0, 0,
+                               sb.ToString (), null);
+               }
+       }
+}
+
+#endif
index b5b0b1aa81100abee5cd8635673fa5e52530b830..0bda5abba45a7853ca3dd3f0a741dce166169980 100644 (file)
@@ -89,9 +89,14 @@ namespace Microsoft.Build.BuildEngine {
                {
                }
 
-               public Project (Engine engine)
+               public Project (Engine engine) : this (engine, null)
+               {
+               }
+               
+               public Project (Engine engine, string toolsVersion)
                {
                        parentEngine  = engine;
+                       ToolsVersion = toolsVersion;
 
                        buildEnabled = ParentEngine.BuildEnabled;
                        xmlDocument = new XmlDocument ();
@@ -116,6 +121,7 @@ namespace Microsoft.Build.BuildEngine {
                                GlobalProperties.AddProperty (bp.Clone (true));
                        
                        ProcessXml ();
+
                }
 
                [MonoTODO ("Not tested")]
@@ -793,8 +799,7 @@ namespace Microsoft.Build.BuildEngine {
                        last_item_group_containing = new Dictionary <string, BuildItemGroup> ();
                        
                        taskDatabase = new TaskDatabase ();
-                       if (ParentEngine.DefaultTasksRegistered)
-                               taskDatabase.CopyTasks (ParentEngine.DefaultTasks);     
+                       taskDatabase.CopyTasks (ParentEngine.GetDefaultTasks (GetToolsVersionToUse ()));
 
                        initialTargets = new List<string> ();
                        defaultTargets = new string [0];
@@ -860,7 +865,7 @@ namespace Microsoft.Build.BuildEngine {
                                                AddChoose (xe);
                                                break;
                                        default:
-                                               throw new InvalidProjectFileException ("Invalid element in project file.");
+                                               throw new InvalidProjectFileException (String.Format ("Invalid element '{0}' in project file.", xe.Name));
                                        }
                                }
                        }
@@ -927,9 +932,15 @@ namespace Microsoft.Build.BuildEngine {
                        EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectName",
                                                Path.GetFileNameWithoutExtension (fullFileName),
                                                PropertyType.Reserved));
-                       EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildBinPath", parentEngine.BinPath, PropertyType.Reserved));
-                       EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildToolsPath", parentEngine.BinPath, PropertyType.Reserved));
+                       string toolsVersionToUse = GetToolsVersionToUse ();
+                       string toolsPath = parentEngine.Toolsets [toolsVersionToUse].ToolsPath;
+                       if (toolsPath == null)
+                               throw new Exception ("Unknown toolsVersion: " + toolsVersionToUse);
+                       EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildBinPath", toolsPath, PropertyType.Reserved));
+                       EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildToolsPath", toolsPath, PropertyType.Reserved));
+                       EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildToolsVersion", toolsVersionToUse, PropertyType.Reserved));
                        EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildExtensionsPath", ExtensionsPath, PropertyType.Reserved));
+                       EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildExtensionsPath32", ExtensionsPath, PropertyType.Reserved));
                        EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDefaultTargets", DefaultTargets, PropertyType.Reserved));
                        EvaluatedProperties.AddProperty (new BuildProperty ("OS", OS, PropertyType.Environment));
 
@@ -942,6 +953,18 @@ namespace Microsoft.Build.BuildEngine {
 
                        EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDirectory", projectDir, PropertyType.Reserved));
                }
+
+               string GetToolsVersionToUse ()
+               {
+                       if (String.IsNullOrEmpty (ToolsVersion)) {
+                               if (HasToolsVersionAttribute)
+                                       return DefaultToolsVersion;
+                               else
+                                       return parentEngine.DefaultToolsVersion;
+                       } else {
+                               return ToolsVersion;
+                       }
+               }
                
                void AddProjectExtensions (XmlElement xmlElement)
                {
@@ -1077,7 +1100,19 @@ namespace Microsoft.Build.BuildEngine {
                                return evaluatedItemsByName;
                        }
                }
-               
+
+               internal IEnumerable EvaluatedItemsByNameAsDictionaryEntries {
+                       get {
+                               if (EvaluatedItemsByName.Count == 0)
+                                       yield break;
+
+                               foreach (KeyValuePair<string, BuildItemGroup> pair in EvaluatedItemsByName) {
+                                       foreach (BuildItem bi in pair.Value)
+                                               yield return new DictionaryEntry (pair.Key, bi.ConvertToITaskItem (null, ExpressionOptions.ExpandItemRefs));
+                               }
+                       }
+               }
+
                internal IDictionary <string, BuildItemGroup> EvaluatedItemsByNameIgnoringCondition {
                        get {
                                // FIXME: do we need to do this here?
@@ -1238,6 +1273,13 @@ namespace Microsoft.Build.BuildEngine {
                        }
                }
 
+               internal IEnumerable EvaluatedPropertiesAsDictionaryEntries {
+                       get {
+                               foreach (BuildProperty bp in EvaluatedProperties)
+                                       yield return new DictionaryEntry (bp.Name, bp.Value);
+                       }
+               }
+
                public string FullFileName {
                        get { return fullFileName; }
                        set { fullFileName = value; }
@@ -1316,6 +1358,29 @@ namespace Microsoft.Build.BuildEngine {
                        get { return xmlDocument.InnerXml; }
                }
 
+               // corresponds to the xml attribute
+               public string DefaultToolsVersion {
+                       get {
+                               if (xmlDocument != null)
+                                       return xmlDocument.DocumentElement.GetAttribute ("ToolsVersion");
+                               return null;
+                       }
+                       set {
+                               if (xmlDocument != null)
+                                       xmlDocument.DocumentElement.SetAttribute ("ToolsVersion", value);
+                       }
+               }
+
+               public bool HasToolsVersionAttribute {
+                       get {
+                               return xmlDocument != null && xmlDocument.DocumentElement.HasAttribute ("ToolsVersion");
+                       }
+               }
+               
+               public string ToolsVersion {
+                       get; internal set;
+               }
+
                internal List<string> BuiltTargetKeys {
                        get { return builtTargetKeys; }
                }
index 485771de49243bef34cc970dcb18b7f353eb3d66..696ffbeedfbf9f646935fad6697756a372835d2b 100644 (file)
@@ -95,7 +95,7 @@ namespace Microsoft.Build.BuildEngine {
                                        if (TryGetObjectFromString (de.Value, currentProperty.PropertyType, out value))
                                                values.Add (de.Key, value);
                                } catch (Exception e) {
-                                       throw new Exception (String.Format (
+                                       throw new InvalidProjectFileException (String.Format (
                                                        "Error converting Property named '{0}' with value '{1}' to type {2}: {3}",
                                                        de.Key, de.Value, currentProperty.PropertyType, e.Message), e);
                                }
@@ -171,10 +171,10 @@ namespace Microsoft.Build.BuildEngine {
                                propertyInfo = taskType.GetProperty (taskParameter, BindingFlags.Public | BindingFlags.Instance |
                                                        BindingFlags.IgnoreCase);
                                if (propertyInfo == null)
-                                       throw new Exception (String.Format (
+                                       throw new InvalidProjectFileException (String.Format (
                                                "The parameter '{0}' was not found for the '{1}' task.", taskParameter, taskElement.Name));
                                if (!propertyInfo.IsDefined (outputAttribute, false))
-                                       throw new Exception ("This is not output property.");
+                                       throw new InvalidProjectFileException ("This is not output property.");
                                
                                o = propertyInfo.GetValue (task, null);
                                // FIXME: maybe we should throw an exception here?
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Toolset.cs b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/Toolset.cs
new file mode 100644 (file)
index 0000000..d795517
--- /dev/null
@@ -0,0 +1,53 @@
+//
+// Toolset.cs
+//
+// Author:
+//     Ankit Jain (jankit@novell.com)
+//
+// Copyright 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+#if NET_2_0
+using System;
+
+namespace Microsoft.Build.BuildEngine
+{
+       public class Toolset
+       {
+               public Toolset (string toolsVersion, string toolsPath, BuildPropertyGroup buildProperties)
+               {
+                       ToolsVersion = toolsVersion;
+                       ToolsPath = toolsPath;
+                       BuildProperties = buildProperties;
+               }
+               
+               public Toolset (string toolsVersion, string toolsPath)
+                       : this (toolsVersion, toolsPath, null)
+               {
+               }
+
+               public BuildPropertyGroup BuildProperties { get; private set; }
+
+               public string ToolsVersion { get; private set; }
+               public string ToolsPath { get; private set; }
+       }
+}
+#endif
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ToolsetCollection.cs b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ToolsetCollection.cs
new file mode 100644 (file)
index 0000000..0c332d4
--- /dev/null
@@ -0,0 +1,99 @@
+//
+// ToolsetCollection.cs
+//
+// Author:
+//     Ankit Jain (jankit@novell.com)
+//
+// Copyright 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+#if NET_2_0
+
+using System;
+using System.Collections.Generic;
+using System.Collections;
+
+namespace Microsoft.Build.BuildEngine
+{
+
+       public class ToolsetCollection : ICollection<Toolset>, IEnumerable<Toolset>, IEnumerable
+       {
+               List<Toolset> toolsets;
+               
+               internal ToolsetCollection ()
+               {
+                       toolsets = new List<Toolset> ();
+               }
+               
+               public int Count
+               {
+                       get { return toolsets.Count; }
+               }
+               
+               public bool IsReadOnly { get { return false; } }
+                       
+               public Toolset this [string toolsVersion]
+               {
+                       get { return toolsets.Find (item => item.ToolsVersion == toolsVersion); }
+               }
+               
+               public void Add (Toolset item)
+               {
+                       toolsets.Add (item);
+               }
+               
+               public void Clear ()
+               {
+                       toolsets.Clear ();
+               }
+               
+               public bool Contains (string toolsVersion)
+               {
+                       return toolsets.Exists (item => item.ToolsVersion == toolsVersion);
+               }
+               
+               public bool Contains (Toolset item)
+               {
+                       return toolsets.Contains (item);
+               }
+
+               public void CopyTo (Toolset[] array, int arrayIndex)
+               {
+                       toolsets.CopyTo (array, arrayIndex);
+               }
+               
+               public IEnumerator<Toolset> GetEnumerator ()
+               {
+                       return toolsets.GetEnumerator ();
+               }
+               
+               IEnumerator IEnumerable.GetEnumerator ()
+               {
+                       return toolsets.GetEnumerator ();
+               }
+               
+               public bool Remove (Toolset item)
+               {
+                       return toolsets.Remove (item);
+               }
+       }
+}
+#endif
diff --git a/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ToolsetDefinitionLocations.cs b/mcs/class/Microsoft.Build.Engine/Microsoft.Build.BuildEngine/ToolsetDefinitionLocations.cs
new file mode 100644 (file)
index 0000000..6f5e106
--- /dev/null
@@ -0,0 +1,39 @@
+//
+// ToolsetDefinitionLocations.cs
+//
+// Author:
+//     Ankit Jain (jankit@novell.com)
+//
+// Copyright 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+#if NET_2_0
+
+namespace Microsoft.Build.BuildEngine
+{
+       public enum ToolsetDefinitionLocations
+       {
+               None,
+               ConfigurationFile,
+               Registry
+       }
+}
+#endif
index 8f429b31a78d7d16ac8175d87aca2e6647917edb..02bc4c2002f52f7d3fc229bd9fe12e3093a34fbd 100644 (file)
@@ -46,6 +46,7 @@ Microsoft.Build.BuildEngine/InternalLoggerException.cs
 Microsoft.Build.BuildEngine/InvalidProjectFileException.cs
 Microsoft.Build.BuildEngine/IReference.cs
 Microsoft.Build.BuildEngine/ItemReference.cs
+Microsoft.Build.BuildEngine/LogExtensions.cs
 Microsoft.Build.BuildEngine/MetadataReference.cs
 Microsoft.Build.BuildEngine/Project.cs
 Microsoft.Build.BuildEngine/ProjectLoadSettings.cs
@@ -56,6 +57,9 @@ Microsoft.Build.BuildEngine/Target.cs
 Microsoft.Build.BuildEngine/TaskDatabase.cs
 Microsoft.Build.BuildEngine/TaskEngine.cs
 Microsoft.Build.BuildEngine/Token.cs
+Microsoft.Build.BuildEngine/Toolset.cs
+Microsoft.Build.BuildEngine/ToolsetCollection.cs
+Microsoft.Build.BuildEngine/ToolsetDefinitionLocations.cs
 Microsoft.Build.BuildEngine/UsingTask.cs
 Microsoft.Build.BuildEngine/UsingTaskCollection.cs
 Microsoft.Build.BuildEngine/Utilities.cs
index 7a11426c77373edc64b35216cedb79bf869e4d0f..c6084a139c698ebb9c28aa62252750c6bb906693 100644 (file)
@@ -1,3 +1,11 @@
+2010-04-06  Ankit Jain  <jankit@novell.com>
+
+       * Consts.cs (ToolsVersionString): New.
+       (GetTasksAsmPath): New.
+       * EngineTest.cs: Use the direct path to the tasks assembly
+       in the UsingTasks.
+       * ProjectTest.cs: Set ToolsVersion to the current profile.
+
 2010-02-19  Ankit Jain  <jankit@novell.com>
 
        * ImportTest.cs (TestMissingImport*): Add new tests for missing
index bae9a32d6e56a9ce97c617c330423719fb45ac43..31a160850a170cd7bbc08aaa2667bfddfd8078c2 100644 (file)
@@ -26,6 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 using System;
+using System.IO;
 using Microsoft.Build.Utilities;
 
 public static class Consts {
@@ -43,4 +44,27 @@ public static class Consts {
                                return ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20);
                }
        }
+
+       public static string ToolsVersionString {
+               get {
+#if NET_4_0
+                       return " ToolsVersion='4.0'";
+#elif NET_3_5
+                       return " ToolsVersion='3.5'";
+#else
+                       return String.Empty;
+#endif
+               }
+       }
+
+       public static string GetTasksAsmPath ()
+       {
+#if NET_4_0
+               return Path.Combine (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version40), "Microsoft.Build.Tasks.v4.0.dll");
+#elif NET_3_5
+               return Path.Combine (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version35), "Microsoft.Build.Tasks.v3.5.dll");
+#else
+               return Path.Combine (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20), "Microsoft.Build.Tasks.dll");
+#endif
+       }
 }
index e18e464cb912243ba67439a832dae2bc1fa1ce1c..b64c1f5bcf141edbb791a8a7d34351e00b6118b0 100644 (file)
@@ -324,8 +324,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
                [Test]
                public void TestGlobalProperties1 ()
                {
-                       string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
-       <UsingTask TaskName=""Microsoft.Build.Tasks.MSBuild"" AssemblyName=""Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" />
+                       string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">"
+                               + GetUsingTask ("MSBuild")
+                               + @"
        <Target Name=""main"">
                <MSBuild Projects=""first.proj"" Targets = ""1;2""/>
                <Message Text=""second""/>
@@ -333,9 +334,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
        </Target>
 </Project>";
 
-                       string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
-       <UsingTask TaskName=""Microsoft.Build.Tasks.MSBuild""
-               AssemblyName=""Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" />
+                       string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">"
+                               + GetUsingTask ("MSBuild")
+                               + @"
        <Target Name = ""1"">
                <MSBuild Projects=""second.proj"" Properties=""foo=bar""/>
                <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo""/>
@@ -363,8 +364,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
                public void TestGlobalProperties1a ()
                {
                        Directory.CreateDirectory ("Test/resources/foo");
-                       string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
-       <UsingTask TaskName=""Microsoft.Build.Tasks.MSBuild"" AssemblyName=""Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" />
+                       string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">"
+                                       + GetUsingTask ("MSBuild")
+                                       + @"
        <Target Name=""main"">
                <MSBuild Projects=""first.proj"" Targets = ""1;2""/>
                <Message Text=""second""/>
@@ -372,9 +374,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
        </Target>
 </Project>";
 
-                       string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
-       <UsingTask TaskName=""Microsoft.Build.Tasks.MSBuild""
-               AssemblyName=""Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" />
+                       string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">"
+                                       + GetUsingTask ("MSBuild")
+                                       + @"
        <Target Name = ""1"">
                <MSBuild Projects=""second.proj"" Properties=""foo=bar""/>
                <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo""/>
@@ -401,8 +403,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
                [Test]
                public void TestGlobalProperties1b ()
                {
-                       string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
-       <UsingTask TaskName=""Microsoft.Build.Tasks.MSBuild"" AssemblyName=""Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" />
+                       string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">"
+                                       + GetUsingTask ("MSBuild")
+                                       + @"
        <Target Name=""main"">
                <MSBuild Projects=""first.proj"" Targets = ""1;2""/>
                <Message Text=""second""/>
@@ -410,9 +413,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
        </Target>
 </Project>";
 
-                       string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
-       <UsingTask TaskName=""Microsoft.Build.Tasks.MSBuild""
-               AssemblyName=""Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" />
+                       string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">"
+                                       + GetUsingTask ("MSBuild")
+                                       + @"
        <Target Name = ""1"">
                <MSBuild Projects=""second.proj"" Properties=""foo=bar""/>
                <MSBuild Projects=""second.proj""/>
@@ -439,8 +442,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
                [Test]
                public void TestGlobalProperties2 ()
                {
-                       string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
-       <UsingTask TaskName=""Microsoft.Build.Tasks.MSBuild"" AssemblyName=""Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" />
+                       string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">"
+                                       + GetUsingTask ("MSBuild")
+                                       + @"
        <Target Name=""main"">
                <MSBuild Projects=""first.proj"" Targets = ""1""/>
                <MSBuild Projects=""first.proj"" Targets = ""2""/>
@@ -449,9 +453,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
        </Target>
 </Project>";
 
-                       string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
-       <UsingTask TaskName=""Microsoft.Build.Tasks.MSBuild""
-               AssemblyName=""Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" />
+                       string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">"
+                                       + GetUsingTask ("MSBuild")
+                                       + @"
        <Target Name = ""1"">
                <MSBuild Projects=""second.proj"" Properties=""foo=bar""/>
                <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo""/>
@@ -478,8 +482,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
                [Test]
                public void TestGlobalProperties3 ()
                {
-                       string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
-       <UsingTask TaskName=""Microsoft.Build.Tasks.MSBuild"" AssemblyName=""Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" />
+                       string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">"
+                                       + GetUsingTask ("MSBuild")
+                                       + @"
        <Target Name=""main"">
                <MSBuild Projects=""first.proj"" Targets = ""1""/>
                <CallTarget Targets=""Call2""/>
@@ -491,9 +496,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
        </Target>
 </Project>";
 
-                       string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
-       <UsingTask TaskName=""Microsoft.Build.Tasks.MSBuild""
-               AssemblyName=""Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" />
+                       string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">"
+                                       + GetUsingTask ("MSBuild")
+                                       + @"
        <Target Name = ""1"">
                <MSBuild Projects=""second.proj"" Properties=""foo=bar""/>
                <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo""/>
@@ -521,8 +526,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
                [Test]
                public void TestGlobalProperties4 ()
                {
-                       string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
-       <UsingTask TaskName=""Microsoft.Build.Tasks.MSBuild"" AssemblyName=""Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" />
+                       string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">"
+                                       + GetUsingTask ("MSBuild")
+                                       + @"
        <Target Name=""main"">
                <MSBuild Projects=""first.proj"" Targets = ""1""/>
                <CallTarget Targets=""Call2""/>
@@ -534,9 +540,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
        </Target>
 </Project>";
 
-                       string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
-       <UsingTask TaskName=""Microsoft.Build.Tasks.MSBuild""
-               AssemblyName=""Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" />
+                       string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">"
+                                       + GetUsingTask ("MSBuild")
+                                       + @"
        <Target Name = ""1"">
                <MSBuild Projects=""second.proj"" Properties=""foo=bar""/>
                <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo""/>
@@ -568,8 +574,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
                [Test]
                public void TestGlobalProperties4a ()
                {
-                       string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
-       <UsingTask TaskName=""Microsoft.Build.Tasks.MSBuild"" AssemblyName=""Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" />
+                       string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">"
+                                       + GetUsingTask ("MSBuild")
+                                       + @"
        <Target Name=""main"">
                <MSBuild Projects=""first.proj"" Targets = ""1""/>
                <CallTarget Targets=""Call2""/>
@@ -581,9 +588,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
        </Target>
 </Project>";
 
-                       string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
-       <UsingTask TaskName=""Microsoft.Build.Tasks.MSBuild""
-               AssemblyName=""Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" />
+                       string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">"
+                                       + GetUsingTask ("MSBuild")
+                                       + @"
        <Target Name = ""1"">
                <MSBuild Projects=""second.proj"" Properties=""foo=bar""/>
                <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo""/>
@@ -615,8 +622,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
                [Test]
                public void TestGlobalProperties4b ()
                {
-                       string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
-       <UsingTask TaskName=""Microsoft.Build.Tasks.MSBuild"" AssemblyName=""Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" />
+                       string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">"
+                                       + GetUsingTask ("MSBuild")
+                                       + @"
        <Target Name=""main"">
                <MSBuild Projects=""first.proj"" Targets = ""1""/>
                <CallTarget Targets=""Call2""/>
@@ -628,9 +636,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
        </Target>
 </Project>";
 
-                       string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
-       <UsingTask TaskName=""Microsoft.Build.Tasks.MSBuild""
-               AssemblyName=""Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" />
+                       string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">"
+                                       + GetUsingTask ("MSBuild")
+                                       + @"
        <Target Name = ""1"">
                <MSBuild Projects=""second.proj"" Properties=""foo=bar""/>
                <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo""/>
@@ -666,8 +674,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
                [Test]
                public void TestGlobalProperties4c ()
                {
-                       string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
-       <UsingTask TaskName=""Microsoft.Build.Tasks.MSBuild"" AssemblyName=""Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" />
+                       string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">"
+                                       + GetUsingTask ("MSBuild")
+                                       + @"
        <Target Name=""main"">
                <MSBuild Projects=""first.proj"" Targets = ""1""/>
                <CallTarget Targets=""Call2""/>
@@ -679,9 +688,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
        </Target>
 </Project>";
 
-                       string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
-       <UsingTask TaskName=""Microsoft.Build.Tasks.MSBuild""
-               AssemblyName=""Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" />
+                       string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">"
+                                       + GetUsingTask ("MSBuild")
+                                       + @"
        <Target Name = ""1"">
                <MSBuild Projects=""second.proj"" Properties=""foo=bar""/>
                <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo""/>
@@ -714,10 +723,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
                [Test]
                public void TestMSBuildOutputs ()
                {
-                       string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
-                       <UsingTask TaskName=""Microsoft.Build.Tasks.MSBuild""
-                                       AssemblyName=""Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" />
-
+                       string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">"
+                                       + GetUsingTask ("MSBuild")
+                                       + @"
         <ItemGroup>
                 <ProjectRef Include=""first.proj"">
                         <Prop3>value</Prop3>
@@ -889,6 +897,9 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
                        }
                }
 
-
+               public static string GetUsingTask (string taskName)
+               {
+                       return "<UsingTask TaskName='Microsoft.Build.Tasks." + taskName + "' AssemblyFile='" + Consts.GetTasksAsmPath () + "' />";
+               }
        }
 }
index cce13c6af674eff37c1d948381412af9ca46d8cf..5d92a43f5a544d6d8ae6ca7d8efbed7a0a4bb2c9 100644 (file)
@@ -1779,7 +1779,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
                        Engine engine = new Engine (Consts.BinPath);
                        Project project = engine.CreateNewProject ();
 
-                       string second = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion=""3.5"">
+                       string second = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" " + Consts.ToolsVersionString + @">
        <PropertyGroup>
          <Prop1>InitialVal</Prop1>
        </PropertyGroup>
@@ -1797,7 +1797,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
                                sw.Write (second);
                        }
 
-                       string third = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion=""3.5"">
+                       string third = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" " + Consts.ToolsVersionString + @">
        <PropertyGroup>
          <ThirdProp>Third Value</ThirdProp>
        </PropertyGroup>
@@ -1972,7 +1972,7 @@ namespace MonoTests.Microsoft.Build.BuildEngine {
                [Test]
                public void TestCaseSensitivityOfProjectElements ()
                {
-                       string projectXml = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion=""3.5"">
+                       string projectXml = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" " + Consts.ToolsVersionString + @">
         <ItemGroup>
                 <Abc Include=""foo"">
                         <MetaDaTA1>md1</MetaDaTA1>
diff --git a/mcs/class/Microsoft.Build.Engine/Test/test-config-file-net-3.5 b/mcs/class/Microsoft.Build.Engine/Test/test-config-file-net-3.5
new file mode 100644 (file)
index 0000000..7756bca
--- /dev/null
@@ -0,0 +1,15 @@
+<?xml version ="1.0"?>
+<configuration>
+    <runtime>
+        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
+            <dependentAssembly>
+                <assemblyIdentity name="Microsoft.Build.Framework" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
+                <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="3.5.0.0"/>
+            </dependentAssembly>
+            <dependentAssembly>
+                <assemblyIdentity name="Microsoft.Build.Engine" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
+                <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="3.5.0.0"/>
+            </dependentAssembly>
+        </assemblyBinding>
+    </runtime>
+</configuration>
diff --git a/mcs/class/Microsoft.Build.Engine/Test/test-config-file-net-4.0 b/mcs/class/Microsoft.Build.Engine/Test/test-config-file-net-4.0
new file mode 100644 (file)
index 0000000..3c78f3b
--- /dev/null
@@ -0,0 +1,15 @@
+<?xml version ="1.0"?>
+<configuration>
+    <runtime>
+        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
+            <dependentAssembly>
+                <assemblyIdentity name="Microsoft.Build.Framework" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
+                <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="4.0.0.0"/>
+            </dependentAssembly>
+            <dependentAssembly>
+                <assemblyIdentity name="Microsoft.Build.Engine" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
+                <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="4.0.0.0"/>
+            </dependentAssembly>
+        </assemblyBinding>
+    </runtime>
+</configuration>
index 74073fb0652a30f45eb94b0f2c51bff4b5275df7..dea06412ca50832f4525f418da8321fd5c1bede0 100644 (file)
@@ -1,3 +1,10 @@
+2010-04-03  Ankit Jain  <jankit@novell.com>
+
+       * Makefile: Import tools/xbuild/xbuild_targets.make, which copies
+       the target and tasks file in the correct place, to allow running
+       tests with different toolsversion.
+       * Microsoft.Build.Framework.dll.sources: Add IBuildEngine2.cs .
+
 2006-04-19  Marek Sieradzki  <marek.sieradzki@gmail.com>
 
        * Microsoft.Build.Framework.targets: Removed.
index 74043402bbc66a63ff7140af0d74033b719c4be2..0cb68bfac6cd19c1a3e79e764060f67ea43dbd21 100644 (file)
@@ -17,5 +17,9 @@ LIB_MCS_FLAGS = \
 
 include ../../build/library.make
 
+export TESTING_MONO=a
+XBUILD_DIR=../../tools/xbuild
+include $(XBUILD_DIR)/xbuild_targets.make
+
 EXTRA_DISTFILES = \
        Mono.XBuild.Framework/AssemblyLoadInfo.cs
index 5be4904c10f3609a81961d77983c30ababacaf93..7e7d3a57db2902586aa9ec7b6326dc55ab653343 100644 (file)
@@ -20,6 +20,7 @@ Microsoft.Build.Framework/CustomBuildEventHandler.cs
 Microsoft.Build.Framework/ExternalProjectFinishedEventArgs.cs
 Microsoft.Build.Framework/ExternalProjectStartedEventArgs.cs
 Microsoft.Build.Framework/IBuildEngine.cs
+Microsoft.Build.Framework/IBuildEngine2.cs
 Microsoft.Build.Framework/IEventSource.cs
 Microsoft.Build.Framework/ILogger.cs
 Microsoft.Build.Framework/ITask.cs
index 47cfed8525ed0c2ab3b08a8e61ca3ff9145f8e85..0f14e7b14208712250993bf2159687d54fb0385a 100644 (file)
@@ -1,3 +1,7 @@
+2010-04-03  Ankit Jain  <jankit@novell.com>
+
+       * IBuildEngine2.cs: New.
+
 2006-12-19  Marek Sieradzki  <marek.sieradzi@gmail.com>
 
        * LoggerException.cs: Changed serialization names.
diff --git a/mcs/class/Microsoft.Build.Framework/Microsoft.Build.Framework/IBuildEngine2.cs b/mcs/class/Microsoft.Build.Framework/Microsoft.Build.Framework/IBuildEngine2.cs
new file mode 100644 (file)
index 0000000..42b456c
--- /dev/null
@@ -0,0 +1,59 @@
+//
+// IBuildEngine2.cs: Provides a way for task authors to use the functionality
+// of the MSBuild engine.
+//
+// Author:
+//     Ankit Jain (jankit@novell.com)
+//
+// Copyright 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+#if NET_2_0
+
+using System;
+using System.Collections;
+
+namespace Microsoft.Build.Framework
+{
+       public interface IBuildEngine2 : IBuildEngine
+       {
+               // Initiates a build of a project file. If the build is
+               // successful, the outputs (if any) of the specified targets
+               // are returned.
+               bool BuildProjectFile (string projectFileName,
+                                      string[] targetNames,
+                                      IDictionary globalProperties,
+                                      IDictionary targetOutputs, string toolsVersion);
+
+               bool BuildProjectFilesInParallel (string[] projectFileNames,
+                                       string [] targetNames,
+                                       IDictionary[] globalProperties,
+                                       IDictionary[] targetOutputsPerProject,
+                                       string[] toolsVersion,
+                                       bool useResultsCache,
+                                       bool unloadProjectsOnCompletion);
+
+               bool IsRunningMultipleNodes { get; }
+
+       }
+}
+
+#endif
index 7e8c05ac911a23255ac88066dbeb2e89d364517b..ff531ad0138f6193cc204abd49f2c52747e33b05 100644 (file)
@@ -1,3 +1,14 @@
+2010-04-03  Ankit Jain  <jankit@novell.com>
+
+       * Makefile: Import tools/xbuild/xbuild_targets.make, which copies
+       the target and tasks file in the correct place, to allow running
+       tests with different toolsversion. Copy the config file for the
+       test assembly. Clean the generated test.dll .
+       Use the correct target assembly name for 4.0 profile
+       (ms.build.tasks.v4.0.dll), and for Utilities assembly.
+       * Microsoft.Build.Tasks_test.dll.sources: Use Consts.cs from Engine
+       instead of maintaining a copy here.
+
 2010-03-02  Ankit Jain  <jankit@novell.com>
 
        Fix tests.
index 70d2cb677526ce4d642a4645711e0adfaf4873e2..34a542a1e1bd586e48d51c51460c8c33f3dd5012 100644 (file)
@@ -14,6 +14,10 @@ else
 
 ifeq (3.5, $(FRAMEWORK_VERSION))
 NAME_SUFFIX = .v3.5
+else
+ifeq (4.0, $(FRAMEWORK_VERSION))
+NAME_SUFFIX = .v4.0
+endif
 endif
 
 LIBRARY_NAME = Microsoft.Build.Tasks$(NAME_SUFFIX).dll
@@ -26,7 +30,7 @@ LIB_MCS_FLAGS = \
        /r:System.Core.dll                      \
        /r:System.Xml.dll                       \
        /r:System.Windows.Forms.dll             \
-       /r:Microsoft.Build.Utilities.dll        \
+       /r:Microsoft.Build.Utilities$(NAME_SUFFIX).dll  \
        /r:Microsoft.Build.Framework.dll        \
        /r:Microsoft.Build.Engine.dll
 
@@ -39,11 +43,35 @@ EXTRA_DISTFILES = \
        Test/resources/test.cs \
        Test/resources/Sample.cs \
        Test/resources/Sample.vb \
-       Test/resources/junk.txt
+       Test/resources/junk.txt \
+       Test/test-config-file*
 
 test-local: Test/resources/test.dll
 
 Test/resources/test.dll: Test/resources/test.cs
        $(CSCOMPILE) -target:library Test/resources/test.cs
 
+clean-local: clean-test-dll
+
+clean-test-dll:
+       rm -f Test/resources/test.dll
+
+test-local: copy-config
+
+ifeq (net_4_0, $(PROFILE))
+copy-config:
+       cp Test/test-config-file-net-4.0 $(test_lib).config
+else
+ifeq (net_3_5, $(PROFILE))
+copy-config:
+       cp Test/test-config-file-net-3.5 $(test_lib).config
+else
+copy-config:
+endif
+endif
+
+export TESTING_MONO=a
+XBUILD_DIR=../../tools/xbuild
+include $(XBUILD_DIR)/xbuild_targets.make
+
 include ../../build/library.make
index 3104cf5673239f2ed9c5bb7d76c9a887d0bb3e43..354d0dc1f908defc93c2fce7f56b1a15f7cb08fa 100644 (file)
@@ -1,3 +1,42 @@
+2010-04-10  Ankit Jain  <jankit@novell.com>
+
+       * GetFrameworkPath.cs (FrameworkVersion40Path): New.
+
+2010-04-10  Ankit Jain  <jankit@novell.com>
+
+       * Copy.cs: Cleanly log errors, instead of throwing exceptions.
+
+2010-04-10  Ankit Jain  <jankit@novell.com>
+
+       * Vbc.cs (LogEventsFromTextOutput):
+       * ToolTask.cs (LogEventsFromTextOutput): Emit the messages
+       that don't match the error regex, as is.
+
+2010-04-08  Ankit Jain  <jankit@novell.com>
+
+       * Copy.cs: Handle non-existant source files.
+
+2010-04-08  Ankit Jain  <jankit@novell.com>
+
+       Fix bug #594541
+       * Vbc.cs (LogEventsFromTextOutput): Override and correctly parse
+       output. Taken regex from monodevelop for this.
+
+2010-04-08  Ankit Jain  <jankit@novell.com>
+
+       * Vbc.cs (ValidateParameters): Always return true, dummy implementation.
+
+2010-04-07  Ankit Jain  <jankit@novell.com>
+
+       * MSBuild.cs: Emit global properties, if any. Sort the property
+       list.
+
+2010-04-03  Ankit Jain  <jankit@novell.com>
+
+       * Csc.cs: Use dmcs as the compiler for 4.0 profile.
+       * MSBuild.cs (ToolsVersion): New.
+       Use toolsVersion for building.
+
 2010-02-10  Ankit Jain  <jankit@novell.com>
 
        * GenerateResource.cs (CompileResourceFile): Check File.Exists
index f704bceb446ed188d52fab433d57a16f3fc13a8a..a090e4716d46179eac1ac836c997a2500907297e 100644 (file)
@@ -57,10 +57,16 @@ namespace Microsoft.Build.Tasks {
                                List <ITaskItem> temporaryCopiedFiles = new List <ITaskItem> ();
                        
                                if (sourceFiles != null && destinationFiles != null &&
-                                       sourceFiles.Length != destinationFiles.Length)
-                                       throw new Exception ("Number of source files is different than number of destination files.");
-                               if (destinationFiles != null && destinationFolder != null)
-                                       throw new Exception ("You must specify only one attribute from DestinationFiles and DestinationFolder");
+                                       sourceFiles.Length != destinationFiles.Length) {
+                                       Log.LogError ("Number of source files is different than number of destination files.");
+                                       return false;
+                               }
+
+                               if (destinationFiles != null && destinationFolder != null) {
+                                       Log.LogError ("You must specify only one attribute from DestinationFiles and DestinationFolder");
+                                       return false;
+                               }
+
                                if (destinationFiles != null && destinationFiles.Length > 0) {
                                        for (int i = 0; i < sourceFiles.Length; i ++) {
                                                ITaskItem sourceItem = sourceFiles [i];
@@ -68,6 +74,11 @@ namespace Microsoft.Build.Tasks {
                                                string sourceFile = sourceItem.GetMetadata ("FullPath");
                                                string destinationFile = destinationItem.GetMetadata ("FullPath");
 
+                                               if (!File.Exists (sourceFile)) {
+                                                       Log.LogError ("Cannot copy {0} to {1}, as the source file doesn't exist.", sourceFile, destinationFile);
+                                                       continue;
+                                               }
+
                                                if (!skipUnchangedFiles || HasFileChanged (sourceFile, destinationFile))
                                                        CopyFile (sourceFile, destinationFile, true);
 
@@ -85,6 +96,11 @@ namespace Microsoft.Build.Tasks {
                                                string filename = sourceItem.GetMetadata ("Filename") + sourceItem.GetMetadata ("Extension");
                                                string destinationFile = Path.Combine (destinationDirectory,filename);
 
+                                               if (!File.Exists (sourceFile)) {
+                                                       Log.LogError ("Cannot copy {0} to {1}, as the source file doesn't exist.", sourceFile, destinationFile);
+                                                       continue;
+                                               }
+
                                                if (!skipUnchangedFiles || directoryCreated ||
                                                        HasFileChanged (sourceFile, destinationFile))
                                                        CopyFile (sourceFile, destinationFile, false);
@@ -99,7 +115,8 @@ namespace Microsoft.Build.Tasks {
                                        }
                                        destinationFiles = temporaryDestinationFiles.ToArray ();
                                } else {
-                                       throw new Exception ("You must specify DestinationFolder or DestinationFiles attribute.");
+                                       Log.LogError ("You must specify DestinationFolder or DestinationFiles attribute.");
+                                       return false;
                                }
                                
                                copiedFiles = temporaryCopiedFiles.ToArray ();
index 8b4217ab32710980bae9dbe07058ec6d843edfca..983996632763a21bb422a1f8a0dc4c97766ba9e8 100644 (file)
@@ -187,7 +187,11 @@ namespace Microsoft.Build.Tasks {
 
                protected override string ToolName {
                        get {
+#if NET_4_0
+                               return Utilities.RunningOnWindows ? "dmcs.bat" : "dmcs";
+#else
                                return Utilities.RunningOnWindows ? "gmcs.bat" : "gmcs";
+#endif
                        }
                }
 
index f32d527913399eb8a099b9057e44b2b991600d50..07e6169fc5a9ec3dd0f053dc60f3c90534acdc12 100644 (file)
@@ -87,6 +87,15 @@ namespace Microsoft.Build.Tasks {
                        }
                }
 
+#if NET_4_0
+               [Output]
+               public string FrameworkVersion40Path {
+                       get {
+                               return ToolLocationHelper.GetPathToDotNetFramework (
+                                               TargetDotNetFrameworkVersion.Version40);
+                       }
+               }
+#endif
        }
 }
 
index 592a41221238d031de3d054a265187f5f93dffd7..90c54cd38c5cb987ae6302701db1ecee5835df44 100644 (file)
@@ -65,9 +65,14 @@ namespace Microsoft.Build.Tasks {
                        string currentDirectory = Environment.CurrentDirectory;
                        Hashtable outputs;
                
-                       Dictionary<string, string> global_properties = SplitPropertiesToDictionary ();
+                       var global_properties = SplitPropertiesToDictionary ();
                        Dictionary<string, ITaskItem> projectsByFileName = new Dictionary<string, ITaskItem> ();
 
+                       Log.LogMessage (MessageImportance.Low, "Global Properties:");
+                       if (global_properties != null)
+                               foreach (KeyValuePair<string, string> pair in global_properties)
+                                       Log.LogMessage (MessageImportance.Low, "\t{0} = {1}", pair.Key, pair.Value);
+
                        foreach (ITaskItem project in projects) {
                                filename = project.GetMetadata ("FullPath");
                                if (!File.Exists (filename)) {
@@ -82,7 +87,14 @@ namespace Microsoft.Build.Tasks {
                                outputs = new Hashtable ();
 
                                try {
-                                       result = BuildEngine.BuildProjectFile (filename, targets, global_properties, outputs);
+                                       // Order of precedence:
+                                       // %(Project.ToolsVersion) , ToolsVersion property
+                                       string tv = project.GetMetadata ("ToolsVersion");
+                                       if (String.IsNullOrEmpty (tv))
+                                               tv = ToolsVersion;
+                                       ThrowIfNotValidToolsVersion (tv);
+
+                                       result = BuildEngine2.BuildProjectFile (filename, targets, global_properties, outputs, tv);
                                } catch (InvalidProjectFileException e) {
                                        Log.LogError ("Error building project {0}: {1}", filename, e.Message);
                                        result = false;
@@ -127,6 +139,12 @@ namespace Microsoft.Build.Tasks {
                        return result;
                }
 
+               void ThrowIfNotValidToolsVersion (string toolsVersion)
+               {
+                       if (!String.IsNullOrEmpty (toolsVersion) && Engine.GlobalEngine.Toolsets [toolsVersion] == null)
+                               throw new Exception (String.Format ("Unknown ToolsVersion : {0}", toolsVersion));
+               }
+
                [Required]
                public ITaskItem [] Projects {
                        get { return projects; }
@@ -170,12 +188,16 @@ namespace Microsoft.Build.Tasks {
                        set { buildInParallel = value; }
                }
 
-               Dictionary<string, string> SplitPropertiesToDictionary ()
+               public string ToolsVersion {
+                       get; set;
+               }
+
+               SortedDictionary<string, string> SplitPropertiesToDictionary ()
                {
                        if (properties == null)
                                return null;
 
-                       Dictionary<string, string> global_properties = new Dictionary<string, string> ();
+                       var global_properties = new SortedDictionary<string, string> ();
                        foreach (string kvpair in properties) {
                                if (String.IsNullOrEmpty (kvpair))
                                        continue;
index 66c0889ce9c4e5cf7f3075ae36609a2128a0fbb3..52a8da8f978be79bc86ba0e2a173806d064435ec 100644 (file)
@@ -31,6 +31,7 @@
 using System;
 using System.IO;
 using System.Text;
+using System.Text.RegularExpressions;
 
 using Microsoft.Build.Framework;
 using Microsoft.Build.Utilities;
@@ -151,9 +152,53 @@ namespace Microsoft.Build.Tasks {
                [MonoTODO]
                protected override bool ValidateParameters ()
                {
-                       throw new NotImplementedException ();
+                       return true;
                }
-               
+
+               protected override void LogEventsFromTextOutput (string singleLine, MessageImportance importance)
+               {
+                       singleLine = singleLine.Trim ();
+                       if (singleLine.Length == 0)
+                               return;
+
+                       // When IncludeDebugInformation is true, prevents the debug symbols stats from braeking this.
+                       if (singleLine.StartsWith ("WROTE SYMFILE") ||
+                               singleLine.StartsWith ("OffsetTable") ||
+                               singleLine.StartsWith ("Compilation succeeded") ||
+                               singleLine.StartsWith ("Compilation failed"))
+                               return;
+
+                       Match match = ErrorRegex.Match (singleLine);
+                       if (!match.Success) {
+                               Log.LogMessage (importance, singleLine);
+                               return;
+                       }
+
+                       string filename = match.Result ("${file}") ?? "";
+
+                       string line = match.Result ("${line}");
+                       int lineNumber = !string.IsNullOrEmpty (line) ? Int32.Parse (line) : 0;
+
+                       string col = match.Result ("${column}");
+                       int columnNumber = 0;
+                       if (!string.IsNullOrEmpty (col))
+                               columnNumber = col == "255+" ? -1 : Int32.Parse (col);
+
+                       string category = match.Result ("${level}");
+                       string code = match.Result ("${number}");
+                       string text = match.Result ("${message}");
+
+                       if (String.Compare (category, "warning", StringComparison.OrdinalIgnoreCase) == 0) {
+                               Log.LogWarning (null, code, null, filename, lineNumber, columnNumber, -1,
+                                       -1, text, null);
+                       } else if (String.Compare (category, "error", StringComparison.OrdinalIgnoreCase) == 0) {
+                               Log.LogError (null, code, null, filename, lineNumber, columnNumber, -1,
+                                       -1, text, null);
+                       } else {
+                               Log.LogMessage (importance, singleLine);
+                       }
+               }
+
                [MonoTODO]
                public string BaseAddress {
                        get { return (string) Bag ["BaseAddress"]; }
@@ -284,6 +329,20 @@ namespace Microsoft.Build.Tasks {
                        get { return (string) Bag ["WarningsNotAsErrors"]; }
                        set { Bag ["WarningsNotAsErrors"] = value; }
                }
+
+               // from md's VBBindingCompilerServices.cs
+               //matches "/home/path/Default.aspx.vb (40,31) : Error VBNC30205: Expected end of statement."
+               //and "Error : VBNC99999: vbnc crashed nearby this location in the source code."
+               //and "Error : VBNC99999: Unexpected error: Object reference not set to an instance of an object"
+               static Regex errorRegex;
+               static Regex ErrorRegex {
+                       get {
+                               if (errorRegex == null)
+                                       errorRegex = new Regex (@"^\s*((?<file>.*)\s?\((?<line>\d*)(,(?<column>\d*))?\) : )?(?<level>\w+) :? ?(?<number>[^:]*): (?<message>.*)$", RegexOptions.Compiled | RegexOptions.ExplicitCapture);
+                               return errorRegex;
+                       }
+               }
+
        }
 }
 
index 4cbc3917c3a19201a0354135b4ffe69795983a6f..0b678d1795c4883847639e62f9765cb4aacd2a35 100644 (file)
@@ -4,7 +4,7 @@ Microsoft.Build.Tasks/AssignProjectConfigurationTest.cs
 Microsoft.Build.Tasks/AssignTargetPathTest.cs
 Microsoft.Build.Tasks/CombinePathTest.cs
 Microsoft.Build.Tasks/CopyTest.cs
-Microsoft.Build.Tasks/Consts.cs
+../../Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/Consts.cs
 Microsoft.Build.Tasks/CreateCSharpManifestResourceNameTest.cs
 Microsoft.Build.Tasks/CreateVisualBasicManifestResourceNameTest.cs
 Microsoft.Build.Tasks/CreateItemTest.cs
index 1458c999c6b8eea4b627b658af1c2937fcaa0b16..3673526ed708c4a6e93dab1f392208fd5c2b9629 100644 (file)
@@ -136,7 +136,7 @@ namespace MonoTests.Microsoft.Build.Tasks
                {
                        StringBuilder sb = new StringBuilder ();
                        sb.Append (@"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">");
-                       sb.Append ("\n<UsingTask TaskName=\"Microsoft.Build.Tasks.AssignProjectConfiguration\" AssemblyName=\"Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" />\n");
+                       sb.Append ("\n" + GetUsingTask ("AssignProjectConfiguration"));
                        sb.AppendFormat (@"<PropertyGroup>{0}</PropertyGroup>", CreateSolutionConfigurationProperty (guids, "Release|AnyCPU"));
                        sb.Append (CreateProjectReferencesItemGroup (project_ref_guids));
 
@@ -179,5 +179,11 @@ namespace MonoTests.Microsoft.Build.Tasks
                        sb.Append ("</ItemGroup>\n");
                        return sb.ToString ();
                }
+               
+               string GetUsingTask (string taskName)
+               {
+                       return "<UsingTask TaskName='Microsoft.Build.Tasks." + taskName + "' AssemblyFile='" + Consts.GetTasksAsmPath () + "' />";
+               }
+
        }
 }
index 8ce07f826a329b3a38639bd2fdc48b852ceac58a..73c326e93e68b00ba82f2db19ee264372f747187 100644 (file)
@@ -1,3 +1,17 @@
+2010-04-06  Ankit Jain  <jankit@novell.com>
+
+       * Consts.cs: Remove.
+       * AssignProjectConfigurationTest.cs:
+       * CreateCSharpManifestResourceNameTest.cs:
+       * CreateVisualBasicManifestResourceNameTest.cs:
+       * CreateItemTest.cs:
+       * FindAppConfigFileTest.cs:
+       * RemoveDuplicatesTest.cs:
+       * TaskBatchingTest.cs:
+       * WriteLinesToFileTest.cs:
+       Set the ToolsVersion to match the profile. Use the
+       full path to the tasks assembly for UsingTasks.
+
 2010-03-04  Ankit Jain  <jankit@novell.com>
 
        * AssignTargetPathTest.cs (CreateProjectString): Remove the
diff --git a/mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/Consts.cs b/mcs/class/Microsoft.Build.Tasks/Test/Microsoft.Build.Tasks/Consts.cs
deleted file mode 100644 (file)
index 2f41a67..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-//
-// Consts.cs
-//
-// Author:
-//   Marek Sieradzki (marek.sieradzki@gmail.com)
-//
-// (C) 2006 Marek Sieradzki
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-using System;
-using Microsoft.Build.Utilities;
-
-public static class Consts {
-
-       static bool RunningOnMono ()
-       {
-               return Type.GetType ("Mono.Runtime") != null;
-       }
-       
-       public static string BinPath {
-               get {
-                       if (RunningOnMono ())
-                               return "../../tools/xbuild/xbuild";
-                       else
-                               return ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20);
-               }
-       }
-}
index 150104c662a475553b3913f216f587cc6a33af77..47f2b75e14f354a54e36a80fe769c70523d96964 100755 (executable)
@@ -235,9 +235,9 @@ namespace MonoTests.Microsoft.Build.Tasks
                        Project project = engine.CreateNewProject ();
                        TestMessageLogger logger = new TestMessageLogger ();
                        engine.RegisterLogger (logger);
-                       Console.WriteLine (projectText);
                        project.LoadXml (projectText);
                        if (!project.Build ("1")) {
+                               Console.WriteLine (projectText);
                                logger.DumpMessages ();
                                Assert.Fail ("Build failed");
                        }
@@ -283,11 +283,16 @@ namespace MonoTests.Microsoft.Build.Tasks
                                sb.AppendFormat (" RootNamespace = \"{0}\"", rootNamespace);
                        sb.Append (">\n \t\t\t<Output TaskParameter=\"ManifestResourceNames\" ItemName=\"ResourceNames\" />\n");
                        sb.Append ("\t\t</CreateCSharpManifestResourceName>\n\t</Target>\n");
-                       sb.Append ("\t<UsingTask TaskName=\"Microsoft.Build.Tasks.CreateCSharpManifestResourceName\" " +
-                               "AssemblyName=\"Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"/>\n");
+                       sb.Append ("\t" + GetUsingTask ("CreateCSharpManifestResourceName"));
                        sb.Append ("</Project>");
 
                        return sb.ToString ();
                }
+               
+               string GetUsingTask (string taskName)
+               {
+                       return "<UsingTask TaskName='Microsoft.Build.Tasks." + taskName + "' AssemblyFile='" + Consts.GetTasksAsmPath () + "' />";
+               }
+
        }
 }
index d16c54572a1b9b5d4fc5e8c87ce8ae4781b8f40b..cfe90118c3871f96118b8ed58999c812adc2d090 100755 (executable)
@@ -252,6 +252,7 @@ namespace MonoTests.Microsoft.Build.Tasks {
 
                }
 
+#if NET_3_5 || NET_4_0
                [Test]
                public void TestItemsWithWildcards () {
                        Engine engine = new Engine (Consts.BinPath);
@@ -274,7 +275,7 @@ namespace MonoTests.Microsoft.Build.Tasks {
                                                          };
 
                        string documentString = @"
-                               <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion=""3.5"">
+                               <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" " + Consts.ToolsVersionString + @">
                                        <PropertyGroup>
                                                <WC>dir\**\*.dll</WC>
                                                <ExWC>*\x*.dll</ExWC>
@@ -318,6 +319,7 @@ namespace MonoTests.Microsoft.Build.Tasks {
                                Directory.Delete (basedir, true);
                        }
                }
+#endif
 
                void CreateDirectoriesAndFiles (string basedir, string[] dirs, string[] files) {
                        foreach (string dir in dirs)
index bb94c5c3af27c5536f7caf838cf52553653549d7..b5b4b18b87fd4dd5f0b18fb729e90468f5a601cd 100755 (executable)
@@ -235,9 +235,9 @@ namespace MonoTests.Microsoft.Build.Tasks
                        Project project = engine.CreateNewProject ();
                        TestMessageLogger logger = new TestMessageLogger ();
                        engine.RegisterLogger (logger);
-                       Console.WriteLine (projectText);
                        project.LoadXml (projectText);
                        if (!project.Build ("1")) {
+                               Console.WriteLine (projectText);
                                logger.DumpMessages ();
                                Assert.Fail ("Build failed");
                        }
@@ -283,11 +283,16 @@ namespace MonoTests.Microsoft.Build.Tasks
                                sb.AppendFormat (" RootNamespace = \"{0}\"", rootNamespace);
                        sb.Append (">\n \t\t\t<Output TaskParameter=\"ManifestResourceNames\" ItemName=\"ResourceNames\" />\n");
                        sb.Append ("\t\t</CreateVisualBasicManifestResourceName>\n\t</Target>\n");
-                       sb.Append ("\t<UsingTask TaskName=\"Microsoft.Build.Tasks.CreateVisualBasicManifestResourceName\" " +
-                               "AssemblyName=\"Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"/>\n");
+                       sb.Append ("\t" + GetUsingTask ("CreateVisualBasicManifestResourceName"));
                        sb.Append ("</Project>");
 
                        return sb.ToString ();
                }
+               
+               string GetUsingTask (string taskName)
+               {
+                       return "<UsingTask TaskName='Microsoft.Build.Tasks." + taskName + "' AssemblyFile='" + Consts.GetTasksAsmPath () + "' />";
+               }
+
        }
 }
index d6b9d0aa4d842745a4edf6367e36181252a4e075..5aaa23086b9873d294a760cd52fd43e04d44287a 100644 (file)
@@ -25,6 +25,8 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
+#if NET_3_5
+
 using System;
 using System.Collections;
 using Microsoft.Build.BuildEngine;
@@ -85,7 +87,7 @@ namespace MonoTests.Microsoft.Build.Tasks {
                void CheckOutput (string[] primary_list, string[] secondary_list, string expected) {
                        StringBuilder sb = new StringBuilder ();
 
-                       sb.Append (@"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion=""3.5"">");
+                       sb.Append (@"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" " + Consts.ToolsVersionString + ">");
                        sb.Append ("\t<ItemGroup>");
                        if (primary_list != null)
                                foreach (string s in primary_list)
@@ -124,4 +126,4 @@ namespace MonoTests.Microsoft.Build.Tasks {
                }
        }
 }      
-
+#endif
index b4c17a8f3716d02c141a25ce5980ce4efb360d6c..6c1975c804c7f89b9a07ddb972ea0eb61fe21d0d 100644 (file)
@@ -44,7 +44,7 @@ namespace MonoTests.Microsoft.Build.Tasks
                public void Test1 ()
                {
                        string documentString = @"
-                                <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion='3.5'>
+                                <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" " + Consts.ToolsVersionString + @">
                                
                                <ItemGroup>
                                        <Items Include='A'>
index 6bfaae755e9ce3f38c2ff715d0480869ecf2784a..e854812b76b16e12f7fd70b0d18dbc87d15eca3c 100755 (executable)
@@ -40,6 +40,12 @@ namespace MonoTests.Microsoft.Build.Tasks
        [TestFixture]
        public class TaskBatchingTest
        {
+               string projectHeader;
+               public TaskBatchingTest ()
+               {
+                       projectHeader = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" " + Consts.ToolsVersionString + ">";
+               }
+
                [Test]
                public void Test1 ()
                {
@@ -548,7 +554,7 @@ namespace MonoTests.Microsoft.Build.Tasks
                // batching should happen only on basis of the task attributes,
                // and not the resolved expression values
                public void TestBatching1 () {
-                       string projectString = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion=""3.5"">
+                       string projectString = projectHeader + @"
        <ItemGroup>
                <item3 Include=""foo""/>
                <item2 Include=""%(item3.Identity)""/>
@@ -584,7 +590,7 @@ namespace MonoTests.Microsoft.Build.Tasks
                // batching should happen only on basis of the task attributes,
                // and not the resolved expression values
                public void TestConditionalBatching2 () {
-                       string projectString = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion=""3.5"">
+                       string projectString = projectHeader + @"
        <ItemGroup>
                <item2 Include=""%(item3.Identity)""/>
                <item4 Include=""%(item2.Identity);@(item3)""/>
@@ -614,7 +620,7 @@ namespace MonoTests.Microsoft.Build.Tasks
 
                [Test]
                public void TestBatchingWithUnbatchedItems () {
-                       string projectString = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion=""3.5"">
+                       string projectString = projectHeader + @"
        <ItemGroup>
                <Item1 Include=""One""/>
                <Item1 Include=""Two""/>
@@ -651,7 +657,7 @@ namespace MonoTests.Microsoft.Build.Tasks
 
                [Test]
                public void TestPropertiesWithBatchedReferences () {
-                       string projectString = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion=""3.5"">
+                       string projectString = projectHeader + @"
        <ItemGroup>
                <Item1 Include=""One""/>
                <Item1 Include=""Two""/>
@@ -693,7 +699,7 @@ namespace MonoTests.Microsoft.Build.Tasks
 
                [Test]
                public void TestPropertiesWithDynamicItems () {
-                       string projectString = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion=""3.5"">
+                       string projectString = projectHeader + @"
        <ItemGroup>
                <Item1 Include=""One""/>
                <Item1 Include=""Two""/>
@@ -748,7 +754,7 @@ namespace MonoTests.Microsoft.Build.Tasks
 
                [Test]
                public void TestTargetInvocationFromBatchedTask () {
-                       string projectString = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion=""3.5"">
+                       string projectString = projectHeader + @"
        <ItemGroup>
                <Item1 Include=""One""/>
                <Item1 Include=""Two""/>
@@ -799,7 +805,7 @@ namespace MonoTests.Microsoft.Build.Tasks
 
                [Test]
                public void TestTargetInvocationFromBatchedTarget () {
-                       string projectString = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion=""3.5"">
+                       string projectString = projectHeader + @"
        <ItemGroup>
                <Item1 Include=""One""/>
                <Item1 Include=""Two""/>
@@ -864,7 +870,7 @@ namespace MonoTests.Microsoft.Build.Tasks
 
                [Test]
                public void TestBatchingWithUnqualifiedMetadataReference () {
-                       string projectString = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion=""3.5"">
+                       string projectString = projectHeader + @"
        <ItemGroup>
                <Item1 Include=""One""><Md>1</Md></Item1>
                <Item1 Include=""Two""><Md>2</Md></Item1>
index 62c03ac7e6bac11d06c03688048fc47f79642396..82d4471a53a66828ed52f2f31a972581e6aa50de 100755 (executable)
@@ -159,7 +159,7 @@ namespace MonoTests.Microsoft.Build.Tasks {
                        Project project;
 
                        StringBuilder sb = new StringBuilder ();
-                       sb.Append (@"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" ToolsVersion='3.5'>
+                       sb.Append (@"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" " + Consts.ToolsVersionString + @">
        <ItemGroup>
 ");
 
diff --git a/mcs/class/Microsoft.Build.Tasks/Test/test-config-file-net-3.5 b/mcs/class/Microsoft.Build.Tasks/Test/test-config-file-net-3.5
new file mode 100644 (file)
index 0000000..7756bca
--- /dev/null
@@ -0,0 +1,15 @@
+<?xml version ="1.0"?>
+<configuration>
+    <runtime>
+        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
+            <dependentAssembly>
+                <assemblyIdentity name="Microsoft.Build.Framework" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
+                <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="3.5.0.0"/>
+            </dependentAssembly>
+            <dependentAssembly>
+                <assemblyIdentity name="Microsoft.Build.Engine" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
+                <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="3.5.0.0"/>
+            </dependentAssembly>
+        </assemblyBinding>
+    </runtime>
+</configuration>
diff --git a/mcs/class/Microsoft.Build.Tasks/Test/test-config-file-net-4.0 b/mcs/class/Microsoft.Build.Tasks/Test/test-config-file-net-4.0
new file mode 100644 (file)
index 0000000..3c78f3b
--- /dev/null
@@ -0,0 +1,15 @@
+<?xml version ="1.0"?>
+<configuration>
+    <runtime>
+        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
+            <dependentAssembly>
+                <assemblyIdentity name="Microsoft.Build.Framework" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
+                <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="4.0.0.0"/>
+            </dependentAssembly>
+            <dependentAssembly>
+                <assemblyIdentity name="Microsoft.Build.Engine" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
+                <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="4.0.0.0"/>
+            </dependentAssembly>
+        </assemblyBinding>
+    </runtime>
+</configuration>
index d82c00379077c1ea0a5f85a22760e9e2eaa83fbe..19ffbef5c9fff167e56559e5d04f882afd0ca9df 100644 (file)
@@ -1,3 +1,10 @@
+2010-04-03  Ankit Jain  <jankit@novell.com>
+
+       * Makefile: Import tools/xbuild/xbuild_targets.make, which copies
+       the target and tasks file in the correct place, to allow running
+       tests with different toolsversion.
+       Use the correct target assembly name for 4.0 profile.
+
 2010-02-10  Ankit Jain  <jankit@novell.com>
 
        * Microsoft.Build.Utilities.dll.sources: Add ProcessStringDictionary.cs
index bbfc0a9f1ae93282b0d27fc6d117bad4550fef78..a600ff9b67e5baba9cc206e50f00cb5285364bd8 100644 (file)
@@ -12,6 +12,10 @@ endif
 
 ifeq (3.5, $(FRAMEWORK_VERSION))
 LIBRARY_NAME = Microsoft.Build.Utilities.v3.5.dll
+else
+ifeq (4.0, $(FRAMEWORK_VERSION))
+LIBRARY_NAME = Microsoft.Build.Utilities.v4.0.dll
+endif
 endif
 
 LIB_MCS_FLAGS = \
@@ -21,4 +25,8 @@ LIB_MCS_FLAGS = \
 
 TEST_MCS_FLAGS = /r:Microsoft.Build.Framework.dll
 
+export TESTING_MONO=a
+XBUILD_DIR=../../tools/xbuild
+include $(XBUILD_DIR)/xbuild_targets.make
+
 include ../../build/library.make
index d7f994b30d9b384d1218c2e7c4fb5466fdf3511f..9b48a6ebad10dc95751fa9872300bf72c768ced4 100644 (file)
@@ -1,3 +1,24 @@
+2010-04-10  Ankit Jain  <jankit@novell.com>
+
+       * ReservedNameUtils.cs (GetReservedMetadata): Handle empty item.
+
+2010-04-08  Ankit Jain  <jankit@novell.com>
+
+       * ToolTask.cs: Use regex to parse output. Regex is from monodevelop.
+
+2010-04-08  Ankit Jain  <jankit@novell.com>
+
+       * ToolTask.cs (ExecuteTool): Check that the tool exists.
+
+2010-04-03  Ankit Jain  <jankit@novell.com>
+
+       * TargetDotNetFrameworkVersion.cs: Add Version40 .
+       * Task.cs (BuildEngine2): New.
+       * ToolLocationHelper.cs: Use class/lib/net_* as the path
+       for the assemblies and targets when running tests.
+       Environment variable TESTING_MONO is set for testing.
+       This allows a 4.0 xbuild to build 2.0/3.5 projects.
+
 2010-02-19  Ankit Jain  <jankit@novell.com>
 
        * TaskItem.cs: Track api changes.
index 451e40ef14584bc5019643ab98c804aded05df38..60cd2dba3dc586491e5bfcd1524c1951b6b32907 100644 (file)
@@ -37,7 +37,12 @@ namespace Microsoft.Build.Utilities
                Version20,
                Version30,
                Version35,
+#if NET_4_0
+               Version40,
+               VersionLatest = Version40
+#else
                VersionLatest = Version35
+#endif
        }
 }
 
index 622763420510eb854d2a4f4fc9273a09dc831e7a..a529e1fafab8051b8295c71fd123c5fb0517056d 100644 (file)
@@ -70,6 +70,10 @@ namespace Microsoft.Build.Utilities
                        }
                }
 
+               public IBuildEngine2 BuildEngine2 {
+                       get { return buildEngine as IBuildEngine2; }
+               }
+
                protected string HelpKeywordPrefix {
                        get {
                                return helpKeywordPrefix;
index 3c132076022b5d981f03fdafb44dd9441fb95e4f..a6c807cfbdfac942da27b1ad8821f38879c14f32 100644 (file)
@@ -50,13 +50,24 @@ namespace Microsoft.Build.Utilities
                        t2 = t1.Parent;
 
                        lib_mono_dir = t2.FullName;
+                       if (Environment.GetEnvironmentVariable ("TESTING_MONO") != null) {
+                               mono_dir = new string [] {
+                                       Path.Combine (lib_mono_dir, "net_1_0"),
+                                       Path.Combine (lib_mono_dir, "net_2_0"),
+                                       Path.Combine (lib_mono_dir, "net_2_0"),
+                                       Path.Combine (lib_mono_dir, "net_3_5"),
+                                       Path.Combine (lib_mono_dir, "net_4_0")
+                               };      
+                       } else {
+                               mono_dir = new string [] {
+                                       Path.Combine (lib_mono_dir, "1.0"),
+                                       Path.Combine (lib_mono_dir, "2.0"),
+                                       Path.Combine (lib_mono_dir, "2.0"),
+                                       Path.Combine (lib_mono_dir, "3.5"),
+                                       Path.Combine (lib_mono_dir, "4.0")
+                               };
+                       }
 
-                       mono_dir = new string [] {
-                               Path.Combine (lib_mono_dir, "1.0"),
-                               Path.Combine (lib_mono_dir, "2.0"),
-                               Path.Combine (lib_mono_dir, "2.0"),
-                               Path.Combine (lib_mono_dir, "3.5")
-                       };
                }
 
                [MonoTODO]
index 2af0265325b47fc905c515e55f3cdd02050a0de6..eed5e7a2760225cdf58dc65d08edfbf467cdfa5f 100644 (file)
@@ -56,8 +56,6 @@ namespace Microsoft.Build.Utilities
                StringBuilder toolOutput;
                bool typeLoadException;
 
-               static Regex            regex;
-               
                protected ToolTask ()
                        : this (null, null)
                {
@@ -81,19 +79,6 @@ namespace Microsoft.Build.Utilities
                        this.environmentOverride = new SCS.ProcessStringDictionary ();
                }
 
-               static ToolTask ()
-               {
-                       regex = new Regex (
-                               @"^\s*"
-                               + @"(((?<ORIGIN>(((\d+>)?[a-zA-Z]?:[^:]*)|([^:]*))):)"
-                               + "|())"
-                               + "(?<SUBCATEGORY>(()|([^:]*? )))"
-                               + "(?<CATEGORY>(error|warning)) "
-                               + "(?<CODE>[^:]*):"
-                               + "(?<TEXT>.*)$",
-                               RegexOptions.IgnoreCase);
-               }
-
                [MonoTODO]
                protected virtual bool CallHostObjectToExecute ()
                {
@@ -126,6 +111,11 @@ namespace Microsoft.Build.Utilities
                        if (pathToTool == null)
                                throw new ArgumentNullException ("pathToTool");
 
+                       if (!File.Exists (pathToTool)) {
+                               Log.LogError ("Tool not found at {0}", pathToTool);
+                               return -1;
+                       }
+
                        string output, error, responseFileName;
                        StreamWriter outwr, errwr;
 
@@ -233,80 +223,33 @@ namespace Microsoft.Build.Utilities
                                singleLine.StartsWith ("Compilation failed"))
                                return;
 
-                       string filename, origin, category, code, subcategory, text;
-                       int lineNumber, columnNumber, endLineNumber, endColumnNumber;
-               
-                       Match m = regex.Match (singleLine);
-                       origin = m.Groups [regex.GroupNumberFromName ("ORIGIN")].Value;
-                       category = m.Groups [regex.GroupNumberFromName ("CATEGORY")].Value;
-                       code = m.Groups [regex.GroupNumberFromName ("CODE")].Value;
-                       subcategory = m.Groups [regex.GroupNumberFromName ("SUBCATEGORY")].Value;
-                       text = m.Groups [regex.GroupNumberFromName ("TEXT")].Value;
-                       
-                       ParseOrigin (origin, out filename, out lineNumber, out columnNumber, out endLineNumber, out endColumnNumber);
-
-                       if (category == "warning") {
-                               Log.LogWarning (subcategory, code, null, filename, lineNumber, columnNumber, endLineNumber,
-                                       endColumnNumber, text, null);
-                       } else if (category == "error") {
-                               Log.LogError (subcategory, code, null, filename, lineNumber, columnNumber, endLineNumber,
-                                       endColumnNumber, text, null);
-                       } else {
+                       Match match = CscErrorRegex.Match (singleLine);
+                       if (!match.Success) {
                                Log.LogMessage (importance, singleLine);
+                               return;
                        }
-               }
-               
-               private void ParseOrigin (string origin, out string filename,
-                                    out int lineNumber, out int columnNumber,
-                                    out int endLineNumber, out int endColumnNumber)
-               {
-                       int lParen;
-                       string[] temp;
-                       string[] left, right;
-                       
-                       if (origin.IndexOf ('(') != -1 ) {
-                               lParen = origin.IndexOf ('(');
-                               filename = origin.Substring (0, lParen);
-                               temp = origin.Substring (lParen + 1, origin.Length - lParen - 2).Split (',');
-                               if (temp.Length == 1) {
-                                       left = temp [0].Split ('-');
-                                       if (left.Length == 1) {
-                                               lineNumber = Int32.Parse (left [0]);
-                                               columnNumber = 0;
-                                               endLineNumber = 0;
-                                               endColumnNumber = 0;
-                                       } else if (left.Length == 2) {
-                                               lineNumber = Int32.Parse (left [0]);
-                                               columnNumber = 0;
-                                               endLineNumber = Int32.Parse (left [1]);
-                                               endColumnNumber = 0;
-                                       } else
-                                               throw new Exception ("Invalid line/column format.");
-                               } else if (temp.Length == 2) {
-                                       right = temp [1].Split ('-');
-                                       lineNumber = Int32.Parse (temp [0]);
-                                       endLineNumber = 0;
-                                       if (right.Length == 1) {
-                                               columnNumber = Int32.Parse (right [0]);
-                                               endColumnNumber = 0;
-                                       } else if (right.Length == 2) {
-                                               columnNumber = Int32.Parse (right [0]);
-                                               endColumnNumber = Int32.Parse (right [0]);
-                                       } else
-                                               throw new Exception ("Invalid line/column format.");
-                               } else if (temp.Length == 4) {
-                                       lineNumber = Int32.Parse (temp [0]);
-                                       endLineNumber = Int32.Parse (temp [2]);
-                                       columnNumber = Int32.Parse (temp [1]);
-                                       endColumnNumber = Int32.Parse (temp [3]);
-                               } else
-                                       throw new Exception ("Invalid line/column format.");
+
+                       string filename = match.Result ("${file}") ?? "";
+                       string line = match.Result ("${line}");
+                       int lineNumber = !string.IsNullOrEmpty (line) ? Int32.Parse (line) : 0;
+
+                       string col = match.Result ("${column}");
+                       int columnNumber = 0;
+                       if (!string.IsNullOrEmpty (col))
+                               columnNumber = col == "255+" ? -1 : Int32.Parse (col);
+
+                       string category = match.Result ("${level}");
+                       string code = match.Result ("${number}");
+                       string text = match.Result ("${message}");
+
+                       if (String.Compare (category, "warning", StringComparison.OrdinalIgnoreCase) == 0) {
+                               Log.LogWarning (null, code, null, filename, lineNumber, columnNumber, -1,
+                                       -1, text, null);
+                       } else if (String.Compare (category, "error", StringComparison.OrdinalIgnoreCase) == 0) {
+                               Log.LogError (null, code, null, filename, lineNumber, columnNumber, -1,
+                                       -1, text, null);
                        } else {
-                               filename = origin;
-                               lineNumber = 0;
-                               columnNumber = 0;
-                               endLineNumber = 0;
-                               endColumnNumber = 0;
+                               Log.LogMessage (importance, singleLine);
                        }
                }
 
@@ -447,6 +390,17 @@ namespace Microsoft.Build.Utilities
                                        toolPath  = value;
                        }
                }
+
+               // Snatched from our codedom code, with some changes to make it compatible with csc
+               // (the line+column group is optional is csc)
+               static Regex errorRegex;
+               static Regex CscErrorRegex {
+                       get {
+                               if (errorRegex == null)
+                                       errorRegex = new Regex (@"^(\s*(?<file>[^\(]+)(\((?<line>\d*)(,(?<column>\d*[\+]*))?\))?:\s+)*(?<level>\w+)\s+(?<number>.*\d):\s*(?<message>.*)", RegexOptions.Compiled | RegexOptions.ExplicitCapture);
+                               return errorRegex;
+                       }
+               }
        }
 }
 
index 49f489948e744c23fd72250b1b631fe3523f77b8..e8379f00be0c623d4c7c1bce5d4c4d985b3126c0 100644 (file)
@@ -72,6 +72,9 @@ namespace Mono.XBuild.Utilities {
                {
                        if (metadataName == null)
                                throw new ArgumentNullException ();
+
+                       if (String.IsNullOrEmpty (itemSpec))
+                               return String.Empty;
                
                        switch (metadataName.ToLower ()) {
                        case "fullpath":
index ff34f3afb7a4cf1e6be103667f6269c372a74350..689f5d03ddf06c72c257c335730b40a73266c70a 100644 (file)
@@ -11,7 +11,7 @@ LIB_MCS_FLAGS = /r:$(corlib) /r:$(CECIL) /d:CECIL -keyfile:$(LIBRARY_SNK)
 
 NO_TEST = yes
 
-ifneq (net_1_1, $(PROFILE))
+ifneq (net_2_0, $(PROFILE))
 NO_INSTALL = yes
 endif
 
index 8570089c59d7708c614b8d05db185c6c881b3db4..140b0ea12905acbcf840cd9d1f11533e84c5127b 100644 (file)
@@ -1,3 +1,20 @@
+2010-04-23  Jb Evain  <jbevain@novell.com>
+
+       * Mono.Cecil/ReflectionWriter.cs: fix writing of exported types.
+
+2010-04-19  Sebastien Pouliot  <sebastien at ximian.com>
+
+       * Mono.Cecil/ReflectionWriter.cs: Partial (forwarders) fix for
+       writing ExternTypes (needed for tuning ML4 correctly)
+
+2010-04-11  Jb Evain  <jbevain@novell.com>
+
+       * Mono.Cecil/GenericParameter.cs: override Module properly.
+
+2010-03-29  Jb Evain  <jbevain@novell.com>
+
+       * Mono.Cecil/AssemblyStripper.cs: optimize.
+
 2010-02-13  Jb Evain  <jbevain@novell.com>
 
        * Mono.Cecil/ReflectionReader.cs: don't cache everything
index 77e72e181d8e21fe1dcd36453349b099f8bf3732..4bd08e9342d9543c2f0d7a7d0946052a17ba3f4a 100644 (file)
@@ -85,10 +85,10 @@ namespace Mono.Cecil {
                                if (!method.HasBody)
                                        continue;
 
-                               method.Body.ExceptionHandlers.Clear();
-                               method.Body.Variables.Clear ();
-                               method.Body.Instructions.Clear ();
-                               method.Body.CilWorker.Emit (OpCodes.Ret);
+                               MethodBody body = new MethodBody (method);
+                               body.CilWorker.Emit (OpCodes.Ret);
+
+                               method.Body = body;
                        }
                }
 
index 04f2e20aebca53c4d58f8ad37cc473b2291c6a4b..99b518201ea269192a9aa25a2cb61bc89670ce11 100644 (file)
@@ -155,7 +155,7 @@ namespace Mono.Cecil {
                                        runtime_path = "v2.0.50727";
                                        break;
                                case "4.0.0.0":
-                                       runtime_path = "v4.0.21006";
+                                       runtime_path = "v4.0.30319";
                                        break;
                                }
                        }
@@ -180,7 +180,7 @@ namespace Mono.Cecil {
                        get {
                                if (m_monoGacPaths == null)
                                        m_monoGacPaths = GetDefaultMonoGacPaths ();
-                               return m_monoGacPaths;  
+                               return m_monoGacPaths;
                        }
                }
 
index 559ec5054ad04d53c3b85375892b5f8fd89d155b..88a58509dee73fc9f74e2dcfecc4d592fbb4f1a6 100644 (file)
@@ -76,6 +76,17 @@ namespace Mono.Cecil {
                        }
                }
 
+               public override ModuleDefinition Module {
+                       get {
+                               if (m_owner is TypeReference)
+                                       return ((TypeReference) m_owner).Module;
+                               if (m_owner is MethodReference)
+                                       return ((MethodReference) m_owner).DeclaringType.Module;
+
+                               throw new InvalidOperationException ();
+                       }
+               }
+
                public override string Name {
                        get {
                                if (m_name != null)
index 5008cbd1515a2bf851130183bb4cee06dee567d3..80b0c11d519f8033d30d522b43f96df175c559f5 100644 (file)
-using System;\r
-using System.Collections;\r
-using System.Runtime.Serialization;\r
-\r
-#if NO_SYSTEM_DLL\r
-namespace System.Collections.Specialized\r
-{\r
-       [Serializable]\r
-       public abstract class NameObjectCollectionBase : ICollection, IEnumerable, ISerializable, IDeserializationCallback\r
-       {\r
-               private Hashtable m_ItemsContainer;\r
-               /// <summary>\r
-               /// Extends Hashtable based Items container to support storing null-key pairs\r
-               /// </summary>\r
-               private _Item m_NullKeyItem;\r
-               private ArrayList m_ItemsArray;\r
-               private IHashCodeProvider m_hashprovider;\r
-               private IComparer m_comparer;\r
-               private int m_defCapacity;\r
-               private bool m_readonly;\r
-               SerializationInfo infoCopy;\r
-               private KeysCollection keyscoll;\r
-#if NET_2_0\r
-               private IEqualityComparer equality_comparer;\r
-\r
-               internal IEqualityComparer EqualityComparer {\r
-                       get { return equality_comparer; }\r
-               }\r
-#endif\r
-               internal IComparer Comparer\r
-               {\r
-                       get { return m_comparer; }\r
-               }\r
-\r
-               internal IHashCodeProvider HashCodeProvider\r
-               {\r
-                       get { return m_hashprovider; }\r
-               }\r
-\r
-               internal class _Item\r
-               {\r
-                       public string key;\r
-                       public object value;\r
-                       public _Item(string key, object value)\r
-                       {\r
-                               this.key = key;\r
-                               this.value = value;\r
-                       }\r
-               }\r
-               /// <summary>\r
-               /// Implements IEnumerable interface for KeysCollection\r
-               /// </summary>\r
-               [Serializable]\r
-               internal class _KeysEnumerator : IEnumerator\r
-               {\r
-                       private NameObjectCollectionBase m_collection;\r
-                       private int m_position;\r
-\r
-                       internal _KeysEnumerator(NameObjectCollectionBase collection)\r
-                       {\r
-                               m_collection = collection;\r
-                               Reset();\r
-                       }\r
-                       public object Current\r
-                       {\r
-\r
-                               get\r
-                               {\r
-                                       if ((m_position < m_collection.Count) || (m_position < 0))\r
-                                               return m_collection.BaseGetKey(m_position);\r
-                                       else\r
-                                               throw new InvalidOperationException();\r
-                               }\r
-\r
-                       }\r
-                       public bool MoveNext()\r
-                       {\r
-                               return ((++m_position) < m_collection.Count);\r
-                       }\r
-                       public void Reset()\r
-                       {\r
-                               m_position = -1;\r
-                       }\r
-               }\r
-\r
-               /// <summary>\r
-               /// SDK: Represents a collection of the String keys of a collection.\r
-               /// </summary>\r
-               [Serializable]\r
-               public class KeysCollection : ICollection, IEnumerable\r
-               {\r
-                       private NameObjectCollectionBase m_collection;\r
-\r
-                       internal KeysCollection(NameObjectCollectionBase collection)\r
-                       {\r
-                               this.m_collection = collection;\r
-                       }\r
-\r
-                       public virtual string Get(int index)\r
-                       {\r
-                               return m_collection.BaseGetKey(index);\r
-                       }\r
-\r
-                       // ICollection methods -----------------------------------\r
-                       void ICollection.CopyTo(Array array, int arrayIndex)\r
-                       {\r
-                               ArrayList items = m_collection.m_ItemsArray;\r
-#if NET_2_0\r
-                               if (null == array)\r
-                                       throw new ArgumentNullException ("array");\r
-\r
-                               if (arrayIndex < 0)\r
-                                       throw new ArgumentOutOfRangeException ("arrayIndex");\r
-\r
-                               if ((array.Length > 0) && (arrayIndex >= array.Length))\r
-                                       throw new ArgumentException ("arrayIndex is equal to or greater than array.Length");\r
-\r
-                               if (arrayIndex + items.Count > array.Length)\r
-                                       throw new ArgumentException ("Not enough room from arrayIndex to end of array for this KeysCollection");\r
-#endif\r
-\r
-                               if (array != null && array.Rank > 1)\r
-                                       throw new ArgumentException("array is multidimensional");\r
-\r
-                               object[] objArray = (object[])array;\r
-                               for (int i = 0; i < items.Count; i++, arrayIndex++)\r
-                                       objArray[arrayIndex] = ((_Item)items[i]).key;\r
-                       }\r
-\r
-                       bool ICollection.IsSynchronized\r
-                       {\r
-                               get\r
-                               {\r
-                                       return false;\r
-                               }\r
-                       }\r
-                       object ICollection.SyncRoot\r
-                       {\r
-                               get\r
-                               {\r
-                                       return m_collection;\r
-                               }\r
-                       }\r
-                       /// <summary>\r
-                       /// Gets the number of keys in the NameObjectCollectionBase.KeysCollection\r
-                       /// </summary>\r
-                       public int Count\r
-                       {\r
-                               get\r
-                               {\r
-                                       return m_collection.Count;\r
-                               }\r
-                       }\r
-\r
-                       public string this[int index]\r
-                       {\r
-                               get { return Get(index); }\r
-                       }\r
-\r
-                       // IEnumerable methods --------------------------------\r
-                       /// <summary>\r
-                       /// SDK: Returns an enumerator that can iterate through the NameObjectCollectionBase.KeysCollection.\r
-                       /// </summary>\r
-                       /// <returns></returns>\r
-                       public IEnumerator GetEnumerator()\r
-                       {\r
-                               return new _KeysEnumerator(m_collection);\r
-                       }\r
-               }\r
-\r
-               //--------------- Protected Instance Constructors --------------\r
-\r
-               /// <summary>\r
-               /// SDK: Initializes a new instance of the NameObjectCollectionBase class that is empty.\r
-               /// </summary>\r
-               protected NameObjectCollectionBase()\r
-               {\r
-                       m_readonly = false;\r
-#if NET_1_0\r
-                       m_hashprovider = CaseInsensitiveHashCodeProvider.Default;\r
-                       m_comparer = CaseInsensitiveComparer.Default;\r
-#else\r
-                       m_hashprovider = CaseInsensitiveHashCodeProvider.DefaultInvariant;\r
-                       m_comparer = CaseInsensitiveComparer.DefaultInvariant;\r
-#endif\r
-                       m_defCapacity = 0;\r
-                       Init();\r
-               }\r
-\r
-               protected NameObjectCollectionBase(int capacity)\r
-               {\r
-                       m_readonly = false;\r
-#if NET_1_0\r
-                       m_hashprovider = CaseInsensitiveHashCodeProvider.Default;\r
-                       m_comparer = CaseInsensitiveComparer.Default;\r
-#else\r
-                       m_hashprovider = CaseInsensitiveHashCodeProvider.DefaultInvariant;\r
-                       m_comparer = CaseInsensitiveComparer.DefaultInvariant;\r
-#endif\r
-                       m_defCapacity = capacity;\r
-                       Init();\r
-               }\r
-\r
-#if NET_2_0\r
-\r
-               internal NameObjectCollectionBase (IEqualityComparer equalityComparer, IComparer comparer, IHashCodeProvider hcp)\r
-               {\r
-                       equality_comparer = equalityComparer;\r
-                       m_comparer = comparer;\r
-                       m_hashprovider = hcp;\r
-                       m_readonly = false;\r
-                       m_defCapacity = 0;\r
-                       Init ();\r
-               }\r
-\r
-               protected NameObjectCollectionBase (IEqualityComparer equalityComparer) : this( (equalityComparer == null ? StringComparer.InvariantCultureIgnoreCase : equalityComparer), null, null)\r
-               {                       \r
-               }               \r
-\r
-               [Obsolete ("Use NameObjectCollectionBase(IEqualityComparer)")]\r
-#endif\r
-               protected NameObjectCollectionBase(IHashCodeProvider hashProvider, IComparer comparer)\r
-               {\r
-                       m_comparer = comparer;\r
-                       m_hashprovider = hashProvider;\r
-                       m_readonly = false;\r
-                       m_defCapacity = 0;\r
-                       Init();\r
-               }\r
-\r
-               protected NameObjectCollectionBase(SerializationInfo info, StreamingContext context)\r
-               {\r
-                       infoCopy = info;\r
-               }\r
-\r
-#if NET_2_0\r
-               protected NameObjectCollectionBase (int capacity, IEqualityComparer equalityComparer)\r
-               {\r
-                       m_readonly = false;\r
-                       equality_comparer = (equalityComparer == null ? StringComparer.InvariantCultureIgnoreCase : equalityComparer);\r
-                       m_defCapacity = capacity;\r
-                       Init();\r
-               }\r
-\r
-               [Obsolete ("Use NameObjectCollectionBase(int,IEqualityComparer)")]\r
-#endif\r
-               protected NameObjectCollectionBase(int capacity, IHashCodeProvider hashProvider, IComparer comparer)\r
-               {\r
-                       m_readonly = false;\r
-\r
-                       m_hashprovider = hashProvider;\r
-                       m_comparer = comparer;\r
-                       m_defCapacity = capacity;\r
-                       Init();\r
-               }\r
-\r
-               private void Init()\r
-               {\r
-#if NET_2_0\r
-                       if (equality_comparer != null)\r
-                               m_ItemsContainer = new Hashtable (m_defCapacity, equality_comparer);\r
-                       else\r
-                               m_ItemsContainer = new Hashtable (m_defCapacity, m_hashprovider, m_comparer);\r
-#else\r
-                       m_ItemsContainer = new Hashtable(m_defCapacity, m_hashprovider, m_comparer);\r
-#endif\r
-                       m_ItemsArray = new ArrayList();\r
-                       m_NullKeyItem = null;\r
-               }\r
-\r
-               //--------------- Public Instance Properties -------------------\r
-\r
-               public virtual NameObjectCollectionBase.KeysCollection Keys\r
-               {\r
-                       get\r
-                       {\r
-                               if (keyscoll == null)\r
-                                       keyscoll = new KeysCollection(this);\r
-                               return keyscoll;\r
-                       }\r
-               }\r
-\r
-               //--------------- Public Instance Methods ----------------------\r
-               // \r
-               /// <summary>\r
-               /// SDK: Returns an enumerator that can iterate through the NameObjectCollectionBase.\r
-               /// \r
-               /// <remark>This enumerator returns the keys of the collection as strings.</remark>\r
-               /// </summary>\r
-               /// <returns></returns>\r
-               public\r
-#if NET_2_0            \r
-               virtual\r
-#endif\r
- IEnumerator GetEnumerator()\r
-               {\r
-                       return new _KeysEnumerator(this);\r
-               }\r
-\r
-               // ISerializable\r
-               public virtual void GetObjectData(SerializationInfo info, StreamingContext context)\r
-               {\r
-                       if (info == null)\r
-                               throw new ArgumentNullException("info");\r
-\r
-                       int count = Count;\r
-                       string[] keys = new string[count];\r
-                       object[] values = new object[count];\r
-                       int i = 0;\r
-                       foreach (_Item item in m_ItemsArray)\r
-                       {\r
-                               keys[i] = item.key;\r
-                               values[i] = item.value;\r
-                               i++;\r
-                       }\r
-\r
-#if NET_2_0\r
-                       if (equality_comparer != null) {\r
-                               info.AddValue ("KeyComparer", equality_comparer, typeof (IEqualityComparer));\r
-                               info.AddValue ("Version", 4, typeof (int));\r
-                       } else {\r
-                               info.AddValue ("HashProvider", m_hashprovider, typeof (IHashCodeProvider));\r
-                               info.AddValue ("Comparer", m_comparer, typeof (IComparer));\r
-                               info.AddValue ("Version", 2, typeof (int));\r
-                       }\r
-#else\r
-                       info.AddValue("HashProvider", m_hashprovider, typeof(IHashCodeProvider));\r
-                       info.AddValue("Comparer", m_comparer, typeof(IComparer));\r
-#endif\r
-                       info.AddValue("ReadOnly", m_readonly);\r
-                       info.AddValue("Count", count);\r
-                       info.AddValue("Keys", keys, typeof(string[]));\r
-                       info.AddValue("Values", values, typeof(object[]));\r
-               }\r
-\r
-               // ICollection\r
-               public virtual int Count\r
-               {\r
-                       get\r
-                       {\r
-                               return m_ItemsArray.Count;\r
-                       }\r
-               }\r
-\r
-               bool ICollection.IsSynchronized\r
-               {\r
-                       get { return false; }\r
-               }\r
-\r
-               object ICollection.SyncRoot\r
-               {\r
-                       get { return this; }\r
-               }\r
-\r
-               void ICollection.CopyTo(Array array, int index)\r
-               {\r
-                       ((ICollection)Keys).CopyTo(array, index);\r
-               }\r
-\r
-               // IDeserializationCallback\r
-               public virtual void OnDeserialization(object sender)\r
-               {\r
-                       SerializationInfo info = infoCopy;\r
-\r
-                       // If a subclass overrides the serialization constructor\r
-                       // and inplements its own serialization process, infoCopy will\r
-                       // be null and we can ignore this callback.\r
-                       if (info == null)\r
-                               return;\r
-\r
-                       infoCopy = null;\r
-                       m_hashprovider = (IHashCodeProvider)info.GetValue("HashProvider",\r
-                                                                               typeof(IHashCodeProvider));\r
-#if NET_2_0\r
-                       if (m_hashprovider == null) {\r
-                               equality_comparer = (IEqualityComparer) info.GetValue ("KeyComparer", typeof (IEqualityComparer));\r
-                       } else {\r
-                               m_comparer = (IComparer) info.GetValue ("Comparer", typeof (IComparer));\r
-                               if (m_comparer == null)\r
-                                       throw new SerializationException ("The comparer is null");\r
-                       }\r
-#else\r
-                       if (m_hashprovider == null)\r
-                               throw new SerializationException("The hash provider is null");\r
-\r
-                       m_comparer = (IComparer)info.GetValue("Comparer", typeof(IComparer));\r
-                       if (m_comparer == null)\r
-                               throw new SerializationException("The comparer is null");\r
-#endif\r
-                       m_readonly = info.GetBoolean("ReadOnly");\r
-                       string[] keys = (string[])info.GetValue("Keys", typeof(string[]));\r
-                       if (keys == null)\r
-                               throw new SerializationException("keys is null");\r
-\r
-                       object[] values = (object[])info.GetValue("Values", typeof(object[]));\r
-                       if (values == null)\r
-                               throw new SerializationException("values is null");\r
-\r
-                       Init();\r
-                       int count = keys.Length;\r
-                       for (int i = 0; i < count; i++)\r
-                               BaseAdd(keys[i], values[i]);\r
-               }\r
-\r
-               //--------------- Protected Instance Properties ----------------\r
-               /// <summary>\r
-               /// SDK: Gets or sets a value indicating whether the NameObjectCollectionBase instance is read-only.\r
-               /// </summary>\r
-               protected bool IsReadOnly\r
-               {\r
-                       get\r
-                       {\r
-                               return m_readonly;\r
-                       }\r
-                       set\r
-                       {\r
-                               m_readonly = value;\r
-                       }\r
-               }\r
-\r
-               //--------------- Protected Instance Methods -------------------\r
-               /// <summary>\r
-               /// Adds an Item with the specified key and value into the <see cref="NameObjectCollectionBase"/>NameObjectCollectionBase instance.\r
-               /// </summary>\r
-               /// <param name="name"></param>\r
-               /// <param name="value"></param>\r
-               protected void BaseAdd(string name, object value)\r
-               {\r
-                       if (this.IsReadOnly)\r
-                               throw new NotSupportedException("Collection is read-only");\r
-\r
-                       _Item newitem = new _Item(name, value);\r
-\r
-                       if (name == null)\r
-                       {\r
-                               //todo: consider nullkey entry\r
-                               if (m_NullKeyItem == null)\r
-                                       m_NullKeyItem = newitem;\r
-                       }\r
-                       else\r
-                               if (m_ItemsContainer[name] == null)\r
-                               {\r
-                                       m_ItemsContainer.Add(name, newitem);\r
-                               }\r
-                       m_ItemsArray.Add(newitem);\r
-               }\r
-\r
-               protected void BaseClear()\r
-               {\r
-                       if (this.IsReadOnly)\r
-                               throw new NotSupportedException("Collection is read-only");\r
-                       Init();\r
-               }\r
-\r
-               /// <summary>\r
-               /// SDK: Gets the value of the entry at the specified index of the NameObjectCollectionBase instance.\r
-               /// </summary>\r
-               /// <param name="index"></param>\r
-               /// <returns></returns>\r
-               protected object BaseGet(int index)\r
-               {\r
-                       return ((_Item)m_ItemsArray[index]).value;\r
-               }\r
-\r
-               /// <summary>\r
-               /// SDK: Gets the value of the first entry with the specified key from the NameObjectCollectionBase instance.\r
-               /// </summary>\r
-               /// <remark>CAUTION: The BaseGet method does not distinguish between a null reference which is returned because the specified key is not found and a null reference which is returned because the value associated with the key is a null reference.</remark>\r
-               /// <param name="name"></param>\r
-               /// <returns></returns>\r
-               protected object BaseGet(string name)\r
-               {\r
-                       _Item item = FindFirstMatchedItem(name);\r
-                       /// CAUTION: The BaseGet method does not distinguish between a null reference which is returned because the specified key is not found and a null reference which is returned because the value associated with the key is a null reference.\r
-                       if (item == null)\r
-                               return null;\r
-                       else\r
-                               return item.value;\r
-               }\r
-\r
-               /// <summary>\r
-               /// SDK:Returns a String array that contains all the keys in the NameObjectCollectionBase instance.\r
-               /// </summary>\r
-               /// <returns>A String array that contains all the keys in the NameObjectCollectionBase instance.</returns>\r
-               protected string[] BaseGetAllKeys()\r
-               {\r
-                       int cnt = m_ItemsArray.Count;\r
-                       string[] allKeys = new string[cnt];\r
-                       for (int i = 0; i < cnt; i++)\r
-                               allKeys[i] = BaseGetKey(i);//((_Item)m_ItemsArray[i]).key;\r
-\r
-                       return allKeys;\r
-               }\r
-\r
-               /// <summary>\r
-               /// SDK: Returns an Object array that contains all the values in the NameObjectCollectionBase instance.\r
-               /// </summary>\r
-               /// <returns>An Object array that contains all the values in the NameObjectCollectionBase instance.</returns>\r
-               protected object[] BaseGetAllValues()\r
-               {\r
-                       int cnt = m_ItemsArray.Count;\r
-                       object[] allValues = new object[cnt];\r
-                       for (int i = 0; i < cnt; i++)\r
-                               allValues[i] = BaseGet(i);\r
-\r
-                       return allValues;\r
-               }\r
-\r
-               protected object[] BaseGetAllValues(Type type)\r
-               {\r
-                       if (type == null)\r
-                               throw new ArgumentNullException("'type' argument can't be null");\r
-                       int cnt = m_ItemsArray.Count;\r
-                       object[] allValues = (object[])Array.CreateInstance(type, cnt);\r
-                       for (int i = 0; i < cnt; i++)\r
-                               allValues[i] = BaseGet(i);\r
-\r
-                       return allValues;\r
-               }\r
-\r
-               protected string BaseGetKey(int index)\r
-               {\r
-                       return ((_Item)m_ItemsArray[index]).key;\r
-               }\r
-\r
-               /// <summary>\r
-               /// Gets a value indicating whether the NameObjectCollectionBase instance contains entries whose keys are not a null reference \r
-               /// </summary>\r
-               /// <returns>true if the NameObjectCollectionBase instance contains entries whose keys are not a null reference otherwise, false.</returns>\r
-               protected bool BaseHasKeys()\r
-               {\r
-                       return (m_ItemsContainer.Count > 0);\r
-               }\r
-\r
-               protected void BaseRemove(string name)\r
-               {\r
-                       int cnt = 0;\r
-                       String key;\r
-                       if (this.IsReadOnly)\r
-                               throw new NotSupportedException("Collection is read-only");\r
-                       if (name != null)\r
-                       {\r
-                               m_ItemsContainer.Remove(name);\r
-                       }\r
-                       else\r
-                       {\r
-                               m_NullKeyItem = null;\r
-                       }\r
-\r
-                       cnt = m_ItemsArray.Count;\r
-                       for (int i = 0; i < cnt; )\r
-                       {\r
-                               key = BaseGetKey(i);\r
-                               if (Equals(key, name))\r
-                               {\r
-                                       m_ItemsArray.RemoveAt(i);\r
-                                       cnt--;\r
-                               }\r
-                               else\r
-                                       i++;\r
-                       }\r
-               }\r
-\r
-               /// <summary>\r
-               /// \r
-               /// </summary>\r
-               /// <param name="index"></param>\r
-               /// <LAME>This function implemented the way Microsoft implemented it - \r
-               /// item is removed from hashtable and array without considering the case when there are two items with the same key but different values in array.\r
-               /// E.g. if\r
-               /// hashtable is [("Key1","value1")] and array contains [("Key1","value1")("Key1","value2")] then\r
-               /// after RemoveAt(1) the collection will be in following state:\r
-               /// hashtable:[] \r
-               /// array: [("Key1","value1")] \r
-               /// It's ok only then the key is uniquely assosiated with the value\r
-               /// To fix it a comparsion of objects stored under the same key in the hashtable and in the arraylist should be added \r
-               /// </LAME>>\r
-               protected void BaseRemoveAt(int index)\r
-               {\r
-                       if (this.IsReadOnly)\r
-                               throw new NotSupportedException("Collection is read-only");\r
-                       string key = BaseGetKey(index);\r
-                       if (key != null)\r
-                       {\r
-                               // TODO: see LAME description above\r
-                               m_ItemsContainer.Remove(key);\r
-                       }\r
-                       else\r
-                               m_NullKeyItem = null;\r
-                       m_ItemsArray.RemoveAt(index);\r
-               }\r
-\r
-               /// <summary>\r
-               /// SDK: Sets the value of the entry at the specified index of the NameObjectCollectionBase instance.\r
-               /// </summary>\r
-               /// <param name="index"></param>\r
-               /// <param name="value"></param>\r
-               protected void BaseSet(int index, object value)\r
-               {\r
-#if NET_2_0\r
-                       if (this.IsReadOnly)\r
-                               throw new NotSupportedException("Collection is read-only");\r
-#endif\r
-                       _Item item = (_Item)m_ItemsArray[index];\r
-                       item.value = value;\r
-               }\r
-\r
-               /// <summary>\r
-               /// Sets the value of the first entry with the specified key in the NameObjectCollectionBase instance, if found; otherwise, adds an entry with the specified key and value into the NameObjectCollectionBase instance.\r
-               /// </summary>\r
-               /// <param name="name">The String key of the entry to set. The key can be a null reference </param>\r
-               /// <param name="value">The Object that represents the new value of the entry to set. The value can be a null reference</param>\r
-               protected void BaseSet(string name, object value)\r
-               {\r
-#if NET_2_0\r
-                       if (this.IsReadOnly)\r
-                               throw new NotSupportedException("Collection is read-only");\r
-#endif\r
-                       _Item item = FindFirstMatchedItem(name);\r
-                       if (item != null)\r
-                               item.value = value;\r
-                       else\r
-                               BaseAdd(name, value);\r
-               }\r
-\r
-               private _Item FindFirstMatchedItem(string name)\r
-               {\r
-                       if (name != null)\r
-                               return (_Item)m_ItemsContainer[name];\r
-                       else\r
-                       {\r
-                               //TODO: consider null key case\r
-                               return m_NullKeyItem;\r
-                       }\r
-               }\r
-\r
-               internal bool Equals(string s1, string s2)\r
-               {\r
-#if NET_2_0\r
-                       if (m_comparer != null)\r
-                               return (m_comparer.Compare (s1, s2) == 0);\r
-                       else\r
-                               return equality_comparer.Equals (s1, s2);\r
-#else\r
-                       return (m_comparer.Compare(s1, s2) == 0);\r
-#endif\r
-               }\r
-       }\r
-}\r
-#endif\r
+using System;
+using System.Collections;
+using System.Runtime.Serialization;
+
+#if NO_SYSTEM_DLL
+namespace System.Collections.Specialized
+{
+       [Serializable]
+       public abstract class NameObjectCollectionBase : ICollection, IEnumerable, ISerializable, IDeserializationCallback
+       {
+               private Hashtable m_ItemsContainer;
+               /// <summary>
+               /// Extends Hashtable based Items container to support storing null-key pairs
+               /// </summary>
+               private _Item m_NullKeyItem;
+               private ArrayList m_ItemsArray;
+               private IHashCodeProvider m_hashprovider;
+               private IComparer m_comparer;
+               private int m_defCapacity;
+               private bool m_readonly;
+               SerializationInfo infoCopy;
+               private KeysCollection keyscoll;
+#if NET_2_0
+               private IEqualityComparer equality_comparer;
+
+               internal IEqualityComparer EqualityComparer {
+                       get { return equality_comparer; }
+               }
+#endif
+               internal IComparer Comparer
+               {
+                       get { return m_comparer; }
+               }
+
+               internal IHashCodeProvider HashCodeProvider
+               {
+                       get { return m_hashprovider; }
+               }
+
+               internal class _Item
+               {
+                       public string key;
+                       public object value;
+                       public _Item(string key, object value)
+                       {
+                               this.key = key;
+                               this.value = value;
+                       }
+               }
+               /// <summary>
+               /// Implements IEnumerable interface for KeysCollection
+               /// </summary>
+               [Serializable]
+               internal class _KeysEnumerator : IEnumerator
+               {
+                       private NameObjectCollectionBase m_collection;
+                       private int m_position;
+
+                       internal _KeysEnumerator(NameObjectCollectionBase collection)
+                       {
+                               m_collection = collection;
+                               Reset();
+                       }
+                       public object Current
+                       {
+
+                               get
+                               {
+                                       if ((m_position < m_collection.Count) || (m_position < 0))
+                                               return m_collection.BaseGetKey(m_position);
+                                       else
+                                               throw new InvalidOperationException();
+                               }
+
+                       }
+                       public bool MoveNext()
+                       {
+                               return ((++m_position) < m_collection.Count);
+                       }
+                       public void Reset()
+                       {
+                               m_position = -1;
+                       }
+               }
+
+               /// <summary>
+               /// SDK: Represents a collection of the String keys of a collection.
+               /// </summary>
+               [Serializable]
+               public class KeysCollection : ICollection, IEnumerable
+               {
+                       private NameObjectCollectionBase m_collection;
+
+                       internal KeysCollection(NameObjectCollectionBase collection)
+                       {
+                               this.m_collection = collection;
+                       }
+
+                       public virtual string Get(int index)
+                       {
+                               return m_collection.BaseGetKey(index);
+                       }
+
+                       // ICollection methods -----------------------------------
+                       void ICollection.CopyTo(Array array, int arrayIndex)
+                       {
+                               ArrayList items = m_collection.m_ItemsArray;
+#if NET_2_0
+                               if (null == array)
+                                       throw new ArgumentNullException ("array");
+
+                               if (arrayIndex < 0)
+                                       throw new ArgumentOutOfRangeException ("arrayIndex");
+
+                               if ((array.Length > 0) && (arrayIndex >= array.Length))
+                                       throw new ArgumentException ("arrayIndex is equal to or greater than array.Length");
+
+                               if (arrayIndex + items.Count > array.Length)
+                                       throw new ArgumentException ("Not enough room from arrayIndex to end of array for this KeysCollection");
+#endif
+
+                               if (array != null && array.Rank > 1)
+                                       throw new ArgumentException("array is multidimensional");
+
+                               object[] objArray = (object[])array;
+                               for (int i = 0; i < items.Count; i++, arrayIndex++)
+                                       objArray[arrayIndex] = ((_Item)items[i]).key;
+                       }
+
+                       bool ICollection.IsSynchronized
+                       {
+                               get
+                               {
+                                       return false;
+                               }
+                       }
+                       object ICollection.SyncRoot
+                       {
+                               get
+                               {
+                                       return m_collection;
+                               }
+                       }
+                       /// <summary>
+                       /// Gets the number of keys in the NameObjectCollectionBase.KeysCollection
+                       /// </summary>
+                       public int Count
+                       {
+                               get
+                               {
+                                       return m_collection.Count;
+                               }
+                       }
+
+                       public string this[int index]
+                       {
+                               get { return Get(index); }
+                       }
+
+                       // IEnumerable methods --------------------------------
+                       /// <summary>
+                       /// SDK: Returns an enumerator that can iterate through the NameObjectCollectionBase.KeysCollection.
+                       /// </summary>
+                       /// <returns></returns>
+                       public IEnumerator GetEnumerator()
+                       {
+                               return new _KeysEnumerator(m_collection);
+                       }
+               }
+
+               //--------------- Protected Instance Constructors --------------
+
+               /// <summary>
+               /// SDK: Initializes a new instance of the NameObjectCollectionBase class that is empty.
+               /// </summary>
+               protected NameObjectCollectionBase()
+               {
+                       m_readonly = false;
+#if NET_1_0
+                       m_hashprovider = CaseInsensitiveHashCodeProvider.Default;
+                       m_comparer = CaseInsensitiveComparer.Default;
+#else
+                       m_hashprovider = CaseInsensitiveHashCodeProvider.DefaultInvariant;
+                       m_comparer = CaseInsensitiveComparer.DefaultInvariant;
+#endif
+                       m_defCapacity = 0;
+                       Init();
+               }
+
+               protected NameObjectCollectionBase(int capacity)
+               {
+                       m_readonly = false;
+#if NET_1_0
+                       m_hashprovider = CaseInsensitiveHashCodeProvider.Default;
+                       m_comparer = CaseInsensitiveComparer.Default;
+#else
+                       m_hashprovider = CaseInsensitiveHashCodeProvider.DefaultInvariant;
+                       m_comparer = CaseInsensitiveComparer.DefaultInvariant;
+#endif
+                       m_defCapacity = capacity;
+                       Init();
+               }
+
+#if NET_2_0
+
+               internal NameObjectCollectionBase (IEqualityComparer equalityComparer, IComparer comparer, IHashCodeProvider hcp)
+               {
+                       equality_comparer = equalityComparer;
+                       m_comparer = comparer;
+                       m_hashprovider = hcp;
+                       m_readonly = false;
+                       m_defCapacity = 0;
+                       Init ();
+               }
+
+               protected NameObjectCollectionBase (IEqualityComparer equalityComparer) : this( (equalityComparer == null ? StringComparer.InvariantCultureIgnoreCase : equalityComparer), null, null)
+               {
+               }
+
+               [Obsolete ("Use NameObjectCollectionBase(IEqualityComparer)")]
+#endif
+               protected NameObjectCollectionBase(IHashCodeProvider hashProvider, IComparer comparer)
+               {
+                       m_comparer = comparer;
+                       m_hashprovider = hashProvider;
+                       m_readonly = false;
+                       m_defCapacity = 0;
+                       Init();
+               }
+
+               protected NameObjectCollectionBase(SerializationInfo info, StreamingContext context)
+               {
+                       infoCopy = info;
+               }
+
+#if NET_2_0
+               protected NameObjectCollectionBase (int capacity, IEqualityComparer equalityComparer)
+               {
+                       m_readonly = false;
+                       equality_comparer = (equalityComparer == null ? StringComparer.InvariantCultureIgnoreCase : equalityComparer);
+                       m_defCapacity = capacity;
+                       Init();
+               }
+
+               [Obsolete ("Use NameObjectCollectionBase(int,IEqualityComparer)")]
+#endif
+               protected NameObjectCollectionBase(int capacity, IHashCodeProvider hashProvider, IComparer comparer)
+               {
+                       m_readonly = false;
+
+                       m_hashprovider = hashProvider;
+                       m_comparer = comparer;
+                       m_defCapacity = capacity;
+                       Init();
+               }
+
+               private void Init()
+               {
+#if NET_2_0
+                       if (equality_comparer != null)
+                               m_ItemsContainer = new Hashtable (m_defCapacity, equality_comparer);
+                       else
+                               m_ItemsContainer = new Hashtable (m_defCapacity, m_hashprovider, m_comparer);
+#else
+                       m_ItemsContainer = new Hashtable(m_defCapacity, m_hashprovider, m_comparer);
+#endif
+                       m_ItemsArray = new ArrayList();
+                       m_NullKeyItem = null;
+               }
+
+               //--------------- Public Instance Properties -------------------
+
+               public virtual NameObjectCollectionBase.KeysCollection Keys
+               {
+                       get
+                       {
+                               if (keyscoll == null)
+                                       keyscoll = new KeysCollection(this);
+                               return keyscoll;
+                       }
+               }
+
+               //--------------- Public Instance Methods ----------------------
+               //
+               /// <summary>
+               /// SDK: Returns an enumerator that can iterate through the NameObjectCollectionBase.
+               ///
+               /// <remark>This enumerator returns the keys of the collection as strings.</remark>
+               /// </summary>
+               /// <returns></returns>
+               public
+#if NET_2_0
+               virtual
+#endif
+ IEnumerator GetEnumerator()
+               {
+                       return new _KeysEnumerator(this);
+               }
+
+               // ISerializable
+               public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
+               {
+                       if (info == null)
+                               throw new ArgumentNullException("info");
+
+                       int count = Count;
+                       string[] keys = new string[count];
+                       object[] values = new object[count];
+                       int i = 0;
+                       foreach (_Item item in m_ItemsArray)
+                       {
+                               keys[i] = item.key;
+                               values[i] = item.value;
+                               i++;
+                       }
+
+#if NET_2_0
+                       if (equality_comparer != null) {
+                               info.AddValue ("KeyComparer", equality_comparer, typeof (IEqualityComparer));
+                               info.AddValue ("Version", 4, typeof (int));
+                       } else {
+                               info.AddValue ("HashProvider", m_hashprovider, typeof (IHashCodeProvider));
+                               info.AddValue ("Comparer", m_comparer, typeof (IComparer));
+                               info.AddValue ("Version", 2, typeof (int));
+                       }
+#else
+                       info.AddValue("HashProvider", m_hashprovider, typeof(IHashCodeProvider));
+                       info.AddValue("Comparer", m_comparer, typeof(IComparer));
+#endif
+                       info.AddValue("ReadOnly", m_readonly);
+                       info.AddValue("Count", count);
+                       info.AddValue("Keys", keys, typeof(string[]));
+                       info.AddValue("Values", values, typeof(object[]));
+               }
+
+               // ICollection
+               public virtual int Count
+               {
+                       get
+                       {
+                               return m_ItemsArray.Count;
+                       }
+               }
+
+               bool ICollection.IsSynchronized
+               {
+                       get { return false; }
+               }
+
+               object ICollection.SyncRoot
+               {
+                       get { return this; }
+               }
+
+               void ICollection.CopyTo(Array array, int index)
+               {
+                       ((ICollection)Keys).CopyTo(array, index);
+               }
+
+               // IDeserializationCallback
+               public virtual void OnDeserialization(object sender)
+               {
+                       SerializationInfo info = infoCopy;
+
+                       // If a subclass overrides the serialization constructor
+                       // and inplements its own serialization process, infoCopy will
+                       // be null and we can ignore this callback.
+                       if (info == null)
+                               return;
+
+                       infoCopy = null;
+                       m_hashprovider = (IHashCodeProvider)info.GetValue("HashProvider",
+                                                                               typeof(IHashCodeProvider));
+#if NET_2_0
+                       if (m_hashprovider == null) {
+                               equality_comparer = (IEqualityComparer) info.GetValue ("KeyComparer", typeof (IEqualityComparer));
+                       } else {
+                               m_comparer = (IComparer) info.GetValue ("Comparer", typeof (IComparer));
+                               if (m_comparer == null)
+                                       throw new SerializationException ("The comparer is null");
+                       }
+#else
+                       if (m_hashprovider == null)
+                               throw new SerializationException("The hash provider is null");
+
+                       m_comparer = (IComparer)info.GetValue("Comparer", typeof(IComparer));
+                       if (m_comparer == null)
+                               throw new SerializationException("The comparer is null");
+#endif
+                       m_readonly = info.GetBoolean("ReadOnly");
+                       string[] keys = (string[])info.GetValue("Keys", typeof(string[]));
+                       if (keys == null)
+                               throw new SerializationException("keys is null");
+
+                       object[] values = (object[])info.GetValue("Values", typeof(object[]));
+                       if (values == null)
+                               throw new SerializationException("values is null");
+
+                       Init();
+                       int count = keys.Length;
+                       for (int i = 0; i < count; i++)
+                               BaseAdd(keys[i], values[i]);
+               }
+
+               //--------------- Protected Instance Properties ----------------
+               /// <summary>
+               /// SDK: Gets or sets a value indicating whether the NameObjectCollectionBase instance is read-only.
+               /// </summary>
+               protected bool IsReadOnly
+               {
+                       get
+                       {
+                               return m_readonly;
+                       }
+                       set
+                       {
+                               m_readonly = value;
+                       }
+               }
+
+               //--------------- Protected Instance Methods -------------------
+               /// <summary>
+               /// Adds an Item with the specified key and value into the <see cref="NameObjectCollectionBase"/>NameObjectCollectionBase instance.
+               /// </summary>
+               /// <param name="name"></param>
+               /// <param name="value"></param>
+               protected void BaseAdd(string name, object value)
+               {
+                       if (this.IsReadOnly)
+                               throw new NotSupportedException("Collection is read-only");
+
+                       _Item newitem = new _Item(name, value);
+
+                       if (name == null)
+                       {
+                               //todo: consider nullkey entry
+                               if (m_NullKeyItem == null)
+                                       m_NullKeyItem = newitem;
+                       }
+                       else
+                               if (m_ItemsContainer[name] == null)
+                               {
+                                       m_ItemsContainer.Add(name, newitem);
+                               }
+                       m_ItemsArray.Add(newitem);
+               }
+
+               protected void BaseClear()
+               {
+                       if (this.IsReadOnly)
+                               throw new NotSupportedException("Collection is read-only");
+                       Init();
+               }
+
+               /// <summary>
+               /// SDK: Gets the value of the entry at the specified index of the NameObjectCollectionBase instance.
+               /// </summary>
+               /// <param name="index"></param>
+               /// <returns></returns>
+               protected object BaseGet(int index)
+               {
+                       return ((_Item)m_ItemsArray[index]).value;
+               }
+
+               /// <summary>
+               /// SDK: Gets the value of the first entry with the specified key from the NameObjectCollectionBase instance.
+               /// </summary>
+               /// <remark>CAUTION: The BaseGet method does not distinguish between a null reference which is returned because the specified key is not found and a null reference which is returned because the value associated with the key is a null reference.</remark>
+               /// <param name="name"></param>
+               /// <returns></returns>
+               protected object BaseGet(string name)
+               {
+                       _Item item = FindFirstMatchedItem(name);
+                       /// CAUTION: The BaseGet method does not distinguish between a null reference which is returned because the specified key is not found and a null reference which is returned because the value associated with the key is a null reference.
+                       if (item == null)
+                               return null;
+                       else
+                               return item.value;
+               }
+
+               /// <summary>
+               /// SDK:Returns a String array that contains all the keys in the NameObjectCollectionBase instance.
+               /// </summary>
+               /// <returns>A String array that contains all the keys in the NameObjectCollectionBase instance.</returns>
+               protected string[] BaseGetAllKeys()
+               {
+                       int cnt = m_ItemsArray.Count;
+                       string[] allKeys = new string[cnt];
+                       for (int i = 0; i < cnt; i++)
+                               allKeys[i] = BaseGetKey(i);//((_Item)m_ItemsArray[i]).key;
+
+                       return allKeys;
+               }
+
+               /// <summary>
+               /// SDK: Returns an Object array that contains all the values in the NameObjectCollectionBase instance.
+               /// </summary>
+               /// <returns>An Object array that contains all the values in the NameObjectCollectionBase instance.</returns>
+               protected object[] BaseGetAllValues()
+               {
+                       int cnt = m_ItemsArray.Count;
+                       object[] allValues = new object[cnt];
+                       for (int i = 0; i < cnt; i++)
+                               allValues[i] = BaseGet(i);
+
+                       return allValues;
+               }
+
+               protected object[] BaseGetAllValues(Type type)
+               {
+                       if (type == null)
+                               throw new ArgumentNullException("'type' argument can't be null");
+                       int cnt = m_ItemsArray.Count;
+                       object[] allValues = (object[])Array.CreateInstance(type, cnt);
+                       for (int i = 0; i < cnt; i++)
+                               allValues[i] = BaseGet(i);
+
+                       return allValues;
+               }
+
+               protected string BaseGetKey(int index)
+               {
+                       return ((_Item)m_ItemsArray[index]).key;
+               }
+
+               /// <summary>
+               /// Gets a value indicating whether the NameObjectCollectionBase instance contains entries whose keys are not a null reference
+               /// </summary>
+               /// <returns>true if the NameObjectCollectionBase instance contains entries whose keys are not a null reference otherwise, false.</returns>
+               protected bool BaseHasKeys()
+               {
+                       return (m_ItemsContainer.Count > 0);
+               }
+
+               protected void BaseRemove(string name)
+               {
+                       int cnt = 0;
+                       String key;
+                       if (this.IsReadOnly)
+                               throw new NotSupportedException("Collection is read-only");
+                       if (name != null)
+                       {
+                               m_ItemsContainer.Remove(name);
+                       }
+                       else
+                       {
+                               m_NullKeyItem = null;
+                       }
+
+                       cnt = m_ItemsArray.Count;
+                       for (int i = 0; i < cnt; )
+                       {
+                               key = BaseGetKey(i);
+                               if (Equals(key, name))
+                               {
+                                       m_ItemsArray.RemoveAt(i);
+                                       cnt--;
+                               }
+                               else
+                                       i++;
+                       }
+               }
+
+               /// <summary>
+               ///
+               /// </summary>
+               /// <param name="index"></param>
+               /// <LAME>This function implemented the way Microsoft implemented it -
+               /// item is removed from hashtable and array without considering the case when there are two items with the same key but different values in array.
+               /// E.g. if
+               /// hashtable is [("Key1","value1")] and array contains [("Key1","value1")("Key1","value2")] then
+               /// after RemoveAt(1) the collection will be in following state:
+               /// hashtable:[]
+               /// array: [("Key1","value1")]
+               /// It's ok only then the key is uniquely assosiated with the value
+               /// To fix it a comparsion of objects stored under the same key in the hashtable and in the arraylist should be added
+               /// </LAME>>
+               protected void BaseRemoveAt(int index)
+               {
+                       if (this.IsReadOnly)
+                               throw new NotSupportedException("Collection is read-only");
+                       string key = BaseGetKey(index);
+                       if (key != null)
+                       {
+                               // TODO: see LAME description above
+                               m_ItemsContainer.Remove(key);
+                       }
+                       else
+                               m_NullKeyItem = null;
+                       m_ItemsArray.RemoveAt(index);
+               }
+
+               /// <summary>
+               /// SDK: Sets the value of the entry at the specified index of the NameObjectCollectionBase instance.
+               /// </summary>
+               /// <param name="index"></param>
+               /// <param name="value"></param>
+               protected void BaseSet(int index, object value)
+               {
+#if NET_2_0
+                       if (this.IsReadOnly)
+                               throw new NotSupportedException("Collection is read-only");
+#endif
+                       _Item item = (_Item)m_ItemsArray[index];
+                       item.value = value;
+               }
+
+               /// <summary>
+               /// Sets the value of the first entry with the specified key in the NameObjectCollectionBase instance, if found; otherwise, adds an entry with the specified key and value into the NameObjectCollectionBase instance.
+               /// </summary>
+               /// <param name="name">The String key of the entry to set. The key can be a null reference </param>
+               /// <param name="value">The Object that represents the new value of the entry to set. The value can be a null reference</param>
+               protected void BaseSet(string name, object value)
+               {
+#if NET_2_0
+                       if (this.IsReadOnly)
+                               throw new NotSupportedException("Collection is read-only");
+#endif
+                       _Item item = FindFirstMatchedItem(name);
+                       if (item != null)
+                               item.value = value;
+                       else
+                               BaseAdd(name, value);
+               }
+
+               private _Item FindFirstMatchedItem(string name)
+               {
+                       if (name != null)
+                               return (_Item)m_ItemsContainer[name];
+                       else
+                       {
+                               //TODO: consider null key case
+                               return m_NullKeyItem;
+                       }
+               }
+
+               internal bool Equals(string s1, string s2)
+               {
+#if NET_2_0
+                       if (m_comparer != null)
+                               return (m_comparer.Compare (s1, s2) == 0);
+                       else
+                               return equality_comparer.Equals (s1, s2);
+#else
+                       return (m_comparer.Compare(s1, s2) == 0);
+#endif
+               }
+       }
+}
+#endif
index ee7f8cb72c533cf476eba9eaef420d6bb5a2fb83..418b8941c78275286b874547dc4e35969e207770 100644 (file)
@@ -425,12 +425,41 @@ namespace Mono.Cecil {
 
                public override void VisitExternTypeCollection (ExternTypeCollection externs)
                {
-                       VisitCollection (externs);
+                       if (externs.Count == 0)
+                               return;
+
+                       ExportedTypeTable etTable = m_tableWriter.GetExportedTypeTable ();
+                       foreach (TypeReference ext in externs) {
+                               TypeDefinition td = ext.Resolve ();
+                               if (td == null)
+                                       continue;
+
+                               MetadataToken scope = GetExportedTypeScope (td);
+
+                               ExportedTypeRow etRow = m_rowWriter.CreateExportedTypeRow (
+                                       td.Attributes,
+                                       0,
+                                       m_mdWriter.AddString (td.Name),
+                                       m_mdWriter.AddString (td.Namespace),
+                                       scope);
+
+                               etTable.Rows.Add (etRow);
+                               ext.MetadataToken = new MetadataToken (TokenType.ExportedType, (uint) etTable.Rows.Count);
+                       }
                }
 
-               public override void VisitExternType (TypeReference externType)
+               MetadataToken GetExportedTypeScope (TypeDefinition t)
                {
-                       // TODO
+                       if (t.DeclaringType != null)
+                               return t.DeclaringType.MetadataToken;
+
+                       if (t.Scope is AssemblyNameReference)
+                               return new MetadataToken (TokenType.AssemblyRef, GetRidFor ((AssemblyNameReference) t.Scope));
+
+                       if (t.Scope is ModuleDefinition)
+                               return new MetadataToken (TokenType.Module, GetRidFor ((ModuleDefinition) t.Scope));
+
+                       throw new NotImplementedException ();
                }
 
                public override void VisitOverrideCollection (OverrideCollection meths)
@@ -860,6 +889,9 @@ namespace Mono.Cecil {
                        if (module.HasCustomAttributes)
                                VisitCustomAttributeCollection (module.CustomAttributes);
 
+                       if (module.ExternTypes.Count > 0)
+                               VisitExternTypeCollection (module.ExternTypes);
+
                        CompleteGenericTables ();
                        SortTables ();
 
index 02f5f2c3868e172d1c933b44d3e2ec717a229c5a..6085cdb42b9e3c37cc27047db46fd1ad6e9214a7 100644 (file)
@@ -105,7 +105,7 @@ namespace Mono.Cecil {
                        case "v2.0.50727":
                                asm.Runtime = TargetRuntime.NET_2_0;
                                break;
-                       case "v4.0.21006" :
+                       case "v4.0.30319" :
                                asm.Runtime = TargetRuntime.NET_4_0;
                                break;
                        }
index 56fda9fcb2cb94911bb9c7c069a143ecae06fe80..da0816093101a98d924b52f792749692d329fe49 100644 (file)
@@ -1,3 +1,9 @@
+2010-04-21  Veerapuram Varadhan  <vvaradhan@novell.com>
+
+       ** Fixes #595918
+       * Tds70.cs (WriteParameterInfo): Write updated decimal value according 
+       to specified scale value.
+       
 2009-08-17  Veerapuram Varadhan  <vvaradhan@novell.com>
 
        ** Fixes #381151 NRE 
index a7c78a0f9e4a57fa2c780cb2b7edcc10072aade9..57fb0914645e385fc2638e012dba459829845478 100644 (file)
@@ -563,6 +563,14 @@ namespace Mono.Data.Tds.Protocol
                        if ( param.TypeName == "decimal" || param.TypeName == "numeric") {
                                Comm.Append ((param.Precision !=0 ) ? param.Precision : (byte) 29);
                                Comm.Append (param.Scale);
+                               // Convert the decimal value according to Scale
+                               if (param.Value != null && param.Value != DBNull.Value &&
+                                   ((decimal)param.Value) != Decimal.MaxValue && 
+                                   ((decimal)param.Value) != Decimal.MinValue) {
+                                       decimal expo = new Decimal (System.Math.Pow (10, (double)param.Scale));
+                                       int pVal = (int)(((decimal)param.Value) * expo);
+                                       param.Value = (decimal)pVal;                            
+                               }
                        }
 
                        
index 7b066b2243eb4a8961eb71f8377b01481dc4db40..cde4e685d64f3564d99888939ec6890205a83238 100644 (file)
@@ -60,4 +60,5 @@ Mono.Debugger.Soft/TypeLoadEvent.cs
 Mono.Debugger.Soft/VMDisconnectEvent.cs
 Mono.Debugger.Soft/InvokeOptions.cs
 Mono.Debugger.Soft/IInvokeAsyncResult.cs
+Mono.Debugger.Soft/IProcess.cs
 
index a2e095eaf19575830d8d52f93dea5fb43ba5fc26..708bb0276cdd7178c65a14ed7fa7bb882b7abc62 100644 (file)
@@ -1,3 +1,17 @@
+2010-04-26  Lluis Sanchez  <lluis@novell.com>
+
+       * IProcess.cs:
+       * VirtualMachine.cs:
+       * VirtualMachineManager.cs:
+       Added new IProcess interface which wraps the debugged process.
+       This abstraction makes it easier to support debugging processes
+       for which we don't have a direct Process reference (for example,
+       if the process is remote).
+
+2010-04-10  Zoltan Varga  <vargaz@gmail.com>
+
+       * ThreadMirror.cs: Add a ThreadId property.
+
 2010-03-05  Martin Baulig  <martin@ximian.com>
 
        Add support for aborting invocations.
index 4088fb667154b40c7d5a28b0d288dc5404da20ee..eace25b3cca9268162737291a31f548b110b07e0 100644 (file)
@@ -303,7 +303,9 @@ namespace Mono.Debugger.Soft
                        GET_FRAME_INFO = 1,
                        GET_NAME = 2,
                        GET_STATE = 3,
-                       GET_INFO = 4
+                       GET_INFO = 4,
+                       /* FIXME: Merge into GET_INFO when the major protocol version is increased */
+                       GET_ID = 5
                }
 
                enum CmdEventRequest {
@@ -1430,6 +1432,10 @@ namespace Mono.Debugger.Soft
                        return res;
                }
 
+               public long Thread_GetId (long id) {
+                       return SendReceive (CommandSet.THREAD, (int)CmdThread.GET_ID, new PacketWriter ().WriteId (id)).ReadLong ();
+               }
+
                /*
                 * MODULE
                 */
diff --git a/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/IProcess.cs b/mcs/class/Mono.Debugger.Soft/Mono.Debugger.Soft/IProcess.cs
new file mode 100644 (file)
index 0000000..ba62ad3
--- /dev/null
@@ -0,0 +1,70 @@
+using System;
+using System.Diagnostics;
+using System.IO;
+
+namespace Mono.Debugger.Soft
+{
+       public interface IProcess
+       {
+               event System.EventHandler Exited;
+               StreamReader StandardOutput { get; }
+               StreamReader StandardError { get; }
+               bool HasExited { get; }
+               void Kill ();
+               int Id { get; }
+               string ProcessName { get; }
+       }
+       
+       internal class ProcessWrapper: IProcess
+       {
+               Process process;
+
+               public ProcessWrapper (Process process)
+               {
+                       this.process = process;
+               }
+               
+               public event System.EventHandler Exited {
+                       add { process.Exited += value; }
+                       remove { process.Exited -= value; }
+               }
+               
+               public StreamReader StandardOutput {
+                       get {
+                               return process.StandardOutput;
+                       }
+               }
+               
+               public StreamReader StandardError {
+                       get {
+                               return process.StandardError;
+                       }
+               }
+               
+               public bool HasExited {
+                       get {
+                               return process.HasExited;
+                       }
+               }
+               
+               public void Kill ()
+               {
+                       process.Kill ();
+               }
+
+               public int Id {
+                       get {
+                               return process.Id;
+                       }
+               }
+               
+               public string ProcessName {
+                       get {
+                               return process.ProcessName;
+                       }
+               }
+               
+               
+               
+       }
+}
index 65e0c0f62ac2bd4344cd7d5aa2bb3a2761b9a900..d18804bd89a67a79b855263af0dc1cb3d2a6d563 100644 (file)
@@ -51,5 +51,15 @@ namespace Mono.Debugger.Soft
                                return info.is_thread_pool;
                        }
                }
+
+               /*
+                * Return a unique identifier for this thread, multiple ThreadMirror objects
+                * may have the same ThreadId because of appdomains.
+                */
+               public long ThreadId {
+                       get {
+                               return vm.conn.Thread_GetId (id);
+                       }
+               }
     }
 }
index b8160781a949d982512d5e67c1dee148df6356b7..6570aeb83cf07b88642192cc12edafc9319f48ad 100644 (file)
@@ -16,11 +16,11 @@ namespace Mono.Debugger.Soft
                object startup_monitor;
                AppDomainMirror root_domain;
                Dictionary<int, EventRequest> requests;
-               Process process;
+               IProcess process;
 
                internal Connection conn;
 
-               internal VirtualMachine (Process process, Connection conn) : base () {
+               internal VirtualMachine (IProcess process, Connection conn) : base () {
                        SetVirtualMachine (this);
                        queue = new Queue ();
                        queue_monitor = new Object ();
@@ -35,7 +35,7 @@ namespace Mono.Debugger.Soft
                public StreamReader StandardOutput { get; set; }
                public StreamReader StandardError { get; set; }
 
-               public Process Process {
+               public IProcess Process {
                        get {
                                return process;
                        }
index 932963473e6d0d2adc381281263c3aa84bc99cb5..17b9032fc2598d16a90e82f1407e1cd92c838e82 100644 (file)
@@ -21,18 +21,18 @@ namespace Mono.Debugger.Soft
                        get; set;
                }
 
-               public delegate Process ProcessLauncher (ProcessStartInfo info);
+               public delegate IProcess ProcessLauncher (ProcessStartInfo info);
        }
 
        public class VirtualMachineManager
        {
-               private delegate VirtualMachine LaunchCallback (Process p, Socket socket);
+               private delegate VirtualMachine LaunchCallback (IProcess p, ProcessStartInfo info, Socket socket);
                private delegate VirtualMachine ListenCallback (Socket dbg_sock, Socket con_sock); 
 
                internal VirtualMachineManager () {
                }
 
-               public static VirtualMachine LaunchInternal (Process p, Socket socket) {
+               public static VirtualMachine LaunchInternal (IProcess p, ProcessStartInfo info, Socket socket) {
                        Socket accepted = null;
                        try {
                                accepted = socket.Accept ();
@@ -44,10 +44,10 @@ namespace Mono.Debugger.Soft
 
                        VirtualMachine vm = new VirtualMachine (p, conn);
 
-                       if (p.StartInfo.RedirectStandardOutput)
+                       if (info.RedirectStandardOutput)
                                vm.StandardOutput = p.StandardOutput;
                        
-                       if (p.StartInfo.RedirectStandardError)
+                       if (info.RedirectStandardError)
                                vm.StandardError = p.StandardError;
 
                        conn.EventHandler = new EventHandler (vm);
@@ -77,18 +77,18 @@ namespace Mono.Debugger.Soft
                        if (options != null && options.Valgrind)
                                info.FileName = "valgrind";
                                
-                       Process p;
+                       IProcess p;
                        if (options != null && options.CustomProcessLauncher != null)
                                p = options.CustomProcessLauncher (info);
                        else
-                               p = Process.Start (info);
+                               p = new ProcessWrapper (Process.Start (info));
                        
                        p.Exited += delegate (object sender, EventArgs eargs) {
                                socket.Close ();
                        };
 
                        LaunchCallback c = new LaunchCallback (LaunchInternal);
-                       return c.BeginInvoke (p, socket, callback, socket);
+                       return c.BeginInvoke (p, info, socket, callback, socket);
                }
 
                public static VirtualMachine EndLaunch (IAsyncResult asyncResult) {
index 3901ef4f9f65e7641465b51ae063fe0e7d72ed02..d1b975c6ce56844a9ea27df526710f7172907bc8 100644 (file)
@@ -1,3 +1,9 @@
+2010-04-15  Jonathan Pryor  <jpryor@novell.com>
+
+       * UnixSignal.cs: Change the native WaitAny() method to accept a
+         Mono_Posix_RuntimeIsShuttingDown delegate, so that we can prevent an
+         infinite loop while shutting the process down.  Fixes #592981.
+
 2009-03-23  Jonathan Pryor  <jpryor@novell.com>
 
        * UnixDriveInfo.cs: UnixDriveInfo.AvailableFreeSpace needs to return 
index fc21e5f9bf966ac701b8f1b8571f0dc4a805dfcf..86a855aeecb40de1b2e5a9ad78ceb11637303933 100644 (file)
@@ -94,9 +94,12 @@ namespace Mono.Unix {
                                EntryPoint="Mono_Unix_UnixSignal_uninstall")]
                private static extern int uninstall (IntPtr info);
 
+               [UnmanagedFunctionPointer (CallingConvention.Cdecl)]
+               delegate int Mono_Posix_RuntimeIsShuttingDown ();
+
                [DllImport (Stdlib.MPH, CallingConvention=CallingConvention.Cdecl,
                                EntryPoint="Mono_Unix_UnixSignal_WaitAny")]
-               private static extern int WaitAny (IntPtr[] infos, int count, int timeout);
+               private static extern int WaitAny (IntPtr[] infos, int count, int timeout, Mono_Posix_RuntimeIsShuttingDown shutting_down);
 
                [DllImport (Stdlib.MPH, CallingConvention=CallingConvention.Cdecl,
                                 EntryPoint="Mono_Posix_SIGRTMIN")]
@@ -199,7 +202,7 @@ namespace Mono.Unix {
                                if (infos [i] == IntPtr.Zero)
                                        throw new InvalidOperationException ("Disposed UnixSignal");
                        }
-                       return WaitAny (infos, infos.Length, millisecondsTimeout);
+                       return WaitAny (infos, infos.Length, millisecondsTimeout, () => Environment.HasShutdownStarted ? 1 : 0);
                }
        }
 }
index e1747f253bdcdbd07a1316e48322dfc93d694336..eda3970564cb67dbd622346c61e1fe70a82a14f8 100644 (file)
@@ -1,3 +1,7 @@
+2010-04-07 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * TlsServerCertificate.cs: display the error code.
+
 2010-03-11 Gonzalo Paniagua Javier <gonzalo@novell.com>
 
        * TlsServerCertificate.cs: chain is built and validated in
index cf17da1223d8b27e205c239e92a1e70dbd8957fd..174e0eb58445bee1cdd6d91518a68e9f5457e475 100644 (file)
@@ -214,7 +214,8 @@ namespace Mono.Security.Protocol.Tls.Handshake.Client
                                        description = AlertDescription.CertificateUnknown;
                                        break;
                                }
-                               throw new TlsException (description, "Invalid certificate received from server.");
+                               string err = String.Format ("0x{0:x}", error);
+                               throw new TlsException (description, "Invalid certificate received from server. Error code: " + err);
                        }
 #endif
                        // the leaf is the web server certificate
index 7c677b39bbd3afa82ba9a4e70bc1eb2b48dcbe67..e6a5442d5ea9c403e5d1ce76cf99a82caa909992 100644 (file)
@@ -1,3 +1,12 @@
+2010-04-23 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * Context.cs:
+       * SslStreamBase.cs:
+       * RecordProtocol.cs: differentiate a received 'CloseNotify' alert from
+       one that we sent. Disposing the stream will try to send the
+       'CloseNotify' alert, if it hasn't already, and ignore any errors. This
+       is needed for FTPS to work.
+
 2010-03-11 Gonzalo Paniagua Javier <gonzalo@novell.com>
 
        * SslStreamBase.cs:
index 295eee5e60621f7c6310fe3ad33992cfc02bb048..792a9970a1774369fcd68897cbe3a3a17fb05aa0 100644 (file)
@@ -76,7 +76,8 @@ namespace Mono.Security.Protocol.Tls
 
                // Misc
                private bool    abbreviatedHandshake;
-               private bool    connectionEnd;
+               private bool    receivedConnectionEnd;
+               private bool    sentConnectionEnd;
                private bool    protocolNegotiated;
                
                // Sequence numbers
@@ -203,10 +204,16 @@ namespace Mono.Security.Protocol.Tls
                        set { this.handshakeState = value; }
                }
 
-               public bool ConnectionEnd
+               public bool ReceivedConnectionEnd
                {
-                       get { return this.connectionEnd; }
-                       set { this.connectionEnd = value; }
+                       get { return this.receivedConnectionEnd; }
+                       set { this.receivedConnectionEnd = value; }
+               }
+
+               public bool SentConnectionEnd
+               {
+                       get { return this.sentConnectionEnd; }
+                       set { this.sentConnectionEnd = value; }
                }
 
                public CipherSuiteCollection SupportedCiphers
index 6ccced66b85d9d50a9a0bf00fe3b58f12e49839b..878233fc95fc742c955b17dcb92b60d9bc00df07 100644 (file)
@@ -311,7 +311,7 @@ namespace Mono.Security.Protocol.Tls
 
                public IAsyncResult BeginReceiveRecord(Stream record, AsyncCallback callback, object state)
                {
-                       if (this.context.ConnectionEnd)
+                       if (this.context.ReceivedConnectionEnd)
                        {
                                throw new TlsException(
                                        AlertDescription.InternalError,
@@ -580,7 +580,7 @@ namespace Mono.Security.Protocol.Tls
                                switch (alertDesc)
                                {
                                        case AlertDescription.CloseNotify:
-                                               this.context.ConnectionEnd = true;
+                                               this.context.ReceivedConnectionEnd = true;
                                                break;
                                }
                                break;
@@ -624,9 +624,8 @@ namespace Mono.Security.Protocol.Tls
                        // Write record
                        this.SendRecord (ContentType.Alert, new byte[2] { (byte) level, (byte) description });
 
-                       if (close)
-                       {
-                               this.context.ConnectionEnd = true;
+                       if (close) {
+                               this.context.SentConnectionEnd = true;
                        }
                }
 
@@ -695,7 +694,7 @@ namespace Mono.Security.Protocol.Tls
 
                public IAsyncResult BeginSendRecord(ContentType contentType, byte[] recordData, AsyncCallback callback, object state)
                {
-                       if (this.context.ConnectionEnd)
+                       if (this.context.SentConnectionEnd)
                        {
                                throw new TlsException(
                                        AlertDescription.InternalError,
@@ -745,7 +744,7 @@ namespace Mono.Security.Protocol.Tls
                        int                     offset,
                        int                     count)
                {
-                       if (this.context.ConnectionEnd)
+                       if (this.context.SentConnectionEnd)
                        {
                                throw new TlsException(
                                        AlertDescription.InternalError,
index f347ccb2bdf72f6e32c170de56b59e468f05f6a5..646f8d928a402dc83b5bd710c58964385616c7b3 100644 (file)
@@ -612,7 +612,7 @@ namespace Mono.Security.Protocol.Tls
                                {
                                        asyncResult.SetComplete(preReadSize);
                                }
-                               else if (!this.context.ConnectionEnd)
+                               else if (!this.context.ReceivedConnectionEnd)
                                {
                                        // this will read data from the network until we have (at least) one
                                        // record to send back to the caller
@@ -731,11 +731,15 @@ namespace Mono.Security.Protocol.Tls
 
                                if (!dataToReturn && (n > 0))
                                {
-                                       // there is no record to return to caller and (possibly) more data waiting
-                                       // so continue reading from network (and appending to stream)
-                                       recordStream.Position = recordStream.Length;
-                                       this.innerStream.BeginRead(recbuf, 0, recbuf.Length,
-                                               new AsyncCallback(InternalReadCallback), state);
+                                       if (context.ReceivedConnectionEnd) {
+                                               internalResult.SetComplete (0);
+                                       } else {
+                                               // there is no record to return to caller and (possibly) more data waiting
+                                               // so continue reading from network (and appending to stream)
+                                               recordStream.Position = recordStream.Length;
+                                               this.innerStream.BeginRead(recbuf, 0, recbuf.Length,
+                                                       new AsyncCallback(InternalReadCallback), state);
+                                       }
                                }
                                else
                                {
@@ -1176,10 +1180,13 @@ namespace Mono.Security.Protocol.Tls
                                        if (this.innerStream != null)
                                        {
                                                if (this.context.HandshakeState == HandshakeState.Finished &&
-                                                       !this.context.ConnectionEnd)
+                                                       !this.context.SentConnectionEnd)
                                                {
-                                                       // Write close notify                                                   
-                                                       this.protocol.SendAlert(AlertDescription.CloseNotify);
+                                                       // Write close notify
+                                                       try {
+                                                               this.protocol.SendAlert(AlertDescription.CloseNotify);
+                                                       } catch {
+                                                       }
                                                }
 
                                                if (this.ownsStream)
index c878a999eacc0b5e21d4d57f24694283e50fa37c..3a1cf930183b92155e5fd1b872a803f6496de0e5 100644 (file)
@@ -206,7 +206,7 @@ namespace Mono.Security {
                                        mask = "yyyyMMddHHmmsszzz";
                                        break;
                        }
-                       return DateTime.ParseExact (t, mask, null, DateTimeStyles.AdjustToUniversal);
+                       return DateTime.ParseExact (t, mask, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
                }
        }
 }
index 56a0e5a2d5fe096b5dd0a5d0096fcc650fadd841..fba575945bf34ae5a0e673f6b3a7ff9f88116832 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-24  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * ASN1Convert.cs: Specify CultureInfo.InvariantCulture (instead of 
+       null) to avoid crash on Windows. Patch by Yoni Shalom.
+
 2008-09-12  Sebastien Pouliot  <sebastien@ximian.com>
 
        * ASN1.cs: Use File.Create instead of OpenWrite to make sure nothing
index 0b78daf5973ff25f9f7fdf4171bd8a9dcbe48c56..2acb3b1e6d6ba10ede711ae6f28614f959045d8e 100644 (file)
@@ -1,3 +1,8 @@
+2010-04-08  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * SubjectAltNameExtensionTest.cs: Add unit tests for multiple
+       DNSNames entries (#594110 and #591516 certificate test case)
+
 2008-06-26  Sebastien Pouliot  <sebastien@ximian.com>
 
        * SubjectAltNameExtensionTest.cs: New. Unit tests for 
index 5c453d68d9c05c0c036288aea1ff9a671bec81bf..9fe01a623d0e5c7e143a4d1e537de61fb105c19c 100644 (file)
@@ -92,5 +92,96 @@ namespace MonoTests.Mono.Security.X509.Extensions {
                        Assert.AreEqual (sane_test.UniformResourceIdentifiers.Length, 0, "URI Count");
                        Assert.AreEqual (sane_test.IPAddresses[0], "192.168.111.111", "IPAddress Test");
                }
+
+               static byte [] multiple_entries_cert = new byte [] {
+                       0x30, 0x82, 0x06, 0x0B, 0x30, 0x82, 0x04, 0xF3, 0xA0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x10, 0x01, 0x47, 0x31, 0x5D, 0x40, 0xFA, 0x32, 0x70, 0xE2, 
+                       0x0F, 0x16, 0x2D, 0xCC, 0xA6, 0x46, 0x0E, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x05, 0x05, 0x00, 0x30, 0x81, 
+                       0xB5, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x17, 0x30, 0x15, 0x06, 0x03, 0x55, 0x04, 0x0A, 0x13, 
+                       0x0E, 0x56, 0x65, 0x72, 0x69, 0x53, 0x69, 0x67, 0x6E, 0x2C, 0x20, 0x49, 0x6E, 0x63, 0x2E, 0x31, 0x1F, 0x30, 0x1D, 0x06, 0x03, 0x55, 0x04, 0x0B, 
+                       0x13, 0x16, 0x56, 0x65, 0x72, 0x69, 0x53, 0x69, 0x67, 0x6E, 0x20, 0x54, 0x72, 0x75, 0x73, 0x74, 0x20, 0x4E, 0x65, 0x74, 0x77, 0x6F, 0x72, 0x6B, 
+                       0x31, 0x3B, 0x30, 0x39, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x32, 0x54, 0x65, 0x72, 0x6D, 0x73, 0x20, 0x6F, 0x66, 0x20, 0x75, 0x73, 0x65, 0x20, 
+                       0x61, 0x74, 0x20, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3A, 0x2F, 0x2F, 0x77, 0x77, 0x77, 0x2E, 0x76, 0x65, 0x72, 0x69, 0x73, 0x69, 0x67, 0x6E, 0x2E, 
+                       0x63, 0x6F, 0x6D, 0x2F, 0x72, 0x70, 0x61, 0x20, 0x28, 0x63, 0x29, 0x30, 0x39, 0x31, 0x2F, 0x30, 0x2D, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x26, 
+                       0x56, 0x65, 0x72, 0x69, 0x53, 0x69, 0x67, 0x6E, 0x20, 0x43, 0x6C, 0x61, 0x73, 0x73, 0x20, 0x33, 0x20, 0x53, 0x65, 0x63, 0x75, 0x72, 0x65, 0x20, 
+                       0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x43, 0x41, 0x20, 0x2D, 0x20, 0x47, 0x32, 0x30, 0x1E, 0x17, 0x0D, 0x30, 0x39, 0x31, 0x32, 0x33, 0x30, 
+                       0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x5A, 0x17, 0x0D, 0x31, 0x31, 0x31, 0x32, 0x33, 0x30, 0x32, 0x33, 0x35, 0x39, 0x35, 0x39, 0x5A, 0x30, 0x81, 
+                       0xDE, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x44, 0x45, 0x31, 0x1B, 0x30, 0x19, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 
+                       0x12, 0x42, 0x61, 0x64, 0x65, 0x6E, 0x2D, 0x57, 0x75, 0x65, 0x72, 0x74, 0x74, 0x65, 0x6D, 0x62, 0x65, 0x72, 0x67, 0x31, 0x11, 0x30, 0x0F, 0x06, 
+                       0x03, 0x55, 0x04, 0x07, 0x14, 0x08, 0x4D, 0x61, 0x6E, 0x6E, 0x68, 0x65, 0x69, 0x6D, 0x31, 0x36, 0x30, 0x34, 0x06, 0x03, 0x55, 0x04, 0x0A, 0x14, 
+                       0x2D, 0x41, 0x44, 0x47, 0x20, 0x41, 0x70, 0x6F, 0x74, 0x68, 0x65, 0x6B, 0x65, 0x6E, 0x20, 0x44, 0x69, 0x65, 0x6E, 0x73, 0x74, 0x6C, 0x65, 0x69, 
+                       0x73, 0x74, 0x75, 0x6E, 0x67, 0x73, 0x67, 0x65, 0x73, 0x65, 0x6C, 0x6C, 0x73, 0x63, 0x68, 0x61, 0x66, 0x74, 0x20, 0x6D, 0x62, 0x48, 0x31, 0x0C, 
+                       0x30, 0x0A, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x14, 0x03, 0x45, 0x44, 0x56, 0x31, 0x33, 0x30, 0x31, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x14, 0x2A, 0x54, 
+                       0x65, 0x72, 0x6D, 0x73, 0x20, 0x6F, 0x66, 0x20, 0x75, 0x73, 0x65, 0x20, 0x61, 0x74, 0x20, 0x77, 0x77, 0x77, 0x2E, 0x76, 0x65, 0x72, 0x69, 0x73, 
+                       0x69, 0x67, 0x6E, 0x2E, 0x63, 0x6F, 0x6D, 0x2F, 0x72, 0x70, 0x61, 0x20, 0x28, 0x63, 0x29, 0x30, 0x35, 0x31, 0x24, 0x30, 0x22, 0x06, 0x03, 0x55, 
+                       0x04, 0x03, 0x14, 0x1B, 0x77, 0x77, 0x77, 0x2E, 0x61, 0x33, 0x30, 0x30, 0x30, 0x2D, 0x66, 0x69, 0x6C, 0x69, 0x61, 0x6C, 0x61, 0x70, 0x6F, 0x74, 
+                       0x68, 0x65, 0x6B, 0x65, 0x2E, 0x64, 0x65, 0x30, 0x81, 0x9F, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 
+                       0x00, 0x03, 0x81, 0x8D, 0x00, 0x30, 0x81, 0x89, 0x02, 0x81, 0x81, 0x00, 0xAE, 0xF3, 0xD4, 0xFE, 0x33, 0x44, 0x0F, 0x68, 0xBB, 0x4C, 0x6D, 0x5F, 
+                       0xAF, 0xE7, 0xBC, 0x20, 0x05, 0xE3, 0xCB, 0xD6, 0x9D, 0x7A, 0x68, 0x8B, 0x3D, 0x63, 0x9B, 0xED, 0x31, 0x4E, 0x7E, 0xE7, 0x0A, 0x80, 0xF5, 0xDD, 
+                       0x29, 0xDE, 0x02, 0x71, 0x82, 0xE7, 0x69, 0x02, 0xBC, 0xAC, 0xA6, 0x09, 0xFF, 0x3A, 0x41, 0xCB, 0x3C, 0x9C, 0x68, 0xB0, 0x80, 0xA6, 0xAF, 0x4C, 
+                       0xED, 0xE7, 0xA7, 0xF1, 0x74, 0x63, 0x3A, 0xF7, 0xC8, 0x66, 0x84, 0x6D, 0xE5, 0x5B, 0x9B, 0x45, 0xBC, 0x78, 0x84, 0x3E, 0x1A, 0x82, 0x84, 0x8C, 
+                       0xB2, 0x06, 0x64, 0x62, 0xB7, 0xB0, 0xE6, 0x9E, 0x5F, 0xAF, 0x58, 0x93, 0xAC, 0xCE, 0x04, 0x71, 0x2A, 0x11, 0xD9, 0xD5, 0x4E, 0xD0, 0x7F, 0x9E, 
+                       0xF7, 0x92, 0x5F, 0x83, 0xAE, 0x32, 0x1F, 0x2E, 0x1B, 0xDD, 0x34, 0xE8, 0x28, 0xC8, 0x4D, 0x97, 0x20, 0xBA, 0xE8, 0x6B, 0x02, 0x03, 0x01, 0x00, 
+                       0x01, 0xA3, 0x82, 0x02, 0x6E, 0x30, 0x82, 0x02, 0x6A, 0x30, 0x81, 0x9A, 0x06, 0x03, 0x55, 0x1D, 0x11, 0x04, 0x81, 0x92, 0x30, 0x81, 0x8F, 0x82, 
+                       0x21, 0x77, 0x77, 0x77, 0x2E, 0x61, 0x72, 0x7A, 0x6E, 0x65, 0x69, 0x6D, 0x69, 0x74, 0x74, 0x65, 0x6C, 0x2D, 0x62, 0x65, 0x73, 0x74, 0x65, 0x6C, 
+                       0x6C, 0x63, 0x65, 0x6E, 0x74, 0x65, 0x72, 0x2E, 0x64, 0x65, 0x82, 0x26, 0x77, 0x77, 0x77, 0x2E, 0x78, 0x6E, 0x65, 0x74, 0x2D, 0x61, 0x72, 0x7A, 
+                       0x6E, 0x65, 0x69, 0x6D, 0x69, 0x74, 0x74, 0x65, 0x6C, 0x2D, 0x62, 0x65, 0x73, 0x74, 0x65, 0x6C, 0x6C, 0x63, 0x65, 0x6E, 0x74, 0x65, 0x72, 0x2E, 
+                       0x64, 0x65, 0x82, 0x25, 0x77, 0x77, 0x77, 0x2E, 0x61, 0x64, 0x67, 0x2D, 0x61, 0x72, 0x7A, 0x6E, 0x65, 0x69, 0x6D, 0x69, 0x74, 0x74, 0x65, 0x6C, 
+                       0x2D, 0x62, 0x65, 0x73, 0x74, 0x65, 0x6C, 0x6C, 0x63, 0x65, 0x6E, 0x74, 0x65, 0x72, 0x2E, 0x64, 0x65, 0x82, 0x1B, 0x77, 0x77, 0x77, 0x2E, 0x61, 
+                       0x33, 0x30, 0x30, 0x30, 0x2D, 0x66, 0x69, 0x6C, 0x69, 0x61, 0x6C, 0x61, 0x70, 0x6F, 0x74, 0x68, 0x65, 0x6B, 0x65, 0x2E, 0x64, 0x65, 0x30, 0x09, 
+                       0x06, 0x03, 0x55, 0x1D, 0x13, 0x04, 0x02, 0x30, 0x00, 0x30, 0x0B, 0x06, 0x03, 0x55, 0x1D, 0x0F, 0x04, 0x04, 0x03, 0x02, 0x05, 0xA0, 0x30, 0x45, 
+                       0x06, 0x03, 0x55, 0x1D, 0x1F, 0x04, 0x3E, 0x30, 0x3C, 0x30, 0x3A, 0xA0, 0x38, 0xA0, 0x36, 0x86, 0x34, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 
+                       0x53, 0x56, 0x52, 0x53, 0x65, 0x63, 0x75, 0x72, 0x65, 0x2D, 0x47, 0x32, 0x2D, 0x63, 0x72, 0x6C, 0x2E, 0x76, 0x65, 0x72, 0x69, 0x73, 0x69, 0x67, 
+                       0x6E, 0x2E, 0x63, 0x6F, 0x6D, 0x2F, 0x53, 0x56, 0x52, 0x53, 0x65, 0x63, 0x75, 0x72, 0x65, 0x47, 0x32, 0x2E, 0x63, 0x72, 0x6C, 0x30, 0x44, 0x06, 
+                       0x03, 0x55, 0x1D, 0x20, 0x04, 0x3D, 0x30, 0x3B, 0x30, 0x39, 0x06, 0x0B, 0x60, 0x86, 0x48, 0x01, 0x86, 0xF8, 0x45, 0x01, 0x07, 0x17, 0x03, 0x30, 
+                       0x2A, 0x30, 0x28, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x02, 0x01, 0x16, 0x1C, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3A, 0x2F, 0x2F, 0x77, 
+                       0x77, 0x77, 0x2E, 0x76, 0x65, 0x72, 0x69, 0x73, 0x69, 0x67, 0x6E, 0x2E, 0x63, 0x6F, 0x6D, 0x2F, 0x72, 0x70, 0x61, 0x30, 0x1D, 0x06, 0x03, 0x55, 
+                       0x1D, 0x25, 0x04, 0x16, 0x30, 0x14, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 
+                       0x03, 0x02, 0x30, 0x1F, 0x06, 0x03, 0x55, 0x1D, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0xA5, 0xEF, 0x0B, 0x11, 0xCE, 0xC0, 0x41, 0x03, 0xA3, 
+                       0x4A, 0x65, 0x90, 0x48, 0xB2, 0x1C, 0xE0, 0x57, 0x2D, 0x7D, 0x47, 0x30, 0x76, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x01, 0x01, 0x04, 
+                       0x6A, 0x30, 0x68, 0x30, 0x24, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x01, 0x86, 0x18, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 
+                       0x6F, 0x63, 0x73, 0x70, 0x2E, 0x76, 0x65, 0x72, 0x69, 0x73, 0x69, 0x67, 0x6E, 0x2E, 0x63, 0x6F, 0x6D, 0x30, 0x40, 0x06, 0x08, 0x2B, 0x06, 0x01, 
+                       0x05, 0x05, 0x07, 0x30, 0x02, 0x86, 0x34, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 0x53, 0x56, 0x52, 0x53, 0x65, 0x63, 0x75, 0x72, 0x65, 0x2D, 
+                       0x47, 0x32, 0x2D, 0x61, 0x69, 0x61, 0x2E, 0x76, 0x65, 0x72, 0x69, 0x73, 0x69, 0x67, 0x6E, 0x2E, 0x63, 0x6F, 0x6D, 0x2F, 0x53, 0x56, 0x52, 0x53, 
+                       0x65, 0x63, 0x75, 0x72, 0x65, 0x47, 0x32, 0x2E, 0x63, 0x65, 0x72, 0x30, 0x6E, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x01, 0x0C, 0x04, 
+                       0x62, 0x30, 0x60, 0xA1, 0x5E, 0xA0, 0x5C, 0x30, 0x5A, 0x30, 0x58, 0x30, 0x56, 0x16, 0x09, 0x69, 0x6D, 0x61, 0x67, 0x65, 0x2F, 0x67, 0x69, 0x66, 
+                       0x30, 0x21, 0x30, 0x1F, 0x30, 0x07, 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A, 0x04, 0x14, 0x4B, 0x6B, 0xB9, 0x28, 0x96, 0x06, 0x0C, 0xBB, 0xD0, 
+                       0x52, 0x38, 0x9B, 0x29, 0xAC, 0x4B, 0x07, 0x8B, 0x21, 0x05, 0x18, 0x30, 0x26, 0x16, 0x24, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 0x6C, 0x6F, 
+                       0x67, 0x6F, 0x2E, 0x76, 0x65, 0x72, 0x69, 0x73, 0x69, 0x67, 0x6E, 0x2E, 0x63, 0x6F, 0x6D, 0x2F, 0x76, 0x73, 0x6C, 0x6F, 0x67, 0x6F, 0x31, 0x2E, 
+                       0x67, 0x69, 0x66, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x05, 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x2F, 
+                       0x1E, 0x71, 0x21, 0xD9, 0xCE, 0xBB, 0x16, 0xEA, 0xA2, 0xD9, 0x5B, 0xA6, 0x0E, 0x1B, 0x9A, 0x32, 0xC2, 0xFA, 0x38, 0xF5, 0x3F, 0xC7, 0xEE, 0xFC, 
+                       0xD7, 0xBE, 0x92, 0x14, 0xAA, 0xBE, 0x94, 0x63, 0xE6, 0xCE, 0x46, 0x9D, 0x28, 0x11, 0x6E, 0x8D, 0x64, 0xDB, 0x4B, 0x7D, 0x03, 0xD2, 0xE7, 0x6B, 
+                       0x23, 0xA4, 0xD2, 0x67, 0xFE, 0x1B, 0xFC, 0x7E, 0x2C, 0xAA, 0xB6, 0x1F, 0x36, 0xD5, 0x65, 0x47, 0xCE, 0xC1, 0x4C, 0xD2, 0x83, 0xBA, 0x1A, 0x8E, 
+                       0x39, 0x74, 0x0E, 0xCC, 0x29, 0x1A, 0x91, 0x09, 0x32, 0x5F, 0x01, 0x14, 0x7A, 0xC8, 0x9C, 0x14, 0x36, 0x78, 0x5F, 0xB0, 0x5E, 0x07, 0xFD, 0x34, 
+                       0xD1, 0x93, 0xD6, 0x79, 0xA0, 0xC1, 0xA0, 0xF2, 0xD7, 0xF0, 0x5E, 0xF7, 0x57, 0xB0, 0xE7, 0x75, 0x60, 0xC5, 0xE6, 0x4F, 0xA9, 0x78, 0x72, 0x47, 
+                       0x72, 0x8F, 0x8A, 0x6B, 0xCD, 0x3D, 0x0D, 0x56, 0xB1, 0x85, 0x5B, 0x2E, 0x1F, 0xF1, 0x00, 0x86, 0x83, 0x72, 0xD4, 0x80, 0x71, 0x1A, 0xBB, 0x08, 
+                       0xCC, 0x6B, 0x67, 0xDA, 0x9B, 0xCB, 0x99, 0xDD, 0xAF, 0x27, 0x0F, 0xCE, 0x30, 0x02, 0x69, 0x74, 0x64, 0x3C, 0x68, 0xB5, 0xFF, 0x60, 0x5F, 0x1D, 
+                       0x6A, 0xBB, 0xF5, 0x0D, 0xC5, 0x96, 0x85, 0xDA, 0x36, 0x4E, 0xF3, 0x84, 0x97, 0x62, 0x9E, 0x18, 0x6E, 0xA9, 0x8D, 0xFD, 0x54, 0x9E, 0x39, 0xFA, 
+                       0x4A, 0x38, 0xF6, 0xF1, 0x1C, 0x63, 0x5D, 0x09, 0x09, 0xC4, 0x18, 0xA9, 0x8C, 0x96, 0x75, 0xEB, 0x0D, 0x91, 0xA5, 0xE8, 0x7E, 0x08, 0x38, 0x49, 
+                       0x77, 0x10, 0x05, 0xF0, 0xD9, 0x57, 0x5A, 0xE2, 0xA0, 0x0C, 0x10, 0x03, 0x46, 0xA2, 0xD1, 0x6A, 0x12, 0x21, 0x81, 0x24, 0x35, 0x94, 0x51, 0x93, 
+                       0x2E, 0x5D, 0x91, 0x2D, 0xAE, 0xB6, 0xBE, 0xFA, 0x26, 0x12, 0xB5, 0x38, 0x9A, 0xAD, 0x6E
+               };
+
+               [Test]
+               public void MultipleEntriesInExtension ()
+               {
+                       X509Certificate cert = new X509Certificate (multiple_entries_cert);
+                       SubjectAltNameExtension sane = new SubjectAltNameExtension (cert.Extensions ["2.5.29.17"]);
+                       Assert.AreEqual (4, sane.DNSNames.Length, "Count");
+                       Assert.AreEqual ("www.arzneimittel-bestellcenter.de", sane.DNSNames [0], "0");
+                       Assert.AreEqual ("www.xnet-arzneimittel-bestellcenter.de", sane.DNSNames [1], "1");
+                       Assert.AreEqual ("www.adg-arzneimittel-bestellcenter.de", sane.DNSNames [2], "2");
+                       Assert.AreEqual ("www.a3000-filialapotheke.de", sane.DNSNames [3], "3");
+               }
+
+               [Test]
+               public void MultipleEntriesInExtension_AsASN1 ()
+               {
+                       X509Certificate cert = new X509Certificate (multiple_entries_cert);
+                       SubjectAltNameExtension sane = new SubjectAltNameExtension (cert.Extensions ["2.5.29.17"].ASN1);
+                       Assert.AreEqual ("www.arzneimittel-bestellcenter.de", sane.DNSNames [0], "0");
+                       Assert.AreEqual ("www.xnet-arzneimittel-bestellcenter.de", sane.DNSNames [1], "1");
+                       Assert.AreEqual ("www.adg-arzneimittel-bestellcenter.de", sane.DNSNames [2], "2");
+                       Assert.AreEqual ("www.a3000-filialapotheke.de", sane.DNSNames [3], "3");
+               }
        }
 }
index 8ab1729a9e21c41ad8f24cb6fec9d0c358aabfde..e508f043319f7b68b7e625cfcf5bf1aeeb5098db 100644 (file)
@@ -1,3 +1,7 @@
+2010-03-24 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Vector4f.cs: Add vector x scalar multiply.
+
 2009-09-18 Rodrigo Kumpera  <rkumpera@novell.com>
 
        * SimdRuntime.cs: Raise an exception if the method been queried
index 77ba2cd6def328504fde43dabe8d54f3660ce61d..db7143b9b4952b293cdef1282405e012f7df392a 100644 (file)
@@ -80,9 +80,7 @@ namespace Mono.Simd
         Abs (implemented as pand [7fffffff,...] )
         Comparison functions
         Mask extraction function
-        Setters
         vector x float ops
-        Single float constructor (expand it to the 4 positions)
                Replace Shuffle with less bug prone methods
 */
 
@@ -223,6 +221,18 @@ namespace Mono.Simd
                        return new Vector4f (v1.x * v2.x, v1.y * v2.y, v1.z * v2.z, v1.w * v2.w);
                }
 
+               [Acceleration (AccelMode.SSE1)]
+               public static Vector4f operator * (float scalar, Vector4f v)
+               {
+                       return new Vector4f (scalar * v.x, scalar * v.y, scalar * v.z, scalar * v.w);
+               }
+
+               [Acceleration (AccelMode.SSE1)]
+               public static Vector4f operator * (Vector4f v, float scalar)
+               {
+                       return new Vector4f (scalar * v.x, scalar * v.y, scalar * v.z, scalar * v.w);
+               }
+
                [Acceleration (AccelMode.SSE1)]
                public static Vector4f operator / (Vector4f v1, Vector4f v2)
                {
diff --git a/mcs/class/Moonlight.Build.Tasks/ChangeLog b/mcs/class/Moonlight.Build.Tasks/ChangeLog
new file mode 100644 (file)
index 0000000..7e63080
--- /dev/null
@@ -0,0 +1,3 @@
+2010-04-13  Ankit Jain  <jankit@novell.com>
+
+       * Initial commit.
diff --git a/mcs/class/Moonlight.Build.Tasks/Makefile b/mcs/class/Moonlight.Build.Tasks/Makefile
new file mode 100644 (file)
index 0000000..7c3511c
--- /dev/null
@@ -0,0 +1,61 @@
+thisdir = class/Moonlight.Build.Tasks
+SUBDIRS = 
+include ../../build/rules.make
+
+LIBRARY = Moonlight.Build.Tasks.dll
+LIBRARY_NAME = Moonlight.Build.Tasks.dll
+
+ifeq (1.0, $(FRAMEWORK_VERSION))
+LIBRARY_NAME = dummy-Moonlight.Build.Tasks.dll
+endif
+
+ifeq (3.5, $(FRAMEWORK_VERSION))
+NAME_SUFFIX = .v3.5
+else
+ifeq (4.0, $(FRAMEWORK_VERSION))
+NAME_SUFFIX = .v4.0
+endif
+endif
+
+NO_INSTALL = yes
+NO_TEST = yes
+NO_SIGN_ASSEMBLY = yes
+
+REFERENCES = \
+       /r:$(corlib)                            \
+       /r:System.dll                           \
+       /r:System.Xml.dll                       \
+       /r:Microsoft.Build.Engine.dll   \
+       /r:Microsoft.Build.Framework.dll        \
+       /r:Microsoft.Build.Utilities$(NAME_SUFFIX).dll \
+       /r:Microsoft.Build.Tasks$(NAME_SUFFIX).dll \
+       /r:ICSharpCode.SharpZipLib.dll
+
+LIB_MCS_FLAGS = \
+       $(REFERENCES) \
+       $(RESOURCE_FILES:%=-resource:%)
+
+RESOURCE_FILES = Moonlight.Build.Tasks/PreviewTemplate.html
+
+EXTRA_DISTFILES = $(RESOURCE_FILES)
+
+XBUILD_DIR=../../tools/xbuild
+include $(XBUILD_DIR)/xbuild_targets.make
+
+include ../../build/library.make
+
+SILVERLIGHT_DIR = $(DESTDIR)$(mono_libdir)/mono/xbuild/Microsoft/Silverlight
+
+install-local: install-lib
+
+install-lib: $(the_lib)
+       -$(MKINSTALLDIRS) $(SILVERLIGHT_DIR)/v2.0
+       -$(MKINSTALLDIRS) $(SILVERLIGHT_DIR)/v3.0
+       $(INSTALL_DATA) $(topdir)/class/lib/$(PROFILE)/$(LIBRARY_NAME) $(SILVERLIGHT_DIR)/v2.0
+       $(INSTALL_DATA) $(topdir)/class/lib/$(PROFILE)/$(LIBRARY_NAME) $(SILVERLIGHT_DIR)/v3.0
+
+uninstall-local: uninstall-lib
+
+uninstall-lib:
+       -rm -f $(SILVERLIGHT_DIR)/v2.0/$(LIBRARY_NAME)
+       -rm -f $(SILVERLIGHT_DIR)/v3.0/$(LIBRARY_NAME)
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks.dll.sources b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks.dll.sources
new file mode 100644 (file)
index 0000000..74c3a27
--- /dev/null
@@ -0,0 +1,6 @@
+Moonlight.Build.Tasks/GenerateXap.cs
+Moonlight.Build.Tasks/XamlG.cs
+Moonlight.Build.Tasks/GetMoonlightFrameworkPath.cs
+Moonlight.Build.Tasks/GenerateMoonlightManifest.cs
+Moonlight.Build.Tasks/CreateTestPage.cs
+Moonlight.Build.Tasks/Respack.cs
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/ChangeLog b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/ChangeLog
new file mode 100644 (file)
index 0000000..8851010
--- /dev/null
@@ -0,0 +1,9 @@
+2010-04-13  Ankit Jain  <jankit@novell.com>
+
+       * CreateTestPage.cs:
+       * GenerateMoonlightManifest.cs:
+       * GetMoonlightFrameworkPath.cs:
+       * GenerateXap.cs:
+       * Respack.cs:
+       * XamlG.cs:
+       MSBuild tasks for building silverlight projects.
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/CreateTestPage.cs b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/CreateTestPage.cs
new file mode 100644 (file)
index 0000000..2805169
--- /dev/null
@@ -0,0 +1,79 @@
+//
+// CreateTestPage.cs: Generates test page for moonlight app
+//
+// Author:
+//     Michael Hutchinson <mhutchinson@novell.com>
+//     Ankit Jain <jankit@novell.com>
+//
+// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
+// Copyright (c) 2010 Novell, Inc. (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.IO;
+using System.Reflection;
+using System.Text;
+
+using Microsoft.Build.Framework;
+using Microsoft.Build.Utilities;
+
+namespace Moonlight.Build.Tasks {
+       public class CreateTestPage : Task {
+
+               public override bool Execute ()
+               {
+                       Log.LogMessage (MessageImportance.Low, "Generating test page {0}", XapFilename);
+
+                       var sb = new StringBuilder ();
+                       using (var sr = new StreamReader (Assembly.GetExecutingAssembly ().GetManifestResourceStream ("PreviewTemplate.html")))
+                               sb.Append (sr.ReadToEnd ());
+
+                       sb.Replace ("@TITLE@", Title);
+                       sb.Replace ("@XAP_FILE@", XapFilename);
+
+                       try{
+                               File.WriteAllText (TestPageFilename, sb.ToString ());
+                       } catch (IOException e) {
+                               Log.LogError (String.Format (
+                                               "Error generating test page file {0}: {1}", TestPageFilename, e.Message));
+                               return false;
+                       }
+
+                       return true;
+               }
+
+               [Required]
+               public string XapFilename {
+                       get; set;
+               }
+
+               [Required]
+               public string Title {
+                       get; set;
+               }
+
+               [Required]
+               [Output]
+               public string TestPageFilename {
+                       get; set;
+               }
+       }
+}
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/GenerateMoonlightManifest.cs b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/GenerateMoonlightManifest.cs
new file mode 100644 (file)
index 0000000..4b7e7a3
--- /dev/null
@@ -0,0 +1,179 @@
+//
+// GenerateMoonlightManifest.cs
+//
+// Author:
+//     Michael Hutchinson <mhutchinson@novell.com>
+//     Ankit Jain <jankit@novell.com>
+//
+// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
+// Copyright (c) 2010 Novell, Inc. (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.IO;
+using System.CodeDom;
+using System.CodeDom.Compiler;
+using System.Xml;
+
+using Microsoft.CSharp;
+
+using Microsoft.Build.Framework;
+using Microsoft.Build.Utilities;
+
+namespace Moonlight.Build.Tasks {
+       public class GenerateMoonlightManifest : Task {
+
+               public override bool Execute ()
+               {
+                       return GenerateManifest ();
+               }
+
+               bool GenerateManifest ()
+               {
+                       const string depNS = "http://schemas.microsoft.com/client/2007/deployment";
+
+                       string template = null;
+                       var manifest = ManifestFile.ItemSpec;
+                       Log.LogMessage (MessageImportance.Normal, "Generating manifest file {0}", manifest);
+
+                       if (SilverlightManifestTemplate != null)
+                               template = String.IsNullOrEmpty (SilverlightManifestTemplate.ItemSpec) ?
+                                                       null :
+                                                       SilverlightManifestTemplate.GetMetadata ("FullPath");
+
+                       XmlDocument doc = new XmlDocument ();
+                       if (template != null) {
+                               if (!File.Exists (template)) {
+                                       Log.LogError ("Could not find manifest template '" +  template + "'.");
+                                       return false;
+                               }
+
+                               try {
+                                       doc.Load (template);
+                               } catch (XmlException ex) {
+                                       Log.LogError (null, null, null, template, ex.LineNumber, ex.LinePosition, 0, 0,
+                                                       "Error loading manifest template '" + ex.Source);
+                                       return false;
+                               } catch (Exception ex) {
+                                       Log.LogError ("Could not load manifest template '" +  template + "'.");
+                                       Log.LogMessage (MessageImportance.Low, "Could not load manifest template '" +  template + "': " + ex.ToString ());
+                                       return false;
+                               }
+
+                       } else {
+                               doc.LoadXml (@"<Deployment xmlns=""http://schemas.microsoft.com/client/2007/deployment"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""></Deployment>");
+                       }
+
+                       try {
+                               XmlNode deploymentNode = doc.DocumentElement;
+                               if (deploymentNode == null || deploymentNode.Name != "Deployment" || deploymentNode.NamespaceURI != depNS) {
+                                       Log.LogError ("Missing or invalid root <Deployment> element in manifest template '" +  template + "'.");
+                                       return false;
+                               }
+                               if (deploymentNode.Attributes["EntryPointAssembly"] == null)
+                                       deploymentNode.Attributes.Append (doc.CreateAttribute ("EntryPointAssembly")).Value =
+                                               EntryPointAssembly.GetMetadata ("Filename");
+
+                               if (!String.IsNullOrEmpty (SilverlightAppEntry) && deploymentNode.Attributes["EntryPointType"] == null)
+                                       deploymentNode.Attributes.Append (doc.CreateAttribute ("EntryPointType")).Value = SilverlightAppEntry;
+
+                               if (deploymentNode.Attributes["RuntimeVersion"] == null) {
+                                       //FIXME:
+                                       /*string fxVersion = MoonlightFrameworkBackend.GetFxVersion (proj.TargetFramework);
+
+                                       if (proj.TargetRuntime is MonoDevelop.Core.Assemblies.MonoTargetRuntime) {
+                                               var package = proj.TargetRuntime.RuntimeAssemblyContext.GetPackage ("moonlight-web-" + fxVersion);
+                                               if (package != null && package.IsFrameworkPackage) {
+                                                       runtimeVersion = package.Version;
+                                               } else {
+                                                       LoggingService.LogWarning ("Moonlight core framework package not found, cannot determine " +
+                                                               "runtime version string. Falling back to default value.");
+                                               }
+                                       }*/
+
+                                       deploymentNode.Attributes.Append (doc.CreateAttribute ("RuntimeVersion")).Value =
+                                                       String.IsNullOrEmpty (RuntimeVersion) ? "2.0.31005.0" : RuntimeVersion;
+                               }
+
+                               XmlNamespaceManager mgr = new XmlNamespaceManager (doc.NameTable);
+                               mgr.AddNamespace ("dep", depNS);
+                               XmlNode partsNode = deploymentNode.SelectSingleNode ("dep:Deployment.Parts", mgr);
+                               if (partsNode == null)
+                                       partsNode = deploymentNode.AppendChild (doc.CreateElement ("Deployment.Parts", depNS));
+
+                               AddAssemblyPart (doc, partsNode, EntryPointAssembly);
+
+                               foreach (ITaskItem ref_item in References)
+                                       AddAssemblyPart (doc, partsNode, ref_item);
+                       } catch (XmlException ex) {
+                               Log.LogError (null, null, null, template, ex.LineNumber, ex.LinePosition, 0, 0,
+                                               "Error processing manifest template: '" + ex.Source);
+                               return false;
+                       }
+
+                       doc.Save (manifest);
+
+                       return true;
+               }
+
+               static void AddAssemblyPart (XmlDocument doc, XmlNode partsNode, ITaskItem filename)
+               {
+                       XmlNode child = doc.CreateElement ("AssemblyPart", "http://schemas.microsoft.com/client/2007/deployment");
+                       child.Attributes.Append (doc.CreateAttribute (
+                                               "Name", "http://schemas.microsoft.com/winfx/2006/xaml")).Value = filename.GetMetadata ("Filename");
+                       string subdir = filename.GetMetadata ("DestinationSubdirectory");
+                       child.Attributes.Append (doc.CreateAttribute ("Source")).Value = Path.Combine (subdir ?? String.Empty, Path.GetFileName (filename.ItemSpec));
+                       partsNode.AppendChild (child);
+               }
+
+               [Required]
+               [Output]
+               public ITaskItem ManifestFile {
+                       get; set;
+               }
+
+               [Required]
+               // with extension
+               public ITaskItem EntryPointAssembly {
+                       get; set;
+               }
+
+               [Required]
+               public ITaskItem[] References {
+                       get; set;
+               }
+
+               public ITaskItem SilverlightManifestTemplate {
+                       get; set;
+               }
+
+               public string SilverlightAppEntry {
+                       get; set;
+               }
+
+               public string RuntimeVersion {
+                       get; set;
+               }
+       }
+
+}
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/GenerateXap.cs b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/GenerateXap.cs
new file mode 100644 (file)
index 0000000..92082ac
--- /dev/null
@@ -0,0 +1,140 @@
+//
+// GenerateXap.cs
+//
+// Author:
+//     Michael Hutchinson <mhutchinson@novell.com>
+//     Ankit Jain <jankit@novell.com>
+//
+// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
+// Copyright (c) 2010 Novell, Inc. (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.IO;
+using System.CodeDom;
+using System.CodeDom.Compiler;
+using System.Xml;
+
+using Microsoft.CSharp;
+
+using Microsoft.Build.Framework;
+using Microsoft.Build.Utilities;
+
+namespace Moonlight.Build.Tasks {
+       public class GenerateXap : Task {
+
+               public override bool Execute ()
+               {
+                       if (InputFiles.Length == 0)
+                               return true;
+
+                       return Zip ();
+               }
+
+               bool Zip ()
+               {
+                       var xapName = XapFilename.ItemSpec;
+                       if (File.Exists (xapName)) {
+                               DateTime lastMod = File.GetLastWriteTime (xapName);
+                               bool needsWrite = false;
+                               foreach (ITaskItem file_item in InputFiles) {
+                                       if (File.GetLastWriteTime (file_item.ItemSpec) > lastMod) {
+                                               needsWrite = true;
+                                               break;
+                                       }
+                               }
+                               if (!needsWrite) {
+                                       Log.LogMessage (MessageImportance.Low, "Skipping xap file {0} generation, its up-to date");
+                                       return true;
+                               }
+                       }
+
+                       Log.LogMessage (MessageImportance.Normal, "Generating compressed xap file {0}", xapName);
+                       try {
+                               using (FileStream fs = new FileStream (xapName, FileMode.Create)) {
+                                       var zip_stream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream (fs);
+                                       zip_stream.SetLevel (9);
+
+                                       AddFilesToZip (InputFiles, zip_stream);
+                                       AddFilesToZip (LocalCopyReferences, zip_stream);
+
+                                       zip_stream.Finish ();
+                                       zip_stream.Close ();
+                               }
+                       } catch (IOException ex) {
+                               Log.LogError ("Error writing xap file.", ex);
+                               Log.LogMessage (MessageImportance.Low, "Error writing xap file:" + ex.ToString ());
+
+                               try {
+                                       if (File.Exists (xapName))
+                                               File.Delete (xapName);
+                               } catch {}
+
+                               return false;
+                       }
+
+                       return true;
+               }
+
+               void AddFilesToZip (ITaskItem [] files, ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream)
+               {
+                       if (files == null)
+                               return;
+
+                       foreach (ITaskItem item in files) {
+                               string target_path = item.GetMetadata ("TargetPath");
+                               if (String.IsNullOrEmpty (target_path))
+                                       target_path = Path.GetFileName (item.ItemSpec);
+
+                               zipStream.PutNextEntry (new ICSharpCode.SharpZipLib.Zip.ZipEntry (target_path));
+                               using (FileStream inStream = File.OpenRead (item.ItemSpec)) {
+                                       int readCount;
+                                       byte[] buffer = new byte[4096];
+
+                                       do {
+                                               readCount = inStream.Read (buffer, 0, buffer.Length);
+                                               zipStream.Write (buffer, 0, readCount);
+                                       } while (readCount > 0);
+                               }
+                       }
+               }
+
+               [Output]
+               [Required]
+               public ITaskItem XapFilename {
+                       get; set;
+               }
+
+               [Required]
+               public ITaskItem[] InputFiles {
+                       get; set;
+               }
+
+               public ITaskItem[] LocalCopyReferences {
+                       get; set;
+               }
+
+       }
+
+
+}
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/GetMoonlightFrameworkPath.cs b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/GetMoonlightFrameworkPath.cs
new file mode 100644 (file)
index 0000000..65072db
--- /dev/null
@@ -0,0 +1,89 @@
+//
+// GetMoonlightFrameworkPath.cs
+//
+// Author:
+//     Michael Hutchinson <mhutchinson@novell.com>
+//     Ankit Jain <jankit@novell.com>
+//
+// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
+// Copyright (c) 2010 Novell, Inc. (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+using SI = System.IO;
+
+using System;
+using System.Text;
+
+using Microsoft.Build.Framework;
+using Microsoft.Build.Utilities;
+
+namespace Moonlight.Build.Tasks {
+       public class GetMoonlightFrameworkPath : Task {
+
+               public override bool Execute ()
+               {
+                       return true;
+               }
+
+               [Required]
+               public string SilverlightVersion {
+                       get; set;
+               }
+
+               [Output]
+               public string FrameworkPath {
+                       get {
+                               if (SilverlightVersion == "3.0")
+                                       return FrameworkVersion30Path;
+                               else
+                                       return FrameworkVersion20Path;
+                       }
+               }
+
+               [Output]
+               public string FrameworkVersion20Path {
+                       get {
+                               return SI.Path.GetFullPath (
+                                               PathCombine (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20),
+                                               "..", "..", "moonlight", "2.0"));
+                       }
+               }
+
+               [Output]
+               public string FrameworkVersion30Path {
+                       get {
+                               return SI.Path.GetFullPath (
+                                               PathCombine (ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20),
+                                               "..", "..", "moonlight", "3.0"));
+                       }
+               }
+
+               static string PathCombine (string path1, params string[] parts)
+               {
+                       StringBuilder sb = new StringBuilder ();
+                       sb.Append (path1);
+                       foreach (string part in parts)
+                               sb.AppendFormat ("{0}{1}", SI.Path.DirectorySeparatorChar, part);
+
+                       return sb.ToString ();
+               }
+       }
+}
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/PreviewTemplate.html b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/PreviewTemplate.html
new file mode 100644 (file)
index 0000000..2be0575
--- /dev/null
@@ -0,0 +1,76 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" >
+<head>
+    <title>@TITLE@</title>
+
+    <style type="text/css">
+    html, body {
+           height: 100%;
+           overflow: auto;
+    }
+    body {
+           padding: 0;
+           margin: 0;
+    }
+    #silverlightControlHost {
+           height: 100%;
+    }
+    </style>
+    
+    <script type="text/javascript">
+        function onSilverlightError(sender, args) {
+        
+            var appSource = "";
+            if (sender != null && sender != 0) {
+                appSource = sender.getHost().Source;
+            } 
+            var errorType = args.ErrorType;
+            var iErrorCode = args.ErrorCode;
+            
+            var errMsg = "Unhandled Error in Silverlight 2 Application " +  appSource + "\n" ;
+
+            errMsg += "Code: "+ iErrorCode + "    \n";
+            errMsg += "Category: " + errorType + "       \n";
+            errMsg += "Message: " + args.ErrorMessage + "     \n";
+
+            if (errorType == "ParserError")
+            {
+                errMsg += "File: " + args.xamlFile + "     \n";
+                errMsg += "Line: " + args.lineNumber + "     \n";
+                errMsg += "Position: " + args.charPosition + "     \n";
+            }
+            else if (errorType == "RuntimeError")
+            {           
+                if (args.lineNumber != 0)
+                {
+                    errMsg += "Line: " + args.lineNumber + "     \n";
+                    errMsg += "Position: " +  args.charPosition + "     \n";
+                }
+                errMsg += "MethodName: " + args.methodName + "     \n";
+            }
+
+            throw new Error(errMsg);
+        }
+    </script>
+</head>
+
+<body>
+    <!-- Runtime errors from Silverlight will be displayed here.
+       This will contain debugging information and should be removed or hidden when debugging is completed -->
+       <div id='errorLocation' style="font-size: small;color: Gray;"></div>
+
+    <div id="silverlightControlHost">
+               <object data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%">
+                       <param name="source" value="@XAP_FILE@"/>
+                       <param name="onerror" value="onSilverlightError" />
+                       <param name="background" value="white" />
+                       <param name="minRuntimeVersion" value="2.0.31005.0" />
+                       <param name="autoUpgrade" value="true" />
+                       <a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">
+                       <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/>
+                       </a>
+               </object>
+               <iframe style='visibility:hidden;height:0;width:0;border:0px'></iframe>
+    </div>
+</body>
+</html>
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/Respack.cs b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/Respack.cs
new file mode 100644 (file)
index 0000000..4f7a544
--- /dev/null
@@ -0,0 +1,105 @@
+//
+// Respack.cs
+//
+// Author:
+//   Ankit Jain (jankit@novell.com)
+//
+// Copyright 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHRespackL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DERespackINGS IN THE SOFTWARE.
+
+using System;
+using System.Diagnostics;
+using System.IO;
+using Microsoft.Build.Framework;
+using Microsoft.Build.Tasks;
+using Microsoft.Build.Utilities;
+using Mono.XBuild.Utilities;
+
+namespace Moonlight.Build.Tasks {
+       public class Respack : ToolTask
+       {
+               public override bool Execute ()
+               {
+                       if (!ValidateParameters ()) {
+                               // not generating any resource file
+                               OutputFile = null;
+                               return true;
+                       }
+
+                       return base.Execute ();
+               }
+
+               void AddCommandLineCommands (CommandLineBuilderExtension commandLine)
+               {
+                       if (Resources.Length == 0)
+                               return;
+
+                       commandLine.AppendFileNameIfNotNull (OutputFile);
+
+                       commandLine.AppendFileNamesIfNotNull (Resources, " ");
+               }
+
+               protected override string GenerateCommandLineCommands ()
+               {
+                       CommandLineBuilderExtension clbe = new CommandLineBuilderExtension ();
+                       AddCommandLineCommands (clbe);
+                       return clbe.ToString ();
+               }
+
+               protected override string GenerateFullPathToTool ()
+               {
+                       return Path.Combine (ToolPath, ToolExe);
+               }
+
+               protected override bool ValidateParameters()
+               {
+                       return Resources.Length > 0;
+               }
+
+               [Required]
+               [Output]
+               public ITaskItem OutputFile {
+                       get; set;
+               }
+
+               [Required]
+               public ITaskItem[] Resources {
+                       get; set;
+               }
+
+               protected override string ToolName {
+                       get {
+                               return RunningOnWindows ? "respack.bat" : "respack";
+                       }
+               }
+
+                static bool RunningOnWindows {
+                        get {
+                                // Code from Mono.GetOptions/Options.cs
+                                // check for non-Unix platforms - see FAQ for more details
+                                // http://www.mono-project.com/FAQ:_Technical#How_to_detect_the_execution_platform_.3F
+                                int platform = (int) Environment.OSVersion.Platform;
+                                return ((platform != 4) && (platform != 128));
+                        }
+
+                }
+       }
+}
diff --git a/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/XamlG.cs b/mcs/class/Moonlight.Build.Tasks/Moonlight.Build.Tasks/XamlG.cs
new file mode 100644 (file)
index 0000000..63bea8a
--- /dev/null
@@ -0,0 +1,375 @@
+//
+// XamlG.cs
+//
+// Author:
+//     Michael Hutchinson <mhutchinson@novell.com>
+//     Ankit Jain <jankit@novell.com>
+//
+// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
+// Copyright (c) 2010 Novell, Inc. (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.IO;
+using System.CodeDom;
+using System.CodeDom.Compiler;
+using System.Xml;
+
+using Microsoft.Build.Framework;
+using Microsoft.Build.Utilities;
+
+namespace Moonlight.Build.Tasks {
+       public class XamlG : Task {
+
+               public override bool Execute ()
+               {
+                       if (Sources.Length == 0)
+                               return true;
+
+                       if (OutputFiles == null || Sources.Length != OutputFiles.Length) {
+                               Log.LogError ("Number of OutputFiles must match the number of Source files");
+                               return false;
+                       }
+
+                       var codedom_provider = GetCodeDomProviderForLanguage (Language);
+                       if (codedom_provider == null) {
+                               Log.LogError ("Language {0} not supported for code generation.", Language);
+                               return false;
+                       }
+
+                       for (int i = 0; i < Sources.Length; i ++) {
+                               ITaskItem source_item = Sources [i];
+                               ITaskItem dest_item = OutputFiles [i];
+                               if (!File.Exists (dest_item.ItemSpec) ||
+                                       File.GetLastWriteTime (dest_item.ItemSpec) < File.GetLastWriteTime (source_item.ItemSpec)) {
+                                       Log.LogMessage (MessageImportance.Low, "Generating codebehind accessors for {0}...", source_item.ItemSpec);
+
+                                       string full_source_path = source_item.GetMetadata ("FullPath");
+                                       try {
+                                               if (!XamlGCompiler.GenerateFile (codedom_provider, AssemblyName, full_source_path, full_source_path, dest_item.ItemSpec, Log)) {
+                                                       Log.LogError ("Error generating {0} from {1}", full_source_path, dest_item.ItemSpec);
+                                                       return false;
+                                               }
+                                       } catch (Exception e) {
+                                               Log.LogError ("Error generating {0} from {1}: {2}", full_source_path, dest_item.ItemSpec, e.Message);
+                                               Log.LogMessage (MessageImportance.Low, "Error generating {0} from {1}: {2}",
+                                                               full_source_path, dest_item.ItemSpec, e.ToString ());
+                                               return false;
+                                       }
+                               }
+                       }
+
+                       return true;
+               }
+
+               CodeDomProvider GetCodeDomProviderForLanguage (string lang)
+               {
+                       switch (lang.ToLower ()) {
+                       case "c#": return new Microsoft.CSharp.CSharpCodeProvider ();
+                       case "vb": return new Microsoft.VisualBasic.VBCodeProvider ();
+                       }
+
+                       return null;
+               }
+
+               [Required]
+               public ITaskItem [] Sources {
+                       get; set;
+               }
+
+               [Required]
+               public string Language {
+                       get; set;
+               }
+
+               [Required]
+               public string AssemblyName {
+                       get; set;
+               }
+
+               [Output]
+               public ITaskItem [] OutputFiles {
+                       get; set;
+               }
+
+               bool HasFileChanged (string source, string dest)
+               {
+                       if (!File.Exists (dest))
+                               return true;
+
+                       FileInfo sourceInfo = new FileInfo (source);
+                       FileInfo destinationInfo = new FileInfo (dest);
+
+                       return !(sourceInfo.Length == destinationInfo.Length &&
+                                       File.GetLastWriteTime(source) <= File.GetLastWriteTime (dest));
+               }
+
+       }
+
+       static class XamlGCompiler
+       {
+               private static bool sl2 = true;
+
+               public static bool GenerateFile (CodeDomProvider provider, string app_name,
+                                                      string xaml_file, string xaml_path_in_project, string out_file, TaskLoggingHelper log)
+               {
+                       XmlDocument xmldoc = new XmlDocument ();
+                       xmldoc.Load (xaml_file);
+
+                       XmlNamespaceManager nsmgr = new XmlNamespaceManager (xmldoc.NameTable);
+                       nsmgr.AddNamespace("x", "http://schemas.microsoft.com/winfx/2006/xaml");
+
+                       XmlNode root = xmldoc.SelectSingleNode ("/*", nsmgr);
+                       if (root == null) {
+                               log.LogError ("{0}: No root node found.", xaml_file);
+                               return false;
+                       }
+
+                       XmlAttribute root_class = root.Attributes ["x:Class"];
+                       if (root_class == null) {
+                               File.WriteAllText (out_file, "");
+                               return true;
+                       }
+
+                       bool is_application = root.LocalName == "Application";
+                       string root_ns;
+                       string root_type;
+                       string root_asm;
+
+                       ParseXmlns (root_class.Value, out root_type, out root_ns, out root_asm);
+
+                       Hashtable names_and_types = GetNamesAndTypes (root, nsmgr);
+//                     Hashtable keys_and_types = GetKeysAndTypes (root, nsmgr);
+
+                       CodeCompileUnit ccu = new CodeCompileUnit ();
+                       CodeNamespace decl_ns = new CodeNamespace (root_ns);
+                       ccu.Namespaces.Add (decl_ns);
+
+                       decl_ns.Imports.Add (new CodeNamespaceImport ("System"));
+                       decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows"));
+                       decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Controls"));
+                       decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Documents"));
+                       decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Input"));
+                       decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Media"));
+                       decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Media.Animation"));
+                       decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Shapes"));
+                       decl_ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Controls.Primitives"));
+
+                       CodeTypeDeclaration decl_type = new CodeTypeDeclaration (root_type);
+                       decl_type.IsPartial = true;
+
+                       decl_ns.Types.Add (decl_type);
+
+                       CodeMemberMethod initcomp = new CodeMemberMethod ();
+                       initcomp.Name = "InitializeComponent";
+                       decl_type.Members.Add (initcomp);
+
+                       if (sl2) {
+                               CodeMemberField field = new CodeMemberField ();
+                               field.Name = "_contentLoaded";
+                               field.Type = new CodeTypeReference (typeof (bool));
+
+                               decl_type.Members.Add (field);
+
+                               CodeConditionStatement is_content_loaded = new CodeConditionStatement (new CodeVariableReferenceExpression ("_contentLoaded"),
+                                               new CodeStatement [] { new CodeMethodReturnStatement () });
+                               initcomp.Statements.Add (is_content_loaded);
+
+                               CodeAssignStatement set_content_loaded = new CodeAssignStatement (new CodeVariableReferenceExpression ("_contentLoaded"),
+                                               new CodePrimitiveExpression (true));
+
+                               initcomp.Statements.Add (set_content_loaded);
+
+                               string component_path = String.Format ("/{0};component/{1}", app_name, xaml_path_in_project);
+                               CodeMethodInvokeExpression load_component = new CodeMethodInvokeExpression (
+                                       new CodeTypeReferenceExpression ("System.Windows.Application"), "LoadComponent",
+                                       new CodeExpression [] { new CodeThisReferenceExpression (),
+                                                               new CodeObjectCreateExpression (new CodeTypeReference ("System.Uri"), new CodeExpression [] {
+                                                                       new CodePrimitiveExpression (component_path),
+                                                                       new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("System.UriKind"), "Relative") })
+                                       });
+                               initcomp.Statements.Add (load_component);
+                       }
+
+                       if (!is_application) {
+                               foreach (DictionaryEntry entry  in names_and_types) {
+                                       string name = (string) entry.Key;
+                                       CodeTypeReference type = (CodeTypeReference) entry.Value;
+
+                                       CodeMemberField field = new CodeMemberField ();
+
+                                       if (sl2)
+                                               field.Attributes = MemberAttributes.Assembly;
+
+                                       field.Name = name;
+                                       field.Type = type;
+
+                                       decl_type.Members.Add (field);
+
+                                       CodeMethodInvokeExpression find_invoke = new CodeMethodInvokeExpression (
+                                               new CodeThisReferenceExpression(), "FindName",
+                                               new CodeExpression[] { new CodePrimitiveExpression (name) } );
+
+                                       CodeCastExpression cast = new CodeCastExpression (type, find_invoke);
+
+                                       CodeAssignStatement assign = new CodeAssignStatement (
+                                               new CodeVariableReferenceExpression (name), cast);
+
+                                       initcomp.Statements.Add (assign);
+                               }
+                       }
+
+
+                       using (StreamWriter writer = new StreamWriter (out_file)) {
+                               provider.GenerateCodeFromCompileUnit (ccu, writer, new CodeGeneratorOptions ());
+                       }
+
+                       return true;
+               }
+
+               private static Hashtable GetNamesAndTypes (XmlNode root, XmlNamespaceManager nsmgr)
+               {
+                       Hashtable res = new Hashtable ();
+
+                       XmlNodeList names = root.SelectNodes ("//*[@x:Name]", nsmgr);
+                       foreach (XmlNode node in names) {
+
+                               // Don't take the root canvas
+                               if (node == root)
+                                       continue;
+
+                               XmlAttribute attr = node.Attributes ["x:Name"];
+                               string name = attr.Value;
+                               string ns = GetNamespace (node);
+                               string member_type = node.LocalName;
+
+                               if (ns != null)
+                                       member_type = String.Concat (ns, ".", member_type);
+
+                               CodeTypeReference type = new CodeTypeReference (member_type);
+                               if (ns != null)
+                                       type.Options |= CodeTypeReferenceOptions.GlobalReference;
+
+                               res [name] = type;
+                       }
+
+                       return res;
+               }
+
+               /*
+               private static Hashtable GetKeysAndTypes (XmlNode root, XmlNamespaceManager nsmgr)
+               {
+                       Hashtable res = new Hashtable ();
+
+                       XmlNodeList keys = root.SelectNodes ("//*[@x:Key]", nsmgr);
+                       foreach (XmlNode node in keys)  {
+
+                               // Don't take the root canvas
+                               if (node == root)
+                                       continue;
+
+                               XmlAttribute attr = node.Attributes ["x:Key"];
+                               string key = attr.Value;
+                               string ns = GetNamespace (node);
+                               string member_type = node.LocalName;
+
+                               if (ns != null)
+                                       member_type = String.Concat (ns, ".", member_type);
+
+                               res [key] = member_type;
+                       }
+
+                       return res;
+               }
+               */
+
+               internal static string GetNamespace (XmlNode node)
+               {
+                       if (!IsCustom (node.NamespaceURI))
+                               return null;
+
+                       return ParseNamespaceFromXmlns (node.NamespaceURI);
+               }
+
+               private static bool IsCustom (string ns)
+               {
+                       switch (ns) {
+                       case "http://schemas.microsoft.com/winfx/2006/xaml":
+                       case "http://schemas.microsoft.com/winfx/2006/xaml/presentation":
+                       case "http://schemas.microsoft.com/client/2007":
+                               return false;
+                       }
+
+                       return true;
+               }
+
+               private static string ParseNamespaceFromXmlns (string xmlns)
+               {
+                       string type_name = null;
+                       string ns = null;
+                       string asm = null;
+
+                       ParseXmlns (xmlns, out type_name, out ns, out asm);
+
+                       return ns;
+               }
+
+//             private static string ParseTypeFromXmlns (string xmlns)
+//             {
+//                     string type_name = null;
+//                     string ns = null;
+//                     string asm = null;
+//
+//                     ParseXmlns (xmlns, out type_name, out ns, out asm);
+//
+//                     return type_name;
+//             }
+
+               internal static void ParseXmlns (string xmlns, out string type_name, out string ns, out string asm)
+               {
+                       type_name = null;
+                       ns = null;
+                       asm = null;
+
+                       string [] decls = xmlns.Split (';');
+                       foreach (string decl in decls) {
+                               if (decl.StartsWith ("clr-namespace:")) {
+                                       ns = decl.Substring (14, decl.Length - 14);
+                                       continue;
+                               }
+                               if (decl.StartsWith ("assembly=")) {
+                                       asm = decl.Substring (9, decl.Length - 9);
+                                       continue;
+                               }
+                               int nsind = decl.LastIndexOf (".");
+                               if (nsind > 0) {
+                                       ns = decl.Substring (0, nsind);
+                                       type_name = decl.Substring (nsind + 1, decl.Length - nsind - 1);
+                               } else {
+                                       type_name = decl;
+                               }
+                       }
+               }
+       }
+
+}
index ae15ef4b2908cf316fa679160a52855f91a39cb2..616ef4577a4995bb34217c3fc205b385f26c3233 100644 (file)
@@ -468,7 +468,7 @@ namespace System.ComponentModel.Composition.Hosting
         private string[] GetFiles()\r
         {\r
             string[] files = Directory.GetFiles(this._fullPath, this._searchPattern);\r
-            return Array.ConvertAll<string, string>(files, (file) => file.ToUpperInvariant());\r
+            return Array.ConvertAll<string, string>(files, (file) => file);\r
         }\r
 \r
         private static string GetFullPath(string path)\r
@@ -478,7 +478,7 @@ namespace System.ComponentModel.Composition.Hosting
                 path = IOPath.Combine(AppDomain.CurrentDomain.BaseDirectory, path);\r
             }\r
 \r
-            return IOPath.GetFullPath(path).ToUpperInvariant();\r
+            return IOPath.GetFullPath(path);\r
         }\r
 \r
         private void Initialize(string path, string searchPattern)\r
index 0ccc1d0801e6a78e2ecd7fd2be7801fd28b77d70..d2adf2ccf02b6fbd021d119d383411f4c782414b 100644 (file)
@@ -73,3 +73,8 @@ using System.Runtime.InteropServices;
 // Extension attribute should be added by compiler
 
 [assembly: SecurityPermission (SecurityAction.RequestMinimum, SkipVerification = true)]
+
+#if NET_4_0
+[assembly: TypeForwardedTo (typeof (System.Security.Cryptography.Aes))]
+#endif
+
index 02c2a5d0dfaf619783d73346cc37732edac93de3..640ce64edd96696067b8037f7e25e1ee67378c14 100644 (file)
@@ -1,3 +1,7 @@
+2010-03-18  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * AssemblyInfo.cs: Add TypeForwardTo for Aes on NET_4_0
+
 2008-08-08  Sebastien Pouliot  <sebastien@ximian.com>
 
        * AssemblyInfo.cs: Remove a few attributes for SL2
index 5bddef0064e34eaaf86951f865d6d5a9ee7ad07a..69b587d7847368e013e4d85016531159c8cc244f 100644 (file)
@@ -1,3 +1,24 @@
+2010-04-23  Rolf Bjarne Kvinge  <RKvinge@novell.com>
+
+       * moonlight_raw_System.Core.dll.sources: Include Lazy.cs and
+       LazyThreadSafetyMode.cs from corlib in here.
+
+2010-04-15  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * System.Core_test.dll.sources: Add PLinq unit tests
+
+2010-04-15  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * net_4_0_System.Core.dll.sources: add PLinq sources
+
+2010-04-06  Jb Evain  <jbevain@novell.com>
+
+       * net_4_0_System.Core.dll.sources: add files to support ToQueryable.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * net_2_1_*.dll.sources: rename to moonlight_*.dll.sources.
+
 2009-12-17  Marek Safar  <marek.safar@gmail.com>
 
        * Makefile: Compile itself using bootstrap System.Core.
index dde17448c70e8821d27c7d88eed1ee4f31093681..893de76b60b7e0524c5f581e78d02f060bd6f736 100644 (file)
@@ -14,7 +14,7 @@ ifeq (4.0, $(FRAMEWORK_VERSION))
 LIB_MCS_FLAGS += -d:CODEPLEX_40
 endif
 
-FULL_PROFILE := $(filter net_2_0 net_4_0 net_2_1_raw monotouch, $(PROFILE))
+FULL_PROFILE := $(filter net_2_0 net_4_0 moonlight_raw monotouch, $(PROFILE))
 ifdef FULL_PROFILE
 LIBRARY_COMPILE = $(BOOT_COMPILE)
 endif
index d89d37399640a035bdf01e4de26dc87db912718d..95a52e7544181099c887a58e1d5b40cac437f33b 100644 (file)
@@ -1,3 +1,7 @@
+2010-04-16  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * HashSet.cs: Implement ISet<T> in MOONLIGHT too
+
 2010-02-13 Gonzalo Paniagua Javier <gonzalo@novell.com>
 
        * HashSet.cs: fix and test for bug #579791.  Patch from Tiaan
index 5a382c1df630658ce1656b1db4c5242088e7a198..157ca51fcb7f0b48d43fc754d1de552c88a3fa7c 100644 (file)
@@ -44,7 +44,7 @@ namespace System.Collections.Generic {
        [DebuggerDisplay ("Count={Count}")]
        [DebuggerTypeProxy (typeof (CollectionDebuggerView<,>))]
        public class HashSet<T> : ICollection<T>, ISerializable, IDeserializationCallback
-#if NET_4_0
+#if NET_4_0 || MOONLIGHT
                                                        , ISet<T>
 #endif
        {
index dffaf5eb7a92502ffe29984ef0aa9717ba3bf72d..58a8fac036f286255d11e8d1bb355bf501fd70e5 100644 (file)
@@ -78,3 +78,5 @@ System.Security.Cryptography/SHA384CryptoServiceProviderTest.cs
 System.Security.Cryptography/SHA512CngTest.cs
 System.Security.Cryptography/SHA512CryptoServiceProviderTest.cs
 System.Runtime.CompilerServices/DynamicAttributeTest.cs
+System.Linq/ParallelEnumerableTests.cs
+System.Linq/ParallelTestHelper.cs
index 1466f2eb6cc416841092a6110878900f534888a4..461c74fddc7f4e47b1a4c964893a9856d28be1c0 100644 (file)
@@ -1,3 +1,15 @@
+2010-04-15  Jb Evain  <jbevain@novell.com>
+
+       * MemoryMappedFile.cs: implement CreateOrOpen.
+
+2010-04-14  Jb Evain  <jbevain@novell.com>
+
+       * MemoryMappedViewAccessor.cs
+       * MemoryMappedFile.cs
+       * MemoryMappedViewStream.cs:
+               Properly retrieve the size of the mmapped file. Fixes the
+               unit tests.
+
 2009-12-14  Miguel de Icaza  <miguel@novell.com>
 
        * MemoryMappedFile.cs: Make this by default use the native
index 7376bc5ae0628a357bac38f7b663867715b8ecd2..346ca16c3117cb846badc20c398d12073c3c9845 100644 (file)
@@ -69,7 +69,6 @@ namespace System.IO.MemoryMappedFiles
                        return CreateFromFile (path, FileMode.Open, null, 0, MemoryMappedFileAccess.ReadWrite);
                }
 
-
                public static MemoryMappedFile CreateFromFile (string path, FileMode mode)
                {
                        return CreateFromFile (path, mode, null, 0, MemoryMappedFileAccess.ReadWrite);
@@ -224,14 +223,16 @@ namespace System.IO.MemoryMappedFiles
                        return CreateFromFile (mapName, FileMode.CreateNew, mapName, capacity, access);
                }
 
-               [MonoTODO]
-                       public static MemoryMappedFile CreateOrOpen (string mapName, long capacity) {
-                       throw new NotImplementedException ();
+               [MonoLimitation ("CreateOrOpen requires that mapName be a file name on Unix")]
+               public static MemoryMappedFile CreateOrOpen (string mapName, long capacity)
+               {
+                       return CreateOrOpen (mapName, capacity, MemoryMappedFileAccess.ReadWrite);
                }
 
-               [MonoTODO]
-                       public static MemoryMappedFile CreateOrOpen (string mapName, long capacity, MemoryMappedFileAccess access) {
-                       throw new NotImplementedException ();
+               [MonoLimitation ("CreateOrOpen requires that mapName be a file name on Unix")]
+               public static MemoryMappedFile CreateOrOpen (string mapName, long capacity, MemoryMappedFileAccess access)
+               {
+                       return CreateFromFile (mapName, FileMode.OpenOrCreate, mapName, capacity, access); 
                }
 
                /*
@@ -333,7 +334,7 @@ namespace System.IO.MemoryMappedFiles
                        }
                }
 
-               internal static unsafe void MapPosix (int file_handle, long offset, long size, MemoryMappedFileAccess access, out IntPtr map_addr, out int offset_diff)
+               internal static unsafe void MapPosix (int file_handle, long offset, ref long size, MemoryMappedFileAccess access, out IntPtr map_addr, out int offset_diff)
                {
                        if (pagesize == 0)
                                pagesize = Syscall.getpagesize ();
index e1fc156c2a36f133dafe22c7e30c2afdd9c4e823..ae9b4541575507cd3b5121331a9ae7ca79e69477 100644 (file)
@@ -73,7 +73,7 @@ namespace System.IO.MemoryMappedFiles
                {
                        int offset_diff;
 
-                       MemoryMappedFile.MapPosix (file_handle, offset, size, access, out mmap_addr, out offset_diff);
+                       MemoryMappedFile.MapPosix (file_handle, offset, ref size, access, out mmap_addr, out offset_diff);
 
                        handle = new SafeMemoryMappedViewHandle ((IntPtr)((long)mmap_addr + offset_diff), size);
                        Initialize (handle, 0, size, ToFileAccess (access));
index 2bf2f8a0084fde6f1d5c9ff8daf2f7fad7b39d97..3abd26cb3d4f41dda1a445ad022249d7e918d0f6 100644 (file)
@@ -53,8 +53,7 @@ namespace System.IO.MemoryMappedFiles
                {
                        int offset_diff;
                        mmap_size = (ulong) size;
-                       MemoryMappedFile.MapPosix (fd, offset, size, access, out mmap_addr, out offset_diff);
-                       
+                       MemoryMappedFile.MapPosix (fd, offset, ref size, access, out mmap_addr, out offset_diff);
                        FileAccess faccess;
 
                        switch (access) {
@@ -94,4 +93,4 @@ namespace System.IO.MemoryMappedFiles
        }
 }
 
-#endif
\ No newline at end of file
+#endif
index a7c2221dc4c4ff1628402522e411c66580f2a397..09221b2afb31b1bfc8c03f96410d19ec1218965a 100644 (file)
@@ -1,3 +1,57 @@
+2010-04-15  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * OrderedParallelQuery.cs:
+       * ParallelEnumerable.cs:
+       * ParallelExecuter.cs:
+       * ParallelPartitioner.cs:
+       * ParallelQuery.cs:
+       * ParallelQueryEnumerator.cs: First check-in of PLinq
+
+2010-04-15  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * ParallelExecutionMode.cs:
+       * ParallelMergeOptions.cs: Initial check-in of PLinq (enum)
+
+2010-04-12  Miguel de Icaza  <miguel@novell.com>
+
+       * Enumerable.cs: Jumbo patch that inlines code, mainly for the AOT
+       scenario where we our compiler cant infer the extra layer of
+       indirection of a lambda function.
+
+       But additionally, since we lack support for our JIT to inline
+       intermediate delegate calls, it should save memory and run
+       faster. 
+
+2010-04-07  Jb Evain  <jbevain@novell.com>
+
+       * EnumerableExecutor.cs: make ctor protected.
+
+2010-04-07  Jb Evain  <jbevain@novell.com>
+
+       * EnumerableQuery_T.cs: implement.
+
+2010-04-07  Jb Evain  <jbevain@novell.com>
+
+       * EnumerableQuery.cs: make ctor protected.
+
+2010-04-06  Jb Evain  <jbevain@novell.com>
+
+       * QueryableEnumerable.cs: make TransformQueryable work on net_4_0.
+
+2010-04-06  Jb Evain  <jbevain@novell.com>
+
+       * QueryableTransformer.cs: use factory method that work for all
+       ET implementations.
+
+2010-03-30  Jb Evain  <jbevain@novell.com>
+
+       * Queryable.cs: implement Zip for net_4_0.
+
+2010-03-24  Jb Evain  <jbevain@novell.com>
+
+       * SortSequenceContext.cs: Fix OrderByDescending stability.
+       Based on a patch by Richard Kiene  <richard.kiene@logos.com>.
+
 2010-02-23  Marek Safar  <marek.safar@gmail.com>
 
        * Enumerable.cs: Implement Zip.
index bda1c0551d6fae11df4265d3e7b0b6b937830c67..56018f49d7d789946354b248c86214a47ab55d06 100644 (file)
@@ -162,48 +162,77 @@ namespace System.Linq
 
                public static double Average (this IEnumerable<int> source)
                {
-                       return Average<int, long, double> (source, (a, b) => a + b, (a, b) => (double) a / (double) b);
+                       Check.Source (source);
+
+                       long total = 0;
+                       int count = 0;
+                       foreach (var element in source){
+                               total = checked (total + element);
+                               count++;
+                       }
+                       if (count == 0)
+                               throw new InvalidOperationException ();
+                       return total / (double) count;
                }
 
                public static double Average (this IEnumerable<long> source)
                {
-                       return Average<long, long, double> (source, (a, b) => a + b, (a, b) => (double) a / (double) b);
+                       Check.Source (source);
+
+                       long total = 0;
+                       long count = 0;
+                       foreach (var element in source){
+                               total += element;
+                               count++;
+                       }
+                       if (count == 0)
+                               throw new InvalidOperationException ();
+                       return total / (double) count;
                }
 
                public static double Average (this IEnumerable<double> source)
                {
-                       return Average<double, double, double> (source, (a, b) => a + b, (a, b) => a / b);
+                       Check.Source (source);
+
+                       double total = 0;
+                       long count = 0;
+                       foreach (var element in source){
+                               total += element;
+                               count++;
+                       }
+                       if (count == 0)
+                               throw new InvalidOperationException ();
+                       return total / count;
                }
 
                public static float Average (this IEnumerable<float> source)
                {
-                       return Average<float, double, float> (source, (a, b) => a + b, (a, b) => (float) a / (float) b);
-               }
+                       Check.Source (source);
 
-               public static decimal Average (this IEnumerable<decimal> source)
-               {
-                       return Average<decimal, decimal, decimal> (source, (a, b) => a + b, (a, b) => a / b);
+                       float total = 0;
+                       long count = 0;
+                       foreach (var element in source){
+                               total += element;
+                               count++;
+                       }
+                       if (count == 0)
+                               throw new InvalidOperationException ();
+                       return total / count;
                }
 
-               static TResult Average<TElement, TAggregate, TResult> (this IEnumerable<TElement> source,
-                       Func<TAggregate, TElement, TAggregate> func, Func<TAggregate, long, TResult> result)
-                       where TElement : struct
-                       where TAggregate : struct
-                       where TResult : struct
+               public static decimal Average (this IEnumerable<decimal> source)
                {
                        Check.Source (source);
 
-                       var total = default (TAggregate);
-                       long counter = 0;
-                       foreach (var element in source) {
-                               total = func (total, element);
-                               ++counter;
+                       decimal total = 0;
+                       long count = 0;
+                       foreach (var element in source){
+                               total += element;
+                               count++;
                        }
-
-                       if (counter == 0)
+                       if (count == 0)
                                throw new InvalidOperationException ();
-
-                       return result (total, counter);
+                       return total / count;
                }
 
                static TResult? AverageNullable<TElement, TAggregate, TResult> (this IEnumerable<TElement?> source,
@@ -234,105 +263,297 @@ namespace System.Linq
                {
                        Check.Source (source);
 
-                       return source.AverageNullable<int, long, double> ((a, b) => a + b, (a, b) => (double) a / (double) b);
+                       long total = 0;
+                       long counter = 0;
+                       
+                       foreach (var element in source) {
+                               if (!element.HasValue)
+                                       continue;
+
+                               total = total + element.Value;
+                               counter++;
+                       }
+
+                       if (counter == 0)
+                               return null;
+
+                       return new double? (total / (double) counter);
                }
 
                public static double? Average (this IEnumerable<long?> source)
                {
                        Check.Source (source);
 
-                       return source.AverageNullable<long, long, double> ((a, b) => a + b, (a, b) => (double) a / b);
+                       long total = 0;
+                       long counter = 0;
+                       
+                       foreach (var element in source) {
+                               if (!element.HasValue)
+                                       continue;
+
+                               total = checked (total + element.Value);
+                               counter++;
+                       }
+
+                       if (counter == 0)
+                               return null;
+
+                       return new double? (total / (double) counter);
+
                }
 
                public static double? Average (this IEnumerable<double?> source)
                {
                        Check.Source (source);
 
-                       return source.AverageNullable<double, double, double> ((a, b) => a + b, (a, b) => a / b);
+                       double total = 0;
+                       long counter = 0;
+                       
+                       foreach (var element in source) {
+                               if (!element.HasValue)
+                                       continue;
+
+                               total = total + element.Value;
+                               counter++;
+                       }
+
+                       if (counter == 0)
+                               return null;
+
+                       return new double? (total / counter);
+
                }
 
                public static decimal? Average (this IEnumerable<decimal?> source)
                {
                        Check.Source (source);
 
-                       return source.AverageNullable<decimal, decimal, decimal> ((a, b) => a + b, (a, b) => a / b);
+                       decimal total = 0;
+                       long counter = 0;
+                       
+                       foreach (var element in source) {
+                               if (!element.HasValue)
+                                       continue;
+
+                               total = total + element.Value;
+                               counter++;
+                       }
+
+                       if (counter == 0)
+                               return null;
+
+                       return new decimal? (total / counter);
+
                }
 
                public static float? Average (this IEnumerable<float?> source)
                {
                        Check.Source (source);
 
-                       return source.AverageNullable<float, double, float> ((a, b) => a + b, (a, b) => (float) a / (float) b);
+                       float total = 0;
+                       long counter = 0;
+                       
+                       foreach (var element in source) {
+                               if (!element.HasValue)
+                                       continue;
+
+                               total = total + element.Value;
+                               counter++;
+                       }
+
+                       if (counter == 0)
+                               return null;
+
+                       return new float? (total / counter);
+
                }
 
                public static double Average<TSource> (this IEnumerable<TSource> source, Func<TSource, int> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return source.Select (selector).Average<int, long, double> ((a, b) => a + b, (a, b) => (double) a / (double) b);
+                       long total = 0;
+                       long count = 0;
+                       foreach (var element in source){
+                               total += selector (element);
+                               count++;
+                       }
+                       if (count == 0)
+                               throw new InvalidOperationException ();
+                       return total / (double) count;
                }
 
                public static double? Average<TSource> (this IEnumerable<TSource> source, Func<TSource, int?> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return source.Select (selector).AverageNullable<int, long, double> ((a, b) => a + b, (a, b) => (double) a / (double) b);
+                       long total = 0;
+                       long counter = 0;
+                       
+                       foreach (var element in source) {
+                               var value = selector (element);
+                               if (!value.HasValue)
+                                       continue;
+
+                               total = total + value.Value;
+                               counter++;
+                       }
+
+                       if (counter == 0)
+                               return null;
+
+                       return new double? (total / (double) counter);
                }
 
                public static double Average<TSource> (this IEnumerable<TSource> source, Func<TSource, long> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return source.Select (selector).Average<long, long, double> ((a, b) => a + b, (a, b) => (double) a / (double) b);
+                       long total = 0;
+                       long count = 0;
+                       foreach (var element in source){
+                               total = checked (total + selector (element));
+                               count++;
+                       }
+                       if (count == 0)
+                               throw new InvalidOperationException ();
+                       return total / (double) count;
+
                }
 
                public static double? Average<TSource> (this IEnumerable<TSource> source, Func<TSource, long?> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return source.Select (selector).AverageNullable<long, long, double> ((a, b) => a + b, (a, b) => (double) a / (double) b);
+                       long total = 0;
+                       long counter = 0;
+                       
+                       foreach (var element in source) {
+                               var value = selector (element);
+                               if (!value.HasValue)
+                                       continue;
+
+                               total = checked (total + value.Value);
+                               counter++;
+                       }
+
+                       if (counter == 0)
+                               return null;
+
+                       return new double? (total / (double) counter);
                }
 
                public static double Average<TSource> (this IEnumerable<TSource> source, Func<TSource, double> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return source.Select (selector).Average<double, double, double> ((a, b) => a + b, (a, b) => a / b);
+                       double total = 0;
+                       long count = 0;
+                       foreach (var element in source){
+                               total += selector (element);
+                               count++;
+                       }
+                       if (count == 0)
+                               throw new InvalidOperationException ();
+                       return total / count;
+
                }
 
                public static double? Average<TSource> (this IEnumerable<TSource> source, Func<TSource, double?> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return source.Select (selector).AverageNullable<double, double, double> ((a, b) => a + b, (a, b) => a / b);
+                       double total = 0;
+                       long counter = 0;
+                       
+                       foreach (var element in source) {
+                               var value = selector (element);
+                               if (!value.HasValue)
+                                       continue;
+
+                               total = total + value.Value;
+                               counter++;
+                       }
+
+                       if (counter == 0)
+                               return null;
+
+                       return new double? (total / counter);
+
                }
 
                public static float Average<TSource> (this IEnumerable<TSource> source, Func<TSource, float> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return source.Select (selector).Average<float, double, float> ((a, b) => a + b, (a, b) => (float) a / (float) b);
+                       float total = 0;
+                       long count = 0;
+                       foreach (var element in source){
+                               total += selector (element);
+                               count++;
+                       }
+                       if (count == 0)
+                               throw new InvalidOperationException ();
+                       return total / count;
                }
 
                public static float? Average<TSource> (this IEnumerable<TSource> source, Func<TSource, float?> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return source.Select (selector).AverageNullable<float, double, float> ((a, b) => a + b, (a, b) => (float) a / (float) b);
+                       float total = 0;
+                       long counter = 0;
+                       
+                       foreach (var element in source) {
+                               var value = selector (element);
+                               if (!value.HasValue)
+                                       continue;
+
+                               total = total + value.Value;
+                               counter++;
+                       }
+
+                       if (counter == 0)
+                               return null;
+
+                       return new float? (total / counter);
                }
 
                public static decimal Average<TSource> (this IEnumerable<TSource> source, Func<TSource, decimal> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return source.Select (selector).Average<decimal, decimal, decimal> ((a, b) => a + b, (a, b) => a / b);
+                       decimal total = 0;
+                       long count = 0;
+                       foreach (var element in source){
+                               total += selector (element);
+                               count++;
+                       }
+                       if (count == 0)
+                               throw new InvalidOperationException ();
+                       return total / count;
                }
 
                public static decimal? Average<TSource> (this IEnumerable<TSource> source, Func<TSource, decimal?> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return source.Select (selector).AverageNullable<decimal, decimal, decimal> ((a, b) => a + b, (a, b) => a / b);
+                       decimal total = 0;
+                       long counter = 0;
+                       
+                       foreach (var element in source) {
+                               var value = selector (element);
+                               if (!value.HasValue)
+                                       continue;
+
+                               total = total + value.Value;
+                               counter++;
+                       }
+
+                       if (counter == 0)
+                               return null;
+
+                       return new decimal? (total / counter);
                }
 
                #endregion
@@ -1027,200 +1248,289 @@ namespace System.Linq
                {
                        Check.Source (source);
 
-                       return Iterate (source, int.MinValue, (a, b) => Math.Max (a, b));
+                       bool empty = true;
+                       var max = int.MinValue;
+                       foreach (var element in source){
+                               max = Math.Max (element, max);
+                               empty = false;
+                       }
+                       if (empty)
+                               throw new InvalidOperationException ();
+                       return max;
                }
 
                public static long Max (this IEnumerable<long> source)
                {
                        Check.Source (source);
 
-                       return Iterate (source, long.MinValue, (a, b) => Math.Max (a, b));
+                       bool empty = true;
+                       var max = long.MinValue;
+                       foreach (var element in source){
+                               max = Math.Max (element, max);
+                               empty = false;
+                       }
+                       if (empty)
+                               throw new InvalidOperationException ();
+                       return max;
                }
 
                public static double Max (this IEnumerable<double> source)
                {
                        Check.Source (source);
 
-                       return Iterate (source, double.MinValue, (a, b) => Math.Max (a, b));
+                       bool empty = true;
+                       var max = double.MinValue;
+                       foreach (var element in source){
+                               max = Math.Max (element, max);
+                               empty = false;
+                       }
+                       if (empty)
+                               throw new InvalidOperationException ();
+                       return max;
                }
 
                public static float Max (this IEnumerable<float> source)
                {
                        Check.Source (source);
 
-                       return Iterate (source, float.MinValue, (a, b) => Math.Max (a, b));
+                       bool empty = true;
+                       var max = float.MinValue;
+                       foreach (var element in source){
+                               max = Math.Max (element, max);
+                               empty = false;
+                       }
+                       if (empty)
+                               throw new InvalidOperationException ();
+                       return max;
                }
 
                public static decimal Max (this IEnumerable<decimal> source)
                {
                        Check.Source (source);
 
-                       return Iterate (source, decimal.MinValue, (a, b) => Math.Max (a, b));
+                       bool empty = true;
+                       var max = decimal.MinValue;
+                       foreach (var element in source){
+                               max = Math.Max (element, max);
+                               empty = false;
+                       }
+                       if (empty)
+                               throw new InvalidOperationException ();
+                       return max;
                }
 
                public static int? Max (this IEnumerable<int?> source)
                {
                        Check.Source (source);
 
-                       return IterateNullable (source, (a, b) => Math.Max (a, b));
-               }
-
-               public static long? Max (this IEnumerable<long?> source)
-               {
-                       Check.Source (source);
-
-                       return IterateNullable (source, (a, b) => Math.Max (a, b));
-               }
-
-               public static double? Max (this IEnumerable<double?> source)
-               {
-                       Check.Source (source);
+                       bool empty = true;
+                       var max = int.MinValue;
+                               
+                       foreach (var element in source) {
+                               if (!element.HasValue)
+                                       continue;
 
-                       return IterateNullable (source, (a, b) => Math.Max (a, b));
-               }
+                               max = Math.Max (element.Value, max);
+                               empty = false;
+                       }
 
-               public static float? Max (this IEnumerable<float?> source)
-               {
-                       Check.Source (source);
+                       if (empty)
+                               return null;
 
-                       return IterateNullable (source, (a, b) => Math.Max (a, b));
+                       return max;
                }
 
-               public static decimal? Max (this IEnumerable<decimal?> source)
+               public static long? Max (this IEnumerable<long?> source)
                {
                        Check.Source (source);
 
-                       return IterateNullable (source, (a, b) => Math.Max (a, b));
-               }
-
-               static T? IterateNullable<T> (IEnumerable<T?> source, Func<T, T, T> selector) where T : struct
-               {
                        bool empty = true;
-                       T? value = null;
+                       var max = long.MinValue;
+                               
                        foreach (var element in source) {
                                if (!element.HasValue)
                                        continue;
 
-                               if (!value.HasValue)
-                                       value = element.Value;
-                               else
-                                       value = selector (element.Value, value.Value);
-
+                               max = Math.Max (element.Value, max);
                                empty = false;
                        }
 
                        if (empty)
                                return null;
 
-                       return value;
+                       return max;
                }
 
-               static TRet? IterateNullable<TSource, TRet> (
-                       IEnumerable<TSource> source,
-                       Func<TSource, TRet?> source_selector,
-                       Func<TRet?, TRet?, bool> selector) where TRet : struct
+               public static double? Max (this IEnumerable<double?> source)
                {
+                       Check.Source (source);
+
                        bool empty = true;
-                       TRet? value = null;
+                       var max = double.MinValue;
+                               
                        foreach (var element in source) {
-                               TRet? item = source_selector (element);
-
-                               if (!value.HasValue)
-                                       value = item;
-                               else if (selector (item, value))
-                                       value = item;
+                               if (!element.HasValue)
+                                       continue;
 
+                               max = Math.Max (element.Value, max);
                                empty = false;
                        }
 
                        if (empty)
                                return null;
 
-                       return value;
+                       return max;
                }
 
-               static TSource IterateNullable<TSource> (IEnumerable<TSource> source, Func<TSource, TSource, bool> selector)
+               public static float? Max (this IEnumerable<float?> source)
                {
-                       var value = default (TSource);
+                       Check.Source (source);
 
+                       bool empty = true;
+                       var max = float.MinValue;
+                               
                        foreach (var element in source) {
-                               if (element == null)
+                               if (!element.HasValue)
                                        continue;
 
-                               if (value == null || selector (element, value))
-                                       value = element;
+                               max = Math.Max (element.Value, max);
+                               empty = false;
                        }
 
-                       return value;
+                       if (empty)
+                               return null;
+
+                       return max;
                }
 
-               static TSource IterateNonNullable<TSource> (IEnumerable<TSource> source, Func<TSource, TSource, bool> selector)
+               public static decimal? Max (this IEnumerable<decimal?> source)
                {
-                       var value = default (TSource);
+                       Check.Source (source);
+
                        bool empty = true;
+                       var max = decimal.MinValue;
+                               
                        foreach (var element in source) {
-                               if (empty) {
-                                       value = element;
-                                       empty = false;
+                               if (!element.HasValue)
                                        continue;
-                               }
 
-                               if (selector (element, value))
-                                       value = element;
+                               max = Math.Max (element.Value, max);
+                               empty = false;
                        }
 
                        if (empty)
-                               throw new InvalidOperationException ();
+                               return null;
 
-                       return value;
+                       return max;
                }
 
+               // TODO: test nullable and non-nullable
                public static TSource Max<TSource> (this IEnumerable<TSource> source)
                {
                        Check.Source (source);
 
                        var comparer = Comparer<TSource>.Default;
-                       Func<TSource, TSource, bool> compare = (a, b) => comparer.Compare (a, b) > 0;
 
-                       if (default (TSource) == null)
-                               return IterateNullable (source, compare);
-
-                       return IterateNonNullable (source, compare);
-               }
+                       TSource max = default (TSource);
+                       
+                       if (default (TSource) == null){
+                               foreach (var element in source) {
+                                       if (element == null)
+                                               continue;
 
-               public static int Max<TSource> (this IEnumerable<TSource> source, Func<TSource, int> selector)
-               {
-                       Check.SourceAndSelector (source, selector);
+                                       if (max == null || comparer.Compare (element, max) > 0)
+                                               max = element;
+                               }
+                       } else {
+                               bool empty = true;
+                               foreach (var element in source) {
+                                       if (empty){
+                                               max = element;
+                                               empty = false;
+                                               continue;
+                                       }
+                                       if (comparer.Compare (element, max) > 0)
+                                               max = element;
+                               }
+                               if (empty)
+                                       throw new InvalidOperationException ();
+                       }
+                       return max;
+               }
+
+               public static int Max<TSource> (this IEnumerable<TSource> source, Func<TSource, int> selector)
+               {
+                       Check.SourceAndSelector (source, selector);
 
-                       return Iterate (source, int.MinValue, (a, b) => Math.Max (selector (a), b));
+                       bool empty = true;
+                       var max = int.MinValue;
+                       foreach (var element in source){
+                               max = Math.Max (selector (element), max);
+                               empty = false;
+                       }
+                       if (empty)
+                               throw new InvalidOperationException ();
+                       return max;
                }
 
                public static long Max<TSource> (this IEnumerable<TSource> source, Func<TSource, long> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return Iterate (source, long.MinValue, (a, b) => Math.Max (selector (a), b));
+                       bool empty = true;
+                       var max = long.MinValue;
+                       foreach (var element in source){
+                               max = Math.Max (selector (element), max);
+                               empty = false;
+                       }
+                       if (empty)
+                               throw new InvalidOperationException ();
+                       return max;
                }
 
                public static double Max<TSource> (this IEnumerable<TSource> source, Func<TSource, double> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return Iterate (source, double.MinValue, (a, b) => Math.Max (selector (a), b));
+                       bool empty = true;
+                       var max = double.MinValue;
+                       foreach (var element in source){
+                               max = Math.Max (selector (element), max);
+                               empty = false;
+                       }
+                       if (empty)
+                               throw new InvalidOperationException ();
+                       return max;
                }
 
                public static float Max<TSource> (this IEnumerable<TSource> source, Func<TSource, float> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return Iterate (source, float.MinValue, (a, b) => Math.Max (selector (a), b));
+                       bool empty = true;
+                       var max = float.MinValue;
+                       foreach (var element in source){
+                               max = Math.Max (selector (element), max);
+                               empty = false;
+                       }
+                       if (empty)
+                               throw new InvalidOperationException ();
+                       return max;
                }
 
                public static decimal Max<TSource> (this IEnumerable<TSource> source, Func<TSource, decimal> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return Iterate (source, decimal.MinValue, (a, b) => Math.Max (selector (a), b));
+                       bool empty = true;
+                       var max = decimal.MinValue;
+                       foreach (var element in source){
+                               max = Math.Max (selector (element), max);
+                               empty = false;
+                       }
+                       if (empty)
+                               throw new InvalidOperationException ();
+                       return max;
                }
 
                static U Iterate<T, U> (IEnumerable<T> source, U initValue, Func<T, U, U> selector)
@@ -1241,41 +1551,112 @@ namespace System.Linq
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return IterateNullable (source, selector, (a, b) => a > b);
+                       bool empty = true;
+                       int? max = null;
+                       foreach (var element in source) {
+                               int? item = selector (element);
+
+                               if (!max.HasValue)
+                                       max = item;
+                               else if (item > max)
+                                       max = item;
+                               empty = false;
+                       }
+
+                       if (empty)
+                               return null;
+                       return max;
                }
 
                public static long? Max<TSource> (this IEnumerable<TSource> source, Func<TSource, long?> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return IterateNullable (source, selector, (a, b) => a > b);
+                       bool empty = true;
+                       long? max = null;
+                       foreach (var element in source) {
+                               long? item = selector (element);
+
+                               if (!max.HasValue)
+                                       max = item;
+                               else if (item > max)
+                                       max = item;
+                               empty = false;
+                       }
+
+                       if (empty)
+                               return null;
+                       return max;
                }
 
                public static double? Max<TSource> (this IEnumerable<TSource> source, Func<TSource, double?> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return IterateNullable (source, selector, (a, b) => a > b);
+                       bool empty = true;
+                       double? max = null;
+                       foreach (var element in source) {
+                               double? item = selector (element);
+
+                               if (!max.HasValue)
+                                       max = item;
+                               else if (item > max)
+                                       max = item;
+                               empty = false;
+                       }
+
+                       if (empty)
+                               return null;
+                       return max;
                }
 
                public static float? Max<TSource> (this IEnumerable<TSource> source, Func<TSource, float?> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return IterateNullable (source, selector, (a, b) => a > b);
+                       bool empty = true;
+                       float? max = null;
+                       foreach (var element in source) {
+                               float? item = selector (element);
+
+                               if (!max.HasValue)
+                                       max = item;
+                               else if (item > max)
+                                       max = item;
+                               empty = false;
+                       }
+
+                       if (empty)
+                               return null;
+                       return max;
                }
 
                public static decimal? Max<TSource> (this IEnumerable<TSource> source, Func<TSource, decimal?> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return IterateNullable (source, selector, (a, b) => a > b);
+                       bool empty = true;
+                       decimal? max = null;
+                       foreach (var element in source) {
+                               decimal? item = selector (element);
+
+                               if (!max.HasValue)
+                                       max = item;
+                               else if (item > max)
+                                       max = item;
+                               empty = false;
+                       }
+
+                       if (empty)
+                               return null;
+                       return max;
                }
 
                public static TResult Max<TSource, TResult> (this IEnumerable<TSource> source, Func<TSource, TResult> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
+                       // TODO: inline
                        return source.Select (selector).Max ();
                }
 
@@ -1287,70 +1668,180 @@ namespace System.Linq
                {
                        Check.Source (source);
 
-                       return Iterate (source, int.MaxValue, (a, b) => Math.Min (a, b));
+                       bool empty = true;
+                       var min = int.MaxValue;
+                       foreach (var element in source){
+                               min = Math.Min (element, min);
+                               empty = false;
+                       }
+                       if (empty)
+                               throw new InvalidOperationException ();
+                       return min;
                }
 
                public static long Min (this IEnumerable<long> source)
                {
                        Check.Source (source);
 
-                       return Iterate (source, long.MaxValue, (a, b) => Math.Min (a, b));
+                       bool empty = true;
+                       var min = long.MaxValue;
+                       foreach (var element in source){
+                               min = Math.Min (element, min);
+                               empty = false;
+                       }
+                       if (empty)
+                               throw new InvalidOperationException ();
+                       return min;
                }
 
                public static double Min (this IEnumerable<double> source)
                {
                        Check.Source (source);
 
-                       return Iterate (source, double.MaxValue, (a, b) => Math.Min (a, b));
+                       bool empty = true;
+                       var min = double.MaxValue;
+                       foreach (var element in source){
+                               min = Math.Min (element, min);
+                               empty = false;
+                       }
+                       if (empty)
+                               throw new InvalidOperationException ();
+                       return min;
                }
 
                public static float Min (this IEnumerable<float> source)
                {
                        Check.Source (source);
 
-                       return Iterate (source, float.MaxValue, (a, b) => Math.Min (a, b));
+                       bool empty = true;
+                       var min = float.MaxValue;
+                       foreach (var element in source){
+                               min = Math.Min (element, min);
+                               empty = false;
+                       }
+                       if (empty)
+                               throw new InvalidOperationException ();
+                       return min;
                }
 
                public static decimal Min (this IEnumerable<decimal> source)
                {
                        Check.Source (source);
 
-                       return Iterate (source, decimal.MaxValue, (a, b) => Math.Min (a, b));
+                       bool empty = true;
+                       var min = decimal.MaxValue;
+                       foreach (var element in source){
+                               min = Math.Min (element, min);
+                               empty = false;
+                       }
+                       if (empty)
+                               throw new InvalidOperationException ();
+                       return min;
                }
 
                public static int? Min (this IEnumerable<int?> source)
                {
                        Check.Source (source);
 
-                       return IterateNullable (source, (a, b) => Math.Min (a, b));
+                       bool empty = true;
+                       var min = int.MaxValue;
+                               
+                       foreach (var element in source) {
+                               if (!element.HasValue)
+                                       continue;
+
+                               min = Math.Min (element.Value, min);
+                               empty = false;
+                       }
+
+                       if (empty)
+                               return null;
+
+                       return min;
                }
 
                public static long? Min (this IEnumerable<long?> source)
                {
                        Check.Source (source);
 
-                       return IterateNullable (source, (a, b) => Math.Min (a, b));
+                       bool empty = true;
+                       var min = long.MaxValue;
+                               
+                       foreach (var element in source) {
+                               if (!element.HasValue)
+                                       continue;
+
+                               min = Math.Min (element.Value, min);
+                               empty = false;
+                       }
+
+                       if (empty)
+                               return null;
+
+                       return min;
                }
 
                public static double? Min (this IEnumerable<double?> source)
                {
                        Check.Source (source);
 
-                       return IterateNullable (source, (a, b) => Math.Min (a, b));
+                       bool empty = true;
+                       var min = double.MaxValue;
+                               
+                       foreach (var element in source) {
+                               if (!element.HasValue)
+                                       continue;
+
+                               min = Math.Min (element.Value, min);
+                               empty = false;
+                       }
+
+                       if (empty)
+                               return null;
+
+                       return min;
                }
 
                public static float? Min (this IEnumerable<float?> source)
                {
                        Check.Source (source);
 
-                       return IterateNullable (source, (a, b) => Math.Min (a, b));
+                       bool empty = true;
+                       var min = float.MaxValue;
+                               
+                       foreach (var element in source) {
+                               if (!element.HasValue)
+                                       continue;
+
+                               min = Math.Min (element.Value, min);
+                               empty = false;
+                       }
+
+                       if (empty)
+                               return null;
+
+                       return min;
                }
 
                public static decimal? Min (this IEnumerable<decimal?> source)
                {
                        Check.Source (source);
 
-                       return IterateNullable (source, (a, b) => Math.Min (a, b));
+                       bool empty = true;
+                       var min = decimal.MaxValue;
+                               
+                       foreach (var element in source) {
+                               if (!element.HasValue)
+                                       continue;
+
+                               min = Math.Min (element.Value, min);
+                               empty = false;
+                       }
+
+                       if (empty)
+                               return null;
+
+                       return min;
                }
 
                public static TSource Min<TSource> (this IEnumerable<TSource> source)
@@ -1358,88 +1849,219 @@ namespace System.Linq
                        Check.Source (source);
 
                        var comparer = Comparer<TSource>.Default;
-                       Func<TSource, TSource, bool> compare = (a, b) => comparer.Compare (a, b) < 0;
 
-                       if (default (TSource) == null)
-                               return IterateNullable (source, compare);
+                       TSource min = default (TSource);
+                       
+                       if (default (TSource) == null){
+                               foreach (var element in source) {
+                                       if (element == null)
+                                               continue;
 
-                       return IterateNonNullable (source, compare);
+                                       if (min == null || comparer.Compare (element, min) < 0)
+                                               min = element;
+                               }
+                       } else {
+                               bool empty = true;
+                               foreach (var element in source) {
+                                       if (empty){
+                                               min = element;
+                                               empty = false;
+                                               continue;
+                                       }
+                                       if (comparer.Compare (element, min) < 0)
+                                               min = element;
+                               }
+                               if (empty)
+                                       throw new InvalidOperationException ();
+                       }
+                       return min;
                }
 
                public static int Min<TSource> (this IEnumerable<TSource> source, Func<TSource, int> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return Iterate (source, int.MaxValue, (a, b) => Math.Min (selector (a), b));
+                       bool empty = true;
+                       var min = int.MaxValue;
+                       foreach (var element in source){
+                               min = Math.Min (selector (element), min);
+                               empty = false;
+                       }
+                       if (empty)
+                               throw new InvalidOperationException ();
+                       return min;
                }
 
                public static long Min<TSource> (this IEnumerable<TSource> source, Func<TSource, long> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return Iterate (source, long.MaxValue, (a, b) => Math.Min (selector (a), b));
+                       bool empty = true;
+                       var min = long.MaxValue;
+                       foreach (var element in source){
+                               min = Math.Min (selector (element), min);
+                               empty = false;
+                       }
+                       if (empty)
+                               throw new InvalidOperationException ();
+                       return min;
                }
 
                public static double Min<TSource> (this IEnumerable<TSource> source, Func<TSource, double> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return Iterate (source, double.MaxValue, (a, b) => Math.Min (selector (a), b));
+                       bool empty = true;
+                       var min = double.MaxValue;
+                       foreach (var element in source){
+                               min = Math.Min (selector (element), min);
+                               empty = false;
+                       }
+                       if (empty)
+                               throw new InvalidOperationException ();
+                       return min;
                }
 
                public static float Min<TSource> (this IEnumerable<TSource> source, Func<TSource, float> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return Iterate (source, float.MaxValue, (a, b) => Math.Min (selector (a), b));
+                       bool empty = true;
+                       var min = float.MaxValue;
+                       foreach (var element in source){
+                               min = Math.Min (selector (element), min);
+                               empty = false;
+                       }
+                       if (empty)
+                               throw new InvalidOperationException ();
+                       return min;
                }
 
                public static decimal Min<TSource> (this IEnumerable<TSource> source, Func<TSource, decimal> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return Iterate (source, decimal.MaxValue, (a, b) => Math.Min (selector (a), b));
+                       bool empty = true;
+                       var min = decimal.MaxValue;
+                       foreach (var element in source){
+                               min = Math.Min (selector (element), min);
+                               empty = false;
+                       }
+                       if (empty)
+                               throw new InvalidOperationException ();
+                       return min;
                }
 
                public static int? Min<TSource> (this IEnumerable<TSource> source, Func<TSource, int?> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return IterateNullable (source, selector, (a, b) => a < b);
+                       bool empty = true;
+                       int? min = null;
+                       foreach (var element in source) {
+                               int? item = selector (element);
+
+                               if (!min.HasValue)
+                                       min = item;
+                               else if (item < min)
+                                       min = item;
+                               empty = false;
+                       }
+
+                       if (empty)
+                               return null;
+                       return min;
                }
 
                public static long? Min<TSource> (this IEnumerable<TSource> source, Func<TSource, long?> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return IterateNullable (source, selector, (a, b) => a < b);
+                       bool empty = true;
+                       long? min = null;
+                       foreach (var element in source) {
+                               long? item = selector (element);
+
+                               if (!min.HasValue)
+                                       min = item;
+                               else if (item < min)
+                                       min = item;
+                               empty = false;
+                       }
+
+                       if (empty)
+                               return null;
+                       return min;
                }
 
                public static float? Min<TSource> (this IEnumerable<TSource> source, Func<TSource, float?> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return IterateNullable (source, selector, (a, b) => a < b);
+                       bool empty = true;
+                       float? min = null;
+                       foreach (var element in source) {
+                               float? item = selector (element);
+
+                               if (!min.HasValue)
+                                       min = item;
+                               else if (item < min)
+                                       min = item;
+                               empty = false;
+                       }
+
+                       if (empty)
+                               return null;
+                       return min;
                }
 
                public static double? Min<TSource> (this IEnumerable<TSource> source, Func<TSource, double?> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return IterateNullable (source, selector, (a, b) => a < b);
+                       bool empty = true;
+                       double? min = null;
+                       foreach (var element in source) {
+                               double? item = selector (element);
+
+                               if (!min.HasValue)
+                                       min = item;
+                               else if (item < min)
+                                       min = item;
+                               empty = false;
+                       }
+
+                       if (empty)
+                               return null;
+                       return min;
                }
 
                public static decimal? Min<TSource> (this IEnumerable<TSource> source, Func<TSource, decimal?> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return IterateNullable (source, selector, (a, b) => a < b);
+                       bool empty = true;
+                       decimal? min = null;
+                       foreach (var element in source) {
+                               decimal? item = selector (element);
+
+                               if (!min.HasValue)
+                                       min = item;
+                               else if (item < min)
+                                       min = item;
+                               empty = false;
+                       }
+
+                       if (empty)
+                               return null;
+                       return min;
                }
 
                public static TResult Min<TSource, TResult> (this IEnumerable<TSource> source, Func<TSource, TResult> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
+                       // TODO: inline
                        return source.Select (selector).Min ();
                }
 
@@ -1803,175 +2425,231 @@ namespace System.Linq
                public static int Sum (this IEnumerable<int> source)
                {
                        Check.Source (source);
-
-                       return Sum<int, int> (source, (a, b) => checked (a + b));
+                       int total = 0;
+                       
+                       foreach (var element in source)
+                               total = checked (total + element);
+                       return total;
                }
 
                public static int? Sum (this IEnumerable<int?> source)
                {
                        Check.Source (source);
 
-                       return source.SumNullable<int?, int?> (0, (total, element) => element.HasValue ? checked (total + element) : total);
+                       int total = 0;
+                       foreach (var element in source) {
+                               if (element.HasValue)
+                                       total = checked (total + element.Value);
+                       }
+                       return total;
                }
 
                public static int Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, int> selector)
                {
                        Check.SourceAndSelector (source, selector);
+                       int total = 0;
+
+                       foreach (var element in source)
+                               total = checked (total + selector (element));
 
-                       return Sum<TSource, int> (source, (a, b) => checked (a + selector (b)));
+                       return total;
                }
 
                public static int? Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, int?> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return source.SumNullable<TSource, int?> (0, (a, b) => {
-                               var value = selector (b);
-                               return value.HasValue ? checked (a + value.Value) : a;
-                       });
+                       int total = 0;
+                       foreach (var element in source) {
+                               var value = selector (element);
+                               if (value.HasValue)
+                                       total = checked (total + value.Value);
+                       }
+                       return total;
                }
 
                public static long Sum (this IEnumerable<long> source)
                {
                        Check.Source (source);
 
-                       return Sum<long, long> (source, (a, b) => checked (a + b));
+                       long total = 0;
+                       
+                       foreach (var element in source)
+                               total = checked (total + element);
+                       return total;
                }
 
                public static long? Sum (this IEnumerable<long?> source)
                {
                        Check.Source (source);
 
-                       return source.SumNullable<long?, long?> (0, (total, element) => element.HasValue ? checked (total + element) : total);
+                       long total = 0;
+                       foreach (var element in source) {
+                               if (element.HasValue)
+                                       total = checked (total + element.Value);
+                       }
+                       return total;
                }
 
                public static long Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, long> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return Sum<TSource, long> (source, (a, b) => checked (a + selector (b)));
+                       long total = 0;
+                       foreach (var element in source)
+                               total = checked (total + selector (element));
+                       return total;
                }
 
                public static long? Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, long?> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return source.SumNullable<TSource, long?> (0, (a, b) => {
-                               var value = selector (b);
-                               return value.HasValue ? checked (a + value.Value) : a;
-                       });
+                       long total = 0;
+                       foreach (var element in source) {
+                               var value = selector (element);
+                               if (value.HasValue)
+                                       total = checked (total + value.Value);
+                       }
+                       return total;
                }
 
                public static double Sum (this IEnumerable<double> source)
                {
                        Check.Source (source);
 
-                       return Sum<double, double> (source, (a, b) => checked (a + b));
+                       double total = 0;
+                       
+                       foreach (var element in source)
+                               total = checked (total + element);
+                       return total;
                }
 
                public static double? Sum (this IEnumerable<double?> source)
                {
                        Check.Source (source);
 
-                       return source.SumNullable<double?, double?> (0, (total, element) => element.HasValue ? checked (total + element) : total);
+                       double total = 0;
+                       foreach (var element in source) {
+                               if (element.HasValue)
+                                       total = checked (total + element.Value);
+                       }
+                       return total;
                }
 
                public static double Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, double> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return Sum<TSource, double> (source, (a, b) => checked (a + selector (b)));
+                       double total = 0;
+                       
+                       foreach (var element in source)
+                               total = checked (total + selector (element));
+                       return total;
                }
 
                public static double? Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, double?> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return source.SumNullable<TSource, double?> (0, (a, b) => {
-                               var value = selector (b);
-                               return value.HasValue ? checked (a + value.Value) : a;
-                       });
+                       double total = 0;
+                       foreach (var element in source) {
+                               var value = selector (element);
+                               if (value.HasValue)
+                                       total = checked (total + value.Value);
+                       }
+                       return total;
                }
 
                public static float Sum (this IEnumerable<float> source)
                {
                        Check.Source (source);
 
-                       return Sum<float, float> (source, (a, b) => checked (a + b));
+                       float total = 0;
+                       
+                       foreach (var element in source)
+                               total = checked (total + element);
+                       return total;
                }
 
                public static float? Sum (this IEnumerable<float?> source)
                {
                        Check.Source (source);
 
-                       return source.SumNullable<float?, float?> (0, (total, element) => element.HasValue ? checked (total + element) : total);
+                       float total = 0;
+                       foreach (var element in source) {
+                               if (element.HasValue)
+                                       total = checked (total + element.Value);
+                       }
+                       return total;
+
                }
 
                public static float Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, float> selector)
                {
                        Check.SourceAndSelector (source, selector);
-
-                       return Sum<TSource, float> (source, (a, b) => checked (a + selector (b)));
+                       float total = 0;
+                       foreach (var element in source)
+                               total = checked (total + selector (element));
+                       return total;
                }
 
                public static float? Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, float?> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return source.SumNullable<TSource, float?> (0, (a, b) => {
-                               var value = selector (b);
-                               return value.HasValue ? checked (a + value.Value) : a;
-                       });
+                       float total = 0;
+                       foreach (var element in source) {
+                               var value = selector (element);
+                               if (value.HasValue)
+                                       total = checked (total + value.Value);
+                       }
+                       return total;
                }
 
                public static decimal Sum (this IEnumerable<decimal> source)
                {
                        Check.Source (source);
-
-                       return Sum<decimal, decimal> (source, (a, b) => checked (a + b));
+                       decimal total = 0;
+                       
+                       foreach (var element in source)
+                               total = checked (total + element);
+                       return total;
                }
 
                public static decimal? Sum (this IEnumerable<decimal?> source)
                {
                        Check.Source (source);
 
-                       return source.SumNullable<decimal?, decimal?> (0, (total, element) => element.HasValue ? checked (total + element) : total);
+                       decimal total = 0;
+                       foreach (var element in source) {
+                               if (element.HasValue)
+                                       total = checked (total + element.Value);
+                       }
+                       return total;
+
                }
 
                public static decimal Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, decimal> selector)
                {
                        Check.SourceAndSelector (source, selector);
-
-                       return Sum<TSource, decimal> (source, (a, b) => checked (a + selector (b)));
+                       decimal total = 0;
+                       
+                       foreach (var element in source)
+                               total = checked (total + selector (element));
+                       return total;
                }
 
                public static decimal? Sum<TSource> (this IEnumerable<TSource> source, Func<TSource, decimal?> selector)
                {
                        Check.SourceAndSelector (source, selector);
 
-                       return source.SumNullable<TSource, decimal?> (0, (a, b) => {
-                               var value = selector (b);
-                               return value.HasValue ? checked (a + value.Value) : a;
-                       });
-               }
-
-               static TR Sum<TA, TR> (this IEnumerable<TA> source, Func<TR, TA, TR> selector)
-               {
-                       TR total = default (TR);
+                       decimal total = 0;
                        foreach (var element in source) {
-                               total = selector (total, element);
+                               var value = selector (element);
+                               if (value.HasValue)
+                                       total = checked (total + value.Value);
                        }
-
-                       return total;
-               }
-
-               static TR SumNullable<TA, TR> (this IEnumerable<TA> source, TR zero, Func<TR, TA, TR> selector)
-               {
-                       TR total = zero;
-                       foreach (var element in source) {
-                               total = selector (total, element);
-                       }
-
                        return total;
                }
 
index 836fe1e0d3c98b752a9fbadfa5d23f48cacf04f6..7d7b16abbf04c8c908eb6c3cba9ecd67ea7bc09d 100644 (file)
@@ -32,6 +32,9 @@ namespace System.Linq
 {
        public abstract class EnumerableExecutor
        {
+               protected EnumerableExecutor ()
+               {
+               }
        }
 }
 
index beb420ab0c718a0da99199088052018d3ec6273a..3ead6e60bad64ecbab461fbaaf67bcda882f216c 100644 (file)
@@ -32,6 +32,9 @@ namespace System.Linq
 {
        public abstract class EnumerableQuery
        {
+               protected EnumerableQuery ()
+               {
+               }
        }
 }
 
index 8120f2a67698ced27ffdedb64fd51586952d43fa..d610d2fc58f86e1a88c8be6fd3d33e19d0b5a55e 100644 (file)
@@ -3,6 +3,7 @@
 //
 // Authors:
 //  Marek Safar  <marek.safar@gmail.com>
+//  Jb Evain  <jbevain@novell.com>
 //
 // Copyright (C) 2009 Novell, Inc (http://www.novell.com)
 //
 
 #if NET_4_0
 
-using System.Linq.Expressions;
+using System.Collections;
 using System.Collections.Generic;
+using System.Linq.Expressions;
 
 namespace System.Linq
 {
-       public class EnumerableQuery<T> : EnumerableQuery
+       public class EnumerableQuery<T> : EnumerableQuery, IOrderedQueryable<T>, IQueryable<T>, IQueryProvider
        {
+               QueryableEnumerable<T> queryable;
+
+               public Type ElementType {
+                       get { return queryable.ElementType; }
+               }
+
+               public Expression Expression {
+                       get { return queryable.Expression; }
+               }
+
+               public IQueryProvider Provider {
+                       get { return queryable; }
+               }
+
                public EnumerableQuery (Expression expression)
                {
+                       queryable = new QueryableEnumerable<T> (expression);
+               }
+
+               public EnumerableQuery (IEnumerable<T> enumerable)
+               {
+                       queryable = new QueryableEnumerable<T> (enumerable);
                }
-               
-               public EnumerableQuery (IEnumerable<T> expression)
+
+               public IEnumerable GetEnumerable ()
+               {
+                       return queryable.GetEnumerable ();
+               }
+
+               IEnumerator IEnumerable.GetEnumerator ()
+               {
+                       return queryable.GetEnumerator ();
+               }
+
+               public IEnumerator<T> GetEnumerator ()
+               {
+                       return queryable.GetEnumerator ();
+               }
+
+               public IQueryable CreateQuery (Expression expression)
+               {
+                       return queryable.CreateQuery (expression);
+               }
+
+               public object Execute (Expression expression)
+               {
+                       return queryable.Execute (expression);
+               }
+
+               public IQueryable<TElem> CreateQuery<TElem> (Expression expression)
+               {
+                       return new EnumerableQuery<TElem> (expression);
+               }
+
+               public TResult Execute<TResult> (Expression expression)
                {
+                       return queryable.Execute<TResult> (expression);
                }
        }
 }
diff --git a/mcs/class/System.Core/System.Linq/Internal/AggregationList.cs b/mcs/class/System.Core/System.Linq/Internal/AggregationList.cs
new file mode 100644 (file)
index 0000000..50bee2b
--- /dev/null
@@ -0,0 +1,135 @@
+#if NET_4_0
+//
+// AggregationList.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace System.Linq
+{
+       internal class AggregationList<T> : IList<T>
+       {
+               readonly IList<IList<T>> listes;
+               readonly int count;
+
+               internal AggregationList (IList<IList<T>> listes)
+               {
+                       this.listes = listes;
+                       foreach (var l in listes)
+                               count += l.Count;
+               }
+
+               public int IndexOf (T item)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public void Insert (int index, T item)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public void RemoveAt (int index)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public T this[int index] {
+                       get {
+                               int listIndex, newIndex;
+                               GetModifiedIndexes (index, out listIndex, out newIndex);
+
+                               return listes[listIndex][newIndex];
+                       }
+                       set {
+                               throw new NotImplementedException();
+                       }
+               }
+
+               void GetModifiedIndexes (int index, out int listIndex, out int newIndex)
+               {
+                       listIndex = 0;
+                       newIndex = index;
+
+                       while (newIndex >= listes[listIndex].Count) {
+                               newIndex -= listes[listIndex].Count;
+                               listIndex++;
+
+                               if (listIndex > listes.Count)
+                                       throw new ArgumentOutOfRangeException ();
+                       }
+               }
+
+               public void Add (T item)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public void Clear ()
+               {
+                       throw new NotImplementedException();
+               }
+
+               public bool Contains (T item)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public void CopyTo (T[] array, int arrayIndex)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public bool Remove (T item)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public int Count {
+                       get {
+                               return count;
+                       }
+               }
+
+               public bool IsReadOnly {
+                       get {
+                               return true;
+                       }
+               }
+
+               IEnumerator<T> IEnumerable<T>.GetEnumerator ()
+               {
+                       return null;
+               }
+
+               IEnumerator IEnumerable.GetEnumerator ()
+               {
+                       return null;
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/ChangeLog b/mcs/class/System.Core/System.Linq/Internal/ChangeLog
new file mode 100644 (file)
index 0000000..e7aa198
--- /dev/null
@@ -0,0 +1,12 @@
+2010-04-15  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * AggregationList.cs:
+       * ConcurrentGrouping.cs:
+       * ConcurrentLookup.cs:
+       * OrderingEnumerator.cs:
+       * ParallelQuickSort.cs:
+       * RangeList.cs:
+       * RepeatList.cs:
+       * ReverseList.cs:
+       * StripPartitioner.cs: Initial check-in of PLinq
+
diff --git a/mcs/class/System.Core/System.Linq/Internal/ConcurrentGrouping.cs b/mcs/class/System.Core/System.Linq/Internal/ConcurrentGrouping.cs
new file mode 100644 (file)
index 0000000..f1cdd3c
--- /dev/null
@@ -0,0 +1,65 @@
+#if NET_4_0
+//
+// ConcurrentGrouping.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.Concurrent;
+
+namespace System.Linq
+{
+       internal class ConcurrentGrouping<TKey, TElement> : IGrouping<TKey, TElement>
+       {
+               TKey key;
+               IEnumerable<TElement> elements;
+
+               internal ConcurrentGrouping (TKey key, IEnumerable<TElement> elements)
+               {
+                       this.key = key;
+                       this.elements = elements;
+               }
+
+               public TKey Key {
+                       get {
+                               return key;
+                       }
+               }
+
+               IEnumerator IEnumerable.GetEnumerator ()
+               {
+                       return ((IEnumerable)elements).GetEnumerator ();
+               }
+
+               IEnumerator<TElement> IEnumerable<TElement>.GetEnumerator ()
+               {
+                       return elements.GetEnumerator ();
+               }
+       }
+}
+
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/ConcurrentLookup.cs b/mcs/class/System.Core/System.Linq/Internal/ConcurrentLookup.cs
new file mode 100644 (file)
index 0000000..a39ccb2
--- /dev/null
@@ -0,0 +1,117 @@
+#if NET_4_0
+//
+// ConcurrentLookup.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.Concurrent;
+
+namespace System.Linq
+{
+       internal class ConcurrentLookup<TKey, TElement> : ILookup<TKey, TElement>
+       {
+               ConcurrentDictionary<TKey, IEnumerable<TElement>> dictionary;
+
+               private class AddSlot
+               {
+                       TElement element;
+
+                       internal AddSlot (TElement element)
+                       {
+                               this.element = element;
+                       }
+
+                       internal IEnumerable<TElement> AddMethod (TKey key)
+                       {
+                               List<TElement> list = new List<TElement> ();
+                               list.Add (element);
+
+                               return list;
+                       }
+
+                       internal IEnumerable<TElement> UpdateMethod (TKey key, IEnumerable<TElement> old)
+                       {
+                               ICollection<TElement> coll = (ICollection<TElement>)old;
+                               coll.Add (element);
+
+                               return coll;
+                       }
+               }
+
+               internal ConcurrentLookup (IEqualityComparer<TKey> comparer)
+               {
+                       this.dictionary = new ConcurrentDictionary<TKey, IEnumerable<TElement>> (comparer);
+               }
+
+               internal void Add (TKey key, TElement element)
+               {
+                       AddSlot slot = new AddSlot (element);
+                       dictionary.AddOrUpdate (key, slot.AddMethod, slot.UpdateMethod);
+               }
+
+               public bool Contains (TKey key)
+               {
+                       return dictionary.ContainsKey (key);
+               }
+
+               public IEnumerable<TElement> this[TKey key] {
+                       get {
+                               return dictionary[key];
+                       }
+               }
+
+               public int Count {
+                       get {
+                               return dictionary.Count;
+                       }
+               }
+               
+               public IList<TKey> Keys {
+                       get {
+                               return (IList<TKey>)dictionary.Keys;
+                       }
+               }
+
+               IEnumerator IEnumerable.GetEnumerator ()
+               {
+                       return (IEnumerator)GetEnumeratorInternal ();
+               }
+
+               IEnumerator<IGrouping<TKey, TElement>> IEnumerable<IGrouping<TKey, TElement>>.GetEnumerator ()
+               {
+                       return GetEnumeratorInternal ();
+               }
+
+               IEnumerator<IGrouping<TKey, TElement>> GetEnumeratorInternal ()
+               {
+                       return dictionary.Select ((pair) => new ConcurrentGrouping<TKey, TElement> (pair.Key, pair.Value)).GetEnumerator ();
+               }
+       }
+}
+
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/OrderingEnumerator.cs b/mcs/class/System.Core/System.Linq/Internal/OrderingEnumerator.cs
new file mode 100644 (file)
index 0000000..61f0949
--- /dev/null
@@ -0,0 +1,144 @@
+#if NET_4_0
+//
+// OrderingEnumerator.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.Concurrent;
+
+namespace System.Linq
+{
+       // Remove use of KeyedBuffer
+       /* Instead, we use a fixed array of nullables. The Add method put the object in its right slot based on the index.
+        * We use a barrier for synchronisation, each add check that the current range of index accepted in the array is correct
+        * and if not wait on the Barrier. The Barrier's generation index is used to calculate the next range.
+        * The IEnumerator interface simply skim the array in order and return the objects.
+        */
+       internal class OrderingEnumerator<T> : IEnumerator<T>
+       {
+               readonly int num;
+
+               public BlockingCollection<KeyValuePair<long, T>> KeyedBuffer;
+               KeyValuePair<long, T>?[] store;
+
+               IEnumerator<KeyValuePair<long, T>?> currEnum;
+               KeyValuePair<long, T> curr;
+
+               internal OrderingEnumerator (int num)
+               {
+                       this.num = num;
+                       KeyedBuffer = new BlockingCollection<KeyValuePair<long, T>> ();
+                       store = new KeyValuePair<long, T>?[num];
+               }
+
+               public void Dispose ()
+               {
+
+               }
+
+               public void Reset ()
+               {
+
+               }
+
+               public bool MoveNext ()
+               {
+                       if (currEnum == null || !currEnum.MoveNext () || !currEnum.Current.HasValue) {
+                               if (!UpdateCurrent ())
+                                       return false;
+                       }
+
+                       if (!currEnum.Current.HasValue)
+                               return false;
+
+                       curr = currEnum.Current.Value;
+
+                       return true;
+               }
+
+               public T Current {
+                       get {
+                               return curr.Value;
+                       }
+               }
+
+               object IEnumerator.Current {
+                       get {
+                               return curr.Value;
+                       }
+               }
+
+               bool UpdateCurrent ()
+               {
+                       if (KeyedBuffer.IsCompleted)
+                               return false;
+
+                       if (KeyedBuffer.Count != num) {
+                               SpinWait sw = new SpinWait ();
+                               while (KeyedBuffer.Count < num && !KeyedBuffer.IsAddingCompleted) {
+                                       sw.SpinOnce ();
+                               }
+                       }
+
+                       // We gather the lot without removing it
+                       int i = 0;
+                       foreach (KeyValuePair<long, T> item in KeyedBuffer.GetConsumingEnumerable ()) {
+                               store[i] = item;
+
+                               if (++i == num || KeyedBuffer.IsCompleted)
+                                       break;
+                       }
+
+                       for (int k = i; k < num; k++) {
+                               store[k] = null;
+                       }
+
+                       Array.Sort (store, ArraySort);
+
+                       currEnum = ((IEnumerable<KeyValuePair<long, T>?>)store).GetEnumerator ();
+
+                       return currEnum.MoveNext ();
+               }
+
+               int ArraySort (KeyValuePair<long, T>? e1, KeyValuePair<long, T>? e2)
+               {
+                       if (!e1.HasValue) {
+                               if (!e2.HasValue)
+                                       return 0;
+
+                               if (e2.HasValue)
+                                       return 1;
+                       }
+                       if (!e2.HasValue && e1.HasValue)
+                               return -1;
+
+                       return e1.Value.Key.CompareTo (e2.Value.Key);
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/ParallelQuickSort.cs b/mcs/class/System.Core/System.Linq/Internal/ParallelQuickSort.cs
new file mode 100644 (file)
index 0000000..52d841b
--- /dev/null
@@ -0,0 +1,285 @@
+#if NET_4_0
+//
+// ParallelQuickSort.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Linq;
+using System.Collections;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Collections.Generic;
+
+namespace System.Linq
+{
+       // HACK: ATM: parallelization of the sort is disabled as task
+       // add more overhead than gain
+       internal class ParallelQuickSort<T>
+       {
+               readonly Comparison<T> comparison;
+               readonly IList<T> list;
+               readonly int[] indexes;
+
+               class SortedCollection : IList<T>
+               {
+                       int[] indexes;
+                       IList<T> source;
+
+                       public SortedCollection (IList<T> source, int[] indexes)
+                       {
+                               this.indexes = indexes;
+                               this.source = source;
+                       }
+
+                       public int IndexOf (T item)
+                       {
+                               throw new NotImplementedException();
+                       }
+
+                       public void Insert (int index, T item)
+                       {
+                               throw new NotImplementedException();
+                       }
+
+                       public void RemoveAt (int index)
+                       {
+                               throw new NotImplementedException();
+                       }
+
+                       public T this[int index] {
+                               get {
+                                       return source[indexes[index]];
+                               }
+                               set {
+                                       throw new NotImplementedException();
+                               }
+                       }
+
+                       public void Add (T item)
+                       {
+                               throw new NotImplementedException();
+                       }
+
+                       public void Clear ()
+                       {
+                               throw new NotImplementedException();
+                       }
+
+                       public bool Contains (T item)
+                       {
+                               throw new NotImplementedException();
+                       }
+
+                       public void CopyTo (T[] array, int arrayIndex)
+                       {
+                               throw new NotImplementedException();
+                       }
+
+                       public bool Remove (T item)
+                       {
+                               throw new NotImplementedException();
+                       }
+
+                       public int Count {
+                               get {
+                                       return source.Count;
+                               }
+                       }
+
+                       public bool IsReadOnly {
+                               get {
+                                       return true;
+                               }
+                       }
+
+                       IEnumerator<T> IEnumerable<T>.GetEnumerator ()
+                       {
+                               return null;
+                       }
+
+                       IEnumerator IEnumerable.GetEnumerator ()
+                       {
+                               return null;
+                       }
+               }
+
+               private ParallelQuickSort (IList<T> list, Comparison<T> comparison)
+               {
+                       this.comparison = comparison;
+                       this.list = list;
+                       this.indexes = CreateIndexes (list.Count);
+               }
+
+               static int[] CreateIndexes (int length)
+               {
+                       var indexes = new int[length];
+                       for (int i = 0; i < length; i++)
+                               indexes [i] = i;
+
+                       return indexes;
+               }
+
+               SortedCollection DoSort ()
+               {
+                       if (list.Count > 1) {
+                               if (list.Count < 5)
+                                       InsertionSort (0, list.Count - 1);
+                               else
+                                       Sort (0, list.Count - 1);
+                       }
+
+                       return new SortedCollection (list, indexes);
+               }
+
+               int Comparison (int index1, int index2)
+               {
+                       return comparison (list[index1], list[index2]);
+               }
+
+               void Sort (int left, int right)
+               {
+                       if (left + 3 <= right) {
+                               int l = left, r = right - 1, pivot = MedianOfThree (left, right);
+                               while (true) {
+                                       while (Comparison (indexes [++l], pivot) < 0) { }
+                                       while (Comparison (indexes [--r], pivot) > 0) { }
+                                       if (l < r)
+                                               Swap (l, r);
+                                       else
+                                               break;
+                               }
+
+                               // Restore pivot
+                               Swap (l, right - 1);
+                               // Partition and sort
+                               Sort (left, l - 1);
+                               Sort (l + 1, right);
+                       } else
+                               // If there are three items in the subarray, insertion sort is better
+                               InsertionSort (left, right);
+               }
+
+               /*void Sort (int left, int right, int depth)
+               {
+                       int l = left, r = right - 1, pivot = MedianOfThree (left, right);
+                       while (true) {
+                               while (Comparison (indexes[++l], pivot) < 0);
+                               while (Comparison (indexes[--r], pivot) > 0);
+                               if (l < r)
+                                       Swap (l, r);
+                               else
+                                       break;
+                       }
+
+                       // Restore pivot
+                       Swap (l, right - 1);
+
+                       // Partition and sort in parallel if appropriate
+                       /*if (depth < maxDepth) {
+                               depth <<= 1;
+                               Task t = Task.Factory.StartNew (() => Sort (left, l - 1, depth));
+                               Sort (l + 1, right, depth);
+
+                               t.Wait ();
+                       } else {*/
+                               // Sequential
+               /*              Sort (left, l - 1);
+                               Sort (l + 1, right);
+                       //}
+               }*/
+
+               /*void ShellSort (int left, int right)
+               {
+                       int[] gaps = new int[] { 4, 1};
+
+                       for (int ic = 0; ic < gaps.Length; ic++) {
+                               int inc = gaps[ic];
+                               int l = left + inc;
+                               for (int i = l; i <= right; i++) {
+                                       T temp = list[i];
+                                       int j = i;
+                                       for (; j >= l && comparison (list[j - inc], temp) > 1; j -= inc)
+                                               list[j] = list[j - inc];
+                                       list[j] = temp;
+                               }
+                       }
+               }*/
+
+               void InsertionSort (int left, int right)
+               {
+                       for (int i = left + 1; i <= right; i++) {
+                               int j, tmp = indexes [i];
+
+                               for (j = i; j > left && Comparison (tmp, indexes [j - 1]) < 0; j--)
+                                       indexes [j] = indexes [j - 1];
+
+                               indexes [j] = tmp;
+                       }
+               }
+
+               /*
+               void InsertionSort (int left, int right)
+               {
+                       for (int i = left + 1; i <= right; i++) {
+                               int j;
+                               T tmp = list[i];
+
+                               for (j = i; j > left && comparison (tmp, list [j - 1]) < 0; j--)
+                                       list [j] = list [j - 1];
+
+                               list [j] = tmp;
+                       }
+               }*/
+
+               void Swap (int left, int right)
+               {
+                       int temp = indexes [right];
+                       indexes [right] = indexes [left];
+                       indexes [left] = temp;
+               }
+
+               int MedianOfThree (int left, int right)
+               {
+                       int center = (left + right) >> 1;
+                       if (Comparison (indexes[center], indexes[left]) < 0)
+                               Swap (left, center);
+                       if (Comparison (indexes[right], indexes[left]) < 0)
+                               Swap (left, right);
+                       if (Comparison (indexes[right], indexes[center]) < 0)
+                               Swap (center, right);
+                       Swap (center, right - 1);
+
+                       return indexes[right - 1];
+               }
+
+               public static IList<T> Sort (IList<T> list, Comparison<T> comparison)
+               {
+                       ParallelQuickSort<T> qs = new ParallelQuickSort<T> (list, comparison);
+
+                       return qs.DoSort ();
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/ChangeLog b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/ChangeLog
new file mode 100644 (file)
index 0000000..e9e87fa
--- /dev/null
@@ -0,0 +1,27 @@
+2010-04-15  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * QueryBaseNode.cs:
+       * QueryCastNode.cs:
+       * QueryChildNode.cs:
+       * QueryConcatNode.cs:
+       * QueryDefaultEmptyNode.cs:
+       * QueryGroupByNode.cs:
+       * QueryMuxNode.cs:
+       * QueryOptionNode.cs:
+       * QueryOrderByNode.cs:
+       * QueryOrderGuardNode.cs:
+       * QueryOrderedStreamNode.cs:
+       * QueryReverseNode.cs:
+       * QuerySelectManyNode.cs:
+       * QuerySelectNode.cs:
+       * QuerySetNode.cs:
+       * QueryStartNode.cs:
+       * QueryStreamNode.cs:
+       * QueryWhereNode.cs:
+       * QueryZipNode.cs:
+       * WrapHelper.cs: Initial check-in of PLinq
+
+2010-04-15  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * SetInclusion.cs: Initial check-in of PLinq (enum)
+
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryBaseNode.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryBaseNode.cs
new file mode 100644 (file)
index 0000000..14c1455
--- /dev/null
@@ -0,0 +1,49 @@
+#if NET_4_0
+//
+// QueryBaseNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Collections.Generic;
+
+namespace System.Linq
+{
+       internal abstract class QueryBaseNode<T> : IVisitableNode
+       {
+               public virtual void Visit (INodeVisitor visitor)
+               {
+                       visitor.Visit<T> (this);
+               }
+
+               internal abstract IList<IEnumerable<T>> GetEnumerables (QueryOptions options);
+
+               internal abstract IList<IEnumerable<KeyValuePair<long, T>>> GetOrderedEnumerables (QueryOptions options);
+
+               internal abstract IEnumerable<T> GetSequential ();
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryCastNode.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryCastNode.cs
new file mode 100644 (file)
index 0000000..1bb6f29
--- /dev/null
@@ -0,0 +1,72 @@
+#if NET_4_0
+//
+// QueryCastNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Collections.Generic;
+
+namespace System.Linq
+{
+       internal class QueryCastNode<T> : QueryStreamNode<object, T>
+       {
+               public QueryCastNode (QueryBaseNode<T> source)
+                       : base (source, false)
+               {
+
+               }
+               
+               internal override IEnumerable<object> GetSequential ()
+               {
+                       return Parent.GetSequential ().Cast<object> ();
+               }
+               
+               internal override IList<IEnumerable<KeyValuePair<long, object>>> GetOrderedEnumerables (QueryOptions options)
+               {
+                       IList<IEnumerable<KeyValuePair<long, T>>> src = Parent.GetOrderedEnumerables (options);
+                       IEnumerable<KeyValuePair<long, object>>[] result = new IEnumerable<KeyValuePair<long, object>> [src.Count];
+                       
+                       for (int i = 0; i < src.Count; i++)
+                               result[i] = src[i].Select ((e) => new KeyValuePair<long, object> (e.Key, (object)e.Value));
+                       
+                       return result;
+               }
+               
+               internal override IList<IEnumerable<object>> GetEnumerables (QueryOptions options)
+               {
+                       IList<IEnumerable<T>> src = Parent.GetEnumerables (options);
+                       IEnumerable<object>[] result = new IEnumerable<object> [src.Count];
+                       
+                       for (int i = 0; i < src.Count; i++)
+                               result[i] = src[i].Cast<object> ();
+                       
+                       return result;
+               }
+       }
+}
+
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryChildNode.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryChildNode.cs
new file mode 100644 (file)
index 0000000..c58834a
--- /dev/null
@@ -0,0 +1,54 @@
+#if NET_4_0
+//
+// QueryChildNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace System.Linq
+{
+       internal abstract class QueryChildNode<T, TParent> : QueryBaseNode<T>
+       {
+               QueryBaseNode<TParent> parent;
+
+               internal QueryChildNode (QueryBaseNode<TParent> parent)
+               //      : base (isOrdered, true)
+               {
+                       this.parent = parent;
+               }
+
+               internal QueryBaseNode<TParent> Parent {
+                       get {
+                               return parent;
+                       }
+               }
+
+               public override void Visit (INodeVisitor visitor)
+               {
+                       visitor.Visit<T, TParent> (this);
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryConcatNode.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryConcatNode.cs
new file mode 100644 (file)
index 0000000..16a0e77
--- /dev/null
@@ -0,0 +1,86 @@
+#if NET_4_0
+//
+// QueryConcatNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace System.Linq
+{
+       internal class QueryConcatNode<TSource> : QueryMuxNode<TSource, TSource, TSource>
+       {
+               public QueryConcatNode (QueryBaseNode<TSource> first, QueryBaseNode<TSource> second)
+                       : this (first, second)
+               {
+               }
+
+               internal override IList<IEnumerable<TSource>> GetEnumerables (QueryOptions options)
+               {
+                       IList<IEnumerable<TSource>> first = Parent.GetEnumerables (options);
+                       IList<IEnumerable<TSource>> second = Second.GetEnumerables (options);
+
+                       IEnumerable<TSource>[] result = new IEnumerable<TSource>[first.Count];
+
+                       for (int i = 0; i < result.Length; i++)
+                               result[i] = CombineEnumerables (first[i], second[i]);
+
+                       return result;
+               }
+
+               internal override IList<IEnumerable<KeyValuePair<long, TSource>>> GetOrderedEnumerables (QueryOptions options)
+               {
+                       IList<IEnumerable<KeyValuePair<long, TSource>>> first = Parent.GetOrderedEnumerables (options);
+                       IList<IEnumerable<KeyValuePair<long, TSource>>> second = Second.GetOrderedEnumerables (options);
+
+                       IEnumerable<KeyValuePair<long, TSource>>[] result = new IEnumerable<KeyValuePair<long, TSource>>[first.Count];
+
+                       for (int i = 0; i < result.Length; i++)
+                               result[i] = CombineEnumerables (first[i], second[i]);
+
+                       return result;
+               }
+
+               internal override IEnumerable<TSource> GetSequential ()
+               {
+                       IEnumerable<TSource> first = Parent.GetSequential ();
+                       IEnumerable<TSource> second = Second.GetSequential ();
+
+                       return first.Concat (second);
+               }
+
+               IEnumerable<TResult> CombineEnumerables<TResult> (IEnumerable<TResult> f, IEnumerable<TResult> s)
+               {
+                       foreach (var e in f)
+                               yield return e;
+                       foreach (var e in s)
+                               yield return e;
+               }
+       }
+}
+
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryDefaultEmptyNode.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryDefaultEmptyNode.cs
new file mode 100644 (file)
index 0000000..e5463d0
--- /dev/null
@@ -0,0 +1,93 @@
+#if NET_4_0
+//
+// QueryDefaultEmptyNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace System.Linq
+{
+       internal class QueryDefaultEmptyNode<TSource> : QueryStreamNode<TSource, TSource>
+       {
+               TSource defaultValue;
+               
+               internal QueryDefaultEmptyNode (QueryBaseNode<TSource> parent, TSource defaultValue)
+                       : base (parent, false)
+               {
+                       this.defaultValue = defaultValue;
+               }
+               
+               internal override IEnumerable<TSource> GetSequential ()
+               {
+                       return Parent.GetSequential ().DefaultIfEmpty (defaultValue);
+               }
+               
+               internal override IList<IEnumerable<TSource>> GetEnumerables (QueryOptions options)
+               {
+                       IList<IEnumerable<TSource>> enumerables = Parent.GetEnumerables (options);
+                       CountdownEvent evt = new CountdownEvent (enumerables.Count);
+                       IEnumerable<TSource>[] result = new IEnumerable<TSource>[enumerables.Count];
+                       
+                       for (int i = 0; i < enumerables.Count; i++)
+                               result[i] = GetEnumerableInternal<TSource> (enumerables[i], evt, 
+                                                                           (s) => s);
+                       
+                       return result;
+               }
+               
+               internal override IList<IEnumerable<KeyValuePair<long, TSource>>> GetOrderedEnumerables (QueryOptions options)
+               {
+                       IList<IEnumerable<KeyValuePair<long, TSource>>> enumerables = Parent.GetOrderedEnumerables (options);
+                       CountdownEvent evt = new CountdownEvent (enumerables.Count);
+                       IEnumerable<KeyValuePair<long, TSource>>[] result = new IEnumerable<KeyValuePair<long, TSource>>[enumerables.Count];
+                       
+                       for (int i = 0; i < enumerables.Count; i++)
+                               result[i] = GetEnumerableInternal<KeyValuePair<long, TSource>> (enumerables[i], evt, 
+                                                                                               (s) => new KeyValuePair<long, TSource> (0, s));
+                       
+                       return result;
+               }
+               
+               IEnumerable<TSecond> GetEnumerableInternal<TSecond> (IEnumerable<TSecond> source, 
+                                                                    CountdownEvent evt,
+                                                                    Func<TSource, TSecond> converter)
+               {
+                       bool processed = false;
+                       
+                       foreach (TSecond second in source) {
+                               processed = true;
+                               yield return second;
+                       }
+                       
+                       if (!processed && evt.Signal ())
+                               yield return converter (defaultValue);
+               }
+       }
+}
+
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryGroupByNode.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryGroupByNode.cs
new file mode 100644 (file)
index 0000000..4ccaac9
--- /dev/null
@@ -0,0 +1,76 @@
+#if NET_4_0
+//
+// QueryOrderByNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.Concurrent;
+
+namespace System.Linq
+{
+       internal class QueryGroupByNode<TSource, TKey, TElement> : QueryStreamNode<IGrouping<TKey, TElement>, TSource>
+       {
+               Func<TSource, TKey> keySelector;
+               Func<TSource, TElement> elementSelector;
+               IEqualityComparer<TKey> comparer;
+               
+               public QueryGroupByNode (QueryBaseNode<TSource> parent,
+                                        Func<TSource, TKey> keySelector, 
+                                        Func<TSource, TElement> elementSelector,
+                                        IEqualityComparer<TKey> comparer)
+                       : base (parent, false)
+               {
+                       this.keySelector = keySelector;
+                       this.elementSelector = elementSelector;
+                       this.comparer = comparer;
+               }
+               
+               internal override IEnumerable<IGrouping<TKey, TElement>> GetSequential ()
+               {
+                       IEnumerable<TSource> src =  Parent.GetSequential ();
+                       
+                       return src.GroupBy (keySelector, elementSelector, comparer);
+               }
+               
+               internal override IList<IEnumerable<KeyValuePair<long, IGrouping<TKey, TElement>>>> GetOrderedEnumerables (QueryOptions options)
+               {
+                       //ConcurrentLookup<TKey, TElement> lookup = new ConcurrentLookup<TKey, TElement> ();
+                       
+                       //ParallelExecuter.ProcessAndBlock (Parent, (e) => lookup.Add (keySelector (e), elementSelector (e)));
+                       
+                       throw new System.NotImplementedException();
+               }
+               
+               internal override IList<IEnumerable<IGrouping<TKey, TElement>>> GetEnumerables (QueryOptions options)
+               {
+                       throw new System.NotImplementedException();
+               }
+       }
+}
+
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryMuxNode.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryMuxNode.cs
new file mode 100644 (file)
index 0000000..49fbab6
--- /dev/null
@@ -0,0 +1,58 @@
+#if NET_4_0
+//
+// QueryMuxNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Linq;
+using System.Collections.Generic;
+using System.Collections.Concurrent;
+
+namespace System.Linq
+{
+       internal abstract class QueryMuxNode<TFirst, TSecond, TResult> : QueryChildNode<TResult, TFirst>
+       {
+               QueryBaseNode<TSecond> second;
+
+               internal QueryMuxNode (QueryBaseNode<TFirst> parent, QueryBaseNode<TSecond> second)
+                       : base (parent)
+               {
+                       this.second = second;
+               }
+
+               internal QueryBaseNode<TSecond> Second {
+                       get {
+                               return second;
+                       }
+               }
+
+               public override void Visit (INodeVisitor visitor)
+               {
+                       visitor.Visit (this);
+               }
+       }
+}
+
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryOptionNode.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryOptionNode.cs
new file mode 100644 (file)
index 0000000..ac096c1
--- /dev/null
@@ -0,0 +1,155 @@
+#if NET_4_0
+//
+// QueryOptionNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+using System.Collections.Generic;
+
+namespace System.Linq
+{
+       // The first four elements correspond to the public operator With*
+       // Last CancellationToken parameter is used internally for ImplementerToken
+       using OptionsList = Tuple<ParallelMergeOptions?, ParallelExecutionMode?, CancellationToken?, int, CancellationTokenSource>;
+
+       internal class QueryOptionNode<T> : QueryChildNode<T, T>
+       {
+
+               public QueryOptionNode (QueryBaseNode<T> parent)
+                       : base (parent)
+               {
+
+               }
+
+               internal virtual OptionsList GetOptions ()
+               {
+                       return new OptionsList (null, null, null, -1, null);
+               }
+
+               internal override IList<IEnumerable<T>> GetEnumerables (QueryOptions options)
+               {
+                       return Parent.GetEnumerables (options);
+               }
+
+               internal override IList<IEnumerable<KeyValuePair<long, T>>> GetOrderedEnumerables (QueryOptions options)
+               {
+                       return Parent.GetOrderedEnumerables (options);
+               }
+
+               internal override IEnumerable<T> GetSequential ()
+               {
+                       return Parent.GetSequential ();
+               }
+
+               public override void Visit (INodeVisitor visitor)
+               {
+                       visitor.Visit<T> (this);
+               }
+       }
+
+       internal class ParallelExecutionModeNode<T> : QueryOptionNode<T>
+       {
+               ParallelExecutionMode mode;
+
+               internal ParallelExecutionModeNode (ParallelExecutionMode mode, QueryBaseNode<T> parent)
+                       : base (parent)
+               {
+                       this.mode = mode;
+               }
+
+               internal override OptionsList GetOptions ()
+               {
+                       return new OptionsList (null, mode, null, -1, null);
+               }
+       }
+
+
+       internal class ParallelMergeOptionsNode<T> : QueryOptionNode<T>
+       {
+               ParallelMergeOptions opts;
+
+               internal ParallelMergeOptionsNode (ParallelMergeOptions opts, QueryBaseNode<T> parent)
+                       : base (parent)
+               {
+                       this.opts = opts;
+               }
+
+               internal override OptionsList GetOptions ()
+               {
+                       return new OptionsList (opts, null, null, -1, null);
+               }
+       }
+
+
+       internal class CancellationTokenNode<T> : QueryOptionNode<T>
+       {
+               CancellationToken token;
+
+               internal CancellationTokenNode (CancellationToken token, QueryBaseNode<T> parent)
+                       : base (parent)
+               {
+                       this.token = token;
+               }
+
+               internal override OptionsList GetOptions ()
+               {
+                       return new OptionsList (null, null, token, -1, null);
+               }
+       }
+
+       internal class DegreeOfParallelismNode<T> : QueryOptionNode<T>
+       {
+               int degreeParallelism;
+
+               internal DegreeOfParallelismNode (int degreeParallelism, QueryBaseNode<T> parent)
+                       : base (parent)
+               {
+                       this.degreeParallelism = degreeParallelism;
+               }
+
+               internal override OptionsList GetOptions ()
+               {
+                       return new OptionsList (null, null, null, degreeParallelism, null);
+               }
+       }
+
+       internal class ImplementerTokenNode<T> : QueryOptionNode<T>
+       {
+               CancellationTokenSource source;
+
+               internal ImplementerTokenNode (CancellationTokenSource token, QueryBaseNode<T> parent)
+                       : base (parent)
+               {
+                       this.source = token;
+               }
+
+               internal override OptionsList GetOptions ()
+               {
+                       return new OptionsList (null, null, null, -1, source);
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryOrderByNode.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryOrderByNode.cs
new file mode 100644 (file)
index 0000000..6261003
--- /dev/null
@@ -0,0 +1,122 @@
+#if NET_4_0
+//
+// QueryOrderByNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.Concurrent;
+
+namespace System.Linq
+{
+       internal class QueryOrderByNode<T> : QueryOrderGuardNode<T>
+       {
+               Comparison<T> comparison;
+
+               public QueryOrderByNode (QueryBaseNode<T> parent, Comparison<T> comparison)
+                       : base (parent, true)
+               {
+                       this.comparison = comparison;
+               }
+
+
+               public QueryOrderByNode (QueryOrderByNode<T> parent, Comparison<T> comparison)
+                       : base (parent.Parent, true)
+               {
+                       this.comparison = MergeComparison (parent.ComparisonFunc, comparison);
+               }
+
+               public Comparison<T> ComparisonFunc {
+                       get {
+                               return comparison;
+                       }
+               }
+
+               internal override IEnumerable<T> GetSequential ()
+               {
+                       return Parent.GetSequential ().OrderBy ((e) => e, new ComparisonComparer (comparison));
+               }
+
+               private class ComparisonComparer : IComparer<T>
+               {
+                       Comparison<T> comparison;
+
+                       internal ComparisonComparer (Comparison<T> comparison)
+                       {
+                               this.comparison = comparison;
+                       }
+
+                       int IComparer<T>.Compare (T x, T y)
+                       {
+                               return comparison (x, y);
+                       }
+               }
+
+               internal override IList<IEnumerable<T>> GetEnumerables (QueryOptions options)
+               {
+                       throw new InvalidOperationException ("Shouldn't be called");
+               }
+
+               internal override IList<IEnumerable<KeyValuePair<long, T>>> GetOrderedEnumerables (QueryOptions options)
+               {
+                       int partitionCount;
+                       IList<T> aggregList = GetAggregatedList (out partitionCount);
+                       IList<T> result = ParallelQuickSort<T>.Sort (aggregList, comparison);
+
+                       OrderablePartitioner<T> partitioner = ParallelPartitioner.CreateForStrips (result, 1);
+
+                       return WrapHelper.Wrap (partitioner.GetOrderablePartitions (options.PartitionCount));
+               }
+
+               IList<T> GetAggregatedList (out int partitionCount)
+               {
+                       AggregationList<T> result = null;
+                       partitionCount = -1;
+
+                       ParallelExecuter.ProcessAndAggregate<T, IList<T>> (Parent, () => new List<T> (),
+                                                                          LocalCall,
+                                                                          (ls) => { result = new AggregationList<T> (ls); });
+
+                       return result;
+               }
+
+               IList<T> LocalCall (IList<T> list, T element)
+               {
+                       list.Add (element);
+                       return list;
+               }
+
+               static Comparison<T> MergeComparison (Comparison<T> source, Comparison<T> other)
+               {
+                       return (e1, e2) => {
+                               int result = source (e1, e2);
+                               return result == 0 ? other (e1, e2) : result;
+                       };
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryOrderGuardNode.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryOrderGuardNode.cs
new file mode 100644 (file)
index 0000000..8224460
--- /dev/null
@@ -0,0 +1,99 @@
+#if NET_4_0
+// QueryOrderGuardNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+
+namespace System.Linq
+{
+       internal abstract class QueryOrderGuardNode<T> : QueryStreamNode<T, T>
+       {
+               bool ensureOrder;
+
+               internal QueryOrderGuardNode (QueryBaseNode<T> parent, bool ensureOrder)
+                       : base (parent, ensureOrder)
+               {
+                       this.ensureOrder = ensureOrder;
+               }
+
+               public bool EnsureOrder {
+                       get {
+                               return ensureOrder;
+                       }
+               }
+
+               internal override IEnumerable<T> GetSequential ()
+               {
+                       return Parent.GetSequential ();
+               }
+
+               public override void Visit (INodeVisitor visitor)
+               {
+                       visitor.Visit<T> (this);
+               }
+       }
+
+       internal class QueryAsUnorderedNode<T> : QueryOrderGuardNode<T>
+       {
+               internal QueryAsUnorderedNode (QueryBaseNode<T> parent)
+                       : base (parent, false)
+               {
+
+               }
+
+               internal override IList<IEnumerable<T>> GetEnumerables (QueryOptions options)
+               {
+                       return Parent.GetEnumerables (options);
+               }
+
+               internal override IList<IEnumerable<KeyValuePair<long, T>>> GetOrderedEnumerables (QueryOptions options)
+               {
+                       return Parent.GetOrderedEnumerables (options);
+               }
+
+       }
+
+       internal class QueryAsOrderedNode<T> : QueryOrderGuardNode<T>
+       {
+               internal QueryAsOrderedNode (QueryBaseNode<T> parent)
+                       : base (parent, true)
+               {
+
+               }
+
+               internal override IList<IEnumerable<T>> GetEnumerables (QueryOptions options)
+               {
+                       return Parent.GetEnumerables (options);
+               }
+
+               internal override IList<IEnumerable<KeyValuePair<long, T>>> GetOrderedEnumerables (QueryOptions options)
+               {
+                       return Parent.GetOrderedEnumerables (options);
+               }
+
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryOrderedStreamNode.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryOrderedStreamNode.cs
new file mode 100644 (file)
index 0000000..50203fb
--- /dev/null
@@ -0,0 +1,40 @@
+#if NET_4_0
+//
+// QueryOrderedStreamNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace System.Linq
+{
+       internal abstract class QueryOrderedStreamNode<T, TParent> : QueryStreamNode<T, TParent>
+       {
+               internal QueryOrderedStreamNode (QueryBaseNode<TParent> parent, bool isIndexed)
+                       : base (parent, isIndexed)
+               {
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryReverseNode.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryReverseNode.cs
new file mode 100644 (file)
index 0000000..c8b87cd
--- /dev/null
@@ -0,0 +1,67 @@
+#if NET_4_0
+//
+// QueryReverseNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Linq;
+using System.Threading;
+using System.Collections.Generic;
+using System.Collections.Concurrent;
+
+namespace System.Linq
+{
+       internal class QueryReverseNode<TSource> : QueryStreamNode<TSource, TSource>
+       {
+               ParallelQuery<TSource> source;
+
+               public QueryReverseNode (ParallelQuery<TSource> source)
+                       : base (source.Node, true)
+               {
+                       this.source = source;
+               }
+
+               internal override IEnumerable<TSource> GetSequential ()
+               {
+                       return Parent.GetSequential ().Reverse ();
+               }
+
+               // As stated in the doc, in this case we do nothing
+               internal override IList<IEnumerable<TSource>> GetEnumerables (QueryOptions options)
+               {
+                       return Parent.GetEnumerables (options);
+               }
+
+               internal override IList<IEnumerable<KeyValuePair<long, TSource>>> GetOrderedEnumerables (QueryOptions options)
+               {
+                       ReverseList<TSource> reversed = new ReverseList<TSource> (source.ToArray ());
+                       OrderablePartitioner<TSource> partitioner = ParallelPartitioner.CreateForStrips (reversed, 1);
+
+                       return WrapHelper.Wrap (partitioner.GetOrderablePartitions (options.PartitionCount));
+               }
+       }
+}
+
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QuerySelectManyNode.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QuerySelectManyNode.cs
new file mode 100644 (file)
index 0000000..6c189ad
--- /dev/null
@@ -0,0 +1,122 @@
+#if NET_4_0
+//
+// QueryConcatNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace System.Linq
+{
+       internal class QuerySelectManyNode<TSource, TCollection, TResult> : QueryStreamNode<TResult, TSource>
+       {
+               Func<TSource, IEnumerable<TCollection>> collectionSelector;
+               Func<TSource, int, IEnumerable<TCollection>> collectionSelectorIndexed;
+               Func<TSource, TCollection, TResult> resultSelector;
+               
+               internal QuerySelectManyNode (QueryBaseNode<TSource> parent,
+                                             Func<TSource, int, IEnumerable<TCollection>> collectionSelectorIndexed,
+                                             Func<TSource, TCollection, TResult> resultSelector)
+                       : base (parent, true)
+               {
+                       this.collectionSelectorIndexed = collectionSelectorIndexed;
+                       this.resultSelector = resultSelector;
+               }
+               
+               internal QuerySelectManyNode (QueryBaseNode<TSource> parent,
+                                             Func<TSource, IEnumerable<TCollection>> collectionSelector,
+                                             Func<TSource, TCollection, TResult> resultSelector)
+                       : base (parent, false)
+               {
+                       this.collectionSelector = collectionSelector;
+                       this.resultSelector = resultSelector;
+               }
+               
+               internal override IEnumerable<TResult> GetSequential ()
+               {
+                       IEnumerable<TSource> source = Parent.GetSequential ();
+                       
+                       if (IsIndexed)
+                               return source.SelectMany (collectionSelectorIndexed, resultSelector);
+                       else
+                               return source.SelectMany (collectionSelector, resultSelector);
+               }
+               
+               internal override IList<IEnumerable<TResult>> GetEnumerables (QueryOptions options)
+               {
+                       IEnumerable<TResult>[] result = null;
+                       
+                       if (IsIndexed) {
+                               IList<IEnumerable<KeyValuePair<long, TSource>>> enumerables = Parent.GetOrderedEnumerables (options);
+                               result = new IEnumerable<TResult>[enumerables.Count];
+                               
+                               for (int i = 0; i < enumerables.Count; i++)
+                                       result[i] = GetEnumerableInternal<KeyValuePair<long, TSource>> (enumerables[i],
+                                                                                                       (kv) => collectionSelectorIndexed (kv.Value, (int)kv.Key),
+                                                                                                       (e, c) => resultSelector (e.Value, c));
+                       } else {
+                               IList<IEnumerable<TSource>> enumerables = Parent.GetEnumerables (options);
+                               result = new IEnumerable<TResult>[enumerables.Count];
+                               
+                               for (int i = 0; i < enumerables.Count; i++)
+                                       result[i] = GetEnumerableInternal<TSource> (enumerables[i],
+                                                                                   collectionSelector,
+                                                                                   (e, c) => resultSelector (e, c));
+                       }
+                       
+                       return result;
+               }
+               
+               // This one is gonna be tricky
+               internal override IList<IEnumerable<KeyValuePair<long, TResult>>> GetOrderedEnumerables (QueryOptions options)
+               {
+                       throw new NotImplementedException ();
+               }
+               
+               IEnumerable<TResult> GetEnumerableInternal<T> (IEnumerable<T> source,
+                                                              Func<T, IEnumerable<TCollection>> collectionner,
+                                                              Func<T, TCollection, TResult> packer)
+               {
+                       foreach (T element in source)
+                               foreach (TCollection item in collectionner (element))
+                                       yield return packer (element, item);
+               }
+               
+               IEnumerable<KeyValuePair<long, TResult>> GetOrderedEnumerableInternal (IEnumerable<KeyValuePair<long, TSource>> source,
+                                                                                      Barrier barrier)
+               {
+                       foreach (KeyValuePair<long, TSource> element in source) {
+                               IEnumerable<TCollection> collection = collectionSelectorIndexed (element.Value, (int)element.Key);
+                               
+                               foreach (TCollection item in collection)
+                                       yield return new KeyValuePair<long, TResult> (-1, resultSelector (element.Value, item));
+                       }
+               }
+       }
+}
+
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QuerySelectNode.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QuerySelectNode.cs
new file mode 100644 (file)
index 0000000..defbcbe
--- /dev/null
@@ -0,0 +1,97 @@
+#if NET_4_0
+//
+// QuerySelectNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Linq;
+using System.Collections.Generic;
+using System.Collections.Concurrent;
+
+namespace System.Linq
+{
+       internal class QuerySelectNode<TResult, TSource> : QueryStreamNode<TResult, TSource>
+       {
+               Func<TSource, int, TResult> indexedSelector;
+               Func<TSource, TResult> selector;
+
+               internal QuerySelectNode (QueryBaseNode<TSource> parent, Func<TSource, TResult> selector)
+                       : base (parent, false)
+               {
+                       this.selector = selector;
+               }
+
+               internal QuerySelectNode (QueryBaseNode<TSource> parent, Func<TSource, int, TResult> selector)
+                       : base (parent, true)
+               {
+                       this.indexedSelector = selector;
+               }
+
+               internal override IEnumerable<TResult> GetSequential ()
+               {
+                       if (IsIndexed)
+                               return Parent.GetSequential ().Select (indexedSelector);
+                       else
+                               return Parent.GetSequential ().Select (selector);
+               }
+
+               internal override IList<IEnumerable<TResult>> GetEnumerables (QueryOptions options)
+               {
+                       if (IsIndexed) {
+                               IList<IEnumerable<KeyValuePair<long, TSource>>> sources = Parent.GetOrderedEnumerables (options);
+                               IEnumerable<TResult>[] results = new IEnumerable<TResult>[sources.Count];
+                               for (int i = 0; i < results.Length; i++)
+                                       results[i] = sources[i].Select ((e) => indexedSelector (e.Value, (int)e.Key));
+                               return results;
+                       } else {
+                               IList<IEnumerable<TSource>> sources = Parent.GetEnumerables (options);
+                               IEnumerable<TResult>[] results = new IEnumerable<TResult>[sources.Count];
+
+                               for (int i = 0; i < results.Length; i++)
+                                       results[i] = sources[i].Select (selector);
+                               return results;
+                       }
+               }
+
+               internal override IList<IEnumerable<KeyValuePair<long, TResult>>> GetOrderedEnumerables (QueryOptions options)
+               {
+                       IList<IEnumerable<KeyValuePair<long, TSource>>> sources = Parent.GetOrderedEnumerables (options);
+                       IEnumerable<KeyValuePair<long, TResult>>[] results = new IEnumerable<KeyValuePair<long, TResult>>[sources.Count];
+
+                       if (IsIndexed) {
+                               for (int i = 0; i < results.Length; i++)
+                                       results[i] = sources[i].
+                                               Select ((e) => new KeyValuePair<long, TResult> (e.Key, indexedSelector (e.Value, (int)e.Key)));
+                       } else {
+                               for (int i = 0; i < results.Length; i++)
+                                       results[i] = sources[i].
+                                               Select ((e) => new KeyValuePair<long, TResult> (e.Key, selector (e.Value)));
+                       }
+
+                       return results;
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QuerySetNode.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QuerySetNode.cs
new file mode 100644 (file)
index 0000000..4ea309a
--- /dev/null
@@ -0,0 +1,145 @@
+#if NET_4_0
+//
+// QueryMuxNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Linq;
+using System.Collections.Generic;
+using System.Collections.Concurrent;
+
+namespace System.Linq
+{
+       internal class QuerySetNode<TSource> : QueryMuxNode<TSource, TSource, TSource>
+       {
+               readonly SetInclusion setInclusion;
+               readonly IEqualityComparer<TSource> comparer;
+
+               internal QuerySetNode (SetInclusion setInclusion, IEqualityComparer<TSource> comparer,
+                                      QueryBaseNode<TSource> first, QueryBaseNode<TSource> second)
+                       : base (first, second)
+               {
+                       this.setInclusion = setInclusion;
+                       this.comparer = comparer;
+               }
+
+               internal override IEnumerable<TSource> GetSequential ()
+               {
+                       IEnumerable<TSource> first = Parent.GetSequential ();
+                       IEnumerable<TSource> second = Second == null ? null : Second.GetSequential ();
+
+                       // We try to do some guessing based on the default
+                       switch (setInclusion) {
+                       case SetInclusionDefaults.Union:
+                               return first.Union (second, comparer);
+                       case SetInclusionDefaults.Intersect:
+                               return first.Intersect (second, comparer);
+                       case SetInclusionDefaults.Except:
+                               return first.Except (second, comparer);
+                       case SetInclusionDefaults.Distinct:
+                               return first.Distinct (comparer);
+                       }
+
+                       // Default is we return the bare source enumerable
+                       return first;
+               }
+
+               internal override IList<IEnumerable<TSource>> GetEnumerables (QueryOptions options)
+               {
+                       IList<IEnumerable<TSource>> first = Parent.GetEnumerables (options);
+                       IList<IEnumerable<TSource>> second = Second.GetEnumerables (options);
+                       
+                       IEnumerable<TSource>[] result = new IEnumerable<TSource>[first.Count];
+                       ConcurrentSkipList<TSource> checker = new ConcurrentSkipList<TSource> (comparer);
+                       
+                       InitConcurrentSkipList (checker, second, (e) => e);
+
+                       for (int i = 0; i < result.Length; i++)
+                               result[i] = GetEnumerable<TSource> (first[i], second[i], checker, (e) => e);
+
+                       return result;
+               }
+
+               internal override IList<IEnumerable<KeyValuePair<long, TSource>>> GetOrderedEnumerables (QueryOptions options)
+               {
+                       IList<IEnumerable<KeyValuePair<long, TSource>>> first = Parent.GetOrderedEnumerables (options);
+                       IList<IEnumerable<KeyValuePair<long, TSource>>> second = Second.GetOrderedEnumerables (options);
+
+                       IEnumerable<KeyValuePair<long, TSource>>[] result = new IEnumerable<KeyValuePair<long, TSource>>[first.Count];
+                       ConcurrentSkipList<TSource> checker = new ConcurrentSkipList<TSource> (comparer);
+                       
+                       InitConcurrentSkipList (checker, second, (e) => e.Value);
+
+                       for (int i = 0; i < result.Length; i++)
+                               result[i] = GetEnumerable<KeyValuePair<long, TSource>> (first[i], second[i], checker, (e) => e.Value);
+
+                       return result;
+               }
+                               
+               void InitConcurrentSkipList<TExtract> (ConcurrentSkipList<TSource> checker,
+                                                      IList<IEnumerable<TExtract>> feeds,
+                                                      Func<TExtract, TSource> extractor)
+               {
+                       if ((setInclusion & SetInclusion.Preload) == 0)
+                               return;
+                       
+                       foreach (IEnumerable<TExtract> feed in feeds)
+                               foreach (TExtract item in feed)
+                                       checker.TryAdd (extractor (item));
+               }
+
+               IEnumerable<TExtract> GetEnumerable<TExtract> (IEnumerable<TExtract> first,
+                                                              IEnumerable<TExtract> second,
+                                                              ConcurrentSkipList<TSource> checker,
+                                                              Func<TExtract, TSource> extractor)
+               {
+                       IEnumerator<TExtract> eFirst = first.GetEnumerator ();
+                       IEnumerator<TExtract> eSecond = second == null ? null : second.GetEnumerator ();
+
+                       IEnumerator<TExtract> current = eFirst;
+                       bool outInclusion = (setInclusion & SetInclusion.Out) > 0;
+                       bool preload = (setInclusion & SetInclusion.Preload) > 0;
+                       bool relaxed = (setInclusion & SetInclusion.Relaxed) > 0;
+
+                       while (current != null) {
+                               while (current.MoveNext ()) {
+                                       bool result = relaxed ?
+                                               checker.Contains (extractor (current.Current)) : checker.TryAdd (extractor (current.Current));
+
+                                       if ((result && outInclusion)
+                                           || (!result && !outInclusion))
+                                               yield return current.Current;
+                               }
+
+                               if (current == eFirst && !preload)
+                                       current = eSecond;
+                               else
+                                       break;
+                       }
+               }
+       }
+}
+
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryStartNode.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryStartNode.cs
new file mode 100644 (file)
index 0000000..58ac27e
--- /dev/null
@@ -0,0 +1,110 @@
+#if NET_4_0
+//
+// QueryStartNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.Concurrent;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace System.Linq
+{
+       internal class QueryStartNode<T> : QueryBaseNode<T>
+       {
+               readonly IEnumerable<T> source;
+               readonly Partitioner<T> customPartitioner;
+
+               internal QueryStartNode (IEnumerable<T> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       this.source = source;
+               }
+
+               internal QueryStartNode (Partitioner<T> custom)
+               {
+                       if (custom == null)
+                               throw new ArgumentNullException ("custom");
+
+                       this.customPartitioner = custom;
+               }
+
+               public override void Visit (INodeVisitor visitor)
+               {
+                       visitor.Visit<T> (this);
+               }
+
+               internal override IEnumerable<T> GetSequential ()
+               {
+                       if (source != null)
+                               return source;
+
+                       return WrapHelper.Wrap (customPartitioner.GetPartitions (1))[0];
+               }
+
+               internal override IList<IEnumerable<T>> GetEnumerables (QueryOptions options)
+               {
+                       if (customPartitioner != null) {
+                               return WrapHelper.Wrap (customPartitioner.GetPartitions (options.PartitionCount));
+                       }
+
+                       Partitioner<T> partitioner
+                               = (options.UseStrip) ? ParallelPartitioner.CreateForStrips (source, 1) : ParallelPartitioner.CreateBest (source);
+
+                       return WrapHelper.Wrap (partitioner.GetPartitions (options.PartitionCount));
+               }
+
+               internal override IList<IEnumerable<KeyValuePair<long, T>>> GetOrderedEnumerables (QueryOptions options)
+               {
+                       OrderablePartitioner<T> partitioner = null;
+                       if (customPartitioner != null) {
+                               partitioner = customPartitioner as OrderablePartitioner<T>;
+                               if (partitioner == null)
+                                       throw new InvalidOperationException ("The partitionner you are using doesn't support ordered partitionning");
+                       } else {
+                               partitioner =
+                                       (options.UseStrip) ? ParallelPartitioner.CreateForStrips (source, 1) : ParallelPartitioner.CreateBest (source);
+                       }
+
+                       options.PartitionerSettings = Tuple.Create (partitioner.KeysOrderedAcrossPartitions,
+                                                                   partitioner.KeysOrderedInEachPartition,
+                                                                   partitioner.KeysNormalized);
+
+                       // We only support one style of partitioning at the moment.
+                       // Standard partitioners follow this style.
+                       if (options.UseStrip && (!partitioner.KeysOrderedInEachPartition || partitioner.KeysOrderedAcrossPartitions))
+                               throw new NotImplementedException ("Partitioner must have KeysOrderedInEachPartition "
+                                                                  + "and !KeysOrderedAcrossPartitions"
+                                                                  + "to be used with indexed operators");
+
+                       return WrapHelper.Wrap (partitioner.GetOrderablePartitions (options.PartitionCount));
+               }
+       }
+}
+#endif
\ No newline at end of file
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryStreamNode.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryStreamNode.cs
new file mode 100644 (file)
index 0000000..572b2c5
--- /dev/null
@@ -0,0 +1,57 @@
+#if NET_4_0
+//
+// QueryStreamNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Collections.Generic;
+
+namespace System.Linq
+{
+       internal abstract class QueryStreamNode<T, TParent> : QueryChildNode<T, TParent>
+       {
+               bool isIndexed;
+
+               internal QueryStreamNode (QueryBaseNode<TParent> parent, bool isIndexed)
+                       : base (parent)
+               {
+                       this.isIndexed = isIndexed;
+               }
+
+               public override void Visit (INodeVisitor visitor)
+               {
+                       visitor.Visit<T, TParent> (this);
+               }
+
+               public bool IsIndexed {
+                       get {
+                               return isIndexed;
+                       }
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryWhereNode.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryWhereNode.cs
new file mode 100644 (file)
index 0000000..74f09d6
--- /dev/null
@@ -0,0 +1,157 @@
+#if NET_4_0
+//
+// QueryWhereNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Linq;
+using System.Threading;
+using System.Collections.Generic;
+
+namespace System.Linq
+{
+
+       internal class QueryWhereNode<TSource> : QueryStreamNode<TSource, TSource>
+       {
+               Func<TSource, int, bool> indexedPredicate;
+               Func<TSource, bool> predicate;
+
+               internal QueryWhereNode (QueryBaseNode<TSource> parent, Func<TSource, bool> predicate)
+                       : base (parent, false)
+               {
+                       this.predicate = predicate;
+               }
+
+               internal QueryWhereNode (QueryBaseNode<TSource> parent, Func<TSource, int, bool> predicate)
+                       : base (parent, true)
+               {
+                       this.indexedPredicate = predicate;
+               }
+
+               internal override IEnumerable<TSource> GetSequential ()
+               {
+                       IEnumerable<TSource> parent = Parent.GetSequential ();
+
+                       if (indexedPredicate != null)
+                               return parent.Where (indexedPredicate);
+                       else
+                               return parent.Where (predicate);
+               }
+
+               internal override IList<IEnumerable<TSource>> GetEnumerables (QueryOptions options)
+               {
+                       if (IsIndexed) {
+                               IList<IEnumerable<KeyValuePair<long, TSource>>> sources = Parent.GetOrderedEnumerables (options);
+                               IEnumerable<TSource>[] results = new IEnumerable<TSource>[sources.Count];
+
+                               for (int i = 0; i < results.Length; i++)
+                                       results[i] =
+                                               sources[i].Where ((e) => indexedPredicate (e.Value, (int)e.Key)).Select ((e) => e.Value);
+                               return results;
+                       } else {
+                               IList<IEnumerable<TSource>> sources = Parent.GetEnumerables (options);
+                               IEnumerable<TSource>[] results = new IEnumerable<TSource>[sources.Count];
+
+                               for (int i = 0; i < results.Length; i++)
+                                       results[i] = sources[i].Where (predicate);
+                               return results;
+                       }
+               }
+
+               internal override IList<IEnumerable<KeyValuePair<long, TSource>>> GetOrderedEnumerables (QueryOptions options)
+               {
+                       IList<IEnumerable<KeyValuePair<long, TSource>>> sources = Parent.GetOrderedEnumerables (options);
+                       IEnumerable<KeyValuePair<long, TSource>>[] results = new IEnumerable<KeyValuePair<long, TSource>>[sources.Count];
+
+                       Tuple<TSource, long, bool>[] store = new Tuple<TSource, long, bool>[results.Length];
+                       long lastIndex = 0;
+
+                       Barrier barrier = new Barrier (results.Length, delegate (Barrier b) {
+                               // Sort the store
+                               Array.Sort (store, ArraySortMethod);
+
+                               // Reassign a good index
+                               int i = 0;
+
+                               for (i = 0; i < store.Length && store[i].Item3; i++) {
+                                       Tuple<TSource, long, bool> old = store[i];
+                                       store[i] = Tuple.Create (old.Item1, lastIndex + i, old.Item3);
+                               }
+
+                               // Update lastIndex for next round
+                               lastIndex += i;
+                       });
+
+                       for (int j = 0; j < results.Length; j++)
+                               results[j] = GetEnumerator (sources[j], barrier, store, j);
+
+                       return results;
+               }
+
+               static int ArraySortMethod (Tuple<TSource, long, bool> lhs, Tuple<TSource, long, bool> rhs)
+               {
+                       if (lhs.Item3 && !rhs.Item3)
+                               return -1;
+                       if (!lhs.Item3 && rhs.Item3)
+                               return 1;
+                       if (!lhs.Item3 && !rhs.Item3)
+                               return 0;
+
+                       return (lhs.Item2 < rhs.Item2) ? -1 : 1;
+               }
+
+               IEnumerable<KeyValuePair<long, TSource>> GetEnumerator (IEnumerable<KeyValuePair<long, TSource>> source,
+                                                                       Barrier barrier,
+                                                                       Tuple<TSource, long, bool>[] store, int index)
+               {
+                       IEnumerator<KeyValuePair<long, TSource>> current = source.GetEnumerator ();
+                       bool result;
+
+                       while (current.MoveNext ()) {
+                               KeyValuePair<long, TSource> curr = current.Current;
+
+                               if (IsIndexed)
+                                       result = indexedPredicate (curr.Value, (int)curr.Key);
+                               else
+                                       result = predicate (curr.Value);
+
+                               store[index] = Tuple.Create (curr.Value, curr.Key, result);
+                               barrier.SignalAndWait ();
+
+                               Tuple<TSource, long, bool> value = store [index];
+
+                               if (value.Item3)
+                                       yield return new KeyValuePair<long, TSource> (value.Item2, value.Item1);
+
+                               // Reset
+                               store[index] = Tuple.Create (default (TSource), long.MaxValue, false);
+                       }
+
+                       // Remove our participation
+                       barrier.RemoveParticipant ();
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryZipNode.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/QueryZipNode.cs
new file mode 100644 (file)
index 0000000..8268db5
--- /dev/null
@@ -0,0 +1,135 @@
+#if NET_4_0
+//
+// QueryZipNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+using System.Linq;
+using System.Collections.Generic;
+using System.Collections.Concurrent;
+
+namespace System.Linq
+{
+       internal class QueryZipNode<TFirst, TSecond, TResult> : QueryMuxNode<TFirst, TSecond, TResult>
+       {
+               Func<TFirst, TSecond, TResult> resultSelector;
+
+               public QueryZipNode (Func<TFirst, TSecond, TResult> resultSelector, QueryBaseNode<TFirst> first, QueryBaseNode<TSecond> second)
+                       : base (first, second)
+               {
+                       this.resultSelector = resultSelector;
+               }
+
+               internal override IEnumerable<TResult> GetSequential ()
+               {
+                       IEnumerable<TFirst> first = Parent.GetSequential ();
+                       IEnumerable<TSecond> second = Second.GetSequential ();
+
+                       return first.Zip (second, resultSelector);
+               }
+
+               internal override IList<IEnumerable<TResult>> GetEnumerables (QueryOptions options)
+               {
+                       IList<IEnumerable<TFirst>> first = Parent.GetEnumerables (options);
+                       IList<IEnumerable<TSecond>> second = Second.GetEnumerables (options);
+
+                       if (first.Count != second.Count)
+                               throw new InvalidOperationException ("Internal size mismatch");
+
+                       IEnumerable<TResult>[] result = new IEnumerable<TResult>[first.Count];
+
+                       for (int i = 0; i < result.Length; i++)
+                               result[i] = GetEnumerable (first[i], second[i]);
+
+                       return result;
+               }
+
+               IEnumerable<TResult> GetEnumerable (IEnumerable<TFirst> first, IEnumerable<TSecond> second)
+               {
+                       IEnumerator<TFirst> eFirst = first.GetEnumerator ();
+                       IEnumerator<TSecond> eSecond = second.GetEnumerator ();
+
+                       while (eFirst.MoveNext ()) {
+                               if (!eSecond.MoveNext ())
+                                       yield break;
+
+                               yield return resultSelector (eFirst.Current, eSecond.Current);
+                       }
+               }
+
+               internal override IList<IEnumerable<KeyValuePair<long, TResult>>> GetOrderedEnumerables (QueryOptions options)
+               {
+                       IList<IEnumerable<KeyValuePair<long, TFirst>>> first = Parent.GetOrderedEnumerables (options);
+                       IList<IEnumerable<KeyValuePair<long, TSecond>>> second = Second.GetOrderedEnumerables (options);
+
+                       if (first.Count != second.Count)
+                               throw new InvalidOperationException ("Internal size mismatch");
+
+                       IEnumerable<KeyValuePair<long, TResult>>[] result = new IEnumerable<KeyValuePair<long, TResult>>[first.Count];
+
+                       KeyValuePair<long, TFirst>[] store1 = new KeyValuePair<long, TFirst>[result.Length];
+                       KeyValuePair<long, TSecond>[] store2 = new KeyValuePair<long, TSecond>[result.Length];
+
+                       Barrier barrier = new Barrier (result.Length, delegate {
+                               Array.Sort (store1, (e1, e2) => e1.Key.CompareTo (e2.Key));
+                               Array.Sort (store2, (e1, e2) => e1.Key.CompareTo (e2.Key));
+                       });
+
+                       for (int i = 0; i < result.Length; i++)
+                               result[i] = GetEnumerable (first[i], second[i], i, store1, store2, barrier);
+
+                       return result;
+               }
+
+               IEnumerable<KeyValuePair<long, TResult>> GetEnumerable (IEnumerable<KeyValuePair<long, TFirst>> first,
+                                                                       IEnumerable<KeyValuePair<long, TSecond>> second,
+                                                                       int index,
+                                                                       KeyValuePair<long, TFirst>[] store1,
+                                                                       KeyValuePair<long, TSecond>[] store2,
+                                                                       Barrier barrier)
+               {
+                       IEnumerator<KeyValuePair<long, TFirst>> eFirst = first.GetEnumerator ();
+                       IEnumerator<KeyValuePair<long, TSecond>> eSecond = second.GetEnumerator ();
+
+                       while (eFirst.MoveNext ()) {
+                               if (!eSecond.MoveNext ())
+                                       break;
+
+                               store1[index] = eFirst.Current;
+                               store2[index] = eSecond.Current;
+
+                               barrier.SignalAndWait ();
+
+                               yield return new KeyValuePair<long, TResult> (store1[index].Key,
+                                                                                resultSelector (store1[index].Value, store2[index].Value));
+                       }
+
+                       barrier.RemoveParticipant ();
+               }
+       }
+}
+
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/SetInclusion.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/SetInclusion.cs
new file mode 100644 (file)
index 0000000..a1ef21c
--- /dev/null
@@ -0,0 +1,52 @@
+#if NET_4_0
+//
+// SetInclusion.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Linq;
+using System.Collections.Generic;
+using System.Collections.Concurrent;
+
+namespace System.Linq
+{
+       [Flags]
+       internal enum SetInclusion {
+               In = 0, // Element should already be in checker
+               Out = 1, // Element shouldn't be already in checker
+               Preload = 2, // Preload second node content and only do real work on first node content
+               Relaxed = 4, // first node content isn't added to checker allowing duplicates
+       }
+
+       internal static class SetInclusionDefaults
+       {
+               public const SetInclusion Union = SetInclusion.Out;
+               public const SetInclusion Intersect = SetInclusion.In;
+               public const SetInclusion Except = SetInclusion.In | SetInclusion.Preload | SetInclusion.Relaxed;
+               public const SetInclusion Distinct = SetInclusion.Out | SetInclusion.Preload;
+       }
+}
+
+#endif
\ No newline at end of file
diff --git a/mcs/class/System.Core/System.Linq/Internal/QueryNodes/WrapHelper.cs b/mcs/class/System.Core/System.Linq/Internal/QueryNodes/WrapHelper.cs
new file mode 100644 (file)
index 0000000..a44d61a
--- /dev/null
@@ -0,0 +1,63 @@
+#if NET_4_0
+//
+// WrapHelper.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Linq;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace System.Linq
+{
+       internal class WrapHelper
+       {
+               class EnumeratorWrapper<TEnum> : IEnumerable<TEnum>
+               {
+                       IEnumerator<TEnum> enumerator;
+
+                       public EnumeratorWrapper (IEnumerator<TEnum> enumerator)
+                       {
+                               this.enumerator = enumerator;
+                       }
+
+                       public IEnumerator<TEnum> GetEnumerator ()
+                       {
+                               return enumerator;
+                       }
+
+                       IEnumerator IEnumerable.GetEnumerator ()
+                       {
+                               return (IEnumerator)enumerator;
+                       }
+               }
+
+               internal static IList<IEnumerable<TEnum>> Wrap<TEnum> (IList<IEnumerator<TEnum>> src)
+               {
+                       return src.Select ((e) => (IEnumerable<TEnum>)new EnumeratorWrapper<TEnum> (e)).ToArray ();
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/RangeList.cs b/mcs/class/System.Core/System.Linq/Internal/RangeList.cs
new file mode 100644 (file)
index 0000000..43e7ed2
--- /dev/null
@@ -0,0 +1,125 @@
+#if NET_4_0
+//
+// RangeList.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace System.Linq
+{
+       internal class RangeList : IList<int>
+       {
+               readonly int start;
+               readonly int count;
+
+               public RangeList (int start, int count)
+               {
+                       this.start = start;
+                       this.count = count;
+               }
+
+               public int IndexOf (int item)
+               {
+                       if (!Contains(item))
+                               return -1;
+
+                       return item - start;
+               }
+
+               public void Insert (int index, int item)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public void RemoveAt (int index)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public int this[int index] {
+                       get {
+                               if (start + index <= count)
+                                       return start + index;
+                               else
+                                       return -1;
+                       }
+                       set {
+                               throw new NotImplementedException();
+                       }
+               }
+
+               public void Add (int item)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public void Clear ()
+               {
+                       throw new NotImplementedException();
+               }
+
+               public bool Contains (int item)
+               {
+                       return start <= item && item <= start + count - 1;
+               }
+
+               public void CopyTo (int[] array, int arrayIndex)
+               {
+                       int counter = start;
+                       for (int i = arrayIndex; i < array.Length && i < (i - arrayIndex) + count; i++)
+                               array[i] = counter++;
+               }
+
+               public bool Remove (int item)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public int Count {
+                       get {
+                               return count;
+                       }
+               }
+
+               public bool IsReadOnly {
+                       get {
+                               return true;
+                       }
+               }
+
+               IEnumerator<int> IEnumerable<int>.GetEnumerator ()
+               {
+                       return null;
+               }
+
+               IEnumerator IEnumerable.GetEnumerator ()
+               {
+                       return null;
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/RepeatList.cs b/mcs/class/System.Core/System.Linq/Internal/RepeatList.cs
new file mode 100644 (file)
index 0000000..35bbd10
--- /dev/null
@@ -0,0 +1,119 @@
+#if NET_4_0
+//
+// RepeatList.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace System.Linq
+{
+       internal class RepeatList<T> : IList<T>
+       {
+               readonly int count;
+               readonly T element;
+
+               public RepeatList (T element, int count)
+               {
+                       this.element = element;
+                       this.count = count;
+               }
+
+               public int IndexOf (T item)
+               {
+                       // No real index, we may just be interested if the value is different from -1
+                       return Contains(item) ? 1 : -1;
+               }
+
+               public void Insert (int index, T item)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public void RemoveAt (int index)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public T this[int index] {
+                       get {
+                               return index < count ? element : default(T);
+                       }
+                       set {
+                               throw new NotImplementedException();
+                       }
+               }
+
+               public void Add (T item)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public void Clear ()
+               {
+                       throw new NotImplementedException();
+               }
+
+               public bool Contains (T item)
+               {
+                       return item.Equals(element);
+               }
+
+               public void CopyTo (T[] array, int arrayIndex)
+               {
+                       for (int i = arrayIndex; i < array.Length && i < (i - arrayIndex) + count; i++)
+                               array[i] = element;
+               }
+
+               public bool Remove (T item)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public int Count {
+                       get {
+                               return count;
+                       }
+               }
+
+               public bool IsReadOnly {
+                       get {
+                               return true;
+                       }
+               }
+
+               IEnumerator<T> IEnumerable<T>.GetEnumerator ()
+               {
+                       return null;
+               }
+
+               IEnumerator IEnumerable.GetEnumerator ()
+               {
+                       return null;
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/ReverseList.cs b/mcs/class/System.Core/System.Linq/Internal/ReverseList.cs
new file mode 100644 (file)
index 0000000..b5ca7d0
--- /dev/null
@@ -0,0 +1,119 @@
+#if NET_4_0
+//
+// QueryReverseNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System.Linq;
+using System.Threading;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace System.Linq
+{
+       internal class ReverseList<T> : IList<T>
+       {
+               readonly IList<T> backend;
+               readonly int count;
+
+               internal ReverseList (IList<T> backend)
+               {
+                       this.backend = backend;
+                       this.count = backend.Count;
+               }
+
+               public int IndexOf (T item)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public void Insert (int index, T item)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public void RemoveAt (int index)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public T this[int index] {
+                       get {
+                               return backend[count - 1 - index];
+                       }
+                       set {
+                               throw new NotImplementedException();
+                       }
+               }
+
+               public void Add (T item)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public void Clear ()
+               {
+                       throw new NotImplementedException();
+               }
+
+               public bool Contains (T item)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public void CopyTo (T[] array, int arrayIndex)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public bool Remove (T item)
+               {
+                       throw new NotImplementedException();
+               }
+
+               public int Count {
+                       get {
+                               return count;
+                       }
+               }
+
+               public bool IsReadOnly {
+                       get {
+                               return true;
+                       }
+               }
+
+               IEnumerator<T> IEnumerable<T>.GetEnumerator ()
+               {
+                       return null;
+               }
+
+               IEnumerator IEnumerable.GetEnumerator ()
+               {
+                       return null;
+               }
+       }
+}
+
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/StripPartitioner.cs b/mcs/class/System.Core/System.Linq/Internal/StripPartitioner.cs
new file mode 100644 (file)
index 0000000..699cb09
--- /dev/null
@@ -0,0 +1,62 @@
+#if NET_4_0
+//
+// StripPartitioner.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+using System.Collections.Generic;
+using System.Collections.Concurrent;
+
+namespace System.Linq
+{
+       internal class StripPartitioner<T> : OrderablePartitioner<T>
+       {
+               IList<T> source;
+
+               public StripPartitioner (IList<T> source) : base (true, false, true)
+               {
+                       this.source = source;
+               }
+
+               public override IList<IEnumerator<KeyValuePair<long, T>>> GetOrderablePartitions (int partitionCount)
+               {
+                       IEnumerator<KeyValuePair<long, T>>[] array = new IEnumerator<KeyValuePair<long, T>>[partitionCount];
+                       for (int i = 0; i < array.Length; i++)
+                               array[i] = GetStripEnumerator (i, partitionCount);
+
+                       return array;
+               }
+
+               IEnumerator<KeyValuePair<long, T>> GetStripEnumerator (int start, int partitionCount)
+               {
+                       for (int i = start; i < source.Count; i += partitionCount) {
+                               //Console.WriteLine ("Num {0} yielding [{1} : {2}]", start, i, source[i]);
+                               yield return new KeyValuePair<long, T> (i, source [i]);
+                       }
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/Visitors/ChangeLog b/mcs/class/System.Core/System.Linq/Internal/Visitors/ChangeLog
new file mode 100644 (file)
index 0000000..55e3ece
--- /dev/null
@@ -0,0 +1,7 @@
+2010-04-15  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * INodeVisitor.cs:
+       * IVisitableNode.cs:
+       * QueryCheckerVisitor.cs:
+       * QueryOptions.cs: First check-in of PLinq
+
diff --git a/mcs/class/System.Core/System.Linq/Internal/Visitors/INodeVisitor.cs b/mcs/class/System.Core/System.Linq/Internal/Visitors/INodeVisitor.cs
new file mode 100644 (file)
index 0000000..1b056fd
--- /dev/null
@@ -0,0 +1,43 @@
+#if NET_4_0
+//
+// INodeVisitor.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace System.Linq
+{
+       internal interface INodeVisitor
+       {
+               void Visit<T> (QueryBaseNode<T> node);
+               void Visit<U, V> (QueryChildNode<U, V> node);
+               void Visit<T> (QueryOptionNode<T> node);
+               void Visit<T> (QueryStartNode<T> node);
+               void Visit<T, TParent> (QueryStreamNode<T, TParent> node);
+               void Visit<T> (QueryOrderGuardNode<T> node);
+               void Visit<TFirst, TSecond, TResult> (QueryMuxNode<TFirst, TSecond, TResult> node);
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/Visitors/IVisitableNode.cs b/mcs/class/System.Core/System.Linq/Internal/Visitors/IVisitableNode.cs
new file mode 100644 (file)
index 0000000..5d7326f
--- /dev/null
@@ -0,0 +1,37 @@
+#if NET_4_0
+//
+// IVisitableNode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace System.Linq
+{
+       internal interface IVisitableNode
+       {
+               void Visit (INodeVisitor visitor);
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/Visitors/QueryCheckerVisitor.cs b/mcs/class/System.Core/System.Linq/Internal/Visitors/QueryCheckerVisitor.cs
new file mode 100644 (file)
index 0000000..df5660f
--- /dev/null
@@ -0,0 +1,162 @@
+#if NET_4_0
+//
+// QueryCheckerVisitor.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+
+namespace System.Linq
+{
+       using OptionsList = Tuple<ParallelMergeOptions?, ParallelExecutionMode?, CancellationToken?, int, CancellationTokenSource>;
+
+       internal class QueryCheckerVisitor : INodeVisitor
+       {
+               // Information gathering
+               ParallelMergeOptions? options = null;
+               ParallelExecutionMode? mode = null;
+               CancellationToken? token = null;
+               int? degreeOfParallelism = null;
+               bool useStrip;
+               CancellationToken implementerToken = CancellationToken.None;
+
+               int partitionCount;
+               bool? behindOrderGuard = null;
+
+               internal QueryCheckerVisitor (int partitionCount)
+               {
+                       this.partitionCount = partitionCount;
+               }
+
+               #region INodeVisitor implementation
+               public void Visit<T> (QueryBaseNode<T> node)
+               {
+                       // Nothing to do atm. Later we can check if the node is a
+                       // Take or a Skip and set accordingly useStrip
+               }
+
+               public void Visit<U, V> (QueryChildNode<U, V> node)
+               {
+                       node.Parent.Visit (this);
+               }
+
+               public void Visit<T> (QueryOptionNode<T> node)
+               {
+                       MergeOptions (node.GetOptions ());
+
+                       Visit<T, T> ((QueryChildNode<T, T>)node);
+               }
+
+               public void Visit<T> (QueryStartNode<T> node)
+               {
+                       if (behindOrderGuard == null)
+                               behindOrderGuard = false;
+                       if (degreeOfParallelism != null)
+                               partitionCount = degreeOfParallelism.Value;
+               }
+
+               public void Visit<T, TParent> (QueryStreamNode<T, TParent> node)
+               {
+                       if (node.IsIndexed)
+                               useStrip = true;
+
+                       Visit<T, TParent> ((QueryChildNode<T, TParent>)node);
+               }
+
+               public void Visit<T> (QueryOrderGuardNode<T> node)
+               {
+                       if (node.EnsureOrder && behindOrderGuard == null)
+                               behindOrderGuard = true;
+               }
+
+               public void Visit<TFirst, TSecond, TResult> (QueryMuxNode<TFirst, TSecond, TResult> node)
+               {
+
+                       Visit<TResult, TFirst> ((QueryChildNode<TResult, TFirst>)node);
+               }
+               #endregion
+
+               internal QueryOptions Options {
+                       get {
+                               return new QueryOptions (options, mode, token == null ? CancellationToken.None : token.Value,
+                                                        useStrip, behindOrderGuard, partitionCount, implementerToken);
+                       }
+               }
+
+               internal bool UseStrip {
+                       get {
+                               return useStrip;
+                       }
+               }
+
+               internal bool BehindOrderGuard {
+                       get {
+                               return behindOrderGuard.Value;
+                       }
+               }
+
+               void MergeOptions (OptionsList list)
+               {
+                       if (list.Item1 != null) {
+                               if (options == null)
+                                       options = list.Item1;
+                               else
+                                       Throw ("WithMergeOptions");
+                       }
+
+                       if (list.Item2 != null) {
+                               if (mode == null)
+                                       mode = list.Item2;
+                               else
+                                       Throw ("WithExecutionMode");
+                       }
+
+                       if (list.Item3 != null) {
+                               if (token == null)
+                                       token = list.Item3;
+                               else
+                                       Throw ("WithCancellationToken");
+                       }
+
+                       if (list.Item4 != -1) {
+                               if (degreeOfParallelism == null)
+                                       degreeOfParallelism = list.Item4;
+                               else
+                                       Throw ("WithDegreeOfParallelism");
+                       }
+
+                       // That one is treated specially
+                       if (list.Item5 != null) {
+                               implementerToken = implementerToken.Chain (list.Item5);
+                       }
+               }
+
+               void Throw (string methName)
+               {
+                       throw new InvalidOperationException ("You can't have more than one " + methName + " node in a query");
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/Internal/Visitors/QueryOptions.cs b/mcs/class/System.Core/System.Linq/Internal/Visitors/QueryOptions.cs
new file mode 100644 (file)
index 0000000..f6d0702
--- /dev/null
@@ -0,0 +1,71 @@
+#if NET_4_0
+//
+// QueryOptions.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+
+namespace System.Linq
+{
+       internal class QueryOptions
+       {
+               public ParallelMergeOptions? Options;
+               public ParallelExecutionMode? Mode;
+               public CancellationToken Token;
+               /* This token is to be used by some operator (like Take) to tell that
+                * the execution of the query can be prematurly stopped
+                *
+                * It is set when passing QueryOptions to the different node's Get method
+                * and ParallelExecuter should check after the call to this method is this guy has been
+                * set. Operator may chain up multiple cancellation token that way.
+                * When checking for this token, the task body should simply return.
+                */
+               public CancellationToken ImplementerToken;
+               public bool UseStrip;
+               public bool? BehindOrderGuard;
+               public int PartitionCount;
+               public Tuple<bool, bool, bool> PartitionerSettings;
+
+               public QueryOptions (ParallelMergeOptions? options,
+                                    ParallelExecutionMode? mode,
+                                    CancellationToken token,
+                                    bool useStrip,
+                                    bool? behindOrderGuard,
+                                    int partitionCount,
+                                    CancellationToken implementerToken)
+               {
+                       Options = options;
+                       Mode = mode;
+                       Token = token;
+                       UseStrip = useStrip;
+                       BehindOrderGuard = behindOrderGuard;
+                       PartitionCount = partitionCount;
+                       PartitionerSettings = null;
+                       ImplementerToken = implementerToken;
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/OrderedParallelQuery.cs b/mcs/class/System.Core/System.Linq/OrderedParallelQuery.cs
new file mode 100644 (file)
index 0000000..a8b80b7
--- /dev/null
@@ -0,0 +1,54 @@
+#if NET_4_0
+//
+// ParallelQuery.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.Concurrent;
+
+namespace System.Linq
+{
+       // Only returned after OrderBy and ThenBy.
+       public class OrderedParallelQuery<TSource> : ParallelQuery<TSource>
+       {
+               QueryOrderByNode<TSource> node;
+
+               internal OrderedParallelQuery (QueryOrderByNode<TSource> node)
+                       : base (node)
+               {
+                       this.node = node;
+               }
+
+               internal new QueryOrderByNode<TSource> Node {
+                       get {
+                               return node;
+                       }
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/ParallelEnumerable.cs b/mcs/class/System.Core/System.Linq/ParallelEnumerable.cs
new file mode 100644 (file)
index 0000000..de5dd6c
--- /dev/null
@@ -0,0 +1,2113 @@
+#if NET_4_0
+//
+// ParallelEnumerable.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.Concurrent;
+
+namespace System.Linq
+{
+       public static class ParallelEnumerable
+       {
+               #region Range & Repeat
+               public static ParallelQuery<int> Range (int start, int count)
+               {
+                       if (int.MaxValue - start < count)
+                               throw new ArgumentOutOfRangeException ("count", "start + count - 1 is larger than Int32.MaxValue");
+                       if (count < 0)
+                               throw new ArgumentOutOfRangeException ("count", "count is less than 0");
+
+                       return (new RangeList (start, count)).AsParallel ();
+               }
+
+               public static ParallelQuery<TResult> Repeat<TResult> (TResult obj, int count)
+               {
+                       if (count < 0)
+                               throw new ArgumentOutOfRangeException ("count", "count is less than 0");
+
+                       return (new RepeatList<TResult> (obj, count)).AsParallel ();
+               }
+               #endregion
+
+               #region Empty
+               public static ParallelQuery<TResult> Empty<TResult> ()
+               {
+                       return Repeat<TResult> (default (TResult), 0);
+               }
+               #endregion
+
+               #region AsParallel
+               public static ParallelQuery<TSource> AsParallel<TSource> (this IEnumerable<TSource> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return new ParallelQuery<TSource> (new QueryStartNode<TSource> (source));
+               }
+
+               public static ParallelQuery<TSource> AsParallel<TSource> (this Partitioner<TSource> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return new ParallelQuery<TSource> (new QueryStartNode<TSource> (source));
+               }
+
+               public static ParallelQuery AsParallel (this IEnumerable source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return new ParallelQuery<object> (new QueryStartNode<object> (source.Cast<object> ()));
+               }
+
+               public static IEnumerable<TSource> AsEnumerable<TSource> (this ParallelQuery<TSource> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.AsSequential ();
+               }
+
+               public static IEnumerable<TSource> AsSequential<TSource> (      this ParallelQuery<TSource> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Node.GetSequential ();
+               }
+               #endregion
+
+               #region AsOrdered / AsUnordered
+               public static ParallelQuery<TSource> AsOrdered<TSource> (this ParallelQuery<TSource> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return new ParallelQuery<TSource> (new QueryAsOrderedNode<TSource> (source.Node));
+               }
+
+               public static ParallelQuery<TSource> AsUnordered<TSource> (this ParallelQuery<TSource> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return new ParallelQuery<TSource> (new QueryAsUnorderedNode<TSource> (source.Node));
+               }
+
+               public static ParallelQuery AsOrdered (ParallelQuery source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.TypedQuery.AsOrdered ();
+               }
+               #endregion
+
+               #region With*
+               public static ParallelQuery<TSource> WithExecutionMode<TSource> (this ParallelQuery<TSource> source,
+                                                                                ParallelExecutionMode executionMode)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return new ParallelQuery<TSource> (new ParallelExecutionModeNode<TSource> (executionMode, source.Node));
+               }
+
+               public static ParallelQuery<TSource> WithCancellation<TSource> (this ParallelQuery<TSource> source,
+                                                                               CancellationToken cancellationToken)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return new ParallelQuery<TSource> (new CancellationTokenNode<TSource> (cancellationToken, source.Node));
+               }
+
+               public static ParallelQuery<TSource> WithMergeOptions<TSource> (this ParallelQuery<TSource> source,
+                                                                               ParallelMergeOptions mergeOptions)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return new ParallelQuery<TSource> (new ParallelMergeOptionsNode<TSource> (mergeOptions, source.Node));
+               }
+
+               public static ParallelQuery<TSource> WithDegreeOfParallelism<TSource> (this ParallelQuery<TSource> source,
+                                                                                      int degreeParallelism)
+               {
+                       if (degreeParallelism < 1 || degreeParallelism > 63)
+                               throw new ArgumentException ("degreeOfParallelism is less than 1 or greater than 63", "degreeParallelism");
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return new ParallelQuery<TSource> (new DegreeOfParallelismNode<TSource> (degreeParallelism, source.Node));
+               }
+
+               internal static ParallelQuery<TSource> WithImplementerToken<TSource> (this ParallelQuery<TSource> source,
+                                                                                     CancellationTokenSource token)
+               {
+                       return new ParallelQuery<TSource> (new ImplementerTokenNode<TSource> (token, source.Node));
+               }
+               #endregion
+
+               #region Select
+               public static ParallelQuery<TResult> Select<TSource, TResult> (this ParallelQuery<TSource> source, Func<TSource, TResult> selector)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (selector == null)
+                               throw new ArgumentNullException ("selector");
+
+                       return new ParallelQuery<TResult> (new QuerySelectNode<TResult, TSource> (source.Node, selector));
+               }
+
+               public static ParallelQuery<TResult> Select<TSource, TResult> (this ParallelQuery<TSource> source, Func<TSource, int, TResult> selector)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (selector == null)
+                               throw new ArgumentNullException ("selector");
+
+                       return new ParallelQuery<TResult> (new QuerySelectNode<TResult, TSource> (source.Node, selector));
+               }
+               #endregion
+               
+               #region SelectMany
+               public static ParallelQuery<TResult> SelectMany<TSource, TResult> (this ParallelQuery<TSource> source,
+                                                                                  Func<TSource, IEnumerable<TResult>> selector)
+               {
+                       return source.SelectMany (selector, (s, e) => e);
+               }
+
+               public static ParallelQuery<TResult> SelectMany<TSource, TResult> (this ParallelQuery<TSource> source,
+                                                                                  Func<TSource, int, IEnumerable<TResult>> selector)
+               {
+                       return source.SelectMany (selector, (s, e) => e);
+               }
+               
+               public static ParallelQuery<TResult> SelectMany<TSource, TCollection, TResult> (this ParallelQuery<TSource> source,
+                                                                                               Func<TSource, IEnumerable<TCollection>> collectionSelector,
+                                                                                               Func<TSource, TCollection, TResult> resultSelector)
+               {
+                       return new ParallelQuery<TResult> (new QuerySelectManyNode<TSource, TCollection, TResult> (source.Node,
+                                                                                                                  collectionSelector,
+                                                                                                                  resultSelector));
+               }
+               
+               public static ParallelQuery<TResult> SelectMany<TSource, TCollection, TResult> (this ParallelQuery<TSource> source,
+                                                                                               Func<TSource, int, IEnumerable<TCollection>> collectionSelector,
+                                                                                               Func<TSource, TCollection, TResult> resultSelector)
+               {
+                       return new ParallelQuery<TResult> (new QuerySelectManyNode<TSource, TCollection, TResult> (source.Node,
+                                                                                                                  collectionSelector,
+                                                                                                                  resultSelector));
+               }
+               #endregion
+
+               #region Where
+               public static ParallelQuery<TSource> Where<TSource> (this ParallelQuery<TSource> source, Func<TSource, bool> predicate)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (predicate == null)
+                               throw new ArgumentNullException ("predicate");
+
+                       return new ParallelQuery<TSource> (new QueryWhereNode<TSource> (source.Node, predicate));
+               }
+
+               public static ParallelQuery<TSource> Where<TSource> (this ParallelQuery<TSource> source, Func<TSource, int, bool> predicate)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (predicate == null)
+                               throw new ArgumentNullException ("predicate");
+
+                       return new ParallelQuery<TSource> (new QueryWhereNode<TSource> (source.Node, predicate));
+               }
+               #endregion
+
+               #region Aggregate
+               public static TSource Aggregate<TSource> (this ParallelQuery<TSource> source, Func<TSource, TSource, TSource> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Aggregate<TSource, TSource, TSource> ((Func<TSource>)null,
+                                                                           func,
+                                                                           func,
+                                                                           (e) => e);
+               }
+
+               public static TAccumulate Aggregate<TSource, TAccumulate> (this ParallelQuery<TSource> source,
+                                                                            TAccumulate seed,
+                                                                            Func<TAccumulate, TSource, TAccumulate> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Aggregate (seed, func, (e) => e);
+               }
+
+               public static TResult Aggregate<TSource, TAccumulate, TResult> (this ParallelQuery<TSource> source,
+                                                                                 TAccumulate seed,
+                                                                                 Func<TAccumulate, TSource, TAccumulate> func,
+                                                                                 Func<TAccumulate, TResult> resultSelector)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+                       if (resultSelector == null)
+                               throw new ArgumentNullException ("resultSelector");
+
+                       TAccumulate accumulator = seed;
+
+                       foreach (TSource value in source)
+                               accumulator = func (accumulator, value);
+
+                       return resultSelector (accumulator);
+               }
+
+               public static TResult Aggregate<TSource, TAccumulate, TResult> (this ParallelQuery<TSource> source,
+                                                                                 TAccumulate seed,
+                                                                                 Func<TAccumulate, TSource, TAccumulate> updateAccumulatorFunc,
+                                                                                 Func<TAccumulate, TAccumulate, TAccumulate> combineAccumulatorsFunc,
+                                                                                 Func<TAccumulate, TResult> resultSelector)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (updateAccumulatorFunc == null)
+                               throw new ArgumentNullException ("updateAccumulatorFunc");
+                       if (combineAccumulatorsFunc == null)
+                               throw new ArgumentNullException ("combineAccumulatorsFunc");
+                       if (resultSelector == null)
+                               throw new ArgumentNullException ("resultSelector");
+
+                       return source.Aggregate (() => seed, updateAccumulatorFunc, combineAccumulatorsFunc, resultSelector);
+               }
+
+               public static TResult Aggregate<TSource, TAccumulate, TResult> (this ParallelQuery<TSource> source,
+                                                                                 Func<TAccumulate> seedFunc,
+                                                                                 Func<TAccumulate, TSource, TAccumulate> updateAccumulatorFunc,
+                                                                                 Func<TAccumulate, TAccumulate, TAccumulate> combineAccumulatorsFunc,
+                                                                                 Func<TAccumulate, TResult> resultSelector)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (seedFunc == null)
+                               throw new ArgumentNullException ("seedFunc");
+                       if (updateAccumulatorFunc == null)
+                               throw new ArgumentNullException ("updateAccumulatorFunc");
+                       if (combineAccumulatorsFunc == null)
+                               throw new ArgumentNullException ("combineAccumulatorsFunc");
+                       if (resultSelector == null)
+                               throw new ArgumentNullException ("resultSelector");
+
+                       TAccumulate accumulator = default (TAccumulate);
+
+                       ParallelExecuter.ProcessAndAggregate<TSource, TAccumulate> (source.Node, seedFunc, updateAccumulatorFunc, (list) => {
+                               accumulator = list [0];
+                               for (int i = 1; i < list.Count; i++)
+                                       accumulator = combineAccumulatorsFunc (accumulator, list[i]);
+                       });
+
+                       return resultSelector (accumulator);;
+               }
+               #endregion
+
+               #region ForAll
+               public static void ForAll<TSource> (this ParallelQuery<TSource> source, Action<TSource> action)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (action == null)
+                               throw new ArgumentNullException ("action");
+
+                       ParallelExecuter.ProcessAndBlock (source.Node, action);
+               }
+               #endregion
+
+               #region OrderBy
+               public static OrderedParallelQuery<TSource> OrderByDescending<TSource, TKey> (this ParallelQuery<TSource> source,
+                                                                                             Func<TSource, TKey> keySelector,
+                                                                                             IComparer<TKey> comparer)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (keySelector == null)
+                               throw new ArgumentNullException ("keySelector");
+                       if (comparer == null)
+                               throw new ArgumentNullException ("comparer");
+
+                       Comparison<TSource> comparison = (e1, e2) => -comparer.Compare (keySelector (e1), keySelector (e2));
+
+                       return new OrderedParallelQuery<TSource> (new QueryOrderByNode<TSource> (source.Node, comparison));
+               }
+
+               public static OrderedParallelQuery<TSource> OrderByDescending<TSource, TKey> (this ParallelQuery<TSource> source,
+                                                                                             Func<TSource, TKey> keySelector)
+               {
+                       return OrderByDescending (source, keySelector, Comparer<TKey>.Default);
+               }
+
+               public static OrderedParallelQuery<TSource> OrderBy<TSource, TKey> (this ParallelQuery<TSource> source,
+                                                                                   Func<TSource, TKey> keySelector)
+               {
+                       return OrderBy (source, keySelector, Comparer<TKey>.Default);
+               }
+
+               public static OrderedParallelQuery<TSource> OrderBy<TSource, TKey> (this ParallelQuery<TSource> source,
+                                                                                   Func<TSource, TKey> keySelector,
+                                                                                   IComparer<TKey> comparer)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (keySelector == null)
+                               throw new ArgumentNullException ("keySelector");
+                       if (comparer == null)
+                               throw new ArgumentNullException ("comparer");
+
+                       Comparison<TSource> comparison = (e1, e2) => comparer.Compare (keySelector (e1), keySelector (e2));
+
+                       return new OrderedParallelQuery<TSource> (new QueryOrderByNode<TSource> (source.Node, comparison));
+               }
+               #endregion
+
+               #region ThenBy
+               public static OrderedParallelQuery<TSource> ThenBy<TSource, TKey> (this OrderedParallelQuery<TSource> source,
+                                                                                  Func<TSource, TKey> keySelector)
+               {
+                       return ThenBy (source, keySelector, Comparer<TKey>.Default);
+               }
+
+               public static OrderedParallelQuery<TSource> ThenBy<TSource, TKey> (this OrderedParallelQuery<TSource> source,
+                                                                                  Func<TSource, TKey> keySelector,
+                                                                                  IComparer<TKey> comparer)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (keySelector == null)
+                               throw new ArgumentNullException ("keySelector");
+                       if (comparer == null)
+                               throw new ArgumentNullException ("comparer");
+
+                       Comparison<TSource> comparison = (e1, e2) => comparer.Compare (keySelector (e1), keySelector (e2));
+
+                       return new OrderedParallelQuery<TSource> (new QueryOrderByNode<TSource> (source.Node, comparison));
+               }
+
+               public static OrderedParallelQuery<TSource> ThenByDescending<TSource, TKey> (this OrderedParallelQuery<TSource> source,
+                                                                                            Func<TSource, TKey> keySelector)
+               {
+                       return ThenByDescending (source, keySelector, Comparer<TKey>.Default);
+               }
+
+               public static OrderedParallelQuery<TSource> ThenByDescending<TSource, TKey> (this OrderedParallelQuery<TSource> source,
+                                                                                            Func<TSource, TKey> keySelector,
+                                                                                            IComparer<TKey> comparer)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (keySelector == null)
+                               throw new ArgumentNullException ("keySelector");
+                       if (comparer == null)
+                               throw new ArgumentNullException ("comparer");
+
+                       Comparison<TSource> comparison = (e1, e2) => -comparer.Compare (keySelector (e1), keySelector (e2));
+
+                       return new OrderedParallelQuery<TSource> (new QueryOrderByNode<TSource> (source.Node, comparison));
+               }
+               #endregion
+
+               #region All
+               public static bool All<TSource> (ParallelQuery<TSource> source, Func<TSource, bool> predicate)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (predicate == null)
+                               throw new ArgumentNullException ("predicate");
+
+                       CancellationTokenSource src = new CancellationTokenSource ();
+                       ParallelQuery<TSource> innerQuery = source.WithImplementerToken (src);
+
+                       bool result = true;
+                       innerQuery.ForAll ((e) => {
+                               if (!predicate (e)) {
+                                       result = false;
+                                       src.Cancel ();
+                               }
+                       });
+
+                       return result;
+               }
+               #endregion
+
+               #region Any
+               public static bool Any<TSource> (this ParallelQuery<TSource> source)
+               {
+                       return Any<TSource> (source, (_) => true);
+               }
+
+               public static bool Any<TSource> (this ParallelQuery<TSource> source, Func<TSource, bool> predicate)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (predicate == null)
+                               throw new ArgumentNullException ("predicate");
+
+                       return !source.All ((e) => !predicate (e));
+               }
+               #endregion
+
+               #region Contains
+               public static bool Contains<TSource> (this ParallelQuery<TSource> source, TSource value)
+               {
+                       return Contains<TSource> (source, value, EqualityComparer<TSource>.Default);
+               }
+
+               public static bool Contains<TSource> (this ParallelQuery<TSource> source, TSource value, IEqualityComparer<TSource> comparer)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (comparer == null)
+                               throw new ArgumentNullException ("comparer");
+
+                       return Any<TSource> (source, (e) => comparer.Equals (value));
+               }
+               #endregion
+
+               #region SequenceEqual
+               public static bool SequenceEqual<TSource> (this ParallelQuery<TSource> first,
+                                                          ParallelQuery<TSource> second)
+               {
+                       if (first == null)
+                               throw new ArgumentNullException ("first");
+                       if (second == null)
+                               throw new ArgumentNullException ("second");
+
+                       return first.SequenceEqual (second, EqualityComparer<TSource>.Default);
+               }
+
+               public static bool SequenceEqual<TSource> (this ParallelQuery<TSource> first,
+                                                          ParallelQuery<TSource> second,
+                                                          IEqualityComparer<TSource> comparer)
+               {
+                       if (first == null)
+                               throw new ArgumentNullException ("first");
+                       if (second == null)
+                               throw new ArgumentNullException ("second");
+                       if (comparer == null)
+                               throw new ArgumentNullException ("comparer");
+
+                       CancellationTokenSource source = new CancellationTokenSource ();
+                       ParallelQuery<bool> innerQuery
+                               = first.Zip (second, (e1, e2) => comparer.Equals (e1, e2)).Where ((e) => !e).WithImplementerToken (source);
+
+                       bool result = true;
+
+                       innerQuery.ForAll ((value) => {
+                               result = false;
+                               source.Cancel ();
+                       });
+
+                       return result;
+               }
+
+               [ObsoleteAttribute("The second data source of a binary operator must be of type System.Linq.ParallelQuery<T> rather "
+                                  + "than System.Collections.Generic.IEnumerable<T>. To fix this problem, use the AsParallel() "
+                                  + "extension method to convert the right data source to System.Linq.ParallelQuery<T>.")]
+               public static bool SequenceEqual<TSource> (this ParallelQuery<TSource> first, IEnumerable<TSource> second)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               [ObsoleteAttribute("The second data source of a binary operator must be of type System.Linq.ParallelQuery<T> rather "
+                                  + "than System.Collections.Generic.IEnumerable<T>. To fix this problem, use the AsParallel() "
+                                  + "extension method to convert the right data source to System.Linq.ParallelQuery<T>.")]
+               public static bool SequenceEqual<TSource> (this ParallelQuery<TSource> first,
+                                                             IEnumerable<TSource> second,
+                                                             IEqualityComparer<TSource> comparer)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               #endregion
+               
+               #region GroupBy
+               public static ParallelQuery<IGrouping<TKey, TSource>> GroupBy<TSource, TKey> (  this ParallelQuery<TSource> source,
+                                                                                             Func<TSource, TKey> keySelector)
+               {
+                       return source.GroupBy (keySelector, EqualityComparer<TKey>.Default);
+               }
+               
+               public static ParallelQuery<IGrouping<TKey, TSource>> GroupBy<TSource, TKey> (  this ParallelQuery<TSource> source,
+                                                                                             Func<TSource, TKey> keySelector,
+                                                                                             IEqualityComparer<TKey> comparer)
+               {
+                       return source.GroupBy (keySelector, (e) => e, comparer);
+               }
+               
+               public static ParallelQuery<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement> (this ParallelQuery<TSource> source,
+                                                                                                        Func<TSource, TKey> keySelector,
+                                                                                                        Func<TSource, TElement> elementSelector)
+               {
+                       return source.GroupBy (keySelector, elementSelector, EqualityComparer<TKey>.Default);
+               }
+               
+               public static ParallelQuery<TResult> GroupBy<TSource, TKey, TResult> (this ParallelQuery<TSource> source,
+                                                                                     Func<TSource, TKey> keySelector,
+                                                                                     Func<TKey, IEnumerable<TSource>, TResult> resultSelector)
+               {
+                       return source.GroupBy (keySelector)
+                               .Select ((g) => resultSelector (g.Key, (IEnumerable<TSource>)g));
+               }
+               
+               public static ParallelQuery<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement> (this ParallelQuery<TSource> source,
+                                                                                                        Func<TSource, TKey> keySelector,
+                                                                                                        Func<TSource, TElement> elementSelector,
+                                                                                                        IEqualityComparer<TKey> comparer)
+               {
+                       throw new NotImplementedException ();
+               }
+               
+               public static ParallelQuery<TResult> GroupBy<TSource, TKey, TElement, TResult> (this ParallelQuery<TSource> source,
+                                                                                               Func<TSource, TKey> keySelector,
+                                                                                               Func<TSource, TElement> elementSelector,
+                                                                                               Func<TKey, IEnumerable<TElement>, TResult> resultSelector)
+               {
+                       return source.GroupBy (keySelector, elementSelector)
+                               .Select ((g) => resultSelector (g.Key, (IEnumerable<TElement>)g));
+               }
+               
+               public static ParallelQuery<TResult> GroupBy<TSource, TKey, TResult> (  this ParallelQuery<TSource> source,
+                                                                                     Func<TSource, TKey> keySelector,
+                                                                                     Func<TKey, IEnumerable<TSource>, TResult> resultSelector,
+                                                                                     IEqualityComparer<TKey> comparer)
+               {
+                       return source.GroupBy (keySelector, comparer)
+                               .Select ((g) => resultSelector (g.Key, (IEnumerable<TSource>)g));
+               }
+               
+               public static ParallelQuery<TResult> GroupBy<TSource, TKey, TElement, TResult> (this ParallelQuery<TSource> source,
+                                                                                               Func<TSource, TKey> keySelector,
+                                                                                               Func<TSource, TElement> elementSelector,
+                                                                                               Func<TKey, IEnumerable<TElement>, TResult> resultSelector,
+                                                                                               IEqualityComparer<TKey> comparer)
+               {
+                       return source.GroupBy (keySelector, elementSelector, comparer)
+                               .Select ((g) => resultSelector (g.Key, (IEnumerable<TElement>)g));
+               }
+               #endregion
+
+               #region GroupJoin
+               public static ParallelQuery<TResult> GroupJoin<TOuter, TInner, TKey, TResult> (this ParallelQuery<TOuter> outer,
+                                                                                              ParallelQuery<TInner> inner,
+                                                                                              Func<TOuter, TKey> outerKeySelector,
+                                                                                              Func<TInner, TKey> innerKeySelector,
+                                                                                              Func<TOuter, IEnumerable<TInner>, TResult> resultSelector)
+               {
+                       return outer.GroupJoin (inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer<TKey>.Default);
+               }
+               
+               public static ParallelQuery<TResult> GroupJoin<TOuter, TInner, TKey, TResult> (this ParallelQuery<TOuter> outer,
+                                                                                              ParallelQuery<TInner> inner,
+                                                                                              Func<TOuter, TKey> outerKeySelector,
+                                                                                              Func<TInner, TKey> innerKeySelector,
+                                                                                              Func<TOuter, IEnumerable<TInner>, TResult> resultSelector,
+                                                                                              IEqualityComparer<TKey> comparer)
+               {
+                       throw new NotImplementedException ();
+               }
+               
+               [ObsoleteAttribute("The second data source of a binary operator must be of type System.Linq.ParallelQuery<T> rather "
+                                  + "than System.Collections.Generic.IEnumerable<T>. To fix this problem, use the AsParallel() "
+                                  + "extension method to convert the right data source to System.Linq.ParallelQuery<T>.")]
+               public static ParallelQuery<TResult> GroupJoin<TOuter, TInner, TKey, TResult> (this ParallelQuery<TOuter> outer,
+                                                                                              IEnumerable<TInner> inner,
+                                                                                              Func<TOuter, TKey> outerKeySelector,
+                                                                                              Func<TInner, TKey> innerKeySelector,
+                                                                                              Func<TOuter, IEnumerable<TInner>, TResult> resultSelector)
+               {
+                       throw new NotSupportedException ();
+               }
+               
+               [ObsoleteAttribute("The second data source of a binary operator must be of type System.Linq.ParallelQuery<T> rather "
+                                  + "than System.Collections.Generic.IEnumerable<T>. To fix this problem, use the AsParallel() "
+                                  + "extension method to convert the right data source to System.Linq.ParallelQuery<T>.")]
+               public static ParallelQuery<TResult> GroupJoin<TOuter, TInner, TKey, TResult> (this ParallelQuery<TOuter> outer,
+                                                                                              IEnumerable<TInner> inner,
+                                                                                              Func<TOuter, TKey> outerKeySelector,
+                                                                                              Func<TInner, TKey> innerKeySelector,
+                                                                                              Func<TOuter, IEnumerable<TInner>, TResult> resultSelector,
+                                                                                              IEqualityComparer<TKey> comparer)
+               {
+                       throw new NotImplementedException ();
+               }
+               #endregion
+
+               #region ElementAt
+               public static TSource ElementAt<TSource> (      this ParallelQuery<TSource> source, int index)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (index < 0)
+                               throw new ArgumentOutOfRangeException ("index");
+                       if (index == 0) {
+                               try {
+                                       return source.First ();
+                               } catch (InvalidOperationException) {
+                                       throw new ArgumentOutOfRangeException ("index");
+                               }
+                       }
+
+                       TSource result = default (TSource);
+
+                       ParallelQuery<TSource> innerQuery = source.Where ((e, i) => i == index);
+
+                       try {
+                               result = innerQuery.First ();
+                       } catch (InvalidOperationException) {
+                               throw new ArgumentOutOfRangeException ("index");
+                       }
+
+                       return result;
+               }
+
+               public static TSource ElementAtOrDefault<TSource> (this ParallelQuery<TSource> source, int index)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       try {
+                               return source.ElementAt (index);
+                       } catch (ArgumentOutOfRangeException) {
+                               return default (TSource);
+                       }
+               }
+               #endregion
+
+               #region Intersect
+               public static ParallelQuery<TSource> Intersect<TSource> (this ParallelQuery<TSource> first,
+                                                                        ParallelQuery<TSource> second)
+               {
+                       return Intersect<TSource> (first, second, EqualityComparer<TSource>.Default);
+               }
+
+               public static ParallelQuery<TSource> Intersect<TSource> (this ParallelQuery<TSource> first,
+                                                                        ParallelQuery<TSource> second,
+                                                                        IEqualityComparer<TSource> comparer)
+               {
+                       if (first == null)
+                               throw new ArgumentNullException ("first");
+                       if (second == null)
+                               throw new ArgumentNullException ("second");
+                       if (comparer == null)
+                               throw new ArgumentNullException ("comparer");
+
+                       return new ParallelQuery<TSource> (new QuerySetNode<TSource> (SetInclusionDefaults.Intersect, comparer, first.Node, second.Node));
+               }
+
+               [ObsoleteAttribute("The second data source of a binary operator must be of type System.Linq.ParallelQuery<T> rather "
+                                  + "than System.Collections.Generic.IEnumerable<T>. To fix this problem, use the AsParallel() "
+                                  + "extension method to convert the right data source to System.Linq.ParallelQuery<T>.")]
+               public static ParallelQuery<TSource> Intersect<TSource> (this ParallelQuery<TSource> first, IEnumerable<TSource> second)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               [ObsoleteAttribute("The second data source of a binary operator must be of type System.Linq.ParallelQuery<T> rather "
+                                  + "than System.Collections.Generic.IEnumerable<T>. To fix this problem, use the AsParallel() "
+                                  + "extension method to convert the right data source to System.Linq.ParallelQuery<T>.")]
+               public static ParallelQuery<TSource> Intersect<TSource> (this ParallelQuery<TSource> first,
+                                                                        IEnumerable<TSource> second,
+                                                                        IEqualityComparer<TSource> comparer)
+               {
+                       throw new NotSupportedException ();
+               }
+               #endregion
+
+               #region Join
+               public static ParallelQuery<TResult> Join<TOuter, TInner, TKey, TResult> (      this ParallelQuery<TOuter> outer,
+                                                                                         ParallelQuery<TInner> inner,
+                                                                                         Func<TOuter, TKey> outerKeySelector,
+                                                                                         Func<TInner, TKey> innerKeySelector,
+                                                                                         Func<TOuter, TInner, TResult> resultSelector)
+               {
+                       return outer.Join (inner, outerKeySelector, innerKeySelector, resultSelector, EqualityComparer<TKey>.Default);
+               }
+               
+               public static ParallelQuery<TResult> Join<TOuter, TInner, TKey, TResult> (      this ParallelQuery<TOuter> outer,
+                                                                                         ParallelQuery<TInner> inner,
+                                                                                         Func<TOuter, TKey> outerKeySelector,
+                                                                                         Func<TInner, TKey> innerKeySelector,
+                                                                                         Func<TOuter, TInner, TResult> resultSelector,
+                                                                                         IEqualityComparer<TKey> comparer)
+               {
+                       throw new NotImplementedException ();
+               }
+               
+               [ObsoleteAttribute("The second data source of a binary operator must be of type System.Linq.ParallelQuery<T> rather "
+                                  + "than System.Collections.Generic.IEnumerable<T>. To fix this problem, use the AsParallel() "
+                                  + "extension method to convert the right data source to System.Linq.ParallelQuery<T>.")]
+               public static ParallelQuery<TResult> Join<TOuter, TInner, TKey, TResult> (      this ParallelQuery<TOuter> outer,
+                                                                                         IEnumerable<TInner> inner,
+                                                                                         Func<TOuter, TKey> outerKeySelector,
+                                                                                         Func<TInner, TKey> innerKeySelector,
+                                                                                         Func<TOuter, TInner, TResult> resultSelector)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               [ObsoleteAttribute("The second data source of a binary operator must be of type System.Linq.ParallelQuery<T> rather "
+                                  + "than System.Collections.Generic.IEnumerable<T>. To fix this problem, use the AsParallel() "
+                                  + "extension method to convert the right data source to System.Linq.ParallelQuery<T>.")]
+               public static ParallelQuery<TResult> Join<TOuter, TInner, TKey, TResult> (this ParallelQuery<TOuter> outer,
+                                                                                         IEnumerable<TInner> inner,
+                                                                                         Func<TOuter, TKey> outerKeySelector,
+                                                                                         Func<TInner, TKey> innerKeySelector,
+                                                                                         Func<TOuter, TInner, TResult> resultSelector,
+                                                                                         IEqualityComparer<TKey> comparer)
+               {
+                       throw new NotSupportedException ();
+               }
+               #endregion
+
+               #region Except
+               public static ParallelQuery<TSource> Except<TSource> (  this ParallelQuery<TSource> first,
+                                                                     ParallelQuery<TSource> second)
+               {
+                       return Except<TSource> (first, second, EqualityComparer<TSource>.Default);
+               }
+
+               public static ParallelQuery<TSource> Except<TSource> (  this ParallelQuery<TSource> first,
+                                                                     ParallelQuery<TSource> second,
+                                                                     IEqualityComparer<TSource> comparer)
+               {
+                       if (first == null)
+                               throw new ArgumentNullException ("first");
+                       if (second == null)
+                               throw new ArgumentNullException ("second");
+                       if (comparer == null)
+                               throw new ArgumentNullException ("comparer");
+
+                       return new ParallelQuery<TSource> (new QuerySetNode<TSource> (SetInclusionDefaults.Except,
+                                                                                     comparer, first.Node, second.Node));
+               }
+
+               [ObsoleteAttribute("The second data source of a binary operator must be of type System.Linq.ParallelQuery<T> rather "
+                                  + "than System.Collections.Generic.IEnumerable<T>. To fix this problem, use the AsParallel() "
+                                  + "extension method to convert the right data source to System.Linq.ParallelQuery<T>.")]
+               public static ParallelQuery<TSource> Except<TSource> (this ParallelQuery<TSource> first,
+                                                                     IEnumerable<TSource> second)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               [ObsoleteAttribute("The second data source of a binary operator must be of type System.Linq.ParallelQuery<T> rather "
+                                  + "than System.Collections.Generic.IEnumerable<T>. To fix this problem, use the AsParallel() "
+                                  + "extension method to convert the right data source to System.Linq.ParallelQuery<T>.")]
+               public static ParallelQuery<TSource> Except<TSource> (  this ParallelQuery<TSource> first,
+                                                                     IEnumerable<TSource> second,
+                                                                     IEqualityComparer<TSource> comparer)
+               {
+                       throw new NotSupportedException ();
+               }
+               #endregion
+
+               #region Distinct
+               public static ParallelQuery<TSource> Distinct<TSource> (this ParallelQuery<TSource> source)
+               {
+                       return Distinct<TSource> (source, EqualityComparer<TSource>.Default);
+               }
+
+               public static ParallelQuery<TSource> Distinct<TSource> (this ParallelQuery<TSource> source, IEqualityComparer<TSource> comparer)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (comparer == null)
+                               throw new ArgumentNullException ("comparer");
+
+                       return new ParallelQuery<TSource> (new QuerySetNode<TSource> (SetInclusionDefaults.Distinct, comparer,
+                                                                                     source.Node, null));
+               }
+               #endregion
+
+               #region Union
+               [ObsoleteAttribute("The second data source of a binary operator must be of type System.Linq.ParallelQuery<T> rather "
+                                  + "than System.Collections.Generic.IEnumerable<T>. To fix this problem, use the AsParallel() "
+                                  + "extension method to convert the right data source to System.Linq.ParallelQuery<T>.")]
+               public static ParallelQuery<TSource> Union<TSource> (this ParallelQuery<TSource> first,
+                                                                    IEnumerable<TSource> second)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               [ObsoleteAttribute("The second data source of a binary operator must be of type System.Linq.ParallelQuery<T> rather "
+                                  + "than System.Collections.Generic.IEnumerable<T>. To fix this problem, use the AsParallel() "
+                                  + "extension method to convert the right data source to System.Linq.ParallelQuery<T>.")]
+               public static ParallelQuery<TSource> Union<TSource>(this ParallelQuery<TSource> first,
+                                                                   IEnumerable<TSource> second,
+                                                                   IEqualityComparer<TSource> comparer)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public static ParallelQuery<TSource> Union<TSource> (this ParallelQuery<TSource> first,
+                                                                    ParallelQuery<TSource> second)
+               {
+                       return first.Union (second, EqualityComparer<TSource>.Default);
+               }
+
+               public static ParallelQuery<TSource> Union<TSource> (this ParallelQuery<TSource> first,
+                                                                    ParallelQuery<TSource> second,
+                                                                    IEqualityComparer<TSource> comparer)
+               {
+                       if (first == null)
+                               throw new ArgumentNullException ("first");
+                       if (second == null)
+                               throw new ArgumentNullException ("second");
+                       if (comparer == null)
+                               throw new ArgumentNullException ("comparer");
+
+                       return new ParallelQuery<TSource> (new QuerySetNode<TSource> (SetInclusionDefaults.Union, comparer, first.Node, second.Node));
+               }
+               #endregion
+
+               #region Take
+               // TODO : introduce some early break up here, use ImplementerToken
+               public static ParallelQuery<TSource> Take<TSource> (this ParallelQuery<TSource> source, int count)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Where ((e, i) => i < count);
+               }
+
+               public static ParallelQuery<TSource> TakeWhile<TSource> (this ParallelQuery<TSource> source,
+                                                                        Func<TSource, bool> predicate)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (predicate == null)
+                               throw new ArgumentNullException ("predicate");
+
+                       return source.Where ((e) => predicate (e));
+               }
+
+               public static ParallelQuery<TSource> TakeWhile<TSource> (this ParallelQuery<TSource> source,
+                                                                        Func<TSource, int, bool> predicate)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (predicate == null)
+                               throw new ArgumentNullException ("predicate");
+
+                       return source.Where ((e, i) => predicate (e, i));
+               }
+               #endregion
+
+               #region Skip
+               public static ParallelQuery<TSource> Skip<TSource> (this ParallelQuery<TSource> source, int count)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Where ((e, i) => i >= count);
+               }
+
+               public static ParallelQuery<TSource> SkipWhile<TSource> (this ParallelQuery<TSource> source,
+                                                                        Func<TSource, bool> predicate)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (predicate == null)
+                               throw new ArgumentNullException ("predicate");
+
+                       return source.Where ((e) => !predicate (e));
+               }
+
+               public static ParallelQuery<TSource> SkipWhile<TSource> (this ParallelQuery<TSource> source,
+                                                                        Func<TSource, int, bool> predicate)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (predicate == null)
+                               throw new ArgumentNullException ("predicate");
+
+                       return source.Where ((e, i) => !predicate (e, i));
+               }
+               #endregion
+
+               #region Single
+               static TSource SingleInternal<TSource> (this ParallelQuery<TSource> source, params TSource[] init)
+               {
+                       TSource result = default(TSource);
+                       bool hasValue = false;
+
+                       foreach (TSource element in source) {
+                               if (hasValue)
+                                       throw new InvalidOperationException ("The input sequence contains more than one element.");
+
+                               result = element;
+                               hasValue = true;
+                       }
+
+                       if (!hasValue && init.Length != 0) {
+                               result = init[0];
+                               hasValue = true;
+                       }
+
+                       if (!hasValue)
+                               throw new InvalidOperationException ("The input sequence is empty.");
+
+                       return result;
+               }
+
+               public static TSource Single<TSource> (this ParallelQuery<TSource> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return SingleInternal<TSource> (source);
+               }
+
+               public static TSource Single<TSource> (this ParallelQuery<TSource> source,
+                                                      Func<TSource, bool> predicate)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (predicate == null)
+                               throw new ArgumentNullException ("predicate");
+
+                       return source.Where (predicate).Single ();
+               }
+
+               public static TSource SingleOrDefault<TSource> (this ParallelQuery<TSource> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return SingleInternal<TSource> (source, default (TSource));
+               }
+
+               public static TSource SingleOrDefault<TSource> (this ParallelQuery<TSource> source, Func<TSource, bool> predicate)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (predicate == null)
+                               throw new ArgumentNullException ("predicate");
+
+                       return source.Where (predicate).SingleOrDefault ();
+               }
+               #endregion
+
+               #region Count
+               public static int Count<TSource> (this ParallelQuery<TSource> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Aggregate<TSource, int, int> (() => 0,
+                                                                  (acc, e) => acc + 1,
+                                                                  (acc1, acc2) => acc1 + acc2,
+                                                                  (result) => result);
+               }
+
+               public static int Count<TSource> (this ParallelQuery<TSource> source, Func<TSource, bool> predicate)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (predicate == null)
+                               throw new ArgumentNullException ("predicate");
+
+                       return source.Where (predicate).Count ();
+               }
+
+               public static long LongCount<TSource> (this ParallelQuery<TSource> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Aggregate<TSource, long, long> (() => 0,
+                                                                     (acc, e) => acc + 1,
+                                                                     (acc1, acc2) => acc1 + acc2,
+                                                                     (result) => result);
+               }
+
+               public static long LongCount<TSource> (this ParallelQuery<TSource> source, Func<TSource, bool> predicate)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (predicate == null)
+                               throw new ArgumentNullException ("predicate");
+
+                       return source.Where (predicate).LongCount ();
+               }
+               #endregion
+
+               #region Average
+               public static double Average (this ParallelQuery<int> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Aggregate (() => new int[2],
+                                               (acc, e) => { acc[0] += e; acc[1]++; return acc; },
+                                               (acc1, acc2) => { acc1[0] += acc2[0]; acc1[1] += acc2[1]; return acc1; },
+                                               (acc) => acc[0] / ((double)acc[1]));
+               }
+
+               public static double Average (this ParallelQuery<long> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Aggregate (() => new long[2],
+                                               (acc, e) => { acc[0] += e; acc[1]++; return acc; },
+                                               (acc1, acc2) => { acc1[0] += acc2[0]; acc1[1] += acc2[1]; return acc1; },
+                                               (acc) => acc[0] / ((double)acc[1]));
+               }
+
+               public static decimal Average (this ParallelQuery<decimal> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Aggregate (() => new decimal[2],
+                                               (acc, e) => { acc[0] += e; acc[1]++; return acc; },
+                                               (acc1, acc2) => { acc1[0] += acc2[0]; acc1[1] += acc2[1]; return acc1; },
+                                               (acc) => acc[0] / acc[1]);
+               }
+
+               public static double Average (this ParallelQuery<double> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Aggregate (() => new double[2],
+                                               (acc, e) => { acc[0] += e; acc[1]++; return acc; },
+                                               (acc1, acc2) => { acc1[0] += acc2[0]; acc1[1] += acc2[1]; return acc1; },
+                                               (acc) => acc[0] / ((double)acc[1]));
+               }
+
+               public static float Average (this ParallelQuery<float> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Aggregate (() => new float[2],
+                                               (acc, e) => { acc[0] += e; acc[1]++; return acc; },
+                                               (acc1, acc2) => { acc1[0] += acc2[0]; acc1[1] += acc2[1]; return acc1; },
+                                               (acc) => acc[0] / acc[1]);
+               }
+               #endregion
+
+               #region More Average
+               public static double? Average (this ParallelQuery<int?> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Select ((e) => e.HasValue ? e.Value : 0).Average ();;
+               }
+
+               public static double? Average (this ParallelQuery<long?> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Select ((e) => e.HasValue ? e.Value : 0).Average ();
+               }
+
+               public static decimal? Average (this ParallelQuery<decimal?> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Select ((e) => e.HasValue ? e.Value : 0).Average ();
+               }
+
+               public static double? Average (this ParallelQuery<double?> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Select ((e) => e.HasValue ? e.Value : 0).Average ();
+               }
+
+               public static float? Average (this ParallelQuery<float?> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Select ((e) => e.HasValue ? e.Value : 0).Average ();
+               }
+
+               public static double Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, int> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Average ();
+               }
+
+               public static double Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, long> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Average ();
+               }
+
+               public static float Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, float> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Average ();
+               }
+
+               public static double Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, double> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Average ();
+               }
+
+               public static decimal Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Average ();
+               }
+
+               public static double? Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, int?> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Average ();
+               }
+
+               public static double? Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, long?> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Average ();
+               }
+
+               public static float? Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, float?> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Average ();
+               }
+
+               public static double? Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, double?> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Average ();
+               }
+
+               public static decimal? Average<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal?> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Average ();
+               }
+               #endregion
+
+               #region Sum
+               public static int Sum (ParallelQuery<int> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Aggregate (0, (e1, e2) => e1 + e2, (sum1, sum2) => sum1 + sum2, (sum) => sum);
+               }
+
+               public static long Sum (ParallelQuery<long> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Aggregate ((long)0, (e1, e2) => e1 + e2, (sum1, sum2) => sum1 + sum2, (sum) => sum);
+               }
+
+               public static float Sum (ParallelQuery<float> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Aggregate (0.0f, (e1, e2) => e1 + e2, (sum1, sum2) => sum1 + sum2, (sum) => sum);
+               }
+
+               public static double Sum (ParallelQuery<double> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Aggregate (0.0, (e1, e2) => e1 + e2, (sum1, sum2) => sum1 + sum2, (sum) => sum);
+               }
+
+               public static decimal Sum (ParallelQuery<decimal> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Aggregate ((decimal)0, (e1, e2) => e1 + e2, (sum1, sum2) => sum1 + sum2, (sum) => sum);
+               }
+
+               public static int? Sum (ParallelQuery<int?> source)
+               {
+                       return source.Select ((e) => e.HasValue ? e.Value : 0).Sum ();
+               }
+
+               public static long? Sum (ParallelQuery<long?> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Select ((e) => e.HasValue ? e.Value : 0).Sum ();
+               }
+
+               public static float? Sum (ParallelQuery<float?> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Select ((e) => e.HasValue ? e.Value : 0).Sum ();
+               }
+
+               public static double? Sum (ParallelQuery<double?> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Select ((e) => e.HasValue ? e.Value : 0).Sum ();
+               }
+
+               public static decimal? Sum (ParallelQuery<decimal?> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Select ((e) => e.HasValue ? e.Value : 0).Sum ();
+               }
+
+               public static int Sum<TSource> (ParallelQuery<TSource> source, Func<TSource, int> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Sum ();
+               }
+
+               public static long Sum<TSource> (ParallelQuery<TSource> source, Func<TSource, long> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Sum ();
+               }
+
+               public static decimal Sum<TSource> (ParallelQuery<TSource> source, Func<TSource, decimal> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Sum ();
+               }
+
+               public static float Sum<TSource> (ParallelQuery<TSource> source, Func<TSource, float> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Sum ();
+               }
+
+               public static double Sum<TSource> (ParallelQuery<TSource> source, Func<TSource, double> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Sum ();
+               }
+
+               public static int? Sum<TSource> (ParallelQuery<TSource> source, Func<TSource, int?> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Sum ();
+               }
+
+               public static long? Sum<TSource> (ParallelQuery<TSource> source, Func<TSource, long?> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Sum ();
+               }
+
+               public static decimal? Sum<TSource> (ParallelQuery<TSource> source, Func<TSource, decimal?> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Sum ();
+               }
+
+               public static float? Sum<TSource> (ParallelQuery<TSource> source, Func<TSource, float?> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Sum ();
+               }
+
+               public static double? Sum<TSource> (ParallelQuery<TSource> source, Func<TSource, double?> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Sum ();
+               }
+               #endregion
+
+               #region Min-Max
+               static T BestOrder<T> (ParallelQuery<T> source, Func<T, T, bool> bestSelector, T seed)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       T best = seed;
+
+                       best = source.Aggregate (() => seed,
+                                               (first, second) => (bestSelector(first, second)) ? first : second,
+                                               (first, second) => (bestSelector(first, second)) ? first : second,
+                                               (e) => e);
+                       return best;
+               }
+
+               public static int Min (this ParallelQuery<int> source)
+               {
+                       return BestOrder (source, (first, second) => first < second, int.MaxValue);
+               }
+
+               public static long Min (this ParallelQuery<long> source)
+               {
+                       return BestOrder (source, (first, second) => first < second, long.MaxValue);
+               }
+
+               public static float Min (this ParallelQuery<float> source)
+               {
+                       return BestOrder (source, (first, second) => first < second, float.MaxValue);
+               }
+
+               public static double Min (this ParallelQuery<double> source)
+               {
+                       return BestOrder (source, (first, second) => first < second, double.MaxValue);
+               }
+
+               public static decimal Min (this ParallelQuery<decimal> source)
+               {
+                       return BestOrder (source, (first, second) => first < second, decimal.MaxValue);
+               }
+
+               public static TSource Min<TSource> (this ParallelQuery<TSource> source)
+               {
+                       IComparer<TSource> comparer = Comparer<TSource>.Default;
+
+                       return BestOrder (source, (first, second) => comparer.Compare (first, second) < 0, default (TSource));
+               }
+
+               public static TResult Min<TSource, TResult> (this ParallelQuery<TSource> source, Func<TSource, TResult> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Min ();
+               }
+
+               public static int? Min (this ParallelQuery<int?> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Select ((e) => e.HasValue ? e.Value : int.MaxValue).Min ();
+               }
+
+               public static long? Min (this ParallelQuery<long?> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Select ((e) => e.HasValue ? e.Value : long.MaxValue).Min ();
+               }
+
+               public static float? Min (this ParallelQuery<float?> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Select ((e) => e.HasValue ? e.Value : float.MaxValue).Min ();
+               }
+
+               public static double? Min (this ParallelQuery<double?> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Select ((e) => e.HasValue ? e.Value : double.MaxValue).Min ();
+               }
+
+               public static decimal? Min (this ParallelQuery<decimal?> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Select ((e) => e.HasValue ? e.Value : decimal.MaxValue).Min ();
+               }
+
+               public static int Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, int> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Min ();
+               }
+
+               public static long Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, long> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Min ();
+               }
+
+               public static float Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, float> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Min ();
+               }
+
+               public static double Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, double> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Min ();
+               }
+
+               public static decimal Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Min ();
+               }
+
+               public static int? Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, int?> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Min ();
+               }
+
+               public static long? Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, long?> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Min ();
+               }
+
+               public static float? Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, float?> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Min ();
+               }
+
+               public static double? Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, double?> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Min ();
+               }
+
+               public static decimal? Min<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal?> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Min ();
+               }
+
+               public static int Max (this ParallelQuery<int> source)
+               {
+                       return BestOrder (source, (first, second) => first > second, int.MinValue);
+               }
+
+               public static long Max(this ParallelQuery<long> source)
+               {
+                       return BestOrder(source, (first, second) => first > second, long.MinValue);
+               }
+
+               public static float Max (this ParallelQuery<float> source)
+               {
+                       return BestOrder(source, (first, second) => first > second, float.MinValue);
+               }
+
+               public static double Max (this ParallelQuery<double> source)
+               {
+                       return BestOrder(source, (first, second) => first > second, double.MinValue);
+               }
+
+               public static decimal Max (this ParallelQuery<decimal> source)
+               {
+                       return BestOrder(source, (first, second) => first > second, decimal.MinValue);
+               }
+
+               public static TSource Max<TSource> (this ParallelQuery<TSource> source)
+               {
+                       IComparer<TSource> comparer = Comparer<TSource>.Default;
+
+                       return BestOrder (source, (first, second) => comparer.Compare (first, second) > 0, default (TSource));
+               }
+
+               public static TResult Max<TSource, TResult> (this ParallelQuery<TSource> source, Func<TSource, TResult> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Max ();
+               }
+
+               public static int? Max (this ParallelQuery<int?> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Select ((e) => e.HasValue ? e.Value : int.MinValue).Max ();
+               }
+
+               public static long? Max (this ParallelQuery<long?> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Select ((e) => e.HasValue ? e.Value : long.MinValue).Max ();
+               }
+
+               public static float? Max (this ParallelQuery<float?> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Select ((e) => e.HasValue ? e.Value : float.MinValue).Max ();
+               }
+
+               public static double? Max (this ParallelQuery<double?> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Select ((e) => e.HasValue ? e.Value : double.MinValue).Max ();
+               }
+
+               public static decimal? Max (this ParallelQuery<decimal?> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.Select ((e) => e.HasValue ? e.Value : decimal.MinValue).Max ();
+               }
+
+               public static int Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, int> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Max ();
+               }
+
+               public static long Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, long> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Max ();
+               }
+
+               public static float Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, float> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Max ();
+               }
+
+               public static double Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, double> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Max ();
+               }
+
+               public static decimal Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Max ();
+               }
+
+               public static int? Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, int?> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Max ();
+               }
+
+               public static long? Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, long?> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Max ();
+               }
+
+               public static float? Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, float?> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Max ();
+               }
+
+               public static double? Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, double?> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Max ();
+               }
+
+               public static decimal? Max<TSource> (this ParallelQuery<TSource> source, Func<TSource, decimal?> func)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (func == null)
+                               throw new ArgumentNullException ("func");
+
+                       return source.Select (func).Max ();
+               }
+               #endregion
+
+               #region Cast / OfType
+               public static ParallelQuery<TResult> Cast<TResult> (this ParallelQuery source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.TypedQuery.Select ((e) => (TResult)e);
+               }
+
+               public static ParallelQuery<TResult> OfType<TResult> (ParallelQuery source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return source.TypedQuery.Where ((e) => e is TResult).Cast<TResult> ();
+               }
+               #endregion
+
+               #region Reverse
+               public static ParallelQuery<TSource> Reverse<TSource> (this ParallelQuery<TSource> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       return new ParallelQuery<TSource> (new QueryReverseNode<TSource> (source));
+               }
+               #endregion
+
+               #region ToArray - ToList - ToDictionary - ToLookup
+               public static List<TSource> ToList<TSource> (this ParallelQuery<TSource> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       OrderedParallelQuery<TSource> ordered = null;
+                       if ((ordered = source as OrderedParallelQuery<TSource>) != null)
+                               return ToListOrdered (ordered);
+
+                       List<TSource> temp = source.Aggregate (() => new List<TSource>(50),
+                                                              (list, e) => { list.Add (e); return list; },
+                                                              (list, list2) => { list.AddRange (list2); return list; },
+                                                              (list) => list);
+                       return temp;
+               }
+
+               static List<TSource> ToListOrdered<TSource> (this OrderedParallelQuery<TSource> source)
+               {
+                       List<TSource> result = new List<TSource> ();
+
+                       foreach (TSource element in source)
+                               result.Add (element);
+
+                       return result;
+               }
+
+               public static TSource[] ToArray<TSource> (this ParallelQuery<TSource> source)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       TSource[] result = null;
+
+                       Func<List<TSource>, TSource, List<TSource>> intermediate = (list, e) => {
+                               list.Add (e); return list;
+                       };
+
+                       Action<IList<List<TSource>>> final = (list) => {
+                               int count = 0;
+
+                               for (int i = 0; i < list.Count; i++)
+                                 count += list[i].Count;
+
+                               result = new TSource[count];
+                               int insertIndex = -1;
+
+                               for (int i = 0; i < list.Count; i++)
+                                 for (int j = 0; j < list[i].Count; j++)
+                                   result [++insertIndex] = list[i][j];
+                       };
+
+                       ParallelExecuter.ProcessAndAggregate<TSource, List<TSource>> (source.Node,
+                                                                                     () => new List<TSource> (),
+                                                                                     intermediate,
+                                                                                     final);
+
+                       return result;
+               }
+
+               public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey> (this ParallelQuery<TSource> source,
+                                                                                    Func<TSource, TKey> keySelector,
+                                                                                    IEqualityComparer<TKey> comparer)
+               {
+                       return ToDictionary<TSource, TKey, TSource> (source, keySelector, (e) => e, comparer);
+               }
+
+               public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey> (this ParallelQuery<TSource> source,
+                                                                                    Func<TSource, TKey> keySelector)
+               {
+                       return ToDictionary<TSource, TKey, TSource> (source, keySelector, (e) => e, EqualityComparer<TKey>.Default);
+               }
+
+               public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement> (this ParallelQuery<TSource> source,
+                                                                                                 Func<TSource, TKey> keySelector,
+                                                                                                 Func<TSource, TElement> elementSelector)
+               {
+                       return ToDictionary<TSource, TKey, TElement> (source, keySelector, elementSelector, EqualityComparer<TKey>.Default);
+               }
+
+               public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement> (this ParallelQuery<TSource> source,
+                                                                                                 Func<TSource, TKey> keySelector,
+                                                                                                 Func<TSource, TElement> elementSelector,
+                                                                                                 IEqualityComparer<TKey> comparer)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (keySelector == null)
+                               throw new ArgumentNullException ("keySelector");
+                       if (comparer == null)
+                               throw new ArgumentNullException ("comparer");
+                       if (elementSelector == null)
+                               throw new ArgumentNullException ("elementSelector");
+
+                       return source.Aggregate (() => new Dictionary<TKey, TElement> (comparer),
+                                                 (d, e) => { d.Add (keySelector (e), elementSelector (e)); return d; },
+                                                 (d1, d2) => { foreach (var couple in d2) d1.Add (couple.Key, couple.Value); return d1; },
+                                                 (d) => d);
+               }
+
+               public static ILookup<TKey, TSource> ToLookup<TSource, TKey> (  this ParallelQuery<TSource> source,
+                                                                             Func<TSource, TKey> keySelector)
+               {
+                       return ToLookup<TSource, TKey, TSource> (source, keySelector, (e) => e, EqualityComparer<TKey>.Default);
+               }
+
+               public static ILookup<TKey, TSource> ToLookup<TSource, TKey> (  this ParallelQuery<TSource> source,
+                                                                             Func<TSource, TKey> keySelector,
+                                                                             IEqualityComparer<TKey> comparer)
+               {
+                       return ToLookup<TSource, TKey, TSource> (source, keySelector, (e) => e, comparer);
+               }
+
+               public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement> (this ParallelQuery<TSource> source,
+                                                                                        Func<TSource, TKey> keySelector,
+                                                                                        Func<TSource, TElement> elementSelector)
+               {
+                       return ToLookup<TSource, TKey, TElement> (source, keySelector, elementSelector, EqualityComparer<TKey>.Default);
+               }
+
+               public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement> (this ParallelQuery<TSource> source,
+                                                                                        Func<TSource, TKey> keySelector,
+                                                                                        Func<TSource, TElement> elementSelector,
+                                                                                        IEqualityComparer<TKey> comparer)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+                       if (keySelector == null)
+                               throw new ArgumentNullException ("keySelector");
+                       if (comparer == null)
+                               throw new ArgumentNullException ("comparer");
+                       if (elementSelector == null)
+                               throw new ArgumentNullException ("elementSelector");
+
+                       ConcurrentLookup<TKey, TElement> lookup = new ConcurrentLookup<TKey, TElement> (comparer);
+                       source.ForAll ((e) => lookup.Add (keySelector (e), elementSelector (e)));
+
+                       return lookup;
+               }
+               #endregion
+
+               #region Concat
+               [ObsoleteAttribute("The second data source of a binary operator must be of type System.Linq.ParallelQuery<T> rather than "
+                                  + "System.Collections.Generic.IEnumerable<T>. To fix this problem, use the AsParallel() extension method "
+                                  + "to convert the right data source to System.Linq.ParallelQuery<T>.")]
+               public static ParallelQuery<TSource> Concat<TSource>(this ParallelQuery<TSource> first,
+                                                                    IEnumerable<TSource> second)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public static ParallelQuery<TSource> Concat<TSource> (  this ParallelQuery<TSource> first, ParallelQuery<TSource> second)
+               {
+                       return new ParallelQuery<TSource> (new QueryConcatNode<TSource> (first.Node, second.Node));
+               }
+               #endregion
+               
+               #region DefaultIfEmpty
+               public static ParallelQuery<TSource> DefaultIfEmpty<TSource> (  this ParallelQuery<TSource> source)
+               {
+                       return source.DefaultIfEmpty (default (TSource));
+               }
+               
+               public static ParallelQuery<TSource> DefaultIfEmpty<TSource> (  this ParallelQuery<TSource> source, TSource defaultValue)
+               {
+                       return new ParallelQuery<TSource> (new QueryDefaultEmptyNode<TSource> (source.Node, defaultValue));
+               }
+               #endregion
+               
+               #region First
+               public static TSource First<TSource> (  this ParallelQuery<TSource> source)
+               {
+                       CancellationTokenSource src = new CancellationTokenSource ();
+                       IEnumerator<TSource> enumerator = source.WithImplementerToken (src).GetEnumerator ();
+                       
+                       if (enumerator == null || !enumerator.MoveNext ())
+                               throw new InvalidOperationException ("source contains no element");
+                       
+                       TSource result = enumerator.Current;
+                       src.Cancel ();
+                       
+                       return result;
+               }
+               
+               public static TSource First<TSource> (  this ParallelQuery<TSource> source, Func<TSource, bool> predicate)
+               {
+                       return source.Where (predicate).First ();
+               }
+               
+               public static TSource FirstOrDefault<TSource> (this ParallelQuery<TSource> source)
+               {
+                       return source.DefaultIfEmpty ().First ();
+               }
+               
+               public static TSource FirstOrDefault<TSource> (this ParallelQuery<TSource> source, Func<TSource, bool> predicate)
+               {
+                       return source.Where (predicate).FirstOrDefault ();
+               }
+               #endregion
+               
+               #region Last
+               public static TSource Last<TSource> (this ParallelQuery<TSource> source)
+               {
+                       return source.Reverse ().First ();
+               }
+               
+               public static TSource Last<TSource> (   this ParallelQuery<TSource> source, Func<TSource, bool> predicate)
+               {
+                       return source.Reverse ().First (predicate);
+               }
+               
+               public static TSource LastOrDefault<TSource> (this ParallelQuery<TSource> source)
+               {
+                       return source.Reverse ().FirstOrDefault ();
+               }
+               
+               public static TSource LastOrDefault<TSource> (this ParallelQuery<TSource> source, Func<TSource, bool> predicate)
+               {
+                       return source.Reverse ().FirstOrDefault (predicate);
+               }
+               #endregion
+
+               #region Zip
+               public static ParallelQuery<TResult> Zip<TFirst, TSecond, TResult> (this ParallelQuery<TFirst> first,
+                                                                                     ParallelQuery<TSecond> second,
+                                                                                     Func<TFirst, TSecond, TResult> resultSelector)
+               {
+                       if (first == null)
+                               throw new ArgumentNullException ("first");
+                       if (second == null)
+                               throw new ArgumentNullException ("second");
+                       if (resultSelector == null)
+                               throw new ArgumentNullException ("resultSelector");
+
+                       return new ParallelQuery<TResult> (new QueryZipNode<TFirst, TSecond, TResult> (resultSelector, first.Node, second.Node));
+               }
+
+               [ObsoleteAttribute("The second data source of a binary operator must be of type System.Linq.ParallelQuery<T> rather "
+                                  + "than System.Collections.Generic.IEnumerable<T>. To fix this problem, use the AsParallel() "
+                                  + "extension method to convert the right data source to System.Linq.ParallelQuery<T>.")]
+               public static ParallelQuery<TResult> Zip<TFirst, TSecond, TResult> (this ParallelQuery<TFirst> first,
+                                                                                     IEnumerable<TSecond> second,
+                                                                                     Func<TFirst, TSecond, TResult> resultSelector)
+               {
+                       throw new NotSupportedException ();
+               }
+               #endregion
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/ParallelExecuter.cs b/mcs/class/System.Core/System.Linq/ParallelExecuter.cs
new file mode 100644 (file)
index 0000000..24f9c1a
--- /dev/null
@@ -0,0 +1,193 @@
+#if NET_4_0
+//
+// ParallelExecuter.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.Concurrent;
+
+namespace System.Linq
+{
+       // TODO: Refactory each of the Process method into one big entity
+       // Check CancellationToken.Canceled parameter in the Task's action body too
+       internal static class ParallelExecuter
+       {
+               internal static QueryOptions CheckQuery<T> (QueryBaseNode<T> startingNode)
+               {
+                       return CheckQuery<T> (startingNode, false);
+               }
+
+               internal static QueryOptions CheckQuery<T> (QueryBaseNode<T> startingNode, bool blocking)
+               {
+                       return CheckQuery (startingNode, GetBestWorkerNumber (blocking));
+               }
+
+               internal static QueryOptions CheckQuery<T> (QueryBaseNode<T> startingNode, int partitionCount)
+               {
+                       QueryCheckerVisitor visitor = new QueryCheckerVisitor (partitionCount);
+                       startingNode.Visit (visitor);
+
+                       return visitor.Options;
+               }
+
+               // QueryOptions.ImplementerToken = QueryOptions.ImplementerToken.Chain (myOperatorSource);
+               internal static CancellationToken Chain (this CancellationToken self, CancellationTokenSource other)
+               {
+                       CancellationTokenSource linked = CancellationTokenSource.CreateLinkedTokenSource (self, other.Token);
+                       return linked.Token;
+               }
+
+               internal static int GetBestWorkerNumber ()
+               {
+                       return GetBestWorkerNumber (false);
+               }
+
+               internal static int GetBestWorkerNumber (bool blocking)
+               {
+                       return blocking ? Environment.ProcessorCount + 1 : Environment.ProcessorCount;
+               }
+
+               internal static Task[] Process<TSource, TElement> (QueryBaseNode<TSource> node, Action<TElement> call,
+                                                                  Func<QueryBaseNode<TSource>, QueryOptions, IList<IEnumerable<TElement>>> acquisitionFunc,
+                                                                  QueryOptions options)
+               {
+                       return Process<TSource, TElement> (node, call, acquisitionFunc, null, options);
+               }
+
+               internal static Task[] Process<TSource, TElement> (QueryBaseNode<TSource> node, Action<TElement> call,
+                                                                  Func<QueryBaseNode<TSource>, QueryOptions, IList<IEnumerable<TElement>>> acquisitionFunc,
+                                                                  Action endAction,
+                                                                  QueryOptions options)
+               {
+                       IList<IEnumerable<TElement>> enumerables = acquisitionFunc (node, options);
+
+                       Task[] tasks = new Task[enumerables.Count];
+
+                       for (int i = 0; i < tasks.Length; i++) {
+                               int index = i;
+                               tasks[i] = Task.Factory.StartNew (() => {
+                                       foreach (TElement item in enumerables[index]) {
+                                               // This is from specific operators
+                                               if (options.ImplementerToken.IsCancellationRequested)
+                                                       break;
+                                               if (options.Token.IsCancellationRequested)
+                                                       throw new OperationCanceledException (options.Token);
+
+                                               call (item);
+                                       }
+                                       if (endAction != null)
+                                               endAction ();
+                                 }, options.Token);
+                       }
+
+                       return tasks;
+               }
+
+               internal static void ProcessAndBlock<T> (QueryBaseNode<T> node, Action<T> call)
+               {
+                       QueryOptions options = CheckQuery (node, true);
+
+                       Task[] tasks = Process (node, call, (n, o) => n.GetEnumerables (o), options);
+                       Task.WaitAll (tasks, options.Token);
+               }
+
+               internal static Action ProcessAndCallback<T> (QueryBaseNode<T> node, Action<T> call,
+                                                             Action callback, QueryOptions options)
+               {
+                       Task[] tasks = Process (node, call, (n, o) => n.GetEnumerables (o), options);
+                       Task.Factory.ContinueWhenAll (tasks,  (_) => callback ());
+
+                       return () => Task.WaitAll (tasks, options.Token);
+               }
+
+               internal static Action ProcessAndCallback<T> (QueryBaseNode<T> node, Action<KeyValuePair<long, T>> call,
+                                                             Action callback, QueryOptions options)
+               {
+                       return ProcessAndCallback<T> (node, call, null, callback, options);
+               }
+
+               internal static Action ProcessAndCallback<T> (QueryBaseNode<T> node, Action<KeyValuePair<long, T>> call,
+                                                             Action endAction,
+                                                             Action callback, QueryOptions options)
+               {
+                       Task[] tasks = Process (node, call, (n, o) => n.GetOrderedEnumerables (o), endAction, options);
+                       Task.Factory.ContinueWhenAll (tasks,  (_) => callback ());
+
+                       return () => Task.WaitAll (tasks, options.Token);
+               }
+
+               internal static void ProcessAndAggregate<T, U> (QueryBaseNode<T> node,
+                                                   Func<U> seedFunc,
+                                                   Func<U, T, U> localCall,
+                                                   Action<IList<U>> call)
+               {
+                       QueryOptions options = CheckQuery (node, true);
+
+                       IList<IEnumerable<T>> enumerables = node.GetEnumerables (options);
+                       U[] locals = new U[enumerables.Count];
+                       Task[] tasks = new Task[enumerables.Count];
+
+                       bool init = false;
+                       if (seedFunc != null) {
+                               for (int i = 0; i < locals.Length; i++)
+                                       locals[i] = seedFunc ();
+                               init = true;
+                       }
+
+                       for (int i = 0; i < tasks.Length; i++) {
+                               int index = i;
+                               tasks[i] = Task.Factory.StartNew (() => {
+                                       foreach (T item in enumerables[index]) {
+                                               // This is from specific operators
+                                               if (options.ImplementerToken.IsCancellationRequested)
+                                                       break;
+                                               if (options.Token.IsCancellationRequested)
+                                                       throw new OperationCanceledException (options.Token);
+
+                                               if (!init) {
+                                                       init = true;
+                                                       // HACK: TODO: omfwtfitsomuchsucks
+                                                       locals[index] = (U)(object)item;
+                                                       continue;
+                                               }
+                                               
+                                               U acc = locals[index];
+                                               locals[index] = localCall (acc, item);
+                                       }
+                               }, options.Token);
+                       }
+
+                       Task.WaitAll (tasks, options.Token);
+
+                       if (call != null)
+                               call (locals);
+               }
+       }
+}
+#endif
\ No newline at end of file
diff --git a/mcs/class/System.Core/System.Linq/ParallelExecutionMode.cs b/mcs/class/System.Core/System.Linq/ParallelExecutionMode.cs
new file mode 100644 (file)
index 0000000..b3c51f7
--- /dev/null
@@ -0,0 +1,38 @@
+#if NET_4_0
+//
+// ParallelExecutionMode.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace System.Linq
+{
+       public enum ParallelExecutionMode
+       {
+               Default = 0,
+               ForceParallelism = 1
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/ParallelMergeOptions.cs b/mcs/class/System.Core/System.Linq/ParallelMergeOptions.cs
new file mode 100644 (file)
index 0000000..0adea44
--- /dev/null
@@ -0,0 +1,40 @@
+#if NET_4_0
+//
+// ParallelMergeOptions.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+
+namespace System.Linq
+{
+       public enum ParallelMergeOptions
+       {
+               Default = 0,
+               NotBuffered,
+               AutoBuffered,
+               FullyBuffered
+       }
+}
+#endif
\ No newline at end of file
diff --git a/mcs/class/System.Core/System.Linq/ParallelPartitioner.cs b/mcs/class/System.Core/System.Linq/ParallelPartitioner.cs
new file mode 100644 (file)
index 0000000..50d6235
--- /dev/null
@@ -0,0 +1,76 @@
+//
+// ParallelPartitioner.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Collections.Generic;
+using System.Collections.Concurrent;
+
+#if NET_4_0
+
+namespace System.Linq
+{
+       internal static class ParallelPartitioner
+       {
+               internal static OrderablePartitioner<T> CreateForChunks<T> (IEnumerable<T> source)
+               {
+                       return Partitioner.Create (source);
+               }
+
+               internal static OrderablePartitioner<T> CreateForRange<T> (IList<T> source)
+               {
+                       return Partitioner.Create (source, true);
+               }
+
+               internal static OrderablePartitioner<T> CreateBest<T> (IEnumerable<T> source)
+               {
+                       IList<T> temp = source as IList<T>;
+                       if (temp != null)
+                               return CreateForRange (temp);
+
+                       return CreateForChunks (source);
+               }
+
+               internal static OrderablePartitioner<T> CreateForStrips<T> (IEnumerable<T> source, int stripSize)
+               {
+                       IList<T> temp = source as IList<T>;
+                       if (temp != null)
+                               return new StripPartitioner<T> (temp);
+
+                       return new EnumerablePartitioner<T> (source, stripSize, 1);
+               }
+
+               internal static OrderablePartitioner<int> CreateForRange (int start, int count)
+               {
+                       return CreateForRange<int> (new RangeList (start, count));
+               }
+
+               internal static OrderablePartitioner<T> CreateForRepeat<T> (T obj, int count)
+               {
+                       return CreateForRange<T> (new RepeatList<T> (obj, count));
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/ParallelQuery.cs b/mcs/class/System.Core/System.Linq/ParallelQuery.cs
new file mode 100644 (file)
index 0000000..6d99813
--- /dev/null
@@ -0,0 +1,125 @@
+//
+// ParallelQuery.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.Concurrent;
+
+#if NET_4_0
+
+namespace System.Linq
+{
+       public class ParallelQuery : IEnumerable
+       {
+               ParallelExecutionMode execMode = ParallelExecutionMode.Default;
+               ParallelMergeOptions mergeOptions = ParallelMergeOptions.Default;
+
+               internal ParallelQuery ()
+               {
+
+               }
+
+               internal ParallelMergeOptions MergeOptions {
+                       get {
+                               return mergeOptions;
+                       }
+                       set {
+                               mergeOptions = value;
+                       }
+               }
+
+               internal ParallelExecutionMode ExecMode {
+                       get {
+                               return execMode;
+                       }
+                       set {
+                               execMode = value;
+                       }
+               }
+
+               IEnumerator IEnumerable.GetEnumerator ()
+               {
+                       return GetEnumeratorTrick ();
+               }
+
+               // Trick to get the correct IEnumerator from ParallelQuery<TSource>
+               internal virtual IEnumerator GetEnumeratorTrick ()
+               {
+                       return null;
+               }
+               
+               internal virtual ParallelQuery<object> TypedQuery {
+                       get {
+                               return null;
+                       }
+               }
+       }
+
+       public class ParallelQuery<TSource> : ParallelQuery, IEnumerable<TSource>, IEnumerable
+       {
+               QueryBaseNode<TSource> node;
+
+               internal ParallelQuery (QueryBaseNode<TSource> node)
+               {
+                       this.node = node;
+               }
+
+               internal QueryBaseNode<TSource> Node {
+                       get {
+                               return node;
+                       }
+               }
+
+               public virtual IEnumerator<TSource> GetEnumerator ()
+               {
+                       return GetEnumeratorInternal ();
+               }
+
+               IEnumerator IEnumerable.GetEnumerator ()
+               {
+                       return (IEnumerator)GetEnumeratorInternal ();
+               }
+
+               IEnumerator<TSource> GetEnumeratorInternal ()
+               {
+                       return new ParallelQueryEnumerator<TSource> (node);
+               }
+
+               internal override IEnumerator GetEnumeratorTrick ()
+               {
+                       return (IEnumerator)GetEnumeratorInternal ();
+               }
+               
+               internal override ParallelQuery<object> TypedQuery {
+                       get {
+                               return new ParallelQuery<object> (new QueryCastNode<TSource> (node));
+                       }
+               }
+       }
+}
+#endif
diff --git a/mcs/class/System.Core/System.Linq/ParallelQueryEnumerator.cs b/mcs/class/System.Core/System.Linq/ParallelQueryEnumerator.cs
new file mode 100644 (file)
index 0000000..d40d20e
--- /dev/null
@@ -0,0 +1,128 @@
+//
+// ParallelEnumerator.cs
+//
+// Author:
+//       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
+//
+// Copyright (c) 2010 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+using System;
+using System.Threading;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.Concurrent;
+
+#if NET_4_0
+
+namespace System.Linq
+{
+       internal class ParallelQueryEnumerator<T> : IEnumerator<T>
+       {
+               readonly int DefaultBufferSize = ParallelExecuter.GetBestWorkerNumber () * 50;
+
+               BlockingCollection<T> buffer;
+               IEnumerator<T> loader;
+               QueryOptions options;
+               OrderingEnumerator<T> ordEnumerator;
+
+               T current;
+
+               Action waitAction;
+
+               internal ParallelQueryEnumerator (QueryBaseNode<T> node)
+               {
+                       this.options = ParallelExecuter.CheckQuery (node);
+                       Setup ();
+
+                       // Launch adding to the buffer asynchronously via Tasks
+                       if (options.BehindOrderGuard.Value) {
+                               // Keep fairness between tasks (i.e. the same task don't ruin order by adding to much of its own)
+                               Barrier barrier = new Barrier (options.PartitionCount);
+                               waitAction = ParallelExecuter.ProcessAndCallback (node,
+                                                                                 (e) => { ordEnumerator.KeyedBuffer.Add (e); barrier.SignalAndWait (); },
+                                                                                 barrier.RemoveParticipant,
+                                                                                 ordEnumerator.KeyedBuffer.CompleteAdding,
+                                                                                 options);
+                       } else {
+                               waitAction = ParallelExecuter.ProcessAndCallback (node,
+                                                                                 buffer.Add,
+                                                                                 buffer.CompleteAdding,
+                                                                                 options);
+                       }
+
+                       if (options.Options.HasValue && options.Options.Value == ParallelMergeOptions.FullyBuffered)
+                               waitAction ();
+               }
+
+               void Setup ()
+               {
+                       if (!options.BehindOrderGuard.Value) {
+                               if (options.Options.HasValue && (options.Options.Value == ParallelMergeOptions.NotBuffered
+                                                                || options.Options.Value == ParallelMergeOptions.FullyBuffered)) {
+                                       buffer = new BlockingCollection<T> ();
+                               } else {
+                                       buffer = new BlockingCollection<T> (DefaultBufferSize);
+                               }
+
+                               IEnumerable<T> source = buffer.GetConsumingEnumerable (options.Token);
+
+                               loader = source.GetEnumerator ();
+                       } else {
+                               loader = ordEnumerator = new OrderingEnumerator<T> (options.PartitionCount);
+                       }
+               }
+
+               public void Dispose ()
+               {
+
+               }
+
+               public void Reset ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public bool MoveNext ()
+               {
+                       // If there are no stuff in the buffer
+                       // but CompleteAdding hasn't been called,
+                       // MoveNext blocks until further results are produced
+                       if (!loader.MoveNext ())
+                               return false;
+
+                       current = loader.Current;
+                       return true;
+               }
+
+               public T Current {
+                       get {
+                               return current;
+                       }
+               }
+
+               object IEnumerator.Current {
+                       get {
+                               return current;
+                       }
+               }
+       }
+}
+#endif
index 4aaccdff3bb1a278acca9297256017fd1c1ee7a2..a4830add0ddb650b4606de1eaa59c5273a2f433a 100644 (file)
@@ -1604,5 +1604,23 @@ namespace System.Linq {
 
                #endregion
 
+#if NET_4_0
+               #region Zip
+
+               public static IQueryable<TResult> Zip<TFirst, TSecond, TResult> (this IQueryable<TFirst> source1, IEnumerable<TSecond> source2, Expression<Func<TFirst, TSecond, TResult>> resultSelector)
+               {
+                       Check.Source1AndSource2 (source1, source2);
+                       if (resultSelector == null)
+                               throw new ArgumentNullException ("resultSelector");
+
+                       return source1.Provider.CreateQuery<TResult> (
+                               StaticCall (
+                                       MakeGeneric (MethodBase.GetCurrentMethod (), typeof (TFirst), typeof (TSecond), typeof (TResult)),
+                                       source1.Expression,
+                                       Expression.Quote (resultSelector)));
+               }
+
+               #endregion
+#endif
        }
 }
index f8ad6d115f46bc4ddc55883b2d8e38b3e17cae6d..34046f0a5248fb53c853bd04a74d007be95bf6de 100644 (file)
@@ -100,11 +100,7 @@ namespace System.Linq {
 
                static Expression TransformQueryable (Expression expression)
                {
-#if NET_4_0 || BOOTSTRAP_NET_4_0
-                       throw new NotImplementedException ();
-#else                                          
                        return new QueryableTransformer ().Transform (expression);
-#endif
                }
 
                public IQueryable<TElem> CreateQuery<TElem> (Expression expression)
index 4a3685898e9a553d97a2aa1ae7f1a584e7315e07..307045f7c39a186e893d45df48bcdf4a3471e040 100644 (file)
@@ -89,7 +89,7 @@ namespace System.Linq {
                                        parameters [i].ParameterType);
                        }
 
-                       return new MethodCallExpression (target, method, arguments.ToReadOnlyCollection ());
+                       return Expression.Call (target, method, arguments);
                }
 
                static Expression UnquoteIfNeeded (Expression expression, Type delegateType)
index 2ec42114a4105d8c26865a31216a0db16b214869..a25427e60cbce19b2f6b5c60f8d89b09d3a4042f 100644 (file)
@@ -62,8 +62,10 @@ namespace System.Linq {
                        if (comparison == 0) {
                                if (child_context != null)
                                        return child_context.Compare (first_index, second_index);
-                               else
-                                       comparison = first_index - second_index;
+
+                               comparison = direction == SortDirection.Descending
+                                       ? second_index - first_index
+                                       : first_index - second_index;
                        }
 
                        return direction == SortDirection.Descending ? -comparison : comparison;
index 2d9f7e078476423523d387d28a798230b1f3888d..618551dcc1536c098cf7aee435c0e802aceba50d 100644 (file)
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0
 
 using System;
 using System.Collections.Generic;
index 3c7da47c1d2c08bc168aacd379127a1dfd60b1ac..eaee476a5005b273ce30f724f51c3036ed336663 100644 (file)
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
+
+// Since 4.0 (both FX and SL) this type is defined in mscorlib - before 4.0 it was in System.Core.dll
+#if (INSIDE_CORLIB && (NET_4_0 || BOOTSTRAP_NET_4_0 || MOONLIGHT)) || (!INSIDE_CORLIB && !NET_4_0 && !BOOTSTRAP_NET_4_0 && !MOONLIGHT)
 \r
+using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
 \r
 namespace System.Security.Cryptography {\r
@@ -37,12 +41,22 @@ namespace System.Security.Cryptography {
        // References:
        // a.   FIPS PUB 197: Advanced Encryption Standard
        //      http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf
-\r
+
+#if INSIDE_CORLIB
+       // since 4.0 (both FX and SL) this type now resides inside mscorlib.dll and link back to System.Core.dll\r
+       #if MOONLIGHT
+       // version has not changed between SL3 (System.Core) and SL4
+       [TypeForwardedFrom (Consts.AssemblySystem_Core)]
+       #elif NET_4_0 || BOOTSTRAP_NET_4_0
+       // use 3.5 version
+       [TypeForwardedFrom ("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
+       #endif
+#endif
        public abstract class Aes : SymmetricAlgorithm {\r
-\r
+
                public static new Aes Create () \r
                {\r
-               return Create ("System.Security.Cryptography.AesManaged, " + Consts.AssemblySystem_Core);\r
+                       return Create ("System.Security.Cryptography.AesManaged, " + Consts.AssemblySystem_Core);\r
                }\r
 \r
                public static new Aes Create (string algName) \r
@@ -66,3 +80,5 @@ namespace System.Security.Cryptography {
                }\r
        }\r
 }\r
+#endif
+
index b25f7385f60b68ee331d8e44cedf6bcd79d0e2d9..aef59b427ec3fac81203f7346687a45ed2b34016 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-18  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * Aes.cs: Build here before NET_4_0 (or MOONLIGHT) otherwise 
+       build only if compiled from mscorlib.dll
+
 2009-11-12  Jb Evain  <jbevain@novell.com>
 
        * Aes.cs: avoid using an hardcoded assembly version for System.Core.
index f2a1126214b10806c04da68ba8c5c05b3287f60f..5100db90a02453986bcce04fe65854f92168c880 100644 (file)
@@ -4,7 +4,7 @@
 // Authors:
 //     Marek Safar  <marek.safar@gmail.com>
 //
-// Copyright (C) 2007 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2007, 2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_4_0 || BOOTSTRAP_NET_4_0
 using System;
 using System.Runtime.CompilerServices;
 
+#if NET_4_0 || BOOTSTRAP_NET_4_0
 [assembly:TypeForwardedTo (typeof(Action<>))]
 [assembly:TypeForwardedTo (typeof(Action<,>))]
 [assembly:TypeForwardedTo (typeof(Action<,,>))]
 [assembly:TypeForwardedTo (typeof(Action<,,,>))]
+#elif MOONLIGHT
+[assembly:TypeForwardedTo (typeof (Action))]
 #endif
 
 namespace System
@@ -62,6 +64,28 @@ namespace System
 
        public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16> (
                T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16);
+#elif MOONLIGHT
+       // Action, Action<T> are defined in mscorlib.dll for SL4
+       public delegate void Action <T1, T2> (T1 arg1, T2 arg2);
+       public delegate void Action <T1, T2, T3> (T1 arg1, T2 arg2, T3 arg3);
+       public delegate void Action <T1, T2, T3, T4> (T1 arg1, T2 arg2, T3 arg3, T4 arg4);
+       // Action<T1..T5> to <T1..T8> are defined in mscorlib.dll for SL4
+       public delegate void Action <T1, T2, T3, T4, T5, T6, T7, T8, T9> (
+               T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9);
+       public delegate void Action <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> (
+               T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10);
+       public delegate void Action <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> (
+               T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11);
+       public delegate void Action <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> (
+               T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12);
+       public delegate void Action <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> (
+               T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13);
+       public delegate void Action <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> (
+               T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14);
+       public delegate void Action <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> (
+               T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15);
+       public delegate void Action <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> (
+               T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16);
 #else
        public delegate void Action ();
        public delegate void Action<T1, T2> (T1 arg1, T2 arg2);
index 5c645381de7c42e3505c0cfbc4461c43e5e3fbf9..30442613a91c25ef6b25835cf07b25c4419d2e69 100644 (file)
@@ -1,3 +1,26 @@
+2010-04-16  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * Actions.cs: Forward Action() to mscorlib.dll and add the new
+       Action<...T16> delegates
+       * Funcs.cs: Add the new Func<...T16> delegates
+       * TimeZoneInfo.cs: Forward to mscorlib.dll
+
+2010-03-30  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * InvalidTimeZoneException.cs
+       * TimeZoneInfo.AdjustmentRule.cs
+       * TimeZoneInfo.cs
+       * TimeZoneInfo.TransitionTime.cs
+       * TimeZoneNotFoundException.cs:
+               Fix Moonlight since these types now reside in mscorlib 
+               for NET_4_0 and also for SL4
+
+2010-03-30  Jb Evain  <jbevain@novell.com>
+
+       * TimeZoneInfo.AdjustmentRule.cs
+       * TimeZoneInfo.TransitionTime.cs:
+               Add TypeForwarderFrom attributes.
+
 2010-01-04  Jb Evain  <jbevain@novell.com>
 
        * TimeZoneInfo.AdjustmentRule.cs, TimeZoneInfo.TransitionTime.cs:
index c42b582a64362691c01458fad154e3d80b29eeb2..f12496d1619d4e0fcea60d4e70578b17af6d4bc6 100644 (file)
@@ -68,5 +68,33 @@ namespace System
        public delegate TResult Func<T1, T2, TResult> (T1 arg1, T2 arg2);
        public delegate TResult Func<T1, T2, T3, TResult> (T1 arg1, T2 arg2, T3 arg3);
        public delegate TResult Func<T1, T2, T3, T4, TResult> (T1 arg1, T2 arg2, T3 arg3, T4 arg4);
+
+       #if MOONLIGHT
+       // Func<T1..T5,Result> to >T1..T8,TResult> are defined in mscorlib.dll for SL4
+
+       public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> (
+               T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9);
+
+       public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult> (
+               T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10);
+
+       public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult> (
+               T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11);
+
+       public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult> (
+               T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12);
+
+       public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult> (
+               T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13);
+
+       public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult> (
+               T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14);
+
+       public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult> (
+               T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15);
+
+       public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TResult> (
+               T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16);
+       #endif
 #endif
 }
index 465ba4f1b174b760683f1170bcc6d472cd3b0687..50ff757d024c2f8e057a45f1760ecb019885ccc8 100644 (file)
@@ -24,7 +24,7 @@
  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  */
 
-#if NET_4_0 || BOOTSTRAP_NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0 || MOONLIGHT
 
 using System;
 using System.Runtime.CompilerServices;
index ad45b1827ead982a1250a135c803a6af774b13ee..1ec0e11244a15c2bf54d94b135580d3f91bc161c 100644 (file)
  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  */
 
-#if (INSIDE_CORLIB && NET_4_0) || (NET_2_1 && !INSIDE_CORLIB) || (NET_3_5 && !NET_4_0 && !BOOTSTRAP_NET_4_0)
+#if (INSIDE_CORLIB && (NET_4_0 || MOONLIGHT)) || (MONOTOUCH && !INSIDE_CORLIB) || (NET_3_5 && !NET_4_0 && !BOOTSTRAP_NET_4_0)
 
+using System.Runtime.CompilerServices;
 using System.Runtime.Serialization;
 
 namespace System
 {
        public sealed partial class TimeZoneInfo {
                [SerializableAttribute]
+#if NET_4_0 || BOOTSTRAP_NET_4_0
+               [TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
+#elif MOONLIGHT
+               [TypeForwardedFrom (Consts.AssemblySystem_Core)]
+#endif
                public sealed class AdjustmentRule : IEquatable<TimeZoneInfo.AdjustmentRule>, ISerializable, IDeserializationCallback
                {
                        DateTime dateEnd;
index 491a07b61dbf15558c3654257ca8d5028471b0af..72eca19ad2cbcba2bf4479ae139e76f8a7c5c3fe 100644 (file)
@@ -24,8 +24,9 @@
  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  */
 
-#if (INSIDE_CORLIB && (NET_4_0 || BOOTSTRAP_NET_4_0)) || (NET_2_1 && !INSIDE_CORLIB) || (NET_3_5 && !NET_4_0 && !BOOTSTRAP_NET_4_0)
+#if (INSIDE_CORLIB && (NET_4_0 || BOOTSTRAP_NET_4_0 || MOONLIGHT)) || (MONOTOUCH && !INSIDE_CORLIB) || (NET_3_5 && !NET_4_0 && !BOOTSTRAP_NET_4_0)
 
+using System.Runtime.CompilerServices;
 using System.Runtime.Serialization;
 
 namespace System
@@ -33,6 +34,11 @@ namespace System
        public sealed partial class TimeZoneInfo 
        {
                [SerializableAttribute]
+#if NET_4_0 || BOOTSTRAP_NET_4_0
+               [TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
+#elif MOONLIGHT
+               [TypeForwardedFrom (Consts.AssemblySystem_Core)]
+#endif
                public struct TransitionTime : IEquatable<TimeZoneInfo.TransitionTime>, ISerializable, IDeserializationCallback
                {
                        DateTime timeOfDay;
index d6d7fa27797f5af4f031e23eb4b81ab2c6ae7796..da0d94fc0003a5a1c68c786825d894dc53133f1f 100644 (file)
 using System;
 using System.Runtime.CompilerServices;
 
-#if !INSIDE_CORLIB && (NET_4_0 || BOOTSTRAP_NET_4_0)
+#if !INSIDE_CORLIB && (NET_4_0 || BOOTSTRAP_NET_4_0 || MOONLIGHT)
 
 [assembly:TypeForwardedTo (typeof(TimeZoneInfo))]
 
-#elif NET_3_5 || (NET_2_1 && !INSIDE_CORLIB)
+#elif NET_3_5 || (MONOTOUCH && !INSIDE_CORLIB) || (MOONLIGHT && INSIDE_CORLIB)
 
 using System.Collections.Generic;
 using System.Collections.ObjectModel;
@@ -45,9 +45,11 @@ using Mono;
 
 namespace System
 {
-#if NET_4_0 || BOOTSRAP_NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0
        [TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
-#endif 
+#elif MOONLIGHT
+       [TypeForwardedFrom (Consts.AssemblySystem_Core)]
+#endif
        [SerializableAttribute]
        public sealed partial class TimeZoneInfo : IEquatable<TimeZoneInfo>, ISerializable, IDeserializationCallback
        {
index accedf33327bda63798218c89c7610527e010d9f..8691e73ac007e699ec11648305b47b2a1afb17f1 100644 (file)
@@ -24,7 +24,7 @@
  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  */
 
-#if NET_4_0 || BOOTSTRAP_NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0 || MOONLIGHT
 
 using System;
 using System.Runtime.CompilerServices;
index 200f5247d9c4cb93ac8fee4a574211f69a15d4c1..d524e80f5c1e12998c9bb67ccc3e6eeb915fca16 100644 (file)
@@ -47,18 +47,25 @@ namespace MonoTests.System.Linq.Expressions {
                        Expression.GetFuncType (null);
                }
 
+               static Type [] GetTestTypeArray (int length)
+               {
+                       return Enumerable.Range (0, length - 1)
+                               .Select (i => typeof (int))
+                               .ToArray ();
+               }
+
                [Test]
                [ExpectedException (typeof (ArgumentException))]
                public void GetFuncTypeArgEmpty ()
                {
-                       Expression.GetFuncType (new Type [0]);
+                       Expression.GetFuncType (Type.EmptyTypes);
                }
 
                [Test]
                [ExpectedException (typeof (ArgumentException))]
                public void GetFuncTypeArgTooBig ()
                {
-                       Expression.GetFuncType (new Type [6]);
+                       Expression.GetFuncType (GetTestTypeArray (64));
                }
 
                [Test]
@@ -91,7 +98,7 @@ namespace MonoTests.System.Linq.Expressions {
                [ExpectedException (typeof (ArgumentException))]
                public void GetActionTypeArgTooBig ()
                {
-                       Expression.GetActionType (new Type [5]);
+                       Expression.GetActionType (GetTestTypeArray (45));
                }
 
                [Test]
@@ -126,7 +133,9 @@ namespace MonoTests.System.Linq.Expressions {
                        var p = Expression.Parameter (typeof (string), null);
                        Assert.AreEqual (null, p.Name);
                        Assert.AreEqual (typeof (string), p.Type);
+#if !NET_4_0
                        Assert.AreEqual ("<param>", p.ToString ());
+#endif
                }
 
                [Test]
@@ -135,7 +144,9 @@ namespace MonoTests.System.Linq.Expressions {
                        var p = Expression.Parameter (typeof (string), "");
                        Assert.AreEqual ("", p.Name);
                        Assert.AreEqual (typeof (string), p.Type);
+#if !NET_4_0
                        Assert.AreEqual ("", p.ToString ());
+#endif
                }
 
                [Test]
index 3f8fe6067a48be0a31d13f97610e4ff512218d5d..d56fe5e933afce27668db069684f0e039356d30b 100644 (file)
@@ -194,11 +194,12 @@ namespace MonoTests.System.Linq.Expressions
                        // These are invalid:
                        InvalidOperation<byte> (Byte.MaxValue, 2);
                        InvalidOperation<sbyte> (SByte.MaxValue, 2);
-
+#if !NET_4_0
                        // Stuff that just fits in 32 bits, does not overflow:
                        MustNotOverflow<short> (Int16.MaxValue, 2);
+                       MustNotOverflow<short> (Int16.MaxValue, 2);
                        MustNotOverflow<ushort> (UInt16.MaxValue, 2);
-
+#endif
                        // Doubles, floats, do not overflow
                        MustNotOverflow<float> (Single.MaxValue, 1);
                        MustNotOverflow<double> (Double.MaxValue, 1);
index 2368e07dcbe1c2203f84d92b3b06c9c5940ac7a7..27a7e2ec3e7bea0dd1fd727152f7e343c10fd104 100644 (file)
@@ -80,7 +80,9 @@ namespace MonoTests.System.Linq.Expressions
                        Assert.AreEqual (ExpressionType.AndAlso, expr.NodeType, "AndAlso#01");
                        Assert.AreEqual (typeof (bool), expr.Type, "AndAlso#02");
                        Assert.IsNull (expr.Method, "AndAlso#03");
+#if !NET_4_0
                        Assert.AreEqual ("(True && False)", expr.ToString(), "AndAlso#04");
+#endif
                }
 
                [Test]
@@ -95,8 +97,10 @@ namespace MonoTests.System.Linq.Expressions
                        Assert.AreEqual (typeof (OpClass), expr.Type, "AndAlso#06");
                        Assert.AreEqual (mi, expr.Method, "AndAlso#07");
                        Assert.AreEqual ("op_BitwiseAnd", expr.Method.Name, "AndAlso#08");
+#if !NET_4_0
                        Assert.AreEqual ("(value(MonoTests.System.Linq.Expressions.OpClass) && value(MonoTests.System.Linq.Expressions.OpClass))",
                                expr.ToString(), "AndAlso#09");
+#endif
                }
 
                [Test]
index 25125c8850c04a357b02aec4e9b111b34e126e53..8f668d288ab00b6908fd60f63b958e17f153b2f3 100644 (file)
@@ -87,7 +87,11 @@ namespace MonoTests.System.Linq.Expressions {
                }
 
                [Test]
+#if NET_4_0
+               [ExpectedException (typeof (ArgumentException))]
+#else
                [ExpectedException (typeof (ArgumentNullException))]
+#endif
                public void ArgInstanceNullForNonStaticMethod ()
                {
                        Expression.Call (null, typeof (object).GetMethod ("ToString"));
@@ -281,7 +285,7 @@ namespace MonoTests.System.Linq.Expressions {
                {
                        return (int) (i as ConstantExpression).Value;
                }
-
+#if !NET_4_0 // dlr bug 5875
                [Test]
                public void CallMethodWithExpressionParameter ()
                {
@@ -292,7 +296,7 @@ namespace MonoTests.System.Linq.Expressions {
 
                        Assert.AreEqual (42, l ());
                }
-
+#endif
                static bool fout_called = false;
 
                public static int FooOut (out int x)
index 44e61ca82248a13084638dca055e493b73a101b1..9b9d4d9e5422349c94abbe7df09a901894aad515 100644 (file)
@@ -81,13 +81,16 @@ namespace MonoTests.System.Linq.Expressions {
 
                        var conv = Expression.Convert (p, typeof (ITzap));
                        Assert.AreEqual (typeof (ITzap), conv.Type);
+#if !NET_4_0
                        Assert.AreEqual ("Convert(<param>)", conv.ToString ());
-
+#endif
                        p = Expression.Parameter (typeof (ITzap), null);
                        conv = Expression.Convert (p, typeof (IFoo));
 
                        Assert.AreEqual (typeof (IFoo), conv.Type);
+#if !NET_4_0
                        Assert.AreEqual ("Convert(<param>)", conv.ToString ());
+#endif
                }
 
                [Test]
index ca3ff35f849d486039cb092cecfe7bc6d6014251..06612bdfa1820c312c899e87bfc69b27cde54db3 100644 (file)
@@ -76,7 +76,9 @@ namespace MonoTests.System.Linq.Expressions
                        Assert.AreEqual (ExpressionType.Equal, expr.NodeType);
                        Assert.AreEqual (typeof (bool), expr.Type);
                        Assert.IsNull (expr.Method);
+#if !NET_4_0
                        Assert.AreEqual ("(1 = 2)", expr.ToString ());
+#endif
                }
 
                [Test]
@@ -93,7 +95,9 @@ namespace MonoTests.System.Linq.Expressions
                        Assert.AreEqual (true, expr.IsLifted);
                        Assert.AreEqual (false, expr.IsLiftedToNull);
                        Assert.IsNull (expr.Method);
+#if !NET_4_0
                        Assert.AreEqual ("(1 = 2)", expr.ToString ());
+#endif
                }
 
                [Test]
@@ -110,7 +114,9 @@ namespace MonoTests.System.Linq.Expressions
                        Assert.AreEqual (true, expr.IsLifted);
                        Assert.AreEqual (true, expr.IsLiftedToNull);
                        Assert.IsNull (expr.Method);
+#if !NET_4_0
                        Assert.AreEqual ("(1 = 2)", expr.ToString ());
+#endif
                }
 
                [Test]
@@ -136,8 +142,9 @@ namespace MonoTests.System.Linq.Expressions
                        Assert.AreEqual (typeof (bool), expr.Type);
                        Assert.AreEqual (mi, expr.Method);
                        Assert.AreEqual ("op_Equality", expr.Method.Name);
-
+#if !NET_4_0
                        Assert.AreEqual ("(value(MonoTests.System.Linq.Expressions.OpClass) = value(MonoTests.System.Linq.Expressions.OpClass))", expr.ToString ());
+#endif
                }
 
                [Test]
index 08a5c7c28111f23d65931d9d676b28cf0d542deb..8c83e312ec13b1abf17b93da7e581be6468b1e24 100644 (file)
@@ -239,7 +239,6 @@ namespace MonoTests.System.Linq.Expressions
                }
 
                [Test]
-               [Category ("NotWorking")]
                public void NestedParentParameterUse ()
                {
                        var a = Expression.Parameter (typeof (int), null);
@@ -268,7 +267,7 @@ namespace MonoTests.System.Linq.Expressions
 
                        Assert.AreEqual (5, l (1));
                }
-
+#if !NET_4_0 // dlr bug 5875
                [Test]
                public void LambdaReturningExpression ()
                {
@@ -281,5 +280,6 @@ namespace MonoTests.System.Linq.Expressions
 
                        Assert.AreEqual (ExpressionType.Constant, q.NodeType);
                }
+#endif
        }
 }
index 5cdf17de1f7dd16d70eb3d145f764a0729088b0f..873dd0d0e27da8eedad817a64d8229163341eee6 100644 (file)
@@ -80,7 +80,9 @@ namespace MonoTests.System.Linq.Expressions
                        Assert.AreEqual (ExpressionType.OrElse, expr.NodeType, "OrElse#01");
                        Assert.AreEqual (typeof (bool), expr.Type, "OrElse#02");
                        Assert.IsNull (expr.Method, "OrElse#03");
+#if !NET_4_0
                        Assert.AreEqual ("(True || False)", expr.ToString(), "OrElse#04");
+#endif
                }
 
                [Test]
@@ -95,8 +97,10 @@ namespace MonoTests.System.Linq.Expressions
                        Assert.AreEqual (typeof (OpClass), expr.Type, "OrElse#06");
                        Assert.AreEqual (mi, expr.Method, "OrElse#07");
                        Assert.AreEqual ("op_BitwiseOr", expr.Method.Name, "OrElse#08");
+#if !NET_4_0
                        Assert.AreEqual ("(value(MonoTests.System.Linq.Expressions.OpClass) || value(MonoTests.System.Linq.Expressions.OpClass))",
                                expr.ToString(), "OrElse#09");
+#endif
                }
 
                public class BrokenMethod {
@@ -276,7 +280,7 @@ namespace MonoTests.System.Linq.Expressions
                        Assert.AreEqual (new Slot (64), orelse (new Slot (64), new Slot (64)));
                        Assert.AreEqual (new Slot (32), orelse (new Slot (32), new Slot (64)));
                }
-
+#if !NET_4_0 // dlr bug 5867
                [Test]
                public void UserDefinedOrElseLiftedToNull ()
                {
@@ -298,7 +302,7 @@ namespace MonoTests.System.Linq.Expressions
                        Assert.AreEqual (new Slot (32), orelse (new Slot (32), null));
                        Assert.AreEqual (null, orelse (null, null));
                }
-
+#endif
                [Test]
                public void UserDefinedOrElseShortCircuit ()
                {
index b95f542121df6903fe487fbcbb34fcc255e2e87b..fedaa5f7ab9041bfb4510501a7dc223063b96bfe 100644 (file)
@@ -37,14 +37,23 @@ namespace MonoTests.System.Linq.Expressions
                        Expression.Quote (null);
                }
 
+#if !NET_4_0
                [Test]
-               public void Constant ()
+               public void QuoteConstant ()
                {
                        UnaryExpression expr = Expression.Quote (Expression.Constant (1));
                        Assert.AreEqual (ExpressionType.Quote, expr.NodeType, "Quote#01");
                        Assert.AreEqual (typeof (ConstantExpression), expr.Type, "Quote#02");
                        Assert.AreEqual ("1", expr.ToString(), "Quote#03");
                }
+#else
+               [Test]
+               [ExpectedException (typeof (ArgumentException))]
+               public void QuoteConstant ()
+               {
+                       Expression.Quote (Expression.Constant (1));
+               }
+#endif
 
                [Test]
                public void CompiledQuote ()
index 393935ad1f83c353251236b578f284a5fe9e4f8d..cbb41f4edf6c45fdda6f91b548a5cb70b89438f1 100644 (file)
@@ -184,6 +184,7 @@ namespace MonoTests.System.Linq.Expressions
                        MustOverflow<uint>  (0, 1);
                }
 
+#if !NET_4_0 // fixed in net_4_0
                [Test]
                public void TestBugCompatibility ()
                {
@@ -191,6 +192,7 @@ namespace MonoTests.System.Linq.Expressions
                        // Sounds very odd, should file a bug with MS.
                        MustNotOverflow<short> (Int16.MinValue, 1);
                }
+#endif
 
                //
                // These should not overflow
index 914aaa5c341d7b3945c9174ae58bb192bc33b905..91fd32e6596816c15c17153285991e5499fe2cb4 100644 (file)
@@ -104,6 +104,7 @@ namespace MonoTests.System.Linq.Expressions
                        Assert.IsTrue (baz_is_bar (new Baz ()));
                }
 
+#if !NET_4_0 // dlr bug 5868
                [Test]
                [Category ("NotDotNet")]
                [ExpectedException (typeof (ArgumentException))]
@@ -111,6 +112,7 @@ namespace MonoTests.System.Linq.Expressions
                {
                        Expression.TypeIs ("yoyo".ToConstant (), typeof (void));
                }
+#endif
 
                public static void TacTac ()
                {
index 2a8b2b7f85824665d367d69a132d865be82c70da..a53f51058c4934256999405ee985ead904fb2443 100644 (file)
@@ -1,3 +1,21 @@
+2010-04-23  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * ParallelEnumerableTests.cs: Fix namespace, add NET_4_0 #ifdef
+       * ParallelTestHelper.cs: Fix namespace
+
+2010-04-15  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * ParallelEnumerableTests.cs: Tweak Skip unit test to avoid deadlocking for now
+
+2010-04-15  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * ParallelEnumerableTests.cs:
+       * ParallelTestHelper.cs: Add PLinq unit tests
+
+2010-03-24  Jb Evain  <jbevain@novell.com>
+
+       * EnumerableTest.cs: add test for #582502.
+
 2009-11-12  Eric Maupin  <me@ermau.com>
 
        * EnumerableMoreTest.cs: Added ToLookup test for null keys, updated old test to check count.
index addc5438c7f43ec9f289fd46c2df2f9225848693..26655c56dfd9912aeb5bc477eb4cca1e4628f87a 100644 (file)
@@ -334,6 +334,21 @@ namespace MonoTests.System.Linq {
                        Assert.AreEqual (23.25, (new long [] { 24, 7, 28, 34 }).Average ());
                }
 
+               [Test]
+               public void TestAverageInt32 ()
+               {
+                       // This does not overflow, computation is done with longs
+                       var x = new int [] { Int32.MaxValue, Int32.MaxValue };
+                       Assert.AreEqual ((double) Int32.MaxValue, x.Average ());
+               }
+               
+               [Test]
+               public void TestAverageOverflowOnInt64 ()
+               {
+                       var x = new long [] { Int64.MaxValue, Int64.MaxValue };
+                       x.Average ();
+               }
+
                [Test]
                public void TestAverageOnLongNullable ()
                {
@@ -490,6 +505,38 @@ namespace MonoTests.System.Linq {
                        Assert.AreEqual ("Zyx", list [3].Name);
                }
 
+               [Test]
+               public void TestOrderByDescendingStability ()
+               {
+                       var data = new [] {
+                               new { Key = true, Value = 1 },
+                               new { Key = false, Value = 2},
+                               new { Key = true, Value = 3},
+                               new { Key = false, Value = 4},
+                               new { Key = true, Value = 5},
+                               new { Key = false, Value = 6},
+                               new { Key = true, Value = 7},
+                               new { Key = false, Value = 8},
+                               new { Key = true, Value = 9},
+                               new { Key = false, Value = 10},
+                       };
+
+                       var expected = new [] {
+                               new { Key = true, Value = 1 },
+                               new { Key = true, Value = 3},
+                               new { Key = true, Value = 5},
+                               new { Key = true, Value = 7},
+                               new { Key = true, Value = 9},
+                               new { Key = false, Value = 2},
+                               new { Key = false, Value = 4},
+                               new { Key = false, Value = 6},
+                               new { Key = false, Value = 8},
+                               new { Key = false, Value = 10},
+                       };
+
+                       AssertAreSame (expected, data.OrderByDescending (x => x.Key));
+               }
+
                static void AssertIsOrdered (IEnumerable<int> e)
                {
                                int f = int.MinValue;
diff --git a/mcs/class/System.Core/Test/System.Linq/ParallelEnumerableTests.cs b/mcs/class/System.Core/Test/System.Linq/ParallelEnumerableTests.cs
new file mode 100644 (file)
index 0000000..ef54334
--- /dev/null
@@ -0,0 +1,747 @@
+// ParallelEnumerableTests.cs
+//
+// Copyright (c) 2008 Jérémie "Garuma" Laval
+//
+// Based on Enumerable test suite by Jb Evain (jbevain@novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+//
+//
+
+#if NET_4_0
+
+using System;
+using System.Threading;
+using System.Linq;
+
+using System.Collections;
+using System.Collections.Generic;
+
+using NUnit.Framework;
+
+namespace MonoTests.System.Linq
+{
+       [TestFixtureAttribute]
+       public class ParallelEnumerableTests
+       {
+               IEnumerable<int> baseEnumerable;
+               
+               [SetUpAttribute]
+               public void Setup ()
+               {
+                       baseEnumerable = Enumerable.Range(1, 10000);
+               }
+               
+               void AreEquivalent (IEnumerable<int> syncEnumerable, IEnumerable<int> asyncEnumerable, int count)
+               {
+                       int[] sync  = Enumerable.ToArray(syncEnumerable);
+                       int[] async = Enumerable.ToArray(asyncEnumerable);
+                       
+                       // This is not AreEquals because ParallelQuery is non-deterministic (IParallelOrderedEnumerable is)
+                       // thus the order of the initial Enumerable might not be preserved
+                       CollectionAssert.AreEquivalent(sync, async, "#" + count);
+               }
+               
+               void AreEquivalent<T> (IEnumerable<T> syncEnumerable, IEnumerable<T> asyncEnumerable, int count)
+               {
+                       T[] sync  = Enumerable.ToArray(syncEnumerable);
+                       T[] async = Enumerable.ToArray(asyncEnumerable);
+                       
+                       // This is not AreEquals because ParallelQuery is non-deterministic (IParallelOrderedEnumerable is)
+                       // thus the order of the initial Enumerable might not be preserved
+                       CollectionAssert.AreEquivalent(sync, async, "#" + count);
+               }
+               
+               static void AssertAreSame<T> (IEnumerable<T> expected, IEnumerable<T> actual)
+               {
+                       if (expected == null) {
+                               Assert.IsNull (actual);
+                               return;
+                       }
+
+                       Assert.IsNotNull (actual);
+
+                       IEnumerator<T> ee = expected.GetEnumerator ();
+                       IEnumerator<T> ea = actual.GetEnumerator ();
+
+                       while (ee.MoveNext ()) {
+                               Assert.IsTrue (ea.MoveNext (), "'" + ee.Current + "' expected.");
+                               Assert.AreEqual (ee.Current, ea.Current);
+                       }
+
+                       if (ea.MoveNext ())
+                               Assert.Fail ("Unexpected element: " + ea.Current);
+               }
+               
+               public static void AssertException<T> (Action action) where T : Exception
+               {
+                       try {
+                               action ();
+                       }
+                       catch (T) {
+                               return;
+                       }
+                       Assert.Fail ("Expected: " + typeof (T).Name);
+               }
+
+               static void AssertAreSame<K, V> (K expectedKey, IEnumerable<V> expectedValues, IGrouping<K, V> actual)
+               {
+                       if (expectedValues == null) {
+                               Assert.IsNull (actual);
+                               return;
+                       }
+
+                       Assert.IsNotNull (actual);
+
+                       Assert.AreEqual (expectedKey, actual.Key);
+
+                       var ee = expectedValues.GetEnumerator ();
+                       var ea = actual.GetEnumerator ();
+
+                       while (ee.MoveNext ()) {
+                               Assert.IsTrue (ea.MoveNext (), "'" + ee.Current + "' expected.");
+                               Assert.AreEqual (ee.Current, ea.Current);
+                       }
+
+                       if (ea.MoveNext ())
+                               Assert.Fail ("Unexpected element: " + ee.Current);
+               }
+
+               static void AssertAreSame<K, V> (IDictionary<K, IEnumerable<V>> expected, IEnumerable<IGrouping<K, V>> actual)
+               {
+                       if (expected == null) {
+                               Assert.IsNull (actual);
+                               return;
+                       }
+
+                       Assert.IsNotNull (actual);
+
+                       var ee = expected.GetEnumerator ();
+                       var ea = actual.GetEnumerator ();
+
+                       while (ee.MoveNext ()) {
+                               Assert.IsTrue (ea.MoveNext (), "'" + ee.Current.Key + "' expected.");
+                               AssertAreSame (ee.Current.Key, ee.Current.Value, ea.Current);
+                       }
+
+                       if (ea.MoveNext ())
+                               Assert.Fail ("Unexpected element: " + ee.Current.Key);
+               }
+
+               static void AssertAreSame<K, V> (IDictionary<K, IEnumerable<V>> expected, ILookup<K, V> actual)
+               {
+                       if (expected == null) {
+                               Assert.IsNull (actual);
+                               return;
+                       }
+
+                       Assert.IsNotNull (actual);
+
+                       var ee = expected.GetEnumerator ();
+                       var ea = actual.GetEnumerator ();
+
+                       while (ee.MoveNext ()) {
+                               Assert.IsTrue (ea.MoveNext (), "'" + ee.Current.Key + "' expected.");
+                               AssertAreSame (ee.Current.Key, ee.Current.Value, ea.Current);
+                       }
+
+                       if (ea.MoveNext ())
+                               Assert.Fail ("Unexpected element: " + ee.Current.Key);
+               }
+
+               static void AssertAreSame<K, V> (IDictionary<K, V> expected, IDictionary<K, V> actual)
+               {
+                       if (expected == null) {
+                               Assert.IsNull (actual);
+                               return;
+                       }
+
+                       Assert.IsNotNull (actual);
+
+                       var ee = expected.GetEnumerator ();
+                       var ea = actual.GetEnumerator ();
+
+                       while (ee.MoveNext ()) {
+                               Assert.IsTrue (ea.MoveNext (), "'" + ee.Current.Key + ", " + ee.Current.Value + "' expected.");
+                               Assert.AreEqual (ee.Current.Key, ea.Current.Key);
+                               Assert.AreEqual (ee.Current.Value, ea.Current.Value);
+                       }
+
+                       if (ea.MoveNext ())
+                               Assert.Fail ("Unexpected element: " + ee.Current.Key + ", " + ee.Current.Value);
+               }
+
+               [Test]
+               public void SelectTestCase ()
+               {
+                       ParallelTestHelper.Repeat (() => {
+                               IEnumerable<int> sync  = baseEnumerable.Select (i => i * i);
+                               IEnumerable<int> async = baseEnumerable.AsParallel ().Select (i => i * i);
+                               
+                               AreEquivalent(sync, async, 1);
+                       });
+               }
+                       
+               [Test]
+               public void WhereTestCase ()
+               {
+                       ParallelTestHelper.Repeat (() => {
+                               IEnumerable<int> sync  = baseEnumerable.Where(i => i % 2 == 0);
+                               IEnumerable<int> async = baseEnumerable.AsParallel().Where(i => i % 2 == 0);
+                               
+                               AreEquivalent(sync, async, 1);
+                       });
+               }
+               
+               [Test]
+               public void CountTestCase ()
+               {
+                       ParallelTestHelper.Repeat (() => {
+                               int sync  = baseEnumerable.Count();
+                               int async = baseEnumerable.AsParallel().Count();
+                               
+                               Assert.AreEqual(sync, async, "#1");
+                       });
+               }
+               
+               [Test]
+               public void AggregateTestCase ()
+               {
+                       ParallelTestHelper.Repeat (() => {
+                               ParallelQuery<int> range = ParallelEnumerable.Repeat (5, 2643);
+                               double average = range.Aggregate(() => new double[2],
+                                                                (acc, elem) => { acc[0] += elem; acc[1]++; return acc; },
+                               (acc1, acc2) => { acc1[0] += acc2[0]; acc1[1] += acc2[1]; return acc1; },
+                               acc => acc[0] / acc[1]);
+                               
+                               Assert.AreEqual(5.0, average, "#1");
+                       });
+               }
+               
+               [Test]
+               public void TestSimpleExcept ()
+               {
+                       ParallelTestHelper.Repeat (() => {
+                               int [] first = {0, 1, 2, 3, 4, 5};
+                               int [] second = {2, 4, 6};
+                               int [] result = {0, 1, 3, 5};
+       
+                               AreEquivalent (result, first.AsParallel ().Except (second.AsParallel ()), 1);
+                       });
+               }
+
+               [Test]
+               public void TestSimpleIntersect ()
+               {
+                       ParallelTestHelper.Repeat (() => {
+                               int [] first = {0, 1, 2, 3, 4, 5};
+                               int [] second = {2, 4, 6};
+                               int [] result = {2, 4};
+       
+                               AreEquivalent (result, first.AsParallel ().Intersect (second.AsParallel ()), 1);
+                       });
+               }
+
+               [Test]
+               public void TestSimpleUnion ()
+               {
+                       ParallelTestHelper.Repeat (() => {
+                               int [] first = {0, 1, 2, 3, 4, 5};
+                               int [] second = {2, 4, 6};
+                               int [] result = {0, 1, 2, 3, 4, 5, 6};
+                               
+                               AreEquivalent (result, first.AsParallel ().Union (second.AsParallel ()), 1);
+                       });
+               }
+               
+               class Foo {}
+               class Bar : Foo {}
+
+               [Test]
+               public void TestCast ()
+               {
+                       Bar a = new Bar ();
+                       Bar b = new Bar ();
+                       Bar c = new Bar ();
+
+                       Foo [] foos = new Foo [] {a, b, c};
+                       Bar [] result = new Bar [] {a, b, c};
+
+                       AreEquivalent (result, foos.AsParallel ().Cast<Bar> (), 1);
+               }
+               
+               [Test]
+               public void TestSkip ()
+               {
+                       int [] data = {0, 1, 2, 3, 4, 5};
+                       int [] result = {3, 4, 5};
+
+                       AssertAreSame (result, data.AsParallel ().AsOrdered ().Skip (3).ToArray ());
+               }
+
+               /*[Test]
+               public void TestSkipWhile ()
+               {
+                       int [] data = {0, 1, 2, 3, 4, 5};
+                       int [] result = {3, 4, 5};
+
+                       AssertAreSame (result, data.AsParallel ().AsOrdered ().SkipWhile (i => i < 3));
+               }
+
+               [Test]
+               public void TestTake ()
+               {
+                       int [] data = {0, 1, 2, 3, 4, 5};
+                       int [] result = {0, 1, 2};
+
+                       AssertAreSame (result, data.AsParallel ().AsOrdered ().Take (3));
+               }
+
+               [Test]
+               public void TestTakeWhile ()
+               {
+                       int [] data = {0, 1, 2, 3, 4, 5};
+                       int [] result = {0, 1, 2};
+
+                       AssertAreSame (result, data.AsParallel ().AsOrdered ().TakeWhile (i => i < 3));
+               }*/
+               
+//             [Test]
+//             public void TestLast ()
+//             {
+//                     int [] data = {1, 2, 3};
+//
+//                     Assert.AreEqual (3, data.AsParallel ().Last ());
+//             }
+//
+//             [Test]
+//             public void TestLastOrDefault ()
+//             {
+//                     int [] data = {};
+//
+//                     Assert.AreEqual (default (int), data.AsParallel ().LastOrDefault ());
+//             }
+//
+//             [Test]
+//             public void TestFirst ()
+//             {
+//                     int [] data = {1, 2, 3};
+//
+//                     Assert.AreEqual (1, data.AsParallel ().First ());
+//             }
+//
+//             [Test]
+//             public void TestFirstOrDefault ()
+//             {
+//                     int [] data = {};
+//
+//                     Assert.AreEqual (default (int), data.AsParallel ().FirstOrDefault ());
+//             }
+               
+               [Test]
+               public void TestReverse ()
+               {
+                       int [] data = {0, 1, 2, 3, 4};
+                       int [] result = {4, 3, 2, 1, 0};
+
+                       AssertAreSame (result, data.AsParallel ().AsOrdered ().Reverse ());
+                       AssertAreSame (result, ParallelEnumerable.Range (0, 5).AsOrdered ().Reverse ());
+               }
+               
+               [Test]
+               public void TestOrderBy ()
+               {
+                       ParallelTestHelper.Repeat (() => {
+                               int [] array = { 14, 53, 3, 9, 11, 14, 5, 32, 2 };
+                               
+                               var q = array.AsParallel ().OrderBy ((i) => i);
+                               AssertIsOrdered (q, array.Length);
+                       });
+               }
+
+               class Baz {
+                       string name;
+                       int age;
+
+                       public string Name
+                       {
+                               get {
+                                       if (string.IsNullOrEmpty (name))
+                                               return Age.ToString ();
+
+                                       return name + " (" + Age + ")";
+                               }
+                       }
+
+                       public int Age
+                       {
+                               get { return age + 1; }
+                       }
+
+                       public Baz (string name, int age)
+                       {
+                               this.name = name;
+                               this.age = age;
+                       }
+
+                       public override int GetHashCode ()
+                       {
+                               return this.Age ^ this.Name.GetHashCode ();
+                       }
+
+                       public override bool Equals (object obj)
+                       {
+                               Baz b = obj as Baz;
+                               if (b == null)
+                                       return false;
+
+                               return b.Age == this.Age && b.Name == this.Name;
+                       }
+
+                       public override string ToString ()
+                       {
+                               return this.Name;
+                       }
+               }
+
+               static IEnumerable<Baz> CreateBazCollection ()
+               {
+                       return new [] {
+                               new Baz ("jb", 25),
+                               new Baz ("ana", 20),
+                               new Baz ("reg", 28),
+                               new Baz ("ro", 25),
+                               new Baz ("jb", 7),
+                       };
+               }
+
+               [Test]
+               public void TestOrderByAgeAscendingTheByNameDescending ()
+               {
+                       ParallelTestHelper.Repeat (() => {
+                               var q = from b in CreateBazCollection ().AsParallel()
+                                               orderby b.Age ascending, b.Name descending
+                                               select b;
+                               //var q = CreateBazCollection ().AsParallel ().OrderBy ((b) => b.Age).ThenByDescending ((b) => b.Name);
+       
+                               var expected = new [] {
+                                       new Baz ("jb", 7),
+                                       new Baz ("ana", 20),
+                                       new Baz ("ro", 25),
+                                       new Baz ("jb", 25),
+                                       new Baz ("reg", 28),
+                               };
+                               
+                               foreach (Baz b in q) {
+                                       Console.Write(b.Name + ", " + b.Age + "; ");
+                               }
+       
+                               AssertAreSame (expected, q);
+                       });
+               }
+
+               class Data {
+                       public int ID { get; set; }
+                       public string Name { get; set; }
+
+                       public override string ToString ()
+                       {
+                               return ID + " " + Name;
+                       }
+               }
+
+               IEnumerable<Data> CreateData ()
+               {
+                       return new [] {
+                               new Data { ID = 10, Name = "bcd" },
+                               new Data { ID = 20, Name = "Abcd" },
+                               new Data { ID = 20, Name = "Ab" },
+                               new Data { ID = 10, Name = "Zyx" },
+                       };
+               }
+
+               [Test]
+               public void TestOrderByIdDescendingThenByNameAscending ()
+               {
+                       ParallelTestHelper.Repeat (() => {
+                               var q = from d in CreateData ().AsParallel()
+                                       orderby d.ID descending, d.Name ascending
+                                               select d;
+                               
+                               var list = new List<Data> (q);
+                               
+                               Assert.AreEqual ("Ab", list [0].Name);
+                               Assert.AreEqual ("Abcd", list [1].Name);
+                               Assert.AreEqual ("bcd", list [2].Name);
+                               Assert.AreEqual ("Zyx", list [3].Name);
+                       });
+               }
+
+               static void AssertIsOrdered (IEnumerable<int> e, int count)
+               {
+                       int f = int.MinValue;
+                       int c = 0;
+                       
+                       foreach (int i in e) {
+                               Assert.IsTrue (f <= i, string.Format ("{0} <= {1}", f, i));
+                               f = i;
+                               c++;
+                       }
+                       
+                       Assert.AreEqual (count, c);
+               }
+               
+               /*
+               [TestAttribute, Ignore]
+               public void ElementAtTestCase()
+               {
+                       ParallelTestHelper.Repeat (() => {
+                               Assert.AreEqual(1, baseEnumerable.ElementAt(0), "#1");
+                               Assert.AreEqual(51, baseEnumerable.ElementAt(50), "#2");
+                               Assert.AreEqual(489, baseEnumerable.ElementAt(488), "#3");
+                       });
+               }
+               
+               [TestAttribute, Ignore]
+               public void TakeTestCase()
+               {
+                       ParallelTestHelper.Repeat (() => {
+                               ParallelQuery<int> async = baseEnumerable.AsParallel().Take(2000);
+                               IEnumerable<int> sync = baseEnumerable.Take(2000);
+                               
+                               AreEquivalent(sync, async, 1);
+                               
+                               async = baseEnumerable.AsParallel().Take(100);
+                               sync = baseEnumerable.Take(100);
+                       
+                               AreEquivalent(sync, async, 2);
+                       });
+               }
+               
+               [TestAttribute, Ignore]
+               public void SkipTestCase()
+               {
+                       ParallelTestHelper.Repeat (() => {
+                               ParallelQuery<int> async = baseEnumerable.AsParallel().AsOrdered().Skip(2000);
+                               IEnumerable<int> sync = baseEnumerable.Skip(2000);
+                               
+                               AreEquivalent(sync, async, 1);
+                               
+                               async = baseEnumerable.AsParallel().Skip(100);
+                               sync = baseEnumerable.Skip(100);
+                               
+                               Assert.AreEqual(sync.Count(), async.Count(), "#2");
+                       });
+               }
+
+               [TestAttribute, Ignore]
+               public void ZipTestCase()
+               {
+                       ParallelTestHelper.Repeat (() => {
+                               ParallelQuery<int> async1 = ParallelEnumerable.Range(0, 10000);
+                               ParallelQuery<int> async2 = ParallelEnumerable.Repeat(1, 10000).Zip(async1, (e1, e2) => e1 + e2);
+                               
+                               int[] expected = Enumerable.Range (1, 10000).ToArray ();
+                               CollectionAssert.AreEquivalent(expected, Enumerable.ToArray (async2), "#1");
+                       });
+               }
+               */
+               [Test]
+               public void RangeTestCase ()
+               {
+                       ParallelTestHelper.Repeat (() => {
+                               IEnumerable<int> sync  = Enumerable.Range(1, 1000);
+                               IEnumerable<int> async = ParallelEnumerable.Range(1, 1000);
+                               
+                               AreEquivalent (sync, async, 1);
+                       });
+               }
+               
+               [Test]
+               public void RepeatTestCase ()
+               {
+                       ParallelTestHelper.Repeat (() => {
+                               IEnumerable<int> sync  = Enumerable.Repeat(1, 1000);
+                               IEnumerable<int> async = ParallelEnumerable.Repeat(1, 1000);
+                               
+                               AreEquivalent (sync, async, 1);
+                       });
+               }
+               
+               [Test]
+               public void TestSum ()
+               {
+                       int [] data = {1, 2, 3, 4};
+
+                       Assert.AreEqual (10, data.AsParallel().Sum ());
+               }
+
+               [Test]
+               public void SumOnEmpty ()
+               {
+                       int [] data = {};
+
+                       Assert.AreEqual (0, data.AsParallel().Sum ());
+               }
+
+               [Test]
+               public void TestMax ()
+               {
+                       int [] data = {1, 3, 5, 2};
+
+                       Assert.AreEqual (5, data.AsParallel().Max ());
+               }
+
+               [Test]
+               public void TestMin ()
+               {
+                       int [] data = {3, 5, 2, 6, 1, 7};
+
+                       Assert.AreEqual (1, data.AsParallel().Min ());
+               }
+               
+               [Test]
+               public void TestToListOrdered ()
+               {
+                       int [] data = { 2, 3, 5 };
+
+                       var list = data.AsParallel().AsOrdered().ToList ();
+
+                       AssertAreSame (data, list);
+                       AssertIsOrdered (list, data.Length);
+
+                       Assert.AreEqual (typeof (List<int>), list.GetType ());
+               }
+
+               [Test]
+               public void TestToArrayOrdered ()
+               {
+                       ICollection<int> coll = new List<int> ();
+                       coll.Add (0);
+                       coll.Add (1);
+                       coll.Add (2);
+
+                       int [] result = {0, 1, 2};
+
+                       var array = coll.AsParallel().AsOrdered().ToArray ();
+
+                       AssertAreSame (result, array);
+                       AssertIsOrdered (array, result.Length);
+
+                       Assert.AreEqual (typeof (int []), array.GetType ());
+               }
+
+               [Test]
+               public void TestToList ()
+               {
+                       int [] data = {3, 5, 2};
+
+                       var list = data.AsParallel().ToList ();
+
+                       CollectionAssert.AreEquivalent (data, list);
+
+                       Assert.AreEqual (typeof (List<int>), list.GetType ());
+               }
+
+               [Test]
+               public void TestToArray ()
+               {
+                       ICollection<int> coll = new List<int> ();
+                       coll.Add (0);
+                       coll.Add (1);
+                       coll.Add (2);
+
+                       int [] result = {0, 1, 2};
+
+                       var array = coll.AsParallel().ToArray ();
+
+                       CollectionAssert.AreEquivalent (result, array);
+
+                       Assert.AreEqual (typeof (int []), array.GetType ());
+               }
+               
+               
+               [Test]
+               public void TestAverageOnInt32 ()
+               {
+                       Assert.AreEqual (23.25, (new int [] { 24, 7, 28, 34 }).Average ());
+               }
+
+               [Test]
+               public void TestAverageOnInt64 ()
+               {
+                       Assert.AreEqual (23.25, (new long [] { 24, 7, 28, 34 }).Average ());
+               }
+               
+               /*
+               [Test]
+               public void AnyArgumentNullTest ()
+               {
+                       string [] data = { "2", "1", "5", "3", "4" };
+
+
+                       // Any<TSource> ()
+                       AssertException<ArgumentNullException> (delegate () { ((IEnumerable<string>) null).AsParallel ().Any (); });
+
+                       // Any<TSource> (Func<TSource, bool>)
+                       AssertException<ArgumentNullException> (delegate () { ((IEnumerable<string>) null).AsParallel ().Any (x => true); });
+                       AssertException<ArgumentNullException> (delegate () { data.AsParallel ().Any ((Func<string, bool>) null); });
+               }*/
+
+               [Test]
+               public void AnyTest ()
+               {
+                       int [] data = { 5, 2, 3, 1, 6 };
+                       int [] empty = { };
+
+
+                       // Any<TSource> ()
+                       Assert.IsTrue (data.AsParallel ().Any ());
+                       Assert.IsFalse (empty.AsParallel ().Any ());
+
+                       // Any<TSource> (Func<TSource, bool>)
+                       Assert.IsTrue (data.AsParallel ().Any (x => x == 5));
+                       Assert.IsFalse (data.AsParallel ().Any (x => x == 9));
+                       Assert.IsFalse (empty.AsParallel ().Any (x => true));
+               }
+
+               /*
+               [Test]
+               public void AllArgumentNullTest ()
+               {
+                       string [] data = { "2", "1", "5", "3", "4" };
+
+                       AssertException<ArgumentNullException> (delegate () { ((IEnumerable<string>) null).AsParallel ().All (x => true); });
+                       AssertException<ArgumentNullException> (delegate () { data.AsParallel ().All ((Func<string, bool>) null); });
+               }*/
+
+               [Test]
+               public void AllTest ()
+               {
+                       int [] data = { 5, 2, 3, 1, 6 };
+                       int [] empty = { };
+
+                       Assert.IsTrue (data.AsParallel ().All (x => true));
+                       Assert.IsFalse (data.AsParallel ().All (x => x != 1));
+                       Assert.IsTrue (empty.AsParallel ().All (x => false));
+               }
+       }
+}
+
+#endif
diff --git a/mcs/class/System.Core/Test/System.Linq/ParallelTestHelper.cs b/mcs/class/System.Core/Test/System.Linq/ParallelTestHelper.cs
new file mode 100644 (file)
index 0000000..eeeef86
--- /dev/null
@@ -0,0 +1,90 @@
+#if NET_4_0
+// TestHelper.cs
+//
+// Copyright (c) 2008 Jérémie "Garuma" Laval
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+//
+//
+
+using System;
+using System.Threading;
+using System.Collections.Concurrent;
+
+namespace MonoTests.System.Linq
+{
+       public static class ParallelTestHelper
+       {
+               const int NumRun = 100;
+               
+               public static void Repeat (Action action)
+               {
+                       Repeat (action, NumRun);
+               }
+               
+               public static void Repeat (Action action, int numRun)
+               {
+                       for (int i = 0; i < numRun; i++) {
+                         //Console.WriteLine ("Run " + i.ToString ());
+                               action ();
+                       }
+               }
+               
+               public static void ParallelStressTest<TSource>(TSource obj, Action<TSource> action)
+               {
+                       ParallelStressTest(obj, action, Environment.ProcessorCount + 2);
+               }
+               
+               public static void ParallelStressTest<TSource>(TSource obj, Action<TSource> action, int numThread)
+               {
+                       Thread[] threads = new Thread[numThread];
+                       for (int i = 0; i < numThread; i++) {
+                               threads[i] = new Thread(new ThreadStart(delegate { action(obj); }));
+                               threads[i].Start();
+                       }
+                       
+                       // Wait for the completion
+                       for (int i = 0; i < numThread; i++)
+                               threads[i].Join();
+               }
+               
+               public static void ParallelAdder(IProducerConsumerCollection<int> collection, int numThread)
+               {
+                       int startIndex = -10;
+                       ParallelTestHelper.ParallelStressTest(collection, delegate (IProducerConsumerCollection<int> c) {
+                               int start = Interlocked.Add(ref startIndex, 10);
+                               for (int i = start; i < start + 10; i++) {
+                                       c.TryAdd(i);
+                               }
+                       }, numThread);
+               }
+               
+               public static void ParallelRemover(IProducerConsumerCollection<int> collection, int numThread, int times)
+               {
+                       int t = -1;
+                       ParallelTestHelper.ParallelStressTest(collection, delegate (IProducerConsumerCollection<int> c) {
+                               int num = Interlocked.Increment(ref t);
+                               int value;
+                               if (num < times)
+                                       c.TryTake (out value);
+                       }, numThread);
+               }
+       }
+}
+#endif
index 9ea3cf1b731ef4b57689480172f85550df80a947..af605f783fad805001211cb794073dbb61f173a1 100644 (file)
@@ -327,7 +327,7 @@ namespace MonoTests.System.Threading
                        }
 
                        foreach (var t in threads) {
-                               Console.WriteLine (t.ThreadState);
+                               // Console.WriteLine (t.ThreadState);
                                t.Join ();
                        }
                }
@@ -387,7 +387,7 @@ namespace MonoTests.System.Threading
                        v.ExitWriteLock ();
 
                        foreach (var t in threads) {
-                               Console.WriteLine (t.ThreadState);
+                               // Console.WriteLine (t.ThreadState);
                                t.Join ();
                        }
                }
diff --git a/mcs/class/System.Core/moonlight_bootstrap_System.Core.dll.sources b/mcs/class/System.Core/moonlight_bootstrap_System.Core.dll.sources
new file mode 100644 (file)
index 0000000..82f86b0
--- /dev/null
@@ -0,0 +1 @@
+#include moonlight_raw_System.Core.dll.sources
diff --git a/mcs/class/System.Core/moonlight_raw_System.Core.dll.sources b/mcs/class/System.Core/moonlight_raw_System.Core.dll.sources
new file mode 100644 (file)
index 0000000..f212d2c
--- /dev/null
@@ -0,0 +1,73 @@
+../../build/common/Consts.cs
+../../build/common/Locale.cs
+../../build/common/MonoTODOAttribute.cs
+../corlib/Mono.Security.Cryptography/CryptoTools.cs
+../corlib/Mono.Security.Cryptography/SymmetricTransform.cs
+../corlib/System/Lazy.cs
+../corlib/System.Threading/LazyThreadSafetyMode.cs
+Assembly/AssemblyInfo.cs
+System/Actions.cs
+System/Funcs.cs
+System/InvalidTimeZoneException.cs
+System/TimeZoneInfo.AdjustmentRule.cs
+System/TimeZoneInfo.cs
+System/TimeZoneInfo.TransitionTime.cs
+System/TimeZoneNotFoundException.cs
+System.Runtime.CompilerServices/ExecutionScope.cs
+System.Runtime.CompilerServices/ExtensionAttribute.cs
+System.Runtime.CompilerServices/IStrongBox.cs
+System.Runtime.CompilerServices/StrongBox_T.cs
+System.Linq/Check.cs
+System.Linq/Enumerable.cs
+System.Linq/QueryableEnumerable.cs
+System.Linq/QueryableTransformer.cs
+System.Linq/Grouping.cs
+System.Linq/IGrouping.cs
+System.Linq/IOrderedQueryable.cs
+System.Linq/IOrderedQueryable_T.cs
+System.Linq/IOrderedEnumerable_T.cs
+System.Linq/IQueryable.cs
+System.Linq/IQueryable_T.cs
+System.Linq/Lookup.cs
+System.Linq/ILookup_T.cs
+System.Linq/OrderedEnumerable.cs
+System.Linq/OrderedSequence.cs
+System.Linq/Queryable.cs
+System.Linq/QuickSort.cs
+System.Linq/SortContext.cs
+System.Linq/SortDirection.cs
+System.Linq/SortSequenceContext.cs
+System.Linq/IQueryProvider.cs
+System.Linq.Expressions/BinaryExpression.cs
+System.Linq.Expressions/ConditionalExpression.cs
+System.Linq.Expressions/ConstantExpression.cs
+System.Linq.Expressions/ElementInit.cs
+System.Linq.Expressions/EmitContext.cs
+System.Linq.Expressions/Expression.cs
+System.Linq.Expressions/Expression_T.cs
+System.Linq.Expressions/ExpressionPrinter.cs
+System.Linq.Expressions/ExpressionType.cs
+System.Linq.Expressions/ExpressionVisitor.cs
+System.Linq.Expressions/ExpressionTransformer.cs
+System.Linq.Expressions/Extensions.cs
+System.Linq.Expressions/InvocationExpression.cs
+System.Linq.Expressions/LambdaExpression.cs
+System.Linq.Expressions/ListInitExpression.cs
+System.Linq.Expressions/MemberAssignment.cs
+System.Linq.Expressions/MemberBinding.cs
+System.Linq.Expressions/MemberBindingType.cs
+System.Linq.Expressions/MemberExpression.cs
+System.Linq.Expressions/MemberInitExpression.cs
+System.Linq.Expressions/MemberListBinding.cs
+System.Linq.Expressions/MemberMemberBinding.cs
+System.Linq.Expressions/MethodCallExpression.cs
+System.Linq.Expressions/NewArrayExpression.cs
+System.Linq.Expressions/NewExpression.cs
+System.Linq.Expressions/ParameterExpression.cs
+System.Linq.Expressions/TypeBinaryExpression.cs
+System.Linq.Expressions/UnaryExpression.cs
+System.Collections.Generic/HashSet.cs
+../corlib/System.Collections.Generic/CollectionDebuggerView.cs
+System.Security.Cryptography/Aes.cs
+System.Security.Cryptography/AesManaged.cs
+System.Security.Cryptography/AesTransform.cs
diff --git a/mcs/class/System.Core/net_2_1_bootstrap_System.Core.dll.sources b/mcs/class/System.Core/net_2_1_bootstrap_System.Core.dll.sources
deleted file mode 100644 (file)
index 5e32150..0000000
+++ /dev/null
@@ -1 +0,0 @@
-#include net_2_1_raw_System.Core.dll.sources
diff --git a/mcs/class/System.Core/net_2_1_raw_System.Core.dll.sources b/mcs/class/System.Core/net_2_1_raw_System.Core.dll.sources
deleted file mode 100644 (file)
index 844e40b..0000000
+++ /dev/null
@@ -1,71 +0,0 @@
-../../build/common/Consts.cs
-../../build/common/Locale.cs
-../../build/common/MonoTODOAttribute.cs
-../corlib/Mono.Security.Cryptography/CryptoTools.cs
-../corlib/Mono.Security.Cryptography/SymmetricTransform.cs
-Assembly/AssemblyInfo.cs
-System/Actions.cs
-System/Funcs.cs
-System/InvalidTimeZoneException.cs
-System/TimeZoneInfo.AdjustmentRule.cs
-System/TimeZoneInfo.cs
-System/TimeZoneInfo.TransitionTime.cs
-System/TimeZoneNotFoundException.cs
-System.Runtime.CompilerServices/ExecutionScope.cs
-System.Runtime.CompilerServices/ExtensionAttribute.cs
-System.Runtime.CompilerServices/IStrongBox.cs
-System.Runtime.CompilerServices/StrongBox_T.cs
-System.Linq/Check.cs
-System.Linq/Enumerable.cs
-System.Linq/QueryableEnumerable.cs
-System.Linq/QueryableTransformer.cs
-System.Linq/Grouping.cs
-System.Linq/IGrouping.cs
-System.Linq/IOrderedQueryable.cs
-System.Linq/IOrderedQueryable_T.cs
-System.Linq/IOrderedEnumerable_T.cs
-System.Linq/IQueryable.cs
-System.Linq/IQueryable_T.cs
-System.Linq/Lookup.cs
-System.Linq/ILookup_T.cs
-System.Linq/OrderedEnumerable.cs
-System.Linq/OrderedSequence.cs
-System.Linq/Queryable.cs
-System.Linq/QuickSort.cs
-System.Linq/SortContext.cs
-System.Linq/SortDirection.cs
-System.Linq/SortSequenceContext.cs
-System.Linq/IQueryProvider.cs
-System.Linq.Expressions/BinaryExpression.cs
-System.Linq.Expressions/ConditionalExpression.cs
-System.Linq.Expressions/ConstantExpression.cs
-System.Linq.Expressions/ElementInit.cs
-System.Linq.Expressions/EmitContext.cs
-System.Linq.Expressions/Expression.cs
-System.Linq.Expressions/Expression_T.cs
-System.Linq.Expressions/ExpressionPrinter.cs
-System.Linq.Expressions/ExpressionType.cs
-System.Linq.Expressions/ExpressionVisitor.cs
-System.Linq.Expressions/ExpressionTransformer.cs
-System.Linq.Expressions/Extensions.cs
-System.Linq.Expressions/InvocationExpression.cs
-System.Linq.Expressions/LambdaExpression.cs
-System.Linq.Expressions/ListInitExpression.cs
-System.Linq.Expressions/MemberAssignment.cs
-System.Linq.Expressions/MemberBinding.cs
-System.Linq.Expressions/MemberBindingType.cs
-System.Linq.Expressions/MemberExpression.cs
-System.Linq.Expressions/MemberInitExpression.cs
-System.Linq.Expressions/MemberListBinding.cs
-System.Linq.Expressions/MemberMemberBinding.cs
-System.Linq.Expressions/MethodCallExpression.cs
-System.Linq.Expressions/NewArrayExpression.cs
-System.Linq.Expressions/NewExpression.cs
-System.Linq.Expressions/ParameterExpression.cs
-System.Linq.Expressions/TypeBinaryExpression.cs
-System.Linq.Expressions/UnaryExpression.cs
-System.Collections.Generic/HashSet.cs
-../corlib/System.Collections.Generic/CollectionDebuggerView.cs
-System.Security.Cryptography/Aes.cs
-System.Security.Cryptography/AesManaged.cs
-System.Security.Cryptography/AesTransform.cs
index 138709e664ceecc102bd58a8dc5edcbce602b783..220ab49fbca08b40211efa83e6a5e2adee86fd31 100644 (file)
@@ -42,6 +42,7 @@ System.Linq/ILookup_T.cs
 System.Linq/OrderedEnumerable.cs
 System.Linq/OrderedSequence.cs
 System.Linq/Queryable.cs
+System.Linq/QueryableTransformer.cs
 System.Linq/QuickSort.cs
 System.Linq/SortContext.cs
 System.Linq/SortDirection.cs
@@ -49,7 +50,6 @@ System.Linq/SortSequenceContext.cs
 System.Linq/IQueryProvider.cs
 System.Collections.Generic/HashSet.cs
 ../corlib/System.Collections.Generic/CollectionDebuggerView.cs
-System.Security.Cryptography/Aes.cs
 System.Security.Cryptography/AesManaged.cs
 System.Security.Cryptography/AesCryptoServiceProvider.cs
 System.Security.Cryptography/AesTransform.cs
@@ -68,6 +68,7 @@ System.Threading/LockRecursionPolicy.cs
 System.Threading/ReaderWriterLockSlim.cs
 
 System.Linq.Expressions/Extensions.cs
+System.Linq.Expressions/ExpressionTransformer.cs
 
 Microsoft.Win32.SafeHandles/SafePipeHandle.cs
 Microsoft.Win32.SafeHandles/SafeMemoryMappedFileHandle.cs
@@ -111,6 +112,7 @@ System.IO/HandleInheritability.cs
 ../dlr/Runtime/Microsoft.Scripting.Core/Actions/IDynamicMetaObjectProvider.cs
 ../dlr/Runtime/Microsoft.Scripting.Core/Actions/InvokeBinder.cs
 ../dlr/Runtime/Microsoft.Scripting.Core/Actions/InvokeMemberBinder.cs
+../dlr/Runtime/Microsoft.Scripting.Core/Actions/IInvokeOnGetBinder.cs
 ../dlr/Runtime/Microsoft.Scripting.Core/Actions/RuleCache.cs
 ../dlr/Runtime/Microsoft.Scripting.Core/Actions/SetIndexBinder.cs
 ../dlr/Runtime/Microsoft.Scripting.Core/Actions/SetMemberBinder.cs
@@ -207,3 +209,48 @@ System.IO/HandleInheritability.cs
 ../dlr/Runtime/Microsoft.Scripting.Core/Utils/ReferenceEqualityComparer.cs
 ../dlr/Runtime/Microsoft.Scripting.Core/Utils/TrueReadOnlyCollection.cs
 ../dlr/Runtime/Microsoft.Scripting.Core/Utils/TypeExtensions.cs
+System.Linq/ParallelQueryEnumerator.cs
+System.Linq/OrderedParallelQuery.cs
+System.Linq/ParallelMergeOptions.cs
+System.Linq/ParallelExecutionMode.cs
+System.Linq/ParallelEnumerable.cs
+System.Linq/ParallelPartitioner.cs
+System.Linq/Internal/RangeList.cs
+System.Linq/Internal/StripPartitioner.cs
+System.Linq/Internal/RepeatList.cs
+System.Linq/Internal/ParallelQuickSort.cs
+System.Linq/Internal/OrderingEnumerator.cs
+System.Linq/Internal/AggregationList.cs
+System.Linq/Internal/ConcurrentLookup.cs
+System.Linq/Internal/ConcurrentGrouping.cs
+System.Linq/Internal/ReverseList.cs
+System.Linq/ParallelExecuter.cs
+System.Linq/ParallelQuery.cs
+System.Linq/Internal/QueryNodes/QueryWhereNode.cs
+System.Linq/Internal/QueryNodes/QueryCastNode.cs
+System.Linq/Internal/QueryNodes/QueryConcatNode.cs
+System.Linq/Internal/QueryNodes/QueryDefaultEmptyNode.cs
+System.Linq/Internal/QueryNodes/QueryOptionNode.cs
+System.Linq/Internal/QueryNodes/QueryGroupByNode.cs
+System.Linq/Internal/QueryNodes/QuerySelectNode.cs
+System.Linq/Internal/QueryNodes/QuerySelectManyNode.cs
+System.Linq/Internal/QueryNodes/QueryStreamNode.cs
+System.Linq/Internal/QueryNodes/QueryOrderedStreamNode.cs
+System.Linq/Internal/QueryNodes/QueryStartNode.cs
+System.Linq/Internal/QueryNodes/QueryBaseNode.cs
+System.Linq/Internal/QueryNodes/QueryChildNode.cs
+System.Linq/Internal/QueryNodes/QueryOrderGuardNode.cs
+System.Linq/Internal/QueryNodes/QueryOrderByNode.cs
+System.Linq/Internal/QueryNodes/QueryMuxNode.cs
+System.Linq/Internal/QueryNodes/QueryZipNode.cs
+System.Linq/Internal/QueryNodes/QuerySetNode.cs
+System.Linq/Internal/QueryNodes/QueryReverseNode.cs
+System.Linq/Internal/QueryNodes/SetInclusion.cs
+System.Linq/Internal/Visitors/INodeVisitor.cs
+System.Linq/Internal/Visitors/IVisitableNode.cs
+System.Linq/Internal/Visitors/QueryCheckerVisitor.cs
+System.Linq/Internal/Visitors/QueryOptions.cs
+System.Linq/Internal/QueryNodes/WrapHelper.cs
+../corlib/System.Collections.Concurrent/Partitioners/EnumerablePartitioner.cs
+../corlib/System.Collections.Concurrent/ConcurrentSkipList.cs
+
index fa3972598423ddf57d1b7a6429667ba66aafe4c9..b6c487f060b265ce91fab65b735e5c73bf77b06f 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-26  Miguel de Icaza  <miguel@novell.com>
+
+       * RowEnumerableDataReader.cs: Applied patch from Tony Fish fixing
+       bug #591397
+
 2008-12-02  Marek Habersack  <mhabersack@novell.com>
 
        * DataRowExtensions.cs: when Field <T> is specialized on a
index 0e583bf611f18b01e0ae00bbf0d803a6b3cc35c0..4a9e571abb1ffe93e5f90cd642a4756dfc404108 100644 (file)
@@ -44,8 +44,8 @@ namespace System.Data
                public RowEnumerableDataReader (IEnumerable source, int depth)
                {
                        this.source = source as EnumerableRowCollection;
-                       if (source == null)
-                               source = new EnumerableRowCollection<DataRow> ((IEnumerable<DataRow>) source);
+                       if (this.source == null)
+                               this.source = new EnumerableRowCollection<DataRow> ((IEnumerable<DataRow>) source);
                        this.depth = depth;
                }
 
@@ -158,10 +158,16 @@ namespace System.Data
 
                public int GetValues (object [] values)
                {
-                       // FIXME: do we need it?
-                       throw new NotSupportedException ();
-               }
+                       int fieldCount = FieldCount;
+                       int i;
 
+                       //target object is byval so we can not just assign new object[] to values , calling side will not change
+                       //hence copy each item into values
+                       for (i = 0; i < values.Length && i < fieldCount; ++i)
+                               values[i] = Current[i];
+                       return i - 1;
+               }
+               
                public bool IsDBNull (int i)
                {
                        return Current.IsNull (i);
index c5d8decf682e784d73430b1e5b6f2892b93dc1ac..3bc8156bb1906f0c669a395d64e3064edaebf3d1 100755 (executable)
@@ -1,3 +1,8 @@
+2010-04-13  Jonathan Pryor  <jpryor@novell.com>
+
+       * src/**/*: Sync with DbLinq r1403.  This is DbLinq 0.20 + fixes.
+         Primarily fixes sqlmetal, codegen, etc.
+
 2009-12-18  Jonathan Pryor  <jpryor@novell.com>
 
        * src/**/*: Sync with DbLinq r1294.  This is DbLinq 0.19.  Fixes
index 6867b7cb288f8e3aeee69d178a4c654ff808192f..242c5b64b15a9e50f29429aa6bc813903bd2e5ac 100755 (executable)
@@ -222,6 +222,7 @@ src/DbLinq/Schema/Dbml/Adapter/EnumType.cs
 src/DbLinq/Schema/Dbml/Adapter/INamedType.cs
 src/DbLinq/Schema/Dbml/Adapter/ISimpleList.cs
 src/DbLinq/Schema/Dbml/Adapter/SpecifiedPropertyUpdater.cs
+src/DbLinq/Schema/Dbml/DatabaseSerializer.cs
 src/DbLinq/Schema/Dbml/DbmlSchema.Adapter.cs
 src/DbLinq/Schema/Dbml/DbmlSchema.cs
 src/DbLinq/Schema/Dbml/DbmlSerializer.cs
index 87c9c56522bd61b50d47b9dbb0c7f1501d29711f..7051baf2e92c97f7b60c2c8723502874611f061b 100644 (file)
@@ -21,16 +21,3 @@ using System.Runtime.InteropServices;
 \r
 // The following GUID is for the ID of the typelib if this project is exposed to COM\r
 [assembly: Guid("a87ac4a4-43ee-4a0a-8edf-42843d5e3bc0")]\r
-\r
-// Version information for an assembly consists of the following four values:\r
-//\r
-//      Major Version\r
-//      Minor Version \r
-//      Build Number\r
-//      Revision\r
-//\r
-// You can specify all the values or you can default the Build and Revision Numbers \r
-// by using the '*' as shown below:\r
-// [assembly: AssemblyVersion("1.0.*")]\r
-[assembly: AssemblyVersion("1.0.0.0")]\r
-[assembly: AssemblyFileVersion("1.0.0.0")]\r
index ed4b88cdc14f152d4554684ad079c4dfb08b47a5..9f9d32200d24d5280d6e1ef9beee479ebc141572 100644 (file)
@@ -21,16 +21,3 @@ using System.Runtime.InteropServices;
 \r
 // The following GUID is for the ID of the typelib if this project is exposed to COM\r
 [assembly: Guid("65a7cab4-3c0b-47cd-bc50-dc8201115dbb")]\r
-\r
-// Version information for an assembly consists of the following four values:\r
-//\r
-//      Major Version\r
-//      Minor Version \r
-//      Build Number\r
-//      Revision\r
-//\r
-// You can specify all the values or you can default the Build and Revision Numbers \r
-// by using the '*' as shown below:\r
-// [assembly: AssemblyVersion("1.0.*")]\r
-[assembly: AssemblyVersion("0.0.1.17")]\r
-[assembly: AssemblyFileVersion("0.19")]\r
index 4984c17343c28e2710a705295aae8b262620598f..95e94cbbd7206471ec4b7403439794e48d836638 100644 (file)
@@ -21,13 +21,3 @@ using System.Runtime.InteropServices;
 \r
 // The following GUID is for the ID of the typelib if this project is exposed to COM\r
 [assembly: Guid("e2381b27-cdb0-401d-9019-f72079b4928d")]\r
-\r
-// Version information for an assembly consists of the following four values:\r
-//\r
-//      Major Version\r
-//      Minor Version \r
-//      Build Number\r
-//      Revision\r
-//\r
-[assembly: AssemblyVersion("0.0.1.17")]\r
-[assembly: AssemblyFileVersion("0.19")]\r
index 6c8b1dd54f5243f042020baaeb6571f5a95aa6a5..d049e83b3594fb0782b3f77b1c4c8a5599e6d0b0 100644 (file)
@@ -21,13 +21,3 @@ using System.Runtime.InteropServices;
 \r
 // The following GUID is for the ID of the typelib if this project is exposed to COM\r
 [assembly: Guid("e2381b27-cdb0-401d-9019-f72079b4928d")]\r
-\r
-// Version information for an assembly consists of the following four values:\r
-//\r
-//      Major Version\r
-//      Minor Version \r
-//      Build Number\r
-//      Revision\r
-//\r
-[assembly: AssemblyVersion("0.0.1.17")]\r
-[assembly: AssemblyFileVersion("0.19")]\r
index da8ecd35dc3254b5eba5884dbb34c0b122fe1d6b..9c8aa14012e1b33cfcbb58d80444e05cd6e6ef47 100644 (file)
@@ -248,8 +248,8 @@ values ('UKMOD', 'MOD','(secret)','U.K.','E14','London');
 insert INTO "Customers" ("CustomerID", "CompanyName","ContactName", "ContactTitle", "Country","PostalCode","City", "Phone")\r
 values ('ALFKI', 'Alfreds Futterkiste','Maria Anders','Sales Representative','Germany','12209','Berlin','030-0074321');\r
 \r
-insert INTO "Customers" ("CustomerID", "CompanyName","ContactName", "ContactTitle", "Country","PostalCode","City", "Phone")\r
-values ('BONAP', 'Bon something','Bon Boss','Sales Representative','France','11109','Paris','033-0074321');\r
+insert INTO "Customers" ("CustomerID", "CompanyName","ContactName", "ContactTitle", "Country", "PostalCode", "Address", "City", "Phone", "Fax")\r
+values ('BONAP', 'Bon app''','Laurence Lebihan','Owner','France','13008','12, rue des Bouchers','Marseille','91.24.45.40', '91.24.45.41');\r
 \r
 insert INTO "Customers" ("CustomerID", "CompanyName","ContactName", "ContactTitle", "Country","PostalCode","City", "Phone")\r
 values ('WARTH', 'Wartian Herkku','Pirkko Koskitalo','Accounting Manager','Finland','90110','Oulu','981-443655');\r
index e4beaac4fd4f5440eca80abf3f6133185d210229..48cb9d0ea29d89fffd964f1ef662ac7f500dacb6 100644 (file)
@@ -34,6 +34,7 @@ DROP SEQUENCE Orders_seq;
 DROP SEQUENCE Employees_seq;\r
 DROP SEQUENCE Categories_Seq;\r
 DROP SEQUENCE Region_seq;\r
+DROP SEQUENCE Territories_seq;\r
 \r
 COMMIT;\r
 \r
index 4984c17343c28e2710a705295aae8b262620598f..95e94cbbd7206471ec4b7403439794e48d836638 100644 (file)
@@ -21,13 +21,3 @@ using System.Runtime.InteropServices;
 \r
 // The following GUID is for the ID of the typelib if this project is exposed to COM\r
 [assembly: Guid("e2381b27-cdb0-401d-9019-f72079b4928d")]\r
-\r
-// Version information for an assembly consists of the following four values:\r
-//\r
-//      Major Version\r
-//      Minor Version \r
-//      Build Number\r
-//      Revision\r
-//\r
-[assembly: AssemblyVersion("0.0.1.17")]\r
-[assembly: AssemblyFileVersion("0.19")]\r
index f6bf319a19e48ab2446fad07479198204df605bf..9ab167eacae840a46abb21442ee18aa06ca686ae 100644 (file)
-#region Auto-generated classes for Northwind database on [TIMESTAMP]\r
-\r
-//\r
-//  ____  _     __  __      _        _\r
+// \r
+//  ____  _     __  __      _        _ \r
 // |  _ \| |__ |  \/  | ___| |_ __ _| |\r
 // | | | | '_ \| |\/| |/ _ \ __/ _` | |\r
 // | |_| | |_) | |  | |  __/ || (_| | |\r
 // |____/|_.__/|_|  |_|\___|\__\__,_|_|\r
 //\r
-// Auto-generated from Northwind on [TIMESTAMP]\r
-// Please visit http://linq.to/db for more information\r
-\r
-#endregion\r
-\r
-using System;\r
-using System.Data;\r
-using System.Data.Linq.Mapping;\r
-using System.Diagnostics;\r
-using System.Reflection;\r
+// Auto-generated from Northwind on 2010-04-08 15:21:38Z.\r
+// Please visit http://code.google.com/p/dblinq2007/ for more information.\r
+//\r
+namespace nwind\r
+{\r
+       using System;\r
+       using System.ComponentModel;\r
+       using System.Data;\r
 #if MONO_STRICT\r
-using System.Data.Linq;\r
+       using System.Data.Linq;\r
 #else   // MONO_STRICT\r
-using DbLinq.Data.Linq;\r
-using DbLinq.Vendor;\r
+       using DbLinq.Data.Linq;\r
+       using DbLinq.Vendor;\r
 #endif  // MONO_STRICT\r
-using System.ComponentModel;\r
-\r
-namespace nwind\r
-{\r
+       using System.Data.Linq.Mapping;\r
+       using System.Diagnostics;\r
+       \r
+       \r
        public partial class Northwind : DataContext\r
        {\r
-               #region Extensibility Method Definitions\r
-\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
-\r
                #endregion\r
-\r
-               public Northwind(string connectionString)\r
-                       : base(connectionString)\r
+               \r
+               \r
+               public Northwind(string connectionString) : \r
+                               base(connectionString)\r
                {\r
-                       OnCreated();\r
+                       this.OnCreated();\r
                }\r
-\r
-               public Northwind(IDbConnection connection)\r
-               #if MONO_STRICT\r
-                       : base(connection)\r
-               #else   // MONO_STRICT\r
-                       : base(connection, new DbLinq.Sqlite.SqliteVendor())\r
-               #endif  // MONO_STRICT\r
+               \r
+               public Northwind(string connection, MappingSource mappingSource) : \r
+                               base(connection, mappingSource)\r
                {\r
-                       OnCreated();\r
+                       this.OnCreated();\r
                }\r
-\r
-               public Northwind(string connection, MappingSource mappingSource)\r
-                       : base(connection, mappingSource)\r
+               \r
+               public Northwind(IDbConnection connection, MappingSource mappingSource) : \r
+                               base(connection, mappingSource)\r
                {\r
-                       OnCreated();\r
+                       this.OnCreated();\r
                }\r
-\r
-               public Northwind(IDbConnection connection, MappingSource mappingSource)\r
-                       : base(connection, mappingSource)\r
+               \r
+               public Table<Category> Categories\r
                {\r
-                       OnCreated();\r
+                       get\r
+                       {\r
+                               return this.GetTable<Category>();\r
+                       }\r
                }\r
-\r
-               #if !MONO_STRICT\r
-               public Northwind(IDbConnection connection, IVendor vendor)\r
-                       : base(connection, vendor)\r
+               \r
+               public Table<Customer> Customers\r
                {\r
-                       OnCreated();\r
+                       get\r
+                       {\r
+                               return this.GetTable<Customer>();\r
+                       }\r
                }\r
-               #endif  // !MONO_STRICT\r
-\r
-               #if !MONO_STRICT\r
-               public Northwind(IDbConnection connection, MappingSource mappingSource, IVendor vendor)\r
-                       : base(connection, mappingSource, vendor)\r
+               \r
+               public Table<CustomerCustomerDemo> CustomerCustomerDemo\r
                {\r
-                       OnCreated();\r
+                       get\r
+                       {\r
+                               return this.GetTable<CustomerCustomerDemo>();\r
+                       }\r
                }\r
-               #endif  // !MONO_STRICT\r
-\r
-               public Table<Category> Categories { get { return GetTable<Category>(); } }\r
-               public Table<Customer> Customers { get { return GetTable<Customer>(); } }\r
-               public Table<CustomerCustomerDemo> CustomerCustomerDemo { get { return GetTable<CustomerCustomerDemo>(); } }\r
-               public Table<CustomerDemographic> CustomerDemographics { get { return GetTable<CustomerDemographic>(); } }\r
-               public Table<Employee> Employees { get { return GetTable<Employee>(); } }\r
-               public Table<EmployeeTerritory> EmployeeTerritories { get { return GetTable<EmployeeTerritory>(); } }\r
-               public Table<Order> Orders { get { return GetTable<Order>(); } }\r
-               public Table<OrderDetail> OrderDetails { get { return GetTable<OrderDetail>(); } }\r
-               public Table<Product> Products { get { return GetTable<Product>(); } }\r
-               public Table<Region> Regions { get { return GetTable<Region>(); } }\r
-               public Table<Shipper> Shippers { get { return GetTable<Shipper>(); } }\r
-               public Table<Supplier> Suppliers { get { return GetTable<Supplier>(); } }\r
-               public Table<Territory> Territories { get { return GetTable<Territory>(); } }\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Categories")]\r
-       public partial class Category : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
+               \r
+               public Table<CustomerDemographic> CustomerDemographics\r
                {\r
-                       if (PropertyChanging != null)\r
+                       get\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               return this.GetTable<CustomerDemographic>();\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
+               \r
+               public Table<Employee> Employees\r
                {\r
-                       if (PropertyChanged != null)\r
+                       get\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               return this.GetTable<Employee>();\r
                        }\r
                }\r
+               \r
+               public Table<EmployeeTerritory> EmployeeTerritories\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<EmployeeTerritory>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Order> Orders\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Order>();\r
+                       }\r
+               }\r
+               \r
+               public Table<OrderDetail> OrderDetails\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<OrderDetail>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Product> Products\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Product>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Region> Regions\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Region>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Shipper> Shippers\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Shipper>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Supplier> Suppliers\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Supplier>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Territory> Territories\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Territory>();\r
+                       }\r
+               }\r
+       }\r
+       \r
+       #region Start MONO_STRICT\r
+#if MONO_STRICT\r
 \r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       public partial class Northwind\r
+       {\r
+               \r
+               public Northwind(IDbConnection connection) : \r
+                               base(connection)\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+       }\r
+       #region End MONO_STRICT\r
+       #endregion\r
+#else     // MONO_STRICT\r
+       \r
+       public partial class Northwind\r
+       {\r
+               \r
+               public Northwind(IDbConnection connection) : \r
+                               base(connection, new DbLinq.Sqlite.SqliteVendor())\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               public Northwind(IDbConnection connection, IVendor sqlDialect) : \r
+                               base(connection, sqlDialect)\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               public Northwind(IDbConnection connection, MappingSource mappingSource, IVendor sqlDialect) : \r
+                               base(connection, mappingSource, sqlDialect)\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+       }\r
+       #region End Not MONO_STRICT\r
+       #endregion\r
+#endif     // MONO_STRICT\r
+       #endregion\r
+       \r
+       [Table(Name="main.Categories")]\r
+       public partial class Category : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private int _categoryID;\r
+               \r
+               private string _categoryName;\r
+               \r
+               private string _description;\r
+               \r
+               private byte[] _picture;\r
+               \r
+               private EntitySet<Product> _products;\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnCategoryIDChanged();\r
+               \r
                partial void OnCategoryIDChanging(int value);\r
+               \r
                partial void OnCategoryNameChanged();\r
+               \r
                partial void OnCategoryNameChanging(string value);\r
+               \r
                partial void OnDescriptionChanged();\r
+               \r
                partial void OnDescriptionChanging(string value);\r
+               \r
                partial void OnPictureChanged();\r
-               partial void OnPictureChanging(Byte[] value);\r
-\r
+               \r
+               partial void OnPictureChanging(byte[] value);\r
                #endregion\r
-\r
-               #region int CategoryID\r
-\r
-               private int _categoryID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_categoryID", Name = "CategoryID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               \r
+               public Category()\r
+               {\r
+                       _products = new EntitySet<Product>(new Action<Product>(this.Products_Attach), new Action<Product>(this.Products_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_categoryID", Name="CategoryID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public int CategoryID\r
                {\r
                        get\r
                        {\r
-                               return _categoryID;\r
+                               return this._categoryID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _categoryID)\r
+                               if ((_categoryID != value))\r
                                {\r
-                                       OnCategoryIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _categoryID = value;\r
-                                       SendPropertyChanged("CategoryID");\r
-                                       OnCategoryIDChanged();\r
+                                       this.OnCategoryIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._categoryID = value;\r
+                                       this.SendPropertyChanged("CategoryID");\r
+                                       this.OnCategoryIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string CategoryName\r
-\r
-               private string _categoryName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_categoryName", Name = "CategoryName", DbType = "nvarchar (15)", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_categoryName", Name="CategoryName", DbType="nvarchar (15)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CategoryName\r
                {\r
                        get\r
                        {\r
-                               return _categoryName;\r
+                               return this._categoryName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _categoryName)\r
+                               if (((_categoryName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCategoryNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _categoryName = value;\r
-                                       SendPropertyChanged("CategoryName");\r
-                                       OnCategoryNameChanged();\r
+                                       this.OnCategoryNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._categoryName = value;\r
+                                       this.SendPropertyChanged("CategoryName");\r
+                                       this.OnCategoryNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Description\r
-\r
-               private string _description;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_description", Name = "Description", DbType = "ntext", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_description", Name="Description", DbType="ntext", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Description\r
                {\r
                        get\r
                        {\r
-                               return _description;\r
+                               return this._description;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _description)\r
+                               if (((_description == value) \r
+                                                       == false))\r
                                {\r
-                                       OnDescriptionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _description = value;\r
-                                       SendPropertyChanged("Description");\r
-                                       OnDescriptionChanged();\r
+                                       this.OnDescriptionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._description = value;\r
+                                       this.SendPropertyChanged("Description");\r
+                                       this.OnDescriptionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region Byte[] Picture\r
-\r
-               private Byte[] _picture;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_picture", Name = "Picture", DbType = "image", AutoSync = AutoSync.Never)]\r
-               public Byte[] Picture\r
+               \r
+               [Column(Storage="_picture", Name="Picture", DbType="image", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public byte[] Picture\r
                {\r
                        get\r
                        {\r
-                               return _picture;\r
+                               return this._picture;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _picture)\r
+                               if (((_picture == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPictureChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _picture = value;\r
-                                       SendPropertyChanged("Picture");\r
-                                       OnPictureChanged();\r
+                                       this.OnPictureChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._picture = value;\r
+                                       this.SendPropertyChanged("Picture");\r
+                                       this.OnPictureChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<Product> _products;\r
-               [Association(Storage = "_products", OtherKey = "CategoryID", ThisKey = "CategoryID", Name = "fk_Products_1")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_products", OtherKey="CategoryID", ThisKey="CategoryID", Name="fk_Products_1")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Product> Products\r
                {\r
                        get\r
                        {\r
-                               return _products;\r
+                               return this._products;\r
                        }\r
                        set\r
                        {\r
-                               _products = value;\r
+                               this._products = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void Products_Attach(Product entity)\r
-               {\r
-                       entity.Category = this;\r
-               }\r
-\r
-               private void Products_Detach(Product entity)\r
-               {\r
-                       entity.Category = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Category()\r
-               {\r
-                       _products = new EntitySet<Product>(Products_Attach, Products_Detach);\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Customers")]\r
-       public partial class Customer : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
                protected virtual void SendPropertyChanging()\r
                {\r
-                       if (PropertyChanging != null)\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               h(this, emptyChangingEventArgs);\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
+               \r
                protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
                        }\r
                }\r
-\r
+               \r
+               #region Attachment handlers\r
+               private void Products_Attach(Product entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Category = this;\r
+               }\r
+               \r
+               private void Products_Detach(Product entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Category = null;\r
+               }\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="main.Customers")]\r
+       public partial class Customer : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _address;\r
+               \r
+               private string _city;\r
+               \r
+               private string _companyName;\r
+               \r
+               private string _contactName;\r
+               \r
+               private string _contactTitle;\r
+               \r
+               private string _country;\r
+               \r
+               private string _customerID;\r
+               \r
+               private string _fax;\r
+               \r
+               private string _phone;\r
+               \r
+               private string _postalCode;\r
+               \r
+               private string _region;\r
+               \r
+               private EntitySet<CustomerCustomerDemo> _customerCustomerDemo;\r
+               \r
+               private EntitySet<Order> _orders;\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnAddressChanged();\r
+               \r
                partial void OnAddressChanging(string value);\r
+               \r
                partial void OnCityChanged();\r
+               \r
                partial void OnCityChanging(string value);\r
+               \r
                partial void OnCompanyNameChanged();\r
+               \r
                partial void OnCompanyNameChanging(string value);\r
+               \r
                partial void OnContactNameChanged();\r
+               \r
                partial void OnContactNameChanging(string value);\r
+               \r
                partial void OnContactTitleChanged();\r
+               \r
                partial void OnContactTitleChanging(string value);\r
+               \r
                partial void OnCountryChanged();\r
+               \r
                partial void OnCountryChanging(string value);\r
+               \r
                partial void OnCustomerIDChanged();\r
+               \r
                partial void OnCustomerIDChanging(string value);\r
+               \r
                partial void OnFaxChanged();\r
+               \r
                partial void OnFaxChanging(string value);\r
+               \r
                partial void OnPhoneChanged();\r
+               \r
                partial void OnPhoneChanging(string value);\r
+               \r
                partial void OnPostalCodeChanged();\r
+               \r
                partial void OnPostalCodeChanging(string value);\r
+               \r
                partial void OnRegionChanged();\r
+               \r
                partial void OnRegionChanging(string value);\r
-\r
                #endregion\r
-\r
-               #region string Address\r
-\r
-               private string _address;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_address", Name = "Address", DbType = "nvarchar (60)", AutoSync = AutoSync.Never)]\r
+               \r
+               \r
+               public Customer()\r
+               {\r
+                       _customerCustomerDemo = new EntitySet<CustomerCustomerDemo>(new Action<CustomerCustomerDemo>(this.CustomerCustomerDemo_Attach), new Action<CustomerCustomerDemo>(this.CustomerCustomerDemo_Detach));\r
+                       _orders = new EntitySet<Order>(new Action<Order>(this.Orders_Attach), new Action<Order>(this.Orders_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_address", Name="Address", DbType="nvarchar (60)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Address\r
                {\r
                        get\r
                        {\r
-                               return _address;\r
+                               return this._address;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _address)\r
+                               if (((_address == value) \r
+                                                       == false))\r
                                {\r
-                                       OnAddressChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _address = value;\r
-                                       SendPropertyChanged("Address");\r
-                                       OnAddressChanged();\r
+                                       this.OnAddressChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._address = value;\r
+                                       this.SendPropertyChanged("Address");\r
+                                       this.OnAddressChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string City\r
-\r
-               private string _city;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_city", Name = "City", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_city", Name="City", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string City\r
                {\r
                        get\r
                        {\r
-                               return _city;\r
+                               return this._city;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _city)\r
+                               if (((_city == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _city = value;\r
-                                       SendPropertyChanged("City");\r
-                                       OnCityChanged();\r
+                                       this.OnCityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._city = value;\r
+                                       this.SendPropertyChanged("City");\r
+                                       this.OnCityChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string CompanyName\r
-\r
-               private string _companyName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_companyName", Name = "CompanyName", DbType = "nvarchar (40)", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_companyName", Name="CompanyName", DbType="nvarchar (40)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CompanyName\r
                {\r
                        get\r
                        {\r
-                               return _companyName;\r
+                               return this._companyName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _companyName)\r
+                               if (((_companyName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCompanyNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _companyName = value;\r
-                                       SendPropertyChanged("CompanyName");\r
-                                       OnCompanyNameChanged();\r
+                                       this.OnCompanyNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._companyName = value;\r
+                                       this.SendPropertyChanged("CompanyName");\r
+                                       this.OnCompanyNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ContactName\r
-\r
-               private string _contactName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_contactName", Name = "ContactName", DbType = "nvarchar (30)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_contactName", Name="ContactName", DbType="nvarchar (30)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ContactName\r
                {\r
                        get\r
                        {\r
-                               return _contactName;\r
+                               return this._contactName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _contactName)\r
+                               if (((_contactName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnContactNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _contactName = value;\r
-                                       SendPropertyChanged("ContactName");\r
-                                       OnContactNameChanged();\r
+                                       this.OnContactNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._contactName = value;\r
+                                       this.SendPropertyChanged("ContactName");\r
+                                       this.OnContactNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ContactTitle\r
-\r
-               private string _contactTitle;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_contactTitle", Name = "ContactTitle", DbType = "nvarchar (30)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_contactTitle", Name="ContactTitle", DbType="nvarchar (30)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ContactTitle\r
                {\r
                        get\r
                        {\r
-                               return _contactTitle;\r
+                               return this._contactTitle;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _contactTitle)\r
+                               if (((_contactTitle == value) \r
+                                                       == false))\r
                                {\r
-                                       OnContactTitleChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _contactTitle = value;\r
-                                       SendPropertyChanged("ContactTitle");\r
-                                       OnContactTitleChanged();\r
+                                       this.OnContactTitleChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._contactTitle = value;\r
+                                       this.SendPropertyChanged("ContactTitle");\r
+                                       this.OnContactTitleChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Country\r
-\r
-               private string _country;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_country", Name = "Country", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_country", Name="Country", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Country\r
                {\r
                        get\r
                        {\r
-                               return _country;\r
+                               return this._country;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _country)\r
+                               if (((_country == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCountryChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _country = value;\r
-                                       SendPropertyChanged("Country");\r
-                                       OnCountryChanged();\r
+                                       this.OnCountryChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._country = value;\r
+                                       this.SendPropertyChanged("Country");\r
+                                       this.OnCountryChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string CustomerID\r
-\r
-               private string _customerID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerID", Name = "CustomerID", DbType = "nchar (5)", IsPrimaryKey = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_customerID", Name="CustomerID", DbType="nchar (5)", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CustomerID\r
                {\r
                        get\r
                        {\r
-                               return _customerID;\r
+                               return this._customerID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerID)\r
+                               if (((_customerID == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCustomerIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerID = value;\r
-                                       SendPropertyChanged("CustomerID");\r
-                                       OnCustomerIDChanged();\r
+                                       this.OnCustomerIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerID = value;\r
+                                       this.SendPropertyChanged("CustomerID");\r
+                                       this.OnCustomerIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Fax\r
-\r
-               private string _fax;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_fax", Name = "Fax", DbType = "nvarchar (24)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_fax", Name="Fax", DbType="nvarchar (24)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Fax\r
                {\r
                        get\r
                        {\r
-                               return _fax;\r
+                               return this._fax;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _fax)\r
+                               if (((_fax == value) \r
+                                                       == false))\r
                                {\r
-                                       OnFaxChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _fax = value;\r
-                                       SendPropertyChanged("Fax");\r
-                                       OnFaxChanged();\r
+                                       this.OnFaxChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._fax = value;\r
+                                       this.SendPropertyChanged("Fax");\r
+                                       this.OnFaxChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Phone\r
-\r
-               private string _phone;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_phone", Name = "Phone", DbType = "nvarchar (24)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_phone", Name="Phone", DbType="nvarchar (24)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Phone\r
                {\r
                        get\r
                        {\r
-                               return _phone;\r
+                               return this._phone;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _phone)\r
+                               if (((_phone == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPhoneChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _phone = value;\r
-                                       SendPropertyChanged("Phone");\r
-                                       OnPhoneChanged();\r
+                                       this.OnPhoneChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._phone = value;\r
+                                       this.SendPropertyChanged("Phone");\r
+                                       this.OnPhoneChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string PostalCode\r
-\r
-               private string _postalCode;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_postalCode", Name = "PostalCode", DbType = "nvarchar (10)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_postalCode", Name="PostalCode", DbType="nvarchar (10)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string PostalCode\r
                {\r
                        get\r
                        {\r
-                               return _postalCode;\r
+                               return this._postalCode;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _postalCode)\r
+                               if (((_postalCode == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPostalCodeChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _postalCode = value;\r
-                                       SendPropertyChanged("PostalCode");\r
-                                       OnPostalCodeChanged();\r
+                                       this.OnPostalCodeChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._postalCode = value;\r
+                                       this.SendPropertyChanged("PostalCode");\r
+                                       this.OnPostalCodeChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Region\r
-\r
-               private string _region;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_region", Name = "Region", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_region", Name="Region", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Region\r
                {\r
                        get\r
                        {\r
-                               return _region;\r
+                               return this._region;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _region)\r
+                               if (((_region == value) \r
+                                                       == false))\r
                                {\r
-                                       OnRegionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _region = value;\r
-                                       SendPropertyChanged("Region");\r
-                                       OnRegionChanged();\r
+                                       this.OnRegionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._region = value;\r
+                                       this.SendPropertyChanged("Region");\r
+                                       this.OnRegionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<CustomerCustomerDemo> _customerCustomerDemo;\r
-               [Association(Storage = "_customerCustomerDemo", OtherKey = "CustomerID", ThisKey = "CustomerID", Name = "fk_CustomerCustomerDemo_0")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_customerCustomerDemo", OtherKey="CustomerID", ThisKey="CustomerID", Name="fk_CustomerCustomerDemo_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<CustomerCustomerDemo> CustomerCustomerDemo\r
                {\r
                        get\r
                        {\r
-                               return _customerCustomerDemo;\r
+                               return this._customerCustomerDemo;\r
                        }\r
                        set\r
                        {\r
-                               _customerCustomerDemo = value;\r
+                               this._customerCustomerDemo = value;\r
                        }\r
                }\r
-\r
-               private EntitySet<Order> _orders;\r
-               [Association(Storage = "_orders", OtherKey = "CustomerID", ThisKey = "CustomerID", Name = "fk_Orders_2")]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_orders", OtherKey="CustomerID", ThisKey="CustomerID", Name="fk_Orders_2")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Order> Orders\r
                {\r
                        get\r
                        {\r
-                               return _orders;\r
+                               return this._orders;\r
                        }\r
                        set\r
                        {\r
-                               _orders = value;\r
+                               this._orders = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               #region Attachment handlers\r
                private void CustomerCustomerDemo_Attach(CustomerCustomerDemo entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Customer = this;\r
                }\r
-\r
+               \r
                private void CustomerCustomerDemo_Detach(CustomerCustomerDemo entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Customer = null;\r
                }\r
-\r
+               \r
                private void Orders_Attach(Order entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Customer = this;\r
                }\r
-\r
+               \r
                private void Orders_Detach(Order entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Customer = null;\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Customer()\r
-               {\r
-                       _customerCustomerDemo = new EntitySet<CustomerCustomerDemo>(CustomerCustomerDemo_Attach, CustomerCustomerDemo_Detach);\r
-                       _orders = new EntitySet<Order>(Orders_Attach, Orders_Detach);\r
-                       OnCreated();\r
-               }\r
-\r
                #endregion\r
-\r
        }\r
-\r
-       [Table(Name = "main.CustomerCustomerDemo")]\r
-       public partial class CustomerCustomerDemo : INotifyPropertyChanging, INotifyPropertyChanged\r
+       \r
+       [Table(Name="main.CustomerCustomerDemo")]\r
+       public partial class CustomerCustomerDemo : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged\r
        {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _customerID;\r
+               \r
+               private string _customerTypeID;\r
+               \r
+               private EntityRef<Customer> _customer = new EntityRef<Customer>();\r
+               \r
+               private EntityRef<CustomerDemographic> _customerDemographic = new EntityRef<CustomerDemographic>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnCustomerIDChanged();\r
+               \r
                partial void OnCustomerIDChanging(string value);\r
+               \r
                partial void OnCustomerTypeIDChanged();\r
+               \r
                partial void OnCustomerTypeIDChanging(string value);\r
-\r
                #endregion\r
-\r
-               #region string CustomerID\r
-\r
-               private string _customerID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerID", Name = "CustomerID", DbType = "nchar (5)", IsPrimaryKey = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               \r
+               public CustomerCustomerDemo()\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_customerID", Name="CustomerID", DbType="nchar (5)", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CustomerID\r
                {\r
                        get\r
                        {\r
-                               return _customerID;\r
+                               return this._customerID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerID)\r
+                               if (((_customerID == value) \r
+                                                       == false))\r
                                {\r
                                        if (_customer.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnCustomerIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerID = value;\r
-                                       SendPropertyChanged("CustomerID");\r
-                                       OnCustomerIDChanged();\r
+                                       this.OnCustomerIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerID = value;\r
+                                       this.SendPropertyChanged("CustomerID");\r
+                                       this.OnCustomerIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string CustomerTypeID\r
-\r
-               private string _customerTypeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerTypeID", Name = "CustomerTypeID", DbType = "nchar", IsPrimaryKey = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_customerTypeID", Name="CustomerTypeID", DbType="nchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CustomerTypeID\r
                {\r
                        get\r
                        {\r
-                               return _customerTypeID;\r
+                               return this._customerTypeID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerTypeID)\r
+                               if (((_customerTypeID == value) \r
+                                                       == false))\r
                                {\r
                                        if (_customerDemographic.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnCustomerTypeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerTypeID = value;\r
-                                       SendPropertyChanged("CustomerTypeID");\r
-                                       OnCustomerTypeIDChanged();\r
+                                       this.OnCustomerTypeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerTypeID = value;\r
+                                       this.SendPropertyChanged("CustomerTypeID");\r
+                                       this.OnCustomerTypeIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Customer> _customer;\r
-               [Association(Storage = "_customer", OtherKey = "CustomerID", ThisKey = "CustomerID", Name = "fk_CustomerCustomerDemo_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_customer", OtherKey="CustomerID", ThisKey="CustomerID", Name="fk_CustomerCustomerDemo_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Customer Customer\r
                {\r
                        get\r
                        {\r
-                               return _customer.Entity;\r
+                               return this._customer.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customer.Entity)\r
+                               if (((this._customer.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_customer.Entity != null)\r
+                                       if ((this._customer.Entity != null))\r
                                        {\r
-                                               var previousCustomer = _customer.Entity;\r
-                                               _customer.Entity = null;\r
+                                               Customer previousCustomer = this._customer.Entity;\r
+                                               this._customer.Entity = null;\r
                                                previousCustomer.CustomerCustomerDemo.Remove(this);\r
                                        }\r
-                                       _customer.Entity = value;\r
-                                       if (value != null)\r
+                                       this._customer.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.CustomerCustomerDemo.Add(this);\r
                                                _customerID = value.CustomerID;\r
@@ -847,28 +905,28 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-               private EntityRef<CustomerDemographic> _customerDemographic;\r
-               [Association(Storage = "_customerDemographic", OtherKey = "CustomerTypeID", ThisKey = "CustomerTypeID", Name = "fk_CustomerCustomerDemo_1", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_customerDemographic", OtherKey="CustomerTypeID", ThisKey="CustomerTypeID", Name="fk_CustomerCustomerDemo_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public CustomerDemographic CustomerDemographic\r
                {\r
                        get\r
                        {\r
-                               return _customerDemographic.Entity;\r
+                               return this._customerDemographic.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerDemographic.Entity)\r
+                               if (((this._customerDemographic.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_customerDemographic.Entity != null)\r
+                                       if ((this._customerDemographic.Entity != null))\r
                                        {\r
-                                               var previousCustomerDemographic = _customerDemographic.Entity;\r
-                                               _customerDemographic.Entity = null;\r
+                                               CustomerDemographic previousCustomerDemographic = this._customerDemographic.Entity;\r
+                                               this._customerDemographic.Entity = null;\r
                                                previousCustomerDemographic.CustomerCustomerDemo.Remove(this);\r
                                        }\r
-                                       _customerDemographic.Entity = value;\r
-                                       if (value != null)\r
+                                       this._customerDemographic.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.CustomerCustomerDemo.Add(this);\r
                                                _customerTypeID = value.CustomerTypeID;\r
@@ -880,783 +938,756 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region ctor\r
-\r
-               public CustomerCustomerDemo()\r
-               {\r
-                       _customer = new EntityRef<Customer>();\r
-                       _customerDemographic = new EntityRef<CustomerDemographic>();\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.CustomerDemographics")]\r
-       public partial class CustomerDemographic : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
                protected virtual void SendPropertyChanging()\r
                {\r
-                       if (PropertyChanging != null)\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               h(this, emptyChangingEventArgs);\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
+               \r
                protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="main.CustomerDemographics")]\r
+       public partial class CustomerDemographic : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _customerDesc;\r
+               \r
+               private string _customerTypeID;\r
+               \r
+               private EntitySet<CustomerCustomerDemo> _customerCustomerDemo;\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnCustomerDescChanged();\r
+               \r
                partial void OnCustomerDescChanging(string value);\r
+               \r
                partial void OnCustomerTypeIDChanged();\r
+               \r
                partial void OnCustomerTypeIDChanging(string value);\r
-\r
                #endregion\r
-\r
-               #region string CustomerDesc\r
-\r
-               private string _customerDesc;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerDesc", Name = "CustomerDesc", DbType = "ntext", AutoSync = AutoSync.Never)]\r
+               \r
+               \r
+               public CustomerDemographic()\r
+               {\r
+                       _customerCustomerDemo = new EntitySet<CustomerCustomerDemo>(new Action<CustomerCustomerDemo>(this.CustomerCustomerDemo_Attach), new Action<CustomerCustomerDemo>(this.CustomerCustomerDemo_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_customerDesc", Name="CustomerDesc", DbType="ntext", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string CustomerDesc\r
                {\r
                        get\r
                        {\r
-                               return _customerDesc;\r
+                               return this._customerDesc;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerDesc)\r
+                               if (((_customerDesc == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCustomerDescChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerDesc = value;\r
-                                       SendPropertyChanged("CustomerDesc");\r
-                                       OnCustomerDescChanged();\r
+                                       this.OnCustomerDescChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerDesc = value;\r
+                                       this.SendPropertyChanged("CustomerDesc");\r
+                                       this.OnCustomerDescChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string CustomerTypeID\r
-\r
-               private string _customerTypeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerTypeID", Name = "CustomerTypeID", DbType = "nchar", IsPrimaryKey = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_customerTypeID", Name="CustomerTypeID", DbType="nchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CustomerTypeID\r
                {\r
                        get\r
                        {\r
-                               return _customerTypeID;\r
+                               return this._customerTypeID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerTypeID)\r
+                               if (((_customerTypeID == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCustomerTypeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerTypeID = value;\r
-                                       SendPropertyChanged("CustomerTypeID");\r
-                                       OnCustomerTypeIDChanged();\r
+                                       this.OnCustomerTypeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerTypeID = value;\r
+                                       this.SendPropertyChanged("CustomerTypeID");\r
+                                       this.OnCustomerTypeIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<CustomerCustomerDemo> _customerCustomerDemo;\r
-               [Association(Storage = "_customerCustomerDemo", OtherKey = "CustomerTypeID", ThisKey = "CustomerTypeID", Name = "fk_CustomerCustomerDemo_1")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_customerCustomerDemo", OtherKey="CustomerTypeID", ThisKey="CustomerTypeID", Name="fk_CustomerCustomerDemo_1")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<CustomerCustomerDemo> CustomerCustomerDemo\r
                {\r
                        get\r
                        {\r
-                               return _customerCustomerDemo;\r
+                               return this._customerCustomerDemo;\r
                        }\r
                        set\r
                        {\r
-                               _customerCustomerDemo = value;\r
+                               this._customerCustomerDemo = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void CustomerCustomerDemo_Attach(CustomerCustomerDemo entity)\r
-               {\r
-                       entity.CustomerDemographic = this;\r
-               }\r
-\r
-               private void CustomerCustomerDemo_Detach(CustomerCustomerDemo entity)\r
-               {\r
-                       entity.CustomerDemographic = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public CustomerDemographic()\r
-               {\r
-                       _customerCustomerDemo = new EntitySet<CustomerCustomerDemo>(CustomerCustomerDemo_Attach, CustomerCustomerDemo_Detach);\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Employees")]\r
-       public partial class Employee : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
                protected virtual void SendPropertyChanging()\r
                {\r
-                       if (PropertyChanging != null)\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               h(this, emptyChangingEventArgs);\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
+               \r
                protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
                        }\r
                }\r
-\r
+               \r
+               #region Attachment handlers\r
+               private void CustomerCustomerDemo_Attach(CustomerCustomerDemo entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.CustomerDemographic = this;\r
+               }\r
+               \r
+               private void CustomerCustomerDemo_Detach(CustomerCustomerDemo entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.CustomerDemographic = null;\r
+               }\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="main.Employees")]\r
+       public partial class Employee : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _address;\r
+               \r
+               private System.Nullable<System.DateTime> _birthDate;\r
+               \r
+               private string _city;\r
+               \r
+               private string _country;\r
+               \r
+               private int _employeeID;\r
+               \r
+               private string _extension;\r
+               \r
+               private string _firstName;\r
+               \r
+               private System.Nullable<System.DateTime> _hireDate;\r
+               \r
+               private string _homePhone;\r
+               \r
+               private string _lastName;\r
+               \r
+               private string _notes;\r
+               \r
+               private byte[] _photo;\r
+               \r
+               private string _photoPath;\r
+               \r
+               private string _postalCode;\r
+               \r
+               private string _region;\r
+               \r
+               private System.Nullable<int> _reportsTo;\r
+               \r
+               private string _title;\r
+               \r
+               private string _titleOfCourtesy;\r
+               \r
+               private EntitySet<EmployeeTerritory> _employeeTerritories;\r
+               \r
+               private EntitySet<Employee> _employees;\r
+               \r
+               private EntitySet<Order> _orders;\r
+               \r
+               private EntityRef<Employee> _reportsToEmployee = new EntityRef<Employee>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnAddressChanged();\r
+               \r
                partial void OnAddressChanging(string value);\r
+               \r
                partial void OnBirthDateChanged();\r
-               partial void OnBirthDateChanging(DateTime? value);\r
+               \r
+               partial void OnBirthDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
                partial void OnCityChanged();\r
+               \r
                partial void OnCityChanging(string value);\r
+               \r
                partial void OnCountryChanged();\r
+               \r
                partial void OnCountryChanging(string value);\r
+               \r
                partial void OnEmployeeIDChanged();\r
+               \r
                partial void OnEmployeeIDChanging(int value);\r
+               \r
                partial void OnExtensionChanged();\r
+               \r
                partial void OnExtensionChanging(string value);\r
+               \r
                partial void OnFirstNameChanged();\r
+               \r
                partial void OnFirstNameChanging(string value);\r
+               \r
                partial void OnHireDateChanged();\r
-               partial void OnHireDateChanging(DateTime? value);\r
+               \r
+               partial void OnHireDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
                partial void OnHomePhoneChanged();\r
+               \r
                partial void OnHomePhoneChanging(string value);\r
+               \r
                partial void OnLastNameChanged();\r
+               \r
                partial void OnLastNameChanging(string value);\r
+               \r
                partial void OnNotesChanged();\r
+               \r
                partial void OnNotesChanging(string value);\r
+               \r
                partial void OnPhotoChanged();\r
-               partial void OnPhotoChanging(Byte[] value);\r
+               \r
+               partial void OnPhotoChanging(byte[] value);\r
+               \r
                partial void OnPhotoPathChanged();\r
+               \r
                partial void OnPhotoPathChanging(string value);\r
+               \r
                partial void OnPostalCodeChanged();\r
+               \r
                partial void OnPostalCodeChanging(string value);\r
+               \r
                partial void OnRegionChanged();\r
+               \r
                partial void OnRegionChanging(string value);\r
+               \r
                partial void OnReportsToChanged();\r
-               partial void OnReportsToChanging(int? value);\r
+               \r
+               partial void OnReportsToChanging(System.Nullable<int> value);\r
+               \r
                partial void OnTitleChanged();\r
+               \r
                partial void OnTitleChanging(string value);\r
+               \r
                partial void OnTitleOfCourtesyChanged();\r
+               \r
                partial void OnTitleOfCourtesyChanging(string value);\r
-\r
                #endregion\r
-\r
-               #region string Address\r
-\r
-               private string _address;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_address", Name = "Address", DbType = "nvarchar (60)", AutoSync = AutoSync.Never)]\r
+               \r
+               \r
+               public Employee()\r
+               {\r
+                       _employeeTerritories = new EntitySet<EmployeeTerritory>(new Action<EmployeeTerritory>(this.EmployeeTerritories_Attach), new Action<EmployeeTerritory>(this.EmployeeTerritories_Detach));\r
+                       _employees = new EntitySet<Employee>(new Action<Employee>(this.Employees_Attach), new Action<Employee>(this.Employees_Detach));\r
+                       _orders = new EntitySet<Order>(new Action<Order>(this.Orders_Attach), new Action<Order>(this.Orders_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_address", Name="Address", DbType="nvarchar (60)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Address\r
                {\r
                        get\r
                        {\r
-                               return _address;\r
+                               return this._address;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _address)\r
+                               if (((_address == value) \r
+                                                       == false))\r
                                {\r
-                                       OnAddressChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _address = value;\r
-                                       SendPropertyChanged("Address");\r
-                                       OnAddressChanged();\r
+                                       this.OnAddressChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._address = value;\r
+                                       this.SendPropertyChanged("Address");\r
+                                       this.OnAddressChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? BirthDate\r
-\r
-               private DateTime? _birthDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_birthDate", Name = "BirthDate", DbType = "datetime", AutoSync = AutoSync.Never)]\r
-               public DateTime? BirthDate\r
+               \r
+               [Column(Storage="_birthDate", Name="BirthDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> BirthDate\r
                {\r
                        get\r
                        {\r
-                               return _birthDate;\r
+                               return this._birthDate;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _birthDate)\r
+                               if ((_birthDate != value))\r
                                {\r
-                                       OnBirthDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _birthDate = value;\r
-                                       SendPropertyChanged("BirthDate");\r
-                                       OnBirthDateChanged();\r
+                                       this.OnBirthDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._birthDate = value;\r
+                                       this.SendPropertyChanged("BirthDate");\r
+                                       this.OnBirthDateChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string City\r
-\r
-               private string _city;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_city", Name = "City", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_city", Name="City", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string City\r
                {\r
                        get\r
                        {\r
-                               return _city;\r
+                               return this._city;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _city)\r
+                               if (((_city == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _city = value;\r
-                                       SendPropertyChanged("City");\r
-                                       OnCityChanged();\r
+                                       this.OnCityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._city = value;\r
+                                       this.SendPropertyChanged("City");\r
+                                       this.OnCityChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Country\r
-\r
-               private string _country;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_country", Name = "Country", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_country", Name="Country", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Country\r
                {\r
                        get\r
                        {\r
-                               return _country;\r
+                               return this._country;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _country)\r
+                               if (((_country == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCountryChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _country = value;\r
-                                       SendPropertyChanged("Country");\r
-                                       OnCountryChanged();\r
+                                       this.OnCountryChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._country = value;\r
+                                       this.SendPropertyChanged("Country");\r
+                                       this.OnCountryChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region int EmployeeID\r
-\r
-               private int _employeeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_employeeID", Name = "EmployeeID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_employeeID", Name="EmployeeID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public int EmployeeID\r
                {\r
                        get\r
                        {\r
-                               return _employeeID;\r
+                               return this._employeeID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _employeeID)\r
+                               if ((_employeeID != value))\r
                                {\r
-                                       OnEmployeeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _employeeID = value;\r
-                                       SendPropertyChanged("EmployeeID");\r
-                                       OnEmployeeIDChanged();\r
+                                       this.OnEmployeeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._employeeID = value;\r
+                                       this.SendPropertyChanged("EmployeeID");\r
+                                       this.OnEmployeeIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Extension\r
-\r
-               private string _extension;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_extension", Name = "Extension", DbType = "nvarchar (4)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_extension", Name="Extension", DbType="nvarchar (4)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Extension\r
                {\r
                        get\r
                        {\r
-                               return _extension;\r
+                               return this._extension;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _extension)\r
+                               if (((_extension == value) \r
+                                                       == false))\r
                                {\r
-                                       OnExtensionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _extension = value;\r
-                                       SendPropertyChanged("Extension");\r
-                                       OnExtensionChanged();\r
+                                       this.OnExtensionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._extension = value;\r
+                                       this.SendPropertyChanged("Extension");\r
+                                       this.OnExtensionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string FirstName\r
-\r
-               private string _firstName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_firstName", Name = "FirstName", DbType = "nvarchar (10)", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_firstName", Name="FirstName", DbType="nvarchar (10)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string FirstName\r
                {\r
                        get\r
                        {\r
-                               return _firstName;\r
+                               return this._firstName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _firstName)\r
+                               if (((_firstName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnFirstNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _firstName = value;\r
-                                       SendPropertyChanged("FirstName");\r
-                                       OnFirstNameChanged();\r
+                                       this.OnFirstNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._firstName = value;\r
+                                       this.SendPropertyChanged("FirstName");\r
+                                       this.OnFirstNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? HireDate\r
-\r
-               private DateTime? _hireDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_hireDate", Name = "HireDate", DbType = "datetime", AutoSync = AutoSync.Never)]\r
-               public DateTime? HireDate\r
+               \r
+               [Column(Storage="_hireDate", Name="HireDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> HireDate\r
                {\r
                        get\r
                        {\r
-                               return _hireDate;\r
+                               return this._hireDate;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _hireDate)\r
+                               if ((_hireDate != value))\r
                                {\r
-                                       OnHireDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _hireDate = value;\r
-                                       SendPropertyChanged("HireDate");\r
-                                       OnHireDateChanged();\r
+                                       this.OnHireDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._hireDate = value;\r
+                                       this.SendPropertyChanged("HireDate");\r
+                                       this.OnHireDateChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string HomePhone\r
-\r
-               private string _homePhone;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_homePhone", Name = "HomePhone", DbType = "nvarchar (24)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_homePhone", Name="HomePhone", DbType="nvarchar (24)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string HomePhone\r
                {\r
                        get\r
                        {\r
-                               return _homePhone;\r
+                               return this._homePhone;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _homePhone)\r
+                               if (((_homePhone == value) \r
+                                                       == false))\r
                                {\r
-                                       OnHomePhoneChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _homePhone = value;\r
-                                       SendPropertyChanged("HomePhone");\r
-                                       OnHomePhoneChanged();\r
+                                       this.OnHomePhoneChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._homePhone = value;\r
+                                       this.SendPropertyChanged("HomePhone");\r
+                                       this.OnHomePhoneChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string LastName\r
-\r
-               private string _lastName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_lastName", Name = "LastName", DbType = "nvarchar (20)", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_lastName", Name="LastName", DbType="nvarchar (20)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string LastName\r
                {\r
                        get\r
                        {\r
-                               return _lastName;\r
+                               return this._lastName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _lastName)\r
+                               if (((_lastName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnLastNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _lastName = value;\r
-                                       SendPropertyChanged("LastName");\r
-                                       OnLastNameChanged();\r
+                                       this.OnLastNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._lastName = value;\r
+                                       this.SendPropertyChanged("LastName");\r
+                                       this.OnLastNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Notes\r
-\r
-               private string _notes;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_notes", Name = "Notes", DbType = "ntext", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_notes", Name="Notes", DbType="ntext", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Notes\r
                {\r
                        get\r
                        {\r
-                               return _notes;\r
+                               return this._notes;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _notes)\r
+                               if (((_notes == value) \r
+                                                       == false))\r
                                {\r
-                                       OnNotesChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _notes = value;\r
-                                       SendPropertyChanged("Notes");\r
-                                       OnNotesChanged();\r
+                                       this.OnNotesChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._notes = value;\r
+                                       this.SendPropertyChanged("Notes");\r
+                                       this.OnNotesChanged();\r
                                }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Byte[] Photo\r
-\r
-               private Byte[] _photo;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_photo", Name = "Photo", DbType = "image", AutoSync = AutoSync.Never)]\r
-               public Byte[] Photo\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_photo", Name="Photo", DbType="image", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public byte[] Photo\r
                {\r
                        get\r
                        {\r
-                               return _photo;\r
+                               return this._photo;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _photo)\r
+                               if (((_photo == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPhotoChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _photo = value;\r
-                                       SendPropertyChanged("Photo");\r
-                                       OnPhotoChanged();\r
+                                       this.OnPhotoChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._photo = value;\r
+                                       this.SendPropertyChanged("Photo");\r
+                                       this.OnPhotoChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string PhotoPath\r
-\r
-               private string _photoPath;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_photoPath", Name = "PhotoPath", DbType = "nvarchar (255)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_photoPath", Name="PhotoPath", DbType="nvarchar (255)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string PhotoPath\r
                {\r
                        get\r
                        {\r
-                               return _photoPath;\r
+                               return this._photoPath;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _photoPath)\r
+                               if (((_photoPath == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPhotoPathChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _photoPath = value;\r
-                                       SendPropertyChanged("PhotoPath");\r
-                                       OnPhotoPathChanged();\r
+                                       this.OnPhotoPathChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._photoPath = value;\r
+                                       this.SendPropertyChanged("PhotoPath");\r
+                                       this.OnPhotoPathChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string PostalCode\r
-\r
-               private string _postalCode;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_postalCode", Name = "PostalCode", DbType = "nvarchar (10)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_postalCode", Name="PostalCode", DbType="nvarchar (10)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string PostalCode\r
                {\r
                        get\r
                        {\r
-                               return _postalCode;\r
+                               return this._postalCode;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _postalCode)\r
+                               if (((_postalCode == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPostalCodeChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _postalCode = value;\r
-                                       SendPropertyChanged("PostalCode");\r
-                                       OnPostalCodeChanged();\r
+                                       this.OnPostalCodeChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._postalCode = value;\r
+                                       this.SendPropertyChanged("PostalCode");\r
+                                       this.OnPostalCodeChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Region\r
-\r
-               private string _region;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_region", Name = "Region", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_region", Name="Region", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Region\r
                {\r
                        get\r
                        {\r
-                               return _region;\r
+                               return this._region;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _region)\r
+                               if (((_region == value) \r
+                                                       == false))\r
                                {\r
-                                       OnRegionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _region = value;\r
-                                       SendPropertyChanged("Region");\r
-                                       OnRegionChanged();\r
+                                       this.OnRegionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._region = value;\r
+                                       this.SendPropertyChanged("Region");\r
+                                       this.OnRegionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region int? ReportsTo\r
-\r
-               private int? _reportsTo;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_reportsTo", Name = "ReportsTo", DbType = "INTEGER", AutoSync = AutoSync.Never)]\r
-               public int? ReportsTo\r
+               \r
+               [Column(Storage="_reportsTo", Name="ReportsTo", DbType="INTEGER", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<int> ReportsTo\r
                {\r
                        get\r
                        {\r
-                               return _reportsTo;\r
+                               return this._reportsTo;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _reportsTo)\r
+                               if ((_reportsTo != value))\r
                                {\r
                                        if (_reportsToEmployee.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnReportsToChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _reportsTo = value;\r
-                                       SendPropertyChanged("ReportsTo");\r
-                                       OnReportsToChanged();\r
+                                       this.OnReportsToChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._reportsTo = value;\r
+                                       this.SendPropertyChanged("ReportsTo");\r
+                                       this.OnReportsToChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Title\r
-\r
-               private string _title;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_title", Name = "Title", DbType = "nvarchar (30)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_title", Name="Title", DbType="nvarchar (30)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Title\r
                {\r
                        get\r
                        {\r
-                               return _title;\r
+                               return this._title;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _title)\r
+                               if (((_title == value) \r
+                                                       == false))\r
                                {\r
-                                       OnTitleChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _title = value;\r
-                                       SendPropertyChanged("Title");\r
-                                       OnTitleChanged();\r
+                                       this.OnTitleChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._title = value;\r
+                                       this.SendPropertyChanged("Title");\r
+                                       this.OnTitleChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string TitleOfCourtesy\r
-\r
-               private string _titleOfCourtesy;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_titleOfCourtesy", Name = "TitleOfCourtesy", DbType = "nvarchar (25)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_titleOfCourtesy", Name="TitleOfCourtesy", DbType="nvarchar (25)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string TitleOfCourtesy\r
                {\r
                        get\r
                        {\r
-                               return _titleOfCourtesy;\r
+                               return this._titleOfCourtesy;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _titleOfCourtesy)\r
+                               if (((_titleOfCourtesy == value) \r
+                                                       == false))\r
                                {\r
-                                       OnTitleOfCourtesyChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _titleOfCourtesy = value;\r
-                                       SendPropertyChanged("TitleOfCourtesy");\r
-                                       OnTitleOfCourtesyChanged();\r
+                                       this.OnTitleOfCourtesyChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._titleOfCourtesy = value;\r
+                                       this.SendPropertyChanged("TitleOfCourtesy");\r
+                                       this.OnTitleOfCourtesyChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<EmployeeTerritory> _employeeTerritories;\r
-               [Association(Storage = "_employeeTerritories", OtherKey = "EmployeeID", ThisKey = "EmployeeID", Name = "fk_EmployeeTerritories_1")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_employeeTerritories", OtherKey="EmployeeID", ThisKey="EmployeeID", Name="fk_EmployeeTerritories_1")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<EmployeeTerritory> EmployeeTerritories\r
                {\r
                        get\r
                        {\r
-                               return _employeeTerritories;\r
+                               return this._employeeTerritories;\r
                        }\r
                        set\r
                        {\r
-                               _employeeTerritories = value;\r
+                               this._employeeTerritories = value;\r
                        }\r
                }\r
-\r
-               private EntitySet<Employee> _employees;\r
-               [Association(Storage = "_employees", OtherKey = "ReportsTo", ThisKey = "EmployeeID", Name = "fk_Employees_0")]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_employees", OtherKey="ReportsTo", ThisKey="EmployeeID", Name="fk_Employees_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Employee> Employees\r
                {\r
                        get\r
                        {\r
-                               return _employees;\r
+                               return this._employees;\r
                        }\r
                        set\r
                        {\r
-                               _employees = value;\r
+                               this._employees = value;\r
                        }\r
                }\r
-\r
-               private EntitySet<Order> _orders;\r
-               [Association(Storage = "_orders", OtherKey = "EmployeeID", ThisKey = "EmployeeID", Name = "fk_Orders_1")]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_orders", OtherKey="EmployeeID", ThisKey="EmployeeID", Name="fk_Orders_1")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Order> Orders\r
                {\r
                        get\r
                        {\r
-                               return _orders;\r
+                               return this._orders;\r
                        }\r
                        set\r
                        {\r
-                               _orders = value;\r
+                               this._orders = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Employee> _reportsToEmployee;\r
-               [Association(Storage = "_reportsToEmployee", OtherKey = "EmployeeID", ThisKey = "ReportsTo", Name = "fk_Employees_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_reportsToEmployee", OtherKey="EmployeeID", ThisKey="ReportsTo", Name="fk_Employees_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Employee ReportsToEmployee\r
                {\r
                        get\r
                        {\r
-                               return _reportsToEmployee.Entity;\r
+                               return this._reportsToEmployee.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _reportsToEmployee.Entity)\r
+                               if (((this._reportsToEmployee.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_reportsToEmployee.Entity != null)\r
+                                       if ((this._reportsToEmployee.Entity != null))\r
                                        {\r
-                                               var previousEmployee = _reportsToEmployee.Entity;\r
-                                               _reportsToEmployee.Entity = null;\r
+                                               Employee previousEmployee = this._reportsToEmployee.Entity;\r
+                                               this._reportsToEmployee.Entity = null;\r
                                                previousEmployee.Employees.Remove(this);\r
                                        }\r
-                                       _reportsToEmployee.Entity = value;\r
-                                       if (value != null)\r
+                                       this._reportsToEmployee.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Employees.Add(this);\r
                                                _reportsTo = value.EmployeeID;\r
@@ -1668,185 +1699,174 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               #region Attachment handlers\r
                private void EmployeeTerritories_Attach(EmployeeTerritory entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Employee = this;\r
                }\r
-\r
+               \r
                private void EmployeeTerritories_Detach(EmployeeTerritory entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Employee = null;\r
                }\r
-\r
+               \r
                private void Employees_Attach(Employee entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.ReportsToEmployee = this;\r
                }\r
-\r
+               \r
                private void Employees_Detach(Employee entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.ReportsToEmployee = null;\r
                }\r
-\r
+               \r
                private void Orders_Attach(Order entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Employee = this;\r
                }\r
-\r
+               \r
                private void Orders_Detach(Order entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Employee = null;\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Employee()\r
-               {\r
-                       _employeeTerritories = new EntitySet<EmployeeTerritory>(EmployeeTerritories_Attach, EmployeeTerritories_Detach);\r
-                       _employees = new EntitySet<Employee>(Employees_Attach, Employees_Detach);\r
-                       _orders = new EntitySet<Order>(Orders_Attach, Orders_Detach);\r
-                       _reportsToEmployee = new EntityRef<Employee>();\r
-                       OnCreated();\r
-               }\r
-\r
                #endregion\r
-\r
        }\r
-\r
-       [Table(Name = "main.EmployeeTerritories")]\r
-       public partial class EmployeeTerritory : INotifyPropertyChanging, INotifyPropertyChanged\r
+       \r
+       [Table(Name="main.EmployeeTerritories")]\r
+       public partial class EmployeeTerritory : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged\r
        {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private int _employeeID;\r
+               \r
+               private string _territoryID;\r
+               \r
+               private EntityRef<Territory> _territory = new EntityRef<Territory>();\r
+               \r
+               private EntityRef<Employee> _employee = new EntityRef<Employee>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnEmployeeIDChanged();\r
+               \r
                partial void OnEmployeeIDChanging(int value);\r
+               \r
                partial void OnTerritoryIDChanged();\r
+               \r
                partial void OnTerritoryIDChanging(string value);\r
-\r
                #endregion\r
-\r
-               #region int EmployeeID\r
-\r
-               private int _employeeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_employeeID", Name = "EmployeeID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               \r
+               public EmployeeTerritory()\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_employeeID", Name="EmployeeID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public int EmployeeID\r
                {\r
                        get\r
                        {\r
-                               return _employeeID;\r
+                               return this._employeeID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _employeeID)\r
+                               if ((_employeeID != value))\r
                                {\r
                                        if (_employee.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnEmployeeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _employeeID = value;\r
-                                       SendPropertyChanged("EmployeeID");\r
-                                       OnEmployeeIDChanged();\r
+                                       this.OnEmployeeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._employeeID = value;\r
+                                       this.SendPropertyChanged("EmployeeID");\r
+                                       this.OnEmployeeIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string TerritoryID\r
-\r
-               private string _territoryID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_territoryID", Name = "TerritoryID", DbType = "nvarchar", IsPrimaryKey = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_territoryID", Name="TerritoryID", DbType="nvarchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string TerritoryID\r
                {\r
                        get\r
                        {\r
-                               return _territoryID;\r
+                               return this._territoryID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _territoryID)\r
+                               if (((_territoryID == value) \r
+                                                       == false))\r
                                {\r
                                        if (_territory.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnTerritoryIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _territoryID = value;\r
-                                       SendPropertyChanged("TerritoryID");\r
-                                       OnTerritoryIDChanged();\r
+                                       this.OnTerritoryIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._territoryID = value;\r
+                                       this.SendPropertyChanged("TerritoryID");\r
+                                       this.OnTerritoryIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Territory> _territory;\r
-               [Association(Storage = "_territory", OtherKey = "TerritoryID", ThisKey = "TerritoryID", Name = "fk_EmployeeTerritories_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_territory", OtherKey="TerritoryID", ThisKey="TerritoryID", Name="fk_EmployeeTerritories_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Territory Territory\r
                {\r
                        get\r
                        {\r
-                               return _territory.Entity;\r
+                               return this._territory.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _territory.Entity)\r
+                               if (((this._territory.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_territory.Entity != null)\r
+                                       if ((this._territory.Entity != null))\r
                                        {\r
-                                               var previousTerritory = _territory.Entity;\r
-                                               _territory.Entity = null;\r
+                                               Territory previousTerritory = this._territory.Entity;\r
+                                               this._territory.Entity = null;\r
                                                previousTerritory.EmployeeTerritories.Remove(this);\r
                                        }\r
-                                       _territory.Entity = value;\r
-                                       if (value != null)\r
+                                       this._territory.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.EmployeeTerritories.Add(this);\r
                                                _territoryID = value.TerritoryID;\r
@@ -1858,28 +1878,28 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-               private EntityRef<Employee> _employee;\r
-               [Association(Storage = "_employee", OtherKey = "EmployeeID", ThisKey = "EmployeeID", Name = "fk_EmployeeTerritories_1", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_employee", OtherKey="EmployeeID", ThisKey="EmployeeID", Name="fk_EmployeeTerritories_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Employee Employee\r
                {\r
                        get\r
                        {\r
-                               return _employee.Entity;\r
+                               return this._employee.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _employee.Entity)\r
+                               if (((this._employee.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_employee.Entity != null)\r
+                                       if ((this._employee.Entity != null))\r
                                        {\r
-                                               var previousEmployee = _employee.Entity;\r
-                                               _employee.Entity = null;\r
+                                               Employee previousEmployee = this._employee.Entity;\r
+                                               this._employee.Entity = null;\r
                                                previousEmployee.EmployeeTerritories.Remove(this);\r
                                        }\r
-                                       _employee.Entity = value;\r
-                                       if (value != null)\r
+                                       this._employee.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.EmployeeTerritories.Add(this);\r
                                                _employeeID = value.EmployeeID;\r
@@ -1891,508 +1911,491 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public EmployeeTerritory()\r
-               {\r
-                       _territory = new EntityRef<Territory>();\r
-                       _employee = new EntityRef<Employee>();\r
-                       OnCreated();\r
-               }\r
-\r
                #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Orders")]\r
-       public partial class Order : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
                protected virtual void SendPropertyChanging()\r
                {\r
-                       if (PropertyChanging != null)\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               h(this, emptyChangingEventArgs);\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
+               \r
                protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="main.Orders")]\r
+       public partial class Order : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _customerID;\r
+               \r
+               private System.Nullable<int> _employeeID;\r
+               \r
+               private System.Nullable<decimal> _freight;\r
+               \r
+               private System.Nullable<System.DateTime> _orderDate;\r
+               \r
+               private int _orderID;\r
+               \r
+               private System.Nullable<System.DateTime> _requiredDate;\r
+               \r
+               private string _shipAddress;\r
+               \r
+               private string _shipCity;\r
+               \r
+               private string _shipCountry;\r
+               \r
+               private string _shipName;\r
+               \r
+               private System.Nullable<System.DateTime> _shippedDate;\r
+               \r
+               private string _shipPostalCode;\r
+               \r
+               private string _shipRegion;\r
+               \r
+               private System.Nullable<int> _shipVia;\r
+               \r
+               private EntitySet<OrderDetail> _orderDetails;\r
+               \r
+               private EntityRef<Shipper> _shipper = new EntityRef<Shipper>();\r
+               \r
+               private EntityRef<Employee> _employee = new EntityRef<Employee>();\r
+               \r
+               private EntityRef<Customer> _customer = new EntityRef<Customer>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnCustomerIDChanged();\r
+               \r
                partial void OnCustomerIDChanging(string value);\r
+               \r
                partial void OnEmployeeIDChanged();\r
-               partial void OnEmployeeIDChanging(int? value);\r
+               \r
+               partial void OnEmployeeIDChanging(System.Nullable<int> value);\r
+               \r
                partial void OnFreightChanged();\r
-               partial void OnFreightChanging(decimal? value);\r
+               \r
+               partial void OnFreightChanging(System.Nullable<decimal> value);\r
+               \r
                partial void OnOrderDateChanged();\r
-               partial void OnOrderDateChanging(DateTime? value);\r
+               \r
+               partial void OnOrderDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
                partial void OnOrderIDChanged();\r
+               \r
                partial void OnOrderIDChanging(int value);\r
+               \r
                partial void OnRequiredDateChanged();\r
-               partial void OnRequiredDateChanging(DateTime? value);\r
+               \r
+               partial void OnRequiredDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
                partial void OnShipAddressChanged();\r
+               \r
                partial void OnShipAddressChanging(string value);\r
+               \r
                partial void OnShipCityChanged();\r
+               \r
                partial void OnShipCityChanging(string value);\r
+               \r
                partial void OnShipCountryChanged();\r
+               \r
                partial void OnShipCountryChanging(string value);\r
+               \r
                partial void OnShipNameChanged();\r
+               \r
                partial void OnShipNameChanging(string value);\r
+               \r
                partial void OnShippedDateChanged();\r
-               partial void OnShippedDateChanging(DateTime? value);\r
+               \r
+               partial void OnShippedDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
                partial void OnShipPostalCodeChanged();\r
+               \r
                partial void OnShipPostalCodeChanging(string value);\r
+               \r
                partial void OnShipRegionChanged();\r
+               \r
                partial void OnShipRegionChanging(string value);\r
+               \r
                partial void OnShipViaChanged();\r
-               partial void OnShipViaChanging(int? value);\r
-\r
+               \r
+               partial void OnShipViaChanging(System.Nullable<int> value);\r
                #endregion\r
-\r
-               #region string CustomerID\r
-\r
-               private string _customerID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerID", Name = "CustomerID", DbType = "nchar (5)", AutoSync = AutoSync.Never)]\r
+               \r
+               \r
+               public Order()\r
+               {\r
+                       _orderDetails = new EntitySet<OrderDetail>(new Action<OrderDetail>(this.OrderDetails_Attach), new Action<OrderDetail>(this.OrderDetails_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_customerID", Name="CustomerID", DbType="nchar (5)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string CustomerID\r
                {\r
                        get\r
                        {\r
-                               return _customerID;\r
+                               return this._customerID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerID)\r
+                               if (((_customerID == value) \r
+                                                       == false))\r
                                {\r
                                        if (_customer.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnCustomerIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerID = value;\r
-                                       SendPropertyChanged("CustomerID");\r
-                                       OnCustomerIDChanged();\r
+                                       this.OnCustomerIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerID = value;\r
+                                       this.SendPropertyChanged("CustomerID");\r
+                                       this.OnCustomerIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region int? EmployeeID\r
-\r
-               private int? _employeeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_employeeID", Name = "EmployeeID", DbType = "INTEGER", AutoSync = AutoSync.Never)]\r
-               public int? EmployeeID\r
+               \r
+               [Column(Storage="_employeeID", Name="EmployeeID", DbType="INTEGER", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<int> EmployeeID\r
                {\r
                        get\r
                        {\r
-                               return _employeeID;\r
+                               return this._employeeID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _employeeID)\r
+                               if ((_employeeID != value))\r
                                {\r
                                        if (_employee.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnEmployeeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _employeeID = value;\r
-                                       SendPropertyChanged("EmployeeID");\r
-                                       OnEmployeeIDChanged();\r
+                                       this.OnEmployeeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._employeeID = value;\r
+                                       this.SendPropertyChanged("EmployeeID");\r
+                                       this.OnEmployeeIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region decimal? Freight\r
-\r
-               private decimal? _freight;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_freight", Name = "Freight", DbType = "money", AutoSync = AutoSync.Never)]\r
-               public decimal? Freight\r
+               \r
+               [Column(Storage="_freight", Name="Freight", DbType="money", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<decimal> Freight\r
                {\r
                        get\r
                        {\r
-                               return _freight;\r
+                               return this._freight;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _freight)\r
+                               if ((_freight != value))\r
                                {\r
-                                       OnFreightChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _freight = value;\r
-                                       SendPropertyChanged("Freight");\r
-                                       OnFreightChanged();\r
+                                       this.OnFreightChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._freight = value;\r
+                                       this.SendPropertyChanged("Freight");\r
+                                       this.OnFreightChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? OrderDate\r
-\r
-               private DateTime? _orderDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_orderDate", Name = "OrderDate", DbType = "datetime", AutoSync = AutoSync.Never)]\r
-               public DateTime? OrderDate\r
+               \r
+               [Column(Storage="_orderDate", Name="OrderDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> OrderDate\r
                {\r
                        get\r
                        {\r
-                               return _orderDate;\r
+                               return this._orderDate;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _orderDate)\r
+                               if ((_orderDate != value))\r
                                {\r
-                                       OnOrderDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _orderDate = value;\r
-                                       SendPropertyChanged("OrderDate");\r
-                                       OnOrderDateChanged();\r
+                                       this.OnOrderDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._orderDate = value;\r
+                                       this.SendPropertyChanged("OrderDate");\r
+                                       this.OnOrderDateChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region int OrderID\r
-\r
-               private int _orderID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_orderID", Name = "OrderID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_orderID", Name="OrderID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public int OrderID\r
                {\r
                        get\r
                        {\r
-                               return _orderID;\r
+                               return this._orderID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _orderID)\r
+                               if ((_orderID != value))\r
                                {\r
-                                       OnOrderIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _orderID = value;\r
-                                       SendPropertyChanged("OrderID");\r
-                                       OnOrderIDChanged();\r
+                                       this.OnOrderIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._orderID = value;\r
+                                       this.SendPropertyChanged("OrderID");\r
+                                       this.OnOrderIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? RequiredDate\r
-\r
-               private DateTime? _requiredDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_requiredDate", Name = "RequiredDate", DbType = "datetime", AutoSync = AutoSync.Never)]\r
-               public DateTime? RequiredDate\r
+               \r
+               [Column(Storage="_requiredDate", Name="RequiredDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> RequiredDate\r
                {\r
                        get\r
                        {\r
-                               return _requiredDate;\r
+                               return this._requiredDate;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _requiredDate)\r
+                               if ((_requiredDate != value))\r
                                {\r
-                                       OnRequiredDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _requiredDate = value;\r
-                                       SendPropertyChanged("RequiredDate");\r
-                                       OnRequiredDateChanged();\r
+                                       this.OnRequiredDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._requiredDate = value;\r
+                                       this.SendPropertyChanged("RequiredDate");\r
+                                       this.OnRequiredDateChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ShipAddress\r
-\r
-               private string _shipAddress;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipAddress", Name = "ShipAddress", DbType = "nvarchar (60)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_shipAddress", Name="ShipAddress", DbType="nvarchar (60)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ShipAddress\r
                {\r
                        get\r
                        {\r
-                               return _shipAddress;\r
+                               return this._shipAddress;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipAddress)\r
+                               if (((_shipAddress == value) \r
+                                                       == false))\r
                                {\r
-                                       OnShipAddressChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipAddress = value;\r
-                                       SendPropertyChanged("ShipAddress");\r
-                                       OnShipAddressChanged();\r
+                                       this.OnShipAddressChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipAddress = value;\r
+                                       this.SendPropertyChanged("ShipAddress");\r
+                                       this.OnShipAddressChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ShipCity\r
-\r
-               private string _shipCity;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipCity", Name = "ShipCity", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_shipCity", Name="ShipCity", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ShipCity\r
                {\r
                        get\r
                        {\r
-                               return _shipCity;\r
+                               return this._shipCity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipCity)\r
+                               if (((_shipCity == value) \r
+                                                       == false))\r
                                {\r
-                                       OnShipCityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipCity = value;\r
-                                       SendPropertyChanged("ShipCity");\r
-                                       OnShipCityChanged();\r
+                                       this.OnShipCityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipCity = value;\r
+                                       this.SendPropertyChanged("ShipCity");\r
+                                       this.OnShipCityChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ShipCountry\r
-\r
-               private string _shipCountry;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipCountry", Name = "ShipCountry", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_shipCountry", Name="ShipCountry", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ShipCountry\r
                {\r
                        get\r
                        {\r
-                               return _shipCountry;\r
+                               return this._shipCountry;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipCountry)\r
+                               if (((_shipCountry == value) \r
+                                                       == false))\r
                                {\r
-                                       OnShipCountryChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipCountry = value;\r
-                                       SendPropertyChanged("ShipCountry");\r
-                                       OnShipCountryChanged();\r
+                                       this.OnShipCountryChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipCountry = value;\r
+                                       this.SendPropertyChanged("ShipCountry");\r
+                                       this.OnShipCountryChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ShipName\r
-\r
-               private string _shipName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipName", Name = "ShipName", DbType = "nvarchar (40)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_shipName", Name="ShipName", DbType="nvarchar (40)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ShipName\r
                {\r
                        get\r
                        {\r
-                               return _shipName;\r
+                               return this._shipName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipName)\r
+                               if (((_shipName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnShipNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipName = value;\r
-                                       SendPropertyChanged("ShipName");\r
-                                       OnShipNameChanged();\r
+                                       this.OnShipNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipName = value;\r
+                                       this.SendPropertyChanged("ShipName");\r
+                                       this.OnShipNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? ShippedDate\r
-\r
-               private DateTime? _shippedDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shippedDate", Name = "ShippedDate", DbType = "datetime", AutoSync = AutoSync.Never)]\r
-               public DateTime? ShippedDate\r
+               \r
+               [Column(Storage="_shippedDate", Name="ShippedDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> ShippedDate\r
                {\r
                        get\r
                        {\r
-                               return _shippedDate;\r
+                               return this._shippedDate;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shippedDate)\r
+                               if ((_shippedDate != value))\r
                                {\r
-                                       OnShippedDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shippedDate = value;\r
-                                       SendPropertyChanged("ShippedDate");\r
-                                       OnShippedDateChanged();\r
+                                       this.OnShippedDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shippedDate = value;\r
+                                       this.SendPropertyChanged("ShippedDate");\r
+                                       this.OnShippedDateChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ShipPostalCode\r
-\r
-               private string _shipPostalCode;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipPostalCode", Name = "ShipPostalCode", DbType = "nvarchar (10)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_shipPostalCode", Name="ShipPostalCode", DbType="nvarchar (10)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ShipPostalCode\r
                {\r
                        get\r
                        {\r
-                               return _shipPostalCode;\r
+                               return this._shipPostalCode;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipPostalCode)\r
+                               if (((_shipPostalCode == value) \r
+                                                       == false))\r
                                {\r
-                                       OnShipPostalCodeChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipPostalCode = value;\r
-                                       SendPropertyChanged("ShipPostalCode");\r
-                                       OnShipPostalCodeChanged();\r
+                                       this.OnShipPostalCodeChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipPostalCode = value;\r
+                                       this.SendPropertyChanged("ShipPostalCode");\r
+                                       this.OnShipPostalCodeChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ShipRegion\r
-\r
-               private string _shipRegion;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipRegion", Name = "ShipRegion", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_shipRegion", Name="ShipRegion", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ShipRegion\r
                {\r
                        get\r
                        {\r
-                               return _shipRegion;\r
+                               return this._shipRegion;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipRegion)\r
+                               if (((_shipRegion == value) \r
+                                                       == false))\r
                                {\r
-                                       OnShipRegionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipRegion = value;\r
-                                       SendPropertyChanged("ShipRegion");\r
-                                       OnShipRegionChanged();\r
+                                       this.OnShipRegionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipRegion = value;\r
+                                       this.SendPropertyChanged("ShipRegion");\r
+                                       this.OnShipRegionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region int? ShipVia\r
-\r
-               private int? _shipVia;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipVia", Name = "ShipVia", DbType = "INTEGER", AutoSync = AutoSync.Never)]\r
-               public int? ShipVia\r
+               \r
+               [Column(Storage="_shipVia", Name="ShipVia", DbType="INTEGER", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<int> ShipVia\r
                {\r
                        get\r
                        {\r
-                               return _shipVia;\r
+                               return this._shipVia;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipVia)\r
+                               if ((_shipVia != value))\r
                                {\r
                                        if (_shipper.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnShipViaChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipVia = value;\r
-                                       SendPropertyChanged("ShipVia");\r
-                                       OnShipViaChanged();\r
+                                       this.OnShipViaChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipVia = value;\r
+                                       this.SendPropertyChanged("ShipVia");\r
+                                       this.OnShipViaChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<OrderDetail> _orderDetails;\r
-               [Association(Storage = "_orderDetails", OtherKey = "OrderID", ThisKey = "OrderID", Name = "\"fk_Order Details_1\"")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_orderDetails", OtherKey="OrderID", ThisKey="OrderID", Name="fk_Order Details_1")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<OrderDetail> OrderDetails\r
                {\r
                        get\r
                        {\r
-                               return _orderDetails;\r
+                               return this._orderDetails;\r
                        }\r
                        set\r
                        {\r
-                               _orderDetails = value;\r
+                               this._orderDetails = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Shipper> _shipper;\r
-               [Association(Storage = "_shipper", OtherKey = "ShipperID", ThisKey = "ShipVia", Name = "fk_Orders_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_shipper", OtherKey="ShipperID", ThisKey="ShipVia", Name="fk_Orders_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Shipper Shipper\r
                {\r
                        get\r
                        {\r
-                               return _shipper.Entity;\r
+                               return this._shipper.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipper.Entity)\r
+                               if (((this._shipper.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_shipper.Entity != null)\r
+                                       if ((this._shipper.Entity != null))\r
                                        {\r
-                                               var previousShipper = _shipper.Entity;\r
-                                               _shipper.Entity = null;\r
+                                               Shipper previousShipper = this._shipper.Entity;\r
+                                               this._shipper.Entity = null;\r
                                                previousShipper.Orders.Remove(this);\r
                                        }\r
-                                       _shipper.Entity = value;\r
-                                       if (value != null)\r
+                                       this._shipper.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Orders.Add(this);\r
                                                _shipVia = value.ShipperID;\r
@@ -2404,28 +2407,28 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-               private EntityRef<Employee> _employee;\r
-               [Association(Storage = "_employee", OtherKey = "EmployeeID", ThisKey = "EmployeeID", Name = "fk_Orders_1", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_employee", OtherKey="EmployeeID", ThisKey="EmployeeID", Name="fk_Orders_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Employee Employee\r
                {\r
                        get\r
                        {\r
-                               return _employee.Entity;\r
+                               return this._employee.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _employee.Entity)\r
+                               if (((this._employee.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_employee.Entity != null)\r
+                                       if ((this._employee.Entity != null))\r
                                        {\r
-                                               var previousEmployee = _employee.Entity;\r
-                                               _employee.Entity = null;\r
+                                               Employee previousEmployee = this._employee.Entity;\r
+                                               this._employee.Entity = null;\r
                                                previousEmployee.Orders.Remove(this);\r
                                        }\r
-                                       _employee.Entity = value;\r
-                                       if (value != null)\r
+                                       this._employee.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Orders.Add(this);\r
                                                _employeeID = value.EmployeeID;\r
@@ -2437,28 +2440,28 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-               private EntityRef<Customer> _customer;\r
-               [Association(Storage = "_customer", OtherKey = "CustomerID", ThisKey = "CustomerID", Name = "fk_Orders_2", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_customer", OtherKey="CustomerID", ThisKey="CustomerID", Name="fk_Orders_2", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Customer Customer\r
                {\r
                        get\r
                        {\r
-                               return _customer.Entity;\r
+                               return this._customer.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customer.Entity)\r
+                               if (((this._customer.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_customer.Entity != null)\r
+                                       if ((this._customer.Entity != null))\r
                                        {\r
-                                               var previousCustomer = _customer.Entity;\r
-                                               _customer.Entity = null;\r
+                                               Customer previousCustomer = this._customer.Entity;\r
+                                               this._customer.Entity = null;\r
                                                previousCustomer.Orders.Remove(this);\r
                                        }\r
-                                       _customer.Entity = value;\r
-                                       if (value != null)\r
+                                       this._customer.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Orders.Add(this);\r
                                                _customerID = value.CustomerID;\r
@@ -2470,249 +2473,230 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void OrderDetails_Attach(OrderDetail entity)\r
-               {\r
-                       entity.Order = this;\r
-               }\r
-\r
-               private void OrderDetails_Detach(OrderDetail entity)\r
-               {\r
-                       entity.Order = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Order()\r
-               {\r
-                       _orderDetails = new EntitySet<OrderDetail>(OrderDetails_Attach, OrderDetails_Detach);\r
-                       _shipper = new EntityRef<Shipper>();\r
-                       _employee = new EntityRef<Employee>();\r
-                       _customer = new EntityRef<Customer>();\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.\"Order Details\"")]\r
-       public partial class OrderDetail : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
                protected virtual void SendPropertyChanging()\r
                {\r
-                       if (PropertyChanging != null)\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               h(this, emptyChangingEventArgs);\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
+               \r
                protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
                        }\r
                }\r
-\r
+               \r
+               #region Attachment handlers\r
+               private void OrderDetails_Attach(OrderDetail entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Order = this;\r
+               }\r
+               \r
+               private void OrderDetails_Detach(OrderDetail entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Order = null;\r
+               }\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="main.Order Details")]\r
+       public partial class OrderDetail : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private float _discount;\r
+               \r
+               private int _orderID;\r
+               \r
+               private int _productID;\r
+               \r
+               private short _quantity;\r
+               \r
+               private decimal _unitPrice;\r
+               \r
+               private EntityRef<Product> _product = new EntityRef<Product>();\r
+               \r
+               private EntityRef<Order> _order = new EntityRef<Order>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnDiscountChanged();\r
+               \r
                partial void OnDiscountChanging(float value);\r
+               \r
                partial void OnOrderIDChanged();\r
+               \r
                partial void OnOrderIDChanging(int value);\r
+               \r
                partial void OnProductIDChanged();\r
+               \r
                partial void OnProductIDChanging(int value);\r
+               \r
                partial void OnQuantityChanged();\r
+               \r
                partial void OnQuantityChanging(short value);\r
+               \r
                partial void OnUnitPriceChanged();\r
+               \r
                partial void OnUnitPriceChanging(decimal value);\r
-\r
                #endregion\r
-\r
-               #region float Discount\r
-\r
-               private float _discount;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_discount", Name = "Discount", DbType = "real", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               \r
+               public OrderDetail()\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_discount", Name="Discount", DbType="real", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public float Discount\r
                {\r
                        get\r
                        {\r
-                               return _discount;\r
+                               return this._discount;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _discount)\r
+                               if ((_discount != value))\r
                                {\r
-                                       OnDiscountChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _discount = value;\r
-                                       SendPropertyChanged("Discount");\r
-                                       OnDiscountChanged();\r
+                                       this.OnDiscountChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._discount = value;\r
+                                       this.SendPropertyChanged("Discount");\r
+                                       this.OnDiscountChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region int OrderID\r
-\r
-               private int _orderID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_orderID", Name = "OrderID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_orderID", Name="OrderID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public int OrderID\r
                {\r
                        get\r
                        {\r
-                               return _orderID;\r
+                               return this._orderID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _orderID)\r
+                               if ((_orderID != value))\r
                                {\r
                                        if (_order.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnOrderIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _orderID = value;\r
-                                       SendPropertyChanged("OrderID");\r
-                                       OnOrderIDChanged();\r
+                                       this.OnOrderIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._orderID = value;\r
+                                       this.SendPropertyChanged("OrderID");\r
+                                       this.OnOrderIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region int ProductID\r
-\r
-               private int _productID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_productID", Name = "ProductID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_productID", Name="ProductID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public int ProductID\r
                {\r
                        get\r
                        {\r
-                               return _productID;\r
+                               return this._productID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _productID)\r
+                               if ((_productID != value))\r
                                {\r
                                        if (_product.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnProductIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _productID = value;\r
-                                       SendPropertyChanged("ProductID");\r
-                                       OnProductIDChanged();\r
+                                       this.OnProductIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._productID = value;\r
+                                       this.SendPropertyChanged("ProductID");\r
+                                       this.OnProductIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region short Quantity\r
-\r
-               private short _quantity;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_quantity", Name = "Quantity", DbType = "smallint", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_quantity", Name="Quantity", DbType="smallint", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public short Quantity\r
                {\r
                        get\r
                        {\r
-                               return _quantity;\r
+                               return this._quantity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _quantity)\r
+                               if ((_quantity != value))\r
                                {\r
-                                       OnQuantityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _quantity = value;\r
-                                       SendPropertyChanged("Quantity");\r
-                                       OnQuantityChanged();\r
+                                       this.OnQuantityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._quantity = value;\r
+                                       this.SendPropertyChanged("Quantity");\r
+                                       this.OnQuantityChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region decimal UnitPrice\r
-\r
-               private decimal _unitPrice;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_unitPrice", Name = "UnitPrice", DbType = "money", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_unitPrice", Name="UnitPrice", DbType="money", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public decimal UnitPrice\r
                {\r
                        get\r
                        {\r
-                               return _unitPrice;\r
+                               return this._unitPrice;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _unitPrice)\r
+                               if ((_unitPrice != value))\r
                                {\r
-                                       OnUnitPriceChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _unitPrice = value;\r
-                                       SendPropertyChanged("UnitPrice");\r
-                                       OnUnitPriceChanged();\r
+                                       this.OnUnitPriceChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._unitPrice = value;\r
+                                       this.SendPropertyChanged("UnitPrice");\r
+                                       this.OnUnitPriceChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Product> _product;\r
-               [Association(Storage = "_product", OtherKey = "ProductID", ThisKey = "ProductID", Name = "\"fk_Order Details_0\"", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_product", OtherKey="ProductID", ThisKey="ProductID", Name="fk_Order Details_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Product Product\r
                {\r
                        get\r
                        {\r
-                               return _product.Entity;\r
+                               return this._product.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _product.Entity)\r
+                               if (((this._product.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_product.Entity != null)\r
+                                       if ((this._product.Entity != null))\r
                                        {\r
-                                               var previousProduct = _product.Entity;\r
-                                               _product.Entity = null;\r
+                                               Product previousProduct = this._product.Entity;\r
+                                               this._product.Entity = null;\r
                                                previousProduct.OrderDetails.Remove(this);\r
                                        }\r
-                                       _product.Entity = value;\r
-                                       if (value != null)\r
+                                       this._product.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.OrderDetails.Add(this);\r
                                                _productID = value.ProductID;\r
@@ -2724,28 +2708,28 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-               private EntityRef<Order> _order;\r
-               [Association(Storage = "_order", OtherKey = "OrderID", ThisKey = "OrderID", Name = "\"fk_Order Details_1\"", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_order", OtherKey="OrderID", ThisKey="OrderID", Name="fk_Order Details_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Order Order\r
                {\r
                        get\r
                        {\r
-                               return _order.Entity;\r
+                               return this._order.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _order.Entity)\r
+                               if (((this._order.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_order.Entity != null)\r
+                                       if ((this._order.Entity != null))\r
                                        {\r
-                                               var previousOrder = _order.Entity;\r
-                                               _order.Entity = null;\r
+                                               Order previousOrder = this._order.Entity;\r
+                                               this._order.Entity = null;\r
                                                previousOrder.OrderDetails.Remove(this);\r
                                        }\r
-                                       _order.Entity = value;\r
-                                       if (value != null)\r
+                                       this._order.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.OrderDetails.Add(this);\r
                                                _orderID = value.OrderID;\r
@@ -2757,392 +2741,372 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public OrderDetail()\r
-               {\r
-                       _product = new EntityRef<Product>();\r
-                       _order = new EntityRef<Order>();\r
-                       OnCreated();\r
-               }\r
-\r
                #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Products")]\r
-       public partial class Product : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
                protected virtual void SendPropertyChanging()\r
                {\r
-                       if (PropertyChanging != null)\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               h(this, emptyChangingEventArgs);\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
+               \r
                protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="main.Products")]\r
+       public partial class Product : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private System.Nullable<int> _categoryID;\r
+               \r
+               private bool _discontinued;\r
+               \r
+               private int _productID;\r
+               \r
+               private string _productName;\r
+               \r
+               private string _quantityPerUnit;\r
+               \r
+               private System.Nullable<short> _reorderLevel;\r
+               \r
+               private System.Nullable<int> _supplierID;\r
+               \r
+               private System.Nullable<decimal> _unitPrice;\r
+               \r
+               private System.Nullable<short> _unitsInStock;\r
+               \r
+               private System.Nullable<short> _unitsOnOrder;\r
+               \r
+               private EntitySet<OrderDetail> _orderDetails;\r
+               \r
+               private EntityRef<Supplier> _supplier = new EntityRef<Supplier>();\r
+               \r
+               private EntityRef<Category> _category = new EntityRef<Category>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnCategoryIDChanged();\r
-               partial void OnCategoryIDChanging(int? value);\r
+               \r
+               partial void OnCategoryIDChanging(System.Nullable<int> value);\r
+               \r
                partial void OnDiscontinuedChanged();\r
+               \r
                partial void OnDiscontinuedChanging(bool value);\r
+               \r
                partial void OnProductIDChanged();\r
+               \r
                partial void OnProductIDChanging(int value);\r
+               \r
                partial void OnProductNameChanged();\r
+               \r
                partial void OnProductNameChanging(string value);\r
+               \r
                partial void OnQuantityPerUnitChanged();\r
+               \r
                partial void OnQuantityPerUnitChanging(string value);\r
+               \r
                partial void OnReorderLevelChanged();\r
-               partial void OnReorderLevelChanging(short? value);\r
+               \r
+               partial void OnReorderLevelChanging(System.Nullable<short> value);\r
+               \r
                partial void OnSupplierIDChanged();\r
-               partial void OnSupplierIDChanging(int? value);\r
+               \r
+               partial void OnSupplierIDChanging(System.Nullable<int> value);\r
+               \r
                partial void OnUnitPriceChanged();\r
-               partial void OnUnitPriceChanging(decimal? value);\r
+               \r
+               partial void OnUnitPriceChanging(System.Nullable<decimal> value);\r
+               \r
                partial void OnUnitsInStockChanged();\r
-               partial void OnUnitsInStockChanging(short? value);\r
+               \r
+               partial void OnUnitsInStockChanging(System.Nullable<short> value);\r
+               \r
                partial void OnUnitsOnOrderChanged();\r
-               partial void OnUnitsOnOrderChanging(short? value);\r
-\r
+               \r
+               partial void OnUnitsOnOrderChanging(System.Nullable<short> value);\r
                #endregion\r
-\r
-               #region int? CategoryID\r
-\r
-               private int? _categoryID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_categoryID", Name = "CategoryID", DbType = "INTEGER", AutoSync = AutoSync.Never)]\r
-               public int? CategoryID\r
+               \r
+               \r
+               public Product()\r
+               {\r
+                       _orderDetails = new EntitySet<OrderDetail>(new Action<OrderDetail>(this.OrderDetails_Attach), new Action<OrderDetail>(this.OrderDetails_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_categoryID", Name="CategoryID", DbType="INTEGER", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<int> CategoryID\r
                {\r
                        get\r
                        {\r
-                               return _categoryID;\r
+                               return this._categoryID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _categoryID)\r
+                               if ((_categoryID != value))\r
                                {\r
                                        if (_category.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnCategoryIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _categoryID = value;\r
-                                       SendPropertyChanged("CategoryID");\r
-                                       OnCategoryIDChanged();\r
+                                       this.OnCategoryIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._categoryID = value;\r
+                                       this.SendPropertyChanged("CategoryID");\r
+                                       this.OnCategoryIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region bool Discontinued\r
-\r
-               private bool _discontinued;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_discontinued", Name = "Discontinued", DbType = "bit", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_discontinued", Name="Discontinued", DbType="bit", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public bool Discontinued\r
                {\r
                        get\r
                        {\r
-                               return _discontinued;\r
+                               return this._discontinued;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _discontinued)\r
+                               if ((_discontinued != value))\r
                                {\r
-                                       OnDiscontinuedChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _discontinued = value;\r
-                                       SendPropertyChanged("Discontinued");\r
-                                       OnDiscontinuedChanged();\r
+                                       this.OnDiscontinuedChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._discontinued = value;\r
+                                       this.SendPropertyChanged("Discontinued");\r
+                                       this.OnDiscontinuedChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region int ProductID\r
-\r
-               private int _productID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_productID", Name = "ProductID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_productID", Name="ProductID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public int ProductID\r
                {\r
                        get\r
                        {\r
-                               return _productID;\r
+                               return this._productID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _productID)\r
+                               if ((_productID != value))\r
                                {\r
-                                       OnProductIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _productID = value;\r
-                                       SendPropertyChanged("ProductID");\r
-                                       OnProductIDChanged();\r
+                                       this.OnProductIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._productID = value;\r
+                                       this.SendPropertyChanged("ProductID");\r
+                                       this.OnProductIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ProductName\r
-\r
-               private string _productName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_productName", Name = "ProductName", DbType = "nvarchar (40)", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_productName", Name="ProductName", DbType="nvarchar (40)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string ProductName\r
                {\r
                        get\r
                        {\r
-                               return _productName;\r
+                               return this._productName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _productName)\r
+                               if (((_productName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnProductNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _productName = value;\r
-                                       SendPropertyChanged("ProductName");\r
-                                       OnProductNameChanged();\r
+                                       this.OnProductNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._productName = value;\r
+                                       this.SendPropertyChanged("ProductName");\r
+                                       this.OnProductNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string QuantityPerUnit\r
-\r
-               private string _quantityPerUnit;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_quantityPerUnit", Name = "QuantityPerUnit", DbType = "nvarchar (20)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_quantityPerUnit", Name="QuantityPerUnit", DbType="nvarchar (20)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string QuantityPerUnit\r
                {\r
                        get\r
                        {\r
-                               return _quantityPerUnit;\r
+                               return this._quantityPerUnit;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _quantityPerUnit)\r
+                               if (((_quantityPerUnit == value) \r
+                                                       == false))\r
                                {\r
-                                       OnQuantityPerUnitChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _quantityPerUnit = value;\r
-                                       SendPropertyChanged("QuantityPerUnit");\r
-                                       OnQuantityPerUnitChanged();\r
+                                       this.OnQuantityPerUnitChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._quantityPerUnit = value;\r
+                                       this.SendPropertyChanged("QuantityPerUnit");\r
+                                       this.OnQuantityPerUnitChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region short? ReorderLevel\r
-\r
-               private short? _reorderLevel;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_reorderLevel", Name = "ReorderLevel", DbType = "smallint", AutoSync = AutoSync.Never)]\r
-               public short? ReorderLevel\r
+               \r
+               [Column(Storage="_reorderLevel", Name="ReorderLevel", DbType="smallint", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<short> ReorderLevel\r
                {\r
                        get\r
                        {\r
-                               return _reorderLevel;\r
+                               return this._reorderLevel;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _reorderLevel)\r
+                               if ((_reorderLevel != value))\r
                                {\r
-                                       OnReorderLevelChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _reorderLevel = value;\r
-                                       SendPropertyChanged("ReorderLevel");\r
-                                       OnReorderLevelChanged();\r
+                                       this.OnReorderLevelChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._reorderLevel = value;\r
+                                       this.SendPropertyChanged("ReorderLevel");\r
+                                       this.OnReorderLevelChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region int? SupplierID\r
-\r
-               private int? _supplierID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_supplierID", Name = "SupplierID", DbType = "INTEGER", AutoSync = AutoSync.Never)]\r
-               public int? SupplierID\r
+               \r
+               [Column(Storage="_supplierID", Name="SupplierID", DbType="INTEGER", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<int> SupplierID\r
                {\r
                        get\r
                        {\r
-                               return _supplierID;\r
+                               return this._supplierID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _supplierID)\r
+                               if ((_supplierID != value))\r
                                {\r
                                        if (_supplier.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnSupplierIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _supplierID = value;\r
-                                       SendPropertyChanged("SupplierID");\r
-                                       OnSupplierIDChanged();\r
+                                       this.OnSupplierIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._supplierID = value;\r
+                                       this.SendPropertyChanged("SupplierID");\r
+                                       this.OnSupplierIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region decimal? UnitPrice\r
-\r
-               private decimal? _unitPrice;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_unitPrice", Name = "UnitPrice", DbType = "money", AutoSync = AutoSync.Never)]\r
-               public decimal? UnitPrice\r
+               \r
+               [Column(Storage="_unitPrice", Name="UnitPrice", DbType="money", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<decimal> UnitPrice\r
                {\r
                        get\r
                        {\r
-                               return _unitPrice;\r
+                               return this._unitPrice;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _unitPrice)\r
+                               if ((_unitPrice != value))\r
                                {\r
-                                       OnUnitPriceChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _unitPrice = value;\r
-                                       SendPropertyChanged("UnitPrice");\r
-                                       OnUnitPriceChanged();\r
+                                       this.OnUnitPriceChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._unitPrice = value;\r
+                                       this.SendPropertyChanged("UnitPrice");\r
+                                       this.OnUnitPriceChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region short? UnitsInStock\r
-\r
-               private short? _unitsInStock;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_unitsInStock", Name = "UnitsInStock", DbType = "smallint", AutoSync = AutoSync.Never)]\r
-               public short? UnitsInStock\r
+               \r
+               [Column(Storage="_unitsInStock", Name="UnitsInStock", DbType="smallint", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<short> UnitsInStock\r
                {\r
                        get\r
                        {\r
-                               return _unitsInStock;\r
+                               return this._unitsInStock;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _unitsInStock)\r
+                               if ((_unitsInStock != value))\r
                                {\r
-                                       OnUnitsInStockChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _unitsInStock = value;\r
-                                       SendPropertyChanged("UnitsInStock");\r
-                                       OnUnitsInStockChanged();\r
+                                       this.OnUnitsInStockChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._unitsInStock = value;\r
+                                       this.SendPropertyChanged("UnitsInStock");\r
+                                       this.OnUnitsInStockChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region short? UnitsOnOrder\r
-\r
-               private short? _unitsOnOrder;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_unitsOnOrder", Name = "UnitsOnOrder", DbType = "smallint", AutoSync = AutoSync.Never)]\r
-               public short? UnitsOnOrder\r
+               \r
+               [Column(Storage="_unitsOnOrder", Name="UnitsOnOrder", DbType="smallint", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<short> UnitsOnOrder\r
                {\r
                        get\r
                        {\r
-                               return _unitsOnOrder;\r
+                               return this._unitsOnOrder;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _unitsOnOrder)\r
+                               if ((_unitsOnOrder != value))\r
                                {\r
-                                       OnUnitsOnOrderChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _unitsOnOrder = value;\r
-                                       SendPropertyChanged("UnitsOnOrder");\r
-                                       OnUnitsOnOrderChanged();\r
+                                       this.OnUnitsOnOrderChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._unitsOnOrder = value;\r
+                                       this.SendPropertyChanged("UnitsOnOrder");\r
+                                       this.OnUnitsOnOrderChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<OrderDetail> _orderDetails;\r
-               [Association(Storage = "_orderDetails", OtherKey = "ProductID", ThisKey = "ProductID", Name = "\"fk_Order Details_0\"")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_orderDetails", OtherKey="ProductID", ThisKey="ProductID", Name="fk_Order Details_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<OrderDetail> OrderDetails\r
                {\r
                        get\r
                        {\r
-                               return _orderDetails;\r
+                               return this._orderDetails;\r
                        }\r
                        set\r
                        {\r
-                               _orderDetails = value;\r
+                               this._orderDetails = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Supplier> _supplier;\r
-               [Association(Storage = "_supplier", OtherKey = "SupplierID", ThisKey = "SupplierID", Name = "fk_Products_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_supplier", OtherKey="SupplierID", ThisKey="SupplierID", Name="fk_Products_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Supplier Supplier\r
                {\r
                        get\r
                        {\r
-                               return _supplier.Entity;\r
+                               return this._supplier.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _supplier.Entity)\r
+                               if (((this._supplier.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_supplier.Entity != null)\r
+                                       if ((this._supplier.Entity != null))\r
                                        {\r
-                                               var previousSupplier = _supplier.Entity;\r
-                                               _supplier.Entity = null;\r
+                                               Supplier previousSupplier = this._supplier.Entity;\r
+                                               this._supplier.Entity = null;\r
                                                previousSupplier.Products.Remove(this);\r
                                        }\r
-                                       _supplier.Entity = value;\r
-                                       if (value != null)\r
+                                       this._supplier.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Products.Add(this);\r
                                                _supplierID = value.SupplierID;\r
@@ -3154,28 +3118,28 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-               private EntityRef<Category> _category;\r
-               [Association(Storage = "_category", OtherKey = "CategoryID", ThisKey = "CategoryID", Name = "fk_Products_1", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_category", OtherKey="CategoryID", ThisKey="CategoryID", Name="fk_Products_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Category Category\r
                {\r
                        get\r
                        {\r
-                               return _category.Entity;\r
+                               return this._category.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _category.Entity)\r
+                               if (((this._category.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_category.Entity != null)\r
+                                       if ((this._category.Entity != null))\r
                                        {\r
-                                               var previousCategory = _category.Entity;\r
-                                               _category.Entity = null;\r
+                                               Category previousCategory = this._category.Entity;\r
+                                               this._category.Entity = null;\r
                                                previousCategory.Products.Remove(this);\r
                                        }\r
-                                       _category.Entity = value;\r
-                                       if (value != null)\r
+                                       this._category.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Products.Add(this);\r
                                                _categoryID = value.CategoryID;\r
@@ -3187,939 +3151,880 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void OrderDetails_Attach(OrderDetail entity)\r
-               {\r
-                       entity.Product = this;\r
-               }\r
-\r
-               private void OrderDetails_Detach(OrderDetail entity)\r
-               {\r
-                       entity.Product = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Product()\r
-               {\r
-                       _orderDetails = new EntitySet<OrderDetail>(OrderDetails_Attach, OrderDetails_Detach);\r
-                       _supplier = new EntityRef<Supplier>();\r
-                       _category = new EntityRef<Category>();\r
-                       OnCreated();\r
-               }\r
-\r
                #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Region")]\r
-       public partial class Region : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
                protected virtual void SendPropertyChanging()\r
                {\r
-                       if (PropertyChanging != null)\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               h(this, emptyChangingEventArgs);\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
+               \r
                protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
                        }\r
                }\r
-\r
+               \r
+               #region Attachment handlers\r
+               private void OrderDetails_Attach(OrderDetail entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Product = this;\r
+               }\r
+               \r
+               private void OrderDetails_Detach(OrderDetail entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Product = null;\r
+               }\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="main.Region")]\r
+       public partial class Region : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _regionDescription;\r
+               \r
+               private int _regionID;\r
+               \r
+               private EntitySet<Territory> _territories;\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnRegionDescriptionChanged();\r
+               \r
                partial void OnRegionDescriptionChanging(string value);\r
+               \r
                partial void OnRegionIDChanged();\r
+               \r
                partial void OnRegionIDChanging(int value);\r
-\r
                #endregion\r
-\r
-               #region string RegionDescription\r
-\r
-               private string _regionDescription;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_regionDescription", Name = "RegionDescription", DbType = "nchar", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               \r
+               public Region()\r
+               {\r
+                       _territories = new EntitySet<Territory>(new Action<Territory>(this.Territories_Attach), new Action<Territory>(this.Territories_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_regionDescription", Name="RegionDescription", DbType="nchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string RegionDescription\r
                {\r
                        get\r
                        {\r
-                               return _regionDescription;\r
+                               return this._regionDescription;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _regionDescription)\r
+                               if (((_regionDescription == value) \r
+                                                       == false))\r
                                {\r
-                                       OnRegionDescriptionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _regionDescription = value;\r
-                                       SendPropertyChanged("RegionDescription");\r
-                                       OnRegionDescriptionChanged();\r
+                                       this.OnRegionDescriptionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._regionDescription = value;\r
+                                       this.SendPropertyChanged("RegionDescription");\r
+                                       this.OnRegionDescriptionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region int RegionID\r
-\r
-               private int _regionID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_regionID", Name = "RegionID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_regionID", Name="RegionID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public int RegionID\r
                {\r
                        get\r
                        {\r
-                               return _regionID;\r
+                               return this._regionID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _regionID)\r
+                               if ((_regionID != value))\r
                                {\r
-                                       OnRegionIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _regionID = value;\r
-                                       SendPropertyChanged("RegionID");\r
-                                       OnRegionIDChanged();\r
+                                       this.OnRegionIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._regionID = value;\r
+                                       this.SendPropertyChanged("RegionID");\r
+                                       this.OnRegionIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<Territory> _territories;\r
-               [Association(Storage = "_territories", OtherKey = "RegionID", ThisKey = "RegionID", Name = "fk_Territories_0")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_territories", OtherKey="RegionID", ThisKey="RegionID", Name="fk_Territories_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Territory> Territories\r
                {\r
                        get\r
                        {\r
-                               return _territories;\r
+                               return this._territories;\r
                        }\r
                        set\r
                        {\r
-                               _territories = value;\r
+                               this._territories = value;\r
                        }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void Territories_Attach(Territory entity)\r
-               {\r
-                       entity.Region = this;\r
-               }\r
-\r
-               private void Territories_Detach(Territory entity)\r
-               {\r
-                       entity.Region = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Region()\r
-               {\r
-                       _territories = new EntitySet<Territory>(Territories_Attach, Territories_Detach);\r
-                       OnCreated();\r
-               }\r
-\r
                #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Shippers")]\r
-       public partial class Shipper : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
                protected virtual void SendPropertyChanging()\r
                {\r
-                       if (PropertyChanging != null)\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               h(this, emptyChangingEventArgs);\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
+               \r
                protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
                        }\r
                }\r
-\r
+               \r
+               #region Attachment handlers\r
+               private void Territories_Attach(Territory entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Region = this;\r
+               }\r
+               \r
+               private void Territories_Detach(Territory entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Region = null;\r
+               }\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="main.Shippers")]\r
+       public partial class Shipper : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _companyName;\r
+               \r
+               private string _phone;\r
+               \r
+               private int _shipperID;\r
+               \r
+               private EntitySet<Order> _orders;\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnCompanyNameChanged();\r
+               \r
                partial void OnCompanyNameChanging(string value);\r
+               \r
                partial void OnPhoneChanged();\r
+               \r
                partial void OnPhoneChanging(string value);\r
+               \r
                partial void OnShipperIDChanged();\r
+               \r
                partial void OnShipperIDChanging(int value);\r
-\r
                #endregion\r
-\r
-               #region string CompanyName\r
-\r
-               private string _companyName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_companyName", Name = "CompanyName", DbType = "nvarchar (40)", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               \r
+               public Shipper()\r
+               {\r
+                       _orders = new EntitySet<Order>(new Action<Order>(this.Orders_Attach), new Action<Order>(this.Orders_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_companyName", Name="CompanyName", DbType="nvarchar (40)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CompanyName\r
                {\r
                        get\r
                        {\r
-                               return _companyName;\r
+                               return this._companyName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _companyName)\r
+                               if (((_companyName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCompanyNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _companyName = value;\r
-                                       SendPropertyChanged("CompanyName");\r
-                                       OnCompanyNameChanged();\r
+                                       this.OnCompanyNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._companyName = value;\r
+                                       this.SendPropertyChanged("CompanyName");\r
+                                       this.OnCompanyNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Phone\r
-\r
-               private string _phone;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_phone", Name = "Phone", DbType = "nvarchar (24)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_phone", Name="Phone", DbType="nvarchar (24)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Phone\r
                {\r
                        get\r
                        {\r
-                               return _phone;\r
+                               return this._phone;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _phone)\r
+                               if (((_phone == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPhoneChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _phone = value;\r
-                                       SendPropertyChanged("Phone");\r
-                                       OnPhoneChanged();\r
+                                       this.OnPhoneChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._phone = value;\r
+                                       this.SendPropertyChanged("Phone");\r
+                                       this.OnPhoneChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region int ShipperID\r
-\r
-               private int _shipperID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipperID", Name = "ShipperID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_shipperID", Name="ShipperID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public int ShipperID\r
                {\r
                        get\r
                        {\r
-                               return _shipperID;\r
+                               return this._shipperID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipperID)\r
+                               if ((_shipperID != value))\r
                                {\r
-                                       OnShipperIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipperID = value;\r
-                                       SendPropertyChanged("ShipperID");\r
-                                       OnShipperIDChanged();\r
+                                       this.OnShipperIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipperID = value;\r
+                                       this.SendPropertyChanged("ShipperID");\r
+                                       this.OnShipperIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<Order> _orders;\r
-               [Association(Storage = "_orders", OtherKey = "ShipVia", ThisKey = "ShipperID", Name = "fk_Orders_0")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_orders", OtherKey="ShipVia", ThisKey="ShipperID", Name="fk_Orders_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Order> Orders\r
                {\r
                        get\r
                        {\r
-                               return _orders;\r
+                               return this._orders;\r
                        }\r
                        set\r
                        {\r
-                               _orders = value;\r
+                               this._orders = value;\r
                        }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void Orders_Attach(Order entity)\r
-               {\r
-                       entity.Shipper = this;\r
-               }\r
-\r
-               private void Orders_Detach(Order entity)\r
-               {\r
-                       entity.Shipper = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Shipper()\r
-               {\r
-                       _orders = new EntitySet<Order>(Orders_Attach, Orders_Detach);\r
-                       OnCreated();\r
-               }\r
-\r
                #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Suppliers")]\r
-       public partial class Supplier : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
                protected virtual void SendPropertyChanging()\r
                {\r
-                       if (PropertyChanging != null)\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               h(this, emptyChangingEventArgs);\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
+               \r
                protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
                        }\r
                }\r
-\r
+               \r
+               #region Attachment handlers\r
+               private void Orders_Attach(Order entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Shipper = this;\r
+               }\r
+               \r
+               private void Orders_Detach(Order entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Shipper = null;\r
+               }\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="main.Suppliers")]\r
+       public partial class Supplier : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _address;\r
+               \r
+               private string _city;\r
+               \r
+               private string _companyName;\r
+               \r
+               private string _contactName;\r
+               \r
+               private string _contactTitle;\r
+               \r
+               private string _country;\r
+               \r
+               private string _fax;\r
+               \r
+               private string _homePage;\r
+               \r
+               private string _phone;\r
+               \r
+               private string _postalCode;\r
+               \r
+               private string _region;\r
+               \r
+               private int _supplierID;\r
+               \r
+               private EntitySet<Product> _products;\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnAddressChanged();\r
+               \r
                partial void OnAddressChanging(string value);\r
+               \r
                partial void OnCityChanged();\r
+               \r
                partial void OnCityChanging(string value);\r
+               \r
                partial void OnCompanyNameChanged();\r
+               \r
                partial void OnCompanyNameChanging(string value);\r
+               \r
                partial void OnContactNameChanged();\r
+               \r
                partial void OnContactNameChanging(string value);\r
+               \r
                partial void OnContactTitleChanged();\r
+               \r
                partial void OnContactTitleChanging(string value);\r
+               \r
                partial void OnCountryChanged();\r
+               \r
                partial void OnCountryChanging(string value);\r
+               \r
                partial void OnFaxChanged();\r
+               \r
                partial void OnFaxChanging(string value);\r
+               \r
                partial void OnHomePageChanged();\r
+               \r
                partial void OnHomePageChanging(string value);\r
+               \r
                partial void OnPhoneChanged();\r
+               \r
                partial void OnPhoneChanging(string value);\r
+               \r
                partial void OnPostalCodeChanged();\r
+               \r
                partial void OnPostalCodeChanging(string value);\r
+               \r
                partial void OnRegionChanged();\r
+               \r
                partial void OnRegionChanging(string value);\r
+               \r
                partial void OnSupplierIDChanged();\r
+               \r
                partial void OnSupplierIDChanging(int value);\r
-\r
                #endregion\r
-\r
-               #region string Address\r
-\r
-               private string _address;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_address", Name = "Address", DbType = "nvarchar (60)", AutoSync = AutoSync.Never)]\r
+               \r
+               \r
+               public Supplier()\r
+               {\r
+                       _products = new EntitySet<Product>(new Action<Product>(this.Products_Attach), new Action<Product>(this.Products_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_address", Name="Address", DbType="nvarchar (60)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Address\r
                {\r
                        get\r
                        {\r
-                               return _address;\r
+                               return this._address;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _address)\r
+                               if (((_address == value) \r
+                                                       == false))\r
                                {\r
-                                       OnAddressChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _address = value;\r
-                                       SendPropertyChanged("Address");\r
-                                       OnAddressChanged();\r
+                                       this.OnAddressChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._address = value;\r
+                                       this.SendPropertyChanged("Address");\r
+                                       this.OnAddressChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string City\r
-\r
-               private string _city;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_city", Name = "City", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_city", Name="City", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string City\r
                {\r
                        get\r
                        {\r
-                               return _city;\r
+                               return this._city;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _city)\r
+                               if (((_city == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _city = value;\r
-                                       SendPropertyChanged("City");\r
-                                       OnCityChanged();\r
+                                       this.OnCityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._city = value;\r
+                                       this.SendPropertyChanged("City");\r
+                                       this.OnCityChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string CompanyName\r
-\r
-               private string _companyName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_companyName", Name = "CompanyName", DbType = "nvarchar (40)", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_companyName", Name="CompanyName", DbType="nvarchar (40)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CompanyName\r
                {\r
                        get\r
                        {\r
-                               return _companyName;\r
+                               return this._companyName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _companyName)\r
+                               if (((_companyName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCompanyNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _companyName = value;\r
-                                       SendPropertyChanged("CompanyName");\r
-                                       OnCompanyNameChanged();\r
+                                       this.OnCompanyNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._companyName = value;\r
+                                       this.SendPropertyChanged("CompanyName");\r
+                                       this.OnCompanyNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ContactName\r
-\r
-               private string _contactName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_contactName", Name = "ContactName", DbType = "nvarchar (30)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_contactName", Name="ContactName", DbType="nvarchar (30)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ContactName\r
                {\r
                        get\r
                        {\r
-                               return _contactName;\r
+                               return this._contactName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _contactName)\r
+                               if (((_contactName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnContactNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _contactName = value;\r
-                                       SendPropertyChanged("ContactName");\r
-                                       OnContactNameChanged();\r
+                                       this.OnContactNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._contactName = value;\r
+                                       this.SendPropertyChanged("ContactName");\r
+                                       this.OnContactNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ContactTitle\r
-\r
-               private string _contactTitle;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_contactTitle", Name = "ContactTitle", DbType = "nvarchar (30)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_contactTitle", Name="ContactTitle", DbType="nvarchar (30)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ContactTitle\r
                {\r
                        get\r
                        {\r
-                               return _contactTitle;\r
+                               return this._contactTitle;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _contactTitle)\r
+                               if (((_contactTitle == value) \r
+                                                       == false))\r
                                {\r
-                                       OnContactTitleChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _contactTitle = value;\r
-                                       SendPropertyChanged("ContactTitle");\r
-                                       OnContactTitleChanged();\r
+                                       this.OnContactTitleChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._contactTitle = value;\r
+                                       this.SendPropertyChanged("ContactTitle");\r
+                                       this.OnContactTitleChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Country\r
-\r
-               private string _country;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_country", Name = "Country", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_country", Name="Country", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Country\r
                {\r
                        get\r
                        {\r
-                               return _country;\r
+                               return this._country;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _country)\r
+                               if (((_country == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCountryChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _country = value;\r
-                                       SendPropertyChanged("Country");\r
-                                       OnCountryChanged();\r
+                                       this.OnCountryChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._country = value;\r
+                                       this.SendPropertyChanged("Country");\r
+                                       this.OnCountryChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Fax\r
-\r
-               private string _fax;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_fax", Name = "Fax", DbType = "nvarchar (24)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_fax", Name="Fax", DbType="nvarchar (24)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Fax\r
                {\r
                        get\r
                        {\r
-                               return _fax;\r
+                               return this._fax;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _fax)\r
+                               if (((_fax == value) \r
+                                                       == false))\r
                                {\r
-                                       OnFaxChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _fax = value;\r
-                                       SendPropertyChanged("Fax");\r
-                                       OnFaxChanged();\r
+                                       this.OnFaxChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._fax = value;\r
+                                       this.SendPropertyChanged("Fax");\r
+                                       this.OnFaxChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string HomePage\r
-\r
-               private string _homePage;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_homePage", Name = "HomePage", DbType = "ntext", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_homePage", Name="HomePage", DbType="ntext", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string HomePage\r
                {\r
                        get\r
                        {\r
-                               return _homePage;\r
+                               return this._homePage;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _homePage)\r
+                               if (((_homePage == value) \r
+                                                       == false))\r
                                {\r
-                                       OnHomePageChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _homePage = value;\r
-                                       SendPropertyChanged("HomePage");\r
-                                       OnHomePageChanged();\r
+                                       this.OnHomePageChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._homePage = value;\r
+                                       this.SendPropertyChanged("HomePage");\r
+                                       this.OnHomePageChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Phone\r
-\r
-               private string _phone;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_phone", Name = "Phone", DbType = "nvarchar (24)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_phone", Name="Phone", DbType="nvarchar (24)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Phone\r
                {\r
                        get\r
                        {\r
-                               return _phone;\r
+                               return this._phone;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _phone)\r
+                               if (((_phone == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPhoneChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _phone = value;\r
-                                       SendPropertyChanged("Phone");\r
-                                       OnPhoneChanged();\r
+                                       this.OnPhoneChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._phone = value;\r
+                                       this.SendPropertyChanged("Phone");\r
+                                       this.OnPhoneChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string PostalCode\r
-\r
-               private string _postalCode;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_postalCode", Name = "PostalCode", DbType = "nvarchar (10)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_postalCode", Name="PostalCode", DbType="nvarchar (10)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string PostalCode\r
                {\r
                        get\r
                        {\r
-                               return _postalCode;\r
+                               return this._postalCode;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _postalCode)\r
+                               if (((_postalCode == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPostalCodeChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _postalCode = value;\r
-                                       SendPropertyChanged("PostalCode");\r
-                                       OnPostalCodeChanged();\r
+                                       this.OnPostalCodeChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._postalCode = value;\r
+                                       this.SendPropertyChanged("PostalCode");\r
+                                       this.OnPostalCodeChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Region\r
-\r
-               private string _region;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_region", Name = "Region", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_region", Name="Region", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Region\r
                {\r
                        get\r
                        {\r
-                               return _region;\r
+                               return this._region;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _region)\r
+                               if (((_region == value) \r
+                                                       == false))\r
                                {\r
-                                       OnRegionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _region = value;\r
-                                       SendPropertyChanged("Region");\r
-                                       OnRegionChanged();\r
+                                       this.OnRegionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._region = value;\r
+                                       this.SendPropertyChanged("Region");\r
+                                       this.OnRegionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region int SupplierID\r
-\r
-               private int _supplierID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_supplierID", Name = "SupplierID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_supplierID", Name="SupplierID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public int SupplierID\r
                {\r
                        get\r
                        {\r
-                               return _supplierID;\r
+                               return this._supplierID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _supplierID)\r
+                               if ((_supplierID != value))\r
                                {\r
-                                       OnSupplierIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _supplierID = value;\r
-                                       SendPropertyChanged("SupplierID");\r
-                                       OnSupplierIDChanged();\r
+                                       this.OnSupplierIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._supplierID = value;\r
+                                       this.SendPropertyChanged("SupplierID");\r
+                                       this.OnSupplierIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<Product> _products;\r
-               [Association(Storage = "_products", OtherKey = "SupplierID", ThisKey = "SupplierID", Name = "fk_Products_0")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_products", OtherKey="SupplierID", ThisKey="SupplierID", Name="fk_Products_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Product> Products\r
                {\r
                        get\r
                        {\r
-                               return _products;\r
+                               return this._products;\r
                        }\r
                        set\r
                        {\r
-                               _products = value;\r
+                               this._products = value;\r
                        }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void Products_Attach(Product entity)\r
-               {\r
-                       entity.Supplier = this;\r
-               }\r
-\r
-               private void Products_Detach(Product entity)\r
-               {\r
-                       entity.Supplier = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Supplier()\r
-               {\r
-                       _products = new EntitySet<Product>(Products_Attach, Products_Detach);\r
-                       OnCreated();\r
-               }\r
-\r
                #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Territories")]\r
-       public partial class Territory : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
                protected virtual void SendPropertyChanging()\r
                {\r
-                       if (PropertyChanging != null)\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               h(this, emptyChangingEventArgs);\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
+               \r
                protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
                        }\r
                }\r
-\r
+               \r
+               #region Attachment handlers\r
+               private void Products_Attach(Product entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Supplier = this;\r
+               }\r
+               \r
+               private void Products_Detach(Product entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Supplier = null;\r
+               }\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="main.Territories")]\r
+       public partial class Territory : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private int _regionID;\r
+               \r
+               private string _territoryDescription;\r
+               \r
+               private string _territoryID;\r
+               \r
+               private EntitySet<EmployeeTerritory> _employeeTerritories;\r
+               \r
+               private EntityRef<Region> _region = new EntityRef<Region>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnRegionIDChanged();\r
+               \r
                partial void OnRegionIDChanging(int value);\r
+               \r
                partial void OnTerritoryDescriptionChanged();\r
+               \r
                partial void OnTerritoryDescriptionChanging(string value);\r
+               \r
                partial void OnTerritoryIDChanged();\r
+               \r
                partial void OnTerritoryIDChanging(string value);\r
-\r
                #endregion\r
-\r
-               #region int RegionID\r
-\r
-               private int _regionID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_regionID", Name = "RegionID", DbType = "INTEGER", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               \r
+               public Territory()\r
+               {\r
+                       _employeeTerritories = new EntitySet<EmployeeTerritory>(new Action<EmployeeTerritory>(this.EmployeeTerritories_Attach), new Action<EmployeeTerritory>(this.EmployeeTerritories_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_regionID", Name="RegionID", DbType="INTEGER", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public int RegionID\r
                {\r
                        get\r
                        {\r
-                               return _regionID;\r
+                               return this._regionID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _regionID)\r
+                               if ((_regionID != value))\r
                                {\r
                                        if (_region.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnRegionIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _regionID = value;\r
-                                       SendPropertyChanged("RegionID");\r
-                                       OnRegionIDChanged();\r
+                                       this.OnRegionIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._regionID = value;\r
+                                       this.SendPropertyChanged("RegionID");\r
+                                       this.OnRegionIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string TerritoryDescription\r
-\r
-               private string _territoryDescription;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_territoryDescription", Name = "TerritoryDescription", DbType = "nchar", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_territoryDescription", Name="TerritoryDescription", DbType="nchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string TerritoryDescription\r
                {\r
                        get\r
                        {\r
-                               return _territoryDescription;\r
+                               return this._territoryDescription;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _territoryDescription)\r
+                               if (((_territoryDescription == value) \r
+                                                       == false))\r
                                {\r
-                                       OnTerritoryDescriptionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _territoryDescription = value;\r
-                                       SendPropertyChanged("TerritoryDescription");\r
-                                       OnTerritoryDescriptionChanged();\r
+                                       this.OnTerritoryDescriptionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._territoryDescription = value;\r
+                                       this.SendPropertyChanged("TerritoryDescription");\r
+                                       this.OnTerritoryDescriptionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string TerritoryID\r
-\r
-               private string _territoryID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_territoryID", Name = "TerritoryID", DbType = "nvarchar", IsPrimaryKey = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_territoryID", Name="TerritoryID", DbType="nvarchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string TerritoryID\r
                {\r
                        get\r
                        {\r
-                               return _territoryID;\r
+                               return this._territoryID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _territoryID)\r
+                               if (((_territoryID == value) \r
+                                                       == false))\r
                                {\r
-                                       OnTerritoryIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _territoryID = value;\r
-                                       SendPropertyChanged("TerritoryID");\r
-                                       OnTerritoryIDChanged();\r
+                                       this.OnTerritoryIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._territoryID = value;\r
+                                       this.SendPropertyChanged("TerritoryID");\r
+                                       this.OnTerritoryIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<EmployeeTerritory> _employeeTerritories;\r
-               [Association(Storage = "_employeeTerritories", OtherKey = "TerritoryID", ThisKey = "TerritoryID", Name = "fk_EmployeeTerritories_0")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_employeeTerritories", OtherKey="TerritoryID", ThisKey="TerritoryID", Name="fk_EmployeeTerritories_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<EmployeeTerritory> EmployeeTerritories\r
                {\r
                        get\r
                        {\r
-                               return _employeeTerritories;\r
+                               return this._employeeTerritories;\r
                        }\r
                        set\r
                        {\r
-                               _employeeTerritories = value;\r
+                               this._employeeTerritories = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Region> _region;\r
-               [Association(Storage = "_region", OtherKey = "RegionID", ThisKey = "RegionID", Name = "fk_Territories_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_region", OtherKey="RegionID", ThisKey="RegionID", Name="fk_Territories_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Region Region\r
                {\r
                        get\r
                        {\r
-                               return _region.Entity;\r
+                               return this._region.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _region.Entity)\r
+                               if (((this._region.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_region.Entity != null)\r
+                                       if ((this._region.Entity != null))\r
                                        {\r
-                                               var previousRegion = _region.Entity;\r
-                                               _region.Entity = null;\r
+                                               Region previousRegion = this._region.Entity;\r
+                                               this._region.Entity = null;\r
                                                previousRegion.Territories.Remove(this);\r
                                        }\r
-                                       _region.Entity = value;\r
-                                       if (value != null)\r
+                                       this._region.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Territories.Add(this);\r
                                                _regionID = value.RegionID;\r
@@ -4131,35 +4036,42 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               #region Attachment handlers\r
                private void EmployeeTerritories_Attach(EmployeeTerritory entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Territory = this;\r
                }\r
-\r
+               \r
                private void EmployeeTerritories_Detach(EmployeeTerritory entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Territory = null;\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Territory()\r
-               {\r
-                       _employeeTerritories = new EntitySet<EmployeeTerritory>(EmployeeTerritories_Attach, EmployeeTerritories_Detach);\r
-                       _region = new EntityRef<Region>();\r
-                       OnCreated();\r
-               }\r
-\r
                #endregion\r
-\r
        }\r
 }\r
index b2fc7bd758afe6890ddc367297f29f1870ffe509..5a83c57afdae2ea33514ad1376d4d051acab866f 100644 (file)
@@ -75,16 +75,6 @@ namespace DbLinq.Firebird
         protected override char SafeNameStartQuote { get { return ' '; } }\r
         protected override char SafeNameEndQuote { get { return ' '; } }\r
 \r
-        /// <summary>\r
-        /// MySQL is case insensitive, and names always specify a case (there is no default casing)\r
-        /// However, tables appear to be full lowercase\r
-        /// </summary>\r
-        /// <param name="dbName"></param>\r
-        /// <returns></returns>\r
-        protected override bool IsNameCaseSafe(string dbName)\r
-        {\r
-            return dbName == dbName.ToUpperInvariant();\r
-        }\r
 \r
         /// <summary>\r
         /// Returns a table alias\r
index 2de7be5f7cc2141170db2aae1394959fddb39e69..a80098686f09cf1d2fb28f71e291446554dba617 100644 (file)
@@ -42,16 +42,4 @@ using DbLinq.Factory;
 // The following GUID is for the ID of the typelib if this project is exposed to COM\r
 [assembly: Guid("7ad419fa-9b5c-46d6-8567-ac33f6b69833")]\r
 \r
-// Version information for an assembly consists of the following four values:\r
-//\r
-//      Major Version\r
-//      Minor Version \r
-//      Build Number\r
-//      Revision\r
-//\r
-// You can specify all the values or you can default the Build and Revision Numbers \r
-// by using the '*' as shown below:\r
-// [assembly: AssemblyVersion("1.0.*")]\r
-[assembly: AssemblyFileVersion("0.19")]\r
-\r
 [assembly: DbLinq]\r
index 1055044df7a054652a54f165ffff9eff629d00a8..12a04ebaa2c332cae8e26de446dec0b2b6dcb272 100644 (file)
@@ -100,11 +100,6 @@ namespace DbLinq.Ingres
             return (":" + nameBase).ToLower();\r
         }\r
 \r
-        protected override bool IsNameCaseSafe(string dbName)\r
-        {\r
-            return dbName == dbName.ToLower();\r
-        }\r
-\r
         protected override SqlStatement GetLiteralStringConcat(SqlStatement a, SqlStatement b)\r
         {\r
             // This needs to be bracketed in case subsequent functions are called upon it\r
index 75ce1c2b8d91317b6118913d7405dcc7f9139ad6..770b7b0a56b5248f36b2c97c6dd5a931249567f2 100644 (file)
@@ -41,13 +41,4 @@ using DbLinq.Factory;
 // The following GUID is for the ID of the typelib if this project is exposed to COM\r
 [assembly: Guid("d393f4ff-9bb6-42ad-bb84-d207115f48b1")]\r
 \r
-// Version information for an assembly consists of the following four values:\r
-//\r
-//      Major Version\r
-//      Minor Version \r
-//      Build Number\r
-//      Revision\r
-//\r
-[assembly: AssemblyFileVersion("0.19")]\r
-\r
 [assembly: DbLinq]\r
index 24a347e9a5b9d356f140abf3cf1873537ddcbdd4..aa3e5a5aa6c80c40fb32264b3651efd8ffe638f1 100644 (file)
@@ -72,16 +72,5 @@ namespace DbLinq.MySql
 \r
         protected override char SafeNameStartQuote { get { return '`'; } }\r
         protected override char SafeNameEndQuote { get { return '`'; } }\r
-\r
-        /// <summary>\r
-        /// MySQL is case insensitive, and names always specify a case (there is no default casing)\r
-        /// However, tables appear to be full lowercase\r
-        /// </summary>\r
-        /// <param name="dbName"></param>\r
-        /// <returns></returns>\r
-        protected override bool IsNameCaseSafe(string dbName)\r
-        {\r
-            return true;\r
-        }\r
     }\r
 }\r
index 75f5d331923069ebaf0c60cca7f6cb79cd63ac37..2d1afcc56eee86bef6702e23d0cbb58cf2c66ce6 100644 (file)
@@ -41,13 +41,4 @@ using DbLinq.Factory;
 // The following GUID is for the ID of the typelib if this project is exposed to COM\r
 [assembly: Guid("c8c37bc2-84ee-41b0-893e-02b4375eabbe")]\r
 \r
-// Version information for an assembly consists of the following four values:\r
-//\r
-//      Major Version\r
-//      Minor Version \r
-//      Build Number\r
-//      Revision\r
-//\r
-[assembly: AssemblyFileVersion("0.19")]\r
-\r
 [assembly: DbLinq]\r
index d941456f87e9b3e1808438361649de03a28e6a01..5f5618baa307490a56d2305169f3cf03b0cdafd1 100644 (file)
@@ -26,6 +26,7 @@
 using System;\r
 using System.Collections.Generic;\r
 using System.Data;\r
+using System.Linq;\r
 using System.Text;\r
 using System.Text.RegularExpressions;\r
 using DbLinq.Util;\r
@@ -39,30 +40,18 @@ namespace DbLinq.Oracle
             public string TableSchema;\r
             public string ConstraintName;\r
             public string TableName;\r
-            public string ColumnName;\r
+            public List<string> ColumnNames = new List<string>();\r
+            public string ColumnNameList { get { return string.Join(",", ColumnNames.ToArray()); } }\r
             public string ConstraintType;\r
             public string ReverseConstraintName;\r
             public string Expression;\r
 \r
             public override string ToString()\r
             {\r
-                return "User_Constraint  " + TableName + "." + ColumnName;\r
+                return "User_Constraint  " + TableName + "." + ColumnNameList;\r
             }\r
         }\r
 \r
-        protected virtual DataConstraint ReadConstraint(IDataReader rdr)\r
-        {\r
-            var constraint = new DataConstraint();\r
-            int field = 0;\r
-            constraint.TableSchema = rdr.GetAsString(field++);\r
-            constraint.ConstraintName = rdr.GetAsString(field++);\r
-            constraint.TableName = rdr.GetAsString(field++);\r
-            constraint.ColumnName = rdr.GetAsString(field++);\r
-            constraint.ConstraintType = rdr.GetAsString(field++);\r
-            constraint.ReverseConstraintName = rdr.GetAsString(field++);\r
-            return constraint;\r
-        }\r
-\r
         private static Regex TriggerMatch1 = new Regex(@".*SELECT\s+(?<exp>\S+.*)\s+INTO\s+\:new.(?<col>\S+)\s+FROM\s+DUAL.*",\r
             RegexOptions.Compiled | RegexOptions.IgnoreCase);\r
 \r
@@ -97,7 +86,7 @@ namespace DbLinq.Oracle
             string expression, column;\r
             if (MatchTrigger(TriggerMatch1, body, out expression, out column))\r
             {\r
-                constraint.ColumnName = column.Trim('"');\r
+                constraint.ColumnNames.Add(column.Trim('"'));\r
                 constraint.Expression = expression;\r
             }\r
             return constraint;\r
@@ -108,15 +97,41 @@ namespace DbLinq.Oracle
             var constraints = new List<DataConstraint>();\r
 \r
             string sql = @"\r
-SELECT UCC.owner, UCC.constraint_name, UCC.table_name, UCC.column_name, UC.constraint_type, UC.R_constraint_name\r
+SELECT UCC.owner, UCC.constraint_name, UCC.table_name, UC.constraint_type, UC.R_constraint_name, UCC.column_name, UCC.position\r
 FROM all_cons_columns UCC, all_constraints UC\r
 WHERE UCC.constraint_name=UC.constraint_name\r
 AND UCC.table_name=UC.table_name\r
+AND UCC.owner=UC.owner\r
 AND UCC.TABLE_NAME NOT LIKE '%$%' AND UCC.TABLE_NAME NOT LIKE 'LOGMNR%' AND UCC.TABLE_NAME NOT IN ('HELP','SQLPLUS_PRODUCT_PROFILE')\r
 AND UC.CONSTRAINT_TYPE!='C'\r
 and lower(UCC.owner) = :owner";\r
 \r
-            constraints.AddRange(DataCommand.Find<DataConstraint>(conn, sql, ":owner", db.ToLower(), ReadConstraint));\r
+            constraints.AddRange(DataCommand.Find(conn, sql, ":owner", db.ToLower(),\r
+                    r => new\r
+                    {\r
+                        Key = new\r
+                        {\r
+                            Owner = r.GetString(0),\r
+                            ConName = r.GetString(1),\r
+                            TableName = r.GetString(2),\r
+                            ConType = r.GetString(3),\r
+                            RevCconName = r.GetAsString(4)\r
+                        },\r
+                        Value = new\r
+                        {\r
+                            ColName = r.GetString(5),\r
+                            ColPos = r.GetInt32(6)\r
+                        }\r
+                    })\r
+                .GroupBy(r => r.Key, r => r.Value, (r, rs) => new DataConstraint\r
+                {\r
+                    TableSchema = r.Owner,\r
+                    ConstraintName = r.ConName,\r
+                    TableName = r.TableName,\r
+                    ConstraintType = r.ConType,\r
+                    ReverseConstraintName = r.RevCconName,\r
+                    ColumnNames = rs.OrderBy(t => t.ColPos).Select(t => t.ColName).ToList()\r
+                }));\r
 \r
             string sql2 =\r
                 @"\r
index 41e36908ca5440f654f5a49e647a027d99b8b400..d6e56a9ac5b86783501f9b40dd81200a9f55d390 100644 (file)
@@ -51,7 +51,7 @@ namespace DbLinq.Oracle
                 DbLinq.Schema.Dbml.Table table = schema.Tables.FirstOrDefault(t => constraintFullDbName == t.Name);\r
                 if (table == null)\r
                 {\r
-                    WriteErrorLine("ERROR L100: Table '" + constraint.TableName + "' not found for column " + constraint.ColumnName);\r
+                    WriteErrorLine("ERROR L100: Table '" + constraint.TableName + "' not found for column " + constraint.ColumnNameList);\r
                     continue;\r
                 }\r
 \r
@@ -61,7 +61,7 @@ namespace DbLinq.Oracle
                 if (constraint.ConstraintType == "P")\r
                 {\r
                     //A) add primary key\r
-                    DbLinq.Schema.Dbml.Column pkColumn = table.Type.Columns.Where(c => c.Name == constraint.ColumnName).First();\r
+                    DbLinq.Schema.Dbml.Column pkColumn = table.Type.Columns.Where(c => constraint.ColumnNames.Contains(c.Name)).First();\r
                     pkColumn.IsPrimaryKey = true;\r
                 }\r
                 else if (constraint.ConstraintType == "R")\r
@@ -75,16 +75,16 @@ namespace DbLinq.Oracle
                         continue;\r
                     }\r
 \r
-                    LoadForeignKey(schema, table, constraint.ColumnName, constraint.TableName, constraint.TableSchema,\r
-                                   referencedConstraint.ColumnName, referencedConstraint.TableName,\r
+                    LoadForeignKey(schema, table, constraint.ColumnNameList, constraint.TableName, constraint.TableSchema,\r
+                                   referencedConstraint.ColumnNameList, referencedConstraint.TableName,\r
                                    referencedConstraint.TableSchema,\r
                                    constraint.ConstraintName, nameFormat, names);\r
 \r
                 }\r
                 // custom type, this is a trigger\r
-                else if (constraint.ConstraintType == "T" && constraint.ColumnName != null)\r
+                else if (constraint.ConstraintType == "T" && constraint.ColumnNames.Count == 1)\r
                 {\r
-                    var column = table.Type.Columns.Where(c => c.Name == constraint.ColumnName).First();\r
+                    var column = table.Type.Columns.Where(c => c.Name == constraint.ColumnNames[0]).First();\r
                     column.Expression = constraint.Expression;\r
                     column.IsDbGenerated = true;\r
                 }\r
index 9a78b7b4ad87044e4d6b69024f0f01630c11d801..505b7c151fc739db0b9e3575d11d0849a15ec5d6 100644 (file)
@@ -41,13 +41,4 @@ using DbLinq.Factory;
 // The following GUID is for the ID of the typelib if this project is exposed to COM\r
 [assembly: Guid("e1f0992f-a414-4479-905e-96c5d51b8cb6")]\r
 \r
-// Version information for an assembly consists of the following four values:\r
-//\r
-//      Major Version\r
-//      Minor Version \r
-//      Build Number\r
-//      Revision\r
-//\r
-[assembly: AssemblyFileVersion("0.19")]\r
-\r
 [assembly: DbLinq]\r
index 0778a6b40b7d37483a20e52441d61049f03f09e1..12270e73fb0e5b9dcb434bff0c7f6a186a75e72e 100644 (file)
@@ -106,7 +106,7 @@ namespace DbLinq.PostgreSql
                 //In Sasha's DB, they don't end with "_pkey", you need to rely on ReadForeignConstraints().\r
                 //In Northwind, they do end with "_pkey".\r
                 bool isPrimaryKey = keyColRow.ConstraintName.EndsWith("_pkey")\r
-                    || primaryKeys.Count(k => k.ConstraintName == keyColRow.ConstraintName) == 1;\r
+                    || primaryKeys.Count(k => k.ConstraintName == keyColRow.ConstraintName) > 0;\r
 \r
                 if (isPrimaryKey)\r
                 {\r
index a546ec56ac0bd97a4e44e2d307a444ea68611ee5..e86a06adf758923f7bd0991cd01f5f3d9d01ca91 100644 (file)
@@ -145,15 +145,5 @@ namespace DbLinq.PostgreSql
 \r
             return string.Format("({0})::{1}", a, sqlTypeName);\r
         }\r
-\r
-        /// <summary>\r
-        /// In PostgreSQL an insensitive name is lowercase\r
-        /// </summary>\r
-        /// <param name="dbName"></param>\r
-        /// <returns></returns>\r
-        protected override bool IsNameCaseSafe(string dbName)\r
-        {\r
-            return dbName == dbName.ToLower();\r
-        }\r
     }\r
 }\r
index 75ce1c2b8d91317b6118913d7405dcc7f9139ad6..770b7b0a56b5248f36b2c97c6dd5a931249567f2 100644 (file)
@@ -41,13 +41,4 @@ using DbLinq.Factory;
 // The following GUID is for the ID of the typelib if this project is exposed to COM\r
 [assembly: Guid("d393f4ff-9bb6-42ad-bb84-d207115f48b1")]\r
 \r
-// Version information for an assembly consists of the following four values:\r
-//\r
-//      Major Version\r
-//      Minor Version \r
-//      Build Number\r
-//      Revision\r
-//\r
-[assembly: AssemblyFileVersion("0.19")]\r
-\r
 [assembly: DbLinq]\r
index a8e46b765c49d766c7be6635a1d4ac4c01fec4b2..dce8d4344707e30f807044a23639039181086748 100644 (file)
@@ -45,4 +45,5 @@ using System.Runtime.InteropServices;
 //      Build Number\r
 //      Revision\r
 //\r
-[assembly: AssemblyVersion("0.19")]\r
+[assembly: AssemblyFileVersion("0.20")]\r
+[assembly: AssemblyVersion("0.20")]\r
index cd372eab8df9fe3a64b3d1c3d259a10c89bb363f..8a1049d42eb90e41261a8618869afa06cb14cb72 100644 (file)
@@ -41,13 +41,4 @@ using DbLinq.Factory;
 // The following GUID is for the ID of the typelib if this project is exposed to COM\r
 [assembly: Guid("55bd884f-8aa6-4dbb-8d29-2d8e879e5f0b")]\r
 \r
-// Version information for an assembly consists of the following four values:\r
-//\r
-//      Major Version\r
-//      Minor Version \r
-//      Build Number\r
-//      Revision\r
-//\r
-[assembly: AssemblyFileVersion("0.19")]\r
-\r
 [assembly: DbLinq]\r
index 7b884ee522758535860a4d4f9c55ad8b8134a2b3..de092b37faddc60644e3093802c5b8b9faebc07c 100644 (file)
@@ -62,6 +62,13 @@ namespace DbLinq.SqlServer
         protected readonly SqlServerSqlProvider sqlProvider = new SqlServerSqlProvider();\r
         public override ISqlProvider SqlProvider { get { return sqlProvider; } }\r
 \r
+        protected override void AppendServer(StringBuilder connectionString, string host)\r
+        {\r
+            // As per http://www.connectionstrings.com/sql-server, \r
+            // port numbers are separated from host names via comma\r
+            AppendConnectionString(connectionString, ConnectionStringServer, host.Replace(':', ','));\r
+        }\r
+\r
         //NOTE: for Oracle, we want to consider 'Array Binding'\r
         //http://download-west.oracle.com/docs/html/A96160_01/features.htm#1049674\r
 \r
@@ -91,6 +98,11 @@ namespace DbLinq.SqlServer
                 var dc = new DataColumn();\r
                 dc.ColumnName = column.MappedName;\r
                 dc.DataType = column.Member.GetMemberType();\r
+                if (dc.DataType.IsNullable())\r
+                {\r
+                    dc.AllowDBNull  = true;\r
+                    dc.DataType     = dc.DataType.GetNullableType();\r
+                }\r
                 dt.Columns.Add(dc);\r
             }\r
 \r
@@ -105,7 +117,7 @@ namespace DbLinq.SqlServer
                     //if (pair.Value.IsDbGenerated)\r
                     //    continue; //don't assign IDENTITY col\r
                     object value = pair.Member.GetMemberValue(row);\r
-                    dr[pair.MappedName] = value;\r
+                    dr[pair.MappedName] = value ?? DBNull.Value;\r
                 }\r
                 //dr[1\r
                 dt.Rows.Add(dr);\r
index 715ab5b0935540557a956b1731bc1a6bc8ee0dce..2b949b11c4d6bbac8409906c67be33d01169d710 100644 (file)
@@ -41,13 +41,4 @@ using DbLinq.Factory;
 // The following GUID is for the ID of the typelib if this project is exposed to COM\r
 [assembly: Guid("9a57ce12-ad10-479f-b181-eb267c8e6c19")]\r
 \r
-// Version information for an assembly consists of the following four values:\r
-//\r
-//      Major Version\r
-//      Minor Version \r
-//      Build Number\r
-//      Revision\r
-//\r
-[assembly: AssemblyFileVersion("0.19")]\r
-\r
 [assembly: DbLinq]\r
index be8e02a37bec0ef5b4cb4eb9af4a1c95e77ca8ff..2df555dbf01965c6734fbb769ee0e03836342eb6 100644 (file)
@@ -49,7 +49,7 @@ namespace DbLinq.Sqlite
 \r
         protected override IList<IDataTableColumn> ReadColumns(IDbConnection connectionString, string databaseName)\r
         {\r
-            const string sql = @" SELECT tbl_name FROM sqlite_master WHERE type='table' order by tbl_name";\r
+            var sql = string.Format(SelectTablesFormat, "");\r
             const string pragma = @"PRAGMA table_info('{0}');";\r
 \r
             return Schema.DataCommand.Find<IDataTableColumn>(connectionString, sql, pragma, ReadColumn);\r
index 6f50e1a87e75408e50c61eb9cc1e0d59bbfd06e3..88b9c8f5d20d9ae56909643fb7d779d6a1332e5a 100644 (file)
@@ -33,9 +33,7 @@ namespace DbLinq.Sqlite
     {\r
         public override IList<IDataName> ReadTables(IDbConnection connectionString, string databaseName)\r
         {\r
-            // note: the ReadDataNameAndSchema relies on information order\r
-            const string sql = @" SELECT tbl_name, 'main' FROM sqlite_master WHERE type='table' order by tbl_name";\r
-\r
+            string sql = string.Format(SelectTablesFormat, ", 'main'");\r
             return Util.DataCommand.Find<IDataName>(connectionString, sql, ReadDataNameAndSchema);\r
         }\r
     }\r
index 2278bec5e788fab0ecbf52ec6aa69a99f8100eee..ceb44afed3fb2e2359ed464f209e3ccbfd52a3ec 100644 (file)
@@ -58,6 +58,16 @@ namespace DbLinq.Sqlite
             return name;\r
         }\r
 \r
+        // note: the ReadDataNameAndSchema relies on information order;\r
+        // tbl_name MUST be first\r
+        const string SelectTablesFormat = \r
+@"   SELECT tbl_name{0}\r
+       FROM sqlite_master\r
+      WHERE type='table' AND\r
+            tbl_name NOT LIKE 'sqlite_%'\r
+   ORDER BY tbl_name";\r
+\r
+\r
         /// <summary>\r
         /// Gets a usable name for the database.\r
         /// </summary>\r
index d9329948675eb84545d936f13683f9c2495127f3..55f690bf8dd1b7f5f5aa9d2b3b4b15e9e8e404cd 100644 (file)
@@ -60,11 +60,6 @@ namespace DbLinq.Sqlite
             return "COUNT(*)";\r
         }\r
 \r
-        protected override bool IsNameCaseSafe(string namePart)\r
-        {\r
-            return true;\r
-        }\r
-\r
         public override SqlStatement GetLiteral(bool literal)\r
         {\r
             if (literal)\r
index 6e3fa4de84a5204f4d53bf7b388497e5ca83647a..06181faed205d3e701f2ff62ac1fb4709370f880 100644 (file)
@@ -103,6 +103,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DbMetal_test_sqlite", "DbMe
 EndProject\r
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SqlMetal_test_sqlite", "DbMetal\Test\SqlMetal_test_sqlite.csproj", "{874A37C6-E59B-4C0D-AAD2-0286E0DA8FD9}"\r
 EndProject\r
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestReporter", "Tools\TestReporter\TestReporter.csproj", "{EEE5CAA1-0312-45F2-94ED-BC311A19CAEF}"\r
+EndProject\r
 Global\r
        GlobalSection(SolutionConfigurationPlatforms) = preSolution\r
                Debug - Mono Strict|Any CPU = Debug - Mono Strict|Any CPU\r
@@ -326,6 +328,12 @@ Global
                {874A37C6-E59B-4C0D-AAD2-0286E0DA8FD9}.Debug|Any CPU.Build.0 = Debug|Any CPU\r
                {874A37C6-E59B-4C0D-AAD2-0286E0DA8FD9}.Release|Any CPU.ActiveCfg = Release|Any CPU\r
                {874A37C6-E59B-4C0D-AAD2-0286E0DA8FD9}.Release|Any CPU.Build.0 = Release|Any CPU\r
+               {EEE5CAA1-0312-45F2-94ED-BC311A19CAEF}.Debug - Mono Strict|Any CPU.ActiveCfg = Debug|Any CPU\r
+               {EEE5CAA1-0312-45F2-94ED-BC311A19CAEF}.Debug - Mono Strict|Any CPU.Build.0 = Debug|Any CPU\r
+               {EEE5CAA1-0312-45F2-94ED-BC311A19CAEF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r
+               {EEE5CAA1-0312-45F2-94ED-BC311A19CAEF}.Debug|Any CPU.Build.0 = Debug|Any CPU\r
+               {EEE5CAA1-0312-45F2-94ED-BC311A19CAEF}.Release|Any CPU.ActiveCfg = Release|Any CPU\r
+               {EEE5CAA1-0312-45F2-94ED-BC311A19CAEF}.Release|Any CPU.Build.0 = Release|Any CPU\r
        EndGlobalSection\r
        GlobalSection(SolutionProperties) = preSolution\r
                HideSolutionNode = FALSE\r
index 838d2b021674b3e6f4a924e9a777c70ad42a92e1..9710a8aad0bec7110912565d75d906ac60c9b601 100644 (file)
@@ -236,18 +236,18 @@ namespace DbLinq.Data.Linq
             System.Text.RegularExpressions.Regex reProvider\r
                 = new System.Text.RegularExpressions.Regex(@"DbLinqProvider=([\w\.]+);?");\r
 \r
-            string assemblyFile = null;\r
+            string assemblyName = null;\r
             string vendor;\r
             if (!reProvider.IsMatch(connectionString))\r
             {\r
                 vendor       = "SqlServer";\r
-                assemblyFile = "DbLinq.SqlServer.dll";\r
+                assemblyName = "DbLinq.SqlServer";\r
             }\r
             else\r
             {\r
                 var match    = reProvider.Match(connectionString);\r
                 vendor       = match.Groups[1].Value;\r
-                assemblyFile = "DbLinq." + vendor + ".dll";\r
+                assemblyName = "DbLinq." + vendor;\r
 \r
                 //plain DbLinq - non MONO: \r
                 //IVendor classes are in DLLs such as "DbLinq.MySql.dll"\r
@@ -268,16 +268,15 @@ namespace DbLinq.Data.Linq
 #if MONO_STRICT\r
                 assembly = typeof (DataContext).Assembly; // System.Data.Linq.dll\r
 #else\r
-                //TODO: check if DLL is already loaded?\r
-                assembly = Assembly.LoadFrom(assemblyFile);\r
+                assembly = Assembly.Load(assemblyName);\r
 #endif\r
             }\r
             catch (Exception e)\r
             {\r
                 throw new ArgumentException(\r
                         string.Format(\r
-                            "Unable to load the `{0}' DbLinq vendor within assembly `{1}'.",\r
-                            assemblyFile, vendor),\r
+                            "Unable to load the `{0}' DbLinq vendor within assembly '{1}.dll'.",\r
+                            assemblyName, vendor),\r
                         "connectionString", e);\r
             }\r
         }\r
@@ -399,11 +398,11 @@ namespace DbLinq.Data.Linq
                     SubmitChangesImpl(failureMode);\r
                 else\r
                 {\r
-                    using (IDatabaseTransaction transaction = DatabaseContext.Transaction())\r
+                    using (IDbTransaction transaction = DatabaseContext.CreateTransaction())\r
                     {\r
                         try\r
                         {\r
-                            Transaction = (DbTransaction) transaction.Transaction;\r
+                            Transaction = (DbTransaction) transaction;\r
                             SubmitChangesImpl(failureMode);\r
                             // TODO: handle conflicts (which can only occur when concurrency mode is implemented)\r
                             transaction.Commit();\r
@@ -1025,7 +1024,10 @@ namespace DbLinq.Data.Linq
                        set { throw new NotImplementedException(); }\r
                }\r
 \r
-        public DbTransaction Transaction { get; set; }\r
+        public DbTransaction Transaction {\r
+            get { return (DbTransaction) DatabaseContext.CurrentTransaction; }\r
+            set { DatabaseContext.CurrentTransaction = value; }\r
+        }\r
 \r
         /// <summary>\r
         /// Runs the given reader and returns columns.\r
index 97fc4ec1768066919a13a445309d189a85243e36..9d8fae805f793f6866dbf9e763c7bb153dbf8e09 100644 (file)
@@ -63,7 +63,10 @@ namespace DbLinq.Data.Linq.Database
         /// Creates a transaction.\r
         /// </summary>\r
         /// <returns></returns>\r
-        IDatabaseTransaction Transaction();\r
+        IDbTransaction CreateTransaction();\r
+\r
+        IDbTransaction CurrentTransaction { get; set; }\r
+\r
         /// <summary>\r
         /// Opens a connection.\r
         /// </summary>\r
index 1a1e7900f0262eb52896e1a2f326079ed93065ea..3bf55cd7480444668d333f73a768c1e5b23bde32 100644 (file)
@@ -44,6 +44,8 @@ namespace DbLinq.Data.Linq.Database.Implementation
             set { ChangeConnection(value, false); }\r
         }\r
 \r
+        public IDbTransaction CurrentTransaction { get; set; }\r
+\r
         private readonly DbProviderFactory _providerFactory;\r
         /// <summary>\r
         /// Gets the provider factory.\r
@@ -101,9 +103,11 @@ namespace DbLinq.Data.Linq.Database.Implementation
         /// Creates a transaction.\r
         /// </summary>\r
         /// <returns></returns>\r
-        public IDatabaseTransaction Transaction()\r
+        public IDbTransaction CreateTransaction()\r
         {\r
-            return new DatabaseTransaction(Connection);\r
+            if (CurrentTransaction != null)\r
+                throw new InvalidOperationException("Attempting to create a transaction while within a transaction.");\r
+            return CurrentTransaction = Connection.BeginTransaction();\r
         }\r
 \r
         /// <summary>\r
@@ -114,7 +118,7 @@ namespace DbLinq.Data.Linq.Database.Implementation
         {\r
             IDbCommand command = Connection.CreateCommand();\r
             if (command.Transaction == null)\r
-                command.Transaction = DatabaseTransaction.currentTransaction;\r
+                command.Transaction = CurrentTransaction;\r
             return command;\r
         }\r
 \r
index f4a147511a405ec18c44094f247fc0ce24063b72..fab34f7a7bdb81b10efe9fcdb0d71cee437f4d35 100644 (file)
@@ -47,7 +47,7 @@ namespace DbLinq.Data.Linq.Database.Implementation
         /// <summary>\r
         /// Ambient transaction\r
         /// </summary>\r
-        private readonly IDatabaseTransaction _transaction;\r
+        private readonly IDbTransaction _transaction;\r
 \r
         private readonly IDbCommand _command;\r
 \r
@@ -100,8 +100,8 @@ namespace DbLinq.Data.Linq.Database.Implementation
             // the transaction is optional\r
             if (createTransaction && !haveHigherTransaction)\r
             {\r
-                _transaction = dataContext.DatabaseContext.Transaction();\r
-                _command.Transaction = _transaction.Transaction;\r
+                _transaction = dataContext.DatabaseContext.CreateTransaction();\r
+                _command.Transaction = _transaction;\r
             }\r
             else\r
                 _command.Transaction = dataContext.Transaction;\r
index 28f4f97d821e111e33147c9f85effeeeff865d9f..329a974c3fcbedd14cbcea24cdc2f89787923132 100644 (file)
@@ -184,7 +184,7 @@ namespace DbLinq.Data.Linq.Mapping
             }\r
             public bool GetBooleanAttribute(XmlReader r, string attributeName)\r
             {\r
-                return r.GetAttribute(attributeName) == "true";\r
+                return string.Compare(r.GetAttribute(attributeName), "true", StringComparison.OrdinalIgnoreCase) == 0;\r
             }\r
             public UpdateCheck GetUpdateCheckAttribute(XmlReader r, string attributeName)\r
             {\r
index 187a5e8dacd9d9f4bcfd852b2c3ce0db1107d2aa..36f2bd07a8d66ac0c01db55e3c43eb9ab3a8419a 100644 (file)
@@ -271,13 +271,13 @@ namespace DbLinq.Data.Linq.Sugar.Implementation
 \r
             // our table is created, with the expressions\r
             // now check if we didn't register exactly the same\r
-            if ((from t in builderContext.EnumerateScopeTables() where t.IsEqualTo(otherTableExpression) select t).SingleOrDefault() == null)\r
-            {\r
-                builderContext.CurrentSelect.Tables.Add(otherTableExpression);\r
-                foreach (var createdColumn in createdColumns)\r
-                    builderContext.CurrentSelect.Columns.Add(createdColumn);\r
-            }\r
-\r
+            var existingTable = (from t in builderContext.EnumerateScopeTables() where t.IsEqualTo(otherTableExpression) select t).SingleOrDefault();\r
+            if (existingTable != null)\r
+                return existingTable;\r
\r
+            builderContext.CurrentSelect.Tables.Add(otherTableExpression);\r
+            foreach (var createdColumn in createdColumns)\r
+                builderContext.CurrentSelect.Columns.Add(createdColumn);\r
             return otherTableExpression;\r
         }\r
 \r
index 8fa90b9d8e48f15ab48cdc14f23f2f88b87b7512..62505027c726e57b1931480eae9edfa15a83b2de 100644 (file)
@@ -402,9 +402,27 @@ namespace DbLinq.Data.Linq.Sugar.Implementation
                     SetInSelectCache(expressions, query);\r
                 }\r
             }\r
+            else if (query.InputParameters.Count > 0)\r
+            {\r
+                Profiler.At("START: GetSelectQuery(), building Expression parameters of cached query");\r
+                var parameters = BuildExpressionParameters(expressions, queryContext);\r
+                query = new SelectQuery(queryContext.DataContext, query.Sql, parameters, query.RowObjectCreator, query.ExecuteMethodName);\r
+                Profiler.At("END: GetSelectQuery(), building Expression parameters of cached query");\r
+            }\r
             return query;\r
         }\r
 \r
+        IList<InputParameterExpression> BuildExpressionParameters(ExpressionChain expressions, QueryContext queryContext)\r
+        {\r
+            var builderContext = new BuilderContext(queryContext);\r
+            var previousExpression = ExpressionDispatcher.CreateTableExpression(expressions.Expressions[0], builderContext);\r
+            previousExpression = BuildExpressionQuery(expressions, previousExpression, builderContext);\r
+            BuildOffsetsAndLimits(builderContext);\r
+            // then prepare Parts for SQL translation\r
+            PrepareSqlOperands(builderContext);\r
+            return builderContext.ExpressionQuery.Parameters;\r
+        }\r
+\r
         /// <summary>\r
         /// Returns a Delegate to create a row for a given IDataRecord\r
         /// The Delegate is Func&lt;IDataRecord,MappingContext,"tableType">\r
index 0e7b60488776d52e7a27d2cbf7102b3c98600146..6790688147b1dc92e748161656d1132ba487c224 100644 (file)
@@ -76,9 +76,9 @@ namespace DbLinq.Data.Linq
         public void BulkInsert(IEnumerable<TEntity> entities, int pageSize)\r
         {\r
             using (Context.DatabaseContext.OpenConnection())\r
-            using (var transaction = Context.DatabaseContext.Transaction())\r
+            using (var transaction = Context.DatabaseContext.CreateTransaction())\r
             {\r
-                Context.Vendor.BulkInsert(this, entities.ToList(), pageSize, transaction.Transaction);\r
+                Context.Vendor.BulkInsert(this, entities.ToList(), pageSize, Context.Transaction);\r
                 transaction.Commit();\r
             }\r
         }\r
index 41f2ab884ab6b58294b29c35bc8653eee519afb2..1f265f21d01414bc585dd6b3e2eb958b365c9942 100644 (file)
     </Compile>\r
     <Compile Include="Data\Linq\ChangeSet.cs" />\r
     <Compile Include="Data\Linq\Database\IDatabaseContext.cs" />\r
-    <Compile Include="Data\Linq\Database\IDatabaseTransaction.cs" />\r
     <Compile Include="Data\Linq\Database\ITransactionalCommand.cs" />\r
     <Compile Include="Data\Linq\Database\Implementation\DatabaseConnection.cs" />\r
     <Compile Include="Data\Linq\Database\Implementation\DatabaseContext.cs" />\r
-    <Compile Include="Data\Linq\Database\Implementation\DatabaseTransaction.cs" />\r
     <Compile Include="Data\Linq\DataLoadOptions.cs" />\r
     <Compile Include="Data\Linq\DBLinqExtendedAttributte.cs" />\r
     <Compile Include="Data\Linq\EntityRef.cs" />\r
     <Compile Include="Schema\Dbml\Adapter\INamedType.cs" />\r
     <Compile Include="Schema\Dbml\Adapter\ISimpleList.cs" />\r
     <Compile Include="Schema\Dbml\Adapter\SpecifiedPropertyUpdater.cs" />\r
+    <Compile Include="Schema\Dbml\DatabaseSerializer.cs" />\r
     <Compile Include="Schema\WordsExtraction.cs" />\r
     <Compile Include="Schema\NameFormat.cs" />\r
     <Compile Include="Schema\AssociationName.cs" />\r
index fe34254a95acab3fc004c3ca2b9ee2d7e83eb731..af4220611875e3f4d17ac325cfa68ccd2d663938 100644 (file)
@@ -42,15 +42,6 @@ using DbLinq.Factory;
 // The following GUID is for the ID of the typelib if this project is exposed to COM\r
 [assembly: Guid("e2381b27-cdb0-401d-9019-f72079b4928d")]\r
 \r
-// Version information for an assembly consists of the following four values:\r
-//\r
-//      Major Version\r
-//      Minor Version \r
-//      Build Number\r
-//      Revision\r
-//\r
-[assembly: AssemblyFileVersion("0.19")]\r
-\r
 [assembly: DbLinq]\r
 \r
 // Regarding tests, it is mandatory, since we test internals\r
@@ -112,6 +103,13 @@ using DbLinq.Factory;
 + "962a12b830c2a70eb70ec77823eb5750e5bdef9e01d097c30b5c5463c3d07d3472b58e4c02f279"\r
 + "2309259f")]\r
 \r
+[assembly: InternalsVisibleTo("DbLinq.SqlServer, PublicKey="\r
++ "0024000004800000940000000602000000240000525341310004000001000100c5753d8c47f400"\r
++ "83f549016a5711238ac8ec297605abccd3dc4b6d0f280b4764eb2cc58ec4e37831edad7e7a07b8"\r
++ "fe4a9cbb059374c0cc047aa28839fed7176761813caf6a2ffa0bff9afb50ead56dd3f56186a663"\r
++ "962a12b830c2a70eb70ec77823eb5750e5bdef9e01d097c30b5c5463c3d07d3472b58e4c02f279"\r
++ "2309259f")]\r
+\r
 [assembly: InternalsVisibleTo("DbLinq.Ingres, PublicKey="\r
 + "0024000004800000940000000602000000240000525341310004000001000100c5753d8c47f400"\r
 + "83f549016a5711238ac8ec297605abccd3dc4b6d0f280b4764eb2cc58ec4e37831edad7e7a07b8"\r
diff --git a/mcs/class/System.Data.Linq/src/DbLinq/Schema/Dbml/DatabaseSerializer.cs b/mcs/class/System.Data.Linq/src/DbLinq/Schema/Dbml/DatabaseSerializer.cs
new file mode 100644 (file)
index 0000000..073eef9
--- /dev/null
@@ -0,0 +1,2223 @@
+// It is automatically generated
+using System;
+using System.Xml;
+using System.Xml.Schema;
+using System.Xml.Serialization;
+using System.Text;
+using System.Collections;
+using System.Globalization;
+
+namespace DbLinq.Schema.Dbml
+{
+       #if !MONO_STRICT
+       public
+       #endif
+       class GeneratedReader : XmlSerializationReader
+       {
+               static readonly System.Reflection.MethodInfo fromBinHexStringMethod = typeof (XmlConvert).GetMethod ("FromBinHexString", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic, null, new System.Type [] {typeof (string)}, null);
+               static byte [] FromBinHexString (string input)
+               {
+                       return input == null ? null : (byte []) fromBinHexStringMethod.Invoke (null, new object [] {input});
+               }
+               public object ReadRoot_Database ()
+               {
+                       Reader.MoveToContent();
+                       if (Reader.LocalName != "Database" || Reader.NamespaceURI != "http://schemas.microsoft.com/linqtosql/dbml/2007")
+                               throw CreateUnknownNodeException();
+                       return ReadObject_Database (false, true);
+               }
+
+               public DbLinq.Schema.Dbml.Database ReadObject_Database (bool isNullable, bool checkType)
+               {
+                       DbLinq.Schema.Dbml.Database ob = null;
+                       if (isNullable && ReadNull()) return null;
+
+                       if (checkType) 
+                       {
+                               System.Xml.XmlQualifiedName t = GetXsiType();
+                               if (t == null)
+                               { }
+                               else if (t.Name != "Database" || t.Namespace != "http://schemas.microsoft.com/linqtosql/dbml/2007")
+                                       throw CreateUnknownTypeException(t);
+                       }
+
+                       ob = (DbLinq.Schema.Dbml.Database) Activator.CreateInstance(typeof(DbLinq.Schema.Dbml.Database), true);
+
+                       Reader.MoveToElement();
+
+                       while (Reader.MoveToNextAttribute())
+                       {
+                               if (Reader.LocalName == "Name" && Reader.NamespaceURI == "") {
+                                       ob.@Name = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "EntityNamespace" && Reader.NamespaceURI == "") {
+                                       ob.@EntityNamespace = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "ContextNamespace" && Reader.NamespaceURI == "") {
+                                       ob.@ContextNamespace = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "Class" && Reader.NamespaceURI == "") {
+                                       ob.@Class = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "AccessModifier" && Reader.NamespaceURI == "") {
+                                       ob.@AccessModifier = GetEnumValue_AccessModifier (Reader.Value);
+                                       ob.AccessModifierSpecified = true;
+                               }
+                               else if (Reader.LocalName == "Modifier" && Reader.NamespaceURI == "") {
+                                       ob.@Modifier = GetEnumValue_ClassModifier (Reader.Value);
+                                       ob.ModifierSpecified = true;
+                               }
+                               else if (Reader.LocalName == "BaseType" && Reader.NamespaceURI == "") {
+                                       ob.@BaseType = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "Provider" && Reader.NamespaceURI == "") {
+                                       ob.@Provider = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "ExternalMapping" && Reader.NamespaceURI == "") {
+                                       ob.@ExternalMapping = XmlConvert.ToBoolean (Reader.Value);
+                                       ob.ExternalMappingSpecified = true;
+                               }
+                               else if (Reader.LocalName == "Serialization" && Reader.NamespaceURI == "") {
+                                       ob.@Serialization = GetEnumValue_SerializationMode (Reader.Value);
+                                       ob.SerializationSpecified = true;
+                               }
+                               else if (Reader.LocalName == "EntityBase" && Reader.NamespaceURI == "") {
+                                       ob.@EntityBase = Reader.Value;
+                               }
+                               else if (IsXmlnsAttribute (Reader.Name)) {
+                               }
+                               else {
+                                       UnknownNode (ob);
+                               }
+                       }
+
+                       Reader.MoveToElement ();
+                       Reader.MoveToElement();
+                       if (Reader.IsEmptyElement) {
+                               Reader.Skip ();
+                               return ob;
+                       }
+
+                       Reader.ReadStartElement();
+                       Reader.MoveToContent();
+
+                       bool b0=false, b1=false, b2=false;
+
+                       DbLinq.Schema.Dbml.Table[] o4;
+                       o4 = null;
+                       DbLinq.Schema.Dbml.Function[] o6;
+                       o6 = null;
+                       int n3=0, n5=0;
+
+                       while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) 
+                       {
+                               if (Reader.NodeType == System.Xml.XmlNodeType.Element) 
+                               {
+                                       if (Reader.LocalName == "Table" && Reader.NamespaceURI == "http://schemas.microsoft.com/linqtosql/dbml/2007" && !b1) {
+                                               o4 = (DbLinq.Schema.Dbml.Table[]) EnsureArrayIndex (o4, n3, typeof(DbLinq.Schema.Dbml.Table));
+                                               o4[n3] = ReadObject_Table (false, true);
+                                               n3++;
+                                       }
+                                       else if (Reader.LocalName == "Function" && Reader.NamespaceURI == "http://schemas.microsoft.com/linqtosql/dbml/2007" && !b2) {
+                                               o6 = (DbLinq.Schema.Dbml.Function[]) EnsureArrayIndex (o6, n5, typeof(DbLinq.Schema.Dbml.Function));
+                                               o6[n5] = ReadObject_Function (false, true);
+                                               n5++;
+                                       }
+                                       else if (Reader.LocalName == "Connection" && Reader.NamespaceURI == "http://schemas.microsoft.com/linqtosql/dbml/2007" && !b0) {
+                                               b0 = true;
+                                               ob.@Connection = ReadObject_Connection (false, true);
+                                       }
+                                       else {
+                                               UnknownNode (ob);
+                                       }
+                               }
+                               else
+                                       UnknownNode(ob);
+
+                               Reader.MoveToContent();
+                       }
+
+                       o4 = (DbLinq.Schema.Dbml.Table[]) ShrinkArray (o4, n3, typeof(DbLinq.Schema.Dbml.Table), true);
+                       ob.@Table = o4;
+                       o6 = (DbLinq.Schema.Dbml.Function[]) ShrinkArray (o6, n5, typeof(DbLinq.Schema.Dbml.Function), true);
+                       ob.@Function = o6;
+
+                       ReadEndElement();
+
+                       return ob;
+               }
+
+               public DbLinq.Schema.Dbml.AccessModifier ReadObject_AccessModifier (bool isNullable, bool checkType)
+               {
+                       Reader.ReadStartElement ();
+                       DbLinq.Schema.Dbml.AccessModifier res = GetEnumValue_AccessModifier (Reader.ReadString());
+                       if (Reader.NodeType != XmlNodeType.None)
+                       Reader.ReadEndElement ();
+                       return res;
+               }
+
+               DbLinq.Schema.Dbml.AccessModifier GetEnumValue_AccessModifier (string xmlName)
+               {
+                       switch (xmlName)
+                       {
+                               case "Public": return DbLinq.Schema.Dbml.AccessModifier.Public;
+                               case "Internal": return DbLinq.Schema.Dbml.AccessModifier.Internal;
+                               case "Protected": return DbLinq.Schema.Dbml.AccessModifier.Protected;
+                               case "ProtectedInternal": return DbLinq.Schema.Dbml.AccessModifier.ProtectedInternal;
+                               case "Private": return DbLinq.Schema.Dbml.AccessModifier.Private;
+                               default:
+                                       throw CreateUnknownConstantException (xmlName, typeof(DbLinq.Schema.Dbml.AccessModifier));
+                       }
+               }
+
+               public DbLinq.Schema.Dbml.ClassModifier ReadObject_ClassModifier (bool isNullable, bool checkType)
+               {
+                       Reader.ReadStartElement ();
+                       DbLinq.Schema.Dbml.ClassModifier res = GetEnumValue_ClassModifier (Reader.ReadString());
+                       if (Reader.NodeType != XmlNodeType.None)
+                       Reader.ReadEndElement ();
+                       return res;
+               }
+
+               DbLinq.Schema.Dbml.ClassModifier GetEnumValue_ClassModifier (string xmlName)
+               {
+                       switch (xmlName)
+                       {
+                               case "Sealed": return DbLinq.Schema.Dbml.ClassModifier.Sealed;
+                               case "Abstract": return DbLinq.Schema.Dbml.ClassModifier.Abstract;
+                               default:
+                                       throw CreateUnknownConstantException (xmlName, typeof(DbLinq.Schema.Dbml.ClassModifier));
+                       }
+               }
+
+               public DbLinq.Schema.Dbml.SerializationMode ReadObject_SerializationMode (bool isNullable, bool checkType)
+               {
+                       Reader.ReadStartElement ();
+                       DbLinq.Schema.Dbml.SerializationMode res = GetEnumValue_SerializationMode (Reader.ReadString());
+                       if (Reader.NodeType != XmlNodeType.None)
+                       Reader.ReadEndElement ();
+                       return res;
+               }
+
+               DbLinq.Schema.Dbml.SerializationMode GetEnumValue_SerializationMode (string xmlName)
+               {
+                       switch (xmlName)
+                       {
+                               case "None": return DbLinq.Schema.Dbml.SerializationMode.None;
+                               case "Unidirectional": return DbLinq.Schema.Dbml.SerializationMode.Unidirectional;
+                               default:
+                                       throw CreateUnknownConstantException (xmlName, typeof(DbLinq.Schema.Dbml.SerializationMode));
+                       }
+               }
+
+               public DbLinq.Schema.Dbml.Table ReadObject_Table (bool isNullable, bool checkType)
+               {
+                       DbLinq.Schema.Dbml.Table ob = null;
+                       if (isNullable && ReadNull()) return null;
+
+                       if (checkType) 
+                       {
+                               System.Xml.XmlQualifiedName t = GetXsiType();
+                               if (t == null)
+                               { }
+                               else if (t.Name != "Table" || t.Namespace != "http://schemas.microsoft.com/linqtosql/dbml/2007")
+                                       throw CreateUnknownTypeException(t);
+                       }
+
+                       ob = (DbLinq.Schema.Dbml.Table) Activator.CreateInstance(typeof(DbLinq.Schema.Dbml.Table), true);
+
+                       Reader.MoveToElement();
+
+                       while (Reader.MoveToNextAttribute())
+                       {
+                               if (Reader.LocalName == "Name" && Reader.NamespaceURI == "") {
+                                       ob.@Name = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "Member" && Reader.NamespaceURI == "") {
+                                       ob.@Member = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "AccessModifier" && Reader.NamespaceURI == "") {
+                                       ob.@AccessModifier = GetEnumValue_AccessModifier (Reader.Value);
+                                       ob.AccessModifierSpecified = true;
+                               }
+                               else if (Reader.LocalName == "Modifier" && Reader.NamespaceURI == "") {
+                                       ob.@Modifier = GetEnumValue_MemberModifier (Reader.Value);
+                                       ob.ModifierSpecified = true;
+                               }
+                               else if (IsXmlnsAttribute (Reader.Name)) {
+                               }
+                               else {
+                                       UnknownNode (ob);
+                               }
+                       }
+
+                       Reader.MoveToElement ();
+                       Reader.MoveToElement();
+                       if (Reader.IsEmptyElement) {
+                               Reader.Skip ();
+                               return ob;
+                       }
+
+                       Reader.ReadStartElement();
+                       Reader.MoveToContent();
+
+                       bool b7=false, b8=false, b9=false, b10=false;
+
+                       while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) 
+                       {
+                               if (Reader.NodeType == System.Xml.XmlNodeType.Element) 
+                               {
+                                       if (Reader.LocalName == "UpdateFunction" && Reader.NamespaceURI == "http://schemas.microsoft.com/linqtosql/dbml/2007" && !b9) {
+                                               b9 = true;
+                                               ob.@UpdateFunction = ReadObject_TableFunction (false, true);
+                                       }
+                                       else if (Reader.LocalName == "Type" && Reader.NamespaceURI == "http://schemas.microsoft.com/linqtosql/dbml/2007" && !b7) {
+                                               b7 = true;
+                                               ob.@Type = ReadObject_Type (false, true);
+                                       }
+                                       else if (Reader.LocalName == "InsertFunction" && Reader.NamespaceURI == "http://schemas.microsoft.com/linqtosql/dbml/2007" && !b8) {
+                                               b8 = true;
+                                               ob.@InsertFunction = ReadObject_TableFunction (false, true);
+                                       }
+                                       else if (Reader.LocalName == "DeleteFunction" && Reader.NamespaceURI == "http://schemas.microsoft.com/linqtosql/dbml/2007" && !b10) {
+                                               b10 = true;
+                                               ob.@DeleteFunction = ReadObject_TableFunction (false, true);
+                                       }
+                                       else {
+                                               UnknownNode (ob);
+                                       }
+                               }
+                               else
+                                       UnknownNode(ob);
+
+                               Reader.MoveToContent();
+                       }
+
+                       ReadEndElement();
+
+                       return ob;
+               }
+
+               public DbLinq.Schema.Dbml.Function ReadObject_Function (bool isNullable, bool checkType)
+               {
+                       DbLinq.Schema.Dbml.Function ob = null;
+                       if (isNullable && ReadNull()) return null;
+
+                       if (checkType) 
+                       {
+                               System.Xml.XmlQualifiedName t = GetXsiType();
+                               if (t == null)
+                               { }
+                               else if (t.Name != "Function" || t.Namespace != "http://schemas.microsoft.com/linqtosql/dbml/2007")
+                                       throw CreateUnknownTypeException(t);
+                       }
+
+                       ob = (DbLinq.Schema.Dbml.Function) Activator.CreateInstance(typeof(DbLinq.Schema.Dbml.Function), true);
+
+                       Reader.MoveToElement();
+
+                       while (Reader.MoveToNextAttribute())
+                       {
+                               if (Reader.LocalName == "Name" && Reader.NamespaceURI == "") {
+                                       ob.@Name = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "Id" && Reader.NamespaceURI == "") {
+                                       ob.@Id = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "Method" && Reader.NamespaceURI == "") {
+                                       ob.@Method = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "AccessModifier" && Reader.NamespaceURI == "") {
+                                       ob.@AccessModifier = GetEnumValue_AccessModifier (Reader.Value);
+                                       ob.AccessModifierSpecified = true;
+                               }
+                               else if (Reader.LocalName == "Modifier" && Reader.NamespaceURI == "") {
+                                       ob.@Modifier = GetEnumValue_MemberModifier (Reader.Value);
+                                       ob.ModifierSpecified = true;
+                               }
+                               else if (Reader.LocalName == "HasMultipleResults" && Reader.NamespaceURI == "") {
+                                       ob.@HasMultipleResults = XmlConvert.ToBoolean (Reader.Value);
+                                       ob.HasMultipleResultsSpecified = true;
+                               }
+                               else if (Reader.LocalName == "IsComposable" && Reader.NamespaceURI == "") {
+                                       ob.@IsComposable = XmlConvert.ToBoolean (Reader.Value);
+                                       ob.IsComposableSpecified = true;
+                               }
+                               else if (IsXmlnsAttribute (Reader.Name)) {
+                               }
+                               else {
+                                       UnknownNode (ob);
+                               }
+                       }
+
+                       Reader.MoveToElement ();
+                       Reader.MoveToElement();
+                       if (Reader.IsEmptyElement) {
+                               Reader.Skip ();
+                               return ob;
+                       }
+
+                       Reader.ReadStartElement();
+                       Reader.MoveToContent();
+
+                       bool b11=false, b12=false;
+
+                       DbLinq.Schema.Dbml.Parameter[] o14;
+                       o14 = null;
+                       System.Object[] o16;
+                       o16 = null;
+                       int n13=0, n15=0;
+
+                       while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) 
+                       {
+                               if (Reader.NodeType == System.Xml.XmlNodeType.Element) 
+                               {
+                                       if (Reader.LocalName == "Return" && Reader.NamespaceURI == "http://schemas.microsoft.com/linqtosql/dbml/2007" && !b12) {
+                                               o16 = (System.Object[]) EnsureArrayIndex (o16, n15, typeof(System.Object));
+                                               o16[n15] = ReadObject_Return (false, true);
+                                               n15++;
+                                       }
+                                       else if (Reader.LocalName == "ElementType" && Reader.NamespaceURI == "http://schemas.microsoft.com/linqtosql/dbml/2007" && !b12) {
+                                               o16 = (System.Object[]) EnsureArrayIndex (o16, n15, typeof(System.Object));
+                                               o16[n15] = ReadObject_Type (false, true);
+                                               n15++;
+                                       }
+                                       else if (Reader.LocalName == "Parameter" && Reader.NamespaceURI == "http://schemas.microsoft.com/linqtosql/dbml/2007" && !b11) {
+                                               o14 = (DbLinq.Schema.Dbml.Parameter[]) EnsureArrayIndex (o14, n13, typeof(DbLinq.Schema.Dbml.Parameter));
+                                               o14[n13] = ReadObject_Parameter (false, true);
+                                               n13++;
+                                       }
+                                       else {
+                                               UnknownNode (ob);
+                                       }
+                               }
+                               else
+                                       UnknownNode(ob);
+
+                               Reader.MoveToContent();
+                       }
+
+                       o14 = (DbLinq.Schema.Dbml.Parameter[]) ShrinkArray (o14, n13, typeof(DbLinq.Schema.Dbml.Parameter), true);
+                       ob.@Parameter = o14;
+                       o16 = (System.Object[]) ShrinkArray (o16, n15, typeof(System.Object), true);
+                       ob.@Items = o16;
+
+                       ReadEndElement();
+
+                       return ob;
+               }
+
+               public DbLinq.Schema.Dbml.Connection ReadObject_Connection (bool isNullable, bool checkType)
+               {
+                       DbLinq.Schema.Dbml.Connection ob = null;
+                       if (isNullable && ReadNull()) return null;
+
+                       if (checkType) 
+                       {
+                               System.Xml.XmlQualifiedName t = GetXsiType();
+                               if (t == null)
+                               { }
+                               else if (t.Name != "Connection" || t.Namespace != "http://schemas.microsoft.com/linqtosql/dbml/2007")
+                                       throw CreateUnknownTypeException(t);
+                       }
+
+                       ob = (DbLinq.Schema.Dbml.Connection) Activator.CreateInstance(typeof(DbLinq.Schema.Dbml.Connection), true);
+
+                       Reader.MoveToElement();
+
+                       while (Reader.MoveToNextAttribute())
+                       {
+                               if (Reader.LocalName == "Provider" && Reader.NamespaceURI == "") {
+                                       ob.@Provider = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "Mode" && Reader.NamespaceURI == "") {
+                                       ob.@Mode = GetEnumValue_ConnectionMode (Reader.Value);
+                                       ob.ModeSpecified = true;
+                               }
+                               else if (Reader.LocalName == "ConnectionString" && Reader.NamespaceURI == "") {
+                                       ob.@ConnectionString = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "SettingsObjectName" && Reader.NamespaceURI == "") {
+                                       ob.@SettingsObjectName = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "SettingsPropertyName" && Reader.NamespaceURI == "") {
+                                       ob.@SettingsPropertyName = Reader.Value;
+                               }
+                               else if (IsXmlnsAttribute (Reader.Name)) {
+                               }
+                               else {
+                                       UnknownNode (ob);
+                               }
+                       }
+
+                       Reader.MoveToElement ();
+                       Reader.MoveToElement();
+                       if (Reader.IsEmptyElement) {
+                               Reader.Skip ();
+                               return ob;
+                       }
+
+                       Reader.ReadStartElement();
+                       Reader.MoveToContent();
+
+                       while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) 
+                       {
+                               if (Reader.NodeType == System.Xml.XmlNodeType.Element) 
+                               {
+                                       UnknownNode (ob);
+                               }
+                               else
+                                       UnknownNode(ob);
+
+                               Reader.MoveToContent();
+                       }
+
+                       ReadEndElement();
+
+                       return ob;
+               }
+
+               public DbLinq.Schema.Dbml.MemberModifier ReadObject_MemberModifier (bool isNullable, bool checkType)
+               {
+                       Reader.ReadStartElement ();
+                       DbLinq.Schema.Dbml.MemberModifier res = GetEnumValue_MemberModifier (Reader.ReadString());
+                       if (Reader.NodeType != XmlNodeType.None)
+                       Reader.ReadEndElement ();
+                       return res;
+               }
+
+               DbLinq.Schema.Dbml.MemberModifier GetEnumValue_MemberModifier (string xmlName)
+               {
+                       switch (xmlName)
+                       {
+                               case "Virtual": return DbLinq.Schema.Dbml.MemberModifier.Virtual;
+                               case "Override": return DbLinq.Schema.Dbml.MemberModifier.Override;
+                               case "New": return DbLinq.Schema.Dbml.MemberModifier.New;
+                               case "NewVirtual": return DbLinq.Schema.Dbml.MemberModifier.NewVirtual;
+                               default:
+                                       throw CreateUnknownConstantException (xmlName, typeof(DbLinq.Schema.Dbml.MemberModifier));
+                       }
+               }
+
+               public DbLinq.Schema.Dbml.TableFunction ReadObject_TableFunction (bool isNullable, bool checkType)
+               {
+                       DbLinq.Schema.Dbml.TableFunction ob = null;
+                       if (isNullable && ReadNull()) return null;
+
+                       if (checkType) 
+                       {
+                               System.Xml.XmlQualifiedName t = GetXsiType();
+                               if (t == null)
+                               { }
+                               else if (t.Name != "TableFunction" || t.Namespace != "http://schemas.microsoft.com/linqtosql/dbml/2007")
+                                       throw CreateUnknownTypeException(t);
+                       }
+
+                       ob = (DbLinq.Schema.Dbml.TableFunction) Activator.CreateInstance(typeof(DbLinq.Schema.Dbml.TableFunction), true);
+
+                       Reader.MoveToElement();
+
+                       while (Reader.MoveToNextAttribute())
+                       {
+                               if (Reader.LocalName == "FunctionId" && Reader.NamespaceURI == "") {
+                                       ob.@FunctionId = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "AccessModifier" && Reader.NamespaceURI == "") {
+                                       ob.@AccessModifier = GetEnumValue_AccessModifier (Reader.Value);
+                                       ob.AccessModifierSpecified = true;
+                               }
+                               else if (IsXmlnsAttribute (Reader.Name)) {
+                               }
+                               else {
+                                       UnknownNode (ob);
+                               }
+                       }
+
+                       Reader.MoveToElement ();
+                       Reader.MoveToElement();
+                       if (Reader.IsEmptyElement) {
+                               Reader.Skip ();
+                               return ob;
+                       }
+
+                       Reader.ReadStartElement();
+                       Reader.MoveToContent();
+
+                       bool b17=false, b18=false;
+
+                       DbLinq.Schema.Dbml.TableFunctionParameter[] o20;
+                       o20 = null;
+                       int n19=0;
+
+                       while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) 
+                       {
+                               if (Reader.NodeType == System.Xml.XmlNodeType.Element) 
+                               {
+                                       if (Reader.LocalName == "Return" && Reader.NamespaceURI == "http://schemas.microsoft.com/linqtosql/dbml/2007" && !b18) {
+                                               b18 = true;
+                                               ob.@Return = ReadObject_TableFunctionReturn (false, true);
+                                       }
+                                       else if (Reader.LocalName == "Argument" && Reader.NamespaceURI == "http://schemas.microsoft.com/linqtosql/dbml/2007" && !b17) {
+                                               o20 = (DbLinq.Schema.Dbml.TableFunctionParameter[]) EnsureArrayIndex (o20, n19, typeof(DbLinq.Schema.Dbml.TableFunctionParameter));
+                                               o20[n19] = ReadObject_TableFunctionParameter (false, true);
+                                               n19++;
+                                       }
+                                       else {
+                                               UnknownNode (ob);
+                                       }
+                               }
+                               else
+                                       UnknownNode(ob);
+
+                               Reader.MoveToContent();
+                       }
+
+                       o20 = (DbLinq.Schema.Dbml.TableFunctionParameter[]) ShrinkArray (o20, n19, typeof(DbLinq.Schema.Dbml.TableFunctionParameter), true);
+                       ob.@Argument = o20;
+
+                       ReadEndElement();
+
+                       return ob;
+               }
+
+               public DbLinq.Schema.Dbml.Type ReadObject_Type (bool isNullable, bool checkType)
+               {
+                       DbLinq.Schema.Dbml.Type ob = null;
+                       if (isNullable && ReadNull()) return null;
+
+                       if (checkType) 
+                       {
+                               System.Xml.XmlQualifiedName t = GetXsiType();
+                               if (t == null)
+                               { }
+                               else if (t.Name != "Type" || t.Namespace != "http://schemas.microsoft.com/linqtosql/dbml/2007")
+                                       throw CreateUnknownTypeException(t);
+                       }
+
+                       ob = (DbLinq.Schema.Dbml.Type) Activator.CreateInstance(typeof(DbLinq.Schema.Dbml.Type), true);
+
+                       Reader.MoveToElement();
+
+                       while (Reader.MoveToNextAttribute())
+                       {
+                               if (Reader.LocalName == "IdRef" && Reader.NamespaceURI == "") {
+                                       ob.@IdRef = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "Id" && Reader.NamespaceURI == "") {
+                                       ob.@Id = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "Name" && Reader.NamespaceURI == "") {
+                                       ob.@Name = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "InheritanceCode" && Reader.NamespaceURI == "") {
+                                       ob.@InheritanceCode = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "IsInheritanceDefault" && Reader.NamespaceURI == "") {
+                                       ob.@IsInheritanceDefault = XmlConvert.ToBoolean (Reader.Value);
+                                       ob.IsInheritanceDefaultSpecified = true;
+                               }
+                               else if (Reader.LocalName == "AccessModifier" && Reader.NamespaceURI == "") {
+                                       ob.@AccessModifier = GetEnumValue_AccessModifier (Reader.Value);
+                                       ob.AccessModifierSpecified = true;
+                               }
+                               else if (Reader.LocalName == "Modifier" && Reader.NamespaceURI == "") {
+                                       ob.@Modifier = GetEnumValue_ClassModifier (Reader.Value);
+                                       ob.ModifierSpecified = true;
+                               }
+                               else if (IsXmlnsAttribute (Reader.Name)) {
+                               }
+                               else {
+                                       UnknownNode (ob);
+                               }
+                       }
+
+                       Reader.MoveToElement ();
+                       Reader.MoveToElement();
+                       if (Reader.IsEmptyElement) {
+                               Reader.Skip ();
+                               return ob;
+                       }
+
+                       Reader.ReadStartElement();
+                       Reader.MoveToContent();
+
+                       bool b21=false, b22=false;
+
+                       System.Object[] o24;
+                       o24 = null;
+                       DbLinq.Schema.Dbml.Type[] o26;
+                       o26 = null;
+                       int n23=0, n25=0;
+
+                       while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) 
+                       {
+                               if (Reader.NodeType == System.Xml.XmlNodeType.Element) 
+                               {
+                                       if (Reader.LocalName == "Column" && Reader.NamespaceURI == "http://schemas.microsoft.com/linqtosql/dbml/2007" && !b21) {
+                                               o24 = (System.Object[]) EnsureArrayIndex (o24, n23, typeof(System.Object));
+                                               o24[n23] = ReadObject_Column (false, true);
+                                               n23++;
+                                       }
+                                       else if (Reader.LocalName == "Association" && Reader.NamespaceURI == "http://schemas.microsoft.com/linqtosql/dbml/2007" && !b21) {
+                                               o24 = (System.Object[]) EnsureArrayIndex (o24, n23, typeof(System.Object));
+                                               o24[n23] = ReadObject_Association (false, true);
+                                               n23++;
+                                       }
+                                       else if (Reader.LocalName == "Type" && Reader.NamespaceURI == "http://schemas.microsoft.com/linqtosql/dbml/2007" && !b22) {
+                                               o26 = (DbLinq.Schema.Dbml.Type[]) EnsureArrayIndex (o26, n25, typeof(DbLinq.Schema.Dbml.Type));
+                                               o26[n25] = ReadObject_Type (false, true);
+                                               n25++;
+                                       }
+                                       else {
+                                               UnknownNode (ob);
+                                       }
+                               }
+                               else
+                                       UnknownNode(ob);
+
+                               Reader.MoveToContent();
+                       }
+
+                       o24 = (System.Object[]) ShrinkArray (o24, n23, typeof(System.Object), true);
+                       ob.@Items = o24;
+                       o26 = (DbLinq.Schema.Dbml.Type[]) ShrinkArray (o26, n25, typeof(DbLinq.Schema.Dbml.Type), true);
+                       ob.@Type1 = o26;
+
+                       ReadEndElement();
+
+                       return ob;
+               }
+
+               public DbLinq.Schema.Dbml.Return ReadObject_Return (bool isNullable, bool checkType)
+               {
+                       DbLinq.Schema.Dbml.Return ob = null;
+                       if (isNullable && ReadNull()) return null;
+
+                       if (checkType) 
+                       {
+                               System.Xml.XmlQualifiedName t = GetXsiType();
+                               if (t == null)
+                               { }
+                               else if (t.Name != "Return" || t.Namespace != "http://schemas.microsoft.com/linqtosql/dbml/2007")
+                                       throw CreateUnknownTypeException(t);
+                       }
+
+                       ob = (DbLinq.Schema.Dbml.Return) Activator.CreateInstance(typeof(DbLinq.Schema.Dbml.Return), true);
+
+                       Reader.MoveToElement();
+
+                       while (Reader.MoveToNextAttribute())
+                       {
+                               if (Reader.LocalName == "Type" && Reader.NamespaceURI == "") {
+                                       ob.@Type = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "DbType" && Reader.NamespaceURI == "") {
+                                       ob.@DbType = Reader.Value;
+                               }
+                               else if (IsXmlnsAttribute (Reader.Name)) {
+                               }
+                               else {
+                                       UnknownNode (ob);
+                               }
+                       }
+
+                       Reader.MoveToElement ();
+                       Reader.MoveToElement();
+                       if (Reader.IsEmptyElement) {
+                               Reader.Skip ();
+                               return ob;
+                       }
+
+                       Reader.ReadStartElement();
+                       Reader.MoveToContent();
+
+                       while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) 
+                       {
+                               if (Reader.NodeType == System.Xml.XmlNodeType.Element) 
+                               {
+                                       UnknownNode (ob);
+                               }
+                               else
+                                       UnknownNode(ob);
+
+                               Reader.MoveToContent();
+                       }
+
+                       ReadEndElement();
+
+                       return ob;
+               }
+
+               public DbLinq.Schema.Dbml.Parameter ReadObject_Parameter (bool isNullable, bool checkType)
+               {
+                       DbLinq.Schema.Dbml.Parameter ob = null;
+                       if (isNullable && ReadNull()) return null;
+
+                       if (checkType) 
+                       {
+                               System.Xml.XmlQualifiedName t = GetXsiType();
+                               if (t == null)
+                               { }
+                               else if (t.Name != "Parameter" || t.Namespace != "http://schemas.microsoft.com/linqtosql/dbml/2007")
+                                       throw CreateUnknownTypeException(t);
+                       }
+
+                       ob = (DbLinq.Schema.Dbml.Parameter) Activator.CreateInstance(typeof(DbLinq.Schema.Dbml.Parameter), true);
+
+                       Reader.MoveToElement();
+
+                       while (Reader.MoveToNextAttribute())
+                       {
+                               if (Reader.LocalName == "Name" && Reader.NamespaceURI == "") {
+                                       ob.@Name = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "Parameter" && Reader.NamespaceURI == "") {
+                                       ob.@Parameter1 = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "Type" && Reader.NamespaceURI == "") {
+                                       ob.@Type = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "DbType" && Reader.NamespaceURI == "") {
+                                       ob.@DbType = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "Direction" && Reader.NamespaceURI == "") {
+                                       ob.@Direction = GetEnumValue_ParameterDirection (Reader.Value);
+                                       ob.DirectionSpecified = true;
+                               }
+                               else if (IsXmlnsAttribute (Reader.Name)) {
+                               }
+                               else {
+                                       UnknownNode (ob);
+                               }
+                       }
+
+                       Reader.MoveToElement ();
+                       Reader.MoveToElement();
+                       if (Reader.IsEmptyElement) {
+                               Reader.Skip ();
+                               return ob;
+                       }
+
+                       Reader.ReadStartElement();
+                       Reader.MoveToContent();
+
+                       while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) 
+                       {
+                               if (Reader.NodeType == System.Xml.XmlNodeType.Element) 
+                               {
+                                       UnknownNode (ob);
+                               }
+                               else
+                                       UnknownNode(ob);
+
+                               Reader.MoveToContent();
+                       }
+
+                       ReadEndElement();
+
+                       return ob;
+               }
+
+               public DbLinq.Schema.Dbml.ConnectionMode ReadObject_ConnectionMode (bool isNullable, bool checkType)
+               {
+                       Reader.ReadStartElement ();
+                       DbLinq.Schema.Dbml.ConnectionMode res = GetEnumValue_ConnectionMode (Reader.ReadString());
+                       if (Reader.NodeType != XmlNodeType.None)
+                       Reader.ReadEndElement ();
+                       return res;
+               }
+
+               DbLinq.Schema.Dbml.ConnectionMode GetEnumValue_ConnectionMode (string xmlName)
+               {
+                       switch (xmlName)
+                       {
+                               case "ConnectionString": return DbLinq.Schema.Dbml.ConnectionMode.ConnectionString;
+                               case "AppSettings": return DbLinq.Schema.Dbml.ConnectionMode.AppSettings;
+                               case "WebSettings": return DbLinq.Schema.Dbml.ConnectionMode.WebSettings;
+                               default:
+                                       throw CreateUnknownConstantException (xmlName, typeof(DbLinq.Schema.Dbml.ConnectionMode));
+                       }
+               }
+
+               public DbLinq.Schema.Dbml.TableFunctionReturn ReadObject_TableFunctionReturn (bool isNullable, bool checkType)
+               {
+                       DbLinq.Schema.Dbml.TableFunctionReturn ob = null;
+                       if (isNullable && ReadNull()) return null;
+
+                       if (checkType) 
+                       {
+                               System.Xml.XmlQualifiedName t = GetXsiType();
+                               if (t == null)
+                               { }
+                               else if (t.Name != "TableFunctionReturn" || t.Namespace != "http://schemas.microsoft.com/linqtosql/dbml/2007")
+                                       throw CreateUnknownTypeException(t);
+                       }
+
+                       ob = (DbLinq.Schema.Dbml.TableFunctionReturn) Activator.CreateInstance(typeof(DbLinq.Schema.Dbml.TableFunctionReturn), true);
+
+                       Reader.MoveToElement();
+
+                       while (Reader.MoveToNextAttribute())
+                       {
+                               if (Reader.LocalName == "Member" && Reader.NamespaceURI == "") {
+                                       ob.@Member = Reader.Value;
+                               }
+                               else if (IsXmlnsAttribute (Reader.Name)) {
+                               }
+                               else {
+                                       UnknownNode (ob);
+                               }
+                       }
+
+                       Reader.MoveToElement ();
+                       Reader.MoveToElement();
+                       if (Reader.IsEmptyElement) {
+                               Reader.Skip ();
+                               return ob;
+                       }
+
+                       Reader.ReadStartElement();
+                       Reader.MoveToContent();
+
+                       while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) 
+                       {
+                               if (Reader.NodeType == System.Xml.XmlNodeType.Element) 
+                               {
+                                       UnknownNode (ob);
+                               }
+                               else
+                                       UnknownNode(ob);
+
+                               Reader.MoveToContent();
+                       }
+
+                       ReadEndElement();
+
+                       return ob;
+               }
+
+               public DbLinq.Schema.Dbml.TableFunctionParameter ReadObject_TableFunctionParameter (bool isNullable, bool checkType)
+               {
+                       DbLinq.Schema.Dbml.TableFunctionParameter ob = null;
+                       if (isNullable && ReadNull()) return null;
+
+                       if (checkType) 
+                       {
+                               System.Xml.XmlQualifiedName t = GetXsiType();
+                               if (t == null)
+                               { }
+                               else if (t.Name != "TableFunctionParameter" || t.Namespace != "http://schemas.microsoft.com/linqtosql/dbml/2007")
+                                       throw CreateUnknownTypeException(t);
+                       }
+
+                       ob = (DbLinq.Schema.Dbml.TableFunctionParameter) Activator.CreateInstance(typeof(DbLinq.Schema.Dbml.TableFunctionParameter), true);
+
+                       Reader.MoveToElement();
+
+                       while (Reader.MoveToNextAttribute())
+                       {
+                               if (Reader.LocalName == "Parameter" && Reader.NamespaceURI == "") {
+                                       ob.@Parameter = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "Member" && Reader.NamespaceURI == "") {
+                                       ob.@Member = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "Version" && Reader.NamespaceURI == "") {
+                                       ob.@Version = GetEnumValue_Version (Reader.Value);
+                                       ob.VersionSpecified = true;
+                               }
+                               else if (IsXmlnsAttribute (Reader.Name)) {
+                               }
+                               else {
+                                       UnknownNode (ob);
+                               }
+                       }
+
+                       Reader.MoveToElement ();
+                       Reader.MoveToElement();
+                       if (Reader.IsEmptyElement) {
+                               Reader.Skip ();
+                               return ob;
+                       }
+
+                       Reader.ReadStartElement();
+                       Reader.MoveToContent();
+
+                       while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) 
+                       {
+                               if (Reader.NodeType == System.Xml.XmlNodeType.Element) 
+                               {
+                                       UnknownNode (ob);
+                               }
+                               else
+                                       UnknownNode(ob);
+
+                               Reader.MoveToContent();
+                       }
+
+                       ReadEndElement();
+
+                       return ob;
+               }
+
+               public DbLinq.Schema.Dbml.Column ReadObject_Column (bool isNullable, bool checkType)
+               {
+                       DbLinq.Schema.Dbml.Column ob = null;
+                       if (isNullable && ReadNull()) return null;
+
+                       if (checkType) 
+                       {
+                               System.Xml.XmlQualifiedName t = GetXsiType();
+                               if (t == null)
+                               { }
+                               else if (t.Name != "Column" || t.Namespace != "http://schemas.microsoft.com/linqtosql/dbml/2007")
+                                       throw CreateUnknownTypeException(t);
+                       }
+
+                       ob = (DbLinq.Schema.Dbml.Column) Activator.CreateInstance(typeof(DbLinq.Schema.Dbml.Column), true);
+
+                       Reader.MoveToElement();
+
+                       while (Reader.MoveToNextAttribute())
+                       {
+                               if (Reader.LocalName == "Name" && Reader.NamespaceURI == "") {
+                                       ob.@Name = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "Member" && Reader.NamespaceURI == "") {
+                                       ob.@Member = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "Storage" && Reader.NamespaceURI == "") {
+                                       ob.@Storage = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "AccessModifier" && Reader.NamespaceURI == "") {
+                                       ob.@AccessModifier = GetEnumValue_AccessModifier (Reader.Value);
+                                       ob.AccessModifierSpecified = true;
+                               }
+                               else if (Reader.LocalName == "Modifier" && Reader.NamespaceURI == "") {
+                                       ob.@Modifier = GetEnumValue_MemberModifier (Reader.Value);
+                                       ob.ModifierSpecified = true;
+                               }
+                               else if (Reader.LocalName == "Type" && Reader.NamespaceURI == "") {
+                                       ob.@Type = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "DbType" && Reader.NamespaceURI == "") {
+                                       ob.@DbType = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "IsReadOnly" && Reader.NamespaceURI == "") {
+                                       ob.@IsReadOnly = XmlConvert.ToBoolean (Reader.Value);
+                                       ob.IsReadOnlySpecified = true;
+                               }
+                               else if (Reader.LocalName == "IsPrimaryKey" && Reader.NamespaceURI == "") {
+                                       ob.@IsPrimaryKey = XmlConvert.ToBoolean (Reader.Value);
+                                       ob.IsPrimaryKeySpecified = true;
+                               }
+                               else if (Reader.LocalName == "IsDbGenerated" && Reader.NamespaceURI == "") {
+                                       ob.@IsDbGenerated = XmlConvert.ToBoolean (Reader.Value);
+                                       ob.IsDbGeneratedSpecified = true;
+                               }
+                               else if (Reader.LocalName == "CanBeNull" && Reader.NamespaceURI == "") {
+                                       ob.@CanBeNull = XmlConvert.ToBoolean (Reader.Value);
+                                       ob.CanBeNullSpecified = true;
+                               }
+                               else if (Reader.LocalName == "UpdateCheck" && Reader.NamespaceURI == "") {
+                                       ob.@UpdateCheck = GetEnumValue_UpdateCheck (Reader.Value);
+                                       ob.UpdateCheckSpecified = true;
+                               }
+                               else if (Reader.LocalName == "IsDiscriminator" && Reader.NamespaceURI == "") {
+                                       ob.@IsDiscriminator = XmlConvert.ToBoolean (Reader.Value);
+                                       ob.IsDiscriminatorSpecified = true;
+                               }
+                               else if (Reader.LocalName == "Expression" && Reader.NamespaceURI == "") {
+                                       ob.@Expression = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "IsVersion" && Reader.NamespaceURI == "") {
+                                       ob.@IsVersion = XmlConvert.ToBoolean (Reader.Value);
+                                       ob.IsVersionSpecified = true;
+                               }
+                               else if (Reader.LocalName == "IsDelayLoaded" && Reader.NamespaceURI == "") {
+                                       ob.@IsDelayLoaded = XmlConvert.ToBoolean (Reader.Value);
+                                       ob.IsDelayLoadedSpecified = true;
+                               }
+                               else if (Reader.LocalName == "AutoSync" && Reader.NamespaceURI == "") {
+                                       ob.@AutoSync = GetEnumValue_AutoSync (Reader.Value);
+                                       ob.AutoSyncSpecified = true;
+                               }
+                               else if (IsXmlnsAttribute (Reader.Name)) {
+                               }
+                               else {
+                                       UnknownNode (ob);
+                               }
+                       }
+
+                       Reader.MoveToElement ();
+                       Reader.MoveToElement();
+                       if (Reader.IsEmptyElement) {
+                               Reader.Skip ();
+                               return ob;
+                       }
+
+                       Reader.ReadStartElement();
+                       Reader.MoveToContent();
+
+                       while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) 
+                       {
+                               if (Reader.NodeType == System.Xml.XmlNodeType.Element) 
+                               {
+                                       UnknownNode (ob);
+                               }
+                               else
+                                       UnknownNode(ob);
+
+                               Reader.MoveToContent();
+                       }
+
+                       ReadEndElement();
+
+                       return ob;
+               }
+
+               public DbLinq.Schema.Dbml.Association ReadObject_Association (bool isNullable, bool checkType)
+               {
+                       DbLinq.Schema.Dbml.Association ob = null;
+                       if (isNullable && ReadNull()) return null;
+
+                       if (checkType) 
+                       {
+                               System.Xml.XmlQualifiedName t = GetXsiType();
+                               if (t == null)
+                               { }
+                               else if (t.Name != "Association" || t.Namespace != "http://schemas.microsoft.com/linqtosql/dbml/2007")
+                                       throw CreateUnknownTypeException(t);
+                       }
+
+                       ob = (DbLinq.Schema.Dbml.Association) Activator.CreateInstance(typeof(DbLinq.Schema.Dbml.Association), true);
+
+                       Reader.MoveToElement();
+
+                       while (Reader.MoveToNextAttribute())
+                       {
+                               if (Reader.LocalName == "Name" && Reader.NamespaceURI == "") {
+                                       ob.@Name = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "Member" && Reader.NamespaceURI == "") {
+                                       ob.@Member = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "Storage" && Reader.NamespaceURI == "") {
+                                       ob.@Storage = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "AccessModifier" && Reader.NamespaceURI == "") {
+                                       ob.@AccessModifier = GetEnumValue_AccessModifier (Reader.Value);
+                                       ob.AccessModifierSpecified = true;
+                               }
+                               else if (Reader.LocalName == "Modifier" && Reader.NamespaceURI == "") {
+                                       ob.@Modifier = GetEnumValue_MemberModifier (Reader.Value);
+                                       ob.ModifierSpecified = true;
+                               }
+                               else if (Reader.LocalName == "Type" && Reader.NamespaceURI == "") {
+                                       ob.@Type = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "ThisKey" && Reader.NamespaceURI == "") {
+                                       ob.@ThisKey = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "OtherKey" && Reader.NamespaceURI == "") {
+                                       ob.@OtherKey = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "IsForeignKey" && Reader.NamespaceURI == "") {
+                                       ob.@IsForeignKey = XmlConvert.ToBoolean (Reader.Value);
+                                       ob.IsForeignKeySpecified = true;
+                               }
+                               else if (Reader.LocalName == "Cardinality" && Reader.NamespaceURI == "") {
+                                       ob.@Cardinality = GetEnumValue_Cardinality (Reader.Value);
+                                       ob.CardinalitySpecified = true;
+                               }
+                               else if (Reader.LocalName == "DeleteRule" && Reader.NamespaceURI == "") {
+                                       ob.@DeleteRule = Reader.Value;
+                               }
+                               else if (Reader.LocalName == "DeleteOnNull" && Reader.NamespaceURI == "") {
+                                       ob.@DeleteOnNull = XmlConvert.ToBoolean (Reader.Value);
+                                       ob.DeleteOnNullSpecified = true;
+                               }
+                               else if (IsXmlnsAttribute (Reader.Name)) {
+                               }
+                               else {
+                                       UnknownNode (ob);
+                               }
+                       }
+
+                       Reader.MoveToElement ();
+                       Reader.MoveToElement();
+                       if (Reader.IsEmptyElement) {
+                               Reader.Skip ();
+                               return ob;
+                       }
+
+                       Reader.ReadStartElement();
+                       Reader.MoveToContent();
+
+                       while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) 
+                       {
+                               if (Reader.NodeType == System.Xml.XmlNodeType.Element) 
+                               {
+                                       UnknownNode (ob);
+                               }
+                               else
+                                       UnknownNode(ob);
+
+                               Reader.MoveToContent();
+                       }
+
+                       ReadEndElement();
+
+                       return ob;
+               }
+
+               public DbLinq.Schema.Dbml.ParameterDirection ReadObject_ParameterDirection (bool isNullable, bool checkType)
+               {
+                       Reader.ReadStartElement ();
+                       DbLinq.Schema.Dbml.ParameterDirection res = GetEnumValue_ParameterDirection (Reader.ReadString());
+                       if (Reader.NodeType != XmlNodeType.None)
+                       Reader.ReadEndElement ();
+                       return res;
+               }
+
+               DbLinq.Schema.Dbml.ParameterDirection GetEnumValue_ParameterDirection (string xmlName)
+               {
+                       switch (xmlName)
+                       {
+                               case "In": return DbLinq.Schema.Dbml.ParameterDirection.In;
+                               case "Out": return DbLinq.Schema.Dbml.ParameterDirection.Out;
+                               case "InOut": return DbLinq.Schema.Dbml.ParameterDirection.InOut;
+                               default:
+                                       throw CreateUnknownConstantException (xmlName, typeof(DbLinq.Schema.Dbml.ParameterDirection));
+                       }
+               }
+
+               public DbLinq.Schema.Dbml.Version ReadObject_Version (bool isNullable, bool checkType)
+               {
+                       Reader.ReadStartElement ();
+                       DbLinq.Schema.Dbml.Version res = GetEnumValue_Version (Reader.ReadString());
+                       if (Reader.NodeType != XmlNodeType.None)
+                       Reader.ReadEndElement ();
+                       return res;
+               }
+
+               DbLinq.Schema.Dbml.Version GetEnumValue_Version (string xmlName)
+               {
+                       switch (xmlName)
+                       {
+                               case "Current": return DbLinq.Schema.Dbml.Version.Current;
+                               case "Original": return DbLinq.Schema.Dbml.Version.Original;
+                               default:
+                                       throw CreateUnknownConstantException (xmlName, typeof(DbLinq.Schema.Dbml.Version));
+                       }
+               }
+
+               public DbLinq.Schema.Dbml.UpdateCheck ReadObject_UpdateCheck (bool isNullable, bool checkType)
+               {
+                       Reader.ReadStartElement ();
+                       DbLinq.Schema.Dbml.UpdateCheck res = GetEnumValue_UpdateCheck (Reader.ReadString());
+                       if (Reader.NodeType != XmlNodeType.None)
+                       Reader.ReadEndElement ();
+                       return res;
+               }
+
+               DbLinq.Schema.Dbml.UpdateCheck GetEnumValue_UpdateCheck (string xmlName)
+               {
+                       switch (xmlName)
+                       {
+                               case "Always": return DbLinq.Schema.Dbml.UpdateCheck.Always;
+                               case "Never": return DbLinq.Schema.Dbml.UpdateCheck.Never;
+                               case "WhenChanged": return DbLinq.Schema.Dbml.UpdateCheck.WhenChanged;
+                               default:
+                                       throw CreateUnknownConstantException (xmlName, typeof(DbLinq.Schema.Dbml.UpdateCheck));
+                       }
+               }
+
+               public DbLinq.Schema.Dbml.AutoSync ReadObject_AutoSync (bool isNullable, bool checkType)
+               {
+                       Reader.ReadStartElement ();
+                       DbLinq.Schema.Dbml.AutoSync res = GetEnumValue_AutoSync (Reader.ReadString());
+                       if (Reader.NodeType != XmlNodeType.None)
+                       Reader.ReadEndElement ();
+                       return res;
+               }
+
+               DbLinq.Schema.Dbml.AutoSync GetEnumValue_AutoSync (string xmlName)
+               {
+                       switch (xmlName)
+                       {
+                               case "Never": return DbLinq.Schema.Dbml.AutoSync.Never;
+                               case "OnInsert": return DbLinq.Schema.Dbml.AutoSync.OnInsert;
+                               case "OnUpdate": return DbLinq.Schema.Dbml.AutoSync.OnUpdate;
+                               case "Always": return DbLinq.Schema.Dbml.AutoSync.Always;
+                               case "Default": return DbLinq.Schema.Dbml.AutoSync.Default;
+                               default:
+                                       throw CreateUnknownConstantException (xmlName, typeof(DbLinq.Schema.Dbml.AutoSync));
+                       }
+               }
+
+               public DbLinq.Schema.Dbml.Cardinality ReadObject_Cardinality (bool isNullable, bool checkType)
+               {
+                       Reader.ReadStartElement ();
+                       DbLinq.Schema.Dbml.Cardinality res = GetEnumValue_Cardinality (Reader.ReadString());
+                       if (Reader.NodeType != XmlNodeType.None)
+                       Reader.ReadEndElement ();
+                       return res;
+               }
+
+               DbLinq.Schema.Dbml.Cardinality GetEnumValue_Cardinality (string xmlName)
+               {
+                       switch (xmlName)
+                       {
+                               case "One": return DbLinq.Schema.Dbml.Cardinality.One;
+                               case "Many": return DbLinq.Schema.Dbml.Cardinality.Many;
+                               default:
+                                       throw CreateUnknownConstantException (xmlName, typeof(DbLinq.Schema.Dbml.Cardinality));
+                       }
+               }
+
+               protected override void InitCallbacks ()
+               {
+               }
+
+               protected override void InitIDs ()
+               {
+               }
+
+       }
+
+       #if !MONO_STRICT
+    public
+    #endif
+       class GeneratedWriter : XmlSerializationWriter
+       {
+               const string xmlNamespace = "http://www.w3.org/2000/xmlns/";
+               static readonly System.Reflection.MethodInfo toBinHexStringMethod = typeof (XmlConvert).GetMethod ("ToBinHexString", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic, null, new System.Type [] {typeof (byte [])}, null);
+               static string ToBinHexString (byte [] input)
+               {
+                       return input == null ? null : (string) toBinHexStringMethod.Invoke (null, new object [] {input});
+               }
+               public void WriteRoot_Database (object o)
+               {
+                       WriteStartDocument ();
+                       DbLinq.Schema.Dbml.Database ob = (DbLinq.Schema.Dbml.Database) o;
+                       TopLevelElement ();
+                       WriteObject_Database (ob, "Database", "http://schemas.microsoft.com/linqtosql/dbml/2007", true, false, true);
+               }
+
+               void WriteObject_Database (DbLinq.Schema.Dbml.Database ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       if (((object)ob) == null)
+                       {
+                               if (isNullable)
+                                       WriteNullTagLiteral(element, namesp);
+                               return;
+                       }
+
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.Database))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("Database", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       WriteAttribute ("Name", "", ob.@Name);
+                       WriteAttribute ("EntityNamespace", "", ob.@EntityNamespace);
+                       WriteAttribute ("ContextNamespace", "", ob.@ContextNamespace);
+                       WriteAttribute ("Class", "", ob.@Class);
+                       if (ob.@AccessModifierSpecified) {
+                               WriteAttribute ("AccessModifier", "", GetEnumValue_AccessModifier (ob.@AccessModifier));
+                       }
+                       if (ob.@ModifierSpecified) {
+                               WriteAttribute ("Modifier", "", GetEnumValue_ClassModifier (ob.@Modifier));
+                       }
+                       WriteAttribute ("BaseType", "", ob.@BaseType);
+                       WriteAttribute ("Provider", "", ob.@Provider);
+                       if (ob.@ExternalMappingSpecified) {
+                               WriteAttribute ("ExternalMapping", "", (ob.@ExternalMapping?"true":"false"));
+                       }
+                       if (ob.@SerializationSpecified) {
+                               WriteAttribute ("Serialization", "", GetEnumValue_SerializationMode (ob.@Serialization));
+                       }
+                       WriteAttribute ("EntityBase", "", ob.@EntityBase);
+
+                       WriteObject_Connection (ob.@Connection, "Connection", "http://schemas.microsoft.com/linqtosql/dbml/2007", false, false, true);
+                       if (ob.@Table != null) {
+                               for (int n27 = 0; n27 < ob.@Table.Length; n27++) {
+                                       WriteObject_Table (ob.@Table[n27], "Table", "http://schemas.microsoft.com/linqtosql/dbml/2007", false, false, true);
+                               }
+                       }
+                       if (ob.@Function != null) {
+                               for (int n28 = 0; n28 < ob.@Function.Length; n28++) {
+                                       WriteObject_Function (ob.@Function[n28], "Function", "http://schemas.microsoft.com/linqtosql/dbml/2007", false, false, true);
+                               }
+                       }
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               void WriteObject_AccessModifier (DbLinq.Schema.Dbml.AccessModifier ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.AccessModifier))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("AccessModifier", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       Writer.WriteString (GetEnumValue_AccessModifier (ob));
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               string GetEnumValue_AccessModifier (DbLinq.Schema.Dbml.AccessModifier val)
+               {
+                       switch (val) {
+                               case DbLinq.Schema.Dbml.AccessModifier.Public: return "Public";
+                               case DbLinq.Schema.Dbml.AccessModifier.Internal: return "Internal";
+                               case DbLinq.Schema.Dbml.AccessModifier.Protected: return "Protected";
+                               case DbLinq.Schema.Dbml.AccessModifier.ProtectedInternal: return "ProtectedInternal";
+                               case DbLinq.Schema.Dbml.AccessModifier.Private: return "Private";
+                               default: throw CreateInvalidEnumValueException ((long) val, typeof (DbLinq.Schema.Dbml.AccessModifier).FullName);
+                       }
+               }
+
+               void WriteObject_ClassModifier (DbLinq.Schema.Dbml.ClassModifier ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.ClassModifier))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("ClassModifier", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       Writer.WriteString (GetEnumValue_ClassModifier (ob));
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               string GetEnumValue_ClassModifier (DbLinq.Schema.Dbml.ClassModifier val)
+               {
+                       switch (val) {
+                               case DbLinq.Schema.Dbml.ClassModifier.Sealed: return "Sealed";
+                               case DbLinq.Schema.Dbml.ClassModifier.Abstract: return "Abstract";
+                               default: throw CreateInvalidEnumValueException ((long) val, typeof (DbLinq.Schema.Dbml.ClassModifier).FullName);
+                       }
+               }
+
+               void WriteObject_SerializationMode (DbLinq.Schema.Dbml.SerializationMode ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.SerializationMode))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("SerializationMode", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       Writer.WriteString (GetEnumValue_SerializationMode (ob));
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               string GetEnumValue_SerializationMode (DbLinq.Schema.Dbml.SerializationMode val)
+               {
+                       switch (val) {
+                               case DbLinq.Schema.Dbml.SerializationMode.None: return "None";
+                               case DbLinq.Schema.Dbml.SerializationMode.Unidirectional: return "Unidirectional";
+                               default: throw CreateInvalidEnumValueException ((long) val, typeof (DbLinq.Schema.Dbml.SerializationMode).FullName);
+                       }
+               }
+
+               void WriteObject_Connection (DbLinq.Schema.Dbml.Connection ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       if (((object)ob) == null)
+                       {
+                               if (isNullable)
+                                       WriteNullTagLiteral(element, namesp);
+                               return;
+                       }
+
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.Connection))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("Connection", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       WriteAttribute ("Provider", "", ob.@Provider);
+                       if (ob.@ModeSpecified) {
+                               WriteAttribute ("Mode", "", GetEnumValue_ConnectionMode (ob.@Mode));
+                       }
+                       WriteAttribute ("ConnectionString", "", ob.@ConnectionString);
+                       WriteAttribute ("SettingsObjectName", "", ob.@SettingsObjectName);
+                       WriteAttribute ("SettingsPropertyName", "", ob.@SettingsPropertyName);
+
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               void WriteObject_Table (DbLinq.Schema.Dbml.Table ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       if (((object)ob) == null)
+                       {
+                               if (isNullable)
+                                       WriteNullTagLiteral(element, namesp);
+                               return;
+                       }
+
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.Table))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("Table", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       WriteAttribute ("Name", "", ob.@Name);
+                       WriteAttribute ("Member", "", ob.@Member);
+                       if (ob.@AccessModifierSpecified) {
+                               WriteAttribute ("AccessModifier", "", GetEnumValue_AccessModifier (ob.@AccessModifier));
+                       }
+                       if (ob.@ModifierSpecified) {
+                               WriteAttribute ("Modifier", "", GetEnumValue_MemberModifier (ob.@Modifier));
+                       }
+
+                       WriteObject_Type (ob.@Type, "Type", "http://schemas.microsoft.com/linqtosql/dbml/2007", false, false, true);
+                       WriteObject_TableFunction (ob.@InsertFunction, "InsertFunction", "http://schemas.microsoft.com/linqtosql/dbml/2007", false, false, true);
+                       WriteObject_TableFunction (ob.@UpdateFunction, "UpdateFunction", "http://schemas.microsoft.com/linqtosql/dbml/2007", false, false, true);
+                       WriteObject_TableFunction (ob.@DeleteFunction, "DeleteFunction", "http://schemas.microsoft.com/linqtosql/dbml/2007", false, false, true);
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               void WriteObject_Function (DbLinq.Schema.Dbml.Function ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       if (((object)ob) == null)
+                       {
+                               if (isNullable)
+                                       WriteNullTagLiteral(element, namesp);
+                               return;
+                       }
+
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.Function))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("Function", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       WriteAttribute ("Name", "", ob.@Name);
+                       WriteAttribute ("Id", "", ob.@Id);
+                       WriteAttribute ("Method", "", ob.@Method);
+                       if (ob.@AccessModifierSpecified) {
+                               WriteAttribute ("AccessModifier", "", GetEnumValue_AccessModifier (ob.@AccessModifier));
+                       }
+                       if (ob.@ModifierSpecified) {
+                               WriteAttribute ("Modifier", "", GetEnumValue_MemberModifier (ob.@Modifier));
+                       }
+                       if (ob.@HasMultipleResultsSpecified) {
+                               WriteAttribute ("HasMultipleResults", "", (ob.@HasMultipleResults?"true":"false"));
+                       }
+                       if (ob.@IsComposableSpecified) {
+                               WriteAttribute ("IsComposable", "", (ob.@IsComposable?"true":"false"));
+                       }
+
+                       if (ob.@Parameter != null) {
+                               for (int n29 = 0; n29 < ob.@Parameter.Length; n29++) {
+                                       WriteObject_Parameter (ob.@Parameter[n29], "Parameter", "http://schemas.microsoft.com/linqtosql/dbml/2007", false, false, true);
+                               }
+                       }
+                       if (ob.@Items != null) {
+                               for (int n30 = 0; n30 < ob.@Items.Length; n30++) {
+                                       if (((object)ob.@Items[n30]) == null) { }
+                                       else if (ob.@Items[n30].GetType() == typeof(DbLinq.Schema.Dbml.Return)) {
+                                               WriteObject_Return (((DbLinq.Schema.Dbml.Return) ob.@Items[n30]), "Return", "http://schemas.microsoft.com/linqtosql/dbml/2007", false, false, true);
+                                       }
+                                       else if (ob.@Items[n30].GetType() == typeof(DbLinq.Schema.Dbml.Type)) {
+                                               WriteObject_Type (((DbLinq.Schema.Dbml.Type) ob.@Items[n30]), "ElementType", "http://schemas.microsoft.com/linqtosql/dbml/2007", false, false, true);
+                                       }
+                                       else throw CreateUnknownTypeException (ob.@Items[n30]);
+                               }
+                       }
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               void WriteObject_ConnectionMode (DbLinq.Schema.Dbml.ConnectionMode ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.ConnectionMode))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("ConnectionMode", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       Writer.WriteString (GetEnumValue_ConnectionMode (ob));
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               string GetEnumValue_ConnectionMode (DbLinq.Schema.Dbml.ConnectionMode val)
+               {
+                       switch (val) {
+                               case DbLinq.Schema.Dbml.ConnectionMode.ConnectionString: return "ConnectionString";
+                               case DbLinq.Schema.Dbml.ConnectionMode.AppSettings: return "AppSettings";
+                               case DbLinq.Schema.Dbml.ConnectionMode.WebSettings: return "WebSettings";
+                               default: throw CreateInvalidEnumValueException ((long) val, typeof (DbLinq.Schema.Dbml.ConnectionMode).FullName);
+                       }
+               }
+
+               void WriteObject_MemberModifier (DbLinq.Schema.Dbml.MemberModifier ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.MemberModifier))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("MemberModifier", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       Writer.WriteString (GetEnumValue_MemberModifier (ob));
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               string GetEnumValue_MemberModifier (DbLinq.Schema.Dbml.MemberModifier val)
+               {
+                       switch (val) {
+                               case DbLinq.Schema.Dbml.MemberModifier.Virtual: return "Virtual";
+                               case DbLinq.Schema.Dbml.MemberModifier.Override: return "Override";
+                               case DbLinq.Schema.Dbml.MemberModifier.New: return "New";
+                               case DbLinq.Schema.Dbml.MemberModifier.NewVirtual: return "NewVirtual";
+                               default: throw CreateInvalidEnumValueException ((long) val, typeof (DbLinq.Schema.Dbml.MemberModifier).FullName);
+                       }
+               }
+
+               void WriteObject_Type (DbLinq.Schema.Dbml.Type ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       if (((object)ob) == null)
+                       {
+                               if (isNullable)
+                                       WriteNullTagLiteral(element, namesp);
+                               return;
+                       }
+
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.Type))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("Type", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       WriteAttribute ("IdRef", "", ob.@IdRef);
+                       WriteAttribute ("Id", "", ob.@Id);
+                       WriteAttribute ("Name", "", ob.@Name);
+                       WriteAttribute ("InheritanceCode", "", ob.@InheritanceCode);
+                       if (ob.@IsInheritanceDefaultSpecified) {
+                               WriteAttribute ("IsInheritanceDefault", "", (ob.@IsInheritanceDefault?"true":"false"));
+                       }
+                       if (ob.@AccessModifierSpecified) {
+                               WriteAttribute ("AccessModifier", "", GetEnumValue_AccessModifier (ob.@AccessModifier));
+                       }
+                       if (ob.@ModifierSpecified) {
+                               WriteAttribute ("Modifier", "", GetEnumValue_ClassModifier (ob.@Modifier));
+                       }
+
+                       if (ob.@Items != null) {
+                               for (int n31 = 0; n31 < ob.@Items.Length; n31++) {
+                                       if (((object)ob.@Items[n31]) == null) { }
+                                       else if (ob.@Items[n31].GetType() == typeof(DbLinq.Schema.Dbml.Column)) {
+                                               WriteObject_Column (((DbLinq.Schema.Dbml.Column) ob.@Items[n31]), "Column", "http://schemas.microsoft.com/linqtosql/dbml/2007", false, false, true);
+                                       }
+                                       else if (ob.@Items[n31].GetType() == typeof(DbLinq.Schema.Dbml.Association)) {
+                                               WriteObject_Association (((DbLinq.Schema.Dbml.Association) ob.@Items[n31]), "Association", "http://schemas.microsoft.com/linqtosql/dbml/2007", false, false, true);
+                                       }
+                                       else throw CreateUnknownTypeException (ob.@Items[n31]);
+                               }
+                       }
+                       if (ob.@Type1 != null) {
+                               for (int n32 = 0; n32 < ob.@Type1.Length; n32++) {
+                                       WriteObject_Type (ob.@Type1[n32], "Type", "http://schemas.microsoft.com/linqtosql/dbml/2007", false, false, true);
+                               }
+                       }
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               void WriteObject_TableFunction (DbLinq.Schema.Dbml.TableFunction ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       if (((object)ob) == null)
+                       {
+                               if (isNullable)
+                                       WriteNullTagLiteral(element, namesp);
+                               return;
+                       }
+
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.TableFunction))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("TableFunction", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       WriteAttribute ("FunctionId", "", ob.@FunctionId);
+                       if (ob.@AccessModifierSpecified) {
+                               WriteAttribute ("AccessModifier", "", GetEnumValue_AccessModifier (ob.@AccessModifier));
+                       }
+
+                       if (ob.@Argument != null) {
+                               for (int n33 = 0; n33 < ob.@Argument.Length; n33++) {
+                                       WriteObject_TableFunctionParameter (ob.@Argument[n33], "Argument", "http://schemas.microsoft.com/linqtosql/dbml/2007", false, false, true);
+                               }
+                       }
+                       WriteObject_TableFunctionReturn (ob.@Return, "Return", "http://schemas.microsoft.com/linqtosql/dbml/2007", false, false, true);
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               void WriteObject_Parameter (DbLinq.Schema.Dbml.Parameter ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       if (((object)ob) == null)
+                       {
+                               if (isNullable)
+                                       WriteNullTagLiteral(element, namesp);
+                               return;
+                       }
+
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.Parameter))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("Parameter", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       WriteAttribute ("Name", "", ob.@Name);
+                       WriteAttribute ("Parameter", "", ob.@Parameter1);
+                       WriteAttribute ("Type", "", ob.@Type);
+                       WriteAttribute ("DbType", "", ob.@DbType);
+                       if (ob.@DirectionSpecified) {
+                               WriteAttribute ("Direction", "", GetEnumValue_ParameterDirection (ob.@Direction));
+                       }
+
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               void WriteObject_Return (DbLinq.Schema.Dbml.Return ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       if (((object)ob) == null)
+                       {
+                               if (isNullable)
+                                       WriteNullTagLiteral(element, namesp);
+                               return;
+                       }
+
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.Return))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("Return", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       WriteAttribute ("Type", "", ob.@Type);
+                       WriteAttribute ("DbType", "", ob.@DbType);
+
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               void WriteObject_Column (DbLinq.Schema.Dbml.Column ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       if (((object)ob) == null)
+                       {
+                               if (isNullable)
+                                       WriteNullTagLiteral(element, namesp);
+                               return;
+                       }
+
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.Column))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("Column", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       WriteAttribute ("Name", "", ob.@Name);
+                       WriteAttribute ("Member", "", ob.@Member);
+                       WriteAttribute ("Storage", "", ob.@Storage);
+                       if (ob.@AccessModifierSpecified) {
+                               WriteAttribute ("AccessModifier", "", GetEnumValue_AccessModifier (ob.@AccessModifier));
+                       }
+                       if (ob.@ModifierSpecified) {
+                               WriteAttribute ("Modifier", "", GetEnumValue_MemberModifier (ob.@Modifier));
+                       }
+                       WriteAttribute ("Type", "", ob.@Type);
+                       WriteAttribute ("DbType", "", ob.@DbType);
+                       if (ob.@IsReadOnlySpecified) {
+                               WriteAttribute ("IsReadOnly", "", (ob.@IsReadOnly?"true":"false"));
+                       }
+                       if (ob.@IsPrimaryKeySpecified) {
+                               WriteAttribute ("IsPrimaryKey", "", (ob.@IsPrimaryKey?"true":"false"));
+                       }
+                       if (ob.@IsDbGeneratedSpecified) {
+                               WriteAttribute ("IsDbGenerated", "", (ob.@IsDbGenerated?"true":"false"));
+                       }
+                       if (ob.@CanBeNullSpecified) {
+                               WriteAttribute ("CanBeNull", "", (ob.@CanBeNull?"true":"false"));
+                       }
+                       if (ob.@UpdateCheckSpecified) {
+                               WriteAttribute ("UpdateCheck", "", GetEnumValue_UpdateCheck (ob.@UpdateCheck));
+                       }
+                       if (ob.@IsDiscriminatorSpecified) {
+                               WriteAttribute ("IsDiscriminator", "", (ob.@IsDiscriminator?"true":"false"));
+                       }
+                       WriteAttribute ("Expression", "", ob.@Expression);
+                       if (ob.@IsVersionSpecified) {
+                               WriteAttribute ("IsVersion", "", (ob.@IsVersion?"true":"false"));
+                       }
+                       if (ob.@IsDelayLoadedSpecified) {
+                               WriteAttribute ("IsDelayLoaded", "", (ob.@IsDelayLoaded?"true":"false"));
+                       }
+                       if (ob.@AutoSyncSpecified) {
+                               WriteAttribute ("AutoSync", "", GetEnumValue_AutoSync (ob.@AutoSync));
+                       }
+
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               void WriteObject_Association (DbLinq.Schema.Dbml.Association ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       if (((object)ob) == null)
+                       {
+                               if (isNullable)
+                                       WriteNullTagLiteral(element, namesp);
+                               return;
+                       }
+
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.Association))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("Association", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       WriteAttribute ("Name", "", ob.@Name);
+                       WriteAttribute ("Member", "", ob.@Member);
+                       WriteAttribute ("Storage", "", ob.@Storage);
+                       if (ob.@AccessModifierSpecified) {
+                               WriteAttribute ("AccessModifier", "", GetEnumValue_AccessModifier (ob.@AccessModifier));
+                       }
+                       if (ob.@ModifierSpecified) {
+                               WriteAttribute ("Modifier", "", GetEnumValue_MemberModifier (ob.@Modifier));
+                       }
+                       WriteAttribute ("Type", "", ob.@Type);
+                       WriteAttribute ("ThisKey", "", ob.@ThisKey);
+                       WriteAttribute ("OtherKey", "", ob.@OtherKey);
+                       if (ob.@IsForeignKeySpecified) {
+                               WriteAttribute ("IsForeignKey", "", (ob.@IsForeignKey?"true":"false"));
+                       }
+                       if (ob.@CardinalitySpecified) {
+                               WriteAttribute ("Cardinality", "", GetEnumValue_Cardinality (ob.@Cardinality));
+                       }
+                       WriteAttribute ("DeleteRule", "", ob.@DeleteRule);
+                       if (ob.@DeleteOnNullSpecified) {
+                               WriteAttribute ("DeleteOnNull", "", (ob.@DeleteOnNull?"true":"false"));
+                       }
+
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               void WriteObject_TableFunctionParameter (DbLinq.Schema.Dbml.TableFunctionParameter ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       if (((object)ob) == null)
+                       {
+                               if (isNullable)
+                                       WriteNullTagLiteral(element, namesp);
+                               return;
+                       }
+
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.TableFunctionParameter))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("TableFunctionParameter", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       WriteAttribute ("Parameter", "", ob.@Parameter);
+                       WriteAttribute ("Member", "", ob.@Member);
+                       if (ob.@VersionSpecified) {
+                               WriteAttribute ("Version", "", GetEnumValue_Version (ob.@Version));
+                       }
+
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               void WriteObject_TableFunctionReturn (DbLinq.Schema.Dbml.TableFunctionReturn ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       if (((object)ob) == null)
+                       {
+                               if (isNullable)
+                                       WriteNullTagLiteral(element, namesp);
+                               return;
+                       }
+
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.TableFunctionReturn))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("TableFunctionReturn", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       WriteAttribute ("Member", "", ob.@Member);
+
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               void WriteObject_ParameterDirection (DbLinq.Schema.Dbml.ParameterDirection ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.ParameterDirection))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("ParameterDirection", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       Writer.WriteString (GetEnumValue_ParameterDirection (ob));
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               string GetEnumValue_ParameterDirection (DbLinq.Schema.Dbml.ParameterDirection val)
+               {
+                       switch (val) {
+                               case DbLinq.Schema.Dbml.ParameterDirection.In: return "In";
+                               case DbLinq.Schema.Dbml.ParameterDirection.Out: return "Out";
+                               case DbLinq.Schema.Dbml.ParameterDirection.InOut: return "InOut";
+                               default: throw CreateInvalidEnumValueException ((long) val, typeof (DbLinq.Schema.Dbml.ParameterDirection).FullName);
+                       }
+               }
+
+               void WriteObject_UpdateCheck (DbLinq.Schema.Dbml.UpdateCheck ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.UpdateCheck))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("UpdateCheck", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       Writer.WriteString (GetEnumValue_UpdateCheck (ob));
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               string GetEnumValue_UpdateCheck (DbLinq.Schema.Dbml.UpdateCheck val)
+               {
+                       switch (val) {
+                               case DbLinq.Schema.Dbml.UpdateCheck.Always: return "Always";
+                               case DbLinq.Schema.Dbml.UpdateCheck.Never: return "Never";
+                               case DbLinq.Schema.Dbml.UpdateCheck.WhenChanged: return "WhenChanged";
+                               default: throw CreateInvalidEnumValueException ((long) val, typeof (DbLinq.Schema.Dbml.UpdateCheck).FullName);
+                       }
+               }
+
+               void WriteObject_AutoSync (DbLinq.Schema.Dbml.AutoSync ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.AutoSync))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("AutoSync", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       Writer.WriteString (GetEnumValue_AutoSync (ob));
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               string GetEnumValue_AutoSync (DbLinq.Schema.Dbml.AutoSync val)
+               {
+                       switch (val) {
+                               case DbLinq.Schema.Dbml.AutoSync.Never: return "Never";
+                               case DbLinq.Schema.Dbml.AutoSync.OnInsert: return "OnInsert";
+                               case DbLinq.Schema.Dbml.AutoSync.OnUpdate: return "OnUpdate";
+                               case DbLinq.Schema.Dbml.AutoSync.Always: return "Always";
+                               case DbLinq.Schema.Dbml.AutoSync.Default: return "Default";
+                               default: throw CreateInvalidEnumValueException ((long) val, typeof (DbLinq.Schema.Dbml.AutoSync).FullName);
+                       }
+               }
+
+               void WriteObject_Cardinality (DbLinq.Schema.Dbml.Cardinality ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.Cardinality))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("Cardinality", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       Writer.WriteString (GetEnumValue_Cardinality (ob));
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               string GetEnumValue_Cardinality (DbLinq.Schema.Dbml.Cardinality val)
+               {
+                       switch (val) {
+                               case DbLinq.Schema.Dbml.Cardinality.One: return "One";
+                               case DbLinq.Schema.Dbml.Cardinality.Many: return "Many";
+                               default: throw CreateInvalidEnumValueException ((long) val, typeof (DbLinq.Schema.Dbml.Cardinality).FullName);
+                       }
+               }
+
+               void WriteObject_Version (DbLinq.Schema.Dbml.Version ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
+               {
+                       System.Type type = ob.GetType ();
+                       if (type == typeof(DbLinq.Schema.Dbml.Version))
+                       { }
+                       else {
+                               throw CreateUnknownTypeException (ob);
+                       }
+
+                       if (writeWrappingElem) {
+                               WriteStartElement (element, namesp, ob);
+                       }
+
+                       if (needType) WriteXsiType("Version", "http://schemas.microsoft.com/linqtosql/dbml/2007");
+
+                       Writer.WriteString (GetEnumValue_Version (ob));
+                       if (writeWrappingElem) WriteEndElement (ob);
+               }
+
+               string GetEnumValue_Version (DbLinq.Schema.Dbml.Version val)
+               {
+                       switch (val) {
+                               case DbLinq.Schema.Dbml.Version.Current: return "Current";
+                               case DbLinq.Schema.Dbml.Version.Original: return "Original";
+                               default: throw CreateInvalidEnumValueException ((long) val, typeof (DbLinq.Schema.Dbml.Version).FullName);
+                       }
+               }
+
+               protected override void InitCallbacks ()
+               {
+               }
+
+       }
+
+
+       #if !MONO_STRICT
+    public
+      #endif
+       class BaseXmlSerializer : System.Xml.Serialization.XmlSerializer
+       {
+               protected override System.Xml.Serialization.XmlSerializationReader CreateReader () {
+                       return new GeneratedReader ();
+               }
+
+               protected override System.Xml.Serialization.XmlSerializationWriter CreateWriter () {
+                       return new GeneratedWriter ();
+               }
+
+               public override bool CanDeserialize (System.Xml.XmlReader xmlReader) {
+                       return true;
+               }
+       }
+
+    #if !MONO_STRICT
+    public
+    #endif
+       sealed class DatabaseSerializer : BaseXmlSerializer
+       {
+               protected override void Serialize (object obj, System.Xml.Serialization.XmlSerializationWriter writer) {
+                       ((GeneratedWriter)writer).WriteRoot_Database(obj);
+               }
+
+               protected override object Deserialize (System.Xml.Serialization.XmlSerializationReader reader) {
+                       return ((GeneratedReader)reader).ReadRoot_Database();
+               }
+       }
+
+       #if !TARGET_JVM
+       #if !MONO_STRICT
+    public
+    #endif
+       class XmlSerializerContract : System.Xml.Serialization.XmlSerializerImplementation
+       {
+               System.Collections.Hashtable readMethods = null;
+               System.Collections.Hashtable writeMethods = null;
+               System.Collections.Hashtable typedSerializers = null;
+
+               public override System.Xml.Serialization.XmlSerializationReader Reader {
+                       get {
+                               return new GeneratedReader();
+                       }
+               }
+
+               public override System.Xml.Serialization.XmlSerializationWriter Writer {
+                       get {
+                               return new GeneratedWriter();
+                       }
+               }
+
+               public override System.Collections.Hashtable ReadMethods {
+                       get {
+                               lock (this) {
+                                       if (readMethods == null) {
+                                               readMethods = new System.Collections.Hashtable ();
+                                               readMethods.Add (@"DbLinq.Schema.Dbml.Database", @"ReadRoot_Database");
+                                       }
+                                       return readMethods;
+                               }
+                       }
+               }
+
+               public override System.Collections.Hashtable WriteMethods {
+                       get {
+                               lock (this) {
+                                       if (writeMethods == null) {
+                                               writeMethods = new System.Collections.Hashtable ();
+                                               writeMethods.Add (@"DbLinq.Schema.Dbml.Database", @"WriteRoot_Database");
+                                       }
+                                       return writeMethods;
+                               }
+                       }
+               }
+
+               public override System.Collections.Hashtable TypedSerializers {
+                       get {
+                               lock (this) {
+                                       if (typedSerializers == null) {
+                                               typedSerializers = new System.Collections.Hashtable ();
+                                               typedSerializers.Add (@"DbLinq.Schema.Dbml.Database", new DatabaseSerializer());
+                                       }
+                                       return typedSerializers;
+                               }
+                       }
+               }
+
+               public XmlSerializer GetSerializer (System.Type type)
+               {
+                       switch (type.FullName) {
+                       case "DbLinq.Schema.Dbml.Database":
+                               return (XmlSerializer) TypedSerializers ["DbLinq.Schema.Dbml.Database"];
+
+                       }
+                       return base.GetSerializer (type);
+               }
+
+               public override bool CanSerialize (System.Type type) {
+                       if (type == typeof(DbLinq.Schema.Dbml.Database)) return true;
+                       return false;
+               }
+       }
+
+       #endif
+}
+
index 790f254a47d4da24fe26552e0545833972390ea7..1a7bb7259adc4dab3cdefeb6a132928f0557ca29 100644 (file)
@@ -99,7 +99,7 @@ namespace DbLinq.Schema.Dbml
             using (Stream xsdStream = OpenXsd())\r
             using (XmlReader xmlReader = OpenXml(xmlStream, xsdStream, validationErrors))\r
             {\r
-                var xmlSerializer = new XmlSerializer(typeof(Database));\r
+                var xmlSerializer = new DatabaseSerializer();\r
                 var dbml = (Database)xmlSerializer.Deserialize(xmlReader);\r
                 return dbml;\r
             }\r
@@ -125,8 +125,8 @@ namespace DbLinq.Schema.Dbml
         /// <param name="dbml">The DBML.</param>\r
         public static void Write(Stream xmlStream, Database dbml)\r
         {\r
-            var xmlSerializer = new XmlSerializer(dbml.GetType());\r
+            var xmlSerializer = new DatabaseSerializer();\r
             xmlSerializer.Serialize(xmlStream, dbml);\r
         }\r
     }\r
-}
\ No newline at end of file
+}\r
index df24530535a229c99e5aff61ce342f630648ed15..d4d63b2c128988843f03c3d302526d2be680dbaf 100644 (file)
     <Compile Include="Data\Linq\ChangeAction.cs" />\r
     <Compile Include="Data\Linq\ChangeSet.cs" />\r
     <Compile Include="Data\Linq\Database\IDatabaseContext.cs" />\r
-    <Compile Include="Data\Linq\Database\IDatabaseTransaction.cs" />\r
     <Compile Include="Data\Linq\Database\Implementation\DatabaseConnection.cs" />\r
     <Compile Include="Data\Linq\Database\Implementation\DatabaseContext.cs" />\r
-    <Compile Include="Data\Linq\Database\Implementation\DatabaseTransaction.cs" />\r
     <Compile Include="Data\Linq\Database\Implementation\TransactionalCommand.cs" />\r
     <Compile Include="Data\Linq\Database\ITransactionalCommand.cs" />\r
     <Compile Include="Data\Linq\DataContext.cs" />\r
     <Compile Include="Schema\Dbml\Adapter\INamedType.cs" />\r
     <Compile Include="Schema\Dbml\Adapter\ISimpleList.cs" />\r
     <Compile Include="Schema\Dbml\Adapter\SpecifiedPropertyUpdater.cs" />\r
+    <Compile Include="Schema\Dbml\DatabaseSerializer.cs" />\r
     <Compile Include="Schema\WordsExtraction.cs" />\r
     <Compile Include="Schema\NameFormat.cs" />\r
     <Compile Include="Schema\AssociationName.cs" />\r
index 7fb0dbc226951d482d16bdf72a262c3f9504fc47..04a391d4dfc3bc7e2437bdf97d637ec3824e18d5 100644 (file)
@@ -80,3 +80,10 @@ using DbLinq.Factory;
 "962a12b830c2a70eb70ec77823eb5750e5bdef9e01d097c30b5c5463c3d07d3472b58e4c02f279" +\r
 "2309259f")]\r
 \r
+[assembly: InternalsVisibleTo("sqlmetal_test_net_4_0, PublicKey=" +\r
+"0024000004800000940000000602000000240000525341310004000001000100c5753d8c47f400" +\r
+"83f549016a5711238ac8ec297605abccd3dc4b6d0f280b4764eb2cc58ec4e37831edad7e7a07b8" +\r
+"fe4a9cbb059374c0cc047aa28839fed7176761813caf6a2ffa0bff9afb50ead56dd3f56186a663" +\r
+"962a12b830c2a70eb70ec77823eb5750e5bdef9e01d097c30b5c5463c3d07d3472b58e4c02f279" +\r
+"2309259f")]\r
+\r
index 0516d0a4a9bef6ef72d93972a5c942f233543642..cc4a0066f7989aa8f24f46f12506fc53ad3cf36d 100644 (file)
@@ -34,6 +34,11 @@ namespace System.Data.Linq.Mapping
        [AttributeUsage (AttributeTargets.Property|AttributeTargets.Field, AllowMultiple = false)]\r
        public sealed class ColumnAttribute : DataAttribute\r
        {\r
+        public ColumnAttribute()\r
+        {\r
+            CanBeNull = true;\r
+        }\r
+\r
                public AutoSync AutoSync { get; set; }\r
                public bool CanBeNull { get; set; }\r
                public string DbType { get; set; }\r
index 0dcd4ed70b52fd58216d7cd8d918f54d879cfa93..449c50904f59c54add3c3215bc6a4bf4f3ecb24d 100644 (file)
@@ -21,15 +21,3 @@ using System.Runtime.InteropServices;
 \r
 // The following GUID is for the ID of the typelib if this project is exposed to COM\r
 [assembly: Guid("52112670-1196-4229-ae51-535cf23869cb")]\r
-\r
-// Version information for an assembly consists of the following four values:\r
-//\r
-//      Major Version\r
-//      Minor Version \r
-//      Build Number\r
-//      Revision\r
-//\r
-// You can specify all the values or you can default the Revision and Build Numbers \r
-// by using the '*' as shown below:\r
-[assembly: AssemblyVersion("1.0.0.0")]\r
-[assembly: AssemblyFileVersion("1.0.0.0")]\r
index 92a13c68a13b0da8565ebadd64ad0aa5ace969da..a54fd61fc0da37d21e85f98e04cb3e00de474e90 100755 (executable)
@@ -3,7 +3,7 @@
   <PropertyGroup>\r
     <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
     <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
-    <ProductVersion>9.0.30729</ProductVersion>\r
+    <ProductVersion>9.0.21022</ProductVersion>\r
     <SchemaVersion>2.0</SchemaVersion>\r
     <ProjectGuid>{AB60629C-6B19-4465-89AA-DBD7A0428F4B}</ProjectGuid>\r
     <OutputType>Library</OutputType>\r
@@ -77,6 +77,7 @@
     <Compile Include="NullProvider.cs">\r
     </Compile>\r
     <Compile Include="PeopleTable.cs" />\r
+    <Compile Include="System.Data.Linq.Mapping\ColumnAttributeTest.cs" />\r
     <Compile Include="TableTest.cs" />\r
   </ItemGroup>\r
   <ItemGroup>\r
index 0dcd4ed70b52fd58216d7cd8d918f54d879cfa93..449c50904f59c54add3c3215bc6a4bf4f3ecb24d 100644 (file)
@@ -21,15 +21,3 @@ using System.Runtime.InteropServices;
 \r
 // The following GUID is for the ID of the typelib if this project is exposed to COM\r
 [assembly: Guid("52112670-1196-4229-ae51-535cf23869cb")]\r
-\r
-// Version information for an assembly consists of the following four values:\r
-//\r
-//      Major Version\r
-//      Minor Version \r
-//      Build Number\r
-//      Revision\r
-//\r
-// You can specify all the values or you can default the Revision and Build Numbers \r
-// by using the '*' as shown below:\r
-[assembly: AssemblyVersion("1.0.0.0")]\r
-[assembly: AssemblyFileVersion("1.0.0.0")]\r
index da8098f779754a7ca620f2e704e9661881cf27b5..c552d999b11a311155b093cb5dde20a2e5dec68a 100644 (file)
@@ -21,15 +21,3 @@ using System.Runtime.InteropServices;
 \r
 // The following GUID is for the ID of the typelib if this project is exposed to COM\r
 [assembly: Guid("0cae4ddc-abd5-4c2a-96c0-918ed1d736e4")]\r
-\r
-// Version information for an assembly consists of the following four values:\r
-//\r
-//      Major Version\r
-//      Minor Version \r
-//      Build Number\r
-//      Revision\r
-//\r
-// You can specify all the values or you can default the Revision and Build Numbers \r
-// by using the '*' as shown below:\r
-[assembly: AssemblyVersion("0.0.1.17")]\r
-[assembly: AssemblyFileVersion("0.19")]\r
index e452032ce0d02c7451a64ec9b654018aeccb7df7..1f443c32ac66030d295c8a83b74bbbef11f0b92b 100644 (file)
@@ -193,11 +193,12 @@ namespace nwind
             Assert.IsTrue(p1.ProductID == 1);\r
         }\r
 \r
+        [Test]\r
         public void A8_SelectSingleOrDefault_QueryCacheDisabled()\r
         {\r
             Northwind db = CreateDB();\r
 #if !MONO_STRICT\r
-            db.QueryCacheEnabled = false;\r
+            db.QueryCacheEnabled = true;\r
 #endif\r
 \r
             // Query for a specific customer\r
diff --git a/mcs/class/System.Data.Linq/src/DbLinq/Test/System.Data.Linq.Mapping/ColumnAttributeTest.cs b/mcs/class/System.Data.Linq/src/DbLinq/Test/System.Data.Linq.Mapping/ColumnAttributeTest.cs
new file mode 100755 (executable)
index 0000000..5ff8967
--- /dev/null
@@ -0,0 +1,64 @@
+#region MIT license\r
+// \r
+// MIT license\r
+//\r
+// Copyright (c) 2010 Novell, Inc.\r
+// \r
+// Permission is hereby granted, free of charge, to any person obtaining a copy\r
+// of this software and associated documentation files (the "Software"), to deal\r
+// in the Software without restriction, including without limitation the rights\r
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r
+// copies of the Software, and to permit persons to whom the Software is\r
+// furnished to do so, subject to the following conditions:\r
+// \r
+// The above copyright notice and this permission notice shall be included in\r
+// all copies or substantial portions of the Software.\r
+// \r
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r
+// THE SOFTWARE.\r
+// \r
+#endregion\r
+\r
+using System;\r
+using System.Collections;\r
+using System.Collections.Generic;\r
+using System.Collections.ObjectModel;\r
+using System.Data.SqlClient;\r
+using System.IO;\r
+using System.Linq;\r
+using System.Reflection;\r
+\r
+using System.Data.Linq.Mapping;\r
+\r
+using DbLinq.Null;\r
+using NUnit.Framework;\r
+\r
+namespace System.Data.Linq.Mapping.Test\r
+{\r
+    [TestFixture]\r
+    public class ColumnAttributeTest\r
+    {\r
+        [Test]\r
+        public void Ctor()\r
+        {\r
+            var c = new ColumnAttribute();\r
+            Assert.AreEqual(AutoSync.Default,   c.AutoSync);\r
+            Assert.AreEqual(true,               c.CanBeNull);\r
+            Assert.AreEqual(null,               c.DbType);\r
+            Assert.AreEqual(null,               c.Expression);\r
+            Assert.AreEqual(false,              c.IsDbGenerated);\r
+            Assert.AreEqual(false,              c.IsDiscriminator);\r
+            Assert.AreEqual(false,              c.IsVersion);\r
+            Assert.AreEqual(UpdateCheck.Always, c.UpdateCheck);\r
+            Assert.AreEqual(false,              c.IsPrimaryKey);\r
+            Assert.AreEqual(null,               c.Name);\r
+            Assert.AreEqual(null,               c.Storage);\r
+            Assert.AreEqual(c.GetType(),        c.TypeId);\r
+        }\r
+    }\r
+}\r
index df6f25a523997e3d4137f9ef0c30a8536770282c..c6b93b01436ae82f7359a9a3c4d8c5d035a4b803 100644 (file)
@@ -62,12 +62,5 @@ namespace DbLinq.Vendor
         /// <returns></returns>\r
         Database Load(string databaseName, INameAliases nameAliases, NameFormat nameFormat,\r
             bool loadStoredProcedures, string contextNamespace, string entityNamespace);\r
-\r
-        /// <summary>\r
-        /// Checks all names in DBML schema, \r
-        /// and enquotes the ones where a casing problem could occur\r
-        /// </summary>\r
-        /// <param name="schema"></param>\r
-        void CheckNamesSafety(Database schema);\r
     }\r
 }\r
index 696ee8779e757804545f0023e3c2536b9e743795..56ab5bb1d5b4a0d59360b93514f19cb678162c78 100644 (file)
@@ -92,7 +92,8 @@ namespace DbLinq.Vendor.Implementation
             assoc.ThisKey = foreignKey;\r
             assoc.OtherKey = reverseForeignKey;\r
             assoc.Member = associationName.ManyToOneMemberName;\r
-            assoc.Cardinality = Cardinality.Many; // TODO: check this is the right direction (even if it appears to be useless)\r
+            assoc.CardinalitySpecified = false;\r
+            // TODO: generate assoc.Cardinality?\r
             table.Type.Associations.Add(assoc);\r
 \r
             //and insert the reverse association:\r
@@ -100,7 +101,8 @@ namespace DbLinq.Vendor.Implementation
             reverseAssociation.Name = constraintName;\r
             reverseAssociation.Type = table.Type.Name;\r
             reverseAssociation.Member = associationName.OneToManyMemberName;\r
-            reverseAssociation.Cardinality = Cardinality.One;\r
+            reverseAssociation.CardinalitySpecified = false;\r
+            // TODO: generate reverseAssociation.Cardinality?\r
             reverseAssociation.ThisKey = reverseForeignKey;\r
             reverseAssociation.OtherKey = foreignKey;\r
             reverseAssociation.DeleteRule = "NO ACTION";\r
index fdcfa54b55a9bfff792186b96d1b0ee4d477c557..6fed0b84e3b2db10b77196929838bae719dc6ea4 100644 (file)
@@ -34,32 +34,6 @@ namespace DbLinq.Vendor.Implementation
 {\r
     partial class SchemaLoader\r
     {\r
-        /// <summary>\r
-        /// Checks all names in DBML schema, \r
-        /// and enquotes the ones where a casing problem could occur\r
-        /// </summary>\r
-        /// <param name="schema"></param>\r
-        public virtual void CheckNamesSafety(Database schema)\r
-        {\r
-            schema.Name = Vendor.SqlProvider.GetSafeName(schema.Name);\r
-            foreach (var table in schema.Table)\r
-            {\r
-                table.Name = Vendor.SqlProvider.GetSafeName(table.Name);\r
-                foreach (var column in table.Type.Columns)\r
-                {\r
-                    column.Name = Vendor.SqlProvider.GetSafeName(column.Name);\r
-                }\r
-                foreach (var association in table.Type.Associations)\r
-                {\r
-                    association.Name = Vendor.SqlProvider.GetSafeName(association.Name);\r
-                }\r
-            }\r
-            foreach (var storedProcedure in schema.Functions)\r
-            {\r
-                storedProcedure.Name = Vendor.SqlProvider.GetSafeName(storedProcedure.Name);\r
-            }\r
-        }\r
-\r
         /// <summary>\r
         /// Gets the primary keys.\r
         /// </summary>\r
@@ -149,22 +123,36 @@ namespace DbLinq.Vendor.Implementation
                     column.Storage = storageGenerator(column.Member);\r
                 }\r
 \r
-                Dictionary<string, int> storageFields = new Dictionary<string,int>();\r
-                Dictionary<string, int> memberFields = new Dictionary<string,int>();\r
+                HashSet<string> storageFields = new HashSet<string>();\r
+                HashSet<string> memberFields = new HashSet<string>();\r
+                foreach (var column in table.Type.Columns)\r
+                {\r
+                    storageFields.Add(column.Storage);\r
+                    memberFields.Add(column.Member);\r
+                }\r
+\r
                 foreach (var association in table.Type.Associations)\r
                 {\r
                     association.Storage = storageGenerator(association.Member);\r
 \r
                     //Associations may contain the same foreign key more than once - add a number suffix to duplicates\r
-                    int storageSuffix = 0;\r
-                    if ( storageFields.TryGetValue(association.Storage, out storageSuffix) )\r
-                        association.Storage += storageSuffix;\r
-                    storageFields[association.Storage] = storageSuffix + 1;\r
+                    for (var suffix = 0; ; suffix++)\r
+                    {\r
+                        var name = suffix == 0 ? association.Storage : association.Storage + suffix;\r
+                        if (storageFields.Contains(name)) continue;\r
+                        association.Storage = name;\r
+                        storageFields.Add(name);\r
+                        break;\r
+                    }\r
 \r
-                    int memberSuffix = 0;\r
-                    if ( memberFields.TryGetValue(association.Member, out memberSuffix) )\r
-                        association.Member += memberSuffix;\r
-                    memberFields[association.Member] = memberSuffix + 1;\r
+                    for (var suffix = 0; ; suffix++)\r
+                    {\r
+                        var name = suffix == 0 ? association.Member : association.Member + suffix;\r
+                        if (memberFields.Contains(name)) continue;\r
+                        association.Member = name;\r
+                        memberFields.Add(name);\r
+                        break;\r
+                    }\r
                 }\r
             }\r
         }\r
index 2f179d3124a058d5fcb0119b3172763338205ddd..ba670473e128f31985402b168684c75abae66e30 100644 (file)
@@ -147,12 +147,16 @@ namespace DbLinq.Vendor.Implementation
             case "float4":\r
             case "real":\r
             case "binary_float":   // oracle type\r
+            case "unsigned float": // mysql type\r
+            case "float unsigned": // mysql type\r
                 return typeof(Single);\r
 \r
             // double\r
             case "double":\r
             case "double precision":\r
             case "binary_double":  // oracle type\r
+            case "unsigned double":// mysql type\r
+            case "double unsigned":// mysql type\r
                 return typeof(Double);\r
 \r
             // decimal\r
@@ -180,6 +184,7 @@ namespace DbLinq.Vendor.Implementation
 \r
             //enum\r
             case "enum":\r
+            case "set":\r
                 return MapEnumDbType(dataType);\r
 \r
             // date\r
@@ -188,6 +193,7 @@ namespace DbLinq.Vendor.Implementation
             case "ingresdate":\r
             case "timestamp":\r
             case "timestamp without time zone":\r
+            case "timestamp with time zone":\r
             case "time":\r
             case "time without time zone": //reported by twain_bu...@msn.com,\r
             case "time with time zone":\r
@@ -430,7 +436,7 @@ namespace DbLinq.Vendor.Implementation
             #endregion\r
         }\r
 \r
-        protected static Regex DefaultEnumDefinitionEx = new Regex(@"\s*enum\s*\((?<values>.*)\s*\)\s*", RegexOptions.Compiled);\r
+        protected static Regex DefaultEnumDefinitionEx = new Regex(@"\s*(enum|set)\s*\((?<values>.*)\s*\)\s*", RegexOptions.Compiled);\r
         protected static Regex EnumValuesEx = new Regex(@"\'(?<value>\w*)\'\s*,?\s*", RegexOptions.Compiled);\r
 \r
         /// <summary>\r
index 528fc0a1796ba9612ce27075acfc9d3322cead38..ef05fc55baa17f3bd07991298be8f18743091364 100644 (file)
@@ -38,6 +38,7 @@ using DbLinq.Data.Linq;
 using DbLinq.Factory;\r
 using DbLinq.Schema;\r
 using DbLinq.Schema.Dbml;\r
+using System.Text.RegularExpressions;\r
 \r
 namespace DbLinq.Vendor.Implementation\r
 {\r
@@ -237,6 +238,8 @@ namespace DbLinq.Vendor.Implementation
             return CreateTableName(dbTableName, dbSchema, nameAliases, nameFormat, GetExtraction(dbTableName));\r
         }\r
 \r
+        Regex startsWithNumber = new Regex(@"^\d", RegexOptions.Compiled);\r
+\r
         /// <summary>\r
         /// Creates the name of the column.\r
         /// </summary>\r
@@ -265,6 +268,10 @@ namespace DbLinq.Vendor.Implementation
             var tableName = CreateTableName(dbTableName, dbSchema, nameAliases, nameFormat);\r
             if (columnName.PropertyName == tableName.ClassName)\r
                 columnName.PropertyName = columnName.PropertyName + "1";\r
+\r
+            if (startsWithNumber.IsMatch(columnName.PropertyName))\r
+                columnName.PropertyName = "_" + columnName.PropertyName;\r
+\r
             columnName.DbName = dbColumnName;\r
             return columnName;\r
         }\r
index a2d0d0c97fc56f2b5aeb310b218c8036088a8ac4..2ede68f23693d72252d3ac5395103e4fde5eb698 100644 (file)
@@ -1587,11 +1587,7 @@ namespace DbLinq.Vendor.Implementation
         /// <returns></returns>\r
         protected virtual string GetSafeNamePart(string namePart)\r
         {\r
-            if (IsMadeSafe(namePart))\r
-                return namePart;\r
-            if (IsNameSafe(namePart) && IsNameCaseSafe(namePart))\r
-                return namePart;\r
-            return MakeNameSafe(namePart);\r
+            return IsMadeSafe(namePart) ? namePart : MakeNameSafe(namePart);\r
         }\r
 \r
         /// <summary>\r
@@ -1609,23 +1605,6 @@ namespace DbLinq.Vendor.Implementation
             return namePart[0] == SafeNameStartQuote && namePart[l - 1] == SafeNameEndQuote;\r
         }\r
 \r
-        /// <summary>\r
-        /// Determines whether [is name case safe] [the specified name part].\r
-        /// </summary>\r
-        /// <param name="namePart">The name part.</param>\r
-        /// <returns>\r
-        ///     <c>true</c> if [is name case safe] [the specified name part]; otherwise, <c>false</c>.\r
-        /// </returns>\r
-        protected virtual bool IsNameCaseSafe(string namePart)\r
-        {\r
-            foreach (char c in namePart)\r
-            {\r
-                if (char.IsLower(c))\r
-                    return false;\r
-            }\r
-            return true;\r
-        }\r
-\r
         /// <summary>\r
         /// Gets the safe name start quote.\r
         /// </summary>\r
@@ -1647,53 +1626,6 @@ namespace DbLinq.Vendor.Implementation
             return namePart.Enquote(SafeNameStartQuote, SafeNameEndQuote);\r
         }\r
 \r
-        /// <summary>\r
-        /// Determines if a given field is dangerous (related to a SQL keyword or containing problematic characters)\r
-        /// </summary>\r
-        protected virtual bool IsNameSafe(string name)\r
-        {\r
-            var nameL = name.ToLower();\r
-            switch (nameL)\r
-            {\r
-            case "user":\r
-            case "default":\r
-            case "bit":\r
-            case "int":\r
-            case "smallint":\r
-            case "tinyint":\r
-            case "mediumint":\r
-\r
-            case "float":\r
-            case "double":\r
-            case "real":\r
-            case "decimal":\r
-            case "numeric":\r
-\r
-            case "blob":\r
-            case "text":\r
-            case "char":\r
-            case "varchar":\r
-\r
-            case "date":\r
-            case "time":\r
-            case "datetime":\r
-            case "timestamp":\r
-            case "year":\r
-\r
-            case "select":\r
-            case "from":\r
-            case "where":\r
-            case "order":\r
-            case "by":\r
-            case "key":\r
-                       case "index":\r
-\r
-                return false;\r
-            default:\r
-                return !name.Contains(' ');\r
-            }\r
-        }\r
-\r
         private static readonly Regex _fieldIdentifierEx = new Regex(@"\[(?<var>[\w.]+)\]",\r
                                                                      RegexOptions.Singleline |\r
                                                                      RegexOptions.ExplicitCapture |\r
index 6a28f53b0726c036450b692cd41bbaa5e51af8c2..c9b68f575ddeeaab600528c1e25522329caf7347 100644 (file)
@@ -39,6 +39,7 @@ using DbLinq.Data.Linq;
 using Data = DbLinq.Data;\r
 \r
 using IExecuteResult = System.Data.Linq.IExecuteResult;\r
+using System.Text;\r
 \r
 namespace DbLinq.Vendor.Implementation\r
 {\r
@@ -134,10 +135,43 @@ namespace DbLinq.Vendor.Implementation
         /// <param name="parts">The parts.</param>\r
         /// <param name="name">The name.</param>\r
         /// <param name="value">The value.</param>\r
-        protected virtual void AddConnectionStringPart(IList<string> parts, string name, string value)\r
+        protected void AppendConnectionString(StringBuilder connectionString, string name, string value)\r
         {\r
             if (!string.IsNullOrEmpty(value) && !string.IsNullOrEmpty(name))\r
-                parts.Add(string.Format("{0}={1}", name, value));\r
+                connectionString.AppendFormat("{0}={1};", name, value);\r
+        }\r
+\r
+        protected virtual void AppendDatabase(StringBuilder connectionString, string databaseName)\r
+        {\r
+            AppendConnectionString(connectionString, ConnectionStringDatabase, databaseName);\r
+        }\r
+\r
+        protected virtual void AppendPassword(StringBuilder connectionString, string password)\r
+        {\r
+            AppendConnectionString(connectionString, ConnectionStringPassword, password);\r
+        }\r
+\r
+        protected virtual void AppendServer(StringBuilder connectionString, string host)\r
+        {\r
+            // A majority of databases want a server/host port number as a separate key:\r
+            //      http://www.connectionstrings.com/postgre-sql\r
+            //      http://www.connectionstrings.com/firebird\r
+            //      http://www.connectionstrings.com/mysql\r
+            // So make this the default.\r
+            if (host == null)\r
+                return;\r
+            var colonIdx = host.IndexOf(':');\r
+            string port = colonIdx < 0 || host.Length == (colonIdx + 1) ? null : host.Substring(colonIdx + 1);\r
+            if (colonIdx >= 0)\r
+                host = host.Substring(0, colonIdx);\r
+            AppendConnectionString(connectionString, ConnectionStringServer, host);\r
+            if (port != null)\r
+                AppendConnectionString(connectionString, "Port", port);\r
+        }\r
+\r
+        protected virtual void AppendUser(StringBuilder connectionString, string userName)\r
+        {\r
+            AppendConnectionString(connectionString, ConnectionStringUser, userName);\r
         }\r
 \r
         /// <summary>\r
@@ -150,12 +184,12 @@ namespace DbLinq.Vendor.Implementation
         /// <returns></returns>\r
         public virtual string BuildConnectionString(string host, string databaseName, string userName, string password)\r
         {\r
-            var connectionStringParts = new List<string>();\r
-            AddConnectionStringPart(connectionStringParts, ConnectionStringServer, host);\r
-            AddConnectionStringPart(connectionStringParts, ConnectionStringDatabase, databaseName);\r
-            AddConnectionStringPart(connectionStringParts, ConnectionStringUser, userName);\r
-            AddConnectionStringPart(connectionStringParts, ConnectionStringPassword, password);\r
-            return string.Join(";", connectionStringParts.ToArray());\r
+            var connectionString = new StringBuilder();\r
+            AppendServer(connectionString, host);\r
+            AppendDatabase(connectionString, databaseName);\r
+            AppendUser(connectionString, userName);\r
+            AppendPassword(connectionString, password);\r
+            return connectionString.ToString();\r
         }\r
 \r
         /// <summary>\r
index 4d607bb799f72ce5c7549e68f94f3c8ab9c89cd9..e92412528c5c69c1d1713423a7fb6605164bccae 100644 (file)
@@ -18,7 +18,7 @@
       <provider name="OracleODP" dbLinqSchemaLoader="DbLinq.Oracle.OracleSchemaLoader, DbLinq.Oracle" databaseConnection="Oracle.DataAccess.Client.OracleConnection, Oracle.DataAccess" />\r
       <provider name="PostgreSQL" dbLinqSchemaLoader="DbLinq.PostgreSql.PgsqlSchemaLoader, DbLinq.PostgreSql" databaseConnection="Npgsql.NpgsqlConnection, Npgsql" />\r
       <provider name="SQLite" dbLinqSchemaLoader="DbLinq.Sqlite.SqliteSchemaLoader, DbLinq.Sqlite" databaseConnection="System.Data.SQLite.SQLiteConnection, System.Data.SQLite" />\r
-      <provider name="SqlServer" dbLinqSchemaLoader="DbLinq.SqlServer.SqlServerSchemaLoader, DbLinq.SqlServer" databaseConnection="System.Data.SqlClient.SqlConnection, System.Data" />\r
+      <provider name="SqlServer" dbLinqSchemaLoader="DbLinq.SqlServer.SqlServerSchemaLoader, DbLinq.SqlServer" databaseConnection="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />\r
       <provider name="Ingres" dbLinqSchemaLoader="DbLinq.Ingres.IngresSchemaLoader, DbLinq.Ingres" databaseConnection="Ingres.Client.IngresConnection, Ingres.Client" />\r
       <provider name="Firebird" dbLinqSchemaLoader="DbLinq.Firebird.FirebirdSchemaLoader, DbLinq.Firebird" databaseConnection="FirebirdSql.Data.FirebirdClient.FbConnection, FirebirdSql.Data.FirebirdClient" />\r
     </providers>\r
index 94dafb94a3c6a29c37456d085a20adffec0df452..73d26d6459c4ba6e3fca07e13c866dc512c883e4 100644 (file)
 // \r
 #endregion\r
 using System;\r
+using System.IO;\r
 using System.Linq;\r
 using System.Collections.Generic;\r
 using System.Configuration;\r
+using System.Text;\r
 \r
 namespace DbMetal.Configuration\r
 {\r
@@ -91,15 +93,31 @@ namespace DbMetal.Configuration
                     string[] allKeyStrings = allKeys.OfType<string>().ToArray();\r
                     \r
                     element = null;\r
-                    error = allKeys.Length == 0 \r
-                        ? "There are no <provider> entries in your app.config"\r
-                        : "Key " + name + " not found among " + allKeys.Length + " config entries {" + string.Join(",",allKeyStrings) + "}";\r
+                    string configFile = Path.GetFileName(typeof(Program).Assembly.Location)+ ".config";\r
+                    error = allKeys.Length == 0\r
+                        ? string.Format("There are no <provider/> entries in your {0} file.", configFile)\r
+                        : GetProvidersDescription(name, allKeyStrings.Length, configFile);\r
                     return false;\r
                 }\r
                 element = (ProviderElement)BaseGet(name.ToLower());\r
                 error = null;\r
                 return true;\r
             }\r
+\r
+            private string GetProvidersDescription(string name, int numKeys, string configFile)\r
+            {\r
+                var message = new StringBuilder();\r
+                message.AppendFormat("Provider '{0}' not found among the {1} config entries in your {2} file.  ",\r
+                    name, numKeys, configFile);\r
+                message.AppendLine("Valid providers include:");\r
+                foreach (ProviderElement p in this.Cast<ProviderElement>().OrderBy(e => e.Name))\r
+                {\r
+                    message.AppendFormat("\t{0} [{1}]",\r
+                        p.Name, p.DatabaseConnection);\r
+                    message.AppendLine();\r
+                }\r
+                return message.ToString();\r
+            }\r
         }\r
 \r
         [ConfigurationProperty("providers", IsDefaultCollection = true)]\r
index 812787d14af158bb6f8013929393e45e7495bc89..0601820638917e90bfdf51a7cb953f7642a1c51d 100644 (file)
       <Link>Properties\DbLinq.ProductInfo.cs</Link>\r
     </Compile>\r
     <Compile Include="Generator\AttributeDefinition.cs" />\r
-    <Compile Include="Generator\Implementation\CodeDomGenerator\AbstractCodeDomGenerator.cs" />\r
+    <Compile Include="Generator\CodeDomGenerator.cs" />\r
     <Compile Include="Generator\EntityInterface\Implementation\INotifyPropertyChangedImplementation.cs" />\r
     <Compile Include="Generator\GenerationContext.cs" />\r
     <Compile Include="Generator\ICodeGenerator.cs" />\r
     <Compile Include="Generator\EntityInterface\Implementation\InterfaceImplementation.cs" />\r
-    <Compile Include="Generator\Implementation\CodeDomGenerator\VisualBasicCodeDomGenerator.cs" />\r
-    <Compile Include="Generator\Implementation\CodeDomGenerator\CSharpCodeDomGenerator.cs" />\r
     <Compile Include="Generator\Implementation\CodeTextGenerator\CodeGenerator.Class.cs" />\r
     <Compile Include="Generator\Implementation\CodeTextGenerator\CodeGenerator.Context.Ctor.cs" />\r
     <Compile Include="Generator\Implementation\CodeTextGenerator\CodeGenerator.cs" />\r
     <EmbeddedResource Include="Language\GermanWords.txt" />\r
   </ItemGroup>\r
   <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />\r
-  <PropertyGroup>\r
-    <PostBuildEvent>rem this is what I call loose coupling\r
-copy "$(SolutionDir)..\lib\Npgsql.dll" "$(TargetDir)"\r
-copy "$(SolutionDir)..\lib\Mono.Security.dll" "$(TargetDir)"\r
-copy "$(SolutionDir)..\lib\Ingres.Stereo.dll" "$(TargetDir)"\r
-copy "$(SolutionDir)..\lib\Oracle.DataAccess.dll" "$(TargetDir)"\r
-copy "$(SolutionDir)..\lib\MySql.Data.dll" "$(TargetDir)"\r
-copy "$(SolutionDir)..\lib\System.Data.SQLite.dll" "$(TargetDir)"\r
-copy "$(SolutionDir)..\lib\FirebirdSql.Data.FirebirdClient.dll" "$(TargetDir)"\r
-</PostBuildEvent>\r
-  </PropertyGroup>\r
-</Project>
\ No newline at end of file
+  <ItemGroup>\r
+    <DependentAssembly Include="$(SolutionDir)..\lib\Npgsql.dll" />\r
+    <DependentAssembly Include="$(SolutionDir)..\lib\Mono.Security.dll" />\r
+    <DependentAssembly Include="$(SolutionDir)..\lib\Ingres.Stereo.dll" />\r
+    <DependentAssembly Include="$(SolutionDir)..\lib\Oracle.DataAccess.dll" />\r
+    <DependentAssembly Include="$(SolutionDir)..\lib\MySql.Data.dll" />\r
+    <DependentAssembly Include="$(SolutionDir)..\lib\System.Data.SQLite.DLL" />\r
+    <DependentAssembly Include="$(SolutionDir)..\lib\FirebirdSql.Data.FirebirdClient.dll" />\r
+  </ItemGroup>\r
+  <Target Name="AfterBuild">\r
+    <Copy \r
+        SourceFiles="@(DependentAssembly)" \r
+        DestinationFolder="$(OutputPath)" />\r
+  </Target>\r
+</Project>\r
diff --git a/mcs/class/System.Data.Linq/src/DbMetal/Generator/CodeDomGenerator.cs b/mcs/class/System.Data.Linq/src/DbMetal/Generator/CodeDomGenerator.cs
new file mode 100755 (executable)
index 0000000..c52bbeb
--- /dev/null
@@ -0,0 +1,1474 @@
+#region MIT license\r
+// \r
+// MIT license\r
+//\r
+// Copyright (c) 2007-2008 Jiri Moudry, Pascal Craponne\r
+// \r
+// Permission is hereby granted, free of charge, to any person obtaining a copy\r
+// of this software and associated documentation files (the "Software"), to deal\r
+// in the Software without restriction, including without limitation the rights\r
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r
+// copies of the Software, and to permit persons to whom the Software is\r
+// furnished to do so, subject to the following conditions:\r
+// \r
+// The above copyright notice and this permission notice shall be included in\r
+// all copies or substantial portions of the Software.\r
+// \r
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r
+// THE SOFTWARE.\r
+// \r
+#endregion\r
+using System;\r
+using System.CodeDom;\r
+using System.CodeDom.Compiler;\r
+using System.Collections.Generic;\r
+using System.ComponentModel;\r
+using System.Data;\r
+using System.Data.Linq.Mapping;\r
+using System.IO;\r
+using System.Linq;\r
+using System.Reflection;\r
+using System.Text;\r
+using System.Text.RegularExpressions;\r
+\r
+using Microsoft.CSharp;\r
+using Microsoft.VisualBasic;\r
+\r
+using DbLinq.Schema.Dbml;\r
+using DbLinq.Schema.Dbml.Adapter;\r
+using DbLinq.Util;\r
+\r
+namespace DbMetal.Generator\r
+{\r
+#if !MONO_STRICT\r
+    public\r
+#endif\r
+    class CodeDomGenerator : ICodeGenerator\r
+    {\r
+        CodeDomProvider Provider { get; set; }\r
+\r
+        // Provided only for Processor.EnumerateCodeGenerators().  DO NOT USE.\r
+        public CodeDomGenerator()\r
+        {\r
+        }\r
+\r
+        public CodeDomGenerator(CodeDomProvider provider)\r
+        {\r
+            this.Provider = provider;\r
+        }\r
+\r
+        public string LanguageCode {\r
+            get { return "*"; }\r
+        }\r
+\r
+        public string Extension {\r
+            get { return "*"; }\r
+        }\r
+\r
+        public static CodeDomGenerator CreateFromFileExtension(string extension)\r
+        {\r
+            return CreateFromLanguage(CodeDomProvider.GetLanguageFromExtension(extension));\r
+        }\r
+\r
+        public static CodeDomGenerator CreateFromLanguage(string language)\r
+        {\r
+            return new CodeDomGenerator(CodeDomProvider.CreateProvider(language));\r
+        }\r
+\r
+        public void Write(TextWriter textWriter, Database dbSchema, GenerationContext context)\r
+        {\r
+            Context = context;\r
+            Provider.CreateGenerator(textWriter).GenerateCodeFromNamespace(\r
+                GenerateCodeDomModel(dbSchema), textWriter, \r
+                new CodeGeneratorOptions() {\r
+                    BracingStyle = "C",\r
+                    IndentString = "\t",\r
+                });\r
+        }\r
+\r
+        static void Warning(string format, params object[] args)\r
+        {\r
+            Console.Error.Write(Path.GetFileName(Environment.GetCommandLineArgs()[0]));\r
+            Console.Error.Write(": warning: ");\r
+            Console.Error.WriteLine(format, args);\r
+        }\r
+\r
+        private CodeTypeMember CreatePartialMethod(string methodName, params CodeParameterDeclarationExpression[] parameters)\r
+        {\r
+            string prototype = null;\r
+            if (Provider is CSharpCodeProvider)\r
+            {\r
+                prototype =\r
+                    "\t\tpartial void {0}({1});" + Environment.NewLine +\r
+                    "\t\t";\r
+            }\r
+            else if (Provider is VBCodeProvider)\r
+            {\r
+                prototype =\r
+                    "\t\tPartial Private Sub {0}({1})" + Environment.NewLine +\r
+                    "\t\tEnd Sub" + Environment.NewLine +\r
+                    "\t\t";\r
+            }\r
+\r
+            if (prototype == null)\r
+            {\r
+                var method = new CodeMemberMethod() {\r
+                    Name = methodName,\r
+                };\r
+                method.Parameters.AddRange(parameters);\r
+                return method;\r
+            }\r
+\r
+            var methodDecl = new StringWriter();\r
+            var gen = Provider.CreateGenerator(methodDecl);\r
+\r
+            bool comma = false;\r
+            foreach (var p in parameters)\r
+            {\r
+                if (comma)\r
+                    methodDecl.Write(", ");\r
+                comma = true;\r
+                gen.GenerateCodeFromExpression(p, methodDecl, null);\r
+            }\r
+            return new CodeSnippetTypeMember(string.Format(prototype, methodName, methodDecl.ToString()));\r
+        }\r
+\r
+        CodeThisReferenceExpression thisReference = new CodeThisReferenceExpression();\r
+\r
+        protected GenerationContext Context { get; set; }\r
+\r
+        protected virtual CodeNamespace GenerateCodeDomModel(Database database)\r
+        {\r
+            CodeNamespace _namespace = new CodeNamespace(Context.Parameters.Namespace ?? database.ContextNamespace);\r
+\r
+            _namespace.Imports.Add(new CodeNamespaceImport("System"));\r
+            _namespace.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));\r
+#if MONO_STRICT\r
+            _namespace.Imports.Add(new CodeNamespaceImport("System.Data"));\r
+            _namespace.Imports.Add(new CodeNamespaceImport("System.Data.Linq"));\r
+            _namespace.Imports.Add(new CodeNamespaceImport("System.Data.Linq.Mapping"));\r
+#else\r
+            AddConditionalImports(_namespace.Imports,\r
+                "System.Data",\r
+                "MONO_STRICT",\r
+                new[] { "System.Data.Linq" },\r
+                new[] { "DbLinq.Data.Linq", "DbLinq.Vendor" },\r
+                "System.Data.Linq.Mapping");\r
+#endif\r
+            _namespace.Imports.Add(new CodeNamespaceImport("System.Diagnostics"));\r
+\r
+            var time = Context.Parameters.GenerateTimestamps ? DateTime.Now.ToString("u") : "[TIMESTAMP]";\r
+            var header = new CodeCommentStatement(GenerateCommentBanner(database, time));\r
+            _namespace.Comments.Add(header);\r
+\r
+            _namespace.Types.Add(GenerateContextClass(database));\r
+#if !MONO_STRICT\r
+            _namespace.Types.Add(GenerateMonoStrictContextConstructors(database));\r
+            _namespace.Types.Add(GenerateNotMonoStrictContextConstructors(database));\r
+#endif\r
+\r
+            foreach (Table table in database.Tables)\r
+                _namespace.Types.Add(GenerateTableClass(table, database));\r
+            return _namespace;\r
+        }\r
+\r
+        void AddConditionalImports(CodeNamespaceImportCollection imports,\r
+                string firstImport,\r
+                string conditional,\r
+                string[] importsIfTrue,\r
+                string[] importsIfFalse,\r
+                string lastImport)\r
+        {\r
+            if (Provider is CSharpCodeProvider)\r
+            {\r
+                // HACK HACK HACK\r
+                // Would be better if CodeDom actually supported conditional compilation constructs...\r
+                // This is predecated upon CSharpCodeGenerator.GenerateNamespaceImport() being implemented as:\r
+                //      output.Write ("using ");\r
+                //      output.Write (GetSafeName (import.Namespace));\r
+                //      output.WriteLine (';');\r
+                // Thus, with "crafty" execution of the namespace, we can stuff arbitrary text in there...\r
+\r
+                var block = new StringBuilder();\r
+                // No 'using', as GenerateNamespaceImport() writes it.\r
+                block.Append(firstImport).Append(";").Append(Environment.NewLine);\r
+                block.Append("#if ").Append(conditional).Append(Environment.NewLine);\r
+                foreach (var ns in importsIfTrue)\r
+                    block.Append("\tusing ").Append(ns).Append(";").Append(Environment.NewLine);\r
+                block.Append("#else   // ").Append(conditional).Append(Environment.NewLine);\r
+                foreach (var ns in importsIfFalse)\r
+                    block.Append("\tusing ").Append(ns).Append(";").Append(Environment.NewLine);\r
+                block.Append("#endif  // ").Append(conditional).Append(Environment.NewLine);\r
+                block.Append("\tusing ").Append(lastImport);\r
+                // No ';', as GenerateNamespaceImport() writes it.\r
+\r
+                imports.Add(new CodeNamespaceImport(block.ToString()));\r
+            }\r
+            else if (Provider is VBCodeProvider)\r
+            {\r
+                // HACK HACK HACK\r
+                // Would be better if CodeDom actually supported conditional compilation constructs...\r
+                // This is predecated upon VBCodeGenerator.GenerateNamespaceImport() being implemented as:\r
+                //      output.Write ("Imports ");\r
+                //      output.Write (import.Namespace);\r
+                //      output.WriteLine ();\r
+                // Thus, with "crafty" execution of the namespace, we can stuff arbitrary text in there...\r
+\r
+                var block = new StringBuilder();\r
+                // No 'Imports', as GenerateNamespaceImport() writes it.\r
+                block.Append(firstImport).Append(Environment.NewLine);\r
+                block.Append("#If ").Append(conditional).Append(" Then").Append(Environment.NewLine);\r
+                foreach (var ns in importsIfTrue)\r
+                    block.Append("Imports ").Append(ns).Append(Environment.NewLine);\r
+                block.Append("#Else     ' ").Append(conditional).Append(Environment.NewLine);\r
+                foreach (var ns in importsIfFalse)\r
+                    block.Append("Imports ").Append(ns).Append(Environment.NewLine);\r
+                block.Append("#End If   ' ").Append(conditional).Append(Environment.NewLine);\r
+                block.Append("Imports ").Append(lastImport);\r
+                // No newline, as GenerateNamespaceImport() writes it.\r
+\r
+                imports.Add(new CodeNamespaceImport(block.ToString()));\r
+            }\r
+            else\r
+            {\r
+                // Default to using the DbLinq imports\r
+                imports.Add(new CodeNamespaceImport(firstImport));\r
+                foreach (var ns in importsIfTrue)\r
+                    imports.Add(new CodeNamespaceImport(ns));\r
+                imports.Add(new CodeNamespaceImport(lastImport));\r
+            }\r
+        }\r
+\r
+        private string GenerateCommentBanner(Database database, string time)\r
+        {\r
+            var result = new StringBuilder();\r
+\r
+            // http://www.network-science.de/ascii/\r
+            // http://www.network-science.de/ascii/ascii.php?TEXT=MetalSequel&x=14&y=14&FONT=_all+fonts+with+your+text_&RICH=no&FORM=left&STRE=no&WIDT=80 \r
+            result.Append(\r
+                @"\r
+  ____  _     __  __      _        _ \r
+ |  _ \| |__ |  \/  | ___| |_ __ _| |\r
+ | | | | '_ \| |\/| |/ _ \ __/ _` | |\r
+ | |_| | |_) | |  | |  __/ || (_| | |\r
+ |____/|_.__/|_|  |_|\___|\__\__,_|_|\r
+\r
+");\r
+            result.AppendLine(String.Format(" Auto-generated from {0} on {1}.", database.Name, time));\r
+            result.AppendLine(" Please visit http://code.google.com/p/dblinq2007/ for more information.");\r
+\r
+            return result.ToString();\r
+        }\r
+\r
+        protected virtual CodeTypeDeclaration GenerateContextClass(Database database)\r
+        {\r
+            var _class = new CodeTypeDeclaration() {\r
+                IsClass         = true, \r
+                IsPartial       = true, \r
+                Name            = database.Class, \r
+                TypeAttributes  = TypeAttributes.Public \r
+            };\r
+\r
+            _class.BaseTypes.Add(GetContextBaseType(database.BaseType));\r
+\r
+            var onCreated = CreatePartialMethod("OnCreated");\r
+            onCreated.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Extensibility Method Declarations"));\r
+            onCreated.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, null));\r
+            _class.Members.Add(onCreated);\r
+\r
+            // Implement Constructor\r
+            GenerateContextConstructors(_class, database);\r
+\r
+            foreach (Table table in database.Tables)\r
+            {\r
+                var tableType = new CodeTypeReference(table.Type.Name);\r
+                var property = new CodeMemberProperty() {\r
+                    Attributes  = MemberAttributes.Public | MemberAttributes.Final,\r
+                    Name        = table.Member, \r
+                    Type        = new CodeTypeReference("Table", tableType), \r
+                };\r
+                property.GetStatements.Add(\r
+                    new CodeMethodReturnStatement(\r
+                        new CodeMethodInvokeExpression(\r
+                            new CodeMethodReferenceExpression(thisReference, "GetTable", tableType))));\r
+                _class.Members.Add(property);\r
+            }\r
+\r
+            foreach (var function in database.Functions)\r
+            {\r
+                GenerateContextFunction(_class, function);\r
+            }\r
+\r
+            return _class;\r
+        }\r
+\r
+        static string GetContextBaseType(string type)\r
+        {\r
+            string baseType = "DataContext";\r
+\r
+            if (!string.IsNullOrEmpty(type))\r
+            {\r
+                var t = TypeLoader.Load(type);\r
+                if (t != null)\r
+                    baseType = t.Name;\r
+            }\r
+\r
+            return baseType;\r
+        }\r
+\r
+        void GenerateContextConstructors(CodeTypeDeclaration contextType, Database database)\r
+        {\r
+            // .ctor(string connectionString);\r
+            var constructor = new CodeConstructor() {\r
+                Attributes = MemberAttributes.Public,\r
+                Parameters = { new CodeParameterDeclarationExpression(typeof(string), "connectionString") },\r
+            };\r
+            constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("connectionString"));\r
+            constructor.Statements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(thisReference, "OnCreated")));\r
+            contextType.Members.Add(constructor);\r
+\r
+#if MONO_STRICT\r
+            // .ctor(IDbConnection connection);\r
+            constructor = new CodeConstructor() {\r
+                Attributes = MemberAttributes.Public,\r
+                Parameters = { new CodeParameterDeclarationExpression("IDbConnection", "connection") },\r
+            };\r
+            constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("connection"));\r
+            constructor.Statements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(thisReference, "OnCreated")));\r
+            contextType.Members.Add(constructor);\r
+#endif\r
+\r
+            // .ctor(string connection, MappingSource mappingSource);\r
+            constructor = new CodeConstructor() {\r
+                Attributes = MemberAttributes.Public,\r
+                Parameters = { \r
+                    new CodeParameterDeclarationExpression(typeof(string), "connection"),\r
+                    new CodeParameterDeclarationExpression("MappingSource", "mappingSource"),\r
+                },\r
+            };\r
+            constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("connection"));\r
+            constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("mappingSource"));\r
+            constructor.Statements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(thisReference, "OnCreated")));\r
+            contextType.Members.Add(constructor);\r
+\r
+            // .ctor(IDbConnection connection, MappingSource mappingSource);\r
+            constructor = new CodeConstructor() {\r
+                Attributes = MemberAttributes.Public,\r
+                Parameters = { \r
+                    new CodeParameterDeclarationExpression("IDbConnection", "connection"),\r
+                    new CodeParameterDeclarationExpression("MappingSource", "mappingSource"),\r
+                },\r
+            };\r
+            constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("connection"));\r
+            constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("mappingSource"));\r
+            constructor.Statements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(thisReference, "OnCreated")));\r
+            contextType.Members.Add(constructor);\r
+        }\r
+\r
+        CodeTypeDeclaration GenerateMonoStrictContextConstructors(Database database)\r
+        {\r
+            var contextType = new CodeTypeDeclaration()\r
+            {\r
+                IsClass         = true,\r
+                IsPartial       = true,\r
+                Name            = database.Class,\r
+                TypeAttributes  = TypeAttributes.Public\r
+            };\r
+            AddConditionalIfElseBlocks(contextType, "MONO_STRICT");\r
+\r
+            // .ctor(IDbConnection connection);\r
+            var constructor = new CodeConstructor() {\r
+                Attributes = MemberAttributes.Public,\r
+                Parameters = { new CodeParameterDeclarationExpression("IDbConnection", "connection") },\r
+            };\r
+            constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("connection"));\r
+            constructor.Statements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(thisReference, "OnCreated")));\r
+            contextType.Members.Add(constructor);\r
+\r
+            return contextType;\r
+        }\r
+\r
+        void AddConditionalIfElseBlocks(CodeTypeMember member, string condition)\r
+        {\r
+            string startIf = null, elseIf = null;\r
+            if (Provider is CSharpCodeProvider)\r
+            {\r
+                startIf = string.Format("Start {0}{1}#if {0}{1}", condition, Environment.NewLine);\r
+                elseIf  = string.Format("End {0}{1}\t#endregion{1}#else     // {0}", condition, Environment.NewLine);\r
+            }\r
+            if (Provider is VBCodeProvider)\r
+            {\r
+                startIf = string.Format("Start {0}\"{1}#If {0} Then{1}    '", condition, Environment.NewLine);\r
+                elseIf  = string.Format("End {0}\"{1}\t#End Region{1}#Else     ' {0}", condition, Environment.NewLine);\r
+            }\r
+            if (startIf != null && elseIf != null)\r
+            {\r
+                member.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, startIf));\r
+                member.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, elseIf));\r
+            }\r
+        }\r
+\r
+        void AddConditionalEndifBlocks(CodeTypeMember member, string condition)\r
+        {\r
+            string endIf = null;\r
+            if (Provider is CSharpCodeProvider)\r
+            {\r
+                endIf   = string.Format("End Not {0}{1}\t#endregion{1}#endif     // {0}", condition, Environment.NewLine);\r
+            }\r
+            if (Provider is VBCodeProvider)\r
+            {\r
+                endIf   = string.Format("End Not {0}\"{1}\t#End Region{1}#End If     ' {0}", condition, Environment.NewLine);\r
+            }\r
+            if (endIf != null)\r
+            {\r
+                member.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, endIf));\r
+                member.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, null));\r
+            }\r
+        }\r
+\r
+        CodeTypeDeclaration GenerateNotMonoStrictContextConstructors(Database database)\r
+        {\r
+            var contextType = new CodeTypeDeclaration() {\r
+                IsClass         = true,\r
+                IsPartial       = true,\r
+                Name            = database.Class,\r
+                TypeAttributes  = TypeAttributes.Public\r
+            };\r
+            AddConditionalEndifBlocks(contextType, "MONO_STRICT");\r
+\r
+            // .ctor(IDbConnection connection);\r
+            var constructor = new CodeConstructor() {\r
+                Attributes = MemberAttributes.Public,\r
+                Parameters = { new CodeParameterDeclarationExpression("IDbConnection", "connection") },\r
+            };\r
+            constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("connection"));\r
+            constructor.BaseConstructorArgs.Add(new CodeObjectCreateExpression(Context.SchemaLoader.Vendor.GetType()));\r
+            constructor.Statements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(thisReference, "OnCreated")));\r
+            contextType.Members.Add(constructor);\r
+\r
+            // .ctor(IDbConnection connection, IVendor mappingSource);\r
+            constructor = new CodeConstructor() {\r
+                Attributes = MemberAttributes.Public,\r
+                Parameters = {\r
+                    new CodeParameterDeclarationExpression("IDbConnection", "connection"),\r
+                    new CodeParameterDeclarationExpression("IVendor", "sqlDialect"),\r
+                },\r
+            };\r
+            constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("connection"));\r
+            constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("sqlDialect"));\r
+            constructor.Statements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(thisReference, "OnCreated")));\r
+            contextType.Members.Add(constructor);\r
+\r
+            // .ctor(IDbConnection connection, MappingSource mappingSource, IVendor mappingSource);\r
+            constructor = new CodeConstructor() {\r
+                Attributes = MemberAttributes.Public,\r
+                Parameters = {\r
+                    new CodeParameterDeclarationExpression("IDbConnection", "connection"),\r
+                    new CodeParameterDeclarationExpression("MappingSource", "mappingSource"),\r
+                    new CodeParameterDeclarationExpression("IVendor", "sqlDialect"),\r
+                },\r
+            };\r
+            constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("connection"));\r
+            constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("mappingSource"));\r
+            constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("sqlDialect"));\r
+            constructor.Statements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(thisReference, "OnCreated")));\r
+            contextType.Members.Add(constructor);\r
+\r
+            return contextType;\r
+        }\r
+        \r
+        void GenerateContextFunction(CodeTypeDeclaration contextType, Function function)\r
+        {\r
+            if (function == null || string.IsNullOrEmpty(function.Name))\r
+            {\r
+                Warning("L33 Invalid storedProcdure object: missing name.");\r
+                return;\r
+            }\r
+\r
+            var methodRetType = GetFunctionReturnType(function);\r
+            var method = new CodeMemberMethod() {\r
+                Attributes  = ToMemberAttributes(function),\r
+                Name        = function.Method ?? function.Name,\r
+                ReturnType  = methodRetType,\r
+                CustomAttributes = {\r
+                    new CodeAttributeDeclaration("Function",\r
+                        new CodeAttributeArgument("Name", new CodePrimitiveExpression(function.Name)),\r
+                        new CodeAttributeArgument("IsComposable", new CodePrimitiveExpression(function.IsComposable))),\r
+                },\r
+            };\r
+            if (method.Parameters != null)\r
+                method.Parameters.AddRange(function.Parameters.Select(x => GetFunctionParameterType(x)).ToArray());\r
+            if (function.Return != null && !string.IsNullOrEmpty(function.Return.DbType))\r
+                method.ReturnTypeCustomAttributes.Add(\r
+                        new CodeAttributeDeclaration("Parameter",\r
+                            new CodeAttributeArgument("DbType", new CodePrimitiveExpression(function.Return.DbType))));\r
+\r
+            contextType.Members.Add(method);\r
+\r
+            for (int i = 0; i < function.Parameters.Count; ++i)\r
+            {\r
+                var p = function.Parameters[i];\r
+                if (!p.DirectionOut)\r
+                    continue;\r
+                method.Statements.Add(\r
+                        new CodeAssignStatement(\r
+                            new CodeVariableReferenceExpression(p.Name),\r
+                            new CodeDefaultValueExpression(new CodeTypeReference(p.Type))));\r
+            }\r
+\r
+            var executeMethodCallArgs = new List<CodeExpression>() {\r
+                thisReference,\r
+                new CodeCastExpression(\r
+                    new CodeTypeReference("System.Reflection.MethodInfo"),\r
+                    new CodeMethodInvokeExpression(\r
+                        new CodeMethodReferenceExpression(\r
+                            new CodeTypeReferenceExpression("System.Reflection.MethodBase"), "GetCurrentMethod"))),\r
+            };\r
+            if (method.Parameters != null)\r
+                executeMethodCallArgs.AddRange(\r
+                        function.Parameters.Select(p => (CodeExpression) new CodeVariableReferenceExpression(p.Name)));\r
+            method.Statements.Add(\r
+                    new CodeVariableDeclarationStatement(\r
+                        new CodeTypeReference("IExecuteResult"),\r
+                        "result",\r
+                        new CodeMethodInvokeExpression(\r
+                            new CodeMethodReferenceExpression(thisReference, "ExecuteMethodCall"),\r
+                            executeMethodCallArgs.ToArray())));\r
+            for (int i = 0; i < function.Parameters.Count; ++i)\r
+            {\r
+                var p = function.Parameters[i];\r
+                if (!p.DirectionOut)\r
+                    continue;\r
+                method.Statements.Add(\r
+                        new CodeAssignStatement(\r
+                            new CodeVariableReferenceExpression(p.Name),\r
+                            new CodeCastExpression(\r
+                                new CodeTypeReference(p.Type),\r
+                                new CodeMethodInvokeExpression(\r
+                                    new CodeMethodReferenceExpression(\r
+                                        new CodeVariableReferenceExpression("result"),\r
+                                        "GetParameterValue"),\r
+                                    new CodePrimitiveExpression(i)))));\r
+            }\r
+\r
+            if (methodRetType != null)\r
+            {\r
+                method.Statements.Add(\r
+                        new CodeMethodReturnStatement(\r
+                            new CodeCastExpression(\r
+                                method.ReturnType,\r
+                                new CodePropertyReferenceExpression(\r
+                                    new CodeVariableReferenceExpression("result"),\r
+                                    "ReturnValue"))));\r
+            }\r
+        }\r
+\r
+        CodeTypeReference GetFunctionReturnType(Function function)\r
+        {\r
+            CodeTypeReference type = null;\r
+            if (function.Return != null)\r
+            {\r
+                type = GetFunctionType(function.Return.Type);\r
+            }\r
+\r
+            bool isDataShapeUnknown = function.ElementType == null\r
+                                      && function.BodyContainsSelectStatement\r
+                                      && !function.IsComposable;\r
+            if (isDataShapeUnknown)\r
+            {\r
+                //if we don't know the shape of results, and the proc body contains some selects,\r
+                //we have no choice but to return an untyped DataSet.\r
+                //\r
+                //TODO: either parse proc body like microsoft, \r
+                //or create a little GUI tool which would call the proc with test values, to determine result shape.\r
+                type = new CodeTypeReference(typeof(DataSet));\r
+            }\r
+            return type;\r
+        }\r
+\r
+        static CodeTypeReference GetFunctionType(string type)\r
+        {\r
+            var t = System.Type.GetType(type);\r
+            if (t == null)\r
+                return new CodeTypeReference(type);\r
+            if (t.IsValueType)\r
+                return new CodeTypeReference(typeof(Nullable<>)) {\r
+                    TypeArguments = {\r
+                        new CodeTypeReference(t),\r
+                    },\r
+                };\r
+            return new CodeTypeReference(t);\r
+        }\r
+\r
+        CodeParameterDeclarationExpression GetFunctionParameterType(Parameter parameter)\r
+        {\r
+            var p = new CodeParameterDeclarationExpression(GetFunctionType(parameter.Type), parameter.Name) {\r
+                CustomAttributes = {\r
+                    new CodeAttributeDeclaration("Parameter",\r
+                        new CodeAttributeArgument("Name", new CodePrimitiveExpression(parameter.Name)),\r
+                        new CodeAttributeArgument("DbType", new CodePrimitiveExpression(parameter.DbType))),\r
+                },\r
+            };\r
+            switch (parameter.Direction)\r
+            {\r
+                case DbLinq.Schema.Dbml.ParameterDirection.In:\r
+                    p.Direction = FieldDirection.In;\r
+                    break;\r
+                case DbLinq.Schema.Dbml.ParameterDirection.Out:\r
+                    p.Direction = FieldDirection.Out;\r
+                    break;\r
+                case DbLinq.Schema.Dbml.ParameterDirection.InOut:\r
+                    p.Direction = FieldDirection.In | FieldDirection.Out;\r
+                    break;\r
+                default:\r
+                    throw new ArgumentOutOfRangeException();\r
+            }\r
+            return p;\r
+        }\r
+\r
+        protected CodeTypeDeclaration GenerateTableClass(Table table, Database database)\r
+        {\r
+            var _class = new CodeTypeDeclaration() {\r
+                IsClass         = true, \r
+                IsPartial       = true, \r
+                Name            = table.Type.Name, \r
+                TypeAttributes  = TypeAttributes.Public,\r
+                CustomAttributes = {\r
+                    new CodeAttributeDeclaration("Table", \r
+                        new CodeAttributeArgument("Name", new CodePrimitiveExpression(table.Name))),\r
+                },\r
+            };\r
+\r
+            WriteCustomTypes(_class, table);\r
+\r
+            var havePrimaryKeys = table.Type.Columns.Any(c => c.IsPrimaryKey);\r
+            if (havePrimaryKeys)\r
+            {\r
+                GenerateINotifyPropertyChanging(_class);\r
+                GenerateINotifyPropertyChanged(_class);\r
+            }\r
+\r
+            // Implement Constructor\r
+            var constructor = new CodeConstructor() { Attributes = MemberAttributes.Public };\r
+            // children are EntitySet\r
+            foreach (var child in GetClassChildren(table))\r
+            {\r
+                // if the association has a storage, we use it. Otherwise, we use the property name\r
+                var entitySetMember = GetStorageFieldName(child);\r
+                constructor.Statements.Add(\r
+                    new CodeAssignStatement(\r
+                        new CodeVariableReferenceExpression(entitySetMember),\r
+                        new CodeObjectCreateExpression(\r
+                            new CodeTypeReference("EntitySet", new CodeTypeReference(child.Type)),\r
+                            new CodeDelegateCreateExpression(\r
+                                new CodeTypeReference("Action", new CodeTypeReference(child.Type)),\r
+                                thisReference, child.Member + "_Attach"),\r
+                            new CodeDelegateCreateExpression(\r
+                                new CodeTypeReference("Action", new CodeTypeReference(child.Type)),\r
+                                thisReference, child.Member + "_Detach"))));\r
+            }\r
+            constructor.Statements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(thisReference, "OnCreated")));\r
+            _class.Members.Add(constructor);\r
+\r
+            if (Context.Parameters.GenerateEqualsHash)\r
+            {\r
+                GenerateEntityGetHashCodeAndEquals(_class, table);\r
+            }\r
+\r
+            GenerateExtensibilityDeclarations(_class, table);\r
+\r
+            // todo: add these when the actually get called\r
+            //partial void OnLoaded();\r
+            //partial void OnValidate(System.Data.Linq.ChangeAction action);\r
+\r
+            // columns\r
+            foreach (Column column in table.Type.Columns)\r
+            {\r
+                var relatedAssociations = from a in table.Type.Associations\r
+                                          where a.IsForeignKey && a.TheseKeys.Contains(column.Name)\r
+                                          select a;\r
+\r
+                var type = ToCodeTypeReference(column);\r
+                var columnMember = column.Member ?? column.Name;\r
+\r
+                var field = new CodeMemberField(type, GetStorageFieldName(column));\r
+                _class.Members.Add(field);\r
+                var fieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name);\r
+\r
+                var onChanging  = GetChangingMethodName(columnMember);\r
+                var onChanged   = GetChangedMethodName(columnMember);\r
+\r
+                var property = new CodeMemberProperty();\r
+                property.Type = type;\r
+                property.Name = columnMember;\r
+                property.Attributes = MemberAttributes.Public | MemberAttributes.Final;\r
+\r
+                var defAttrValues = new ColumnAttribute();\r
+                var args = new List<CodeAttributeArgument>() {\r
+                    new CodeAttributeArgument("Storage", new CodePrimitiveExpression(GetStorageFieldName(column))),\r
+                    new CodeAttributeArgument("Name", new CodePrimitiveExpression(column.Name)),\r
+                    new CodeAttributeArgument("DbType", new CodePrimitiveExpression(column.DbType)),\r
+                };\r
+                if (defAttrValues.IsPrimaryKey != column.IsPrimaryKey)\r
+                    args.Add(new CodeAttributeArgument("IsPrimaryKey", new CodePrimitiveExpression(column.IsPrimaryKey)));\r
+                if (defAttrValues.IsDbGenerated != column.IsDbGenerated)\r
+                    args.Add(new CodeAttributeArgument("IsDbGenerated", new CodePrimitiveExpression(column.IsDbGenerated)));\r
+                if (column.AutoSync != DbLinq.Schema.Dbml.AutoSync.Default)\r
+                    args.Add(new CodeAttributeArgument("AutoSync", \r
+                        new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("AutoSync"), column.AutoSync.ToString())));\r
+                if (defAttrValues.CanBeNull != column.CanBeNull)\r
+                    args.Add(new CodeAttributeArgument("CanBeNull", new CodePrimitiveExpression(column.CanBeNull)));\r
+                if (column.Expression != null)\r
+                    args.Add(new CodeAttributeArgument("Expression", new CodePrimitiveExpression(column.Expression)));\r
+                property.CustomAttributes.Add(\r
+                    new CodeAttributeDeclaration("Column", args.ToArray()));\r
+                property.CustomAttributes.Add(new CodeAttributeDeclaration("DebuggerNonUserCode"));\r
+\r
+                property.GetStatements.Add(new CodeMethodReturnStatement(fieldReference));\r
+\r
+                var whenUpdating = new List<CodeStatement>(\r
+                    from assoc in relatedAssociations\r
+                    select (CodeStatement) new CodeConditionStatement(\r
+                        new CodePropertyReferenceExpression(\r
+                            new CodeVariableReferenceExpression(GetStorageFieldName(assoc)),\r
+                            "HasLoadedOrAssignedValue"),\r
+                        new CodeThrowExceptionStatement(\r
+                            new CodeObjectCreateExpression(typeof(System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException)))));\r
+                whenUpdating.Add(\r
+                        new CodeExpressionStatement(new CodeMethodInvokeExpression(thisReference, onChanging, new CodePropertySetValueReferenceExpression())));\r
+                if (havePrimaryKeys)\r
+                    whenUpdating.Add(\r
+                            new CodeExpressionStatement(new CodeMethodInvokeExpression(thisReference, "SendPropertyChanging")));\r
+                whenUpdating.Add(\r
+                        new CodeAssignStatement(fieldReference, new CodePropertySetValueReferenceExpression()));\r
+                if (havePrimaryKeys)\r
+                    whenUpdating.Add(\r
+                            new CodeExpressionStatement(new CodeMethodInvokeExpression(thisReference, "SendPropertyChanged", new CodePrimitiveExpression(property.Name))));\r
+                whenUpdating.Add(\r
+                        new CodeExpressionStatement(new CodeMethodInvokeExpression(thisReference, onChanged)));\r
+\r
+                var fieldType = TypeLoader.Load(column.Type);\r
+                // This is needed for VB.NET generation; \r
+                // int/string/etc. can use '<>' for comparison, but NOT arrays and other reference types.\r
+                // arrays/etc. require the 'Is' operator, which is CodeBinaryOperatorType.IdentityEquality.\r
+                // The VB IsNot operator is not exposed from CodeDom.\r
+                // Thus, we need to special-case: if fieldType is a ref or nullable type,\r
+                //  generate '(field Is value) = false'; otherwise, \r
+                //  generate '(field <> value)'\r
+                CodeBinaryOperatorExpression condition = fieldType.IsClass || fieldType.IsNullable()\r
+                    ? ValuesAreNotEqual_Ref(new CodeVariableReferenceExpression(field.Name), new CodePropertySetValueReferenceExpression())\r
+                    : ValuesAreNotEqual(new CodeVariableReferenceExpression(field.Name), new CodePropertySetValueReferenceExpression());\r
+                property.SetStatements.Add(new CodeConditionStatement(condition, whenUpdating.ToArray()));\r
+                _class.Members.Add(property);\r
+            }\r
+\r
+            GenerateEntityChildren(_class, table, database);\r
+            GenerateEntityChildrenAttachment(_class, table, database);\r
+            GenerateEntityParents(_class, table, database);\r
+\r
+            return _class;\r
+        }\r
+\r
+        void WriteCustomTypes(CodeTypeDeclaration entity, Table table)\r
+        {\r
+            // detect required custom types\r
+            foreach (var column in table.Type.Columns)\r
+            {\r
+                var extendedType = column.ExtendedType;\r
+                var enumType = extendedType as EnumType;\r
+                if (enumType != null)\r
+                {\r
+                    Context.ExtendedTypes[column] = new GenerationContext.ExtendedTypeAndName {\r
+                        Type = column.ExtendedType,\r
+                        Table = table\r
+                    };\r
+                }\r
+            }\r
+\r
+            var customTypesNames = new List<string>();\r
+\r
+            // create names and avoid conflits\r
+            foreach (var extendedTypePair in Context.ExtendedTypes)\r
+            {\r
+                if (extendedTypePair.Value.Table != table)\r
+                    continue;\r
+\r
+                if (string.IsNullOrEmpty(extendedTypePair.Value.Type.Name))\r
+                {\r
+                    string name = extendedTypePair.Key.Member + "Type";\r
+                    for (; ; )\r
+                    {\r
+                        if ((from t in Context.ExtendedTypes.Values where t.Type.Name == name select t).FirstOrDefault() == null)\r
+                        {\r
+                            extendedTypePair.Value.Type.Name = name;\r
+                            break;\r
+                        }\r
+                        // at 3rd loop, it will look ugly, however we will never go there\r
+                        name = extendedTypePair.Value.Table.Type.Name + name;\r
+                    }\r
+                }\r
+                customTypesNames.Add(extendedTypePair.Value.Type.Name);\r
+            }\r
+\r
+            // write custom types\r
+            if (customTypesNames.Count > 0)\r
+            {\r
+                var customTypes = new List<CodeTypeDeclaration>(customTypesNames.Count);\r
+\r
+                foreach (var extendedTypePair in Context.ExtendedTypes)\r
+                {\r
+                    if (extendedTypePair.Value.Table != table)\r
+                        continue;\r
+\r
+                    var extendedType = extendedTypePair.Value.Type;\r
+                    var enumValue = extendedType as EnumType;\r
+\r
+                    if (enumValue != null)\r
+                    {\r
+                        var enumType = new CodeTypeDeclaration(enumValue.Name) {\r
+                            TypeAttributes = TypeAttributes.Public,\r
+                            IsEnum = true,\r
+                        };\r
+                        customTypes.Add(enumType);\r
+                        var orderedValues = from nv in enumValue orderby nv.Value select nv;\r
+                        int currentValue = 1;\r
+                        foreach (var nameValue in orderedValues)\r
+                        {\r
+                            var field = new CodeMemberField() {\r
+                                Name = nameValue.Key,\r
+                            };\r
+                            enumType.Members.Add(field);\r
+                            if (nameValue.Value != currentValue)\r
+                            {\r
+                                currentValue = nameValue.Value;\r
+                                field.InitExpression = new CodePrimitiveExpression(nameValue.Value);\r
+                            }\r
+                            currentValue++;\r
+                        }\r
+                    }\r
+                }\r
+\r
+                if (customTypes.Count == 0)\r
+                    return;\r
+                customTypes.First().StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start,\r
+                        string.Format("Custom type definitions for {0}", string.Join(", ", customTypesNames.ToArray()))));\r
+                customTypes.Last().EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, null));\r
+                entity.Members.AddRange(customTypes.ToArray());\r
+            }\r
+        }\r
+\r
+        void GenerateExtensibilityDeclarations(CodeTypeDeclaration entity, Table table)\r
+        {\r
+            var partialMethods = new[] { CreatePartialMethod("OnCreated") }\r
+                .Concat(table.Type.Columns.Select(c => new[] { CreateChangedMethodDecl(c), CreateChangingMethodDecl(c) })\r
+                    .SelectMany(md => md)).ToArray();\r
+            partialMethods.First().StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Extensibility Method Declarations"));\r
+            partialMethods.Last().EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, null));\r
+            entity.Members.AddRange(partialMethods);\r
+        }\r
+\r
+        static string GetChangedMethodName(string columnName)\r
+        {\r
+            return string.Format("On{0}Changed", columnName);\r
+        }\r
+\r
+        CodeTypeMember CreateChangedMethodDecl(Column column)\r
+        {\r
+            return CreatePartialMethod(GetChangedMethodName(column.Member));\r
+        }\r
+\r
+        static string GetChangingMethodName(string columnName)\r
+        {\r
+            return string.Format("On{0}Changing", columnName);\r
+        }\r
+\r
+        CodeTypeMember CreateChangingMethodDecl(Column column)\r
+        {\r
+            return CreatePartialMethod(GetChangingMethodName(column.Member),\r
+                    new CodeParameterDeclarationExpression(ToCodeTypeReference(column), "value"));\r
+        }\r
+\r
+        static CodeTypeReference ToCodeTypeReference(Column column)\r
+        {\r
+            var t = System.Type.GetType(column.Type);\r
+            if (t == null)\r
+                return new CodeTypeReference(column.Type);\r
+            return t.IsValueType && column.CanBeNull\r
+                ? new CodeTypeReference("System.Nullable", new CodeTypeReference(column.Type))\r
+                : new CodeTypeReference(column.Type);\r
+        }\r
+\r
+        CodeBinaryOperatorExpression ValuesAreNotEqual(CodeExpression a, CodeExpression b)\r
+        {\r
+            return new CodeBinaryOperatorExpression(a, CodeBinaryOperatorType.IdentityInequality, b);\r
+        }\r
+\r
+        CodeBinaryOperatorExpression ValuesAreNotEqual_Ref(CodeExpression a, CodeExpression b)\r
+        {\r
+            return new CodeBinaryOperatorExpression(\r
+                        new CodeBinaryOperatorExpression(\r
+                            a,\r
+                            CodeBinaryOperatorType.IdentityEquality,\r
+                            b),\r
+                        CodeBinaryOperatorType.ValueEquality,\r
+                        new CodePrimitiveExpression(false));\r
+        }\r
+\r
+        CodeBinaryOperatorExpression ValueIsNull(CodeExpression value)\r
+        {\r
+            return new CodeBinaryOperatorExpression(\r
+                value,\r
+                CodeBinaryOperatorType.IdentityEquality,\r
+                new CodePrimitiveExpression(null));\r
+        }\r
+\r
+        CodeBinaryOperatorExpression ValueIsNotNull(CodeExpression value)\r
+        {\r
+            return new CodeBinaryOperatorExpression(\r
+                value,\r
+                CodeBinaryOperatorType.IdentityInequality, \r
+                new CodePrimitiveExpression(null));\r
+        }\r
+\r
+        static string GetStorageFieldName(Column column)\r
+        {\r
+            return GetStorageFieldName(column.Storage ?? column.Member);\r
+        }\r
+\r
+        static string GetStorageFieldName(string storage)\r
+        {\r
+            if (storage.StartsWith("_"))\r
+                return storage;\r
+            return "_" + storage;\r
+        }\r
+\r
+        private void GenerateINotifyPropertyChanging(CodeTypeDeclaration entity)\r
+        {\r
+            entity.BaseTypes.Add(typeof(INotifyPropertyChanging));\r
+            var propertyChangingEvent = new CodeMemberEvent() {\r
+                Attributes  = MemberAttributes.Public,\r
+                Name        = "PropertyChanging",\r
+                Type        = new CodeTypeReference(typeof(PropertyChangingEventHandler)),\r
+                ImplementationTypes = {\r
+                    new CodeTypeReference(typeof(INotifyPropertyChanging))\r
+                },\r
+            };\r
+            var eventArgs = new CodeMemberField(new CodeTypeReference(typeof(PropertyChangingEventArgs)), "emptyChangingEventArgs") {\r
+                Attributes      = MemberAttributes.Static | MemberAttributes.Private,\r
+                InitExpression  = new CodeObjectCreateExpression(new CodeTypeReference(typeof(PropertyChangingEventArgs)),\r
+                    new CodePrimitiveExpression("")),\r
+            };\r
+            var method = new CodeMemberMethod() {\r
+                Attributes  = MemberAttributes.Family,\r
+                Name        = "SendPropertyChanging",\r
+            };\r
+            method.Statements.Add(new CodeVariableDeclarationStatement(typeof(PropertyChangingEventHandler), "h") {\r
+                InitExpression  = new CodeEventReferenceExpression(thisReference, "PropertyChanging"),\r
+            });\r
+            method.Statements.Add(new CodeConditionStatement(\r
+                    ValueIsNotNull(new CodeVariableReferenceExpression("h")),\r
+                    new CodeExpressionStatement(\r
+                        new CodeDelegateInvokeExpression(new CodeVariableReferenceExpression("h"), thisReference, new CodeFieldReferenceExpression(null, "emptyChangingEventArgs")))));\r
+\r
+            entity.Members.Add(propertyChangingEvent);\r
+            entity.Members.Add(eventArgs);\r
+            entity.Members.Add(method);\r
+        }\r
+\r
+        private void GenerateINotifyPropertyChanged(CodeTypeDeclaration entity)\r
+        {\r
+            entity.BaseTypes.Add(typeof(INotifyPropertyChanged));\r
+\r
+            var propertyChangedEvent = new CodeMemberEvent() {\r
+                Attributes = MemberAttributes.Public,\r
+                Name = "PropertyChanged",\r
+                Type = new CodeTypeReference(typeof(PropertyChangedEventHandler)),\r
+                ImplementationTypes = {\r
+                    new CodeTypeReference(typeof(INotifyPropertyChanged))\r
+                },\r
+            };\r
+\r
+            var method = new CodeMemberMethod() { \r
+                Attributes = MemberAttributes.Family, \r
+                Name = "SendPropertyChanged", \r
+                Parameters = { new CodeParameterDeclarationExpression(typeof(System.String), "propertyName") } \r
+            };\r
+            method.Statements.Add(new CodeVariableDeclarationStatement(typeof(PropertyChangedEventHandler), "h") {\r
+                InitExpression = new CodeEventReferenceExpression(thisReference, "PropertyChanged"),\r
+            });\r
+            method.Statements.Add(new CodeConditionStatement(\r
+                    ValueIsNotNull(new CodeVariableReferenceExpression("h")),\r
+                    new CodeExpressionStatement(\r
+                        new CodeDelegateInvokeExpression(new CodeVariableReferenceExpression("h"), thisReference, new CodeObjectCreateExpression(typeof(PropertyChangedEventArgs), new CodeVariableReferenceExpression("propertyName"))))));\r
+\r
+            entity.Members.Add(propertyChangedEvent);\r
+            entity.Members.Add(method);\r
+        }\r
+\r
+        void GenerateEntityGetHashCodeAndEquals(CodeTypeDeclaration entity, Table table)\r
+        {\r
+            var primaryKeys = table.Type.Columns.Where(c => c.IsPrimaryKey);\r
+            var pkCount = primaryKeys.Count();\r
+            if (pkCount == 0)\r
+            {\r
+                Warning("Table {0} has no primary key(s).  Skipping /generate-equals-hash for this table.",\r
+                        table.Name);\r
+                return;\r
+            }\r
+            entity.BaseTypes.Add(new CodeTypeReference(typeof(IEquatable<>)) {\r
+                TypeArguments = { new CodeTypeReference(entity.Name) },\r
+            });\r
+\r
+            var method = new CodeMemberMethod() {\r
+                Attributes  = MemberAttributes.Public | MemberAttributes.Override,\r
+                Name        = "GetHashCode",\r
+                ReturnType  = new CodeTypeReference(typeof(int)),\r
+            };\r
+            entity.Members.Add(method);\r
+            method.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "hc", new CodePrimitiveExpression(0)));\r
+            var numShifts = 32 / pkCount;\r
+            int pki = 0;\r
+            foreach (var pk in primaryKeys)\r
+            {\r
+                var shift = 1 << (pki++ * numShifts);\r
+                // lack of exclusive-or means we instead split the 32-bit hash code value\r
+                // into pkCount "chunks", each chunk being numShifts in size.\r
+                // Thus, if there are two primary keys, the first primary key gets the\r
+                // lower 16 bits, while the second primray key gets the upper 16 bits.\r
+                CodeStatement update = new CodeAssignStatement(\r
+                        new CodeVariableReferenceExpression("hc"),\r
+                        new CodeBinaryOperatorExpression(\r
+                            new CodeVariableReferenceExpression("hc"),\r
+                            CodeBinaryOperatorType.BitwiseOr,\r
+                            new CodeBinaryOperatorExpression(\r
+                                new CodeMethodInvokeExpression(\r
+                                    new CodeMethodReferenceExpression(\r
+                                        new CodeVariableReferenceExpression(GetStorageFieldName(pk)),\r
+                                        "GetHashCode")),\r
+                                CodeBinaryOperatorType.Multiply,\r
+                                new CodePrimitiveExpression(shift))));\r
+                var pkType = System.Type.GetType(pk.Type);\r
+                if (pk.CanBeNull || (pkType != null && (pkType.IsClass || pkType.IsNullable())))\r
+                {\r
+                    update = new CodeConditionStatement(\r
+                            ValueIsNotNull(new CodeVariableReferenceExpression(GetStorageFieldName(pk))),\r
+                            update);\r
+                }\r
+                method.Statements.Add(update);\r
+            }\r
+            method.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("hc")));\r
+\r
+            method = new CodeMemberMethod() {\r
+                Attributes  = MemberAttributes.Public | MemberAttributes.Override,\r
+                Name        = "Equals",\r
+                ReturnType  = new CodeTypeReference(typeof(bool)),\r
+                Parameters = {\r
+                    new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(object)), "value"),\r
+                },\r
+            };\r
+            entity.Members.Add(method);\r
+            method.Statements.Add(\r
+                    new CodeConditionStatement(\r
+                        ValueIsNull(new CodeVariableReferenceExpression("value")), \r
+                        new CodeMethodReturnStatement(new CodePrimitiveExpression(false))));\r
+            method.Statements.Add(\r
+                    new CodeConditionStatement(\r
+                        ValuesAreNotEqual_Ref(\r
+                            new CodeMethodInvokeExpression(\r
+                                new CodeMethodReferenceExpression(\r
+                                    new CodeVariableReferenceExpression("value"),\r
+                                    "GetType")),\r
+                            new CodeMethodInvokeExpression(\r
+                                new CodeMethodReferenceExpression(thisReference, "GetType"))),\r
+                        new CodeMethodReturnStatement(new CodePrimitiveExpression(false))));\r
+            method.Statements.Add(\r
+                    new CodeVariableDeclarationStatement(\r
+                        new CodeTypeReference(entity.Name),\r
+                        "other",\r
+                        new CodeCastExpression(new CodeTypeReference(entity.Name), new CodeVariableReferenceExpression("value"))));\r
+            method.Statements.Add(\r
+                    new CodeMethodReturnStatement(\r
+                        new CodeMethodInvokeExpression(\r
+                            new CodeMethodReferenceExpression(thisReference, "Equals"),\r
+                            new CodeVariableReferenceExpression("other"))));\r
+\r
+            method = new CodeMemberMethod() {\r
+                Attributes  = MemberAttributes.Public,\r
+                Name        = "Equals",\r
+                ReturnType  = new CodeTypeReference(typeof(bool)),\r
+                Parameters  = {\r
+                    new CodeParameterDeclarationExpression(new CodeTypeReference(entity.Name), "value"),\r
+                },\r
+                ImplementationTypes = {\r
+                    new CodeTypeReference("IEquatable", new CodeTypeReference(entity.Name)),\r
+                },\r
+            };\r
+            entity.Members.Add(method);\r
+            method.Statements.Add(\r
+                    new CodeConditionStatement(\r
+                        ValueIsNull(new CodeVariableReferenceExpression("value")),\r
+                        new CodeMethodReturnStatement(new CodePrimitiveExpression(false))));\r
+\r
+            CodeExpression equals = null;\r
+            foreach (var pk in primaryKeys)\r
+            {\r
+                var compare = new CodeMethodInvokeExpression(\r
+                        new CodeMethodReferenceExpression(\r
+                            new CodePropertyReferenceExpression(\r
+                                new CodeTypeReferenceExpression(\r
+                                    new CodeTypeReference("System.Collections.Generic.EqualityComparer",\r
+                                        new CodeTypeReference(pk.Type))),\r
+                                "Default"),\r
+                            "Equals"),\r
+                        new CodeFieldReferenceExpression(thisReference, GetStorageFieldName(pk)),\r
+                        new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("value"), GetStorageFieldName(pk)));\r
+                equals = equals == null\r
+                    ? (CodeExpression) compare\r
+                    : (CodeExpression) new CodeBinaryOperatorExpression(\r
+                        equals,\r
+                        CodeBinaryOperatorType.BooleanAnd,\r
+                        compare);\r
+            }\r
+            method.Statements.Add(\r
+                    new CodeMethodReturnStatement(equals));\r
+        }\r
+\r
+        void GenerateEntityChildren(CodeTypeDeclaration entity, Table table, Database schema)\r
+        {\r
+            var children = GetClassChildren(table);\r
+            if (children.Any())\r
+            {\r
+                var childMembers = new List<CodeTypeMember>();\r
+\r
+                foreach (var child in children)\r
+                {\r
+                    bool hasDuplicates = (from c in children where c.Member == child.Member select c).Count() > 1;\r
+\r
+                    // the following is apparently useless\r
+                    var targetTable = schema.Tables.FirstOrDefault(t => t.Type.Name == child.Type);\r
+                    if (targetTable == null)\r
+                    {\r
+                        //Logger.Write(Level.Error, "ERROR L143 target table class not found:" + child.Type);\r
+                        continue;\r
+                    }\r
+\r
+                    var childType = new CodeTypeReference("EntitySet", new CodeTypeReference(child.Type));\r
+                    var storage = GetStorageFieldName(child);\r
+                    entity.Members.Add(new CodeMemberField(childType, storage));\r
+\r
+                    var childName = hasDuplicates\r
+                        ? child.Member + "_" + string.Join("", child.OtherKeys.ToArray())\r
+                        : child.Member;\r
+                    var property = new CodeMemberProperty() {\r
+                        Name        = childName,\r
+                        Type        = childType,\r
+                        Attributes  = ToMemberAttributes(child),\r
+                        CustomAttributes = {\r
+                            new CodeAttributeDeclaration("Association",\r
+                                new CodeAttributeArgument("Storage", new CodePrimitiveExpression(GetStorageFieldName(child))),\r
+                                new CodeAttributeArgument("OtherKey", new CodePrimitiveExpression(child.OtherKey)),\r
+                                new CodeAttributeArgument("ThisKey", new CodePrimitiveExpression(child.ThisKey)),\r
+                                new CodeAttributeArgument("Name", new CodePrimitiveExpression(child.Name))),\r
+                            new CodeAttributeDeclaration("DebuggerNonUserCode"),\r
+                        },\r
+                    };\r
+                    childMembers.Add(property);\r
+                    property.GetStatements.Add(new CodeMethodReturnStatement(\r
+                            new CodeFieldReferenceExpression(thisReference, storage)));\r
+                    property.SetStatements.Add(new CodeAssignStatement(\r
+                            new CodeFieldReferenceExpression(thisReference, storage),\r
+                            new CodePropertySetValueReferenceExpression()));\r
+                }\r
+\r
+                if (childMembers.Count == 0)\r
+                    return;\r
+                childMembers.First().StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Children"));\r
+                childMembers.Last().EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, null));\r
+                entity.Members.AddRange(childMembers.ToArray());\r
+            }\r
+        }\r
+\r
+        IEnumerable<Association> GetClassChildren(Table table)\r
+        {\r
+            return table.Type.Associations.Where(a => !a.IsForeignKey);\r
+        }\r
+\r
+        static MemberAttributes ToMemberAttributes(Association association)\r
+        {\r
+            MemberAttributes attrs = 0;\r
+            if (!association.AccessModifierSpecified)\r
+                attrs |= MemberAttributes.Public;\r
+            else\r
+                switch (association.AccessModifier)\r
+                {\r
+                    case AccessModifier.Internal:           attrs = MemberAttributes.Assembly; break;\r
+                    case AccessModifier.Private:            attrs = MemberAttributes.Private; break;\r
+                    case AccessModifier.Protected:          attrs = MemberAttributes.Family; break;\r
+                    case AccessModifier.ProtectedInternal:  attrs = MemberAttributes.FamilyOrAssembly; break;\r
+                    case AccessModifier.Public:             attrs = MemberAttributes.Public; break;\r
+                    default:\r
+                        throw new ArgumentOutOfRangeException("association", "Modifier value '" + association.AccessModifierSpecified + "' is an unsupported value.");\r
+                }\r
+            if (!association.ModifierSpecified)\r
+                attrs |= MemberAttributes.Final;\r
+            else\r
+                switch (association.Modifier)\r
+                {\r
+                    case MemberModifier.New:        attrs |= MemberAttributes.New | MemberAttributes.Final; break;\r
+                    case MemberModifier.NewVirtual: attrs |= MemberAttributes.New; break;\r
+                    case MemberModifier.Override:   attrs |= MemberAttributes.Override; break;\r
+                    case MemberModifier.Virtual:    break;\r
+                }\r
+            return attrs;\r
+        }\r
+\r
+        static MemberAttributes ToMemberAttributes(Function function)\r
+        {\r
+            MemberAttributes attrs = 0;\r
+            if (!function.AccessModifierSpecified)\r
+                attrs |= MemberAttributes.Public;\r
+            else\r
+                switch (function.AccessModifier)\r
+                {\r
+                    case AccessModifier.Internal:           attrs = MemberAttributes.Assembly; break;\r
+                    case AccessModifier.Private:            attrs = MemberAttributes.Private; break;\r
+                    case AccessModifier.Protected:          attrs = MemberAttributes.Family; break;\r
+                    case AccessModifier.ProtectedInternal:  attrs = MemberAttributes.FamilyOrAssembly; break;\r
+                    case AccessModifier.Public:             attrs = MemberAttributes.Public; break;\r
+                    default:\r
+                        throw new ArgumentOutOfRangeException("function", "Modifier value '" + function.AccessModifierSpecified + "' is an unsupported value.");\r
+                }\r
+            if (!function.ModifierSpecified)\r
+                attrs |= MemberAttributes.Final;\r
+            else\r
+                switch (function.Modifier)\r
+                {\r
+                    case MemberModifier.New:        attrs |= MemberAttributes.New | MemberAttributes.Final; break;\r
+                    case MemberModifier.NewVirtual: attrs |= MemberAttributes.New; break;\r
+                    case MemberModifier.Override:   attrs |= MemberAttributes.Override; break;\r
+                    case MemberModifier.Virtual:    break;\r
+                }\r
+            return attrs;\r
+        }\r
+\r
+        static string GetStorageFieldName(Association association)\r
+        {\r
+            return association.Storage != null \r
+                ? GetStorageFieldName(association.Storage) \r
+                : "_" + CreateIdentifier(association.Member ?? association.Name);\r
+        }\r
+\r
+        static string CreateIdentifier(string value)\r
+        {\r
+            return Regex.Replace(value, @"\W", "_");\r
+        }\r
+\r
+        void GenerateEntityChildrenAttachment(CodeTypeDeclaration entity, Table table, Database schema)\r
+        {\r
+            var children = GetClassChildren(table).ToList();\r
+            if (!children.Any())\r
+                return;\r
+\r
+            var havePrimaryKeys = table.Type.Columns.Any(c => c.IsPrimaryKey);\r
+\r
+            var handlers = new List<CodeTypeMember>();\r
+\r
+            foreach (var child in children)\r
+            {\r
+                // the reverse child is the association seen from the child\r
+                // we're going to use it...\r
+                var reverseChild = schema.GetReverseAssociation(child);\r
+                // ... to get the parent name\r
+                var memberName = reverseChild.Member;\r
+\r
+                var sendPropertyChanging = new CodeExpressionStatement(\r
+                        new CodeMethodInvokeExpression(\r
+                            new CodeMethodReferenceExpression(thisReference, "SendPropertyChanging")));\r
+\r
+                var attach = new CodeMemberMethod() {\r
+                    Name = child.Member + "_Attach",\r
+                    Parameters = {\r
+                        new CodeParameterDeclarationExpression(child.Type, "entity"),\r
+                    },\r
+                };\r
+                handlers.Add(attach);\r
+                if (havePrimaryKeys)\r
+                    attach.Statements.Add(sendPropertyChanging);\r
+                attach.Statements.Add(\r
+                        new CodeAssignStatement(\r
+                            new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("entity"), memberName),\r
+                            thisReference));\r
+\r
+                var detach = new CodeMemberMethod() {\r
+                    Name = child.Member + "_Detach",\r
+                    Parameters = {\r
+                        new CodeParameterDeclarationExpression(child.Type, "entity"),\r
+                    },\r
+                };\r
+                handlers.Add(detach);\r
+                if (havePrimaryKeys)\r
+                    detach.Statements.Add(sendPropertyChanging);\r
+                detach.Statements.Add(\r
+                        new CodeAssignStatement(\r
+                            new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("entity"), memberName),\r
+                            new CodePrimitiveExpression(null)));\r
+            }\r
+\r
+            if (handlers.Count == 0)\r
+                return;\r
+\r
+            handlers.First().StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Attachment handlers"));\r
+            handlers.Last().EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, null));\r
+            entity.Members.AddRange(handlers.ToArray());\r
+        }\r
+\r
+        void GenerateEntityParents(CodeTypeDeclaration entity, Table table, Database schema)\r
+        {\r
+            var parents = table.Type.Associations.Where(a => a.IsForeignKey);\r
+            if (!parents.Any())\r
+                return;\r
+\r
+            var parentMembers = new List<CodeTypeMember>();\r
+\r
+            foreach (var parent in parents)\r
+            {\r
+                bool hasDuplicates = (from p in parents where p.Member == parent.Member select p).Count() > 1;\r
+                // WriteClassParent(writer, parent, hasDuplicates, schema, context);\r
+                // the following is apparently useless\r
+                DbLinq.Schema.Dbml.Table targetTable = schema.Tables.FirstOrDefault(t => t.Type.Name == parent.Type);\r
+                if (targetTable == null)\r
+                {\r
+                    //Logger.Write(Level.Error, "ERROR L191 target table type not found: " + parent.Type + "  (processing " + parent.Name + ")");\r
+                    continue;\r
+                }\r
+\r
+                string member = parent.Member;\r
+                string storageField = GetStorageFieldName(parent);\r
+                // TODO: remove this\r
+                if (member == parent.ThisKey)\r
+                {\r
+                    member = parent.ThisKey + targetTable.Type.Name; //repeat name to prevent collision (same as Linq)\r
+                    storageField = "_x_" + parent.Member;\r
+                }\r
+\r
+                var parentType = new CodeTypeReference(targetTable.Type.Name);\r
+                entity.Members.Add(new CodeMemberField(new CodeTypeReference("EntityRef", parentType), storageField) {\r
+                    InitExpression = new CodeObjectCreateExpression(new CodeTypeReference("EntityRef", parentType)),\r
+                });\r
+\r
+                var parentName = hasDuplicates\r
+                    ? member + "_" + string.Join("", parent.TheseKeys.ToArray())\r
+                    : member;\r
+                var property = new CodeMemberProperty() {\r
+                    Name        = parentName,\r
+                    Type        = parentType,\r
+                    Attributes  = ToMemberAttributes(parent),\r
+                    CustomAttributes = {\r
+                        new CodeAttributeDeclaration("Association",\r
+                            new CodeAttributeArgument("Storage", new CodePrimitiveExpression(storageField)),\r
+                            new CodeAttributeArgument("OtherKey", new CodePrimitiveExpression(parent.OtherKey)),\r
+                            new CodeAttributeArgument("ThisKey", new CodePrimitiveExpression(parent.ThisKey)),\r
+                            new CodeAttributeArgument("Name", new CodePrimitiveExpression(parent.Name)),\r
+                            new CodeAttributeArgument("IsForeignKey", new CodePrimitiveExpression(parent.IsForeignKey))),\r
+                        new CodeAttributeDeclaration("DebuggerNonUserCode"),\r
+                    },\r
+                };\r
+                parentMembers.Add(property);\r
+                property.GetStatements.Add(new CodeMethodReturnStatement(\r
+                        new CodePropertyReferenceExpression(\r
+                            new CodeFieldReferenceExpression(thisReference, storageField),\r
+                            "Entity")));\r
+\r
+                // algorithm is:\r
+                // 1.1. must be different than previous value\r
+                // 1.2. or HasLoadedOrAssignedValue is false (but why?)\r
+                // 2. implementations before change\r
+                // 3. if previous value not null\r
+                // 3.1. place parent in temp variable\r
+                // 3.2. set [Storage].Entity to null\r
+                // 3.3. remove it from parent list\r
+                // 4. assign value to [Storage].Entity\r
+                // 5. if value is not null\r
+                // 5.1. add it to parent list\r
+                // 5.2. set FK members with entity keys\r
+                // 6. else\r
+                // 6.1. set FK members to defaults (null or 0)\r
+                // 7. implementationas after change\r
+                var otherAssociation = schema.GetReverseAssociation(parent);\r
+                var parentEntity = new CodePropertyReferenceExpression(\r
+                        new CodeFieldReferenceExpression(thisReference, storageField),\r
+                        "Entity");\r
+                var parentTable = schema.Tables.Single(t => t.Type.Associations.Contains(parent));\r
+                var childKeys = parent.TheseKeys.ToArray();\r
+                var childColumns = (from ck in childKeys select table.Type.Columns.Single(c => c.Member == ck))\r
+                                    .ToArray();\r
+                var parentKeys = parent.OtherKeys.ToArray();\r
+                property.SetStatements.Add(new CodeConditionStatement(\r
+                        // 1.1\r
+                        ValuesAreNotEqual_Ref(parentEntity, new CodePropertySetValueReferenceExpression()),\r
+                        // 2. TODO: code before the change\r
+                        // 3. \r
+                        new CodeConditionStatement(\r
+                            ValueIsNotNull(parentEntity),\r
+                            // 3.1\r
+                            new CodeVariableDeclarationStatement(parentType, "previous" + parent.Type, parentEntity),\r
+                            // 3.2\r
+                            new CodeAssignStatement(parentEntity, new CodePrimitiveExpression(null)),\r
+                            // 3.3\r
+                            new CodeExpressionStatement(\r
+                                 new CodeMethodInvokeExpression(\r
+                                    new CodeMethodReferenceExpression(\r
+                                        new CodePropertyReferenceExpression(\r
+                                            new CodeVariableReferenceExpression("previous" + parent.Type),\r
+                                            otherAssociation.Member),\r
+                                        "Remove"),\r
+                                    thisReference))),\r
+                        // 4.\r
+                        new CodeAssignStatement(parentEntity, new CodePropertySetValueReferenceExpression()),\r
+                        // 5. if value is null or not...\r
+                        new CodeConditionStatement(\r
+                            ValueIsNotNull(new CodePropertySetValueReferenceExpression()),\r
+                            // 5.1\r
+                            new CodeStatement[]{\r
+                                new CodeExpressionStatement(\r
+                                    new CodeMethodInvokeExpression(\r
+                                        new CodeMethodReferenceExpression(\r
+                                            new CodePropertyReferenceExpression(\r
+                                                new CodePropertySetValueReferenceExpression(),\r
+                                                otherAssociation.Member),\r
+                                            "Add"),\r
+                                        thisReference))\r
+                            // 5.2\r
+                            }.Concat(Enumerable.Range(0, parentKeys.Length).Select(i =>\r
+                                (CodeStatement) new CodeAssignStatement(\r
+                                    new CodeVariableReferenceExpression(GetStorageFieldName(childColumns[i])),\r
+                                    new CodePropertyReferenceExpression(\r
+                                        new CodePropertySetValueReferenceExpression(),\r
+                                        parentKeys[i]))\r
+                            )).ToArray(),\r
+                            // 6.\r
+                            Enumerable.Range(0, parentKeys.Length).Select(i => {\r
+                                var column = parentTable.Type.Columns.Single(c => c.Member == childKeys[i]);\r
+                                return (CodeStatement) new CodeAssignStatement(\r
+                                    new CodeVariableReferenceExpression(GetStorageFieldName(childColumns[i])),\r
+                                    column.CanBeNull\r
+                                        ? (CodeExpression) new CodePrimitiveExpression(null)\r
+                                        : (CodeExpression) new CodeDefaultValueExpression(new CodeTypeReference(column.Type)));\r
+                            }).ToArray())\r
+                        // 7: TODO\r
+                ));\r
+            }\r
+\r
+            if (parentMembers.Count == 0)\r
+                return;\r
+            parentMembers.First().StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Parents"));\r
+            parentMembers.Last().EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, null));\r
+            entity.Members.AddRange(parentMembers.ToArray());\r
+        }\r
+    }\r
+}\r
index 36dc76c68d8bc99429d6c8d5b6d91c3636bbae70..8a9eb415f44e09e81279ca4d491fe5c9a673d9aa 100644 (file)
@@ -139,15 +139,18 @@ namespace DbMetal.Generator
             using (WriteEnum(specificationDefinition, name))\r
             {\r
                 var orderedValues = from nv in values orderby nv.Value select nv;\r
-                int currentValue = 1;\r
+                int currentValue = 1, counter = 0;\r
                 foreach (var nameValue in orderedValues)\r
                 {\r
+\r
+                    var suffix = ++counter < orderedValues.Count() ? "," : "";\r
+\r
                     if (nameValue.Value == currentValue)\r
-                        WriteLine(string.Format("{0},", nameValue.Key));\r
+                        WriteLine(string.Format("{0}{1}", nameValue.Key, suffix));\r
                     else\r
                     {\r
                         currentValue = nameValue.Value;\r
-                        WriteLine(string.Format("{0} = {1},", nameValue.Key, nameValue.Value));\r
+                        WriteLine(string.Format("{0} = {1}{2}", nameValue.Key, nameValue.Value, suffix));\r
                     }\r
                     currentValue++;\r
                 }\r
index 3a8c5806c5eb1d1a34835a805a22ea6af1a6bd02..ecae22bee6a24bf014bbc87fb78dc0b2a7cd34ea 100644 (file)
@@ -39,13 +39,6 @@ namespace DbMetal.Generator
         /// </summary>\r
         ISchemaLoader Load(Parameters parameters);\r
 \r
-        /// <summary>\r
-        /// loads a ISchemaLoader from a provider id string (used by schema loader)\r
-        /// </summary>\r
-        /// <param name="provider"></param>\r
-        /// <returns></returns>\r
-        ISchemaLoader Load(string provider);\r
-\r
         /// <summary>\r
         /// given a schemaLoaderType and dbConnType \r
         /// (e.g. DbLinq.Oracle.OracleSchemaLoader and System.Data.OracleClient.OracleConnection),\r
index 7f5369a0e9bae7a374d0f75f23945d6605a2db23..00c0350fd9456580c6994d4a1703b3c1170a2227 100644 (file)
@@ -34,8 +34,8 @@ namespace DbMetal.Generator.Implementation.CodeTextGenerator
 #endif\r
     class CSCodeGenerator : CodeGenerator\r
     {\r
-        public override string LanguageCode { get { return "C#"; } }\r
-        public override string Extension { get { return ".cs"; } }\r
+        public override string LanguageCode { get { return "obsolete-c#"; } }\r
+        public override string Extension { get { return ".obsolete-cs"; } }\r
 \r
         protected override CodeWriter CreateCodeWriter(TextWriter textWriter)\r
         {\r
index 345129abf0d57cf6b834af0aad73aa9b6ab0f52b..cd41a57c30f6097e757adb9d80aaf8e946793a77 100644 (file)
@@ -76,8 +76,6 @@ namespace DbMetal.Generator.Implementation.CodeTextGenerator
 \r
             var tableAttribute = NewAttributeDefinition<TableAttribute>();\r
             tableAttribute["Name"] = table.Name;\r
-            //using (WriteAttributes(writer, context.Parameters.EntityExposedAttributes))\r
-            using (WriteAttributes(writer, GetAttributeNames(context, context.Parameters.EntityExposedAttributes)))\r
             using (writer.WriteAttribute(tableAttribute))\r
             using (writer.WriteClass(specifications,\r
                                      table.Type.Name, entityBase, context.Parameters.EntityInterfaces))\r
@@ -86,7 +84,7 @@ namespace DbMetal.Generator.Implementation.CodeTextGenerator
                 WriteCustomTypes(writer, table, schema, context);\r
                 WriteClassExtensibilityDeclarations(writer, table, context);\r
                 WriteClassProperties(writer, table, context);\r
-                if (context.Parameters.GenerateEqualsAndHash)\r
+                if (context.Parameters.GenerateEqualsHash)\r
                     WriteClassEqualsAndHash(writer, table, context);\r
                 WriteClassChildren(writer, table, schema, context);\r
                 WriteClassParents(writer, table, schema, context);\r
@@ -119,13 +117,12 @@ namespace DbMetal.Generator.Implementation.CodeTextGenerator
                         var member = writer.GetVariableExpression(primaryKey.Storage);\r
                         string primaryKeyHashCode = writer.GetMethodCallExpression(writer.GetMemberExpression(member, "GetHashCode"));\r
                         if (primaryKey.CanBeNull\r
-                        || primaryKey.ExtendedType == null\r
                         || GetType(primaryKey.Type, false).IsClass) // this patch to ensure that even if DB does not allow nulls,\r
                         // our in-memory object won't generate a fault\r
                         {\r
                             var isNullExpression = writer.GetEqualExpression(member, writer.GetNullExpression());\r
                             var nullExpression = writer.GetLiteralValue(0);\r
-                            primaryKeyHashCode = writer.GetTernaryExpression(isNullExpression, nullExpression, primaryKeyHashCode);\r
+                            primaryKeyHashCode = "(" + writer.GetTernaryExpression(isNullExpression, nullExpression, primaryKeyHashCode) + ")";\r
                         }\r
                         if (string.IsNullOrEmpty(hashCode))\r
                             hashCode = primaryKeyHashCode;\r
@@ -154,9 +151,14 @@ namespace DbMetal.Generator.Implementation.CodeTextGenerator
                     foreach (var primaryKey in primaryKeys)\r
                     {\r
                         var member = writer.GetVariableExpression(primaryKey.Storage);\r
-                        string primaryKeyTest = writer.GetMethodCallExpression(writer.GetMemberExpression(writer.GetLiteralType(typeof(object)), "Equals"),\r
-                                                                               member,\r
-                                                                               writer.GetMemberExpression(other, member));\r
+                        string primaryKeyTest = writer.GetMethodCallExpression(\r
+                                writer.GetMemberExpression(\r
+                                    writer.GetMemberExpression(\r
+                                        writer.GetGenericName("System.Collections.Generic.EqualityComparer", primaryKey.Type),\r
+                                        "Default"),\r
+                                    "Equals"),\r
+                                member,\r
+                                writer.GetMemberExpression(other, member));\r
                         if (string.IsNullOrEmpty(andExpression))\r
                             andExpression = primaryKeyTest;\r
                         else\r
@@ -269,7 +271,7 @@ namespace DbMetal.Generator.Implementation.CodeTextGenerator
         /// <param name="context"></param>\r
         /// <param name="attributes"></param>\r
         /// <returns></returns>\r
-        protected virtual string[] GetAttributeNames(GenerationContext context, string[] attributes)\r
+        protected virtual string[] GetAttributeNames(GenerationContext context, IEnumerable<string> attributes)\r
         {\r
             return (from a in attributes select GetName(a)).ToArray();\r
         }\r
@@ -325,7 +327,7 @@ namespace DbMetal.Generator.Implementation.CodeTextGenerator
                 specifications |= GetSpecificationDefinition(property.Modifier);\r
 \r
             //using (WriteAttributes(writer, context.Parameters.MemberExposedAttributes))\r
-            using (WriteAttributes(writer, GetAttributeNames(context, context.Parameters.MemberExposedAttributes)))\r
+            using (WriteAttributes(writer, GetAttributeNames(context, context.Parameters.MemberAttributes)))\r
             using (writer.WriteAttribute(NewAttributeDefinition<DebuggerNonUserCodeAttribute>()))\r
             using (writer.WriteAttribute(column))\r
             using (writer.WriteProperty(specifications, property.Member, GetTypeOrExtendedType(writer, property)))\r
index bc3a7e28b7084e176bace17f84177ad590ac035b..690f04702f9cbd6ee48a82ca654dff81ffeea756 100644 (file)
@@ -177,12 +177,8 @@ namespace DbMetal.Generator.Implementation.CodeTextGenerator
                 implementation.WriteHeader(writer, context);\r
 \r
             // write namespaces for members attributes\r
-            foreach (var memberExposedAttribute in context.Parameters.MemberExposedAttributes)\r
-                WriteUsingNamespace(writer, GetNamespace(memberExposedAttribute));\r
-\r
-            // write namespaces for clases attributes\r
-            foreach (var entityExposedAttribute in context.Parameters.EntityExposedAttributes)\r
-                WriteUsingNamespace(writer, GetNamespace(entityExposedAttribute));\r
+            foreach (var memberAttribute in context.Parameters.MemberAttributes)\r
+                WriteUsingNamespace(writer, GetNamespace(memberAttribute));\r
 \r
             writer.WriteLine();\r
         }\r
@@ -224,12 +220,10 @@ namespace DbMetal.Generator.Implementation.CodeTextGenerator
 \r
 \r
             string contextBase = schema.BaseType;\r
-            var contextBaseType = TypeLoader.Load(contextBase);\r
-            // if we don't specify a base type, use the default\r
-            if (string.IsNullOrEmpty(contextBase))\r
-            {\r
-                contextBaseType = typeof(DataContext);\r
-            }\r
+            var contextBaseType = string.IsNullOrEmpty(contextBase)\r
+                ? typeof(DataContext)\r
+                : TypeLoader.Load(contextBase);\r
+\r
             // in all cases, get the literal type name from loaded type\r
             contextBase = writer.GetLiteralType(contextBaseType);\r
 \r
index 5a93e5031d54e57defe9fb064dbb843cdbfd0bf9..f3dee040a3354f788bcdf59af7ec2ad3548c0075 100644 (file)
@@ -72,37 +72,31 @@ namespace DbMetal.Generator.Implementation
         {\r
             var parameters = new Parameters { Log = Log };\r
 \r
-            if (args.Length == 0)\r
-                PrintUsage(parameters);\r
+            parameters.WriteHeader();\r
 \r
-            else\r
+            try\r
             {\r
-                parameters.WriteHeader();\r
-\r
-                try\r
-                {\r
-                    parameters.Parse(args);\r
-                }\r
-                catch (Exception e)\r
-                {\r
-                    Output.WriteErrorLine(Log, e.Message);\r
-                    PrintUsage(parameters);\r
-                    return;\r
-                }\r
+                parameters.Parse(args);\r
+            }\r
+            catch (Exception e)\r
+            {\r
+                Output.WriteErrorLine(Log, e.Message);\r
+                PrintUsage(parameters);\r
+                return;\r
+            }\r
 \r
-                if (parameters.Help)\r
-                {\r
-                    PrintUsage(parameters);\r
-                    return;\r
-                }\r
+            if (args.Length == 0 || parameters.Help)\r
+            {\r
+                PrintUsage(parameters);\r
+                return;\r
+            }\r
 \r
-                ProcessSchema(parameters);\r
+            ProcessSchema(parameters);\r
 \r
-                if (parameters.ReadLineAtExit)\r
-                {\r
-                    // '-readLineAtExit' flag: useful when running from Visual Studio\r
-                    Console.ReadKey();\r
-                }\r
+            if (parameters.Readline)\r
+            {\r
+                // '-readLineAtExit' flag: useful when running from Visual Studio\r
+                Console.ReadKey();\r
             }\r
         }\r
 \r
@@ -114,14 +108,47 @@ namespace DbMetal.Generator.Implementation
                 ISchemaLoader schemaLoader;\r
                 // then we load the schema\r
                 var dbSchema = ReadSchema(parameters, out schemaLoader);\r
+\r
+                if (!SchemaIsValid(dbSchema))\r
+                    return;\r
+\r
                 // the we write it (to DBML or code)\r
                 WriteSchema(dbSchema, schemaLoader, parameters);\r
             }\r
             catch (Exception ex)\r
             {\r
                 string assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;\r
-                Output.WriteErrorLine(Log, assemblyName + " failed:" + ex);\r
+                Log.WriteErrorLine(assemblyName + ": {0}", parameters.Debug ? ex.ToString() : ex.Message);\r
+            }\r
+        }\r
+\r
+        bool SchemaIsValid(Database database)\r
+        {\r
+            bool error = false;\r
+            foreach (var table in database.Tables)\r
+            {\r
+                error = ValidateAssociations(database, table) || error;\r
             }\r
+            return !error;\r
+        }\r
+\r
+        bool ValidateAssociations(Database database, Table table)\r
+        {\r
+            bool error = false;\r
+            foreach (var association in table.Type.Associations)\r
+            {\r
+                var otherType           = database.Tables.Single(t => t.Type.Name == association.Type).Type;\r
+                var otherAssociation    = otherType.Associations.Single(a => a.Type == table.Type.Name && a.ThisKey == association.OtherKey);\r
+                var otherColumn         = otherType.Columns.Single(c => c.Member == association.OtherKey);\r
+\r
+                if (association.CardinalitySpecified && association.Cardinality == Cardinality.Many && association.IsForeignKey)\r
+                {\r
+                    error = true;\r
+                    Log.WriteErrorLine("Error DBML1059: The IsForeignKey attribute of the Association element '{0}' of the Type element '{1}' cannnot be '{2}' when the Cardinality attribute is '{3}'.",\r
+                            association.Name, table.Type.Name, association.IsForeignKey, association.Cardinality);\r
+                }\r
+            }\r
+            return error;\r
         }\r
 \r
         protected void WriteSchema(Database dbSchema, ISchemaLoader schemaLoader, Parameters parameters)\r
@@ -147,9 +174,6 @@ namespace DbMetal.Generator.Implementation
                 if (string.IsNullOrEmpty(filename))\r
                     filename = dbSchema.Name;\r
 \r
-                // TODO: move such check to runtime.\r
-                schemaLoader.CheckNamesSafety(dbSchema);\r
-\r
                 parameters.Write("<<< writing C# classes in file '{0}'", filename);\r
                 GenerateCode(parameters, dbSchema, schemaLoader, filename);\r
 \r
@@ -182,7 +206,7 @@ namespace DbMetal.Generator.Implementation
 \r
         protected virtual ICodeGenerator FindCodeGeneratorByExtension(string extension)\r
         {\r
-            return EnumerateCodeGenerators().SingleOrDefault(gen => gen.Extension == extension);\r
+            return EnumerateCodeGenerators().SingleOrDefault(gen => gen.Extension == extension.ToLowerInvariant());\r
         }\r
 \r
         public virtual ICodeGenerator FindCodeGenerator(Parameters parameters, string filename)\r
@@ -194,9 +218,10 @@ namespace DbMetal.Generator.Implementation
 \r
         public void GenerateCode(Parameters parameters, Database dbSchema, ISchemaLoader schemaLoader, string filename)\r
         {\r
-            ICodeGenerator codeGenerator = FindCodeGenerator(parameters, filename);\r
-            if (codeGenerator == null)\r
-                throw new ArgumentException("Please specify either a /language or a /code file");\r
+            ICodeGenerator codeGenerator = FindCodeGenerator(parameters, filename) ??\r
+                (string.IsNullOrEmpty(parameters.Language)\r
+                    ? CodeDomGenerator.CreateFromFileExtension(Path.GetExtension(filename))\r
+                    : CodeDomGenerator.CreateFromLanguage(parameters.Language));\r
 \r
             if (string.IsNullOrEmpty(filename))\r
                 filename = dbSchema.Class;\r
@@ -232,7 +257,8 @@ namespace DbMetal.Generator.Implementation
             else // load DBML\r
             {\r
                 dbSchema = ReadSchema(parameters, parameters.SchemaXmlFile);\r
-                schemaLoader = SchemaLoaderFactory.Load(dbSchema.Provider);\r
+                parameters.Provider = parameters.Provider ?? dbSchema.Provider;\r
+                schemaLoader = SchemaLoaderFactory.Load(parameters);\r
             }\r
 \r
             if (schemaLoader == null)\r
index cd06ffd4157f8290151728093e5d4a5383e61f5a..fe8662c05999a7f6ccf8782a14329a2b129c66ff 100644 (file)
@@ -60,27 +60,9 @@ namespace DbMetal.Generator.Implementation
             string databaseConnectionType;\r
             string sqlDialectType;\r
             GetLoaderAndConnection(parameters, out dbLinqSchemaLoaderType, out databaseConnectionType, out sqlDialectType);\r
-            if (dbLinqSchemaLoaderType == null)\r
-                throw new ApplicationException("Please provide -Provider=MySql (or Oracle, OracleODP, PostgreSql, Sqlite - see app.config for provider listing)");\r
             return Load(parameters, dbLinqSchemaLoaderType, databaseConnectionType, sqlDialectType);\r
         }\r
 \r
-        /// <summary>\r
-        /// loads a ISchemaLoader from a provider id string (used by schema loader)\r
-        /// </summary>\r
-        /// <param name="provider"></param>\r
-        /// <returns></returns>\r
-        public ISchemaLoader Load(string provider)\r
-        {\r
-            string dbLinqSchemaLoaderType;\r
-            string databaseConnectionType;\r
-            string sqlDialectType;\r
-            GetLoaderAndConnection(provider, out dbLinqSchemaLoaderType, out databaseConnectionType, out sqlDialectType);\r
-            if (dbLinqSchemaLoaderType == null)\r
-                return null;\r
-            return Load(null, dbLinqSchemaLoaderType, databaseConnectionType, sqlDialectType);\r
-        }\r
-\r
         /// <summary>\r
         /// given a schemaLoaderType and dbConnType \r
         /// (e.g. DbLinq.Oracle.OracleSchemaLoader and System.Data.OracleClient.OracleConnection),\r
@@ -140,106 +122,20 @@ namespace DbMetal.Generator.Implementation
 \r
         public ISchemaLoader Load(Parameters parameters, string dbLinqSchemaLoaderTypeName, string databaseConnectionTypeName, string sqlDialectTypeName)\r
         {\r
-            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;\r
             Type dbLinqSchemaLoaderType = Type.GetType(dbLinqSchemaLoaderTypeName);\r
             Type databaseConnectionType = Type.GetType(databaseConnectionTypeName);\r
             Type sqlDialectType         = string.IsNullOrEmpty(sqlDialectTypeName) ? null : Type.GetType(sqlDialectTypeName);\r
 \r
             if (dbLinqSchemaLoaderType == null)\r
-                throw new ArgumentException("Unable to resolve dbLinqSchemaLoaderType: " + dbLinqSchemaLoaderTypeName);\r
+                throw new ArgumentException("Could not load dbLinqSchemaLoaderType type '" + dbLinqSchemaLoaderTypeName + "'.  Try using the --with-schema-loader=TYPE option.");\r
             if (databaseConnectionType == null)\r
-                throw new ArgumentException("Unable to resolve databaseConnectionType: " + databaseConnectionTypeName);\r
+                throw new ArgumentException("Could not load databaseConnectionType type '" + databaseConnectionTypeName + "'.  Try using the --with-dbconnection=TYPE option.");\r
 \r
             ISchemaLoader loader = Load(parameters, dbLinqSchemaLoaderType, databaseConnectionType, sqlDialectType);\r
-            AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;\r
             return loader;\r
         }\r
 \r
-        private Assembly LoadAssembly(string path)\r
-        {\r
-            if (File.Exists(path))\r
-                return Assembly.LoadFile(path);\r
-            return null;\r
-        }\r
-\r
-        private Assembly LoadAssembly(string baseName, string path)\r
-        {\r
-            string basePath = Path.Combine(path, baseName);\r
-            Assembly assembly = LoadAssembly(basePath + ".dll");\r
-            if (assembly == null)\r
-                assembly = LoadAssembly(basePath + ".exe");\r
-            return assembly;\r
-        }\r
-\r
-        private Assembly LocalLoadAssembly(string baseName)\r
-        {\r
-            Assembly assembly = LoadAssembly(baseName, Directory.GetCurrentDirectory());\r
-            if (assembly == null) {\r
-                var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().CodeBase);\r
-                assembly = LoadAssembly(baseName, path);\r
-            }\r
-            return assembly;\r
-        }\r
-\r
-        private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\r
-        {\r
-            // try to load from within the current AppDomain\r
-            IList<Assembly> assemblies = AppDomain.CurrentDomain.GetAssemblies();\r
-            foreach (Assembly loadedAssembly in assemblies)\r
-            {\r
-                if (loadedAssembly.GetName().Name == args.Name)\r
-                    return loadedAssembly;\r
-            }\r
-            var assembly = LocalLoadAssembly(args.Name);\r
-            if (assembly == null)\r
-                assembly = GacLoadAssembly(args.Name);\r
-            return assembly;\r
-        }\r
-\r
-        /// <summary>\r
-        /// This is dirty, and must not be used in production environment\r
-        /// </summary>\r
-        /// <param name="shortName"></param>\r
-        /// <returns></returns>\r
-        private Assembly GacLoadAssembly(string shortName)\r
-        {\r
-            var systemRoot = Environment.GetEnvironmentVariable("SystemRoot");\r
-            string assemblyDirectory = Path.Combine(systemRoot, "Assembly");\r
-            var assembly = GacLoadAssembly(shortName, Path.Combine(assemblyDirectory, "GAC_MSIL"));\r
-            if (assembly == null)\r
-                assembly = GacLoadAssembly(shortName, Path.Combine(assemblyDirectory, "GAC_32"));\r
-            if (assembly == null)\r
-                assembly = GacLoadAssembly(shortName, Path.Combine(assemblyDirectory, "GAC"));\r
-            return assembly;\r
-        }\r
-\r
-        private Assembly GacLoadAssembly(string shortName, string directory)\r
-        {\r
-            string assemblyDirectory = Path.Combine(directory, shortName);\r
-            if (Directory.Exists(assemblyDirectory))\r
-            {\r
-                Version latestVersion = null;\r
-                string latestVersionDirectory = null;\r
-                foreach (string versionDirectory in Directory.GetDirectories(assemblyDirectory))\r
-                {\r
-                    var testVersion = new Version(Path.GetFileName(versionDirectory).Split('_')[0]);\r
-                    if (latestVersion == null || testVersion.CompareTo(latestVersion) > 0)\r
-                    {\r
-                        latestVersion = testVersion;\r
-                        latestVersionDirectory = versionDirectory;\r
-                    }\r
-                }\r
-                if (latestVersionDirectory != null)\r
-                {\r
-                    string assemblyPath = Path.Combine(latestVersionDirectory, shortName + ".dll");\r
-                    if (File.Exists(assemblyPath))\r
-                        return Assembly.LoadFile(assemblyPath);\r
-                }\r
-            }\r
-            return null;\r
-        }\r
-\r
-        protected void GetLoaderAndConnection(string provider, out string dbLinqSchemaLoaderType, out string databaseConnectionType, out string sqlDialectType)\r
+        private void GetLoaderAndConnection(string provider, out string dbLinqSchemaLoaderType, out string databaseConnectionType, out string sqlDialectType)\r
         {\r
             var configuration = (ProvidersSection)ConfigurationManager.GetSection("providers");\r
 \r
@@ -247,8 +143,7 @@ namespace DbMetal.Generator.Implementation
             string errorMsg = null;\r
             if (configuration == null || !configuration.Providers.TryGetProvider(provider, out element, out errorMsg))\r
             {\r
-                Output.WriteErrorLine(Log, "Failed to load provider {0} : {1}", provider, errorMsg);\r
-                throw new ApplicationException("Failed to load provider " + provider);\r
+                throw new ApplicationException(string.Format("Failed to load provider {0}: {1}", provider, errorMsg));\r
             }\r
 \r
             //var element = configuration.Providers.GetProvider(provider);\r
@@ -260,22 +155,33 @@ namespace DbMetal.Generator.Implementation
 \r
         protected void GetLoaderAndConnection(Parameters parameters, out string dbLinqSchemaLoaderType, out string databaseConnectionType, out string sqlDialectType)\r
         {\r
+            dbLinqSchemaLoaderType = databaseConnectionType = sqlDialectType = null;\r
+\r
             if (!string.IsNullOrEmpty(parameters.Provider))\r
             {\r
                 GetLoaderAndConnection(parameters.Provider, out dbLinqSchemaLoaderType, out databaseConnectionType, out sqlDialectType);\r
             }\r
-            else\r
+            else if (!string.IsNullOrEmpty(parameters.DbLinqSchemaLoaderProvider) &&\r
+                !string.IsNullOrEmpty(parameters.DatabaseConnectionProvider) &&\r
+                !string.IsNullOrEmpty(parameters.SqlDialectType))\r
             {\r
-                dbLinqSchemaLoaderType = parameters.DbLinqSchemaLoaderProvider;\r
-                databaseConnectionType = parameters.DatabaseConnectionProvider;\r
-                sqlDialectType         = parameters.SqlDialectType;\r
+                // User manually specified everything we need; don't bother with the\r
+                // default .exe.config provider lookup\r
             }\r
-            if (string.IsNullOrEmpty(dbLinqSchemaLoaderType))\r
+            else\r
             {\r
                 // No provider specified, not explicitly provided either\r
                 // Default to using SQL Server for sqlmetal.exe compatibility\r
                 GetLoaderAndConnection("SqlServer", out dbLinqSchemaLoaderType, out databaseConnectionType, out sqlDialectType);\r
             }\r
+\r
+            // Allow command-line options to override the .exe.config file.\r
+            if (!string.IsNullOrEmpty(parameters.DbLinqSchemaLoaderProvider))\r
+                dbLinqSchemaLoaderType = parameters.DbLinqSchemaLoaderProvider;\r
+            if (!string.IsNullOrEmpty(parameters.DatabaseConnectionProvider))\r
+                databaseConnectionType = parameters.DatabaseConnectionProvider;\r
+            if (!string.IsNullOrEmpty(parameters.SqlDialectType))\r
+                sqlDialectType = parameters.SqlDialectType;\r
         }\r
 \r
     }\r
index 9d6eb21255cdb5f779708e6878af78b8f821ba18..c9bd728c20d4c8f9567677f134d75949fcc91d32 100644 (file)
@@ -41,70 +41,62 @@ namespace DbMetal
     {\r
         /// <summary>\r
         /// user name for database access\r
-        /// SQLMetal compatible\r
         /// </summary>\r
         public string User { get; set; }\r
 \r
         /// <summary>\r
         /// user password for database access\r
-        /// SQLMetal compatible\r
         /// </summary>\r
         public string Password { get; set; }\r
 \r
         /// <summary>\r
         /// server host name\r
-        /// SQLMetal compatible\r
         /// </summary>\r
         public string Server { get; set; }\r
 \r
         /// <summary>\r
         /// database name\r
-        /// SQLMetal compatible\r
         /// </summary>\r
         public string Database { get; set; }\r
 \r
         /// <summary>\r
         /// This connection string if present overrides User, Password, Server.\r
         /// Database is always used to generate the specific DataContext name\r
-        /// SQLMetal compatible\r
         /// </summary>\r
         public string Conn { get; set; }\r
 \r
         /// <summary>\r
         /// the namespace to put our classes into\r
-        /// SQLMetal compatible\r
         /// </summary>\r
         public string Namespace { get; set; }\r
 \r
         /// <summary>\r
         /// the language to generate classes for\r
-        /// SQLMetal compatible\r
         /// </summary>\r
         public string Language { get; set; }\r
 \r
         /// <summary>\r
         /// If present, write out C# code\r
-        /// SQLMetal compatible\r
         /// </summary>\r
         public string Code { get; set; }\r
 \r
         /// <summary>\r
-        /// If present, write out DBML XML representing the DB\r
-        /// SQLMetal compatible\r
+        /// if present, write out DBML XML representing the DB\r
         /// </summary>\r
         public string Dbml { get; set; }\r
 \r
         /// <summary>\r
         /// when true, we will call Singularize()/Pluralize() functions.\r
-        /// SQLMetal compatible\r
         /// </summary>\r
         public bool Pluralize { get; set; }\r
 \r
+        /// <summary>\r
+        /// the culture used for word recognition and pluralization\r
+        /// </summary>\r
         public string Culture { get; set; }\r
 \r
         /// <summary>\r
-        /// Load object renamings from an xml file\r
-        /// DbLinq specific\r
+        /// load object renamings from an xml file\r
         /// </summary>\r
         public string Aliases { get; set; }\r
 \r
@@ -123,93 +115,84 @@ namespace DbMetal
 \r
         /// <summary>\r
         /// base class from which all generated entities will inherit\r
-        /// SQLMetal compatible\r
         /// </summary>\r
         public string EntityBase { get; set; }\r
 \r
         /// <summary>\r
-        /// Interfaces to be implemented\r
+        /// interfaces to be implemented\r
         /// </summary>\r
         public string[] EntityInterfaces { get; set; }\r
 \r
         /// <summary>\r
-        /// Extra attributes to be implemented by class\r
-        /// </summary>\r
-        public string EntityAttributes { get; set; }\r
-        public string[] EntityExposedAttributes { get { return GetArray(EntityAttributes); } }\r
-\r
-        /// <summary>\r
-        /// Extra attributes to be implemented by class\r
+        /// extra attributes to be implemented by class members\r
         /// </summary>\r
-        public string MemberAttributes { get; set; }\r
-        public string[] MemberExposedAttributes { get { return GetArray(MemberAttributes); } }\r
+        public IList<string> MemberAttributes { get; set; }\r
 \r
         /// <summary>\r
-        /// base class from which all generated entities will inherit\r
-        /// SQLMetal compatible\r
+        /// generate Equals() and GetHashCode()\r
         /// </summary>\r
-        public bool GenerateEqualsAndHash { get; set; }\r
+        public bool GenerateEqualsHash { get; set; }\r
 \r
         /// <summary>\r
         /// export stored procedures\r
-        /// SQLMetal compatible\r
         /// </summary>\r
         public bool Sprocs { get; set; }\r
 \r
         /// <summary>\r
         /// preserve case of database names\r
-        /// DbLinq specific\r
         /// </summary>\r
         public string Case { get; set; }\r
 \r
-        bool useDomainTypes = true;\r
-\r
-        /// <summary>\r
-        /// if true, and PostgreSql database contains DOMAINS (typedefs), \r
-        /// we will generate code DbType='DerivedType'.\r
-        /// if false, generate code DbType='BaseType'.\r
-        /// DbLinq specific\r
-        /// </summary>\r
-        public bool UseDomainTypes\r
-        {\r
-            get { return useDomainTypes; }\r
-            set { useDomainTypes = value; }\r
-        }\r
-\r
         /// <summary>\r
         /// force a Console.ReadKey at end of program.\r
         /// Useful when running from Studio, so the output window does not disappear\r
         /// picrap comment: you may use the tool to write output to Visual Studio output window instead of a console window\r
-        /// DbLinq specific\r
         /// </summary>\r
-        public bool ReadLineAtExit { get; set; }\r
+        public bool Readline { get; set; }\r
 \r
         /// <summary>\r
         /// specifies a provider (which here is a pair or ISchemaLoader and IDbConnection implementors)\r
-        /// SQLMetal compatible\r
         /// </summary>\r
         public string Provider { get; set; }\r
 \r
         /// <summary>\r
-        /// For fine tuning, we allow to specifiy an ISchemaLoader\r
-        /// DbLinq specific\r
+        /// for fine tuning, we allow to specifiy an ISchemaLoader\r
         /// </summary>\r
         public string DbLinqSchemaLoaderProvider { get; set; }\r
 \r
         /// <summary>\r
-        /// For fine tuning, we allow to specifiy an IDbConnection\r
-        /// DbLinq specific\r
+        /// for fine tuning, we allow to specifiy an IDbConnection\r
         /// </summary>\r
         public string DatabaseConnectionProvider { get; set; }\r
 \r
+        /// <summary>\r
+        /// the SQL dialect used by the database\r
+        /// </summary>\r
         public string SqlDialectType { get; set; }\r
 \r
+        /// <summary>\r
+        /// the types to be generated\r
+        /// </summary>\r
         public IList<string> GenerateTypes { get; set; }\r
 \r
+        /// <summary>\r
+        /// if true, put a timestamp comment before the generated code\r
+        /// </summary>\r
         public bool GenerateTimestamps { get; set; }\r
 \r
+        /// <summary>\r
+        /// show help\r
+        /// </summary>\r
         public bool Help { get; set; }\r
 \r
+        /// <summary>\r
+        /// Show stack traces in error messages, etc., instead of just the message.\r
+        /// </summary>\r
+        public bool Debug { get; set; }\r
+\r
+        /// <summary>\r
+        /// non-option parameters\r
+        /// </summary>\r
         public IList<string> Extra = new List<string>();\r
 \r
         TextWriter log;\r
@@ -227,111 +210,113 @@ namespace DbMetal
             Schema = true;\r
             Culture = "en";\r
             GenerateTypes = new List<string>();\r
+            MemberAttributes = new List<string>();\r
             GenerateTimestamps = true;\r
             EntityInterfaces = new []{ "INotifyPropertyChanging", "INotifyPropertyChanged" };\r
         }\r
 \r
-        /// <summary>\r
-        /// Converts a list separated by a comma to a string array\r
-        /// </summary>\r
-        /// <param name="list"></param>\r
-        /// <returns></returns>\r
-        public string[] GetArray(string list)\r
-        {\r
-            if (string.IsNullOrEmpty(list))\r
-                return new string[0];\r
-            return (from entityInterface in list.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)\r
-                    select entityInterface.Trim()).ToArray();\r
-        }\r
-\r
         public void Parse(IList<string> args)\r
         {\r
             Options = new OptionSet() {\r
+                 // SQLMetal compatible\r
                 { "c|conn=",\r
                   "Database {CONNECTION STRING}. Cannot be used with /server, "\r
                   +"/user or /password options.",\r
                   conn => Conn = conn },\r
+                 // SQLMetal compatible\r
                 { "u|user=",\r
                   "Login user {NAME}.",\r
                   name => User = name },\r
+                 // SQLMetal compatible\r
                 { "p|password=",\r
                   "Login {PASSWORD}.",\r
                   password => Password = password },\r
+                 // SQLMetal compatible\r
                 { "s|server=",\r
                   "Database server {NAME}.",\r
                   name => Server = name },\r
+                 // SQLMetal compatible\r
                 { "d|database=",\r
                   "Database catalog {NAME} on server.",\r
                   name => Database = name },\r
                 { "provider=",\r
                   "Specify {PROVIDER}. May be Ingres, MySql, Oracle, OracleODP, PostgreSql or Sqlite.",\r
                   provider => Provider = provider },\r
-                { "dbLinqSchemaLoaderProvider=",\r
-                  "Specify a custom ISchemaLoader implementation {TYPE}.",\r
+                { "with-schema-loader=",\r
+                  "ISchemaLoader implementation {TYPE}.",\r
                   type => DbLinqSchemaLoaderProvider = type },\r
-                { "databaseConnectionProvider=",\r
-                  "Specify a custom IDbConnection implementation {TYPE}.",\r
+                { "with-dbconnection=",\r
+                  "IDbConnection implementation {TYPE}.",\r
                   type => DatabaseConnectionProvider = type },\r
-                { "sqlDialectType=",\r
-                  "The IVendor implementation {TYPE}.",\r
+                { "with-sql-dialect=",\r
+                  "IVendor implementation {TYPE}.",\r
                   type => SqlDialectType = type },\r
+                 // SQLMetal compatible\r
                 { "code=",\r
                   "Output as source code to {FILE}. Cannot be used with /dbml option.",\r
                   file => Code = file },\r
+                 // SQLMetal compatible\r
                 { "dbml=",\r
                   "Output as dbml to {FILE}. Cannot be used with /map option.",\r
                   file => Dbml = file },\r
+                 // SQLMetal compatible\r
                 { "language=",\r
                   "Language {NAME} for source code: C#, C#2 or VB "\r
                   +"(default: derived from extension on code file name).",\r
                   name => Language = name },\r
-                { "aliases|renamesFile=",\r
+                { "aliases=",\r
                   "Use mapping {FILE}.",\r
                   file => Aliases = file },\r
                 { "schema",\r
-                  "Generate schema in code files (default='true').",\r
-                  v => Schema = v != null},\r
+                  "Generate schema in code files (default: enabled).",\r
+                  v => Schema = v != null },\r
+                 // SQLMetal compatible\r
                 { "namespace=",\r
                   "Namespace {NAME} of generated code (default: no namespace).",\r
                   name => Namespace = name },\r
-                { "entityBase=",\r
+                 // SQLMetal compatible\r
+                { "entitybase=",\r
                   "Base {TYPE} of entity classes in the generated code "\r
                   +"(default: entities have no base class).",\r
                   type => EntityBase = type },\r
-                { "entityAttributes=",\r
-                  "Comma separated {ATTRIBUTE(S)} of entity classes in the generated code.",\r
-                  attributes => EntityAttributes = attributes },\r
-                { "memberAttributes=",\r
-                  "Comma separated {ATTRIBUTE(S)} of entity members in the generated code.",\r
-                  attributes => MemberAttributes = attributes },\r
+                { "member-attribute=",\r
+                  "{ATTRIBUTE} for entity members in the generated code, "\r
+                  +"can be specified multiple times.",\r
+                  attribute => MemberAttributes.Add(attribute) },\r
                 { "generate-type=",\r
                   "Generate only the {TYPE} selected, can be specified multiple times "\r
                   +"and does not prevent references from being generated (default: "\r
                   +"generate a DataContex subclass and all the entities in the schema).",\r
                   type => GenerateTypes.Add(type) },\r
-                { "generateEqualsAndHash",\r
+                { "generate-equals-hash",\r
                   "Generates overrides for Equals() and GetHashCode() methods.",\r
-                  v => GenerateEqualsAndHash = v != null},\r
+                  v => GenerateEqualsHash = v != null },\r
+                 // SQLMetal compatible\r
                 { "sprocs",\r
                   "Extract stored procedures.",\r
                   v => Sprocs = v != null},\r
+                 // SQLMetal compatible\r
                 { "pluralize",\r
                   "Automatically pluralize or singularize class and member names "\r
                   +"using specified culture rules.",\r
                   v => Pluralize = v != null},\r
                 { "culture=",\r
-                  "Specify {CULTURE} for word recognition and pluralization (default=\"en\").",\r
+                  "Specify {CULTURE} for word recognition and pluralization (default\"en\").",\r
                   culture => Culture = culture },\r
                 { "case=",\r
                   "Transform names with the indicated {STYLE} "\r
                   +"(default: net; may be: leave, pascal, camel, net).",\r
                   style => Case = style },\r
                 { "generate-timestamps",\r
-                  "Generate timestampes in the generated code. True by default.",\r
+                  "Generate timestampes in the generated code (default: enabled).",\r
                   v => GenerateTimestamps = v != null },\r
-                { "readlineAtExit",\r
+                { "readline",\r
                   "Wait for a key to be pressed after processing.",\r
-                  v => ReadLineAtExit = v != null },\r
+                  v => Readline = v != null },\r
+                { "debug",\r
+                  "Enables additional information to help with debugging, " + \r
+                  "such as full stack traces in error messages.",\r
+                  v => Debug = v != null },\r
                 { "h|?|help",\r
                   "Show this help",\r
                   v => Help = v != null }\r
index 8bf4086f27eb2d88445ffa51c69641a765b37650..6ca42bc77db4c35d3625b34fbdd6301e3433eae6 100644 (file)
@@ -41,13 +41,4 @@ using DbLinq.Factory;
 // The following GUID is for the ID of the typelib if this project is exposed to COM\r
 [assembly: Guid("7ae782c4-e495-44ff-821d-8580dbe184d4")]\r
 \r
-// Version information for an assembly consists of the following four values:\r
-//\r
-//      Major Version\r
-//      Minor Version \r
-//      Build Number\r
-//      Revision\r
-//\r
-[assembly: AssemblyFileVersion("0.19")]\r
-\r
 [assembly: DbLinq]\r
index ef0399ae348b71e743079d4a2dd31cdf52342c0c..65c1a81eab15443c06d9eb91021b15d064578706 100755 (executable)
       <Link>Properties\DbLinq.ProductInfo.cs</Link>\r
     </Compile>\r
     <Compile Include="Generator\AttributeDefinition.cs" />\r
-    <Compile Include="Generator\Implementation\CodeDomGenerator\AbstractCodeDomGenerator.cs" />\r
+    <Compile Include="Generator\CodeDomGenerator.cs" />\r
     <Compile Include="Generator\EntityInterface\Implementation\INotifyPropertyChangedImplementation.cs" />\r
     <Compile Include="Generator\GenerationContext.cs" />\r
     <Compile Include="Generator\ICodeGenerator.cs" />\r
     <Compile Include="Generator\EntityInterface\Implementation\InterfaceImplementation.cs" />\r
-    <Compile Include="Generator\Implementation\CodeDomGenerator\VisualBasicCodeDomGenerator.cs" />\r
-    <Compile Include="Generator\Implementation\CodeDomGenerator\CSharpCodeDomGenerator.cs" />\r
     <Compile Include="Generator\Implementation\CodeTextGenerator\CodeGenerator.Class.cs" />\r
     <Compile Include="Generator\Implementation\CodeTextGenerator\CodeGenerator.Context.Ctor.cs" />\r
     <Compile Include="Generator\Implementation\CodeTextGenerator\CodeGenerator.cs" />\r
     </ProjectReference>\r
   </ItemGroup>\r
   <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />\r
-  <PropertyGroup>\r
-    <PostBuildEvent>rem this is what I call loose coupling\r
-copy "$(SolutionDir)..\lib\Npgsql.dll" "$(TargetDir)"\r
-copy "$(SolutionDir)..\lib\Mono.Security.dll" "$(TargetDir)"\r
-copy "$(SolutionDir)..\lib\Ingres.Stereo.dll" "$(TargetDir)"\r
-copy "$(SolutionDir)..\lib\Oracle.DataAccess.dll" "$(TargetDir)"\r
-copy "$(SolutionDir)..\lib\MySql.Data.dll" "$(TargetDir)"\r
-copy "$(SolutionDir)..\lib\System.Data.SQLite.dll" "$(TargetDir)"\r
-copy "$(SolutionDir)..\lib\FirebirdSql.Data.FirebirdClient.dll" "$(TargetDir)"\r
-</PostBuildEvent>\r
-  </PropertyGroup>\r
-</Project>
\ No newline at end of file
+  <ItemGroup>\r
+    <DependentAssembly Include="$(SolutionDir)..\lib\Npgsql.dll" />\r
+    <DependentAssembly Include="$(SolutionDir)..\lib\Mono.Security.dll" />\r
+    <DependentAssembly Include="$(SolutionDir)..\lib\Ingres.Stereo.dll" />\r
+    <DependentAssembly Include="$(SolutionDir)..\lib\Oracle.DataAccess.dll" />\r
+    <DependentAssembly Include="$(SolutionDir)..\lib\MySql.Data.dll" />\r
+    <DependentAssembly Include="$(SolutionDir)..\lib\System.Data.SQLite.DLL" />\r
+    <DependentAssembly Include="$(SolutionDir)..\lib\FirebirdSql.Data.FirebirdClient.dll" />\r
+  </ItemGroup>\r
+  <Target Name="AfterBuild">\r
+    <Copy \r
+        SourceFiles="@(DependentAssembly)" \r
+        DestinationFolder="$(OutputPath)" />\r
+  </Target>\r
+</Project>\r
diff --git a/mcs/class/System.Data.Linq/src/DbMetal/Test/AppRunner.cs b/mcs/class/System.Data.Linq/src/DbMetal/Test/AppRunner.cs
new file mode 100755 (executable)
index 0000000..6d40227
--- /dev/null
@@ -0,0 +1,108 @@
+#region MIT license\r
+// \r
+// MIT license\r
+//\r
+// Copyright (c) 2010 Novell, Inc.\r
+// \r
+// Permission is hereby granted, free of charge, to any person obtaining a copy\r
+// of this software and associated documentation files (the "Software"), to deal\r
+// in the Software without restriction, including without limitation the rights\r
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r
+// copies of the Software, and to permit persons to whom the Software is\r
+// furnished to do so, subject to the following conditions:\r
+// \r
+// The above copyright notice and this permission notice shall be included in\r
+// all copies or substantial portions of the Software.\r
+// \r
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r
+// THE SOFTWARE.\r
+// \r
+#endregion\r
+\r
+using System;\r
+using System.Collections.Generic;\r
+using System.IO;\r
+using System.Linq;\r
+using DbMetal;\r
+using NUnit.Framework;\r
+\r
+namespace DbMetal_Test_Sqlite\r
+{\r
+    class DbMetalAppDomainSetup : MarshalByRefObject\r
+    {\r
+        public void SetStandardError(TextWriter stderr)\r
+        {\r
+            Console.SetError(stderr);\r
+        }\r
+\r
+        public void Run(string[] args)\r
+        {\r
+            Program.Main(args);\r
+        }\r
+    }\r
+\r
+    static class AppRunner\r
+    {\r
+#if MONO_STRICT\r
+        const string Program                = "sqlmetal";\r
+        const string DbConnectionProvider   = "Mono.Data.Sqlite.SqliteConnection, Mono.Data.Sqlite";\r
+        const string DbLinqSchemaLoader     = "DbLinq.Vendor.DbSchemaLoader, System.Data.Linq";\r
+        const string SqlDialect             = "DbLinq.Sqlite.SqliteVendor, System.Data.Linq";\r
+#else\r
+        const string Program                = "DbMetal";\r
+        const string DbConnectionProvider   = "System.Data.SQLite.SQLiteConnection, System.Data.SQLite";\r
+        const string DbLinqSchemaLoader     = "DbLinq.Vendor.DbSchemaLoader, DbLinq";\r
+        const string SqlDialect             = "DbLinq.Sqlite.SqliteVendor, DbLinq.Sqlite";\r
+#endif\r
+\r
+        public static void WithinAppDomain(string expectedFile, string createdFile, IEnumerable<string> args)\r
+        {\r
+            var bd = AppDomain.CurrentDomain.BaseDirectory;\r
+            var info = new AppDomainSetup()\r
+            {\r
+                ApplicationBase     = bd,\r
+                ApplicationName     = Program + ".exe",\r
+                ConfigurationFile   = Program + ".exe.config",\r
+            };\r
+            AppDomain ad = AppDomain.CreateDomain("DbMetal Sqlite Test", null, info);\r
+            var t = typeof(DbMetalAppDomainSetup);\r
+            var s = (DbMetalAppDomainSetup)ad.CreateInstanceAndUnwrap(t.Assembly.GetName().Name, t.FullName);\r
+            var stderr = new StringWriter();\r
+            s.SetStandardError(stderr);\r
+            var testdir = Path.Combine(bd, Path.Combine("..", "tests"));\r
+            var expectedDir = Path.Combine(testdir, "expected");\r
+            s.Run(new []{\r
+                "/provider:Sqlite",\r
+                "/conn:Data Source=" + Path.Combine(testdir, "Northwind.db3"),\r
+            }.Concat(args).ToArray());\r
+            AppDomain.Unload(ad);\r
+            if (stderr.GetStringBuilder().Length != 0)\r
+                Console.Error.Write(stderr.GetStringBuilder().ToString());\r
+            Assert.AreEqual(0, stderr.GetStringBuilder().Length);\r
+            FileAssert.AreEqual(Path.Combine(expectedDir, string.Format (expectedFile, Program)), createdFile);\r
+            File.Delete(createdFile);\r
+        }\r
+\r
+        public static void WithDbSchemaLoader(string expectedFile, string createdFile, IEnumerable<string> args)\r
+        {\r
+            var bd = AppDomain.CurrentDomain.BaseDirectory;\r
+            var testdir = Path.Combine(bd, Path.Combine("..", "tests"));\r
+            var expectedDir = Path.Combine(testdir, "expected");\r
+\r
+            DbMetal.Program.Main(new []{\r
+                "/conn:Data Source=" + Path.Combine(testdir, "Northwind.db3"),\r
+                "--with-dbconnection=" + DbConnectionProvider,\r
+                "--with-schema-loader=" + DbLinqSchemaLoader,\r
+                "--with-sql-dialect=" + SqlDialect,\r
+            }.Concat(args).ToArray());\r
+\r
+            FileAssert.AreEqual(Path.Combine(expectedDir, string.Format(expectedFile, Program)), createdFile);\r
+            File.Delete(createdFile);\r
+        }\r
+    }\r
+}
\ No newline at end of file
diff --git a/mcs/class/System.Data.Linq/src/DbMetal/Test/CreateDbmlFromSqliteDbTest.cs b/mcs/class/System.Data.Linq/src/DbMetal/Test/CreateDbmlFromSqliteDbTest.cs
new file mode 100755 (executable)
index 0000000..f3ac66b
--- /dev/null
@@ -0,0 +1,55 @@
+#region MIT license\r
+// \r
+// MIT license\r
+//\r
+// Copyright (c) 2010 Novell, Inc.\r
+// \r
+// Permission is hereby granted, free of charge, to any person obtaining a copy\r
+// of this software and associated documentation files (the "Software"), to deal\r
+// in the Software without restriction, including without limitation the rights\r
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r
+// copies of the Software, and to permit persons to whom the Software is\r
+// furnished to do so, subject to the following conditions:\r
+// \r
+// The above copyright notice and this permission notice shall be included in\r
+// all copies or substantial portions of the Software.\r
+// \r
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r
+// THE SOFTWARE.\r
+// \r
+#endregion\r
+\r
+using System;\r
+using System.IO;\r
+using DbMetal;\r
+using NUnit.Framework;\r
+\r
+namespace DbMetal_Test_Sqlite\r
+{\r
+    [TestFixture]\r
+    public class CreateDbmlFromSqliteDbTest\r
+    {\r
+        [Test]\r
+        public void CreateViaProvider()\r
+        {\r
+            var created = "Northwind.dbml";\r
+            AppRunner.WithinAppDomain("Northwind.Sqlite-{0}.dbml", created, new[]{\r
+                "/dbml:" + created,\r
+            });\r
+        }\r
+\r
+        [Test]\r
+        public void CreateViaDbSchemaLoader()\r
+        {\r
+            var created = "Northwind.dbml";\r
+            AppRunner.WithDbSchemaLoader("Northwind.Sqlite+DbSchemaLoader-{0}.dbml", created, new[]{\r
+                "/dbml:" + created,\r
+            });\r
+        }\r
+    }\r
+}\r
index ed3abfaa2ad945970b2a1f479b0aa05d8f8914d9..cfd87026294e93d32d7d3ccb46572ea55f619349 100755 (executable)
@@ -31,93 +31,35 @@ using NUnit.Framework;
 \r
 namespace DbMetal_Test_Sqlite\r
 {\r
-    class DbMetalAppDomainSetup : MarshalByRefObject\r
-    {\r
-        public void SetStandardError(TextWriter stderr)\r
-        {\r
-            Console.SetError(stderr);\r
-        }\r
-\r
-        public void Run(string[] args)\r
-        {\r
-            Program.Main(args);\r
-        }\r
-    }\r
-\r
     [TestFixture]\r
     public class CreateEntitiesFromSqliteDbTest\r
     {\r
         [Test]\r
         public void CreateViaProvider()\r
         {\r
-#if MONO_STRICT\r
-            var app = "sqlmetal";\r
-#else\r
-            var app = "DbMetal";\r
-#endif\r
-            var bd = AppDomain.CurrentDomain.BaseDirectory;\r
-            var info = new AppDomainSetup()\r
-            {\r
-                ApplicationBase     = bd,\r
-                ApplicationName     = app + ".exe",\r
-                ConfigurationFile   = app + ".exe.config",\r
-            };\r
-            AppDomain ad = AppDomain.CreateDomain("DbMetal Sqlite Test", null, info);\r
-            var t = typeof(DbMetalAppDomainSetup);\r
-            var s = (DbMetalAppDomainSetup)ad.CreateInstanceAndUnwrap(t.Assembly.GetName().Name, t.FullName);\r
-            var stderr = new StringWriter();\r
-            s.SetStandardError(stderr);\r
-            var testdir = Path.Combine(bd, Path.Combine("..", "tests"));\r
-            var db = Path.Combine(bd, Path.Combine("..", Path.Combine("tests", "Northwind.db3")));\r
-            s.Run(new string[]{\r
-                "/code:Northwind.Sqlite.cs",\r
-                "/conn:Data Source=" + Path.Combine(testdir, "Northwind.db3"),\r
+            var created = "Northwind.Sqlite.cs";\r
+            AppRunner.WithinAppDomain("Northwind.Sqlite-{0}.cs", created, new[]{\r
+                "/code:" + created,\r
                 "/database:Northwind",\r
+                "--generate-equals-hash",\r
                 "--generate-timestamps-",\r
                 "/namespace:nwind",\r
                 "/pluralize",\r
-                "/provider:Sqlite",\r
             });\r
-            AppDomain.Unload(ad);\r
-            if (stderr.GetStringBuilder().Length != 0)\r
-                Console.Error.Write(stderr.GetStringBuilder().ToString());\r
-            Assert.AreEqual(0, stderr.GetStringBuilder().Length);\r
-            FileAssert.AreEqual(Path.Combine(testdir, "Northwind.Expected.Sqlite-" + app + ".cs"), "Northwind.Sqlite.cs");\r
-            File.Delete("Northwind.Sqlite.cs");\r
         }\r
 \r
         [Test]\r
         public void CreateViaDbSchemaLoader()\r
         {\r
-#if MONO_STRICT\r
-            var app                     = "sqlmetal";\r
-            var dbConnectionProvider    = "Mono.Data.Sqlite.SqliteConnection, Mono.Data.Sqlite";\r
-            var dbLinqSchemaLoader      = "DbLinq.Vendor.DbSchemaLoader, System.Data.Linq";\r
-            var sqlDialect              = "DbLinq.Sqlite.SqliteVendor, System.Data.Linq";\r
-#else\r
-            var app                     = "DbMetal";\r
-            var dbConnectionProvider    = "System.Data.SQLite.SQLiteConnection, System.Data.SQLite";\r
-            var dbLinqSchemaLoader      = "DbLinq.Vendor.DbSchemaLoader, DbLinq";\r
-            var sqlDialect              = "DbLinq.Sqlite.SqliteVendor, DbLinq.Sqlite";\r
-#endif\r
-            var bd = AppDomain.CurrentDomain.BaseDirectory;\r
-            var testdir = Path.Combine(bd, Path.Combine("..", "tests"));\r
-            var expectedDir = Path.Combine(testdir, "expected");\r
-\r
-            Program.Main(new string[]{\r
-                "/code:Northwind.Sqlite.cs",\r
-                "/conn:Data Source=" + Path.Combine(testdir, "Northwind.db3"),\r
+            var created = "Northwind.Sqlite.cs";\r
+            AppRunner.WithDbSchemaLoader("Northwind.Sqlite+DbSchemaLoader-{0}.cs", created, new[]{\r
+                "/code:" + created,\r
                 "/database:Northwind",\r
-                "/databaseConnectionProvider=" + dbConnectionProvider,\r
-                "/dbLinqSchemaLoaderProvider=" + dbLinqSchemaLoader,\r
+                "--generate-equals-hash",\r
                 "--generate-timestamps-",\r
                 "/namespace:nwind",\r
                 "/pluralize",\r
-                "/sqlDialectType=" + sqlDialect,\r
             });\r
-\r
-            FileAssert.AreEqual(Path.Combine(expectedDir, "Northwind.Sqlite+DbSchemaLoader-" + app + ".cs"), "Northwind.Sqlite.cs");\r
-            File.Delete("Northwind.Sqlite.cs");\r
         }\r
     }\r
 }
\ No newline at end of file
index 665c8adde76e586dae45fa121c0ea89ba94dd1d0..fb4fd3594c81144c492c91dd925517eecd763f74 100755 (executable)
@@ -42,6 +42,8 @@
     </Reference>\r
   </ItemGroup>\r
   <ItemGroup>\r
+    <Compile Include="AppRunner.cs" />\r
+    <Compile Include="CreateDbmlFromSqliteDbTest.cs" />\r
     <Compile Include="CreateEntitiesFromSqliteDbTest.cs" />\r
   </ItemGroup>\r
   <ItemGroup>\r
index 99b67ea1b8c86b412523bdb391f44d5a97dcdd9f..ab31e2c580581b101e3875f195fcd0ef1db00603 100755 (executable)
@@ -42,6 +42,8 @@
     </Reference>\r
   </ItemGroup>\r
   <ItemGroup>\r
+    <Compile Include="AppRunner.cs" />\r
+    <Compile Include="CreateDbmlFromSqliteDbTest.cs" />\r
     <Compile Include="CreateEntitiesFromSqliteDbTest.cs" />\r
   </ItemGroup>\r
   <ItemGroup>\r
index 66337327ae54a573771d0ceb82ef648a473c0198..4ba59b2321faf2a8f6ef21bcf4f625d96e1da1d9 100644 (file)
@@ -13,7 +13,7 @@
       <provider name="Oracle" dbLinqSchemaLoader="DbLinq.Oracle.OracleSchemaLoader, System.Data.Linq" databaseConnection="System.Data.OracleClient.OracleConnection, System.Data.OracleClient" />\r
       <provider name="OracleODP" dbLinqSchemaLoader="DbLinq.Oracle.OracleSchemaLoader, System.Data.Linq" databaseConnection="Oracle.DataAccess.Client.OracleConnection, Oracle.DataAccess" />\r
       <provider name="PostgreSQL" dbLinqSchemaLoader="DbLinq.PostgreSql.PgsqlSchemaLoader, System.Data.Linq" databaseConnection="Npgsql.NpgsqlConnection, Npgsql" />\r
-      <provider name="SQLite" dbLinqSchemaLoader="DbLinq.Sqlite.SqliteSchemaLoader, System.Data.Linq" databaseConnection="System.Data.SQLite.SQLiteConnection, System.Data.SQLite" />\r
+      <provider name="SQLite" dbLinqSchemaLoader="DbLinq.Sqlite.SqliteSchemaLoader, System.Data.Linq" databaseConnection="Mono.Data.Sqlite.SqliteConnection, Mono.Data.Sqlite" />\r
       <provider name="SqlServer" dbLinqSchemaLoader="DbLinq.SqlServer.SqlServerSchemaLoader, System.Data.Linq" databaseConnection="System.Data.SqlClient.SqlConnection, System.Data" />\r
       <provider name="Ingres" dbLinqSchemaLoader="DbLinq.Ingres.IngresSchemaLoader, System.Data.Linq" databaseConnection="Ingres.Client.IngresConnection, Ingres.Client" />\r
       <provider name="Firebird" dbLinqSchemaLoader="DbLinq.Firebird.FirebirdSchemaLoader, System.Data.Linq" databaseConnection="FirebirdSql.Data.FirebirdClient.FbConnection, FirebirdSql.Data.FirebirdClient" />\r
index 8b6d0f969f667e47b41883ad2e9302f381899111..d869a5bf03307d5f1381619124c7a9f3645e5888 100644 (file)
@@ -21,16 +21,3 @@ using System.Runtime.InteropServices;
 \r
 // The following GUID is for the ID of the typelib if this project is exposed to COM\r
 [assembly: Guid("2e39c94e-8988-41cf-a6a4-81a82fa02066")]\r
-\r
-// Version information for an assembly consists of the following four values:\r
-//\r
-//      Major Version\r
-//      Minor Version \r
-//      Build Number\r
-//      Revision\r
-//\r
-// You can specify all the values or you can default the Build and Revision Numbers \r
-// by using the '*' as shown below:\r
-// [assembly: AssemblyVersion("1.0.*")]\r
-[assembly: AssemblyVersion("1.0.0.0")]\r
-[assembly: AssemblyFileVersion("1.0.0.0")]\r
index 6cbd4fbe3b29f157ea0d4d93e2201d704fda733e..57032638bcf59e5a45df1896e0cf3b93e33d0ac8 100644 (file)
@@ -21,16 +21,3 @@ using System.Runtime.InteropServices;
 \r
 // The following GUID is for the ID of the typelib if this project is exposed to COM\r
 [assembly: Guid("a4b927a0-9719-47b5-ad36-21ecf88d7978")]\r
-\r
-// Version information for an assembly consists of the following four values:\r
-//\r
-//      Major Version\r
-//      Minor Version \r
-//      Build Number\r
-//      Revision\r
-//\r
-// You can specify all the values or you can default the Build and Revision Numbers \r
-// by using the '*' as shown below:\r
-// [assembly: AssemblyVersion("1.0.*")]\r
-[assembly: AssemblyVersion("1.0.0.0")]\r
-[assembly: AssemblyFileVersion("1.0.0.0")]\r
diff --git a/mcs/class/System.Data.Linq/tests/Northwind.Expected.Sqlite-DbMetal.cs b/mcs/class/System.Data.Linq/tests/Northwind.Expected.Sqlite-DbMetal.cs
deleted file mode 100755 (executable)
index f6bf319..0000000
+++ /dev/null
@@ -1,4165 +0,0 @@
-#region Auto-generated classes for Northwind database on [TIMESTAMP]\r
-\r
-//\r
-//  ____  _     __  __      _        _\r
-// |  _ \| |__ |  \/  | ___| |_ __ _| |\r
-// | | | | '_ \| |\/| |/ _ \ __/ _` | |\r
-// | |_| | |_) | |  | |  __/ || (_| | |\r
-// |____/|_.__/|_|  |_|\___|\__\__,_|_|\r
-//\r
-// Auto-generated from Northwind on [TIMESTAMP]\r
-// Please visit http://linq.to/db for more information\r
-\r
-#endregion\r
-\r
-using System;\r
-using System.Data;\r
-using System.Data.Linq.Mapping;\r
-using System.Diagnostics;\r
-using System.Reflection;\r
-#if MONO_STRICT\r
-using System.Data.Linq;\r
-#else   // MONO_STRICT\r
-using DbLinq.Data.Linq;\r
-using DbLinq.Vendor;\r
-#endif  // MONO_STRICT\r
-using System.ComponentModel;\r
-\r
-namespace nwind\r
-{\r
-       public partial class Northwind : DataContext\r
-       {\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-\r
-               #endregion\r
-\r
-               public Northwind(string connectionString)\r
-                       : base(connectionString)\r
-               {\r
-                       OnCreated();\r
-               }\r
-\r
-               public Northwind(IDbConnection connection)\r
-               #if MONO_STRICT\r
-                       : base(connection)\r
-               #else   // MONO_STRICT\r
-                       : base(connection, new DbLinq.Sqlite.SqliteVendor())\r
-               #endif  // MONO_STRICT\r
-               {\r
-                       OnCreated();\r
-               }\r
-\r
-               public Northwind(string connection, MappingSource mappingSource)\r
-                       : base(connection, mappingSource)\r
-               {\r
-                       OnCreated();\r
-               }\r
-\r
-               public Northwind(IDbConnection connection, MappingSource mappingSource)\r
-                       : base(connection, mappingSource)\r
-               {\r
-                       OnCreated();\r
-               }\r
-\r
-               #if !MONO_STRICT\r
-               public Northwind(IDbConnection connection, IVendor vendor)\r
-                       : base(connection, vendor)\r
-               {\r
-                       OnCreated();\r
-               }\r
-               #endif  // !MONO_STRICT\r
-\r
-               #if !MONO_STRICT\r
-               public Northwind(IDbConnection connection, MappingSource mappingSource, IVendor vendor)\r
-                       : base(connection, mappingSource, vendor)\r
-               {\r
-                       OnCreated();\r
-               }\r
-               #endif  // !MONO_STRICT\r
-\r
-               public Table<Category> Categories { get { return GetTable<Category>(); } }\r
-               public Table<Customer> Customers { get { return GetTable<Customer>(); } }\r
-               public Table<CustomerCustomerDemo> CustomerCustomerDemo { get { return GetTable<CustomerCustomerDemo>(); } }\r
-               public Table<CustomerDemographic> CustomerDemographics { get { return GetTable<CustomerDemographic>(); } }\r
-               public Table<Employee> Employees { get { return GetTable<Employee>(); } }\r
-               public Table<EmployeeTerritory> EmployeeTerritories { get { return GetTable<EmployeeTerritory>(); } }\r
-               public Table<Order> Orders { get { return GetTable<Order>(); } }\r
-               public Table<OrderDetail> OrderDetails { get { return GetTable<OrderDetail>(); } }\r
-               public Table<Product> Products { get { return GetTable<Product>(); } }\r
-               public Table<Region> Regions { get { return GetTable<Region>(); } }\r
-               public Table<Shipper> Shippers { get { return GetTable<Shipper>(); } }\r
-               public Table<Supplier> Suppliers { get { return GetTable<Supplier>(); } }\r
-               public Table<Territory> Territories { get { return GetTable<Territory>(); } }\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Categories")]\r
-       public partial class Category : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnCategoryIDChanged();\r
-               partial void OnCategoryIDChanging(int value);\r
-               partial void OnCategoryNameChanged();\r
-               partial void OnCategoryNameChanging(string value);\r
-               partial void OnDescriptionChanged();\r
-               partial void OnDescriptionChanging(string value);\r
-               partial void OnPictureChanged();\r
-               partial void OnPictureChanging(Byte[] value);\r
-\r
-               #endregion\r
-\r
-               #region int CategoryID\r
-\r
-               private int _categoryID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_categoryID", Name = "CategoryID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public int CategoryID\r
-               {\r
-                       get\r
-                       {\r
-                               return _categoryID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _categoryID)\r
-                               {\r
-                                       OnCategoryIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _categoryID = value;\r
-                                       SendPropertyChanged("CategoryID");\r
-                                       OnCategoryIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string CategoryName\r
-\r
-               private string _categoryName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_categoryName", Name = "CategoryName", DbType = "nvarchar (15)", AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public string CategoryName\r
-               {\r
-                       get\r
-                       {\r
-                               return _categoryName;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _categoryName)\r
-                               {\r
-                                       OnCategoryNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _categoryName = value;\r
-                                       SendPropertyChanged("CategoryName");\r
-                                       OnCategoryNameChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Description\r
-\r
-               private string _description;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_description", Name = "Description", DbType = "ntext", AutoSync = AutoSync.Never)]\r
-               public string Description\r
-               {\r
-                       get\r
-                       {\r
-                               return _description;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _description)\r
-                               {\r
-                                       OnDescriptionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _description = value;\r
-                                       SendPropertyChanged("Description");\r
-                                       OnDescriptionChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Byte[] Picture\r
-\r
-               private Byte[] _picture;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_picture", Name = "Picture", DbType = "image", AutoSync = AutoSync.Never)]\r
-               public Byte[] Picture\r
-               {\r
-                       get\r
-                       {\r
-                               return _picture;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _picture)\r
-                               {\r
-                                       OnPictureChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _picture = value;\r
-                                       SendPropertyChanged("Picture");\r
-                                       OnPictureChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Children\r
-\r
-               private EntitySet<Product> _products;\r
-               [Association(Storage = "_products", OtherKey = "CategoryID", ThisKey = "CategoryID", Name = "fk_Products_1")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<Product> Products\r
-               {\r
-                       get\r
-                       {\r
-                               return _products;\r
-                       }\r
-                       set\r
-                       {\r
-                               _products = value;\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void Products_Attach(Product entity)\r
-               {\r
-                       entity.Category = this;\r
-               }\r
-\r
-               private void Products_Detach(Product entity)\r
-               {\r
-                       entity.Category = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Category()\r
-               {\r
-                       _products = new EntitySet<Product>(Products_Attach, Products_Detach);\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Customers")]\r
-       public partial class Customer : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnAddressChanged();\r
-               partial void OnAddressChanging(string value);\r
-               partial void OnCityChanged();\r
-               partial void OnCityChanging(string value);\r
-               partial void OnCompanyNameChanged();\r
-               partial void OnCompanyNameChanging(string value);\r
-               partial void OnContactNameChanged();\r
-               partial void OnContactNameChanging(string value);\r
-               partial void OnContactTitleChanged();\r
-               partial void OnContactTitleChanging(string value);\r
-               partial void OnCountryChanged();\r
-               partial void OnCountryChanging(string value);\r
-               partial void OnCustomerIDChanged();\r
-               partial void OnCustomerIDChanging(string value);\r
-               partial void OnFaxChanged();\r
-               partial void OnFaxChanging(string value);\r
-               partial void OnPhoneChanged();\r
-               partial void OnPhoneChanging(string value);\r
-               partial void OnPostalCodeChanged();\r
-               partial void OnPostalCodeChanging(string value);\r
-               partial void OnRegionChanged();\r
-               partial void OnRegionChanging(string value);\r
-\r
-               #endregion\r
-\r
-               #region string Address\r
-\r
-               private string _address;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_address", Name = "Address", DbType = "nvarchar (60)", AutoSync = AutoSync.Never)]\r
-               public string Address\r
-               {\r
-                       get\r
-                       {\r
-                               return _address;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _address)\r
-                               {\r
-                                       OnAddressChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _address = value;\r
-                                       SendPropertyChanged("Address");\r
-                                       OnAddressChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string City\r
-\r
-               private string _city;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_city", Name = "City", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
-               public string City\r
-               {\r
-                       get\r
-                       {\r
-                               return _city;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _city)\r
-                               {\r
-                                       OnCityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _city = value;\r
-                                       SendPropertyChanged("City");\r
-                                       OnCityChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string CompanyName\r
-\r
-               private string _companyName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_companyName", Name = "CompanyName", DbType = "nvarchar (40)", AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public string CompanyName\r
-               {\r
-                       get\r
-                       {\r
-                               return _companyName;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _companyName)\r
-                               {\r
-                                       OnCompanyNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _companyName = value;\r
-                                       SendPropertyChanged("CompanyName");\r
-                                       OnCompanyNameChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ContactName\r
-\r
-               private string _contactName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_contactName", Name = "ContactName", DbType = "nvarchar (30)", AutoSync = AutoSync.Never)]\r
-               public string ContactName\r
-               {\r
-                       get\r
-                       {\r
-                               return _contactName;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _contactName)\r
-                               {\r
-                                       OnContactNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _contactName = value;\r
-                                       SendPropertyChanged("ContactName");\r
-                                       OnContactNameChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ContactTitle\r
-\r
-               private string _contactTitle;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_contactTitle", Name = "ContactTitle", DbType = "nvarchar (30)", AutoSync = AutoSync.Never)]\r
-               public string ContactTitle\r
-               {\r
-                       get\r
-                       {\r
-                               return _contactTitle;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _contactTitle)\r
-                               {\r
-                                       OnContactTitleChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _contactTitle = value;\r
-                                       SendPropertyChanged("ContactTitle");\r
-                                       OnContactTitleChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Country\r
-\r
-               private string _country;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_country", Name = "Country", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
-               public string Country\r
-               {\r
-                       get\r
-                       {\r
-                               return _country;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _country)\r
-                               {\r
-                                       OnCountryChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _country = value;\r
-                                       SendPropertyChanged("Country");\r
-                                       OnCountryChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string CustomerID\r
-\r
-               private string _customerID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerID", Name = "CustomerID", DbType = "nchar (5)", IsPrimaryKey = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public string CustomerID\r
-               {\r
-                       get\r
-                       {\r
-                               return _customerID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _customerID)\r
-                               {\r
-                                       OnCustomerIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerID = value;\r
-                                       SendPropertyChanged("CustomerID");\r
-                                       OnCustomerIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Fax\r
-\r
-               private string _fax;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_fax", Name = "Fax", DbType = "nvarchar (24)", AutoSync = AutoSync.Never)]\r
-               public string Fax\r
-               {\r
-                       get\r
-                       {\r
-                               return _fax;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _fax)\r
-                               {\r
-                                       OnFaxChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _fax = value;\r
-                                       SendPropertyChanged("Fax");\r
-                                       OnFaxChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Phone\r
-\r
-               private string _phone;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_phone", Name = "Phone", DbType = "nvarchar (24)", AutoSync = AutoSync.Never)]\r
-               public string Phone\r
-               {\r
-                       get\r
-                       {\r
-                               return _phone;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _phone)\r
-                               {\r
-                                       OnPhoneChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _phone = value;\r
-                                       SendPropertyChanged("Phone");\r
-                                       OnPhoneChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string PostalCode\r
-\r
-               private string _postalCode;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_postalCode", Name = "PostalCode", DbType = "nvarchar (10)", AutoSync = AutoSync.Never)]\r
-               public string PostalCode\r
-               {\r
-                       get\r
-                       {\r
-                               return _postalCode;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _postalCode)\r
-                               {\r
-                                       OnPostalCodeChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _postalCode = value;\r
-                                       SendPropertyChanged("PostalCode");\r
-                                       OnPostalCodeChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Region\r
-\r
-               private string _region;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_region", Name = "Region", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
-               public string Region\r
-               {\r
-                       get\r
-                       {\r
-                               return _region;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _region)\r
-                               {\r
-                                       OnRegionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _region = value;\r
-                                       SendPropertyChanged("Region");\r
-                                       OnRegionChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Children\r
-\r
-               private EntitySet<CustomerCustomerDemo> _customerCustomerDemo;\r
-               [Association(Storage = "_customerCustomerDemo", OtherKey = "CustomerID", ThisKey = "CustomerID", Name = "fk_CustomerCustomerDemo_0")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<CustomerCustomerDemo> CustomerCustomerDemo\r
-               {\r
-                       get\r
-                       {\r
-                               return _customerCustomerDemo;\r
-                       }\r
-                       set\r
-                       {\r
-                               _customerCustomerDemo = value;\r
-                       }\r
-               }\r
-\r
-               private EntitySet<Order> _orders;\r
-               [Association(Storage = "_orders", OtherKey = "CustomerID", ThisKey = "CustomerID", Name = "fk_Orders_2")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<Order> Orders\r
-               {\r
-                       get\r
-                       {\r
-                               return _orders;\r
-                       }\r
-                       set\r
-                       {\r
-                               _orders = value;\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void CustomerCustomerDemo_Attach(CustomerCustomerDemo entity)\r
-               {\r
-                       entity.Customer = this;\r
-               }\r
-\r
-               private void CustomerCustomerDemo_Detach(CustomerCustomerDemo entity)\r
-               {\r
-                       entity.Customer = null;\r
-               }\r
-\r
-               private void Orders_Attach(Order entity)\r
-               {\r
-                       entity.Customer = this;\r
-               }\r
-\r
-               private void Orders_Detach(Order entity)\r
-               {\r
-                       entity.Customer = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Customer()\r
-               {\r
-                       _customerCustomerDemo = new EntitySet<CustomerCustomerDemo>(CustomerCustomerDemo_Attach, CustomerCustomerDemo_Detach);\r
-                       _orders = new EntitySet<Order>(Orders_Attach, Orders_Detach);\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.CustomerCustomerDemo")]\r
-       public partial class CustomerCustomerDemo : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnCustomerIDChanged();\r
-               partial void OnCustomerIDChanging(string value);\r
-               partial void OnCustomerTypeIDChanged();\r
-               partial void OnCustomerTypeIDChanging(string value);\r
-\r
-               #endregion\r
-\r
-               #region string CustomerID\r
-\r
-               private string _customerID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerID", Name = "CustomerID", DbType = "nchar (5)", IsPrimaryKey = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public string CustomerID\r
-               {\r
-                       get\r
-                       {\r
-                               return _customerID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _customerID)\r
-                               {\r
-                                       if (_customer.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnCustomerIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerID = value;\r
-                                       SendPropertyChanged("CustomerID");\r
-                                       OnCustomerIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string CustomerTypeID\r
-\r
-               private string _customerTypeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerTypeID", Name = "CustomerTypeID", DbType = "nchar", IsPrimaryKey = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public string CustomerTypeID\r
-               {\r
-                       get\r
-                       {\r
-                               return _customerTypeID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _customerTypeID)\r
-                               {\r
-                                       if (_customerDemographic.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnCustomerTypeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerTypeID = value;\r
-                                       SendPropertyChanged("CustomerTypeID");\r
-                                       OnCustomerTypeIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Parents\r
-\r
-               private EntityRef<Customer> _customer;\r
-               [Association(Storage = "_customer", OtherKey = "CustomerID", ThisKey = "CustomerID", Name = "fk_CustomerCustomerDemo_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Customer Customer\r
-               {\r
-                       get\r
-                       {\r
-                               return _customer.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _customer.Entity)\r
-                               {\r
-                                       if (_customer.Entity != null)\r
-                                       {\r
-                                               var previousCustomer = _customer.Entity;\r
-                                               _customer.Entity = null;\r
-                                               previousCustomer.CustomerCustomerDemo.Remove(this);\r
-                                       }\r
-                                       _customer.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.CustomerCustomerDemo.Add(this);\r
-                                               _customerID = value.CustomerID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _customerID = default(string);\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-               private EntityRef<CustomerDemographic> _customerDemographic;\r
-               [Association(Storage = "_customerDemographic", OtherKey = "CustomerTypeID", ThisKey = "CustomerTypeID", Name = "fk_CustomerCustomerDemo_1", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public CustomerDemographic CustomerDemographic\r
-               {\r
-                       get\r
-                       {\r
-                               return _customerDemographic.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _customerDemographic.Entity)\r
-                               {\r
-                                       if (_customerDemographic.Entity != null)\r
-                                       {\r
-                                               var previousCustomerDemographic = _customerDemographic.Entity;\r
-                                               _customerDemographic.Entity = null;\r
-                                               previousCustomerDemographic.CustomerCustomerDemo.Remove(this);\r
-                                       }\r
-                                       _customerDemographic.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.CustomerCustomerDemo.Add(this);\r
-                                               _customerTypeID = value.CustomerTypeID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _customerTypeID = default(string);\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public CustomerCustomerDemo()\r
-               {\r
-                       _customer = new EntityRef<Customer>();\r
-                       _customerDemographic = new EntityRef<CustomerDemographic>();\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.CustomerDemographics")]\r
-       public partial class CustomerDemographic : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnCustomerDescChanged();\r
-               partial void OnCustomerDescChanging(string value);\r
-               partial void OnCustomerTypeIDChanged();\r
-               partial void OnCustomerTypeIDChanging(string value);\r
-\r
-               #endregion\r
-\r
-               #region string CustomerDesc\r
-\r
-               private string _customerDesc;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerDesc", Name = "CustomerDesc", DbType = "ntext", AutoSync = AutoSync.Never)]\r
-               public string CustomerDesc\r
-               {\r
-                       get\r
-                       {\r
-                               return _customerDesc;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _customerDesc)\r
-                               {\r
-                                       OnCustomerDescChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerDesc = value;\r
-                                       SendPropertyChanged("CustomerDesc");\r
-                                       OnCustomerDescChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string CustomerTypeID\r
-\r
-               private string _customerTypeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerTypeID", Name = "CustomerTypeID", DbType = "nchar", IsPrimaryKey = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public string CustomerTypeID\r
-               {\r
-                       get\r
-                       {\r
-                               return _customerTypeID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _customerTypeID)\r
-                               {\r
-                                       OnCustomerTypeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerTypeID = value;\r
-                                       SendPropertyChanged("CustomerTypeID");\r
-                                       OnCustomerTypeIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Children\r
-\r
-               private EntitySet<CustomerCustomerDemo> _customerCustomerDemo;\r
-               [Association(Storage = "_customerCustomerDemo", OtherKey = "CustomerTypeID", ThisKey = "CustomerTypeID", Name = "fk_CustomerCustomerDemo_1")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<CustomerCustomerDemo> CustomerCustomerDemo\r
-               {\r
-                       get\r
-                       {\r
-                               return _customerCustomerDemo;\r
-                       }\r
-                       set\r
-                       {\r
-                               _customerCustomerDemo = value;\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void CustomerCustomerDemo_Attach(CustomerCustomerDemo entity)\r
-               {\r
-                       entity.CustomerDemographic = this;\r
-               }\r
-\r
-               private void CustomerCustomerDemo_Detach(CustomerCustomerDemo entity)\r
-               {\r
-                       entity.CustomerDemographic = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public CustomerDemographic()\r
-               {\r
-                       _customerCustomerDemo = new EntitySet<CustomerCustomerDemo>(CustomerCustomerDemo_Attach, CustomerCustomerDemo_Detach);\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Employees")]\r
-       public partial class Employee : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnAddressChanged();\r
-               partial void OnAddressChanging(string value);\r
-               partial void OnBirthDateChanged();\r
-               partial void OnBirthDateChanging(DateTime? value);\r
-               partial void OnCityChanged();\r
-               partial void OnCityChanging(string value);\r
-               partial void OnCountryChanged();\r
-               partial void OnCountryChanging(string value);\r
-               partial void OnEmployeeIDChanged();\r
-               partial void OnEmployeeIDChanging(int value);\r
-               partial void OnExtensionChanged();\r
-               partial void OnExtensionChanging(string value);\r
-               partial void OnFirstNameChanged();\r
-               partial void OnFirstNameChanging(string value);\r
-               partial void OnHireDateChanged();\r
-               partial void OnHireDateChanging(DateTime? value);\r
-               partial void OnHomePhoneChanged();\r
-               partial void OnHomePhoneChanging(string value);\r
-               partial void OnLastNameChanged();\r
-               partial void OnLastNameChanging(string value);\r
-               partial void OnNotesChanged();\r
-               partial void OnNotesChanging(string value);\r
-               partial void OnPhotoChanged();\r
-               partial void OnPhotoChanging(Byte[] value);\r
-               partial void OnPhotoPathChanged();\r
-               partial void OnPhotoPathChanging(string value);\r
-               partial void OnPostalCodeChanged();\r
-               partial void OnPostalCodeChanging(string value);\r
-               partial void OnRegionChanged();\r
-               partial void OnRegionChanging(string value);\r
-               partial void OnReportsToChanged();\r
-               partial void OnReportsToChanging(int? value);\r
-               partial void OnTitleChanged();\r
-               partial void OnTitleChanging(string value);\r
-               partial void OnTitleOfCourtesyChanged();\r
-               partial void OnTitleOfCourtesyChanging(string value);\r
-\r
-               #endregion\r
-\r
-               #region string Address\r
-\r
-               private string _address;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_address", Name = "Address", DbType = "nvarchar (60)", AutoSync = AutoSync.Never)]\r
-               public string Address\r
-               {\r
-                       get\r
-                       {\r
-                               return _address;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _address)\r
-                               {\r
-                                       OnAddressChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _address = value;\r
-                                       SendPropertyChanged("Address");\r
-                                       OnAddressChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? BirthDate\r
-\r
-               private DateTime? _birthDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_birthDate", Name = "BirthDate", DbType = "datetime", AutoSync = AutoSync.Never)]\r
-               public DateTime? BirthDate\r
-               {\r
-                       get\r
-                       {\r
-                               return _birthDate;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _birthDate)\r
-                               {\r
-                                       OnBirthDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _birthDate = value;\r
-                                       SendPropertyChanged("BirthDate");\r
-                                       OnBirthDateChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string City\r
-\r
-               private string _city;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_city", Name = "City", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
-               public string City\r
-               {\r
-                       get\r
-                       {\r
-                               return _city;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _city)\r
-                               {\r
-                                       OnCityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _city = value;\r
-                                       SendPropertyChanged("City");\r
-                                       OnCityChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Country\r
-\r
-               private string _country;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_country", Name = "Country", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
-               public string Country\r
-               {\r
-                       get\r
-                       {\r
-                               return _country;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _country)\r
-                               {\r
-                                       OnCountryChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _country = value;\r
-                                       SendPropertyChanged("Country");\r
-                                       OnCountryChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int EmployeeID\r
-\r
-               private int _employeeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_employeeID", Name = "EmployeeID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public int EmployeeID\r
-               {\r
-                       get\r
-                       {\r
-                               return _employeeID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _employeeID)\r
-                               {\r
-                                       OnEmployeeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _employeeID = value;\r
-                                       SendPropertyChanged("EmployeeID");\r
-                                       OnEmployeeIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Extension\r
-\r
-               private string _extension;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_extension", Name = "Extension", DbType = "nvarchar (4)", AutoSync = AutoSync.Never)]\r
-               public string Extension\r
-               {\r
-                       get\r
-                       {\r
-                               return _extension;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _extension)\r
-                               {\r
-                                       OnExtensionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _extension = value;\r
-                                       SendPropertyChanged("Extension");\r
-                                       OnExtensionChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string FirstName\r
-\r
-               private string _firstName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_firstName", Name = "FirstName", DbType = "nvarchar (10)", AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public string FirstName\r
-               {\r
-                       get\r
-                       {\r
-                               return _firstName;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _firstName)\r
-                               {\r
-                                       OnFirstNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _firstName = value;\r
-                                       SendPropertyChanged("FirstName");\r
-                                       OnFirstNameChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? HireDate\r
-\r
-               private DateTime? _hireDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_hireDate", Name = "HireDate", DbType = "datetime", AutoSync = AutoSync.Never)]\r
-               public DateTime? HireDate\r
-               {\r
-                       get\r
-                       {\r
-                               return _hireDate;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _hireDate)\r
-                               {\r
-                                       OnHireDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _hireDate = value;\r
-                                       SendPropertyChanged("HireDate");\r
-                                       OnHireDateChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string HomePhone\r
-\r
-               private string _homePhone;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_homePhone", Name = "HomePhone", DbType = "nvarchar (24)", AutoSync = AutoSync.Never)]\r
-               public string HomePhone\r
-               {\r
-                       get\r
-                       {\r
-                               return _homePhone;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _homePhone)\r
-                               {\r
-                                       OnHomePhoneChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _homePhone = value;\r
-                                       SendPropertyChanged("HomePhone");\r
-                                       OnHomePhoneChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string LastName\r
-\r
-               private string _lastName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_lastName", Name = "LastName", DbType = "nvarchar (20)", AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public string LastName\r
-               {\r
-                       get\r
-                       {\r
-                               return _lastName;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _lastName)\r
-                               {\r
-                                       OnLastNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _lastName = value;\r
-                                       SendPropertyChanged("LastName");\r
-                                       OnLastNameChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Notes\r
-\r
-               private string _notes;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_notes", Name = "Notes", DbType = "ntext", AutoSync = AutoSync.Never)]\r
-               public string Notes\r
-               {\r
-                       get\r
-                       {\r
-                               return _notes;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _notes)\r
-                               {\r
-                                       OnNotesChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _notes = value;\r
-                                       SendPropertyChanged("Notes");\r
-                                       OnNotesChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Byte[] Photo\r
-\r
-               private Byte[] _photo;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_photo", Name = "Photo", DbType = "image", AutoSync = AutoSync.Never)]\r
-               public Byte[] Photo\r
-               {\r
-                       get\r
-                       {\r
-                               return _photo;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _photo)\r
-                               {\r
-                                       OnPhotoChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _photo = value;\r
-                                       SendPropertyChanged("Photo");\r
-                                       OnPhotoChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string PhotoPath\r
-\r
-               private string _photoPath;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_photoPath", Name = "PhotoPath", DbType = "nvarchar (255)", AutoSync = AutoSync.Never)]\r
-               public string PhotoPath\r
-               {\r
-                       get\r
-                       {\r
-                               return _photoPath;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _photoPath)\r
-                               {\r
-                                       OnPhotoPathChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _photoPath = value;\r
-                                       SendPropertyChanged("PhotoPath");\r
-                                       OnPhotoPathChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string PostalCode\r
-\r
-               private string _postalCode;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_postalCode", Name = "PostalCode", DbType = "nvarchar (10)", AutoSync = AutoSync.Never)]\r
-               public string PostalCode\r
-               {\r
-                       get\r
-                       {\r
-                               return _postalCode;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _postalCode)\r
-                               {\r
-                                       OnPostalCodeChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _postalCode = value;\r
-                                       SendPropertyChanged("PostalCode");\r
-                                       OnPostalCodeChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Region\r
-\r
-               private string _region;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_region", Name = "Region", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
-               public string Region\r
-               {\r
-                       get\r
-                       {\r
-                               return _region;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _region)\r
-                               {\r
-                                       OnRegionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _region = value;\r
-                                       SendPropertyChanged("Region");\r
-                                       OnRegionChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int? ReportsTo\r
-\r
-               private int? _reportsTo;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_reportsTo", Name = "ReportsTo", DbType = "INTEGER", AutoSync = AutoSync.Never)]\r
-               public int? ReportsTo\r
-               {\r
-                       get\r
-                       {\r
-                               return _reportsTo;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _reportsTo)\r
-                               {\r
-                                       if (_reportsToEmployee.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnReportsToChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _reportsTo = value;\r
-                                       SendPropertyChanged("ReportsTo");\r
-                                       OnReportsToChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Title\r
-\r
-               private string _title;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_title", Name = "Title", DbType = "nvarchar (30)", AutoSync = AutoSync.Never)]\r
-               public string Title\r
-               {\r
-                       get\r
-                       {\r
-                               return _title;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _title)\r
-                               {\r
-                                       OnTitleChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _title = value;\r
-                                       SendPropertyChanged("Title");\r
-                                       OnTitleChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string TitleOfCourtesy\r
-\r
-               private string _titleOfCourtesy;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_titleOfCourtesy", Name = "TitleOfCourtesy", DbType = "nvarchar (25)", AutoSync = AutoSync.Never)]\r
-               public string TitleOfCourtesy\r
-               {\r
-                       get\r
-                       {\r
-                               return _titleOfCourtesy;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _titleOfCourtesy)\r
-                               {\r
-                                       OnTitleOfCourtesyChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _titleOfCourtesy = value;\r
-                                       SendPropertyChanged("TitleOfCourtesy");\r
-                                       OnTitleOfCourtesyChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Children\r
-\r
-               private EntitySet<EmployeeTerritory> _employeeTerritories;\r
-               [Association(Storage = "_employeeTerritories", OtherKey = "EmployeeID", ThisKey = "EmployeeID", Name = "fk_EmployeeTerritories_1")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<EmployeeTerritory> EmployeeTerritories\r
-               {\r
-                       get\r
-                       {\r
-                               return _employeeTerritories;\r
-                       }\r
-                       set\r
-                       {\r
-                               _employeeTerritories = value;\r
-                       }\r
-               }\r
-\r
-               private EntitySet<Employee> _employees;\r
-               [Association(Storage = "_employees", OtherKey = "ReportsTo", ThisKey = "EmployeeID", Name = "fk_Employees_0")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<Employee> Employees\r
-               {\r
-                       get\r
-                       {\r
-                               return _employees;\r
-                       }\r
-                       set\r
-                       {\r
-                               _employees = value;\r
-                       }\r
-               }\r
-\r
-               private EntitySet<Order> _orders;\r
-               [Association(Storage = "_orders", OtherKey = "EmployeeID", ThisKey = "EmployeeID", Name = "fk_Orders_1")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<Order> Orders\r
-               {\r
-                       get\r
-                       {\r
-                               return _orders;\r
-                       }\r
-                       set\r
-                       {\r
-                               _orders = value;\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Parents\r
-\r
-               private EntityRef<Employee> _reportsToEmployee;\r
-               [Association(Storage = "_reportsToEmployee", OtherKey = "EmployeeID", ThisKey = "ReportsTo", Name = "fk_Employees_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Employee ReportsToEmployee\r
-               {\r
-                       get\r
-                       {\r
-                               return _reportsToEmployee.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _reportsToEmployee.Entity)\r
-                               {\r
-                                       if (_reportsToEmployee.Entity != null)\r
-                                       {\r
-                                               var previousEmployee = _reportsToEmployee.Entity;\r
-                                               _reportsToEmployee.Entity = null;\r
-                                               previousEmployee.Employees.Remove(this);\r
-                                       }\r
-                                       _reportsToEmployee.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.Employees.Add(this);\r
-                                               _reportsTo = value.EmployeeID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _reportsTo = null;\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void EmployeeTerritories_Attach(EmployeeTerritory entity)\r
-               {\r
-                       entity.Employee = this;\r
-               }\r
-\r
-               private void EmployeeTerritories_Detach(EmployeeTerritory entity)\r
-               {\r
-                       entity.Employee = null;\r
-               }\r
-\r
-               private void Employees_Attach(Employee entity)\r
-               {\r
-                       entity.ReportsToEmployee = this;\r
-               }\r
-\r
-               private void Employees_Detach(Employee entity)\r
-               {\r
-                       entity.ReportsToEmployee = null;\r
-               }\r
-\r
-               private void Orders_Attach(Order entity)\r
-               {\r
-                       entity.Employee = this;\r
-               }\r
-\r
-               private void Orders_Detach(Order entity)\r
-               {\r
-                       entity.Employee = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Employee()\r
-               {\r
-                       _employeeTerritories = new EntitySet<EmployeeTerritory>(EmployeeTerritories_Attach, EmployeeTerritories_Detach);\r
-                       _employees = new EntitySet<Employee>(Employees_Attach, Employees_Detach);\r
-                       _orders = new EntitySet<Order>(Orders_Attach, Orders_Detach);\r
-                       _reportsToEmployee = new EntityRef<Employee>();\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.EmployeeTerritories")]\r
-       public partial class EmployeeTerritory : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnEmployeeIDChanged();\r
-               partial void OnEmployeeIDChanging(int value);\r
-               partial void OnTerritoryIDChanged();\r
-               partial void OnTerritoryIDChanging(string value);\r
-\r
-               #endregion\r
-\r
-               #region int EmployeeID\r
-\r
-               private int _employeeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_employeeID", Name = "EmployeeID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public int EmployeeID\r
-               {\r
-                       get\r
-                       {\r
-                               return _employeeID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _employeeID)\r
-                               {\r
-                                       if (_employee.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnEmployeeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _employeeID = value;\r
-                                       SendPropertyChanged("EmployeeID");\r
-                                       OnEmployeeIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string TerritoryID\r
-\r
-               private string _territoryID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_territoryID", Name = "TerritoryID", DbType = "nvarchar", IsPrimaryKey = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public string TerritoryID\r
-               {\r
-                       get\r
-                       {\r
-                               return _territoryID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _territoryID)\r
-                               {\r
-                                       if (_territory.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnTerritoryIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _territoryID = value;\r
-                                       SendPropertyChanged("TerritoryID");\r
-                                       OnTerritoryIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Parents\r
-\r
-               private EntityRef<Territory> _territory;\r
-               [Association(Storage = "_territory", OtherKey = "TerritoryID", ThisKey = "TerritoryID", Name = "fk_EmployeeTerritories_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Territory Territory\r
-               {\r
-                       get\r
-                       {\r
-                               return _territory.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _territory.Entity)\r
-                               {\r
-                                       if (_territory.Entity != null)\r
-                                       {\r
-                                               var previousTerritory = _territory.Entity;\r
-                                               _territory.Entity = null;\r
-                                               previousTerritory.EmployeeTerritories.Remove(this);\r
-                                       }\r
-                                       _territory.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.EmployeeTerritories.Add(this);\r
-                                               _territoryID = value.TerritoryID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _territoryID = default(string);\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-               private EntityRef<Employee> _employee;\r
-               [Association(Storage = "_employee", OtherKey = "EmployeeID", ThisKey = "EmployeeID", Name = "fk_EmployeeTerritories_1", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Employee Employee\r
-               {\r
-                       get\r
-                       {\r
-                               return _employee.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _employee.Entity)\r
-                               {\r
-                                       if (_employee.Entity != null)\r
-                                       {\r
-                                               var previousEmployee = _employee.Entity;\r
-                                               _employee.Entity = null;\r
-                                               previousEmployee.EmployeeTerritories.Remove(this);\r
-                                       }\r
-                                       _employee.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.EmployeeTerritories.Add(this);\r
-                                               _employeeID = value.EmployeeID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _employeeID = default(int);\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public EmployeeTerritory()\r
-               {\r
-                       _territory = new EntityRef<Territory>();\r
-                       _employee = new EntityRef<Employee>();\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Orders")]\r
-       public partial class Order : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnCustomerIDChanged();\r
-               partial void OnCustomerIDChanging(string value);\r
-               partial void OnEmployeeIDChanged();\r
-               partial void OnEmployeeIDChanging(int? value);\r
-               partial void OnFreightChanged();\r
-               partial void OnFreightChanging(decimal? value);\r
-               partial void OnOrderDateChanged();\r
-               partial void OnOrderDateChanging(DateTime? value);\r
-               partial void OnOrderIDChanged();\r
-               partial void OnOrderIDChanging(int value);\r
-               partial void OnRequiredDateChanged();\r
-               partial void OnRequiredDateChanging(DateTime? value);\r
-               partial void OnShipAddressChanged();\r
-               partial void OnShipAddressChanging(string value);\r
-               partial void OnShipCityChanged();\r
-               partial void OnShipCityChanging(string value);\r
-               partial void OnShipCountryChanged();\r
-               partial void OnShipCountryChanging(string value);\r
-               partial void OnShipNameChanged();\r
-               partial void OnShipNameChanging(string value);\r
-               partial void OnShippedDateChanged();\r
-               partial void OnShippedDateChanging(DateTime? value);\r
-               partial void OnShipPostalCodeChanged();\r
-               partial void OnShipPostalCodeChanging(string value);\r
-               partial void OnShipRegionChanged();\r
-               partial void OnShipRegionChanging(string value);\r
-               partial void OnShipViaChanged();\r
-               partial void OnShipViaChanging(int? value);\r
-\r
-               #endregion\r
-\r
-               #region string CustomerID\r
-\r
-               private string _customerID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerID", Name = "CustomerID", DbType = "nchar (5)", AutoSync = AutoSync.Never)]\r
-               public string CustomerID\r
-               {\r
-                       get\r
-                       {\r
-                               return _customerID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _customerID)\r
-                               {\r
-                                       if (_customer.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnCustomerIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerID = value;\r
-                                       SendPropertyChanged("CustomerID");\r
-                                       OnCustomerIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int? EmployeeID\r
-\r
-               private int? _employeeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_employeeID", Name = "EmployeeID", DbType = "INTEGER", AutoSync = AutoSync.Never)]\r
-               public int? EmployeeID\r
-               {\r
-                       get\r
-                       {\r
-                               return _employeeID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _employeeID)\r
-                               {\r
-                                       if (_employee.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnEmployeeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _employeeID = value;\r
-                                       SendPropertyChanged("EmployeeID");\r
-                                       OnEmployeeIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region decimal? Freight\r
-\r
-               private decimal? _freight;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_freight", Name = "Freight", DbType = "money", AutoSync = AutoSync.Never)]\r
-               public decimal? Freight\r
-               {\r
-                       get\r
-                       {\r
-                               return _freight;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _freight)\r
-                               {\r
-                                       OnFreightChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _freight = value;\r
-                                       SendPropertyChanged("Freight");\r
-                                       OnFreightChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? OrderDate\r
-\r
-               private DateTime? _orderDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_orderDate", Name = "OrderDate", DbType = "datetime", AutoSync = AutoSync.Never)]\r
-               public DateTime? OrderDate\r
-               {\r
-                       get\r
-                       {\r
-                               return _orderDate;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _orderDate)\r
-                               {\r
-                                       OnOrderDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _orderDate = value;\r
-                                       SendPropertyChanged("OrderDate");\r
-                                       OnOrderDateChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int OrderID\r
-\r
-               private int _orderID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_orderID", Name = "OrderID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public int OrderID\r
-               {\r
-                       get\r
-                       {\r
-                               return _orderID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _orderID)\r
-                               {\r
-                                       OnOrderIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _orderID = value;\r
-                                       SendPropertyChanged("OrderID");\r
-                                       OnOrderIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? RequiredDate\r
-\r
-               private DateTime? _requiredDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_requiredDate", Name = "RequiredDate", DbType = "datetime", AutoSync = AutoSync.Never)]\r
-               public DateTime? RequiredDate\r
-               {\r
-                       get\r
-                       {\r
-                               return _requiredDate;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _requiredDate)\r
-                               {\r
-                                       OnRequiredDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _requiredDate = value;\r
-                                       SendPropertyChanged("RequiredDate");\r
-                                       OnRequiredDateChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ShipAddress\r
-\r
-               private string _shipAddress;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipAddress", Name = "ShipAddress", DbType = "nvarchar (60)", AutoSync = AutoSync.Never)]\r
-               public string ShipAddress\r
-               {\r
-                       get\r
-                       {\r
-                               return _shipAddress;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _shipAddress)\r
-                               {\r
-                                       OnShipAddressChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipAddress = value;\r
-                                       SendPropertyChanged("ShipAddress");\r
-                                       OnShipAddressChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ShipCity\r
-\r
-               private string _shipCity;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipCity", Name = "ShipCity", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
-               public string ShipCity\r
-               {\r
-                       get\r
-                       {\r
-                               return _shipCity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _shipCity)\r
-                               {\r
-                                       OnShipCityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipCity = value;\r
-                                       SendPropertyChanged("ShipCity");\r
-                                       OnShipCityChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ShipCountry\r
-\r
-               private string _shipCountry;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipCountry", Name = "ShipCountry", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
-               public string ShipCountry\r
-               {\r
-                       get\r
-                       {\r
-                               return _shipCountry;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _shipCountry)\r
-                               {\r
-                                       OnShipCountryChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipCountry = value;\r
-                                       SendPropertyChanged("ShipCountry");\r
-                                       OnShipCountryChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ShipName\r
-\r
-               private string _shipName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipName", Name = "ShipName", DbType = "nvarchar (40)", AutoSync = AutoSync.Never)]\r
-               public string ShipName\r
-               {\r
-                       get\r
-                       {\r
-                               return _shipName;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _shipName)\r
-                               {\r
-                                       OnShipNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipName = value;\r
-                                       SendPropertyChanged("ShipName");\r
-                                       OnShipNameChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? ShippedDate\r
-\r
-               private DateTime? _shippedDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shippedDate", Name = "ShippedDate", DbType = "datetime", AutoSync = AutoSync.Never)]\r
-               public DateTime? ShippedDate\r
-               {\r
-                       get\r
-                       {\r
-                               return _shippedDate;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _shippedDate)\r
-                               {\r
-                                       OnShippedDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shippedDate = value;\r
-                                       SendPropertyChanged("ShippedDate");\r
-                                       OnShippedDateChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ShipPostalCode\r
-\r
-               private string _shipPostalCode;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipPostalCode", Name = "ShipPostalCode", DbType = "nvarchar (10)", AutoSync = AutoSync.Never)]\r
-               public string ShipPostalCode\r
-               {\r
-                       get\r
-                       {\r
-                               return _shipPostalCode;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _shipPostalCode)\r
-                               {\r
-                                       OnShipPostalCodeChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipPostalCode = value;\r
-                                       SendPropertyChanged("ShipPostalCode");\r
-                                       OnShipPostalCodeChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ShipRegion\r
-\r
-               private string _shipRegion;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipRegion", Name = "ShipRegion", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
-               public string ShipRegion\r
-               {\r
-                       get\r
-                       {\r
-                               return _shipRegion;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _shipRegion)\r
-                               {\r
-                                       OnShipRegionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipRegion = value;\r
-                                       SendPropertyChanged("ShipRegion");\r
-                                       OnShipRegionChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int? ShipVia\r
-\r
-               private int? _shipVia;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipVia", Name = "ShipVia", DbType = "INTEGER", AutoSync = AutoSync.Never)]\r
-               public int? ShipVia\r
-               {\r
-                       get\r
-                       {\r
-                               return _shipVia;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _shipVia)\r
-                               {\r
-                                       if (_shipper.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnShipViaChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipVia = value;\r
-                                       SendPropertyChanged("ShipVia");\r
-                                       OnShipViaChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Children\r
-\r
-               private EntitySet<OrderDetail> _orderDetails;\r
-               [Association(Storage = "_orderDetails", OtherKey = "OrderID", ThisKey = "OrderID", Name = "\"fk_Order Details_1\"")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<OrderDetail> OrderDetails\r
-               {\r
-                       get\r
-                       {\r
-                               return _orderDetails;\r
-                       }\r
-                       set\r
-                       {\r
-                               _orderDetails = value;\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Parents\r
-\r
-               private EntityRef<Shipper> _shipper;\r
-               [Association(Storage = "_shipper", OtherKey = "ShipperID", ThisKey = "ShipVia", Name = "fk_Orders_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Shipper Shipper\r
-               {\r
-                       get\r
-                       {\r
-                               return _shipper.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _shipper.Entity)\r
-                               {\r
-                                       if (_shipper.Entity != null)\r
-                                       {\r
-                                               var previousShipper = _shipper.Entity;\r
-                                               _shipper.Entity = null;\r
-                                               previousShipper.Orders.Remove(this);\r
-                                       }\r
-                                       _shipper.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.Orders.Add(this);\r
-                                               _shipVia = value.ShipperID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _shipVia = null;\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-               private EntityRef<Employee> _employee;\r
-               [Association(Storage = "_employee", OtherKey = "EmployeeID", ThisKey = "EmployeeID", Name = "fk_Orders_1", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Employee Employee\r
-               {\r
-                       get\r
-                       {\r
-                               return _employee.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _employee.Entity)\r
-                               {\r
-                                       if (_employee.Entity != null)\r
-                                       {\r
-                                               var previousEmployee = _employee.Entity;\r
-                                               _employee.Entity = null;\r
-                                               previousEmployee.Orders.Remove(this);\r
-                                       }\r
-                                       _employee.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.Orders.Add(this);\r
-                                               _employeeID = value.EmployeeID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _employeeID = null;\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-               private EntityRef<Customer> _customer;\r
-               [Association(Storage = "_customer", OtherKey = "CustomerID", ThisKey = "CustomerID", Name = "fk_Orders_2", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Customer Customer\r
-               {\r
-                       get\r
-                       {\r
-                               return _customer.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _customer.Entity)\r
-                               {\r
-                                       if (_customer.Entity != null)\r
-                                       {\r
-                                               var previousCustomer = _customer.Entity;\r
-                                               _customer.Entity = null;\r
-                                               previousCustomer.Orders.Remove(this);\r
-                                       }\r
-                                       _customer.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.Orders.Add(this);\r
-                                               _customerID = value.CustomerID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _customerID = null;\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void OrderDetails_Attach(OrderDetail entity)\r
-               {\r
-                       entity.Order = this;\r
-               }\r
-\r
-               private void OrderDetails_Detach(OrderDetail entity)\r
-               {\r
-                       entity.Order = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Order()\r
-               {\r
-                       _orderDetails = new EntitySet<OrderDetail>(OrderDetails_Attach, OrderDetails_Detach);\r
-                       _shipper = new EntityRef<Shipper>();\r
-                       _employee = new EntityRef<Employee>();\r
-                       _customer = new EntityRef<Customer>();\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.\"Order Details\"")]\r
-       public partial class OrderDetail : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnDiscountChanged();\r
-               partial void OnDiscountChanging(float value);\r
-               partial void OnOrderIDChanged();\r
-               partial void OnOrderIDChanging(int value);\r
-               partial void OnProductIDChanged();\r
-               partial void OnProductIDChanging(int value);\r
-               partial void OnQuantityChanged();\r
-               partial void OnQuantityChanging(short value);\r
-               partial void OnUnitPriceChanged();\r
-               partial void OnUnitPriceChanging(decimal value);\r
-\r
-               #endregion\r
-\r
-               #region float Discount\r
-\r
-               private float _discount;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_discount", Name = "Discount", DbType = "real", AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public float Discount\r
-               {\r
-                       get\r
-                       {\r
-                               return _discount;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _discount)\r
-                               {\r
-                                       OnDiscountChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _discount = value;\r
-                                       SendPropertyChanged("Discount");\r
-                                       OnDiscountChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int OrderID\r
-\r
-               private int _orderID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_orderID", Name = "OrderID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public int OrderID\r
-               {\r
-                       get\r
-                       {\r
-                               return _orderID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _orderID)\r
-                               {\r
-                                       if (_order.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnOrderIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _orderID = value;\r
-                                       SendPropertyChanged("OrderID");\r
-                                       OnOrderIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int ProductID\r
-\r
-               private int _productID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_productID", Name = "ProductID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public int ProductID\r
-               {\r
-                       get\r
-                       {\r
-                               return _productID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _productID)\r
-                               {\r
-                                       if (_product.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnProductIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _productID = value;\r
-                                       SendPropertyChanged("ProductID");\r
-                                       OnProductIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region short Quantity\r
-\r
-               private short _quantity;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_quantity", Name = "Quantity", DbType = "smallint", AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public short Quantity\r
-               {\r
-                       get\r
-                       {\r
-                               return _quantity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _quantity)\r
-                               {\r
-                                       OnQuantityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _quantity = value;\r
-                                       SendPropertyChanged("Quantity");\r
-                                       OnQuantityChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region decimal UnitPrice\r
-\r
-               private decimal _unitPrice;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_unitPrice", Name = "UnitPrice", DbType = "money", AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public decimal UnitPrice\r
-               {\r
-                       get\r
-                       {\r
-                               return _unitPrice;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _unitPrice)\r
-                               {\r
-                                       OnUnitPriceChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _unitPrice = value;\r
-                                       SendPropertyChanged("UnitPrice");\r
-                                       OnUnitPriceChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Parents\r
-\r
-               private EntityRef<Product> _product;\r
-               [Association(Storage = "_product", OtherKey = "ProductID", ThisKey = "ProductID", Name = "\"fk_Order Details_0\"", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Product Product\r
-               {\r
-                       get\r
-                       {\r
-                               return _product.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _product.Entity)\r
-                               {\r
-                                       if (_product.Entity != null)\r
-                                       {\r
-                                               var previousProduct = _product.Entity;\r
-                                               _product.Entity = null;\r
-                                               previousProduct.OrderDetails.Remove(this);\r
-                                       }\r
-                                       _product.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.OrderDetails.Add(this);\r
-                                               _productID = value.ProductID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _productID = default(int);\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-               private EntityRef<Order> _order;\r
-               [Association(Storage = "_order", OtherKey = "OrderID", ThisKey = "OrderID", Name = "\"fk_Order Details_1\"", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Order Order\r
-               {\r
-                       get\r
-                       {\r
-                               return _order.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _order.Entity)\r
-                               {\r
-                                       if (_order.Entity != null)\r
-                                       {\r
-                                               var previousOrder = _order.Entity;\r
-                                               _order.Entity = null;\r
-                                               previousOrder.OrderDetails.Remove(this);\r
-                                       }\r
-                                       _order.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.OrderDetails.Add(this);\r
-                                               _orderID = value.OrderID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _orderID = default(int);\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public OrderDetail()\r
-               {\r
-                       _product = new EntityRef<Product>();\r
-                       _order = new EntityRef<Order>();\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Products")]\r
-       public partial class Product : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnCategoryIDChanged();\r
-               partial void OnCategoryIDChanging(int? value);\r
-               partial void OnDiscontinuedChanged();\r
-               partial void OnDiscontinuedChanging(bool value);\r
-               partial void OnProductIDChanged();\r
-               partial void OnProductIDChanging(int value);\r
-               partial void OnProductNameChanged();\r
-               partial void OnProductNameChanging(string value);\r
-               partial void OnQuantityPerUnitChanged();\r
-               partial void OnQuantityPerUnitChanging(string value);\r
-               partial void OnReorderLevelChanged();\r
-               partial void OnReorderLevelChanging(short? value);\r
-               partial void OnSupplierIDChanged();\r
-               partial void OnSupplierIDChanging(int? value);\r
-               partial void OnUnitPriceChanged();\r
-               partial void OnUnitPriceChanging(decimal? value);\r
-               partial void OnUnitsInStockChanged();\r
-               partial void OnUnitsInStockChanging(short? value);\r
-               partial void OnUnitsOnOrderChanged();\r
-               partial void OnUnitsOnOrderChanging(short? value);\r
-\r
-               #endregion\r
-\r
-               #region int? CategoryID\r
-\r
-               private int? _categoryID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_categoryID", Name = "CategoryID", DbType = "INTEGER", AutoSync = AutoSync.Never)]\r
-               public int? CategoryID\r
-               {\r
-                       get\r
-                       {\r
-                               return _categoryID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _categoryID)\r
-                               {\r
-                                       if (_category.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnCategoryIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _categoryID = value;\r
-                                       SendPropertyChanged("CategoryID");\r
-                                       OnCategoryIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region bool Discontinued\r
-\r
-               private bool _discontinued;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_discontinued", Name = "Discontinued", DbType = "bit", AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public bool Discontinued\r
-               {\r
-                       get\r
-                       {\r
-                               return _discontinued;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _discontinued)\r
-                               {\r
-                                       OnDiscontinuedChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _discontinued = value;\r
-                                       SendPropertyChanged("Discontinued");\r
-                                       OnDiscontinuedChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int ProductID\r
-\r
-               private int _productID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_productID", Name = "ProductID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public int ProductID\r
-               {\r
-                       get\r
-                       {\r
-                               return _productID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _productID)\r
-                               {\r
-                                       OnProductIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _productID = value;\r
-                                       SendPropertyChanged("ProductID");\r
-                                       OnProductIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ProductName\r
-\r
-               private string _productName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_productName", Name = "ProductName", DbType = "nvarchar (40)", AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public string ProductName\r
-               {\r
-                       get\r
-                       {\r
-                               return _productName;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _productName)\r
-                               {\r
-                                       OnProductNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _productName = value;\r
-                                       SendPropertyChanged("ProductName");\r
-                                       OnProductNameChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string QuantityPerUnit\r
-\r
-               private string _quantityPerUnit;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_quantityPerUnit", Name = "QuantityPerUnit", DbType = "nvarchar (20)", AutoSync = AutoSync.Never)]\r
-               public string QuantityPerUnit\r
-               {\r
-                       get\r
-                       {\r
-                               return _quantityPerUnit;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _quantityPerUnit)\r
-                               {\r
-                                       OnQuantityPerUnitChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _quantityPerUnit = value;\r
-                                       SendPropertyChanged("QuantityPerUnit");\r
-                                       OnQuantityPerUnitChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region short? ReorderLevel\r
-\r
-               private short? _reorderLevel;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_reorderLevel", Name = "ReorderLevel", DbType = "smallint", AutoSync = AutoSync.Never)]\r
-               public short? ReorderLevel\r
-               {\r
-                       get\r
-                       {\r
-                               return _reorderLevel;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _reorderLevel)\r
-                               {\r
-                                       OnReorderLevelChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _reorderLevel = value;\r
-                                       SendPropertyChanged("ReorderLevel");\r
-                                       OnReorderLevelChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int? SupplierID\r
-\r
-               private int? _supplierID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_supplierID", Name = "SupplierID", DbType = "INTEGER", AutoSync = AutoSync.Never)]\r
-               public int? SupplierID\r
-               {\r
-                       get\r
-                       {\r
-                               return _supplierID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _supplierID)\r
-                               {\r
-                                       if (_supplier.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnSupplierIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _supplierID = value;\r
-                                       SendPropertyChanged("SupplierID");\r
-                                       OnSupplierIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region decimal? UnitPrice\r
-\r
-               private decimal? _unitPrice;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_unitPrice", Name = "UnitPrice", DbType = "money", AutoSync = AutoSync.Never)]\r
-               public decimal? UnitPrice\r
-               {\r
-                       get\r
-                       {\r
-                               return _unitPrice;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _unitPrice)\r
-                               {\r
-                                       OnUnitPriceChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _unitPrice = value;\r
-                                       SendPropertyChanged("UnitPrice");\r
-                                       OnUnitPriceChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region short? UnitsInStock\r
-\r
-               private short? _unitsInStock;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_unitsInStock", Name = "UnitsInStock", DbType = "smallint", AutoSync = AutoSync.Never)]\r
-               public short? UnitsInStock\r
-               {\r
-                       get\r
-                       {\r
-                               return _unitsInStock;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _unitsInStock)\r
-                               {\r
-                                       OnUnitsInStockChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _unitsInStock = value;\r
-                                       SendPropertyChanged("UnitsInStock");\r
-                                       OnUnitsInStockChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region short? UnitsOnOrder\r
-\r
-               private short? _unitsOnOrder;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_unitsOnOrder", Name = "UnitsOnOrder", DbType = "smallint", AutoSync = AutoSync.Never)]\r
-               public short? UnitsOnOrder\r
-               {\r
-                       get\r
-                       {\r
-                               return _unitsOnOrder;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _unitsOnOrder)\r
-                               {\r
-                                       OnUnitsOnOrderChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _unitsOnOrder = value;\r
-                                       SendPropertyChanged("UnitsOnOrder");\r
-                                       OnUnitsOnOrderChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Children\r
-\r
-               private EntitySet<OrderDetail> _orderDetails;\r
-               [Association(Storage = "_orderDetails", OtherKey = "ProductID", ThisKey = "ProductID", Name = "\"fk_Order Details_0\"")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<OrderDetail> OrderDetails\r
-               {\r
-                       get\r
-                       {\r
-                               return _orderDetails;\r
-                       }\r
-                       set\r
-                       {\r
-                               _orderDetails = value;\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Parents\r
-\r
-               private EntityRef<Supplier> _supplier;\r
-               [Association(Storage = "_supplier", OtherKey = "SupplierID", ThisKey = "SupplierID", Name = "fk_Products_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Supplier Supplier\r
-               {\r
-                       get\r
-                       {\r
-                               return _supplier.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _supplier.Entity)\r
-                               {\r
-                                       if (_supplier.Entity != null)\r
-                                       {\r
-                                               var previousSupplier = _supplier.Entity;\r
-                                               _supplier.Entity = null;\r
-                                               previousSupplier.Products.Remove(this);\r
-                                       }\r
-                                       _supplier.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.Products.Add(this);\r
-                                               _supplierID = value.SupplierID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _supplierID = null;\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-               private EntityRef<Category> _category;\r
-               [Association(Storage = "_category", OtherKey = "CategoryID", ThisKey = "CategoryID", Name = "fk_Products_1", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Category Category\r
-               {\r
-                       get\r
-                       {\r
-                               return _category.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _category.Entity)\r
-                               {\r
-                                       if (_category.Entity != null)\r
-                                       {\r
-                                               var previousCategory = _category.Entity;\r
-                                               _category.Entity = null;\r
-                                               previousCategory.Products.Remove(this);\r
-                                       }\r
-                                       _category.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.Products.Add(this);\r
-                                               _categoryID = value.CategoryID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _categoryID = null;\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void OrderDetails_Attach(OrderDetail entity)\r
-               {\r
-                       entity.Product = this;\r
-               }\r
-\r
-               private void OrderDetails_Detach(OrderDetail entity)\r
-               {\r
-                       entity.Product = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Product()\r
-               {\r
-                       _orderDetails = new EntitySet<OrderDetail>(OrderDetails_Attach, OrderDetails_Detach);\r
-                       _supplier = new EntityRef<Supplier>();\r
-                       _category = new EntityRef<Category>();\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Region")]\r
-       public partial class Region : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnRegionDescriptionChanged();\r
-               partial void OnRegionDescriptionChanging(string value);\r
-               partial void OnRegionIDChanged();\r
-               partial void OnRegionIDChanging(int value);\r
-\r
-               #endregion\r
-\r
-               #region string RegionDescription\r
-\r
-               private string _regionDescription;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_regionDescription", Name = "RegionDescription", DbType = "nchar", AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public string RegionDescription\r
-               {\r
-                       get\r
-                       {\r
-                               return _regionDescription;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _regionDescription)\r
-                               {\r
-                                       OnRegionDescriptionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _regionDescription = value;\r
-                                       SendPropertyChanged("RegionDescription");\r
-                                       OnRegionDescriptionChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int RegionID\r
-\r
-               private int _regionID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_regionID", Name = "RegionID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public int RegionID\r
-               {\r
-                       get\r
-                       {\r
-                               return _regionID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _regionID)\r
-                               {\r
-                                       OnRegionIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _regionID = value;\r
-                                       SendPropertyChanged("RegionID");\r
-                                       OnRegionIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Children\r
-\r
-               private EntitySet<Territory> _territories;\r
-               [Association(Storage = "_territories", OtherKey = "RegionID", ThisKey = "RegionID", Name = "fk_Territories_0")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<Territory> Territories\r
-               {\r
-                       get\r
-                       {\r
-                               return _territories;\r
-                       }\r
-                       set\r
-                       {\r
-                               _territories = value;\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void Territories_Attach(Territory entity)\r
-               {\r
-                       entity.Region = this;\r
-               }\r
-\r
-               private void Territories_Detach(Territory entity)\r
-               {\r
-                       entity.Region = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Region()\r
-               {\r
-                       _territories = new EntitySet<Territory>(Territories_Attach, Territories_Detach);\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Shippers")]\r
-       public partial class Shipper : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnCompanyNameChanged();\r
-               partial void OnCompanyNameChanging(string value);\r
-               partial void OnPhoneChanged();\r
-               partial void OnPhoneChanging(string value);\r
-               partial void OnShipperIDChanged();\r
-               partial void OnShipperIDChanging(int value);\r
-\r
-               #endregion\r
-\r
-               #region string CompanyName\r
-\r
-               private string _companyName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_companyName", Name = "CompanyName", DbType = "nvarchar (40)", AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public string CompanyName\r
-               {\r
-                       get\r
-                       {\r
-                               return _companyName;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _companyName)\r
-                               {\r
-                                       OnCompanyNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _companyName = value;\r
-                                       SendPropertyChanged("CompanyName");\r
-                                       OnCompanyNameChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Phone\r
-\r
-               private string _phone;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_phone", Name = "Phone", DbType = "nvarchar (24)", AutoSync = AutoSync.Never)]\r
-               public string Phone\r
-               {\r
-                       get\r
-                       {\r
-                               return _phone;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _phone)\r
-                               {\r
-                                       OnPhoneChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _phone = value;\r
-                                       SendPropertyChanged("Phone");\r
-                                       OnPhoneChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int ShipperID\r
-\r
-               private int _shipperID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipperID", Name = "ShipperID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public int ShipperID\r
-               {\r
-                       get\r
-                       {\r
-                               return _shipperID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _shipperID)\r
-                               {\r
-                                       OnShipperIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipperID = value;\r
-                                       SendPropertyChanged("ShipperID");\r
-                                       OnShipperIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Children\r
-\r
-               private EntitySet<Order> _orders;\r
-               [Association(Storage = "_orders", OtherKey = "ShipVia", ThisKey = "ShipperID", Name = "fk_Orders_0")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<Order> Orders\r
-               {\r
-                       get\r
-                       {\r
-                               return _orders;\r
-                       }\r
-                       set\r
-                       {\r
-                               _orders = value;\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void Orders_Attach(Order entity)\r
-               {\r
-                       entity.Shipper = this;\r
-               }\r
-\r
-               private void Orders_Detach(Order entity)\r
-               {\r
-                       entity.Shipper = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Shipper()\r
-               {\r
-                       _orders = new EntitySet<Order>(Orders_Attach, Orders_Detach);\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Suppliers")]\r
-       public partial class Supplier : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnAddressChanged();\r
-               partial void OnAddressChanging(string value);\r
-               partial void OnCityChanged();\r
-               partial void OnCityChanging(string value);\r
-               partial void OnCompanyNameChanged();\r
-               partial void OnCompanyNameChanging(string value);\r
-               partial void OnContactNameChanged();\r
-               partial void OnContactNameChanging(string value);\r
-               partial void OnContactTitleChanged();\r
-               partial void OnContactTitleChanging(string value);\r
-               partial void OnCountryChanged();\r
-               partial void OnCountryChanging(string value);\r
-               partial void OnFaxChanged();\r
-               partial void OnFaxChanging(string value);\r
-               partial void OnHomePageChanged();\r
-               partial void OnHomePageChanging(string value);\r
-               partial void OnPhoneChanged();\r
-               partial void OnPhoneChanging(string value);\r
-               partial void OnPostalCodeChanged();\r
-               partial void OnPostalCodeChanging(string value);\r
-               partial void OnRegionChanged();\r
-               partial void OnRegionChanging(string value);\r
-               partial void OnSupplierIDChanged();\r
-               partial void OnSupplierIDChanging(int value);\r
-\r
-               #endregion\r
-\r
-               #region string Address\r
-\r
-               private string _address;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_address", Name = "Address", DbType = "nvarchar (60)", AutoSync = AutoSync.Never)]\r
-               public string Address\r
-               {\r
-                       get\r
-                       {\r
-                               return _address;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _address)\r
-                               {\r
-                                       OnAddressChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _address = value;\r
-                                       SendPropertyChanged("Address");\r
-                                       OnAddressChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string City\r
-\r
-               private string _city;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_city", Name = "City", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
-               public string City\r
-               {\r
-                       get\r
-                       {\r
-                               return _city;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _city)\r
-                               {\r
-                                       OnCityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _city = value;\r
-                                       SendPropertyChanged("City");\r
-                                       OnCityChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string CompanyName\r
-\r
-               private string _companyName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_companyName", Name = "CompanyName", DbType = "nvarchar (40)", AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public string CompanyName\r
-               {\r
-                       get\r
-                       {\r
-                               return _companyName;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _companyName)\r
-                               {\r
-                                       OnCompanyNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _companyName = value;\r
-                                       SendPropertyChanged("CompanyName");\r
-                                       OnCompanyNameChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ContactName\r
-\r
-               private string _contactName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_contactName", Name = "ContactName", DbType = "nvarchar (30)", AutoSync = AutoSync.Never)]\r
-               public string ContactName\r
-               {\r
-                       get\r
-                       {\r
-                               return _contactName;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _contactName)\r
-                               {\r
-                                       OnContactNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _contactName = value;\r
-                                       SendPropertyChanged("ContactName");\r
-                                       OnContactNameChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ContactTitle\r
-\r
-               private string _contactTitle;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_contactTitle", Name = "ContactTitle", DbType = "nvarchar (30)", AutoSync = AutoSync.Never)]\r
-               public string ContactTitle\r
-               {\r
-                       get\r
-                       {\r
-                               return _contactTitle;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _contactTitle)\r
-                               {\r
-                                       OnContactTitleChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _contactTitle = value;\r
-                                       SendPropertyChanged("ContactTitle");\r
-                                       OnContactTitleChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Country\r
-\r
-               private string _country;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_country", Name = "Country", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
-               public string Country\r
-               {\r
-                       get\r
-                       {\r
-                               return _country;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _country)\r
-                               {\r
-                                       OnCountryChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _country = value;\r
-                                       SendPropertyChanged("Country");\r
-                                       OnCountryChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Fax\r
-\r
-               private string _fax;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_fax", Name = "Fax", DbType = "nvarchar (24)", AutoSync = AutoSync.Never)]\r
-               public string Fax\r
-               {\r
-                       get\r
-                       {\r
-                               return _fax;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _fax)\r
-                               {\r
-                                       OnFaxChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _fax = value;\r
-                                       SendPropertyChanged("Fax");\r
-                                       OnFaxChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string HomePage\r
-\r
-               private string _homePage;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_homePage", Name = "HomePage", DbType = "ntext", AutoSync = AutoSync.Never)]\r
-               public string HomePage\r
-               {\r
-                       get\r
-                       {\r
-                               return _homePage;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _homePage)\r
-                               {\r
-                                       OnHomePageChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _homePage = value;\r
-                                       SendPropertyChanged("HomePage");\r
-                                       OnHomePageChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Phone\r
-\r
-               private string _phone;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_phone", Name = "Phone", DbType = "nvarchar (24)", AutoSync = AutoSync.Never)]\r
-               public string Phone\r
-               {\r
-                       get\r
-                       {\r
-                               return _phone;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _phone)\r
-                               {\r
-                                       OnPhoneChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _phone = value;\r
-                                       SendPropertyChanged("Phone");\r
-                                       OnPhoneChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string PostalCode\r
-\r
-               private string _postalCode;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_postalCode", Name = "PostalCode", DbType = "nvarchar (10)", AutoSync = AutoSync.Never)]\r
-               public string PostalCode\r
-               {\r
-                       get\r
-                       {\r
-                               return _postalCode;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _postalCode)\r
-                               {\r
-                                       OnPostalCodeChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _postalCode = value;\r
-                                       SendPropertyChanged("PostalCode");\r
-                                       OnPostalCodeChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Region\r
-\r
-               private string _region;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_region", Name = "Region", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
-               public string Region\r
-               {\r
-                       get\r
-                       {\r
-                               return _region;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _region)\r
-                               {\r
-                                       OnRegionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _region = value;\r
-                                       SendPropertyChanged("Region");\r
-                                       OnRegionChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int SupplierID\r
-\r
-               private int _supplierID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_supplierID", Name = "SupplierID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public int SupplierID\r
-               {\r
-                       get\r
-                       {\r
-                               return _supplierID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _supplierID)\r
-                               {\r
-                                       OnSupplierIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _supplierID = value;\r
-                                       SendPropertyChanged("SupplierID");\r
-                                       OnSupplierIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Children\r
-\r
-               private EntitySet<Product> _products;\r
-               [Association(Storage = "_products", OtherKey = "SupplierID", ThisKey = "SupplierID", Name = "fk_Products_0")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<Product> Products\r
-               {\r
-                       get\r
-                       {\r
-                               return _products;\r
-                       }\r
-                       set\r
-                       {\r
-                               _products = value;\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void Products_Attach(Product entity)\r
-               {\r
-                       entity.Supplier = this;\r
-               }\r
-\r
-               private void Products_Detach(Product entity)\r
-               {\r
-                       entity.Supplier = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Supplier()\r
-               {\r
-                       _products = new EntitySet<Product>(Products_Attach, Products_Detach);\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Territories")]\r
-       public partial class Territory : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnRegionIDChanged();\r
-               partial void OnRegionIDChanging(int value);\r
-               partial void OnTerritoryDescriptionChanged();\r
-               partial void OnTerritoryDescriptionChanging(string value);\r
-               partial void OnTerritoryIDChanged();\r
-               partial void OnTerritoryIDChanging(string value);\r
-\r
-               #endregion\r
-\r
-               #region int RegionID\r
-\r
-               private int _regionID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_regionID", Name = "RegionID", DbType = "INTEGER", AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public int RegionID\r
-               {\r
-                       get\r
-                       {\r
-                               return _regionID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _regionID)\r
-                               {\r
-                                       if (_region.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnRegionIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _regionID = value;\r
-                                       SendPropertyChanged("RegionID");\r
-                                       OnRegionIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string TerritoryDescription\r
-\r
-               private string _territoryDescription;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_territoryDescription", Name = "TerritoryDescription", DbType = "nchar", AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public string TerritoryDescription\r
-               {\r
-                       get\r
-                       {\r
-                               return _territoryDescription;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _territoryDescription)\r
-                               {\r
-                                       OnTerritoryDescriptionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _territoryDescription = value;\r
-                                       SendPropertyChanged("TerritoryDescription");\r
-                                       OnTerritoryDescriptionChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string TerritoryID\r
-\r
-               private string _territoryID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_territoryID", Name = "TerritoryID", DbType = "nvarchar", IsPrimaryKey = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
-               public string TerritoryID\r
-               {\r
-                       get\r
-                       {\r
-                               return _territoryID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _territoryID)\r
-                               {\r
-                                       OnTerritoryIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _territoryID = value;\r
-                                       SendPropertyChanged("TerritoryID");\r
-                                       OnTerritoryIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Children\r
-\r
-               private EntitySet<EmployeeTerritory> _employeeTerritories;\r
-               [Association(Storage = "_employeeTerritories", OtherKey = "TerritoryID", ThisKey = "TerritoryID", Name = "fk_EmployeeTerritories_0")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<EmployeeTerritory> EmployeeTerritories\r
-               {\r
-                       get\r
-                       {\r
-                               return _employeeTerritories;\r
-                       }\r
-                       set\r
-                       {\r
-                               _employeeTerritories = value;\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Parents\r
-\r
-               private EntityRef<Region> _region;\r
-               [Association(Storage = "_region", OtherKey = "RegionID", ThisKey = "RegionID", Name = "fk_Territories_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Region Region\r
-               {\r
-                       get\r
-                       {\r
-                               return _region.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _region.Entity)\r
-                               {\r
-                                       if (_region.Entity != null)\r
-                                       {\r
-                                               var previousRegion = _region.Entity;\r
-                                               _region.Entity = null;\r
-                                               previousRegion.Territories.Remove(this);\r
-                                       }\r
-                                       _region.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.Territories.Add(this);\r
-                                               _regionID = value.RegionID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _regionID = default(int);\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void EmployeeTerritories_Attach(EmployeeTerritory entity)\r
-               {\r
-                       entity.Territory = this;\r
-               }\r
-\r
-               private void EmployeeTerritories_Detach(EmployeeTerritory entity)\r
-               {\r
-                       entity.Territory = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Territory()\r
-               {\r
-                       _employeeTerritories = new EntitySet<EmployeeTerritory>(EmployeeTerritories_Attach, EmployeeTerritories_Detach);\r
-                       _region = new EntityRef<Region>();\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-}\r
diff --git a/mcs/class/System.Data.Linq/tests/Northwind.Expected.Sqlite-sqlmetal.cs b/mcs/class/System.Data.Linq/tests/Northwind.Expected.Sqlite-sqlmetal.cs
deleted file mode 100755 (executable)
index 5478096..0000000
+++ /dev/null
@@ -1,4140 +0,0 @@
-#region Auto-generated classes for Northwind database on [TIMESTAMP]\r
-\r
-//\r
-//  ____  _     __  __      _        _\r
-// |  _ \| |__ |  \/  | ___| |_ __ _| |\r
-// | | | | '_ \| |\/| |/ _ \ __/ _` | |\r
-// | |_| | |_) | |  | |  __/ || (_| | |\r
-// |____/|_.__/|_|  |_|\___|\__\__,_|_|\r
-//\r
-// Auto-generated from Northwind on [TIMESTAMP]\r
-// Please visit http://linq.to/db for more information\r
-\r
-#endregion\r
-\r
-using System;\r
-using System.Data;\r
-using System.Data.Linq.Mapping;\r
-using System.Diagnostics;\r
-using System.Reflection;\r
-using System.Data.Linq;\r
-using System.ComponentModel;\r
-\r
-namespace nwind\r
-{\r
-       public partial class Northwind : DataContext\r
-       {\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-\r
-               #endregion\r
-\r
-               public Northwind(string connectionString)\r
-                       : base(connectionString)\r
-               {\r
-                       OnCreated();\r
-               }\r
-\r
-               public Northwind(IDbConnection connection)\r
-                       : base(connection)\r
-               {\r
-                       OnCreated();\r
-               }\r
-\r
-               public Northwind(string connection, MappingSource mappingSource)\r
-                       : base(connection, mappingSource)\r
-               {\r
-                       OnCreated();\r
-               }\r
-\r
-               public Northwind(IDbConnection connection, MappingSource mappingSource)\r
-                       : base(connection, mappingSource)\r
-               {\r
-                       OnCreated();\r
-               }\r
-\r
-               public Table<Category> Categories { get { return GetTable<Category>(); } }\r
-               public Table<Customer> Customers { get { return GetTable<Customer>(); } }\r
-               public Table<CustomerCustomerDemo> CustomerCustomerDemo { get { return GetTable<CustomerCustomerDemo>(); } }\r
-               public Table<CustomerDemographic> CustomerDemographics { get { return GetTable<CustomerDemographic>(); } }\r
-               public Table<Employee> Employees { get { return GetTable<Employee>(); } }\r
-               public Table<EmployeeTerritory> EmployeeTerritories { get { return GetTable<EmployeeTerritory>(); } }\r
-               public Table<Order> Orders { get { return GetTable<Order>(); } }\r
-               public Table<OrderDetail> OrderDetails { get { return GetTable<OrderDetail>(); } }\r
-               public Table<Product> Products { get { return GetTable<Product>(); } }\r
-               public Table<Region> Regions { get { return GetTable<Region>(); } }\r
-               public Table<Shipper> Shippers { get { return GetTable<Shipper>(); } }\r
-               public Table<Supplier> Suppliers { get { return GetTable<Supplier>(); } }\r
-               public Table<Territory> Territories { get { return GetTable<Territory>(); } }\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Categories")]\r
-       public partial class Category : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnCategoryIDChanged();\r
-               partial void OnCategoryIDChanging(int value);\r
-               partial void OnCategoryNameChanged();\r
-               partial void OnCategoryNameChanging(string value);\r
-               partial void OnDescriptionChanged();\r
-               partial void OnDescriptionChanging(string value);\r
-               partial void OnPictureChanged();\r
-               partial void OnPictureChanging(Byte[] value);\r
-\r
-               #endregion\r
-\r
-               #region int CategoryID\r
-\r
-               private int _categoryID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_categoryID", Name = "CategoryID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never)]\r
-               public int CategoryID\r
-               {\r
-                       get\r
-                       {\r
-                               return _categoryID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _categoryID)\r
-                               {\r
-                                       OnCategoryIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _categoryID = value;\r
-                                       SendPropertyChanged("CategoryID");\r
-                                       OnCategoryIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string CategoryName\r
-\r
-               private string _categoryName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_categoryName", Name = "CategoryName", DbType = "nvarchar (15)", AutoSync = AutoSync.Never)]\r
-               public string CategoryName\r
-               {\r
-                       get\r
-                       {\r
-                               return _categoryName;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _categoryName)\r
-                               {\r
-                                       OnCategoryNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _categoryName = value;\r
-                                       SendPropertyChanged("CategoryName");\r
-                                       OnCategoryNameChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Description\r
-\r
-               private string _description;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_description", Name = "Description", DbType = "ntext", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string Description\r
-               {\r
-                       get\r
-                       {\r
-                               return _description;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _description)\r
-                               {\r
-                                       OnDescriptionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _description = value;\r
-                                       SendPropertyChanged("Description");\r
-                                       OnDescriptionChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Byte[] Picture\r
-\r
-               private Byte[] _picture;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_picture", Name = "Picture", DbType = "image", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public Byte[] Picture\r
-               {\r
-                       get\r
-                       {\r
-                               return _picture;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _picture)\r
-                               {\r
-                                       OnPictureChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _picture = value;\r
-                                       SendPropertyChanged("Picture");\r
-                                       OnPictureChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Children\r
-\r
-               private EntitySet<Product> _products;\r
-               [Association(Storage = "_products", OtherKey = "CategoryID", ThisKey = "CategoryID", Name = "fk_Products_1")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<Product> Products\r
-               {\r
-                       get\r
-                       {\r
-                               return _products;\r
-                       }\r
-                       set\r
-                       {\r
-                               _products = value;\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void Products_Attach(Product entity)\r
-               {\r
-                       entity.Category = this;\r
-               }\r
-\r
-               private void Products_Detach(Product entity)\r
-               {\r
-                       entity.Category = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Category()\r
-               {\r
-                       _products = new EntitySet<Product>(Products_Attach, Products_Detach);\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Customers")]\r
-       public partial class Customer : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnAddressChanged();\r
-               partial void OnAddressChanging(string value);\r
-               partial void OnCityChanged();\r
-               partial void OnCityChanging(string value);\r
-               partial void OnCompanyNameChanged();\r
-               partial void OnCompanyNameChanging(string value);\r
-               partial void OnContactNameChanged();\r
-               partial void OnContactNameChanging(string value);\r
-               partial void OnContactTitleChanged();\r
-               partial void OnContactTitleChanging(string value);\r
-               partial void OnCountryChanged();\r
-               partial void OnCountryChanging(string value);\r
-               partial void OnCustomerIDChanged();\r
-               partial void OnCustomerIDChanging(string value);\r
-               partial void OnFaxChanged();\r
-               partial void OnFaxChanging(string value);\r
-               partial void OnPhoneChanged();\r
-               partial void OnPhoneChanging(string value);\r
-               partial void OnPostalCodeChanged();\r
-               partial void OnPostalCodeChanging(string value);\r
-               partial void OnRegionChanged();\r
-               partial void OnRegionChanging(string value);\r
-\r
-               #endregion\r
-\r
-               #region string Address\r
-\r
-               private string _address;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_address", Name = "Address", DbType = "nvarchar (60)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string Address\r
-               {\r
-                       get\r
-                       {\r
-                               return _address;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _address)\r
-                               {\r
-                                       OnAddressChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _address = value;\r
-                                       SendPropertyChanged("Address");\r
-                                       OnAddressChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string City\r
-\r
-               private string _city;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_city", Name = "City", DbType = "nvarchar (15)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string City\r
-               {\r
-                       get\r
-                       {\r
-                               return _city;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _city)\r
-                               {\r
-                                       OnCityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _city = value;\r
-                                       SendPropertyChanged("City");\r
-                                       OnCityChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string CompanyName\r
-\r
-               private string _companyName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_companyName", Name = "CompanyName", DbType = "nvarchar (40)", AutoSync = AutoSync.Never)]\r
-               public string CompanyName\r
-               {\r
-                       get\r
-                       {\r
-                               return _companyName;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _companyName)\r
-                               {\r
-                                       OnCompanyNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _companyName = value;\r
-                                       SendPropertyChanged("CompanyName");\r
-                                       OnCompanyNameChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ContactName\r
-\r
-               private string _contactName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_contactName", Name = "ContactName", DbType = "nvarchar (30)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string ContactName\r
-               {\r
-                       get\r
-                       {\r
-                               return _contactName;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _contactName)\r
-                               {\r
-                                       OnContactNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _contactName = value;\r
-                                       SendPropertyChanged("ContactName");\r
-                                       OnContactNameChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ContactTitle\r
-\r
-               private string _contactTitle;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_contactTitle", Name = "ContactTitle", DbType = "nvarchar (30)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string ContactTitle\r
-               {\r
-                       get\r
-                       {\r
-                               return _contactTitle;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _contactTitle)\r
-                               {\r
-                                       OnContactTitleChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _contactTitle = value;\r
-                                       SendPropertyChanged("ContactTitle");\r
-                                       OnContactTitleChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Country\r
-\r
-               private string _country;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_country", Name = "Country", DbType = "nvarchar (15)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string Country\r
-               {\r
-                       get\r
-                       {\r
-                               return _country;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _country)\r
-                               {\r
-                                       OnCountryChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _country = value;\r
-                                       SendPropertyChanged("Country");\r
-                                       OnCountryChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string CustomerID\r
-\r
-               private string _customerID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerID", Name = "CustomerID", DbType = "nchar (5)", IsPrimaryKey = true, AutoSync = AutoSync.Never)]\r
-               public string CustomerID\r
-               {\r
-                       get\r
-                       {\r
-                               return _customerID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _customerID)\r
-                               {\r
-                                       OnCustomerIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerID = value;\r
-                                       SendPropertyChanged("CustomerID");\r
-                                       OnCustomerIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Fax\r
-\r
-               private string _fax;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_fax", Name = "Fax", DbType = "nvarchar (24)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string Fax\r
-               {\r
-                       get\r
-                       {\r
-                               return _fax;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _fax)\r
-                               {\r
-                                       OnFaxChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _fax = value;\r
-                                       SendPropertyChanged("Fax");\r
-                                       OnFaxChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Phone\r
-\r
-               private string _phone;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_phone", Name = "Phone", DbType = "nvarchar (24)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string Phone\r
-               {\r
-                       get\r
-                       {\r
-                               return _phone;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _phone)\r
-                               {\r
-                                       OnPhoneChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _phone = value;\r
-                                       SendPropertyChanged("Phone");\r
-                                       OnPhoneChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string PostalCode\r
-\r
-               private string _postalCode;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_postalCode", Name = "PostalCode", DbType = "nvarchar (10)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string PostalCode\r
-               {\r
-                       get\r
-                       {\r
-                               return _postalCode;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _postalCode)\r
-                               {\r
-                                       OnPostalCodeChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _postalCode = value;\r
-                                       SendPropertyChanged("PostalCode");\r
-                                       OnPostalCodeChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Region\r
-\r
-               private string _region;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_region", Name = "Region", DbType = "nvarchar (15)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string Region\r
-               {\r
-                       get\r
-                       {\r
-                               return _region;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _region)\r
-                               {\r
-                                       OnRegionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _region = value;\r
-                                       SendPropertyChanged("Region");\r
-                                       OnRegionChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Children\r
-\r
-               private EntitySet<CustomerCustomerDemo> _customerCustomerDemo;\r
-               [Association(Storage = "_customerCustomerDemo", OtherKey = "CustomerID", ThisKey = "CustomerID", Name = "fk_CustomerCustomerDemo_0")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<CustomerCustomerDemo> CustomerCustomerDemo\r
-               {\r
-                       get\r
-                       {\r
-                               return _customerCustomerDemo;\r
-                       }\r
-                       set\r
-                       {\r
-                               _customerCustomerDemo = value;\r
-                       }\r
-               }\r
-\r
-               private EntitySet<Order> _orders;\r
-               [Association(Storage = "_orders", OtherKey = "CustomerID", ThisKey = "CustomerID", Name = "fk_Orders_2")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<Order> Orders\r
-               {\r
-                       get\r
-                       {\r
-                               return _orders;\r
-                       }\r
-                       set\r
-                       {\r
-                               _orders = value;\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void CustomerCustomerDemo_Attach(CustomerCustomerDemo entity)\r
-               {\r
-                       entity.Customer = this;\r
-               }\r
-\r
-               private void CustomerCustomerDemo_Detach(CustomerCustomerDemo entity)\r
-               {\r
-                       entity.Customer = null;\r
-               }\r
-\r
-               private void Orders_Attach(Order entity)\r
-               {\r
-                       entity.Customer = this;\r
-               }\r
-\r
-               private void Orders_Detach(Order entity)\r
-               {\r
-                       entity.Customer = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Customer()\r
-               {\r
-                       _customerCustomerDemo = new EntitySet<CustomerCustomerDemo>(CustomerCustomerDemo_Attach, CustomerCustomerDemo_Detach);\r
-                       _orders = new EntitySet<Order>(Orders_Attach, Orders_Detach);\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.CustomerCustomerDemo")]\r
-       public partial class CustomerCustomerDemo : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnCustomerIDChanged();\r
-               partial void OnCustomerIDChanging(string value);\r
-               partial void OnCustomerTypeIDChanged();\r
-               partial void OnCustomerTypeIDChanging(string value);\r
-\r
-               #endregion\r
-\r
-               #region string CustomerID\r
-\r
-               private string _customerID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerID", Name = "CustomerID", DbType = "nchar (5)", IsPrimaryKey = true, AutoSync = AutoSync.Never)]\r
-               public string CustomerID\r
-               {\r
-                       get\r
-                       {\r
-                               return _customerID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _customerID)\r
-                               {\r
-                                       if (_customer.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnCustomerIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerID = value;\r
-                                       SendPropertyChanged("CustomerID");\r
-                                       OnCustomerIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string CustomerTypeID\r
-\r
-               private string _customerTypeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerTypeID", Name = "CustomerTypeID", DbType = "nchar", IsPrimaryKey = true, AutoSync = AutoSync.Never)]\r
-               public string CustomerTypeID\r
-               {\r
-                       get\r
-                       {\r
-                               return _customerTypeID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _customerTypeID)\r
-                               {\r
-                                       if (_customerDemographic.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnCustomerTypeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerTypeID = value;\r
-                                       SendPropertyChanged("CustomerTypeID");\r
-                                       OnCustomerTypeIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Parents\r
-\r
-               private EntityRef<Customer> _customer;\r
-               [Association(Storage = "_customer", OtherKey = "CustomerID", ThisKey = "CustomerID", Name = "fk_CustomerCustomerDemo_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Customer Customer\r
-               {\r
-                       get\r
-                       {\r
-                               return _customer.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _customer.Entity)\r
-                               {\r
-                                       if (_customer.Entity != null)\r
-                                       {\r
-                                               var previousCustomer = _customer.Entity;\r
-                                               _customer.Entity = null;\r
-                                               previousCustomer.CustomerCustomerDemo.Remove(this);\r
-                                       }\r
-                                       _customer.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.CustomerCustomerDemo.Add(this);\r
-                                               _customerID = value.CustomerID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _customerID = default(string);\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-               private EntityRef<CustomerDemographic> _customerDemographic;\r
-               [Association(Storage = "_customerDemographic", OtherKey = "CustomerTypeID", ThisKey = "CustomerTypeID", Name = "fk_CustomerCustomerDemo_1", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public CustomerDemographic CustomerDemographic\r
-               {\r
-                       get\r
-                       {\r
-                               return _customerDemographic.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _customerDemographic.Entity)\r
-                               {\r
-                                       if (_customerDemographic.Entity != null)\r
-                                       {\r
-                                               var previousCustomerDemographic = _customerDemographic.Entity;\r
-                                               _customerDemographic.Entity = null;\r
-                                               previousCustomerDemographic.CustomerCustomerDemo.Remove(this);\r
-                                       }\r
-                                       _customerDemographic.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.CustomerCustomerDemo.Add(this);\r
-                                               _customerTypeID = value.CustomerTypeID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _customerTypeID = default(string);\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public CustomerCustomerDemo()\r
-               {\r
-                       _customer = new EntityRef<Customer>();\r
-                       _customerDemographic = new EntityRef<CustomerDemographic>();\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.CustomerDemographics")]\r
-       public partial class CustomerDemographic : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnCustomerDescChanged();\r
-               partial void OnCustomerDescChanging(string value);\r
-               partial void OnCustomerTypeIDChanged();\r
-               partial void OnCustomerTypeIDChanging(string value);\r
-\r
-               #endregion\r
-\r
-               #region string CustomerDesc\r
-\r
-               private string _customerDesc;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerDesc", Name = "CustomerDesc", DbType = "ntext", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string CustomerDesc\r
-               {\r
-                       get\r
-                       {\r
-                               return _customerDesc;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _customerDesc)\r
-                               {\r
-                                       OnCustomerDescChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerDesc = value;\r
-                                       SendPropertyChanged("CustomerDesc");\r
-                                       OnCustomerDescChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string CustomerTypeID\r
-\r
-               private string _customerTypeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerTypeID", Name = "CustomerTypeID", DbType = "nchar", IsPrimaryKey = true, AutoSync = AutoSync.Never)]\r
-               public string CustomerTypeID\r
-               {\r
-                       get\r
-                       {\r
-                               return _customerTypeID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _customerTypeID)\r
-                               {\r
-                                       OnCustomerTypeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerTypeID = value;\r
-                                       SendPropertyChanged("CustomerTypeID");\r
-                                       OnCustomerTypeIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Children\r
-\r
-               private EntitySet<CustomerCustomerDemo> _customerCustomerDemo;\r
-               [Association(Storage = "_customerCustomerDemo", OtherKey = "CustomerTypeID", ThisKey = "CustomerTypeID", Name = "fk_CustomerCustomerDemo_1")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<CustomerCustomerDemo> CustomerCustomerDemo\r
-               {\r
-                       get\r
-                       {\r
-                               return _customerCustomerDemo;\r
-                       }\r
-                       set\r
-                       {\r
-                               _customerCustomerDemo = value;\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void CustomerCustomerDemo_Attach(CustomerCustomerDemo entity)\r
-               {\r
-                       entity.CustomerDemographic = this;\r
-               }\r
-\r
-               private void CustomerCustomerDemo_Detach(CustomerCustomerDemo entity)\r
-               {\r
-                       entity.CustomerDemographic = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public CustomerDemographic()\r
-               {\r
-                       _customerCustomerDemo = new EntitySet<CustomerCustomerDemo>(CustomerCustomerDemo_Attach, CustomerCustomerDemo_Detach);\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Employees")]\r
-       public partial class Employee : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnAddressChanged();\r
-               partial void OnAddressChanging(string value);\r
-               partial void OnBirthDateChanged();\r
-               partial void OnBirthDateChanging(DateTime? value);\r
-               partial void OnCityChanged();\r
-               partial void OnCityChanging(string value);\r
-               partial void OnCountryChanged();\r
-               partial void OnCountryChanging(string value);\r
-               partial void OnEmployeeIDChanged();\r
-               partial void OnEmployeeIDChanging(int value);\r
-               partial void OnExtensionChanged();\r
-               partial void OnExtensionChanging(string value);\r
-               partial void OnFirstNameChanged();\r
-               partial void OnFirstNameChanging(string value);\r
-               partial void OnHireDateChanged();\r
-               partial void OnHireDateChanging(DateTime? value);\r
-               partial void OnHomePhoneChanged();\r
-               partial void OnHomePhoneChanging(string value);\r
-               partial void OnLastNameChanged();\r
-               partial void OnLastNameChanging(string value);\r
-               partial void OnNotesChanged();\r
-               partial void OnNotesChanging(string value);\r
-               partial void OnPhotoChanged();\r
-               partial void OnPhotoChanging(Byte[] value);\r
-               partial void OnPhotoPathChanged();\r
-               partial void OnPhotoPathChanging(string value);\r
-               partial void OnPostalCodeChanged();\r
-               partial void OnPostalCodeChanging(string value);\r
-               partial void OnRegionChanged();\r
-               partial void OnRegionChanging(string value);\r
-               partial void OnReportsToChanged();\r
-               partial void OnReportsToChanging(int? value);\r
-               partial void OnTitleChanged();\r
-               partial void OnTitleChanging(string value);\r
-               partial void OnTitleOfCourtesyChanged();\r
-               partial void OnTitleOfCourtesyChanging(string value);\r
-\r
-               #endregion\r
-\r
-               #region string Address\r
-\r
-               private string _address;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_address", Name = "Address", DbType = "nvarchar (60)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string Address\r
-               {\r
-                       get\r
-                       {\r
-                               return _address;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _address)\r
-                               {\r
-                                       OnAddressChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _address = value;\r
-                                       SendPropertyChanged("Address");\r
-                                       OnAddressChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? BirthDate\r
-\r
-               private DateTime? _birthDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_birthDate", Name = "BirthDate", DbType = "datetime", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public DateTime? BirthDate\r
-               {\r
-                       get\r
-                       {\r
-                               return _birthDate;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _birthDate)\r
-                               {\r
-                                       OnBirthDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _birthDate = value;\r
-                                       SendPropertyChanged("BirthDate");\r
-                                       OnBirthDateChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string City\r
-\r
-               private string _city;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_city", Name = "City", DbType = "nvarchar (15)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string City\r
-               {\r
-                       get\r
-                       {\r
-                               return _city;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _city)\r
-                               {\r
-                                       OnCityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _city = value;\r
-                                       SendPropertyChanged("City");\r
-                                       OnCityChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Country\r
-\r
-               private string _country;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_country", Name = "Country", DbType = "nvarchar (15)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string Country\r
-               {\r
-                       get\r
-                       {\r
-                               return _country;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _country)\r
-                               {\r
-                                       OnCountryChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _country = value;\r
-                                       SendPropertyChanged("Country");\r
-                                       OnCountryChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int EmployeeID\r
-\r
-               private int _employeeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_employeeID", Name = "EmployeeID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never)]\r
-               public int EmployeeID\r
-               {\r
-                       get\r
-                       {\r
-                               return _employeeID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _employeeID)\r
-                               {\r
-                                       OnEmployeeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _employeeID = value;\r
-                                       SendPropertyChanged("EmployeeID");\r
-                                       OnEmployeeIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Extension\r
-\r
-               private string _extension;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_extension", Name = "Extension", DbType = "nvarchar (4)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string Extension\r
-               {\r
-                       get\r
-                       {\r
-                               return _extension;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _extension)\r
-                               {\r
-                                       OnExtensionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _extension = value;\r
-                                       SendPropertyChanged("Extension");\r
-                                       OnExtensionChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string FirstName\r
-\r
-               private string _firstName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_firstName", Name = "FirstName", DbType = "nvarchar (10)", AutoSync = AutoSync.Never)]\r
-               public string FirstName\r
-               {\r
-                       get\r
-                       {\r
-                               return _firstName;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _firstName)\r
-                               {\r
-                                       OnFirstNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _firstName = value;\r
-                                       SendPropertyChanged("FirstName");\r
-                                       OnFirstNameChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? HireDate\r
-\r
-               private DateTime? _hireDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_hireDate", Name = "HireDate", DbType = "datetime", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public DateTime? HireDate\r
-               {\r
-                       get\r
-                       {\r
-                               return _hireDate;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _hireDate)\r
-                               {\r
-                                       OnHireDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _hireDate = value;\r
-                                       SendPropertyChanged("HireDate");\r
-                                       OnHireDateChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string HomePhone\r
-\r
-               private string _homePhone;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_homePhone", Name = "HomePhone", DbType = "nvarchar (24)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string HomePhone\r
-               {\r
-                       get\r
-                       {\r
-                               return _homePhone;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _homePhone)\r
-                               {\r
-                                       OnHomePhoneChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _homePhone = value;\r
-                                       SendPropertyChanged("HomePhone");\r
-                                       OnHomePhoneChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string LastName\r
-\r
-               private string _lastName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_lastName", Name = "LastName", DbType = "nvarchar (20)", AutoSync = AutoSync.Never)]\r
-               public string LastName\r
-               {\r
-                       get\r
-                       {\r
-                               return _lastName;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _lastName)\r
-                               {\r
-                                       OnLastNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _lastName = value;\r
-                                       SendPropertyChanged("LastName");\r
-                                       OnLastNameChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Notes\r
-\r
-               private string _notes;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_notes", Name = "Notes", DbType = "ntext", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string Notes\r
-               {\r
-                       get\r
-                       {\r
-                               return _notes;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _notes)\r
-                               {\r
-                                       OnNotesChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _notes = value;\r
-                                       SendPropertyChanged("Notes");\r
-                                       OnNotesChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Byte[] Photo\r
-\r
-               private Byte[] _photo;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_photo", Name = "Photo", DbType = "image", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public Byte[] Photo\r
-               {\r
-                       get\r
-                       {\r
-                               return _photo;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _photo)\r
-                               {\r
-                                       OnPhotoChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _photo = value;\r
-                                       SendPropertyChanged("Photo");\r
-                                       OnPhotoChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string PhotoPath\r
-\r
-               private string _photoPath;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_photoPath", Name = "PhotoPath", DbType = "nvarchar (255)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string PhotoPath\r
-               {\r
-                       get\r
-                       {\r
-                               return _photoPath;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _photoPath)\r
-                               {\r
-                                       OnPhotoPathChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _photoPath = value;\r
-                                       SendPropertyChanged("PhotoPath");\r
-                                       OnPhotoPathChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string PostalCode\r
-\r
-               private string _postalCode;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_postalCode", Name = "PostalCode", DbType = "nvarchar (10)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string PostalCode\r
-               {\r
-                       get\r
-                       {\r
-                               return _postalCode;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _postalCode)\r
-                               {\r
-                                       OnPostalCodeChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _postalCode = value;\r
-                                       SendPropertyChanged("PostalCode");\r
-                                       OnPostalCodeChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Region\r
-\r
-               private string _region;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_region", Name = "Region", DbType = "nvarchar (15)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string Region\r
-               {\r
-                       get\r
-                       {\r
-                               return _region;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _region)\r
-                               {\r
-                                       OnRegionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _region = value;\r
-                                       SendPropertyChanged("Region");\r
-                                       OnRegionChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int? ReportsTo\r
-\r
-               private int? _reportsTo;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_reportsTo", Name = "ReportsTo", DbType = "INTEGER", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public int? ReportsTo\r
-               {\r
-                       get\r
-                       {\r
-                               return _reportsTo;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _reportsTo)\r
-                               {\r
-                                       if (_reportsToEmployee.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnReportsToChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _reportsTo = value;\r
-                                       SendPropertyChanged("ReportsTo");\r
-                                       OnReportsToChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Title\r
-\r
-               private string _title;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_title", Name = "Title", DbType = "nvarchar (30)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string Title\r
-               {\r
-                       get\r
-                       {\r
-                               return _title;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _title)\r
-                               {\r
-                                       OnTitleChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _title = value;\r
-                                       SendPropertyChanged("Title");\r
-                                       OnTitleChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string TitleOfCourtesy\r
-\r
-               private string _titleOfCourtesy;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_titleOfCourtesy", Name = "TitleOfCourtesy", DbType = "nvarchar (25)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string TitleOfCourtesy\r
-               {\r
-                       get\r
-                       {\r
-                               return _titleOfCourtesy;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _titleOfCourtesy)\r
-                               {\r
-                                       OnTitleOfCourtesyChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _titleOfCourtesy = value;\r
-                                       SendPropertyChanged("TitleOfCourtesy");\r
-                                       OnTitleOfCourtesyChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Children\r
-\r
-               private EntitySet<EmployeeTerritory> _employeeTerritories;\r
-               [Association(Storage = "_employeeTerritories", OtherKey = "EmployeeID", ThisKey = "EmployeeID", Name = "fk_EmployeeTerritories_1")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<EmployeeTerritory> EmployeeTerritories\r
-               {\r
-                       get\r
-                       {\r
-                               return _employeeTerritories;\r
-                       }\r
-                       set\r
-                       {\r
-                               _employeeTerritories = value;\r
-                       }\r
-               }\r
-\r
-               private EntitySet<Employee> _employees;\r
-               [Association(Storage = "_employees", OtherKey = "ReportsTo", ThisKey = "EmployeeID", Name = "fk_Employees_0")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<Employee> Employees\r
-               {\r
-                       get\r
-                       {\r
-                               return _employees;\r
-                       }\r
-                       set\r
-                       {\r
-                               _employees = value;\r
-                       }\r
-               }\r
-\r
-               private EntitySet<Order> _orders;\r
-               [Association(Storage = "_orders", OtherKey = "EmployeeID", ThisKey = "EmployeeID", Name = "fk_Orders_1")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<Order> Orders\r
-               {\r
-                       get\r
-                       {\r
-                               return _orders;\r
-                       }\r
-                       set\r
-                       {\r
-                               _orders = value;\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Parents\r
-\r
-               private EntityRef<Employee> _reportsToEmployee;\r
-               [Association(Storage = "_reportsToEmployee", OtherKey = "EmployeeID", ThisKey = "ReportsTo", Name = "fk_Employees_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Employee ReportsToEmployee\r
-               {\r
-                       get\r
-                       {\r
-                               return _reportsToEmployee.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _reportsToEmployee.Entity)\r
-                               {\r
-                                       if (_reportsToEmployee.Entity != null)\r
-                                       {\r
-                                               var previousEmployee = _reportsToEmployee.Entity;\r
-                                               _reportsToEmployee.Entity = null;\r
-                                               previousEmployee.Employees.Remove(this);\r
-                                       }\r
-                                       _reportsToEmployee.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.Employees.Add(this);\r
-                                               _reportsTo = value.EmployeeID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _reportsTo = null;\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void EmployeeTerritories_Attach(EmployeeTerritory entity)\r
-               {\r
-                       entity.Employee = this;\r
-               }\r
-\r
-               private void EmployeeTerritories_Detach(EmployeeTerritory entity)\r
-               {\r
-                       entity.Employee = null;\r
-               }\r
-\r
-               private void Employees_Attach(Employee entity)\r
-               {\r
-                       entity.ReportsToEmployee = this;\r
-               }\r
-\r
-               private void Employees_Detach(Employee entity)\r
-               {\r
-                       entity.ReportsToEmployee = null;\r
-               }\r
-\r
-               private void Orders_Attach(Order entity)\r
-               {\r
-                       entity.Employee = this;\r
-               }\r
-\r
-               private void Orders_Detach(Order entity)\r
-               {\r
-                       entity.Employee = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Employee()\r
-               {\r
-                       _employeeTerritories = new EntitySet<EmployeeTerritory>(EmployeeTerritories_Attach, EmployeeTerritories_Detach);\r
-                       _employees = new EntitySet<Employee>(Employees_Attach, Employees_Detach);\r
-                       _orders = new EntitySet<Order>(Orders_Attach, Orders_Detach);\r
-                       _reportsToEmployee = new EntityRef<Employee>();\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.EmployeeTerritories")]\r
-       public partial class EmployeeTerritory : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnEmployeeIDChanged();\r
-               partial void OnEmployeeIDChanging(int value);\r
-               partial void OnTerritoryIDChanged();\r
-               partial void OnTerritoryIDChanging(string value);\r
-\r
-               #endregion\r
-\r
-               #region int EmployeeID\r
-\r
-               private int _employeeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_employeeID", Name = "EmployeeID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never)]\r
-               public int EmployeeID\r
-               {\r
-                       get\r
-                       {\r
-                               return _employeeID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _employeeID)\r
-                               {\r
-                                       if (_employee.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnEmployeeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _employeeID = value;\r
-                                       SendPropertyChanged("EmployeeID");\r
-                                       OnEmployeeIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string TerritoryID\r
-\r
-               private string _territoryID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_territoryID", Name = "TerritoryID", DbType = "nvarchar", IsPrimaryKey = true, AutoSync = AutoSync.Never)]\r
-               public string TerritoryID\r
-               {\r
-                       get\r
-                       {\r
-                               return _territoryID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _territoryID)\r
-                               {\r
-                                       if (_territory.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnTerritoryIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _territoryID = value;\r
-                                       SendPropertyChanged("TerritoryID");\r
-                                       OnTerritoryIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Parents\r
-\r
-               private EntityRef<Territory> _territory;\r
-               [Association(Storage = "_territory", OtherKey = "TerritoryID", ThisKey = "TerritoryID", Name = "fk_EmployeeTerritories_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Territory Territory\r
-               {\r
-                       get\r
-                       {\r
-                               return _territory.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _territory.Entity)\r
-                               {\r
-                                       if (_territory.Entity != null)\r
-                                       {\r
-                                               var previousTerritory = _territory.Entity;\r
-                                               _territory.Entity = null;\r
-                                               previousTerritory.EmployeeTerritories.Remove(this);\r
-                                       }\r
-                                       _territory.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.EmployeeTerritories.Add(this);\r
-                                               _territoryID = value.TerritoryID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _territoryID = default(string);\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-               private EntityRef<Employee> _employee;\r
-               [Association(Storage = "_employee", OtherKey = "EmployeeID", ThisKey = "EmployeeID", Name = "fk_EmployeeTerritories_1", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Employee Employee\r
-               {\r
-                       get\r
-                       {\r
-                               return _employee.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _employee.Entity)\r
-                               {\r
-                                       if (_employee.Entity != null)\r
-                                       {\r
-                                               var previousEmployee = _employee.Entity;\r
-                                               _employee.Entity = null;\r
-                                               previousEmployee.EmployeeTerritories.Remove(this);\r
-                                       }\r
-                                       _employee.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.EmployeeTerritories.Add(this);\r
-                                               _employeeID = value.EmployeeID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _employeeID = default(int);\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public EmployeeTerritory()\r
-               {\r
-                       _territory = new EntityRef<Territory>();\r
-                       _employee = new EntityRef<Employee>();\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Orders")]\r
-       public partial class Order : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnCustomerIDChanged();\r
-               partial void OnCustomerIDChanging(string value);\r
-               partial void OnEmployeeIDChanged();\r
-               partial void OnEmployeeIDChanging(int? value);\r
-               partial void OnFreightChanged();\r
-               partial void OnFreightChanging(decimal? value);\r
-               partial void OnOrderDateChanged();\r
-               partial void OnOrderDateChanging(DateTime? value);\r
-               partial void OnOrderIDChanged();\r
-               partial void OnOrderIDChanging(int value);\r
-               partial void OnRequiredDateChanged();\r
-               partial void OnRequiredDateChanging(DateTime? value);\r
-               partial void OnShipAddressChanged();\r
-               partial void OnShipAddressChanging(string value);\r
-               partial void OnShipCityChanged();\r
-               partial void OnShipCityChanging(string value);\r
-               partial void OnShipCountryChanged();\r
-               partial void OnShipCountryChanging(string value);\r
-               partial void OnShipNameChanged();\r
-               partial void OnShipNameChanging(string value);\r
-               partial void OnShippedDateChanged();\r
-               partial void OnShippedDateChanging(DateTime? value);\r
-               partial void OnShipPostalCodeChanged();\r
-               partial void OnShipPostalCodeChanging(string value);\r
-               partial void OnShipRegionChanged();\r
-               partial void OnShipRegionChanging(string value);\r
-               partial void OnShipViaChanged();\r
-               partial void OnShipViaChanging(int? value);\r
-\r
-               #endregion\r
-\r
-               #region string CustomerID\r
-\r
-               private string _customerID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerID", Name = "CustomerID", DbType = "nchar (5)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string CustomerID\r
-               {\r
-                       get\r
-                       {\r
-                               return _customerID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _customerID)\r
-                               {\r
-                                       if (_customer.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnCustomerIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerID = value;\r
-                                       SendPropertyChanged("CustomerID");\r
-                                       OnCustomerIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int? EmployeeID\r
-\r
-               private int? _employeeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_employeeID", Name = "EmployeeID", DbType = "INTEGER", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public int? EmployeeID\r
-               {\r
-                       get\r
-                       {\r
-                               return _employeeID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _employeeID)\r
-                               {\r
-                                       if (_employee.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnEmployeeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _employeeID = value;\r
-                                       SendPropertyChanged("EmployeeID");\r
-                                       OnEmployeeIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region decimal? Freight\r
-\r
-               private decimal? _freight;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_freight", Name = "Freight", DbType = "money", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public decimal? Freight\r
-               {\r
-                       get\r
-                       {\r
-                               return _freight;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _freight)\r
-                               {\r
-                                       OnFreightChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _freight = value;\r
-                                       SendPropertyChanged("Freight");\r
-                                       OnFreightChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? OrderDate\r
-\r
-               private DateTime? _orderDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_orderDate", Name = "OrderDate", DbType = "datetime", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public DateTime? OrderDate\r
-               {\r
-                       get\r
-                       {\r
-                               return _orderDate;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _orderDate)\r
-                               {\r
-                                       OnOrderDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _orderDate = value;\r
-                                       SendPropertyChanged("OrderDate");\r
-                                       OnOrderDateChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int OrderID\r
-\r
-               private int _orderID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_orderID", Name = "OrderID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never)]\r
-               public int OrderID\r
-               {\r
-                       get\r
-                       {\r
-                               return _orderID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _orderID)\r
-                               {\r
-                                       OnOrderIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _orderID = value;\r
-                                       SendPropertyChanged("OrderID");\r
-                                       OnOrderIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? RequiredDate\r
-\r
-               private DateTime? _requiredDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_requiredDate", Name = "RequiredDate", DbType = "datetime", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public DateTime? RequiredDate\r
-               {\r
-                       get\r
-                       {\r
-                               return _requiredDate;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _requiredDate)\r
-                               {\r
-                                       OnRequiredDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _requiredDate = value;\r
-                                       SendPropertyChanged("RequiredDate");\r
-                                       OnRequiredDateChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ShipAddress\r
-\r
-               private string _shipAddress;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipAddress", Name = "ShipAddress", DbType = "nvarchar (60)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string ShipAddress\r
-               {\r
-                       get\r
-                       {\r
-                               return _shipAddress;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _shipAddress)\r
-                               {\r
-                                       OnShipAddressChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipAddress = value;\r
-                                       SendPropertyChanged("ShipAddress");\r
-                                       OnShipAddressChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ShipCity\r
-\r
-               private string _shipCity;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipCity", Name = "ShipCity", DbType = "nvarchar (15)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string ShipCity\r
-               {\r
-                       get\r
-                       {\r
-                               return _shipCity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _shipCity)\r
-                               {\r
-                                       OnShipCityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipCity = value;\r
-                                       SendPropertyChanged("ShipCity");\r
-                                       OnShipCityChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ShipCountry\r
-\r
-               private string _shipCountry;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipCountry", Name = "ShipCountry", DbType = "nvarchar (15)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string ShipCountry\r
-               {\r
-                       get\r
-                       {\r
-                               return _shipCountry;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _shipCountry)\r
-                               {\r
-                                       OnShipCountryChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipCountry = value;\r
-                                       SendPropertyChanged("ShipCountry");\r
-                                       OnShipCountryChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ShipName\r
-\r
-               private string _shipName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipName", Name = "ShipName", DbType = "nvarchar (40)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string ShipName\r
-               {\r
-                       get\r
-                       {\r
-                               return _shipName;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _shipName)\r
-                               {\r
-                                       OnShipNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipName = value;\r
-                                       SendPropertyChanged("ShipName");\r
-                                       OnShipNameChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? ShippedDate\r
-\r
-               private DateTime? _shippedDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shippedDate", Name = "ShippedDate", DbType = "datetime", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public DateTime? ShippedDate\r
-               {\r
-                       get\r
-                       {\r
-                               return _shippedDate;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _shippedDate)\r
-                               {\r
-                                       OnShippedDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shippedDate = value;\r
-                                       SendPropertyChanged("ShippedDate");\r
-                                       OnShippedDateChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ShipPostalCode\r
-\r
-               private string _shipPostalCode;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipPostalCode", Name = "ShipPostalCode", DbType = "nvarchar (10)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string ShipPostalCode\r
-               {\r
-                       get\r
-                       {\r
-                               return _shipPostalCode;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _shipPostalCode)\r
-                               {\r
-                                       OnShipPostalCodeChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipPostalCode = value;\r
-                                       SendPropertyChanged("ShipPostalCode");\r
-                                       OnShipPostalCodeChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ShipRegion\r
-\r
-               private string _shipRegion;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipRegion", Name = "ShipRegion", DbType = "nvarchar (15)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string ShipRegion\r
-               {\r
-                       get\r
-                       {\r
-                               return _shipRegion;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _shipRegion)\r
-                               {\r
-                                       OnShipRegionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipRegion = value;\r
-                                       SendPropertyChanged("ShipRegion");\r
-                                       OnShipRegionChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int? ShipVia\r
-\r
-               private int? _shipVia;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipVia", Name = "ShipVia", DbType = "INTEGER", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public int? ShipVia\r
-               {\r
-                       get\r
-                       {\r
-                               return _shipVia;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _shipVia)\r
-                               {\r
-                                       if (_shipper.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnShipViaChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipVia = value;\r
-                                       SendPropertyChanged("ShipVia");\r
-                                       OnShipViaChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Children\r
-\r
-               private EntitySet<OrderDetail> _orderDetails;\r
-               [Association(Storage = "_orderDetails", OtherKey = "OrderID", ThisKey = "OrderID", Name = "\"fk_Order Details_1\"")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<OrderDetail> OrderDetails\r
-               {\r
-                       get\r
-                       {\r
-                               return _orderDetails;\r
-                       }\r
-                       set\r
-                       {\r
-                               _orderDetails = value;\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Parents\r
-\r
-               private EntityRef<Shipper> _shipper;\r
-               [Association(Storage = "_shipper", OtherKey = "ShipperID", ThisKey = "ShipVia", Name = "fk_Orders_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Shipper Shipper\r
-               {\r
-                       get\r
-                       {\r
-                               return _shipper.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _shipper.Entity)\r
-                               {\r
-                                       if (_shipper.Entity != null)\r
-                                       {\r
-                                               var previousShipper = _shipper.Entity;\r
-                                               _shipper.Entity = null;\r
-                                               previousShipper.Orders.Remove(this);\r
-                                       }\r
-                                       _shipper.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.Orders.Add(this);\r
-                                               _shipVia = value.ShipperID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _shipVia = null;\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-               private EntityRef<Employee> _employee;\r
-               [Association(Storage = "_employee", OtherKey = "EmployeeID", ThisKey = "EmployeeID", Name = "fk_Orders_1", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Employee Employee\r
-               {\r
-                       get\r
-                       {\r
-                               return _employee.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _employee.Entity)\r
-                               {\r
-                                       if (_employee.Entity != null)\r
-                                       {\r
-                                               var previousEmployee = _employee.Entity;\r
-                                               _employee.Entity = null;\r
-                                               previousEmployee.Orders.Remove(this);\r
-                                       }\r
-                                       _employee.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.Orders.Add(this);\r
-                                               _employeeID = value.EmployeeID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _employeeID = null;\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-               private EntityRef<Customer> _customer;\r
-               [Association(Storage = "_customer", OtherKey = "CustomerID", ThisKey = "CustomerID", Name = "fk_Orders_2", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Customer Customer\r
-               {\r
-                       get\r
-                       {\r
-                               return _customer.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _customer.Entity)\r
-                               {\r
-                                       if (_customer.Entity != null)\r
-                                       {\r
-                                               var previousCustomer = _customer.Entity;\r
-                                               _customer.Entity = null;\r
-                                               previousCustomer.Orders.Remove(this);\r
-                                       }\r
-                                       _customer.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.Orders.Add(this);\r
-                                               _customerID = value.CustomerID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _customerID = null;\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void OrderDetails_Attach(OrderDetail entity)\r
-               {\r
-                       entity.Order = this;\r
-               }\r
-\r
-               private void OrderDetails_Detach(OrderDetail entity)\r
-               {\r
-                       entity.Order = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Order()\r
-               {\r
-                       _orderDetails = new EntitySet<OrderDetail>(OrderDetails_Attach, OrderDetails_Detach);\r
-                       _shipper = new EntityRef<Shipper>();\r
-                       _employee = new EntityRef<Employee>();\r
-                       _customer = new EntityRef<Customer>();\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.\"Order Details\"")]\r
-       public partial class OrderDetail : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnDiscountChanged();\r
-               partial void OnDiscountChanging(float value);\r
-               partial void OnOrderIDChanged();\r
-               partial void OnOrderIDChanging(int value);\r
-               partial void OnProductIDChanged();\r
-               partial void OnProductIDChanging(int value);\r
-               partial void OnQuantityChanged();\r
-               partial void OnQuantityChanging(short value);\r
-               partial void OnUnitPriceChanged();\r
-               partial void OnUnitPriceChanging(decimal value);\r
-\r
-               #endregion\r
-\r
-               #region float Discount\r
-\r
-               private float _discount;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_discount", Name = "Discount", DbType = "real", AutoSync = AutoSync.Never)]\r
-               public float Discount\r
-               {\r
-                       get\r
-                       {\r
-                               return _discount;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _discount)\r
-                               {\r
-                                       OnDiscountChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _discount = value;\r
-                                       SendPropertyChanged("Discount");\r
-                                       OnDiscountChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int OrderID\r
-\r
-               private int _orderID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_orderID", Name = "OrderID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never)]\r
-               public int OrderID\r
-               {\r
-                       get\r
-                       {\r
-                               return _orderID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _orderID)\r
-                               {\r
-                                       if (_order.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnOrderIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _orderID = value;\r
-                                       SendPropertyChanged("OrderID");\r
-                                       OnOrderIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int ProductID\r
-\r
-               private int _productID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_productID", Name = "ProductID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never)]\r
-               public int ProductID\r
-               {\r
-                       get\r
-                       {\r
-                               return _productID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _productID)\r
-                               {\r
-                                       if (_product.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnProductIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _productID = value;\r
-                                       SendPropertyChanged("ProductID");\r
-                                       OnProductIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region short Quantity\r
-\r
-               private short _quantity;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_quantity", Name = "Quantity", DbType = "smallint", AutoSync = AutoSync.Never)]\r
-               public short Quantity\r
-               {\r
-                       get\r
-                       {\r
-                               return _quantity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _quantity)\r
-                               {\r
-                                       OnQuantityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _quantity = value;\r
-                                       SendPropertyChanged("Quantity");\r
-                                       OnQuantityChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region decimal UnitPrice\r
-\r
-               private decimal _unitPrice;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_unitPrice", Name = "UnitPrice", DbType = "money", AutoSync = AutoSync.Never)]\r
-               public decimal UnitPrice\r
-               {\r
-                       get\r
-                       {\r
-                               return _unitPrice;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _unitPrice)\r
-                               {\r
-                                       OnUnitPriceChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _unitPrice = value;\r
-                                       SendPropertyChanged("UnitPrice");\r
-                                       OnUnitPriceChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Parents\r
-\r
-               private EntityRef<Product> _product;\r
-               [Association(Storage = "_product", OtherKey = "ProductID", ThisKey = "ProductID", Name = "\"fk_Order Details_0\"", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Product Product\r
-               {\r
-                       get\r
-                       {\r
-                               return _product.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _product.Entity)\r
-                               {\r
-                                       if (_product.Entity != null)\r
-                                       {\r
-                                               var previousProduct = _product.Entity;\r
-                                               _product.Entity = null;\r
-                                               previousProduct.OrderDetails.Remove(this);\r
-                                       }\r
-                                       _product.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.OrderDetails.Add(this);\r
-                                               _productID = value.ProductID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _productID = default(int);\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-               private EntityRef<Order> _order;\r
-               [Association(Storage = "_order", OtherKey = "OrderID", ThisKey = "OrderID", Name = "\"fk_Order Details_1\"", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Order Order\r
-               {\r
-                       get\r
-                       {\r
-                               return _order.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _order.Entity)\r
-                               {\r
-                                       if (_order.Entity != null)\r
-                                       {\r
-                                               var previousOrder = _order.Entity;\r
-                                               _order.Entity = null;\r
-                                               previousOrder.OrderDetails.Remove(this);\r
-                                       }\r
-                                       _order.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.OrderDetails.Add(this);\r
-                                               _orderID = value.OrderID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _orderID = default(int);\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public OrderDetail()\r
-               {\r
-                       _product = new EntityRef<Product>();\r
-                       _order = new EntityRef<Order>();\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Products")]\r
-       public partial class Product : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnCategoryIDChanged();\r
-               partial void OnCategoryIDChanging(int? value);\r
-               partial void OnDiscontinuedChanged();\r
-               partial void OnDiscontinuedChanging(bool value);\r
-               partial void OnProductIDChanged();\r
-               partial void OnProductIDChanging(int value);\r
-               partial void OnProductNameChanged();\r
-               partial void OnProductNameChanging(string value);\r
-               partial void OnQuantityPerUnitChanged();\r
-               partial void OnQuantityPerUnitChanging(string value);\r
-               partial void OnReorderLevelChanged();\r
-               partial void OnReorderLevelChanging(short? value);\r
-               partial void OnSupplierIDChanged();\r
-               partial void OnSupplierIDChanging(int? value);\r
-               partial void OnUnitPriceChanged();\r
-               partial void OnUnitPriceChanging(decimal? value);\r
-               partial void OnUnitsInStockChanged();\r
-               partial void OnUnitsInStockChanging(short? value);\r
-               partial void OnUnitsOnOrderChanged();\r
-               partial void OnUnitsOnOrderChanging(short? value);\r
-\r
-               #endregion\r
-\r
-               #region int? CategoryID\r
-\r
-               private int? _categoryID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_categoryID", Name = "CategoryID", DbType = "INTEGER", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public int? CategoryID\r
-               {\r
-                       get\r
-                       {\r
-                               return _categoryID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _categoryID)\r
-                               {\r
-                                       if (_category.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnCategoryIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _categoryID = value;\r
-                                       SendPropertyChanged("CategoryID");\r
-                                       OnCategoryIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region bool Discontinued\r
-\r
-               private bool _discontinued;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_discontinued", Name = "Discontinued", DbType = "bit", AutoSync = AutoSync.Never)]\r
-               public bool Discontinued\r
-               {\r
-                       get\r
-                       {\r
-                               return _discontinued;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _discontinued)\r
-                               {\r
-                                       OnDiscontinuedChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _discontinued = value;\r
-                                       SendPropertyChanged("Discontinued");\r
-                                       OnDiscontinuedChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int ProductID\r
-\r
-               private int _productID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_productID", Name = "ProductID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never)]\r
-               public int ProductID\r
-               {\r
-                       get\r
-                       {\r
-                               return _productID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _productID)\r
-                               {\r
-                                       OnProductIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _productID = value;\r
-                                       SendPropertyChanged("ProductID");\r
-                                       OnProductIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ProductName\r
-\r
-               private string _productName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_productName", Name = "ProductName", DbType = "nvarchar (40)", AutoSync = AutoSync.Never)]\r
-               public string ProductName\r
-               {\r
-                       get\r
-                       {\r
-                               return _productName;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _productName)\r
-                               {\r
-                                       OnProductNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _productName = value;\r
-                                       SendPropertyChanged("ProductName");\r
-                                       OnProductNameChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string QuantityPerUnit\r
-\r
-               private string _quantityPerUnit;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_quantityPerUnit", Name = "QuantityPerUnit", DbType = "nvarchar (20)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string QuantityPerUnit\r
-               {\r
-                       get\r
-                       {\r
-                               return _quantityPerUnit;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _quantityPerUnit)\r
-                               {\r
-                                       OnQuantityPerUnitChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _quantityPerUnit = value;\r
-                                       SendPropertyChanged("QuantityPerUnit");\r
-                                       OnQuantityPerUnitChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region short? ReorderLevel\r
-\r
-               private short? _reorderLevel;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_reorderLevel", Name = "ReorderLevel", DbType = "smallint", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public short? ReorderLevel\r
-               {\r
-                       get\r
-                       {\r
-                               return _reorderLevel;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _reorderLevel)\r
-                               {\r
-                                       OnReorderLevelChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _reorderLevel = value;\r
-                                       SendPropertyChanged("ReorderLevel");\r
-                                       OnReorderLevelChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int? SupplierID\r
-\r
-               private int? _supplierID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_supplierID", Name = "SupplierID", DbType = "INTEGER", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public int? SupplierID\r
-               {\r
-                       get\r
-                       {\r
-                               return _supplierID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _supplierID)\r
-                               {\r
-                                       if (_supplier.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnSupplierIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _supplierID = value;\r
-                                       SendPropertyChanged("SupplierID");\r
-                                       OnSupplierIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region decimal? UnitPrice\r
-\r
-               private decimal? _unitPrice;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_unitPrice", Name = "UnitPrice", DbType = "money", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public decimal? UnitPrice\r
-               {\r
-                       get\r
-                       {\r
-                               return _unitPrice;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _unitPrice)\r
-                               {\r
-                                       OnUnitPriceChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _unitPrice = value;\r
-                                       SendPropertyChanged("UnitPrice");\r
-                                       OnUnitPriceChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region short? UnitsInStock\r
-\r
-               private short? _unitsInStock;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_unitsInStock", Name = "UnitsInStock", DbType = "smallint", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public short? UnitsInStock\r
-               {\r
-                       get\r
-                       {\r
-                               return _unitsInStock;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _unitsInStock)\r
-                               {\r
-                                       OnUnitsInStockChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _unitsInStock = value;\r
-                                       SendPropertyChanged("UnitsInStock");\r
-                                       OnUnitsInStockChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region short? UnitsOnOrder\r
-\r
-               private short? _unitsOnOrder;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_unitsOnOrder", Name = "UnitsOnOrder", DbType = "smallint", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public short? UnitsOnOrder\r
-               {\r
-                       get\r
-                       {\r
-                               return _unitsOnOrder;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _unitsOnOrder)\r
-                               {\r
-                                       OnUnitsOnOrderChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _unitsOnOrder = value;\r
-                                       SendPropertyChanged("UnitsOnOrder");\r
-                                       OnUnitsOnOrderChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Children\r
-\r
-               private EntitySet<OrderDetail> _orderDetails;\r
-               [Association(Storage = "_orderDetails", OtherKey = "ProductID", ThisKey = "ProductID", Name = "\"fk_Order Details_0\"")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<OrderDetail> OrderDetails\r
-               {\r
-                       get\r
-                       {\r
-                               return _orderDetails;\r
-                       }\r
-                       set\r
-                       {\r
-                               _orderDetails = value;\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Parents\r
-\r
-               private EntityRef<Supplier> _supplier;\r
-               [Association(Storage = "_supplier", OtherKey = "SupplierID", ThisKey = "SupplierID", Name = "fk_Products_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Supplier Supplier\r
-               {\r
-                       get\r
-                       {\r
-                               return _supplier.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _supplier.Entity)\r
-                               {\r
-                                       if (_supplier.Entity != null)\r
-                                       {\r
-                                               var previousSupplier = _supplier.Entity;\r
-                                               _supplier.Entity = null;\r
-                                               previousSupplier.Products.Remove(this);\r
-                                       }\r
-                                       _supplier.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.Products.Add(this);\r
-                                               _supplierID = value.SupplierID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _supplierID = null;\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-               private EntityRef<Category> _category;\r
-               [Association(Storage = "_category", OtherKey = "CategoryID", ThisKey = "CategoryID", Name = "fk_Products_1", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Category Category\r
-               {\r
-                       get\r
-                       {\r
-                               return _category.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _category.Entity)\r
-                               {\r
-                                       if (_category.Entity != null)\r
-                                       {\r
-                                               var previousCategory = _category.Entity;\r
-                                               _category.Entity = null;\r
-                                               previousCategory.Products.Remove(this);\r
-                                       }\r
-                                       _category.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.Products.Add(this);\r
-                                               _categoryID = value.CategoryID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _categoryID = null;\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void OrderDetails_Attach(OrderDetail entity)\r
-               {\r
-                       entity.Product = this;\r
-               }\r
-\r
-               private void OrderDetails_Detach(OrderDetail entity)\r
-               {\r
-                       entity.Product = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Product()\r
-               {\r
-                       _orderDetails = new EntitySet<OrderDetail>(OrderDetails_Attach, OrderDetails_Detach);\r
-                       _supplier = new EntityRef<Supplier>();\r
-                       _category = new EntityRef<Category>();\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Region")]\r
-       public partial class Region : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnRegionDescriptionChanged();\r
-               partial void OnRegionDescriptionChanging(string value);\r
-               partial void OnRegionIDChanged();\r
-               partial void OnRegionIDChanging(int value);\r
-\r
-               #endregion\r
-\r
-               #region string RegionDescription\r
-\r
-               private string _regionDescription;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_regionDescription", Name = "RegionDescription", DbType = "nchar", AutoSync = AutoSync.Never)]\r
-               public string RegionDescription\r
-               {\r
-                       get\r
-                       {\r
-                               return _regionDescription;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _regionDescription)\r
-                               {\r
-                                       OnRegionDescriptionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _regionDescription = value;\r
-                                       SendPropertyChanged("RegionDescription");\r
-                                       OnRegionDescriptionChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int RegionID\r
-\r
-               private int _regionID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_regionID", Name = "RegionID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never)]\r
-               public int RegionID\r
-               {\r
-                       get\r
-                       {\r
-                               return _regionID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _regionID)\r
-                               {\r
-                                       OnRegionIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _regionID = value;\r
-                                       SendPropertyChanged("RegionID");\r
-                                       OnRegionIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Children\r
-\r
-               private EntitySet<Territory> _territories;\r
-               [Association(Storage = "_territories", OtherKey = "RegionID", ThisKey = "RegionID", Name = "fk_Territories_0")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<Territory> Territories\r
-               {\r
-                       get\r
-                       {\r
-                               return _territories;\r
-                       }\r
-                       set\r
-                       {\r
-                               _territories = value;\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void Territories_Attach(Territory entity)\r
-               {\r
-                       entity.Region = this;\r
-               }\r
-\r
-               private void Territories_Detach(Territory entity)\r
-               {\r
-                       entity.Region = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Region()\r
-               {\r
-                       _territories = new EntitySet<Territory>(Territories_Attach, Territories_Detach);\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Shippers")]\r
-       public partial class Shipper : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnCompanyNameChanged();\r
-               partial void OnCompanyNameChanging(string value);\r
-               partial void OnPhoneChanged();\r
-               partial void OnPhoneChanging(string value);\r
-               partial void OnShipperIDChanged();\r
-               partial void OnShipperIDChanging(int value);\r
-\r
-               #endregion\r
-\r
-               #region string CompanyName\r
-\r
-               private string _companyName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_companyName", Name = "CompanyName", DbType = "nvarchar (40)", AutoSync = AutoSync.Never)]\r
-               public string CompanyName\r
-               {\r
-                       get\r
-                       {\r
-                               return _companyName;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _companyName)\r
-                               {\r
-                                       OnCompanyNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _companyName = value;\r
-                                       SendPropertyChanged("CompanyName");\r
-                                       OnCompanyNameChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Phone\r
-\r
-               private string _phone;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_phone", Name = "Phone", DbType = "nvarchar (24)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string Phone\r
-               {\r
-                       get\r
-                       {\r
-                               return _phone;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _phone)\r
-                               {\r
-                                       OnPhoneChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _phone = value;\r
-                                       SendPropertyChanged("Phone");\r
-                                       OnPhoneChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int ShipperID\r
-\r
-               private int _shipperID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipperID", Name = "ShipperID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never)]\r
-               public int ShipperID\r
-               {\r
-                       get\r
-                       {\r
-                               return _shipperID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _shipperID)\r
-                               {\r
-                                       OnShipperIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipperID = value;\r
-                                       SendPropertyChanged("ShipperID");\r
-                                       OnShipperIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Children\r
-\r
-               private EntitySet<Order> _orders;\r
-               [Association(Storage = "_orders", OtherKey = "ShipVia", ThisKey = "ShipperID", Name = "fk_Orders_0")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<Order> Orders\r
-               {\r
-                       get\r
-                       {\r
-                               return _orders;\r
-                       }\r
-                       set\r
-                       {\r
-                               _orders = value;\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void Orders_Attach(Order entity)\r
-               {\r
-                       entity.Shipper = this;\r
-               }\r
-\r
-               private void Orders_Detach(Order entity)\r
-               {\r
-                       entity.Shipper = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Shipper()\r
-               {\r
-                       _orders = new EntitySet<Order>(Orders_Attach, Orders_Detach);\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Suppliers")]\r
-       public partial class Supplier : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnAddressChanged();\r
-               partial void OnAddressChanging(string value);\r
-               partial void OnCityChanged();\r
-               partial void OnCityChanging(string value);\r
-               partial void OnCompanyNameChanged();\r
-               partial void OnCompanyNameChanging(string value);\r
-               partial void OnContactNameChanged();\r
-               partial void OnContactNameChanging(string value);\r
-               partial void OnContactTitleChanged();\r
-               partial void OnContactTitleChanging(string value);\r
-               partial void OnCountryChanged();\r
-               partial void OnCountryChanging(string value);\r
-               partial void OnFaxChanged();\r
-               partial void OnFaxChanging(string value);\r
-               partial void OnHomePageChanged();\r
-               partial void OnHomePageChanging(string value);\r
-               partial void OnPhoneChanged();\r
-               partial void OnPhoneChanging(string value);\r
-               partial void OnPostalCodeChanged();\r
-               partial void OnPostalCodeChanging(string value);\r
-               partial void OnRegionChanged();\r
-               partial void OnRegionChanging(string value);\r
-               partial void OnSupplierIDChanged();\r
-               partial void OnSupplierIDChanging(int value);\r
-\r
-               #endregion\r
-\r
-               #region string Address\r
-\r
-               private string _address;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_address", Name = "Address", DbType = "nvarchar (60)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string Address\r
-               {\r
-                       get\r
-                       {\r
-                               return _address;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _address)\r
-                               {\r
-                                       OnAddressChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _address = value;\r
-                                       SendPropertyChanged("Address");\r
-                                       OnAddressChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string City\r
-\r
-               private string _city;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_city", Name = "City", DbType = "nvarchar (15)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string City\r
-               {\r
-                       get\r
-                       {\r
-                               return _city;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _city)\r
-                               {\r
-                                       OnCityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _city = value;\r
-                                       SendPropertyChanged("City");\r
-                                       OnCityChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string CompanyName\r
-\r
-               private string _companyName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_companyName", Name = "CompanyName", DbType = "nvarchar (40)", AutoSync = AutoSync.Never)]\r
-               public string CompanyName\r
-               {\r
-                       get\r
-                       {\r
-                               return _companyName;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _companyName)\r
-                               {\r
-                                       OnCompanyNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _companyName = value;\r
-                                       SendPropertyChanged("CompanyName");\r
-                                       OnCompanyNameChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ContactName\r
-\r
-               private string _contactName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_contactName", Name = "ContactName", DbType = "nvarchar (30)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string ContactName\r
-               {\r
-                       get\r
-                       {\r
-                               return _contactName;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _contactName)\r
-                               {\r
-                                       OnContactNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _contactName = value;\r
-                                       SendPropertyChanged("ContactName");\r
-                                       OnContactNameChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string ContactTitle\r
-\r
-               private string _contactTitle;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_contactTitle", Name = "ContactTitle", DbType = "nvarchar (30)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string ContactTitle\r
-               {\r
-                       get\r
-                       {\r
-                               return _contactTitle;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _contactTitle)\r
-                               {\r
-                                       OnContactTitleChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _contactTitle = value;\r
-                                       SendPropertyChanged("ContactTitle");\r
-                                       OnContactTitleChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Country\r
-\r
-               private string _country;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_country", Name = "Country", DbType = "nvarchar (15)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string Country\r
-               {\r
-                       get\r
-                       {\r
-                               return _country;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _country)\r
-                               {\r
-                                       OnCountryChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _country = value;\r
-                                       SendPropertyChanged("Country");\r
-                                       OnCountryChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Fax\r
-\r
-               private string _fax;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_fax", Name = "Fax", DbType = "nvarchar (24)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string Fax\r
-               {\r
-                       get\r
-                       {\r
-                               return _fax;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _fax)\r
-                               {\r
-                                       OnFaxChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _fax = value;\r
-                                       SendPropertyChanged("Fax");\r
-                                       OnFaxChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string HomePage\r
-\r
-               private string _homePage;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_homePage", Name = "HomePage", DbType = "ntext", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string HomePage\r
-               {\r
-                       get\r
-                       {\r
-                               return _homePage;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _homePage)\r
-                               {\r
-                                       OnHomePageChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _homePage = value;\r
-                                       SendPropertyChanged("HomePage");\r
-                                       OnHomePageChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Phone\r
-\r
-               private string _phone;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_phone", Name = "Phone", DbType = "nvarchar (24)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string Phone\r
-               {\r
-                       get\r
-                       {\r
-                               return _phone;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _phone)\r
-                               {\r
-                                       OnPhoneChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _phone = value;\r
-                                       SendPropertyChanged("Phone");\r
-                                       OnPhoneChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string PostalCode\r
-\r
-               private string _postalCode;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_postalCode", Name = "PostalCode", DbType = "nvarchar (10)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string PostalCode\r
-               {\r
-                       get\r
-                       {\r
-                               return _postalCode;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _postalCode)\r
-                               {\r
-                                       OnPostalCodeChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _postalCode = value;\r
-                                       SendPropertyChanged("PostalCode");\r
-                                       OnPostalCodeChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string Region\r
-\r
-               private string _region;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_region", Name = "Region", DbType = "nvarchar (15)", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public string Region\r
-               {\r
-                       get\r
-                       {\r
-                               return _region;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _region)\r
-                               {\r
-                                       OnRegionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _region = value;\r
-                                       SendPropertyChanged("Region");\r
-                                       OnRegionChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region int SupplierID\r
-\r
-               private int _supplierID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_supplierID", Name = "SupplierID", DbType = "INTEGER", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never)]\r
-               public int SupplierID\r
-               {\r
-                       get\r
-                       {\r
-                               return _supplierID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _supplierID)\r
-                               {\r
-                                       OnSupplierIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _supplierID = value;\r
-                                       SendPropertyChanged("SupplierID");\r
-                                       OnSupplierIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Children\r
-\r
-               private EntitySet<Product> _products;\r
-               [Association(Storage = "_products", OtherKey = "SupplierID", ThisKey = "SupplierID", Name = "fk_Products_0")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<Product> Products\r
-               {\r
-                       get\r
-                       {\r
-                               return _products;\r
-                       }\r
-                       set\r
-                       {\r
-                               _products = value;\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void Products_Attach(Product entity)\r
-               {\r
-                       entity.Supplier = this;\r
-               }\r
-\r
-               private void Products_Detach(Product entity)\r
-               {\r
-                       entity.Supplier = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Supplier()\r
-               {\r
-                       _products = new EntitySet<Product>(Products_Attach, Products_Detach);\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "main.Territories")]\r
-       public partial class Territory : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
-               partial void OnCreated();\r
-               partial void OnRegionIDChanged();\r
-               partial void OnRegionIDChanging(int value);\r
-               partial void OnTerritoryDescriptionChanged();\r
-               partial void OnTerritoryDescriptionChanging(string value);\r
-               partial void OnTerritoryIDChanged();\r
-               partial void OnTerritoryIDChanging(string value);\r
-\r
-               #endregion\r
-\r
-               #region int RegionID\r
-\r
-               private int _regionID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_regionID", Name = "RegionID", DbType = "INTEGER", AutoSync = AutoSync.Never)]\r
-               public int RegionID\r
-               {\r
-                       get\r
-                       {\r
-                               return _regionID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _regionID)\r
-                               {\r
-                                       if (_region.HasLoadedOrAssignedValue)\r
-                                       {\r
-                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnRegionIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _regionID = value;\r
-                                       SendPropertyChanged("RegionID");\r
-                                       OnRegionIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string TerritoryDescription\r
-\r
-               private string _territoryDescription;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_territoryDescription", Name = "TerritoryDescription", DbType = "nchar", AutoSync = AutoSync.Never)]\r
-               public string TerritoryDescription\r
-               {\r
-                       get\r
-                       {\r
-                               return _territoryDescription;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _territoryDescription)\r
-                               {\r
-                                       OnTerritoryDescriptionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _territoryDescription = value;\r
-                                       SendPropertyChanged("TerritoryDescription");\r
-                                       OnTerritoryDescriptionChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region string TerritoryID\r
-\r
-               private string _territoryID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_territoryID", Name = "TerritoryID", DbType = "nvarchar", IsPrimaryKey = true, AutoSync = AutoSync.Never)]\r
-               public string TerritoryID\r
-               {\r
-                       get\r
-                       {\r
-                               return _territoryID;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _territoryID)\r
-                               {\r
-                                       OnTerritoryIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _territoryID = value;\r
-                                       SendPropertyChanged("TerritoryID");\r
-                                       OnTerritoryIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Children\r
-\r
-               private EntitySet<EmployeeTerritory> _employeeTerritories;\r
-               [Association(Storage = "_employeeTerritories", OtherKey = "TerritoryID", ThisKey = "TerritoryID", Name = "fk_EmployeeTerritories_0")]\r
-               [DebuggerNonUserCode]\r
-               public EntitySet<EmployeeTerritory> EmployeeTerritories\r
-               {\r
-                       get\r
-                       {\r
-                               return _employeeTerritories;\r
-                       }\r
-                       set\r
-                       {\r
-                               _employeeTerritories = value;\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Parents\r
-\r
-               private EntityRef<Region> _region;\r
-               [Association(Storage = "_region", OtherKey = "RegionID", ThisKey = "RegionID", Name = "fk_Territories_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
-               public Region Region\r
-               {\r
-                       get\r
-                       {\r
-                               return _region.Entity;\r
-                       }\r
-                       set\r
-                       {\r
-                               if (value != _region.Entity)\r
-                               {\r
-                                       if (_region.Entity != null)\r
-                                       {\r
-                                               var previousRegion = _region.Entity;\r
-                                               _region.Entity = null;\r
-                                               previousRegion.Territories.Remove(this);\r
-                                       }\r
-                                       _region.Entity = value;\r
-                                       if (value != null)\r
-                                       {\r
-                                               value.Territories.Add(this);\r
-                                               _regionID = value.RegionID;\r
-                                       }\r
-                                       else\r
-                                       {\r
-                                               _regionID = default(int);\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void EmployeeTerritories_Attach(EmployeeTerritory entity)\r
-               {\r
-                       entity.Territory = this;\r
-               }\r
-\r
-               private void EmployeeTerritories_Detach(EmployeeTerritory entity)\r
-               {\r
-                       entity.Territory = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Territory()\r
-               {\r
-                       _employeeTerritories = new EntitySet<EmployeeTerritory>(EmployeeTerritories_Attach, EmployeeTerritories_Detach);\r
-                       _region = new EntityRef<Region>();\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
-       }\r
-}\r
index e69be51da67ea4abefe6239dbfe831af31e9ac24..cab72c8ccdd57d8486f1ab6714831c1b7ef8d9ca 100755 (executable)
-#region Auto-generated classes for Northwind database on [TIMESTAMP]\r
-\r
-//\r
-//  ____  _     __  __      _        _\r
+// \r
+//  ____  _     __  __      _        _ \r
 // |  _ \| |__ |  \/  | ___| |_ __ _| |\r
 // | | | | '_ \| |\/| |/ _ \ __/ _` | |\r
 // | |_| | |_) | |  | |  __/ || (_| | |\r
 // |____/|_.__/|_|  |_|\___|\__\__,_|_|\r
 //\r
-// Auto-generated from Northwind on [TIMESTAMP]\r
-// Please visit http://linq.to/db for more information\r
-\r
-#endregion\r
-\r
-using System;\r
-using System.Data;\r
-using System.Data.Linq.Mapping;\r
-using System.Diagnostics;\r
-using System.Reflection;\r
+// Auto-generated from Northwind on [TIMESTAMP].\r
+// Please visit http://code.google.com/p/dblinq2007/ for more information.\r
+//\r
+namespace nwind\r
+{\r
+       using System;\r
+       using System.ComponentModel;\r
+       using System.Data;\r
 #if MONO_STRICT\r
-using System.Data.Linq;\r
+       using System.Data.Linq;\r
 #else   // MONO_STRICT\r
-using DbLinq.Data.Linq;\r
-using DbLinq.Vendor;\r
+       using DbLinq.Data.Linq;\r
+       using DbLinq.Vendor;\r
 #endif  // MONO_STRICT\r
-using System.ComponentModel;\r
-\r
-namespace nwind\r
-{\r
+       using System.Data.Linq.Mapping;\r
+       using System.Diagnostics;\r
+       \r
+       \r
        public partial class Northwind : DataContext\r
        {\r
-               #region Extensibility Method Definitions\r
-\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
-\r
                #endregion\r
-\r
-               public Northwind(string connectionString)\r
-                       : base(connectionString)\r
+               \r
+               \r
+               public Northwind(string connectionString) : \r
+                               base(connectionString)\r
                {\r
-                       OnCreated();\r
+                       this.OnCreated();\r
                }\r
-\r
-               public Northwind(IDbConnection connection)\r
-               #if MONO_STRICT\r
-                       : base(connection)\r
-               #else   // MONO_STRICT\r
-                       : base(connection, new DbLinq.Sqlite.SqliteVendor())\r
-               #endif  // MONO_STRICT\r
+               \r
+               public Northwind(string connection, MappingSource mappingSource) : \r
+                               base(connection, mappingSource)\r
                {\r
-                       OnCreated();\r
+                       this.OnCreated();\r
                }\r
-\r
-               public Northwind(string connection, MappingSource mappingSource)\r
-                       : base(connection, mappingSource)\r
+               \r
+               public Northwind(IDbConnection connection, MappingSource mappingSource) : \r
+                               base(connection, mappingSource)\r
                {\r
-                       OnCreated();\r
+                       this.OnCreated();\r
                }\r
-\r
-               public Northwind(IDbConnection connection, MappingSource mappingSource)\r
-                       : base(connection, mappingSource)\r
+               \r
+               public Table<Category> Categories\r
                {\r
-                       OnCreated();\r
+                       get\r
+                       {\r
+                               return this.GetTable<Category>();\r
+                       }\r
                }\r
-\r
-               #if !MONO_STRICT\r
-               public Northwind(IDbConnection connection, IVendor vendor)\r
-                       : base(connection, vendor)\r
+               \r
+               public Table<Customer> Customers\r
                {\r
-                       OnCreated();\r
+                       get\r
+                       {\r
+                               return this.GetTable<Customer>();\r
+                       }\r
                }\r
-               #endif  // !MONO_STRICT\r
-\r
-               #if !MONO_STRICT\r
-               public Northwind(IDbConnection connection, MappingSource mappingSource, IVendor vendor)\r
-                       : base(connection, mappingSource, vendor)\r
+               \r
+               public Table<CustomerCustomerDemo> CustomerCustomerDemo\r
                {\r
-                       OnCreated();\r
+                       get\r
+                       {\r
+                               return this.GetTable<CustomerCustomerDemo>();\r
+                       }\r
                }\r
-               #endif  // !MONO_STRICT\r
-\r
-               public Table<Category> Categories { get { return GetTable<Category>(); } }\r
-               public Table<Customer> Customers { get { return GetTable<Customer>(); } }\r
-               public Table<CustomerCustomerDemo> CustomerCustomerDemo { get { return GetTable<CustomerCustomerDemo>(); } }\r
-               public Table<CustomerDemographic> CustomerDemographics { get { return GetTable<CustomerDemographic>(); } }\r
-               public Table<Employee> Employees { get { return GetTable<Employee>(); } }\r
-               public Table<EmployeeTerritory> EmployeeTerritories { get { return GetTable<EmployeeTerritory>(); } }\r
-               public Table<Order> Orders { get { return GetTable<Order>(); } }\r
-               public Table<OrderDetail> OrderDetails { get { return GetTable<OrderDetail>(); } }\r
-               public Table<Product> Products { get { return GetTable<Product>(); } }\r
-               public Table<Region> Regions { get { return GetTable<Region>(); } }\r
-               public Table<Shipper> Shippers { get { return GetTable<Shipper>(); } }\r
-               public Table<Supplier> Suppliers { get { return GetTable<Supplier>(); } }\r
-               public Table<Territory> Territories { get { return GetTable<Territory>(); } }\r
-\r
-       }\r
-\r
-       [Table(Name = "Categories")]\r
-       public partial class Category : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
+               \r
+               public Table<CustomerDemographic> CustomerDemographics\r
                {\r
-                       if (PropertyChanging != null)\r
+                       get\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               return this.GetTable<CustomerDemographic>();\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
+               \r
+               public Table<Employee> Employees\r
                {\r
-                       if (PropertyChanged != null)\r
+                       get\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               return this.GetTable<Employee>();\r
                        }\r
                }\r
+               \r
+               public Table<EmployeeTerritory> EmployeeTerritories\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<EmployeeTerritory>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Order> Orders\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Order>();\r
+                       }\r
+               }\r
+               \r
+               public Table<OrderDetail> OrderDetails\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<OrderDetail>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Product> Products\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Product>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Region> Regions\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Region>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Shipper> Shippers\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Shipper>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Supplier> Suppliers\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Supplier>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Territory> Territories\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Territory>();\r
+                       }\r
+               }\r
+       }\r
+       \r
+       #region Start MONO_STRICT\r
+#if MONO_STRICT\r
 \r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       public partial class Northwind\r
+       {\r
+               \r
+               public Northwind(IDbConnection connection) : \r
+                               base(connection)\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+       }\r
+       #region End MONO_STRICT\r
+       #endregion\r
+#else     // MONO_STRICT\r
+       \r
+       public partial class Northwind\r
+       {\r
+               \r
+               public Northwind(IDbConnection connection) : \r
+                               base(connection, new DbLinq.Sqlite.SqliteVendor())\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               public Northwind(IDbConnection connection, IVendor sqlDialect) : \r
+                               base(connection, sqlDialect)\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               public Northwind(IDbConnection connection, MappingSource mappingSource, IVendor sqlDialect) : \r
+                               base(connection, mappingSource, sqlDialect)\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+       }\r
+       #region End Not MONO_STRICT\r
+       #endregion\r
+#endif     // MONO_STRICT\r
+       #endregion\r
+       \r
+       [Table(Name="Categories")]\r
+       public partial class Category : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Category>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private long _categoryID;\r
+               \r
+               private string _categoryName;\r
+               \r
+               private string _description;\r
+               \r
+               private byte[] _picture;\r
+               \r
+               private EntitySet<Product> _products;\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnCategoryIDChanged();\r
+               \r
                partial void OnCategoryIDChanging(long value);\r
+               \r
                partial void OnCategoryNameChanged();\r
+               \r
                partial void OnCategoryNameChanging(string value);\r
+               \r
                partial void OnDescriptionChanged();\r
+               \r
                partial void OnDescriptionChanging(string value);\r
+               \r
                partial void OnPictureChanged();\r
-               partial void OnPictureChanging(Byte[] value);\r
-\r
+               \r
+               partial void OnPictureChanging(byte[] value);\r
                #endregion\r
-\r
-               #region long CategoryID\r
-\r
-               private long _categoryID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_categoryID", Name = "CategoryID", DbType = "integer", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               \r
+               public Category()\r
+               {\r
+                       _products = new EntitySet<Product>(new Action<Product>(this.Products_Attach), new Action<Product>(this.Products_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_categoryID", Name="CategoryID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long CategoryID\r
                {\r
                        get\r
                        {\r
-                               return _categoryID;\r
+                               return this._categoryID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _categoryID)\r
+                               if ((_categoryID != value))\r
                                {\r
-                                       OnCategoryIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _categoryID = value;\r
-                                       SendPropertyChanged("CategoryID");\r
-                                       OnCategoryIDChanged();\r
+                                       this.OnCategoryIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._categoryID = value;\r
+                                       this.SendPropertyChanged("CategoryID");\r
+                                       this.OnCategoryIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string CategoryName\r
-\r
-               private string _categoryName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_categoryName", Name = "CategoryName", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_categoryName", Name="CategoryName", DbType="nvarchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CategoryName\r
                {\r
                        get\r
                        {\r
-                               return _categoryName;\r
+                               return this._categoryName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _categoryName)\r
+                               if (((_categoryName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCategoryNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _categoryName = value;\r
-                                       SendPropertyChanged("CategoryName");\r
-                                       OnCategoryNameChanged();\r
+                                       this.OnCategoryNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._categoryName = value;\r
+                                       this.SendPropertyChanged("CategoryName");\r
+                                       this.OnCategoryNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Description\r
-\r
-               private string _description;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_description", Name = "Description", DbType = "ntext", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_description", Name="Description", DbType="ntext", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Description\r
                {\r
                        get\r
                        {\r
-                               return _description;\r
+                               return this._description;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _description)\r
+                               if (((_description == value) \r
+                                                       == false))\r
                                {\r
-                                       OnDescriptionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _description = value;\r
-                                       SendPropertyChanged("Description");\r
-                                       OnDescriptionChanged();\r
+                                       this.OnDescriptionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._description = value;\r
+                                       this.SendPropertyChanged("Description");\r
+                                       this.OnDescriptionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region Byte[] Picture\r
-\r
-               private Byte[] _picture;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_picture", Name = "Picture", DbType = "image", AutoSync = AutoSync.Never)]\r
-               public Byte[] Picture\r
+               \r
+               [Column(Storage="_picture", Name="Picture", DbType="image", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public byte[] Picture\r
                {\r
                        get\r
                        {\r
-                               return _picture;\r
+                               return this._picture;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _picture)\r
+                               if (((_picture == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPictureChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _picture = value;\r
-                                       SendPropertyChanged("Picture");\r
-                                       OnPictureChanged();\r
+                                       this.OnPictureChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._picture = value;\r
+                                       this.SendPropertyChanged("Picture");\r
+                                       this.OnPictureChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<Product> _products;\r
-               [Association(Storage = "_products", OtherKey = "CategoryID", ThisKey = "CategoryID", Name = "FK_Products_1")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_products", OtherKey="CategoryID", ThisKey="CategoryID", Name="FK_Products_1")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Product> Products\r
                {\r
                        get\r
                        {\r
-                               return _products;\r
+                               return this._products;\r
                        }\r
                        set\r
                        {\r
-                               _products = value;\r
+                               this._products = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void Products_Attach(Product entity)\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
                {\r
-                       entity.Category = this;\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
                }\r
-\r
-               private void Products_Detach(Product entity)\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       entity.Category = null;\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Category()\r
+               \r
+               public override int GetHashCode()\r
                {\r
-                       _products = new EntitySet<Product>(Products_Attach, Products_Detach);\r
-                       OnCreated();\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_categoryID.GetHashCode() * 1));\r
+                       return hc;\r
                }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "Customers")]\r
-       public partial class Customer : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
+               \r
+               public override bool Equals(object value)\r
                {\r
-                       if (PropertyChanging != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               return false;\r
                        }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Category other = ((Category)(value));\r
+                       return this.Equals(other);\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
+               \r
+               public virtual bool Equals(Category value)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               return false;\r
                        }\r
+                       return System.Collections.Generic.EqualityComparer<long>.Default.Equals(this._categoryID, value._categoryID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void Products_Attach(Product entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Category = this;\r
+               }\r
+               \r
+               private void Products_Detach(Product entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Category = null;\r
                }\r
-\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="Customers")]\r
+       public partial class Customer : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Customer>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _address;\r
+               \r
+               private string _city;\r
+               \r
+               private string _companyName;\r
+               \r
+               private string _contactName;\r
+               \r
+               private string _contactTitle;\r
+               \r
+               private string _country;\r
+               \r
+               private string _customerID;\r
+               \r
+               private string _fax;\r
+               \r
+               private string _phone;\r
+               \r
+               private string _postalCode;\r
+               \r
+               private string _region;\r
+               \r
+               private EntitySet<Order> _orders;\r
+               \r
+               private EntitySet<CustomerCustomerDemo> _customerCustomerDemo;\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnAddressChanged();\r
+               \r
                partial void OnAddressChanging(string value);\r
+               \r
                partial void OnCityChanged();\r
+               \r
                partial void OnCityChanging(string value);\r
+               \r
                partial void OnCompanyNameChanged();\r
+               \r
                partial void OnCompanyNameChanging(string value);\r
+               \r
                partial void OnContactNameChanged();\r
+               \r
                partial void OnContactNameChanging(string value);\r
+               \r
                partial void OnContactTitleChanged();\r
+               \r
                partial void OnContactTitleChanging(string value);\r
+               \r
                partial void OnCountryChanged();\r
+               \r
                partial void OnCountryChanging(string value);\r
+               \r
                partial void OnCustomerIDChanged();\r
+               \r
                partial void OnCustomerIDChanging(string value);\r
+               \r
                partial void OnFaxChanged();\r
+               \r
                partial void OnFaxChanging(string value);\r
+               \r
                partial void OnPhoneChanged();\r
+               \r
                partial void OnPhoneChanging(string value);\r
+               \r
                partial void OnPostalCodeChanged();\r
+               \r
                partial void OnPostalCodeChanging(string value);\r
+               \r
                partial void OnRegionChanged();\r
+               \r
                partial void OnRegionChanging(string value);\r
-\r
                #endregion\r
-\r
-               #region string Address\r
-\r
-               private string _address;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_address", Name = "Address", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               \r
+               public Customer()\r
+               {\r
+                       _orders = new EntitySet<Order>(new Action<Order>(this.Orders_Attach), new Action<Order>(this.Orders_Detach));\r
+                       _customerCustomerDemo = new EntitySet<CustomerCustomerDemo>(new Action<CustomerCustomerDemo>(this.CustomerCustomerDemo_Attach), new Action<CustomerCustomerDemo>(this.CustomerCustomerDemo_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_address", Name="Address", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Address\r
                {\r
                        get\r
                        {\r
-                               return _address;\r
+                               return this._address;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _address)\r
+                               if (((_address == value) \r
+                                                       == false))\r
                                {\r
-                                       OnAddressChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _address = value;\r
-                                       SendPropertyChanged("Address");\r
-                                       OnAddressChanged();\r
+                                       this.OnAddressChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._address = value;\r
+                                       this.SendPropertyChanged("Address");\r
+                                       this.OnAddressChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string City\r
-\r
-               private string _city;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_city", Name = "City", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_city", Name="City", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string City\r
                {\r
                        get\r
                        {\r
-                               return _city;\r
+                               return this._city;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _city)\r
+                               if (((_city == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _city = value;\r
-                                       SendPropertyChanged("City");\r
-                                       OnCityChanged();\r
+                                       this.OnCityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._city = value;\r
+                                       this.SendPropertyChanged("City");\r
+                                       this.OnCityChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string CompanyName\r
-\r
-               private string _companyName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_companyName", Name = "CompanyName", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_companyName", Name="CompanyName", DbType="nvarchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CompanyName\r
                {\r
                        get\r
                        {\r
-                               return _companyName;\r
+                               return this._companyName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _companyName)\r
+                               if (((_companyName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCompanyNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _companyName = value;\r
-                                       SendPropertyChanged("CompanyName");\r
-                                       OnCompanyNameChanged();\r
+                                       this.OnCompanyNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._companyName = value;\r
+                                       this.SendPropertyChanged("CompanyName");\r
+                                       this.OnCompanyNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ContactName\r
-\r
-               private string _contactName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_contactName", Name = "ContactName", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_contactName", Name="ContactName", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ContactName\r
                {\r
                        get\r
                        {\r
-                               return _contactName;\r
+                               return this._contactName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _contactName)\r
+                               if (((_contactName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnContactNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _contactName = value;\r
-                                       SendPropertyChanged("ContactName");\r
-                                       OnContactNameChanged();\r
+                                       this.OnContactNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._contactName = value;\r
+                                       this.SendPropertyChanged("ContactName");\r
+                                       this.OnContactNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ContactTitle\r
-\r
-               private string _contactTitle;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_contactTitle", Name = "ContactTitle", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_contactTitle", Name="ContactTitle", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ContactTitle\r
                {\r
                        get\r
                        {\r
-                               return _contactTitle;\r
+                               return this._contactTitle;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _contactTitle)\r
+                               if (((_contactTitle == value) \r
+                                                       == false))\r
                                {\r
-                                       OnContactTitleChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _contactTitle = value;\r
-                                       SendPropertyChanged("ContactTitle");\r
-                                       OnContactTitleChanged();\r
+                                       this.OnContactTitleChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._contactTitle = value;\r
+                                       this.SendPropertyChanged("ContactTitle");\r
+                                       this.OnContactTitleChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Country\r
-\r
-               private string _country;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_country", Name = "Country", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_country", Name="Country", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Country\r
                {\r
                        get\r
                        {\r
-                               return _country;\r
+                               return this._country;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _country)\r
+                               if (((_country == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCountryChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _country = value;\r
-                                       SendPropertyChanged("Country");\r
-                                       OnCountryChanged();\r
+                                       this.OnCountryChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._country = value;\r
+                                       this.SendPropertyChanged("Country");\r
+                                       this.OnCountryChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string CustomerID\r
-\r
-               private string _customerID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerID", Name = "CustomerID", DbType = "nchar", IsPrimaryKey = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_customerID", Name="CustomerID", DbType="nchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CustomerID\r
                {\r
                        get\r
                        {\r
-                               return _customerID;\r
+                               return this._customerID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerID)\r
+                               if (((_customerID == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCustomerIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerID = value;\r
-                                       SendPropertyChanged("CustomerID");\r
-                                       OnCustomerIDChanged();\r
+                                       this.OnCustomerIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerID = value;\r
+                                       this.SendPropertyChanged("CustomerID");\r
+                                       this.OnCustomerIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Fax\r
-\r
-               private string _fax;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_fax", Name = "Fax", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_fax", Name="Fax", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Fax\r
                {\r
                        get\r
                        {\r
-                               return _fax;\r
+                               return this._fax;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _fax)\r
+                               if (((_fax == value) \r
+                                                       == false))\r
                                {\r
-                                       OnFaxChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _fax = value;\r
-                                       SendPropertyChanged("Fax");\r
-                                       OnFaxChanged();\r
+                                       this.OnFaxChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._fax = value;\r
+                                       this.SendPropertyChanged("Fax");\r
+                                       this.OnFaxChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Phone\r
-\r
-               private string _phone;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_phone", Name = "Phone", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_phone", Name="Phone", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Phone\r
                {\r
                        get\r
                        {\r
-                               return _phone;\r
+                               return this._phone;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _phone)\r
+                               if (((_phone == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPhoneChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _phone = value;\r
-                                       SendPropertyChanged("Phone");\r
-                                       OnPhoneChanged();\r
+                                       this.OnPhoneChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._phone = value;\r
+                                       this.SendPropertyChanged("Phone");\r
+                                       this.OnPhoneChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string PostalCode\r
-\r
-               private string _postalCode;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_postalCode", Name = "PostalCode", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_postalCode", Name="PostalCode", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string PostalCode\r
                {\r
                        get\r
                        {\r
-                               return _postalCode;\r
+                               return this._postalCode;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _postalCode)\r
+                               if (((_postalCode == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPostalCodeChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _postalCode = value;\r
-                                       SendPropertyChanged("PostalCode");\r
-                                       OnPostalCodeChanged();\r
+                                       this.OnPostalCodeChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._postalCode = value;\r
+                                       this.SendPropertyChanged("PostalCode");\r
+                                       this.OnPostalCodeChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Region\r
-\r
-               private string _region;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_region", Name = "Region", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_region", Name="Region", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Region\r
                {\r
                        get\r
                        {\r
-                               return _region;\r
+                               return this._region;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _region)\r
+                               if (((_region == value) \r
+                                                       == false))\r
                                {\r
-                                       OnRegionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _region = value;\r
-                                       SendPropertyChanged("Region");\r
-                                       OnRegionChanged();\r
+                                       this.OnRegionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._region = value;\r
+                                       this.SendPropertyChanged("Region");\r
+                                       this.OnRegionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<Order> _orders;\r
-               [Association(Storage = "_orders", OtherKey = "CustomerID", ThisKey = "CustomerID", Name = "FK_Orders_2")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_orders", OtherKey="CustomerID", ThisKey="CustomerID", Name="FK_Orders_2")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Order> Orders\r
                {\r
                        get\r
                        {\r
-                               return _orders;\r
+                               return this._orders;\r
                        }\r
                        set\r
                        {\r
-                               _orders = value;\r
+                               this._orders = value;\r
                        }\r
                }\r
-\r
-               private EntitySet<CustomerCustomerDemo> _customerCustomerDemo;\r
-               [Association(Storage = "_customerCustomerDemo", OtherKey = "CustomerID", ThisKey = "CustomerID", Name = "FK_CustomerCustomerDemo_0")]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_customerCustomerDemo", OtherKey="CustomerID", ThisKey="CustomerID", Name="FK_CustomerCustomerDemo_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<CustomerCustomerDemo> CustomerCustomerDemo\r
                {\r
                        get\r
                        {\r
-                               return _customerCustomerDemo;\r
+                               return this._customerCustomerDemo;\r
                        }\r
                        set\r
                        {\r
-                               _customerCustomerDemo = value;\r
+                               this._customerCustomerDemo = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       if ((_customerID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_customerID.GetHashCode() * 1));\r
+                       }\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Customer other = ((Customer)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Customer value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._customerID, value._customerID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
                private void Orders_Attach(Order entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Customer = this;\r
                }\r
-\r
+               \r
                private void Orders_Detach(Order entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Customer = null;\r
                }\r
-\r
+               \r
                private void CustomerCustomerDemo_Attach(CustomerCustomerDemo entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Customer = this;\r
                }\r
-\r
+               \r
                private void CustomerCustomerDemo_Detach(CustomerCustomerDemo entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Customer = null;\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Customer()\r
-               {\r
-                       _orders = new EntitySet<Order>(Orders_Attach, Orders_Detach);\r
-                       _customerCustomerDemo = new EntitySet<CustomerCustomerDemo>(CustomerCustomerDemo_Attach, CustomerCustomerDemo_Detach);\r
-                       OnCreated();\r
-               }\r
-\r
                #endregion\r
-\r
        }\r
-\r
-       [Table(Name = "CustomerCustomerDemo")]\r
-       public partial class CustomerCustomerDemo : INotifyPropertyChanging, INotifyPropertyChanged\r
+       \r
+       [Table(Name="CustomerCustomerDemo")]\r
+       public partial class CustomerCustomerDemo : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<CustomerCustomerDemo>\r
        {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _customerID;\r
+               \r
+               private string _customerTypeID;\r
+               \r
+               private EntityRef<Customer> _customer = new EntityRef<Customer>();\r
+               \r
+               private EntityRef<CustomerDemographic> _customerDemographic = new EntityRef<CustomerDemographic>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnCustomerIDChanged();\r
+               \r
                partial void OnCustomerIDChanging(string value);\r
+               \r
                partial void OnCustomerTypeIDChanged();\r
+               \r
                partial void OnCustomerTypeIDChanging(string value);\r
-\r
                #endregion\r
-\r
-               #region string CustomerID\r
-\r
-               private string _customerID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerID", Name = "CustomerID", DbType = "nchar", IsPrimaryKey = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               \r
+               public CustomerCustomerDemo()\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_customerID", Name="CustomerID", DbType="nchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CustomerID\r
                {\r
                        get\r
                        {\r
-                               return _customerID;\r
+                               return this._customerID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerID)\r
+                               if (((_customerID == value) \r
+                                                       == false))\r
                                {\r
                                        if (_customer.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnCustomerIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerID = value;\r
-                                       SendPropertyChanged("CustomerID");\r
-                                       OnCustomerIDChanged();\r
+                                       this.OnCustomerIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerID = value;\r
+                                       this.SendPropertyChanged("CustomerID");\r
+                                       this.OnCustomerIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string CustomerTypeID\r
-\r
-               private string _customerTypeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerTypeID", Name = "CustomerTypeID", DbType = "nchar", IsPrimaryKey = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_customerTypeID", Name="CustomerTypeID", DbType="nchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CustomerTypeID\r
                {\r
                        get\r
                        {\r
-                               return _customerTypeID;\r
+                               return this._customerTypeID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerTypeID)\r
+                               if (((_customerTypeID == value) \r
+                                                       == false))\r
                                {\r
                                        if (_customerDemographic.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnCustomerTypeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerTypeID = value;\r
-                                       SendPropertyChanged("CustomerTypeID");\r
-                                       OnCustomerTypeIDChanged();\r
+                                       this.OnCustomerTypeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerTypeID = value;\r
+                                       this.SendPropertyChanged("CustomerTypeID");\r
+                                       this.OnCustomerTypeIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Customer> _customer;\r
-               [Association(Storage = "_customer", OtherKey = "CustomerID", ThisKey = "CustomerID", Name = "FK_CustomerCustomerDemo_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_customer", OtherKey="CustomerID", ThisKey="CustomerID", Name="FK_CustomerCustomerDemo_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Customer Customer\r
                {\r
                        get\r
                        {\r
-                               return _customer.Entity;\r
+                               return this._customer.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customer.Entity)\r
+                               if (((this._customer.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_customer.Entity != null)\r
+                                       if ((this._customer.Entity != null))\r
                                        {\r
-                                               var previousCustomer = _customer.Entity;\r
-                                               _customer.Entity = null;\r
+                                               Customer previousCustomer = this._customer.Entity;\r
+                                               this._customer.Entity = null;\r
                                                previousCustomer.CustomerCustomerDemo.Remove(this);\r
                                        }\r
-                                       _customer.Entity = value;\r
-                                       if (value != null)\r
+                                       this._customer.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.CustomerCustomerDemo.Add(this);\r
                                                _customerID = value.CustomerID;\r
@@ -847,28 +972,28 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-               private EntityRef<CustomerDemographic> _customerDemographic;\r
-               [Association(Storage = "_customerDemographic", OtherKey = "CustomerTypeID", ThisKey = "CustomerTypeID", Name = "FK_CustomerCustomerDemo_1", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_customerDemographic", OtherKey="CustomerTypeID", ThisKey="CustomerTypeID", Name="FK_CustomerCustomerDemo_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public CustomerDemographic CustomerDemographic\r
                {\r
                        get\r
                        {\r
-                               return _customerDemographic.Entity;\r
+                               return this._customerDemographic.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerDemographic.Entity)\r
+                               if (((this._customerDemographic.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_customerDemographic.Entity != null)\r
+                                       if ((this._customerDemographic.Entity != null))\r
                                        {\r
-                                               var previousCustomerDemographic = _customerDemographic.Entity;\r
-                                               _customerDemographic.Entity = null;\r
+                                               CustomerDemographic previousCustomerDemographic = this._customerDemographic.Entity;\r
+                                               this._customerDemographic.Entity = null;\r
                                                previousCustomerDemographic.CustomerCustomerDemo.Remove(this);\r
                                        }\r
-                                       _customerDemographic.Entity = value;\r
-                                       if (value != null)\r
+                                       this._customerDemographic.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.CustomerCustomerDemo.Add(this);\r
                                                _customerTypeID = value.CustomerTypeID;\r
@@ -880,783 +1005,831 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region ctor\r
-\r
-               public CustomerCustomerDemo()\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
                {\r
-                       _customer = new EntityRef<Customer>();\r
-                       _customerDemographic = new EntityRef<CustomerDemographic>();\r
-                       OnCreated();\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
                }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "CustomerDemographics")]\r
-       public partial class CustomerDemographic : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       if ((_customerID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_customerID.GetHashCode() * 1));\r
+                       }\r
+                       if ((_customerTypeID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_customerTypeID.GetHashCode() * 65536));\r
+                       }\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
                {\r
-                       if (PropertyChanging != null)\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               return false;\r
                        }\r
+                       CustomerCustomerDemo other = ((CustomerCustomerDemo)(value));\r
+                       return this.Equals(other);\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
+               \r
+               public virtual bool Equals(CustomerCustomerDemo value)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               return false;\r
                        }\r
+                       return (System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._customerID, value._customerID) && System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._customerTypeID, value._customerTypeID));\r
                }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="CustomerDemographics")]\r
+       public partial class CustomerDemographic : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<CustomerDemographic>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _customerDesc;\r
+               \r
+               private string _customerTypeID;\r
+               \r
+               private EntitySet<CustomerCustomerDemo> _customerCustomerDemo;\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnCustomerDescChanged();\r
+               \r
                partial void OnCustomerDescChanging(string value);\r
+               \r
                partial void OnCustomerTypeIDChanged();\r
+               \r
                partial void OnCustomerTypeIDChanging(string value);\r
-\r
                #endregion\r
-\r
-               #region string CustomerDesc\r
-\r
-               private string _customerDesc;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerDesc", Name = "CustomerDesc", DbType = "ntext", AutoSync = AutoSync.Never)]\r
+               \r
+               \r
+               public CustomerDemographic()\r
+               {\r
+                       _customerCustomerDemo = new EntitySet<CustomerCustomerDemo>(new Action<CustomerCustomerDemo>(this.CustomerCustomerDemo_Attach), new Action<CustomerCustomerDemo>(this.CustomerCustomerDemo_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_customerDesc", Name="CustomerDesc", DbType="ntext", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string CustomerDesc\r
                {\r
                        get\r
                        {\r
-                               return _customerDesc;\r
+                               return this._customerDesc;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerDesc)\r
+                               if (((_customerDesc == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCustomerDescChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerDesc = value;\r
-                                       SendPropertyChanged("CustomerDesc");\r
-                                       OnCustomerDescChanged();\r
+                                       this.OnCustomerDescChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerDesc = value;\r
+                                       this.SendPropertyChanged("CustomerDesc");\r
+                                       this.OnCustomerDescChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string CustomerTypeID\r
-\r
-               private string _customerTypeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerTypeID", Name = "CustomerTypeID", DbType = "nchar", IsPrimaryKey = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_customerTypeID", Name="CustomerTypeID", DbType="nchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CustomerTypeID\r
                {\r
                        get\r
                        {\r
-                               return _customerTypeID;\r
+                               return this._customerTypeID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerTypeID)\r
+                               if (((_customerTypeID == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCustomerTypeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerTypeID = value;\r
-                                       SendPropertyChanged("CustomerTypeID");\r
-                                       OnCustomerTypeIDChanged();\r
+                                       this.OnCustomerTypeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerTypeID = value;\r
+                                       this.SendPropertyChanged("CustomerTypeID");\r
+                                       this.OnCustomerTypeIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<CustomerCustomerDemo> _customerCustomerDemo;\r
-               [Association(Storage = "_customerCustomerDemo", OtherKey = "CustomerTypeID", ThisKey = "CustomerTypeID", Name = "FK_CustomerCustomerDemo_1")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_customerCustomerDemo", OtherKey="CustomerTypeID", ThisKey="CustomerTypeID", Name="FK_CustomerCustomerDemo_1")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<CustomerCustomerDemo> CustomerCustomerDemo\r
                {\r
                        get\r
                        {\r
-                               return _customerCustomerDemo;\r
+                               return this._customerCustomerDemo;\r
                        }\r
                        set\r
                        {\r
-                               _customerCustomerDemo = value;\r
+                               this._customerCustomerDemo = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void CustomerCustomerDemo_Attach(CustomerCustomerDemo entity)\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
                {\r
-                       entity.CustomerDemographic = this;\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
                }\r
-\r
-               private void CustomerCustomerDemo_Detach(CustomerCustomerDemo entity)\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       entity.CustomerDemographic = null;\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public CustomerDemographic()\r
+               \r
+               public override int GetHashCode()\r
                {\r
-                       _customerCustomerDemo = new EntitySet<CustomerCustomerDemo>(CustomerCustomerDemo_Attach, CustomerCustomerDemo_Detach);\r
-                       OnCreated();\r
+                       int hc = 0;\r
+                       if ((_customerTypeID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_customerTypeID.GetHashCode() * 1));\r
+                       }\r
+                       return hc;\r
                }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "Employees")]\r
-       public partial class Employee : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
+               \r
+               public override bool Equals(object value)\r
                {\r
-                       if (PropertyChanging != null)\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               return false;\r
                        }\r
+                       CustomerDemographic other = ((CustomerDemographic)(value));\r
+                       return this.Equals(other);\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
+               \r
+               public virtual bool Equals(CustomerDemographic value)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               return false;\r
                        }\r
+                       return System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._customerTypeID, value._customerTypeID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void CustomerCustomerDemo_Attach(CustomerCustomerDemo entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.CustomerDemographic = this;\r
+               }\r
+               \r
+               private void CustomerCustomerDemo_Detach(CustomerCustomerDemo entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.CustomerDemographic = null;\r
                }\r
-\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="Employees")]\r
+       public partial class Employee : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Employee>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _address;\r
+               \r
+               private System.Nullable<System.DateTime> _birthDate;\r
+               \r
+               private string _city;\r
+               \r
+               private string _country;\r
+               \r
+               private long _employeeID;\r
+               \r
+               private string _extension;\r
+               \r
+               private string _firstName;\r
+               \r
+               private System.Nullable<System.DateTime> _hireDate;\r
+               \r
+               private string _homePhone;\r
+               \r
+               private string _lastName;\r
+               \r
+               private string _notes;\r
+               \r
+               private byte[] _photo;\r
+               \r
+               private string _photoPath;\r
+               \r
+               private string _postalCode;\r
+               \r
+               private string _region;\r
+               \r
+               private System.Nullable<long> _reportsTo;\r
+               \r
+               private string _title;\r
+               \r
+               private string _titleOfCourtesy;\r
+               \r
+               private EntitySet<Employee> _employees;\r
+               \r
+               private EntitySet<Order> _orders;\r
+               \r
+               private EntitySet<EmployeeTerritory> _employeeTerritories;\r
+               \r
+               private EntityRef<Employee> _reportsToEmployee = new EntityRef<Employee>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnAddressChanged();\r
+               \r
                partial void OnAddressChanging(string value);\r
+               \r
                partial void OnBirthDateChanged();\r
-               partial void OnBirthDateChanging(DateTime? value);\r
+               \r
+               partial void OnBirthDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
                partial void OnCityChanged();\r
+               \r
                partial void OnCityChanging(string value);\r
+               \r
                partial void OnCountryChanged();\r
+               \r
                partial void OnCountryChanging(string value);\r
+               \r
                partial void OnEmployeeIDChanged();\r
+               \r
                partial void OnEmployeeIDChanging(long value);\r
+               \r
                partial void OnExtensionChanged();\r
+               \r
                partial void OnExtensionChanging(string value);\r
+               \r
                partial void OnFirstNameChanged();\r
+               \r
                partial void OnFirstNameChanging(string value);\r
+               \r
                partial void OnHireDateChanged();\r
-               partial void OnHireDateChanging(DateTime? value);\r
+               \r
+               partial void OnHireDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
                partial void OnHomePhoneChanged();\r
+               \r
                partial void OnHomePhoneChanging(string value);\r
+               \r
                partial void OnLastNameChanged();\r
+               \r
                partial void OnLastNameChanging(string value);\r
+               \r
                partial void OnNotesChanged();\r
+               \r
                partial void OnNotesChanging(string value);\r
+               \r
                partial void OnPhotoChanged();\r
-               partial void OnPhotoChanging(Byte[] value);\r
+               \r
+               partial void OnPhotoChanging(byte[] value);\r
+               \r
                partial void OnPhotoPathChanged();\r
+               \r
                partial void OnPhotoPathChanging(string value);\r
+               \r
                partial void OnPostalCodeChanged();\r
+               \r
                partial void OnPostalCodeChanging(string value);\r
+               \r
                partial void OnRegionChanged();\r
+               \r
                partial void OnRegionChanging(string value);\r
+               \r
                partial void OnReportsToChanged();\r
-               partial void OnReportsToChanging(long? value);\r
+               \r
+               partial void OnReportsToChanging(System.Nullable<long> value);\r
+               \r
                partial void OnTitleChanged();\r
+               \r
                partial void OnTitleChanging(string value);\r
+               \r
                partial void OnTitleOfCourtesyChanged();\r
+               \r
                partial void OnTitleOfCourtesyChanging(string value);\r
-\r
                #endregion\r
-\r
-               #region string Address\r
-\r
-               private string _address;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_address", Name = "Address", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               \r
+               public Employee()\r
+               {\r
+                       _employees = new EntitySet<Employee>(new Action<Employee>(this.Employees_Attach), new Action<Employee>(this.Employees_Detach));\r
+                       _orders = new EntitySet<Order>(new Action<Order>(this.Orders_Attach), new Action<Order>(this.Orders_Detach));\r
+                       _employeeTerritories = new EntitySet<EmployeeTerritory>(new Action<EmployeeTerritory>(this.EmployeeTerritories_Attach), new Action<EmployeeTerritory>(this.EmployeeTerritories_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_address", Name="Address", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Address\r
                {\r
                        get\r
                        {\r
-                               return _address;\r
+                               return this._address;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _address)\r
+                               if (((_address == value) \r
+                                                       == false))\r
                                {\r
-                                       OnAddressChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _address = value;\r
-                                       SendPropertyChanged("Address");\r
-                                       OnAddressChanged();\r
+                                       this.OnAddressChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._address = value;\r
+                                       this.SendPropertyChanged("Address");\r
+                                       this.OnAddressChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? BirthDate\r
-\r
-               private DateTime? _birthDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_birthDate", Name = "BirthDate", DbType = "datetime", AutoSync = AutoSync.Never)]\r
-               public DateTime? BirthDate\r
+               \r
+               [Column(Storage="_birthDate", Name="BirthDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> BirthDate\r
                {\r
                        get\r
                        {\r
-                               return _birthDate;\r
+                               return this._birthDate;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _birthDate)\r
+                               if ((_birthDate != value))\r
                                {\r
-                                       OnBirthDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _birthDate = value;\r
-                                       SendPropertyChanged("BirthDate");\r
-                                       OnBirthDateChanged();\r
+                                       this.OnBirthDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._birthDate = value;\r
+                                       this.SendPropertyChanged("BirthDate");\r
+                                       this.OnBirthDateChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string City\r
-\r
-               private string _city;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_city", Name = "City", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_city", Name="City", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string City\r
                {\r
                        get\r
                        {\r
-                               return _city;\r
+                               return this._city;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _city)\r
+                               if (((_city == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _city = value;\r
-                                       SendPropertyChanged("City");\r
-                                       OnCityChanged();\r
+                                       this.OnCityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._city = value;\r
+                                       this.SendPropertyChanged("City");\r
+                                       this.OnCityChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Country\r
-\r
-               private string _country;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_country", Name = "Country", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_country", Name="Country", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Country\r
                {\r
                        get\r
                        {\r
-                               return _country;\r
+                               return this._country;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _country)\r
+                               if (((_country == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCountryChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _country = value;\r
-                                       SendPropertyChanged("Country");\r
-                                       OnCountryChanged();\r
+                                       this.OnCountryChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._country = value;\r
+                                       this.SendPropertyChanged("Country");\r
+                                       this.OnCountryChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long EmployeeID\r
-\r
-               private long _employeeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_employeeID", Name = "EmployeeID", DbType = "integer", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_employeeID", Name="EmployeeID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long EmployeeID\r
                {\r
                        get\r
                        {\r
-                               return _employeeID;\r
+                               return this._employeeID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _employeeID)\r
+                               if ((_employeeID != value))\r
                                {\r
-                                       OnEmployeeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _employeeID = value;\r
-                                       SendPropertyChanged("EmployeeID");\r
-                                       OnEmployeeIDChanged();\r
+                                       this.OnEmployeeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._employeeID = value;\r
+                                       this.SendPropertyChanged("EmployeeID");\r
+                                       this.OnEmployeeIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Extension\r
-\r
-               private string _extension;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_extension", Name = "Extension", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_extension", Name="Extension", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Extension\r
                {\r
                        get\r
                        {\r
-                               return _extension;\r
+                               return this._extension;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _extension)\r
+                               if (((_extension == value) \r
+                                                       == false))\r
                                {\r
-                                       OnExtensionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _extension = value;\r
-                                       SendPropertyChanged("Extension");\r
-                                       OnExtensionChanged();\r
+                                       this.OnExtensionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._extension = value;\r
+                                       this.SendPropertyChanged("Extension");\r
+                                       this.OnExtensionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string FirstName\r
-\r
-               private string _firstName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_firstName", Name = "FirstName", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_firstName", Name="FirstName", DbType="nvarchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string FirstName\r
                {\r
                        get\r
                        {\r
-                               return _firstName;\r
+                               return this._firstName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _firstName)\r
+                               if (((_firstName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnFirstNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _firstName = value;\r
-                                       SendPropertyChanged("FirstName");\r
-                                       OnFirstNameChanged();\r
+                                       this.OnFirstNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._firstName = value;\r
+                                       this.SendPropertyChanged("FirstName");\r
+                                       this.OnFirstNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? HireDate\r
-\r
-               private DateTime? _hireDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_hireDate", Name = "HireDate", DbType = "datetime", AutoSync = AutoSync.Never)]\r
-               public DateTime? HireDate\r
+               \r
+               [Column(Storage="_hireDate", Name="HireDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> HireDate\r
                {\r
                        get\r
                        {\r
-                               return _hireDate;\r
+                               return this._hireDate;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _hireDate)\r
+                               if ((_hireDate != value))\r
                                {\r
-                                       OnHireDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _hireDate = value;\r
-                                       SendPropertyChanged("HireDate");\r
-                                       OnHireDateChanged();\r
+                                       this.OnHireDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._hireDate = value;\r
+                                       this.SendPropertyChanged("HireDate");\r
+                                       this.OnHireDateChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string HomePhone\r
-\r
-               private string _homePhone;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_homePhone", Name = "HomePhone", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_homePhone", Name="HomePhone", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string HomePhone\r
                {\r
                        get\r
                        {\r
-                               return _homePhone;\r
+                               return this._homePhone;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _homePhone)\r
+                               if (((_homePhone == value) \r
+                                                       == false))\r
                                {\r
-                                       OnHomePhoneChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _homePhone = value;\r
-                                       SendPropertyChanged("HomePhone");\r
-                                       OnHomePhoneChanged();\r
+                                       this.OnHomePhoneChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._homePhone = value;\r
+                                       this.SendPropertyChanged("HomePhone");\r
+                                       this.OnHomePhoneChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string LastName\r
-\r
-               private string _lastName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_lastName", Name = "LastName", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_lastName", Name="LastName", DbType="nvarchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string LastName\r
                {\r
                        get\r
                        {\r
-                               return _lastName;\r
+                               return this._lastName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _lastName)\r
+                               if (((_lastName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnLastNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _lastName = value;\r
-                                       SendPropertyChanged("LastName");\r
-                                       OnLastNameChanged();\r
+                                       this.OnLastNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._lastName = value;\r
+                                       this.SendPropertyChanged("LastName");\r
+                                       this.OnLastNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Notes\r
-\r
-               private string _notes;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_notes", Name = "Notes", DbType = "ntext", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_notes", Name="Notes", DbType="ntext", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Notes\r
                {\r
                        get\r
                        {\r
-                               return _notes;\r
+                               return this._notes;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _notes)\r
+                               if (((_notes == value) \r
+                                                       == false))\r
                                {\r
-                                       OnNotesChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _notes = value;\r
-                                       SendPropertyChanged("Notes");\r
-                                       OnNotesChanged();\r
+                                       this.OnNotesChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._notes = value;\r
+                                       this.SendPropertyChanged("Notes");\r
+                                       this.OnNotesChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region Byte[] Photo\r
-\r
-               private Byte[] _photo;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_photo", Name = "Photo", DbType = "image", AutoSync = AutoSync.Never)]\r
-               public Byte[] Photo\r
+               \r
+               [Column(Storage="_photo", Name="Photo", DbType="image", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public byte[] Photo\r
                {\r
                        get\r
                        {\r
-                               return _photo;\r
+                               return this._photo;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _photo)\r
+                               if (((_photo == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPhotoChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _photo = value;\r
-                                       SendPropertyChanged("Photo");\r
-                                       OnPhotoChanged();\r
+                                       this.OnPhotoChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._photo = value;\r
+                                       this.SendPropertyChanged("Photo");\r
+                                       this.OnPhotoChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string PhotoPath\r
-\r
-               private string _photoPath;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_photoPath", Name = "PhotoPath", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_photoPath", Name="PhotoPath", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string PhotoPath\r
                {\r
                        get\r
                        {\r
-                               return _photoPath;\r
+                               return this._photoPath;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _photoPath)\r
+                               if (((_photoPath == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPhotoPathChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _photoPath = value;\r
-                                       SendPropertyChanged("PhotoPath");\r
-                                       OnPhotoPathChanged();\r
+                                       this.OnPhotoPathChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._photoPath = value;\r
+                                       this.SendPropertyChanged("PhotoPath");\r
+                                       this.OnPhotoPathChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string PostalCode\r
-\r
-               private string _postalCode;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_postalCode", Name = "PostalCode", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_postalCode", Name="PostalCode", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string PostalCode\r
                {\r
                        get\r
                        {\r
-                               return _postalCode;\r
+                               return this._postalCode;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _postalCode)\r
+                               if (((_postalCode == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPostalCodeChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _postalCode = value;\r
-                                       SendPropertyChanged("PostalCode");\r
-                                       OnPostalCodeChanged();\r
+                                       this.OnPostalCodeChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._postalCode = value;\r
+                                       this.SendPropertyChanged("PostalCode");\r
+                                       this.OnPostalCodeChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Region\r
-\r
-               private string _region;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_region", Name = "Region", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_region", Name="Region", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Region\r
                {\r
                        get\r
                        {\r
-                               return _region;\r
+                               return this._region;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _region)\r
+                               if (((_region == value) \r
+                                                       == false))\r
                                {\r
-                                       OnRegionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _region = value;\r
-                                       SendPropertyChanged("Region");\r
-                                       OnRegionChanged();\r
+                                       this.OnRegionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._region = value;\r
+                                       this.SendPropertyChanged("Region");\r
+                                       this.OnRegionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long? ReportsTo\r
-\r
-               private long? _reportsTo;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_reportsTo", Name = "ReportsTo", DbType = "integer", AutoSync = AutoSync.Never)]\r
-               public long? ReportsTo\r
+               \r
+               [Column(Storage="_reportsTo", Name="ReportsTo", DbType="integer", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<long> ReportsTo\r
                {\r
                        get\r
                        {\r
-                               return _reportsTo;\r
+                               return this._reportsTo;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _reportsTo)\r
+                               if ((_reportsTo != value))\r
                                {\r
                                        if (_reportsToEmployee.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnReportsToChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _reportsTo = value;\r
-                                       SendPropertyChanged("ReportsTo");\r
-                                       OnReportsToChanged();\r
+                                       this.OnReportsToChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._reportsTo = value;\r
+                                       this.SendPropertyChanged("ReportsTo");\r
+                                       this.OnReportsToChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Title\r
-\r
-               private string _title;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_title", Name = "Title", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_title", Name="Title", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Title\r
                {\r
                        get\r
                        {\r
-                               return _title;\r
+                               return this._title;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _title)\r
+                               if (((_title == value) \r
+                                                       == false))\r
                                {\r
-                                       OnTitleChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _title = value;\r
-                                       SendPropertyChanged("Title");\r
-                                       OnTitleChanged();\r
+                                       this.OnTitleChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._title = value;\r
+                                       this.SendPropertyChanged("Title");\r
+                                       this.OnTitleChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string TitleOfCourtesy\r
-\r
-               private string _titleOfCourtesy;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_titleOfCourtesy", Name = "TitleOfCourtesy", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_titleOfCourtesy", Name="TitleOfCourtesy", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string TitleOfCourtesy\r
                {\r
                        get\r
                        {\r
-                               return _titleOfCourtesy;\r
+                               return this._titleOfCourtesy;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _titleOfCourtesy)\r
+                               if (((_titleOfCourtesy == value) \r
+                                                       == false))\r
                                {\r
-                                       OnTitleOfCourtesyChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _titleOfCourtesy = value;\r
-                                       SendPropertyChanged("TitleOfCourtesy");\r
-                                       OnTitleOfCourtesyChanged();\r
+                                       this.OnTitleOfCourtesyChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._titleOfCourtesy = value;\r
+                                       this.SendPropertyChanged("TitleOfCourtesy");\r
+                                       this.OnTitleOfCourtesyChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<Employee> _employees;\r
-               [Association(Storage = "_employees", OtherKey = "ReportsTo", ThisKey = "EmployeeID", Name = "FK_Employees_0")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_employees", OtherKey="ReportsTo", ThisKey="EmployeeID", Name="FK_Employees_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Employee> Employees\r
                {\r
                        get\r
                        {\r
-                               return _employees;\r
+                               return this._employees;\r
                        }\r
                        set\r
                        {\r
-                               _employees = value;\r
+                               this._employees = value;\r
                        }\r
                }\r
-\r
-               private EntitySet<Order> _orders;\r
-               [Association(Storage = "_orders", OtherKey = "EmployeeID", ThisKey = "EmployeeID", Name = "FK_Orders_1")]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_orders", OtherKey="EmployeeID", ThisKey="EmployeeID", Name="FK_Orders_1")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Order> Orders\r
                {\r
                        get\r
                        {\r
-                               return _orders;\r
+                               return this._orders;\r
                        }\r
                        set\r
                        {\r
-                               _orders = value;\r
+                               this._orders = value;\r
                        }\r
                }\r
-\r
-               private EntitySet<EmployeeTerritory> _employeeTerritories;\r
-               [Association(Storage = "_employeeTerritories", OtherKey = "EmployeeID", ThisKey = "EmployeeID", Name = "FK_EmployeeTerritories_1")]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_employeeTerritories", OtherKey="EmployeeID", ThisKey="EmployeeID", Name="FK_EmployeeTerritories_1")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<EmployeeTerritory> EmployeeTerritories\r
                {\r
                        get\r
                        {\r
-                               return _employeeTerritories;\r
+                               return this._employeeTerritories;\r
                        }\r
                        set\r
                        {\r
-                               _employeeTerritories = value;\r
+                               this._employeeTerritories = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Employee> _reportsToEmployee;\r
-               [Association(Storage = "_reportsToEmployee", OtherKey = "EmployeeID", ThisKey = "ReportsTo", Name = "FK_Employees_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_reportsToEmployee", OtherKey="EmployeeID", ThisKey="ReportsTo", Name="FK_Employees_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Employee ReportsToEmployee\r
                {\r
                        get\r
                        {\r
-                               return _reportsToEmployee.Entity;\r
+                               return this._reportsToEmployee.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _reportsToEmployee.Entity)\r
+                               if (((this._reportsToEmployee.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_reportsToEmployee.Entity != null)\r
+                                       if ((this._reportsToEmployee.Entity != null))\r
                                        {\r
-                                               var previousEmployee = _reportsToEmployee.Entity;\r
-                                               _reportsToEmployee.Entity = null;\r
+                                               Employee previousEmployee = this._reportsToEmployee.Entity;\r
+                                               this._reportsToEmployee.Entity = null;\r
                                                previousEmployee.Employees.Remove(this);\r
                                        }\r
-                                       _reportsToEmployee.Entity = value;\r
-                                       if (value != null)\r
+                                       this._reportsToEmployee.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Employees.Add(this);\r
                                                _reportsTo = value.EmployeeID;\r
@@ -1668,185 +1841,206 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_employeeID.GetHashCode() * 1));\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Employee other = ((Employee)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Employee value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<long>.Default.Equals(this._employeeID, value._employeeID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
                private void Employees_Attach(Employee entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.ReportsToEmployee = this;\r
                }\r
-\r
+               \r
                private void Employees_Detach(Employee entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.ReportsToEmployee = null;\r
                }\r
-\r
+               \r
                private void Orders_Attach(Order entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Employee = this;\r
                }\r
-\r
+               \r
                private void Orders_Detach(Order entity)\r
                {\r
-                       entity.Employee = null;\r
-               }\r
-\r
-               private void EmployeeTerritories_Attach(EmployeeTerritory entity)\r
-               {\r
-                       entity.Employee = this;\r
-               }\r
-\r
-               private void EmployeeTerritories_Detach(EmployeeTerritory entity)\r
-               {\r
-                       entity.Employee = null;\r
-               }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Employee()\r
-               {\r
-                       _employees = new EntitySet<Employee>(Employees_Attach, Employees_Detach);\r
-                       _orders = new EntitySet<Order>(Orders_Attach, Orders_Detach);\r
-                       _employeeTerritories = new EntitySet<EmployeeTerritory>(EmployeeTerritories_Attach, EmployeeTerritories_Detach);\r
-                       _reportsToEmployee = new EntityRef<Employee>();\r
-                       OnCreated();\r
+                       this.SendPropertyChanging();\r
+                       entity.Employee = null;\r
                }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "EmployeeTerritories")]\r
-       public partial class EmployeeTerritory : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
+               \r
+               private void EmployeeTerritories_Attach(EmployeeTerritory entity)\r
                {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
+                       this.SendPropertyChanging();\r
+                       entity.Employee = this;\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
+               \r
+               private void EmployeeTerritories_Detach(EmployeeTerritory entity)\r
                {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
+                       this.SendPropertyChanging();\r
+                       entity.Employee = null;\r
                }\r
-\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="EmployeeTerritories")]\r
+       public partial class EmployeeTerritory : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<EmployeeTerritory>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private long _employeeID;\r
+               \r
+               private string _territoryID;\r
+               \r
+               private EntityRef<Territory> _territory = new EntityRef<Territory>();\r
+               \r
+               private EntityRef<Employee> _employee = new EntityRef<Employee>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnEmployeeIDChanged();\r
+               \r
                partial void OnEmployeeIDChanging(long value);\r
+               \r
                partial void OnTerritoryIDChanged();\r
+               \r
                partial void OnTerritoryIDChanging(string value);\r
-\r
                #endregion\r
-\r
-               #region long EmployeeID\r
-\r
-               private long _employeeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_employeeID", Name = "EmployeeID", DbType = "integer", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               \r
+               public EmployeeTerritory()\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_employeeID", Name="EmployeeID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long EmployeeID\r
                {\r
                        get\r
                        {\r
-                               return _employeeID;\r
+                               return this._employeeID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _employeeID)\r
+                               if ((_employeeID != value))\r
                                {\r
                                        if (_employee.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnEmployeeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _employeeID = value;\r
-                                       SendPropertyChanged("EmployeeID");\r
-                                       OnEmployeeIDChanged();\r
+                                       this.OnEmployeeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._employeeID = value;\r
+                                       this.SendPropertyChanged("EmployeeID");\r
+                                       this.OnEmployeeIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string TerritoryID\r
-\r
-               private string _territoryID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_territoryID", Name = "TerritoryID", DbType = "nvarchar", IsPrimaryKey = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_territoryID", Name="TerritoryID", DbType="nvarchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string TerritoryID\r
                {\r
                        get\r
                        {\r
-                               return _territoryID;\r
+                               return this._territoryID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _territoryID)\r
+                               if (((_territoryID == value) \r
+                                                       == false))\r
                                {\r
                                        if (_territory.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnTerritoryIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _territoryID = value;\r
-                                       SendPropertyChanged("TerritoryID");\r
-                                       OnTerritoryIDChanged();\r
+                                       this.OnTerritoryIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._territoryID = value;\r
+                                       this.SendPropertyChanged("TerritoryID");\r
+                                       this.OnTerritoryIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Territory> _territory;\r
-               [Association(Storage = "_territory", OtherKey = "TerritoryID", ThisKey = "TerritoryID", Name = "FK_EmployeeTerritories_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_territory", OtherKey="TerritoryID", ThisKey="TerritoryID", Name="FK_EmployeeTerritories_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Territory Territory\r
                {\r
                        get\r
                        {\r
-                               return _territory.Entity;\r
+                               return this._territory.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _territory.Entity)\r
+                               if (((this._territory.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_territory.Entity != null)\r
+                                       if ((this._territory.Entity != null))\r
                                        {\r
-                                               var previousTerritory = _territory.Entity;\r
-                                               _territory.Entity = null;\r
+                                               Territory previousTerritory = this._territory.Entity;\r
+                                               this._territory.Entity = null;\r
                                                previousTerritory.EmployeeTerritories.Remove(this);\r
                                        }\r
-                                       _territory.Entity = value;\r
-                                       if (value != null)\r
+                                       this._territory.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.EmployeeTerritories.Add(this);\r
                                                _territoryID = value.TerritoryID;\r
@@ -1858,28 +2052,28 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-               private EntityRef<Employee> _employee;\r
-               [Association(Storage = "_employee", OtherKey = "EmployeeID", ThisKey = "EmployeeID", Name = "FK_EmployeeTerritories_1", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_employee", OtherKey="EmployeeID", ThisKey="EmployeeID", Name="FK_EmployeeTerritories_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Employee Employee\r
                {\r
                        get\r
                        {\r
-                               return _employee.Entity;\r
+                               return this._employee.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _employee.Entity)\r
+                               if (((this._employee.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_employee.Entity != null)\r
+                                       if ((this._employee.Entity != null))\r
                                        {\r
-                                               var previousEmployee = _employee.Entity;\r
-                                               _employee.Entity = null;\r
+                                               Employee previousEmployee = this._employee.Entity;\r
+                                               this._employee.Entity = null;\r
                                                previousEmployee.EmployeeTerritories.Remove(this);\r
                                        }\r
-                                       _employee.Entity = value;\r
-                                       if (value != null)\r
+                                       this._employee.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.EmployeeTerritories.Add(this);\r
                                                _employeeID = value.EmployeeID;\r
@@ -1891,508 +2085,528 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public EmployeeTerritory()\r
-               {\r
-                       _territory = new EntityRef<Territory>();\r
-                       _employee = new EntityRef<Employee>();\r
-                       OnCreated();\r
-               }\r
-\r
                #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "Orders")]\r
-       public partial class Order : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
                protected virtual void SendPropertyChanging()\r
                {\r
-                       if (PropertyChanging != null)\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               h(this, emptyChangingEventArgs);\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
+               \r
                protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_employeeID.GetHashCode() * 1));\r
+                       if ((_territoryID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_territoryID.GetHashCode() * 65536));\r
+                       }\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       EmployeeTerritory other = ((EmployeeTerritory)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(EmployeeTerritory value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return (System.Collections.Generic.EqualityComparer<long>.Default.Equals(this._employeeID, value._employeeID) && System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._territoryID, value._territoryID));\r
+               }\r
+       }\r
+       \r
+       [Table(Name="Orders")]\r
+       public partial class Order : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Order>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _customerID;\r
+               \r
+               private System.Nullable<long> _employeeID;\r
+               \r
+               private System.Nullable<decimal> _freight;\r
+               \r
+               private System.Nullable<System.DateTime> _orderDate;\r
+               \r
+               private long _orderID;\r
+               \r
+               private System.Nullable<System.DateTime> _requiredDate;\r
+               \r
+               private string _shipAddress;\r
+               \r
+               private string _shipCity;\r
+               \r
+               private string _shipCountry;\r
+               \r
+               private string _shipName;\r
+               \r
+               private System.Nullable<System.DateTime> _shippedDate;\r
+               \r
+               private string _shipPostalCode;\r
+               \r
+               private string _shipRegion;\r
+               \r
+               private System.Nullable<long> _shipVia;\r
+               \r
+               private EntitySet<OrderDetail> _orderDetails;\r
+               \r
+               private EntityRef<Shipper> _shipper = new EntityRef<Shipper>();\r
+               \r
+               private EntityRef<Employee> _employee = new EntityRef<Employee>();\r
+               \r
+               private EntityRef<Customer> _customer = new EntityRef<Customer>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnCustomerIDChanged();\r
+               \r
                partial void OnCustomerIDChanging(string value);\r
+               \r
                partial void OnEmployeeIDChanged();\r
-               partial void OnEmployeeIDChanging(long? value);\r
+               \r
+               partial void OnEmployeeIDChanging(System.Nullable<long> value);\r
+               \r
                partial void OnFreightChanged();\r
-               partial void OnFreightChanging(decimal? value);\r
+               \r
+               partial void OnFreightChanging(System.Nullable<decimal> value);\r
+               \r
                partial void OnOrderDateChanged();\r
-               partial void OnOrderDateChanging(DateTime? value);\r
+               \r
+               partial void OnOrderDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
                partial void OnOrderIDChanged();\r
+               \r
                partial void OnOrderIDChanging(long value);\r
+               \r
                partial void OnRequiredDateChanged();\r
-               partial void OnRequiredDateChanging(DateTime? value);\r
+               \r
+               partial void OnRequiredDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
                partial void OnShipAddressChanged();\r
+               \r
                partial void OnShipAddressChanging(string value);\r
+               \r
                partial void OnShipCityChanged();\r
+               \r
                partial void OnShipCityChanging(string value);\r
+               \r
                partial void OnShipCountryChanged();\r
+               \r
                partial void OnShipCountryChanging(string value);\r
+               \r
                partial void OnShipNameChanged();\r
+               \r
                partial void OnShipNameChanging(string value);\r
+               \r
                partial void OnShippedDateChanged();\r
-               partial void OnShippedDateChanging(DateTime? value);\r
+               \r
+               partial void OnShippedDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
                partial void OnShipPostalCodeChanged();\r
+               \r
                partial void OnShipPostalCodeChanging(string value);\r
+               \r
                partial void OnShipRegionChanged();\r
+               \r
                partial void OnShipRegionChanging(string value);\r
+               \r
                partial void OnShipViaChanged();\r
-               partial void OnShipViaChanging(long? value);\r
-\r
+               \r
+               partial void OnShipViaChanging(System.Nullable<long> value);\r
                #endregion\r
-\r
-               #region string CustomerID\r
-\r
-               private string _customerID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerID", Name = "CustomerID", DbType = "nchar", AutoSync = AutoSync.Never)]\r
+               \r
+               \r
+               public Order()\r
+               {\r
+                       _orderDetails = new EntitySet<OrderDetail>(new Action<OrderDetail>(this.OrderDetails_Attach), new Action<OrderDetail>(this.OrderDetails_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_customerID", Name="CustomerID", DbType="nchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string CustomerID\r
                {\r
                        get\r
                        {\r
-                               return _customerID;\r
+                               return this._customerID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerID)\r
+                               if (((_customerID == value) \r
+                                                       == false))\r
                                {\r
                                        if (_customer.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnCustomerIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerID = value;\r
-                                       SendPropertyChanged("CustomerID");\r
-                                       OnCustomerIDChanged();\r
+                                       this.OnCustomerIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerID = value;\r
+                                       this.SendPropertyChanged("CustomerID");\r
+                                       this.OnCustomerIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long? EmployeeID\r
-\r
-               private long? _employeeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_employeeID", Name = "EmployeeID", DbType = "integer", AutoSync = AutoSync.Never)]\r
-               public long? EmployeeID\r
+               \r
+               [Column(Storage="_employeeID", Name="EmployeeID", DbType="integer", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<long> EmployeeID\r
                {\r
                        get\r
                        {\r
-                               return _employeeID;\r
+                               return this._employeeID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _employeeID)\r
+                               if ((_employeeID != value))\r
                                {\r
                                        if (_employee.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnEmployeeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _employeeID = value;\r
-                                       SendPropertyChanged("EmployeeID");\r
-                                       OnEmployeeIDChanged();\r
+                                       this.OnEmployeeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._employeeID = value;\r
+                                       this.SendPropertyChanged("EmployeeID");\r
+                                       this.OnEmployeeIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region decimal? Freight\r
-\r
-               private decimal? _freight;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_freight", Name = "Freight", DbType = "money", AutoSync = AutoSync.Never)]\r
-               public decimal? Freight\r
+               \r
+               [Column(Storage="_freight", Name="Freight", DbType="money", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<decimal> Freight\r
                {\r
                        get\r
                        {\r
-                               return _freight;\r
+                               return this._freight;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _freight)\r
+                               if ((_freight != value))\r
                                {\r
-                                       OnFreightChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _freight = value;\r
-                                       SendPropertyChanged("Freight");\r
-                                       OnFreightChanged();\r
+                                       this.OnFreightChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._freight = value;\r
+                                       this.SendPropertyChanged("Freight");\r
+                                       this.OnFreightChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? OrderDate\r
-\r
-               private DateTime? _orderDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_orderDate", Name = "OrderDate", DbType = "datetime", AutoSync = AutoSync.Never)]\r
-               public DateTime? OrderDate\r
+               \r
+               [Column(Storage="_orderDate", Name="OrderDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> OrderDate\r
                {\r
                        get\r
                        {\r
-                               return _orderDate;\r
+                               return this._orderDate;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _orderDate)\r
+                               if ((_orderDate != value))\r
                                {\r
-                                       OnOrderDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _orderDate = value;\r
-                                       SendPropertyChanged("OrderDate");\r
-                                       OnOrderDateChanged();\r
+                                       this.OnOrderDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._orderDate = value;\r
+                                       this.SendPropertyChanged("OrderDate");\r
+                                       this.OnOrderDateChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long OrderID\r
-\r
-               private long _orderID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_orderID", Name = "OrderID", DbType = "integer", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_orderID", Name="OrderID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long OrderID\r
                {\r
                        get\r
                        {\r
-                               return _orderID;\r
+                               return this._orderID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _orderID)\r
+                               if ((_orderID != value))\r
                                {\r
-                                       OnOrderIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _orderID = value;\r
-                                       SendPropertyChanged("OrderID");\r
-                                       OnOrderIDChanged();\r
+                                       this.OnOrderIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._orderID = value;\r
+                                       this.SendPropertyChanged("OrderID");\r
+                                       this.OnOrderIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? RequiredDate\r
-\r
-               private DateTime? _requiredDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_requiredDate", Name = "RequiredDate", DbType = "datetime", AutoSync = AutoSync.Never)]\r
-               public DateTime? RequiredDate\r
+               \r
+               [Column(Storage="_requiredDate", Name="RequiredDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> RequiredDate\r
                {\r
                        get\r
                        {\r
-                               return _requiredDate;\r
+                               return this._requiredDate;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _requiredDate)\r
+                               if ((_requiredDate != value))\r
                                {\r
-                                       OnRequiredDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _requiredDate = value;\r
-                                       SendPropertyChanged("RequiredDate");\r
-                                       OnRequiredDateChanged();\r
+                                       this.OnRequiredDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._requiredDate = value;\r
+                                       this.SendPropertyChanged("RequiredDate");\r
+                                       this.OnRequiredDateChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ShipAddress\r
-\r
-               private string _shipAddress;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipAddress", Name = "ShipAddress", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_shipAddress", Name="ShipAddress", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ShipAddress\r
                {\r
                        get\r
                        {\r
-                               return _shipAddress;\r
+                               return this._shipAddress;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipAddress)\r
+                               if (((_shipAddress == value) \r
+                                                       == false))\r
                                {\r
-                                       OnShipAddressChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipAddress = value;\r
-                                       SendPropertyChanged("ShipAddress");\r
-                                       OnShipAddressChanged();\r
+                                       this.OnShipAddressChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipAddress = value;\r
+                                       this.SendPropertyChanged("ShipAddress");\r
+                                       this.OnShipAddressChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ShipCity\r
-\r
-               private string _shipCity;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipCity", Name = "ShipCity", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_shipCity", Name="ShipCity", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ShipCity\r
                {\r
                        get\r
                        {\r
-                               return _shipCity;\r
+                               return this._shipCity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipCity)\r
+                               if (((_shipCity == value) \r
+                                                       == false))\r
                                {\r
-                                       OnShipCityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipCity = value;\r
-                                       SendPropertyChanged("ShipCity");\r
-                                       OnShipCityChanged();\r
+                                       this.OnShipCityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipCity = value;\r
+                                       this.SendPropertyChanged("ShipCity");\r
+                                       this.OnShipCityChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ShipCountry\r
-\r
-               private string _shipCountry;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipCountry", Name = "ShipCountry", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_shipCountry", Name="ShipCountry", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ShipCountry\r
                {\r
                        get\r
                        {\r
-                               return _shipCountry;\r
+                               return this._shipCountry;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipCountry)\r
+                               if (((_shipCountry == value) \r
+                                                       == false))\r
                                {\r
-                                       OnShipCountryChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipCountry = value;\r
-                                       SendPropertyChanged("ShipCountry");\r
-                                       OnShipCountryChanged();\r
+                                       this.OnShipCountryChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipCountry = value;\r
+                                       this.SendPropertyChanged("ShipCountry");\r
+                                       this.OnShipCountryChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ShipName\r
-\r
-               private string _shipName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipName", Name = "ShipName", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_shipName", Name="ShipName", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ShipName\r
                {\r
                        get\r
                        {\r
-                               return _shipName;\r
+                               return this._shipName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipName)\r
+                               if (((_shipName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnShipNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipName = value;\r
-                                       SendPropertyChanged("ShipName");\r
-                                       OnShipNameChanged();\r
+                                       this.OnShipNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipName = value;\r
+                                       this.SendPropertyChanged("ShipName");\r
+                                       this.OnShipNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? ShippedDate\r
-\r
-               private DateTime? _shippedDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shippedDate", Name = "ShippedDate", DbType = "datetime", AutoSync = AutoSync.Never)]\r
-               public DateTime? ShippedDate\r
+               \r
+               [Column(Storage="_shippedDate", Name="ShippedDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> ShippedDate\r
                {\r
                        get\r
                        {\r
-                               return _shippedDate;\r
+                               return this._shippedDate;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shippedDate)\r
+                               if ((_shippedDate != value))\r
                                {\r
-                                       OnShippedDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shippedDate = value;\r
-                                       SendPropertyChanged("ShippedDate");\r
-                                       OnShippedDateChanged();\r
+                                       this.OnShippedDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shippedDate = value;\r
+                                       this.SendPropertyChanged("ShippedDate");\r
+                                       this.OnShippedDateChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ShipPostalCode\r
-\r
-               private string _shipPostalCode;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipPostalCode", Name = "ShipPostalCode", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_shipPostalCode", Name="ShipPostalCode", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ShipPostalCode\r
                {\r
                        get\r
                        {\r
-                               return _shipPostalCode;\r
+                               return this._shipPostalCode;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipPostalCode)\r
+                               if (((_shipPostalCode == value) \r
+                                                       == false))\r
                                {\r
-                                       OnShipPostalCodeChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipPostalCode = value;\r
-                                       SendPropertyChanged("ShipPostalCode");\r
-                                       OnShipPostalCodeChanged();\r
+                                       this.OnShipPostalCodeChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipPostalCode = value;\r
+                                       this.SendPropertyChanged("ShipPostalCode");\r
+                                       this.OnShipPostalCodeChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ShipRegion\r
-\r
-               private string _shipRegion;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipRegion", Name = "ShipRegion", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_shipRegion", Name="ShipRegion", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ShipRegion\r
                {\r
                        get\r
                        {\r
-                               return _shipRegion;\r
+                               return this._shipRegion;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipRegion)\r
+                               if (((_shipRegion == value) \r
+                                                       == false))\r
                                {\r
-                                       OnShipRegionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipRegion = value;\r
-                                       SendPropertyChanged("ShipRegion");\r
-                                       OnShipRegionChanged();\r
+                                       this.OnShipRegionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipRegion = value;\r
+                                       this.SendPropertyChanged("ShipRegion");\r
+                                       this.OnShipRegionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long? ShipVia\r
-\r
-               private long? _shipVia;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipVia", Name = "ShipVia", DbType = "integer", AutoSync = AutoSync.Never)]\r
-               public long? ShipVia\r
+               \r
+               [Column(Storage="_shipVia", Name="ShipVia", DbType="integer", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<long> ShipVia\r
                {\r
                        get\r
                        {\r
-                               return _shipVia;\r
+                               return this._shipVia;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipVia)\r
+                               if ((_shipVia != value))\r
                                {\r
                                        if (_shipper.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnShipViaChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipVia = value;\r
-                                       SendPropertyChanged("ShipVia");\r
-                                       OnShipViaChanged();\r
+                                       this.OnShipViaChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipVia = value;\r
+                                       this.SendPropertyChanged("ShipVia");\r
+                                       this.OnShipViaChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<OrderDetail> _orderDetails;\r
-               [Association(Storage = "_orderDetails", OtherKey = "OrderID", ThisKey = "OrderID", Name = "\"FK_Order Details_1\"")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_orderDetails", OtherKey="OrderID", ThisKey="OrderID", Name="FK_Order Details_1")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<OrderDetail> OrderDetails\r
                {\r
                        get\r
                        {\r
-                               return _orderDetails;\r
+                               return this._orderDetails;\r
                        }\r
                        set\r
                        {\r
-                               _orderDetails = value;\r
+                               this._orderDetails = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Shipper> _shipper;\r
-               [Association(Storage = "_shipper", OtherKey = "ShipperID", ThisKey = "ShipVia", Name = "FK_Orders_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_shipper", OtherKey="ShipperID", ThisKey="ShipVia", Name="FK_Orders_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Shipper Shipper\r
                {\r
                        get\r
                        {\r
-                               return _shipper.Entity;\r
+                               return this._shipper.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipper.Entity)\r
+                               if (((this._shipper.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_shipper.Entity != null)\r
+                                       if ((this._shipper.Entity != null))\r
                                        {\r
-                                               var previousShipper = _shipper.Entity;\r
-                                               _shipper.Entity = null;\r
+                                               Shipper previousShipper = this._shipper.Entity;\r
+                                               this._shipper.Entity = null;\r
                                                previousShipper.Orders.Remove(this);\r
                                        }\r
-                                       _shipper.Entity = value;\r
-                                       if (value != null)\r
+                                       this._shipper.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Orders.Add(this);\r
                                                _shipVia = value.ShipperID;\r
@@ -2404,28 +2618,28 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-               private EntityRef<Employee> _employee;\r
-               [Association(Storage = "_employee", OtherKey = "EmployeeID", ThisKey = "EmployeeID", Name = "FK_Orders_1", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_employee", OtherKey="EmployeeID", ThisKey="EmployeeID", Name="FK_Orders_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Employee Employee\r
                {\r
                        get\r
                        {\r
-                               return _employee.Entity;\r
+                               return this._employee.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _employee.Entity)\r
+                               if (((this._employee.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_employee.Entity != null)\r
+                                       if ((this._employee.Entity != null))\r
                                        {\r
-                                               var previousEmployee = _employee.Entity;\r
-                                               _employee.Entity = null;\r
+                                               Employee previousEmployee = this._employee.Entity;\r
+                                               this._employee.Entity = null;\r
                                                previousEmployee.Orders.Remove(this);\r
                                        }\r
-                                       _employee.Entity = value;\r
-                                       if (value != null)\r
+                                       this._employee.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Orders.Add(this);\r
                                                _employeeID = value.EmployeeID;\r
@@ -2437,28 +2651,28 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-               private EntityRef<Customer> _customer;\r
-               [Association(Storage = "_customer", OtherKey = "CustomerID", ThisKey = "CustomerID", Name = "FK_Orders_2", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_customer", OtherKey="CustomerID", ThisKey="CustomerID", Name="FK_Orders_2", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Customer Customer\r
                {\r
                        get\r
                        {\r
-                               return _customer.Entity;\r
+                               return this._customer.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customer.Entity)\r
+                               if (((this._customer.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_customer.Entity != null)\r
+                                       if ((this._customer.Entity != null))\r
                                        {\r
-                                               var previousCustomer = _customer.Entity;\r
-                                               _customer.Entity = null;\r
+                                               Customer previousCustomer = this._customer.Entity;\r
+                                               this._customer.Entity = null;\r
                                                previousCustomer.Orders.Remove(this);\r
                                        }\r
-                                       _customer.Entity = value;\r
-                                       if (value != null)\r
+                                       this._customer.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Orders.Add(this);\r
                                                _customerID = value.CustomerID;\r
@@ -2470,249 +2684,262 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void OrderDetails_Attach(OrderDetail entity)\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
                {\r
-                       entity.Order = this;\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
                }\r
-\r
-               private void OrderDetails_Detach(OrderDetail entity)\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       entity.Order = null;\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Order()\r
+               \r
+               public override int GetHashCode()\r
                {\r
-                       _orderDetails = new EntitySet<OrderDetail>(OrderDetails_Attach, OrderDetails_Detach);\r
-                       _shipper = new EntityRef<Shipper>();\r
-                       _employee = new EntityRef<Employee>();\r
-                       _customer = new EntityRef<Customer>();\r
-                       OnCreated();\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_orderID.GetHashCode() * 1));\r
+                       return hc;\r
                }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "\"Order Details\"")]\r
-       public partial class OrderDetail : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
+               \r
+               public override bool Equals(object value)\r
                {\r
-                       if (PropertyChanging != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               return false;\r
                        }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Order other = ((Order)(value));\r
+                       return this.Equals(other);\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
+               \r
+               public virtual bool Equals(Order value)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               return false;\r
                        }\r
+                       return System.Collections.Generic.EqualityComparer<long>.Default.Equals(this._orderID, value._orderID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void OrderDetails_Attach(OrderDetail entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Order = this;\r
+               }\r
+               \r
+               private void OrderDetails_Detach(OrderDetail entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Order = null;\r
                }\r
-\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="Order Details")]\r
+       public partial class OrderDetail : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<OrderDetail>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private float _discount;\r
+               \r
+               private long _orderID;\r
+               \r
+               private long _productID;\r
+               \r
+               private short _quantity;\r
+               \r
+               private decimal _unitPrice;\r
+               \r
+               private EntityRef<Product> _product = new EntityRef<Product>();\r
+               \r
+               private EntityRef<Order> _order = new EntityRef<Order>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnDiscountChanged();\r
+               \r
                partial void OnDiscountChanging(float value);\r
+               \r
                partial void OnOrderIDChanged();\r
+               \r
                partial void OnOrderIDChanging(long value);\r
+               \r
                partial void OnProductIDChanged();\r
+               \r
                partial void OnProductIDChanging(long value);\r
+               \r
                partial void OnQuantityChanged();\r
+               \r
                partial void OnQuantityChanging(short value);\r
+               \r
                partial void OnUnitPriceChanged();\r
+               \r
                partial void OnUnitPriceChanging(decimal value);\r
-\r
                #endregion\r
-\r
-               #region float Discount\r
-\r
-               private float _discount;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_discount", Name = "Discount", DbType = "real", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               \r
+               public OrderDetail()\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_discount", Name="Discount", DbType="real", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public float Discount\r
                {\r
                        get\r
                        {\r
-                               return _discount;\r
+                               return this._discount;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _discount)\r
+                               if ((_discount != value))\r
                                {\r
-                                       OnDiscountChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _discount = value;\r
-                                       SendPropertyChanged("Discount");\r
-                                       OnDiscountChanged();\r
+                                       this.OnDiscountChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._discount = value;\r
+                                       this.SendPropertyChanged("Discount");\r
+                                       this.OnDiscountChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long OrderID\r
-\r
-               private long _orderID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_orderID", Name = "OrderID", DbType = "integer", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_orderID", Name="OrderID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long OrderID\r
                {\r
                        get\r
                        {\r
-                               return _orderID;\r
+                               return this._orderID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _orderID)\r
+                               if ((_orderID != value))\r
                                {\r
                                        if (_order.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnOrderIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _orderID = value;\r
-                                       SendPropertyChanged("OrderID");\r
-                                       OnOrderIDChanged();\r
+                                       this.OnOrderIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._orderID = value;\r
+                                       this.SendPropertyChanged("OrderID");\r
+                                       this.OnOrderIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long ProductID\r
-\r
-               private long _productID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_productID", Name = "ProductID", DbType = "integer", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_productID", Name="ProductID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long ProductID\r
                {\r
                        get\r
                        {\r
-                               return _productID;\r
+                               return this._productID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _productID)\r
+                               if ((_productID != value))\r
                                {\r
                                        if (_product.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
-                                       }\r
-                                       OnProductIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _productID = value;\r
-                                       SendPropertyChanged("ProductID");\r
-                                       OnProductIDChanged();\r
-                               }\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region short Quantity\r
-\r
-               private short _quantity;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_quantity", Name = "Quantity", DbType = "smallint", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+                                       }\r
+                                       this.OnProductIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._productID = value;\r
+                                       this.SendPropertyChanged("ProductID");\r
+                                       this.OnProductIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_quantity", Name="Quantity", DbType="smallint", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public short Quantity\r
                {\r
                        get\r
                        {\r
-                               return _quantity;\r
+                               return this._quantity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _quantity)\r
+                               if ((_quantity != value))\r
                                {\r
-                                       OnQuantityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _quantity = value;\r
-                                       SendPropertyChanged("Quantity");\r
-                                       OnQuantityChanged();\r
+                                       this.OnQuantityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._quantity = value;\r
+                                       this.SendPropertyChanged("Quantity");\r
+                                       this.OnQuantityChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region decimal UnitPrice\r
-\r
-               private decimal _unitPrice;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_unitPrice", Name = "UnitPrice", DbType = "money", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_unitPrice", Name="UnitPrice", DbType="money", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public decimal UnitPrice\r
                {\r
                        get\r
                        {\r
-                               return _unitPrice;\r
+                               return this._unitPrice;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _unitPrice)\r
+                               if ((_unitPrice != value))\r
                                {\r
-                                       OnUnitPriceChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _unitPrice = value;\r
-                                       SendPropertyChanged("UnitPrice");\r
-                                       OnUnitPriceChanged();\r
+                                       this.OnUnitPriceChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._unitPrice = value;\r
+                                       this.SendPropertyChanged("UnitPrice");\r
+                                       this.OnUnitPriceChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Product> _product;\r
-               [Association(Storage = "_product", OtherKey = "ProductID", ThisKey = "ProductID", Name = "\"FK_Order Details_0\"", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_product", OtherKey="ProductID", ThisKey="ProductID", Name="FK_Order Details_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Product Product\r
                {\r
                        get\r
                        {\r
-                               return _product.Entity;\r
+                               return this._product.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _product.Entity)\r
+                               if (((this._product.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_product.Entity != null)\r
+                                       if ((this._product.Entity != null))\r
                                        {\r
-                                               var previousProduct = _product.Entity;\r
-                                               _product.Entity = null;\r
+                                               Product previousProduct = this._product.Entity;\r
+                                               this._product.Entity = null;\r
                                                previousProduct.OrderDetails.Remove(this);\r
                                        }\r
-                                       _product.Entity = value;\r
-                                       if (value != null)\r
+                                       this._product.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.OrderDetails.Add(this);\r
                                                _productID = value.ProductID;\r
@@ -2724,28 +2951,28 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-               private EntityRef<Order> _order;\r
-               [Association(Storage = "_order", OtherKey = "OrderID", ThisKey = "OrderID", Name = "\"FK_Order Details_1\"", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_order", OtherKey="OrderID", ThisKey="OrderID", Name="FK_Order Details_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Order Order\r
                {\r
                        get\r
                        {\r
-                               return _order.Entity;\r
+                               return this._order.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _order.Entity)\r
+                               if (((this._order.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_order.Entity != null)\r
+                                       if ((this._order.Entity != null))\r
                                        {\r
-                                               var previousOrder = _order.Entity;\r
-                                               _order.Entity = null;\r
+                                               Order previousOrder = this._order.Entity;\r
+                                               this._order.Entity = null;\r
                                                previousOrder.OrderDetails.Remove(this);\r
                                        }\r
-                                       _order.Entity = value;\r
-                                       if (value != null)\r
+                                       this._order.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.OrderDetails.Add(this);\r
                                                _orderID = value.OrderID;\r
@@ -2757,392 +2984,406 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public OrderDetail()\r
-               {\r
-                       _product = new EntityRef<Product>();\r
-                       _order = new EntityRef<Order>();\r
-                       OnCreated();\r
-               }\r
-\r
                #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "Products")]\r
-       public partial class Product : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
                protected virtual void SendPropertyChanging()\r
                {\r
-                       if (PropertyChanging != null)\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               h(this, emptyChangingEventArgs);\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
+               \r
                protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_orderID.GetHashCode() * 1));\r
+                       hc = (hc \r
+                                               | (_productID.GetHashCode() * 65536));\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       OrderDetail other = ((OrderDetail)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(OrderDetail value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return (System.Collections.Generic.EqualityComparer<long>.Default.Equals(this._orderID, value._orderID) && System.Collections.Generic.EqualityComparer<long>.Default.Equals(this._productID, value._productID));\r
+               }\r
+       }\r
+       \r
+       [Table(Name="Products")]\r
+       public partial class Product : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Product>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private System.Nullable<long> _categoryID;\r
+               \r
+               private bool _discontinued;\r
+               \r
+               private long _productID;\r
+               \r
+               private string _productName;\r
+               \r
+               private string _quantityPerUnit;\r
+               \r
+               private System.Nullable<short> _reorderLevel;\r
+               \r
+               private System.Nullable<long> _supplierID;\r
+               \r
+               private System.Nullable<decimal> _unitPrice;\r
+               \r
+               private System.Nullable<short> _unitsInStock;\r
+               \r
+               private System.Nullable<short> _unitsOnOrder;\r
+               \r
+               private EntitySet<OrderDetail> _orderDetails;\r
+               \r
+               private EntityRef<Supplier> _supplier = new EntityRef<Supplier>();\r
+               \r
+               private EntityRef<Category> _category = new EntityRef<Category>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnCategoryIDChanged();\r
-               partial void OnCategoryIDChanging(long? value);\r
+               \r
+               partial void OnCategoryIDChanging(System.Nullable<long> value);\r
+               \r
                partial void OnDiscontinuedChanged();\r
+               \r
                partial void OnDiscontinuedChanging(bool value);\r
+               \r
                partial void OnProductIDChanged();\r
+               \r
                partial void OnProductIDChanging(long value);\r
+               \r
                partial void OnProductNameChanged();\r
+               \r
                partial void OnProductNameChanging(string value);\r
+               \r
                partial void OnQuantityPerUnitChanged();\r
+               \r
                partial void OnQuantityPerUnitChanging(string value);\r
+               \r
                partial void OnReorderLevelChanged();\r
-               partial void OnReorderLevelChanging(short? value);\r
+               \r
+               partial void OnReorderLevelChanging(System.Nullable<short> value);\r
+               \r
                partial void OnSupplierIDChanged();\r
-               partial void OnSupplierIDChanging(long? value);\r
+               \r
+               partial void OnSupplierIDChanging(System.Nullable<long> value);\r
+               \r
                partial void OnUnitPriceChanged();\r
-               partial void OnUnitPriceChanging(decimal? value);\r
+               \r
+               partial void OnUnitPriceChanging(System.Nullable<decimal> value);\r
+               \r
                partial void OnUnitsInStockChanged();\r
-               partial void OnUnitsInStockChanging(short? value);\r
+               \r
+               partial void OnUnitsInStockChanging(System.Nullable<short> value);\r
+               \r
                partial void OnUnitsOnOrderChanged();\r
-               partial void OnUnitsOnOrderChanging(short? value);\r
-\r
+               \r
+               partial void OnUnitsOnOrderChanging(System.Nullable<short> value);\r
                #endregion\r
-\r
-               #region long? CategoryID\r
-\r
-               private long? _categoryID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_categoryID", Name = "CategoryID", DbType = "integer", AutoSync = AutoSync.Never)]\r
-               public long? CategoryID\r
+               \r
+               \r
+               public Product()\r
+               {\r
+                       _orderDetails = new EntitySet<OrderDetail>(new Action<OrderDetail>(this.OrderDetails_Attach), new Action<OrderDetail>(this.OrderDetails_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_categoryID", Name="CategoryID", DbType="integer", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<long> CategoryID\r
                {\r
                        get\r
                        {\r
-                               return _categoryID;\r
+                               return this._categoryID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _categoryID)\r
+                               if ((_categoryID != value))\r
                                {\r
                                        if (_category.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnCategoryIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _categoryID = value;\r
-                                       SendPropertyChanged("CategoryID");\r
-                                       OnCategoryIDChanged();\r
+                                       this.OnCategoryIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._categoryID = value;\r
+                                       this.SendPropertyChanged("CategoryID");\r
+                                       this.OnCategoryIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region bool Discontinued\r
-\r
-               private bool _discontinued;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_discontinued", Name = "Discontinued", DbType = "bit", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_discontinued", Name="Discontinued", DbType="bit", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public bool Discontinued\r
                {\r
                        get\r
                        {\r
-                               return _discontinued;\r
+                               return this._discontinued;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _discontinued)\r
+                               if ((_discontinued != value))\r
                                {\r
-                                       OnDiscontinuedChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _discontinued = value;\r
-                                       SendPropertyChanged("Discontinued");\r
-                                       OnDiscontinuedChanged();\r
+                                       this.OnDiscontinuedChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._discontinued = value;\r
+                                       this.SendPropertyChanged("Discontinued");\r
+                                       this.OnDiscontinuedChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long ProductID\r
-\r
-               private long _productID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_productID", Name = "ProductID", DbType = "integer", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_productID", Name="ProductID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long ProductID\r
                {\r
                        get\r
                        {\r
-                               return _productID;\r
+                               return this._productID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _productID)\r
+                               if ((_productID != value))\r
                                {\r
-                                       OnProductIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _productID = value;\r
-                                       SendPropertyChanged("ProductID");\r
-                                       OnProductIDChanged();\r
+                                       this.OnProductIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._productID = value;\r
+                                       this.SendPropertyChanged("ProductID");\r
+                                       this.OnProductIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ProductName\r
-\r
-               private string _productName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_productName", Name = "ProductName", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_productName", Name="ProductName", DbType="nvarchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string ProductName\r
                {\r
                        get\r
                        {\r
-                               return _productName;\r
+                               return this._productName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _productName)\r
+                               if (((_productName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnProductNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _productName = value;\r
-                                       SendPropertyChanged("ProductName");\r
-                                       OnProductNameChanged();\r
+                                       this.OnProductNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._productName = value;\r
+                                       this.SendPropertyChanged("ProductName");\r
+                                       this.OnProductNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string QuantityPerUnit\r
-\r
-               private string _quantityPerUnit;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_quantityPerUnit", Name = "QuantityPerUnit", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_quantityPerUnit", Name="QuantityPerUnit", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string QuantityPerUnit\r
                {\r
                        get\r
                        {\r
-                               return _quantityPerUnit;\r
+                               return this._quantityPerUnit;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _quantityPerUnit)\r
+                               if (((_quantityPerUnit == value) \r
+                                                       == false))\r
                                {\r
-                                       OnQuantityPerUnitChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _quantityPerUnit = value;\r
-                                       SendPropertyChanged("QuantityPerUnit");\r
-                                       OnQuantityPerUnitChanged();\r
+                                       this.OnQuantityPerUnitChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._quantityPerUnit = value;\r
+                                       this.SendPropertyChanged("QuantityPerUnit");\r
+                                       this.OnQuantityPerUnitChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region short? ReorderLevel\r
-\r
-               private short? _reorderLevel;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_reorderLevel", Name = "ReorderLevel", DbType = "smallint", AutoSync = AutoSync.Never)]\r
-               public short? ReorderLevel\r
+               \r
+               [Column(Storage="_reorderLevel", Name="ReorderLevel", DbType="smallint", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<short> ReorderLevel\r
                {\r
                        get\r
                        {\r
-                               return _reorderLevel;\r
+                               return this._reorderLevel;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _reorderLevel)\r
+                               if ((_reorderLevel != value))\r
                                {\r
-                                       OnReorderLevelChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _reorderLevel = value;\r
-                                       SendPropertyChanged("ReorderLevel");\r
-                                       OnReorderLevelChanged();\r
+                                       this.OnReorderLevelChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._reorderLevel = value;\r
+                                       this.SendPropertyChanged("ReorderLevel");\r
+                                       this.OnReorderLevelChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long? SupplierID\r
-\r
-               private long? _supplierID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_supplierID", Name = "SupplierID", DbType = "integer", AutoSync = AutoSync.Never)]\r
-               public long? SupplierID\r
+               \r
+               [Column(Storage="_supplierID", Name="SupplierID", DbType="integer", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<long> SupplierID\r
                {\r
                        get\r
                        {\r
-                               return _supplierID;\r
+                               return this._supplierID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _supplierID)\r
+                               if ((_supplierID != value))\r
                                {\r
                                        if (_supplier.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnSupplierIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _supplierID = value;\r
-                                       SendPropertyChanged("SupplierID");\r
-                                       OnSupplierIDChanged();\r
+                                       this.OnSupplierIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._supplierID = value;\r
+                                       this.SendPropertyChanged("SupplierID");\r
+                                       this.OnSupplierIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region decimal? UnitPrice\r
-\r
-               private decimal? _unitPrice;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_unitPrice", Name = "UnitPrice", DbType = "money", AutoSync = AutoSync.Never)]\r
-               public decimal? UnitPrice\r
+               \r
+               [Column(Storage="_unitPrice", Name="UnitPrice", DbType="money", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<decimal> UnitPrice\r
                {\r
                        get\r
                        {\r
-                               return _unitPrice;\r
+                               return this._unitPrice;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _unitPrice)\r
+                               if ((_unitPrice != value))\r
                                {\r
-                                       OnUnitPriceChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _unitPrice = value;\r
-                                       SendPropertyChanged("UnitPrice");\r
-                                       OnUnitPriceChanged();\r
+                                       this.OnUnitPriceChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._unitPrice = value;\r
+                                       this.SendPropertyChanged("UnitPrice");\r
+                                       this.OnUnitPriceChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region short? UnitsInStock\r
-\r
-               private short? _unitsInStock;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_unitsInStock", Name = "UnitsInStock", DbType = "smallint", AutoSync = AutoSync.Never)]\r
-               public short? UnitsInStock\r
+               \r
+               [Column(Storage="_unitsInStock", Name="UnitsInStock", DbType="smallint", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<short> UnitsInStock\r
                {\r
                        get\r
                        {\r
-                               return _unitsInStock;\r
+                               return this._unitsInStock;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _unitsInStock)\r
+                               if ((_unitsInStock != value))\r
                                {\r
-                                       OnUnitsInStockChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _unitsInStock = value;\r
-                                       SendPropertyChanged("UnitsInStock");\r
-                                       OnUnitsInStockChanged();\r
+                                       this.OnUnitsInStockChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._unitsInStock = value;\r
+                                       this.SendPropertyChanged("UnitsInStock");\r
+                                       this.OnUnitsInStockChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region short? UnitsOnOrder\r
-\r
-               private short? _unitsOnOrder;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_unitsOnOrder", Name = "UnitsOnOrder", DbType = "smallint", AutoSync = AutoSync.Never)]\r
-               public short? UnitsOnOrder\r
+               \r
+               [Column(Storage="_unitsOnOrder", Name="UnitsOnOrder", DbType="smallint", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<short> UnitsOnOrder\r
                {\r
                        get\r
                        {\r
-                               return _unitsOnOrder;\r
+                               return this._unitsOnOrder;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _unitsOnOrder)\r
+                               if ((_unitsOnOrder != value))\r
                                {\r
-                                       OnUnitsOnOrderChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _unitsOnOrder = value;\r
-                                       SendPropertyChanged("UnitsOnOrder");\r
-                                       OnUnitsOnOrderChanged();\r
+                                       this.OnUnitsOnOrderChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._unitsOnOrder = value;\r
+                                       this.SendPropertyChanged("UnitsOnOrder");\r
+                                       this.OnUnitsOnOrderChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<OrderDetail> _orderDetails;\r
-               [Association(Storage = "_orderDetails", OtherKey = "ProductID", ThisKey = "ProductID", Name = "\"FK_Order Details_0\"")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_orderDetails", OtherKey="ProductID", ThisKey="ProductID", Name="FK_Order Details_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<OrderDetail> OrderDetails\r
                {\r
                        get\r
                        {\r
-                               return _orderDetails;\r
+                               return this._orderDetails;\r
                        }\r
                        set\r
                        {\r
-                               _orderDetails = value;\r
+                               this._orderDetails = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Supplier> _supplier;\r
-               [Association(Storage = "_supplier", OtherKey = "SupplierID", ThisKey = "SupplierID", Name = "FK_Products_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_supplier", OtherKey="SupplierID", ThisKey="SupplierID", Name="FK_Products_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Supplier Supplier\r
                {\r
                        get\r
                        {\r
-                               return _supplier.Entity;\r
+                               return this._supplier.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _supplier.Entity)\r
+                               if (((this._supplier.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_supplier.Entity != null)\r
+                                       if ((this._supplier.Entity != null))\r
                                        {\r
-                                               var previousSupplier = _supplier.Entity;\r
-                                               _supplier.Entity = null;\r
+                                               Supplier previousSupplier = this._supplier.Entity;\r
+                                               this._supplier.Entity = null;\r
                                                previousSupplier.Products.Remove(this);\r
                                        }\r
-                                       _supplier.Entity = value;\r
-                                       if (value != null)\r
+                                       this._supplier.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Products.Add(this);\r
                                                _supplierID = value.SupplierID;\r
@@ -3154,28 +3395,28 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-               private EntityRef<Category> _category;\r
-               [Association(Storage = "_category", OtherKey = "CategoryID", ThisKey = "CategoryID", Name = "FK_Products_1", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_category", OtherKey="CategoryID", ThisKey="CategoryID", Name="FK_Products_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Category Category\r
                {\r
                        get\r
                        {\r
-                               return _category.Entity;\r
+                               return this._category.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _category.Entity)\r
+                               if (((this._category.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_category.Entity != null)\r
+                                       if ((this._category.Entity != null))\r
                                        {\r
-                                               var previousCategory = _category.Entity;\r
-                                               _category.Entity = null;\r
+                                               Category previousCategory = this._category.Entity;\r
+                                               this._category.Entity = null;\r
                                                previousCategory.Products.Remove(this);\r
                                        }\r
-                                       _category.Entity = value;\r
-                                       if (value != null)\r
+                                       this._category.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Products.Add(this);\r
                                                _categoryID = value.CategoryID;\r
@@ -3187,939 +3428,1008 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void OrderDetails_Attach(OrderDetail entity)\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
                {\r
-                       entity.Product = this;\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
                }\r
-\r
-               private void OrderDetails_Detach(OrderDetail entity)\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       entity.Product = null;\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Product()\r
+               \r
+               public override int GetHashCode()\r
                {\r
-                       _orderDetails = new EntitySet<OrderDetail>(OrderDetails_Attach, OrderDetails_Detach);\r
-                       _supplier = new EntityRef<Supplier>();\r
-                       _category = new EntityRef<Category>();\r
-                       OnCreated();\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_productID.GetHashCode() * 1));\r
+                       return hc;\r
                }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "Region")]\r
-       public partial class Region : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
+               \r
+               public override bool Equals(object value)\r
                {\r
-                       if (PropertyChanging != null)\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               return false;\r
                        }\r
+                       Product other = ((Product)(value));\r
+                       return this.Equals(other);\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
+               \r
+               public virtual bool Equals(Product value)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               return false;\r
                        }\r
+                       return System.Collections.Generic.EqualityComparer<long>.Default.Equals(this._productID, value._productID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void OrderDetails_Attach(OrderDetail entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Product = this;\r
+               }\r
+               \r
+               private void OrderDetails_Detach(OrderDetail entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Product = null;\r
                }\r
-\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="Region")]\r
+       public partial class Region : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Region>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _regionDescription;\r
+               \r
+               private long _regionID;\r
+               \r
+               private EntitySet<Territory> _territories;\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnRegionDescriptionChanged();\r
+               \r
                partial void OnRegionDescriptionChanging(string value);\r
+               \r
                partial void OnRegionIDChanged();\r
+               \r
                partial void OnRegionIDChanging(long value);\r
-\r
                #endregion\r
-\r
-               #region string RegionDescription\r
-\r
-               private string _regionDescription;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_regionDescription", Name = "RegionDescription", DbType = "nchar", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               \r
+               public Region()\r
+               {\r
+                       _territories = new EntitySet<Territory>(new Action<Territory>(this.Territories_Attach), new Action<Territory>(this.Territories_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_regionDescription", Name="RegionDescription", DbType="nchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string RegionDescription\r
                {\r
                        get\r
                        {\r
-                               return _regionDescription;\r
+                               return this._regionDescription;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _regionDescription)\r
+                               if (((_regionDescription == value) \r
+                                                       == false))\r
                                {\r
-                                       OnRegionDescriptionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _regionDescription = value;\r
-                                       SendPropertyChanged("RegionDescription");\r
-                                       OnRegionDescriptionChanged();\r
+                                       this.OnRegionDescriptionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._regionDescription = value;\r
+                                       this.SendPropertyChanged("RegionDescription");\r
+                                       this.OnRegionDescriptionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long RegionID\r
-\r
-               private long _regionID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_regionID", Name = "RegionID", DbType = "integer", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_regionID", Name="RegionID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long RegionID\r
                {\r
                        get\r
                        {\r
-                               return _regionID;\r
+                               return this._regionID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _regionID)\r
+                               if ((_regionID != value))\r
                                {\r
-                                       OnRegionIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _regionID = value;\r
-                                       SendPropertyChanged("RegionID");\r
-                                       OnRegionIDChanged();\r
+                                       this.OnRegionIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._regionID = value;\r
+                                       this.SendPropertyChanged("RegionID");\r
+                                       this.OnRegionIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<Territory> _territories;\r
-               [Association(Storage = "_territories", OtherKey = "RegionID", ThisKey = "RegionID", Name = "FK_Territories_0")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_territories", OtherKey="RegionID", ThisKey="RegionID", Name="FK_Territories_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Territory> Territories\r
                {\r
                        get\r
                        {\r
-                               return _territories;\r
+                               return this._territories;\r
                        }\r
                        set\r
                        {\r
-                               _territories = value;\r
+                               this._territories = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void Territories_Attach(Territory entity)\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
                {\r
-                       entity.Region = this;\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
                }\r
-\r
-               private void Territories_Detach(Territory entity)\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       entity.Region = null;\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Region()\r
+               \r
+               public override int GetHashCode()\r
                {\r
-                       _territories = new EntitySet<Territory>(Territories_Attach, Territories_Detach);\r
-                       OnCreated();\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_regionID.GetHashCode() * 1));\r
+                       return hc;\r
                }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "Shippers")]\r
-       public partial class Shipper : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
+               \r
+               public override bool Equals(object value)\r
                {\r
-                       if (PropertyChanging != null)\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               return false;\r
                        }\r
+                       Region other = ((Region)(value));\r
+                       return this.Equals(other);\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
+               \r
+               public virtual bool Equals(Region value)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               return false;\r
                        }\r
+                       return System.Collections.Generic.EqualityComparer<long>.Default.Equals(this._regionID, value._regionID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void Territories_Attach(Territory entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Region = this;\r
+               }\r
+               \r
+               private void Territories_Detach(Territory entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Region = null;\r
                }\r
-\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="Shippers")]\r
+       public partial class Shipper : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Shipper>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _companyName;\r
+               \r
+               private string _phone;\r
+               \r
+               private long _shipperID;\r
+               \r
+               private EntitySet<Order> _orders;\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnCompanyNameChanged();\r
+               \r
                partial void OnCompanyNameChanging(string value);\r
+               \r
                partial void OnPhoneChanged();\r
+               \r
                partial void OnPhoneChanging(string value);\r
+               \r
                partial void OnShipperIDChanged();\r
+               \r
                partial void OnShipperIDChanging(long value);\r
-\r
                #endregion\r
-\r
-               #region string CompanyName\r
-\r
-               private string _companyName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_companyName", Name = "CompanyName", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               \r
+               public Shipper()\r
+               {\r
+                       _orders = new EntitySet<Order>(new Action<Order>(this.Orders_Attach), new Action<Order>(this.Orders_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_companyName", Name="CompanyName", DbType="nvarchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CompanyName\r
                {\r
                        get\r
                        {\r
-                               return _companyName;\r
+                               return this._companyName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _companyName)\r
+                               if (((_companyName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCompanyNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _companyName = value;\r
-                                       SendPropertyChanged("CompanyName");\r
-                                       OnCompanyNameChanged();\r
+                                       this.OnCompanyNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._companyName = value;\r
+                                       this.SendPropertyChanged("CompanyName");\r
+                                       this.OnCompanyNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Phone\r
-\r
-               private string _phone;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_phone", Name = "Phone", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_phone", Name="Phone", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Phone\r
                {\r
                        get\r
                        {\r
-                               return _phone;\r
+                               return this._phone;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _phone)\r
+                               if (((_phone == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPhoneChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _phone = value;\r
-                                       SendPropertyChanged("Phone");\r
-                                       OnPhoneChanged();\r
+                                       this.OnPhoneChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._phone = value;\r
+                                       this.SendPropertyChanged("Phone");\r
+                                       this.OnPhoneChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long ShipperID\r
-\r
-               private long _shipperID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipperID", Name = "ShipperID", DbType = "integer", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_shipperID", Name="ShipperID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long ShipperID\r
                {\r
                        get\r
                        {\r
-                               return _shipperID;\r
+                               return this._shipperID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipperID)\r
+                               if ((_shipperID != value))\r
                                {\r
-                                       OnShipperIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipperID = value;\r
-                                       SendPropertyChanged("ShipperID");\r
-                                       OnShipperIDChanged();\r
+                                       this.OnShipperIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipperID = value;\r
+                                       this.SendPropertyChanged("ShipperID");\r
+                                       this.OnShipperIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<Order> _orders;\r
-               [Association(Storage = "_orders", OtherKey = "ShipVia", ThisKey = "ShipperID", Name = "FK_Orders_0")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_orders", OtherKey="ShipVia", ThisKey="ShipperID", Name="FK_Orders_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Order> Orders\r
                {\r
                        get\r
                        {\r
-                               return _orders;\r
+                               return this._orders;\r
                        }\r
                        set\r
                        {\r
-                               _orders = value;\r
+                               this._orders = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void Orders_Attach(Order entity)\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
                {\r
-                       entity.Shipper = this;\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
                }\r
-\r
-               private void Orders_Detach(Order entity)\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       entity.Shipper = null;\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Shipper()\r
+               \r
+               public override int GetHashCode()\r
                {\r
-                       _orders = new EntitySet<Order>(Orders_Attach, Orders_Detach);\r
-                       OnCreated();\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_shipperID.GetHashCode() * 1));\r
+                       return hc;\r
                }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "Suppliers")]\r
-       public partial class Supplier : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
+               \r
+               public override bool Equals(object value)\r
                {\r
-                       if (PropertyChanging != null)\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               return false;\r
                        }\r
+                       Shipper other = ((Shipper)(value));\r
+                       return this.Equals(other);\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
+               \r
+               public virtual bool Equals(Shipper value)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               return false;\r
                        }\r
+                       return System.Collections.Generic.EqualityComparer<long>.Default.Equals(this._shipperID, value._shipperID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void Orders_Attach(Order entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Shipper = this;\r
+               }\r
+               \r
+               private void Orders_Detach(Order entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Shipper = null;\r
                }\r
-\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="Suppliers")]\r
+       public partial class Supplier : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Supplier>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _address;\r
+               \r
+               private string _city;\r
+               \r
+               private string _companyName;\r
+               \r
+               private string _contactName;\r
+               \r
+               private string _contactTitle;\r
+               \r
+               private string _country;\r
+               \r
+               private string _fax;\r
+               \r
+               private string _homePage;\r
+               \r
+               private string _phone;\r
+               \r
+               private string _postalCode;\r
+               \r
+               private string _region;\r
+               \r
+               private long _supplierID;\r
+               \r
+               private EntitySet<Product> _products;\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnAddressChanged();\r
+               \r
                partial void OnAddressChanging(string value);\r
+               \r
                partial void OnCityChanged();\r
+               \r
                partial void OnCityChanging(string value);\r
+               \r
                partial void OnCompanyNameChanged();\r
+               \r
                partial void OnCompanyNameChanging(string value);\r
+               \r
                partial void OnContactNameChanged();\r
+               \r
                partial void OnContactNameChanging(string value);\r
+               \r
                partial void OnContactTitleChanged();\r
+               \r
                partial void OnContactTitleChanging(string value);\r
+               \r
                partial void OnCountryChanged();\r
+               \r
                partial void OnCountryChanging(string value);\r
+               \r
                partial void OnFaxChanged();\r
+               \r
                partial void OnFaxChanging(string value);\r
+               \r
                partial void OnHomePageChanged();\r
+               \r
                partial void OnHomePageChanging(string value);\r
+               \r
                partial void OnPhoneChanged();\r
+               \r
                partial void OnPhoneChanging(string value);\r
+               \r
                partial void OnPostalCodeChanged();\r
+               \r
                partial void OnPostalCodeChanging(string value);\r
+               \r
                partial void OnRegionChanged();\r
+               \r
                partial void OnRegionChanging(string value);\r
+               \r
                partial void OnSupplierIDChanged();\r
+               \r
                partial void OnSupplierIDChanging(long value);\r
-\r
                #endregion\r
-\r
-               #region string Address\r
-\r
-               private string _address;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_address", Name = "Address", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               \r
+               public Supplier()\r
+               {\r
+                       _products = new EntitySet<Product>(new Action<Product>(this.Products_Attach), new Action<Product>(this.Products_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_address", Name="Address", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Address\r
                {\r
                        get\r
                        {\r
-                               return _address;\r
+                               return this._address;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _address)\r
+                               if (((_address == value) \r
+                                                       == false))\r
                                {\r
-                                       OnAddressChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _address = value;\r
-                                       SendPropertyChanged("Address");\r
-                                       OnAddressChanged();\r
+                                       this.OnAddressChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._address = value;\r
+                                       this.SendPropertyChanged("Address");\r
+                                       this.OnAddressChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string City\r
-\r
-               private string _city;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_city", Name = "City", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_city", Name="City", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string City\r
                {\r
                        get\r
                        {\r
-                               return _city;\r
+                               return this._city;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _city)\r
+                               if (((_city == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _city = value;\r
-                                       SendPropertyChanged("City");\r
-                                       OnCityChanged();\r
+                                       this.OnCityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._city = value;\r
+                                       this.SendPropertyChanged("City");\r
+                                       this.OnCityChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string CompanyName\r
-\r
-               private string _companyName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_companyName", Name = "CompanyName", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_companyName", Name="CompanyName", DbType="nvarchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CompanyName\r
                {\r
                        get\r
                        {\r
-                               return _companyName;\r
+                               return this._companyName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _companyName)\r
+                               if (((_companyName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCompanyNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _companyName = value;\r
-                                       SendPropertyChanged("CompanyName");\r
-                                       OnCompanyNameChanged();\r
+                                       this.OnCompanyNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._companyName = value;\r
+                                       this.SendPropertyChanged("CompanyName");\r
+                                       this.OnCompanyNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ContactName\r
-\r
-               private string _contactName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_contactName", Name = "ContactName", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_contactName", Name="ContactName", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ContactName\r
                {\r
                        get\r
                        {\r
-                               return _contactName;\r
+                               return this._contactName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _contactName)\r
+                               if (((_contactName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnContactNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _contactName = value;\r
-                                       SendPropertyChanged("ContactName");\r
-                                       OnContactNameChanged();\r
+                                       this.OnContactNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._contactName = value;\r
+                                       this.SendPropertyChanged("ContactName");\r
+                                       this.OnContactNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ContactTitle\r
-\r
-               private string _contactTitle;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_contactTitle", Name = "ContactTitle", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_contactTitle", Name="ContactTitle", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ContactTitle\r
                {\r
                        get\r
                        {\r
-                               return _contactTitle;\r
+                               return this._contactTitle;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _contactTitle)\r
+                               if (((_contactTitle == value) \r
+                                                       == false))\r
                                {\r
-                                       OnContactTitleChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _contactTitle = value;\r
-                                       SendPropertyChanged("ContactTitle");\r
-                                       OnContactTitleChanged();\r
+                                       this.OnContactTitleChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._contactTitle = value;\r
+                                       this.SendPropertyChanged("ContactTitle");\r
+                                       this.OnContactTitleChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Country\r
-\r
-               private string _country;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_country", Name = "Country", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_country", Name="Country", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Country\r
                {\r
                        get\r
                        {\r
-                               return _country;\r
+                               return this._country;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _country)\r
+                               if (((_country == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCountryChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _country = value;\r
-                                       SendPropertyChanged("Country");\r
-                                       OnCountryChanged();\r
+                                       this.OnCountryChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._country = value;\r
+                                       this.SendPropertyChanged("Country");\r
+                                       this.OnCountryChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Fax\r
-\r
-               private string _fax;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_fax", Name = "Fax", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_fax", Name="Fax", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Fax\r
                {\r
                        get\r
                        {\r
-                               return _fax;\r
+                               return this._fax;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _fax)\r
+                               if (((_fax == value) \r
+                                                       == false))\r
                                {\r
-                                       OnFaxChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _fax = value;\r
-                                       SendPropertyChanged("Fax");\r
-                                       OnFaxChanged();\r
+                                       this.OnFaxChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._fax = value;\r
+                                       this.SendPropertyChanged("Fax");\r
+                                       this.OnFaxChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string HomePage\r
-\r
-               private string _homePage;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_homePage", Name = "HomePage", DbType = "ntext", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_homePage", Name="HomePage", DbType="ntext", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string HomePage\r
                {\r
                        get\r
                        {\r
-                               return _homePage;\r
+                               return this._homePage;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _homePage)\r
+                               if (((_homePage == value) \r
+                                                       == false))\r
                                {\r
-                                       OnHomePageChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _homePage = value;\r
-                                       SendPropertyChanged("HomePage");\r
-                                       OnHomePageChanged();\r
+                                       this.OnHomePageChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._homePage = value;\r
+                                       this.SendPropertyChanged("HomePage");\r
+                                       this.OnHomePageChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Phone\r
-\r
-               private string _phone;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_phone", Name = "Phone", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_phone", Name="Phone", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Phone\r
                {\r
                        get\r
                        {\r
-                               return _phone;\r
+                               return this._phone;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _phone)\r
+                               if (((_phone == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPhoneChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _phone = value;\r
-                                       SendPropertyChanged("Phone");\r
-                                       OnPhoneChanged();\r
+                                       this.OnPhoneChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._phone = value;\r
+                                       this.SendPropertyChanged("Phone");\r
+                                       this.OnPhoneChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string PostalCode\r
-\r
-               private string _postalCode;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_postalCode", Name = "PostalCode", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_postalCode", Name="PostalCode", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string PostalCode\r
                {\r
                        get\r
                        {\r
-                               return _postalCode;\r
+                               return this._postalCode;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _postalCode)\r
+                               if (((_postalCode == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPostalCodeChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _postalCode = value;\r
-                                       SendPropertyChanged("PostalCode");\r
-                                       OnPostalCodeChanged();\r
+                                       this.OnPostalCodeChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._postalCode = value;\r
+                                       this.SendPropertyChanged("PostalCode");\r
+                                       this.OnPostalCodeChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Region\r
-\r
-               private string _region;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_region", Name = "Region", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_region", Name="Region", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Region\r
                {\r
                        get\r
                        {\r
-                               return _region;\r
+                               return this._region;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _region)\r
+                               if (((_region == value) \r
+                                                       == false))\r
                                {\r
-                                       OnRegionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _region = value;\r
-                                       SendPropertyChanged("Region");\r
-                                       OnRegionChanged();\r
+                                       this.OnRegionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._region = value;\r
+                                       this.SendPropertyChanged("Region");\r
+                                       this.OnRegionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long SupplierID\r
-\r
-               private long _supplierID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_supplierID", Name = "SupplierID", DbType = "integer", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_supplierID", Name="SupplierID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long SupplierID\r
                {\r
                        get\r
                        {\r
-                               return _supplierID;\r
+                               return this._supplierID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _supplierID)\r
+                               if ((_supplierID != value))\r
                                {\r
-                                       OnSupplierIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _supplierID = value;\r
-                                       SendPropertyChanged("SupplierID");\r
-                                       OnSupplierIDChanged();\r
+                                       this.OnSupplierIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._supplierID = value;\r
+                                       this.SendPropertyChanged("SupplierID");\r
+                                       this.OnSupplierIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<Product> _products;\r
-               [Association(Storage = "_products", OtherKey = "SupplierID", ThisKey = "SupplierID", Name = "FK_Products_0")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_products", OtherKey="SupplierID", ThisKey="SupplierID", Name="FK_Products_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Product> Products\r
                {\r
                        get\r
                        {\r
-                               return _products;\r
+                               return this._products;\r
                        }\r
                        set\r
                        {\r
-                               _products = value;\r
+                               this._products = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void Products_Attach(Product entity)\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
                {\r
-                       entity.Supplier = this;\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
                }\r
-\r
-               private void Products_Detach(Product entity)\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       entity.Supplier = null;\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Supplier()\r
+               \r
+               public override int GetHashCode()\r
                {\r
-                       _products = new EntitySet<Product>(Products_Attach, Products_Detach);\r
-                       OnCreated();\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_supplierID.GetHashCode() * 1));\r
+                       return hc;\r
                }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "Territories")]\r
-       public partial class Territory : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
+               \r
+               public override bool Equals(object value)\r
                {\r
-                       if (PropertyChanging != null)\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               return false;\r
                        }\r
+                       Supplier other = ((Supplier)(value));\r
+                       return this.Equals(other);\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
+               \r
+               public virtual bool Equals(Supplier value)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               return false;\r
                        }\r
+                       return System.Collections.Generic.EqualityComparer<long>.Default.Equals(this._supplierID, value._supplierID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void Products_Attach(Product entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Supplier = this;\r
+               }\r
+               \r
+               private void Products_Detach(Product entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Supplier = null;\r
                }\r
-\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="Territories")]\r
+       public partial class Territory : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Territory>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private long _regionID;\r
+               \r
+               private string _territoryDescription;\r
+               \r
+               private string _territoryID;\r
+               \r
+               private EntitySet<EmployeeTerritory> _employeeTerritories;\r
+               \r
+               private EntityRef<Region> _region = new EntityRef<Region>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnRegionIDChanged();\r
+               \r
                partial void OnRegionIDChanging(long value);\r
+               \r
                partial void OnTerritoryDescriptionChanged();\r
+               \r
                partial void OnTerritoryDescriptionChanging(string value);\r
+               \r
                partial void OnTerritoryIDChanged();\r
+               \r
                partial void OnTerritoryIDChanging(string value);\r
-\r
                #endregion\r
-\r
-               #region long RegionID\r
-\r
-               private long _regionID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_regionID", Name = "RegionID", DbType = "integer", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               \r
+               public Territory()\r
+               {\r
+                       _employeeTerritories = new EntitySet<EmployeeTerritory>(new Action<EmployeeTerritory>(this.EmployeeTerritories_Attach), new Action<EmployeeTerritory>(this.EmployeeTerritories_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_regionID", Name="RegionID", DbType="integer", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long RegionID\r
                {\r
                        get\r
                        {\r
-                               return _regionID;\r
+                               return this._regionID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _regionID)\r
+                               if ((_regionID != value))\r
                                {\r
                                        if (_region.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnRegionIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _regionID = value;\r
-                                       SendPropertyChanged("RegionID");\r
-                                       OnRegionIDChanged();\r
+                                       this.OnRegionIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._regionID = value;\r
+                                       this.SendPropertyChanged("RegionID");\r
+                                       this.OnRegionIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string TerritoryDescription\r
-\r
-               private string _territoryDescription;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_territoryDescription", Name = "TerritoryDescription", DbType = "nchar", AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_territoryDescription", Name="TerritoryDescription", DbType="nchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string TerritoryDescription\r
                {\r
                        get\r
                        {\r
-                               return _territoryDescription;\r
+                               return this._territoryDescription;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _territoryDescription)\r
+                               if (((_territoryDescription == value) \r
+                                                       == false))\r
                                {\r
-                                       OnTerritoryDescriptionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _territoryDescription = value;\r
-                                       SendPropertyChanged("TerritoryDescription");\r
-                                       OnTerritoryDescriptionChanged();\r
+                                       this.OnTerritoryDescriptionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._territoryDescription = value;\r
+                                       this.SendPropertyChanged("TerritoryDescription");\r
+                                       this.OnTerritoryDescriptionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string TerritoryID\r
-\r
-               private string _territoryID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_territoryID", Name = "TerritoryID", DbType = "nvarchar", IsPrimaryKey = true, AutoSync = AutoSync.Never, CanBeNull = false)]\r
+               \r
+               [Column(Storage="_territoryID", Name="TerritoryID", DbType="nvarchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string TerritoryID\r
                {\r
                        get\r
                        {\r
-                               return _territoryID;\r
+                               return this._territoryID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _territoryID)\r
+                               if (((_territoryID == value) \r
+                                                       == false))\r
                                {\r
-                                       OnTerritoryIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _territoryID = value;\r
-                                       SendPropertyChanged("TerritoryID");\r
-                                       OnTerritoryIDChanged();\r
+                                       this.OnTerritoryIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._territoryID = value;\r
+                                       this.SendPropertyChanged("TerritoryID");\r
+                                       this.OnTerritoryIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<EmployeeTerritory> _employeeTerritories;\r
-               [Association(Storage = "_employeeTerritories", OtherKey = "TerritoryID", ThisKey = "TerritoryID", Name = "FK_EmployeeTerritories_0")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_employeeTerritories", OtherKey="TerritoryID", ThisKey="TerritoryID", Name="FK_EmployeeTerritories_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<EmployeeTerritory> EmployeeTerritories\r
                {\r
                        get\r
                        {\r
-                               return _employeeTerritories;\r
+                               return this._employeeTerritories;\r
                        }\r
                        set\r
                        {\r
-                               _employeeTerritories = value;\r
+                               this._employeeTerritories = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Region> _region;\r
-               [Association(Storage = "_region", OtherKey = "RegionID", ThisKey = "RegionID", Name = "FK_Territories_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_region", OtherKey="RegionID", ThisKey="RegionID", Name="FK_Territories_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Region Region\r
                {\r
                        get\r
                        {\r
-                               return _region.Entity;\r
+                               return this._region.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _region.Entity)\r
+                               if (((this._region.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_region.Entity != null)\r
+                                       if ((this._region.Entity != null))\r
                                        {\r
-                                               var previousRegion = _region.Entity;\r
-                                               _region.Entity = null;\r
+                                               Region previousRegion = this._region.Entity;\r
+                                               this._region.Entity = null;\r
                                                previousRegion.Territories.Remove(this);\r
                                        }\r
-                                       _region.Entity = value;\r
-                                       if (value != null)\r
+                                       this._region.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Territories.Add(this);\r
                                                _regionID = value.RegionID;\r
@@ -4131,35 +4441,77 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       if ((_territoryID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_territoryID.GetHashCode() * 1));\r
+                       }\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Territory other = ((Territory)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Territory value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._territoryID, value._territoryID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
                private void EmployeeTerritories_Attach(EmployeeTerritory entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Territory = this;\r
                }\r
-\r
+               \r
                private void EmployeeTerritories_Detach(EmployeeTerritory entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Territory = null;\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Territory()\r
-               {\r
-                       _employeeTerritories = new EntitySet<EmployeeTerritory>(EmployeeTerritories_Attach, EmployeeTerritories_Detach);\r
-                       _region = new EntityRef<Region>();\r
-                       OnCreated();\r
-               }\r
-\r
                #endregion\r
-\r
        }\r
 }\r
diff --git a/mcs/class/System.Data.Linq/tests/expected/Northwind.Sqlite+DbSchemaLoader-DbMetal.dbml b/mcs/class/System.Data.Linq/tests/expected/Northwind.Sqlite+DbSchemaLoader-DbMetal.dbml
new file mode 100755 (executable)
index 0000000..4cf3316
--- /dev/null
@@ -0,0 +1,169 @@
+<?xml version="1.0"?>\r
+<Database xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Name="main" Class="Main" BaseType="DbLinq.Data.Linq.DataContext" xmlns="http://schemas.microsoft.com/linqtosql/dbml/2007">\r
+  <Table Name="Categories" Member="Categories">\r
+    <Type Name="Categories">\r
+      <Association Name="FK_Products_1" Member="Products" Storage="_products" Type="Products" ThisKey="CategoryID" OtherKey="CategoryID" DeleteRule="NO ACTION" />\r
+      <Column Name="CategoryID" Member="CategoryID" Storage="_categoryID" Type="System.Int64" DbType="integer" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="CategoryName" Member="CategoryName" Storage="_categoryName" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="Description" Member="Description" Storage="_description" Type="System.String" DbType="ntext" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Picture" Member="Picture" Storage="_picture" Type="System.Byte[]" DbType="image" IsPrimaryKey="false" CanBeNull="true" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="CustomerCustomerDemo" Member="CustomerCustomerDemo">\r
+    <Type Name="CustomerCustomerDemo">\r
+      <Association Name="FK_CustomerCustomerDemo_0" Member="Customers" Storage="_customers" Type="Customers" ThisKey="CustomerID" OtherKey="CustomerID" IsForeignKey="true" />\r
+      <Association Name="FK_CustomerCustomerDemo_1" Member="CustomerDemographics" Storage="_customerDemographics" Type="CustomerDemographics" ThisKey="CustomerTypeID" OtherKey="CustomerTypeID" IsForeignKey="true" />\r
+      <Column Name="CustomerID" Member="CustomerID" Storage="_customerID" Type="System.String" DbType="nchar" IsPrimaryKey="true" CanBeNull="false" />\r
+      <Column Name="CustomerTypeID" Member="CustomerTypeID" Storage="_customerTypeID" Type="System.String" DbType="nchar" IsPrimaryKey="true" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="CustomerDemographics" Member="CustomerDemographics">\r
+    <Type Name="CustomerDemographics">\r
+      <Association Name="FK_CustomerCustomerDemo_1" Member="CustomerCustomerDemo" Storage="_customerCustomerDemo" Type="CustomerCustomerDemo" ThisKey="CustomerTypeID" OtherKey="CustomerTypeID" DeleteRule="NO ACTION" />\r
+      <Column Name="CustomerDesc" Member="CustomerDesc" Storage="_customerDesc" Type="System.String" DbType="ntext" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="CustomerTypeID" Member="CustomerTypeID" Storage="_customerTypeID" Type="System.String" DbType="nchar" IsPrimaryKey="true" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="Customers" Member="Customers">\r
+    <Type Name="Customers">\r
+      <Association Name="FK_Orders_2" Member="Orders" Storage="_orders" Type="Orders" ThisKey="CustomerID" OtherKey="CustomerID" DeleteRule="NO ACTION" />\r
+      <Association Name="FK_CustomerCustomerDemo_0" Member="CustomerCustomerDemo" Storage="_customerCustomerDemo" Type="CustomerCustomerDemo" ThisKey="CustomerID" OtherKey="CustomerID" DeleteRule="NO ACTION" />\r
+      <Column Name="Address" Member="Address" Storage="_address" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="City" Member="City" Storage="_city" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="CompanyName" Member="CompanyName" Storage="_companyName" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="ContactName" Member="ContactName" Storage="_contactName" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ContactTitle" Member="ContactTitle" Storage="_contactTitle" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Country" Member="Country" Storage="_country" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="CustomerID" Member="CustomerID" Storage="_customerID" Type="System.String" DbType="nchar" IsPrimaryKey="true" CanBeNull="false" />\r
+      <Column Name="Fax" Member="Fax" Storage="_fax" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Phone" Member="Phone" Storage="_phone" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="PostalCode" Member="PostalCode" Storage="_postalCode" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Region" Member="Region" Storage="_region" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="Employees" Member="Employees">\r
+    <Type Name="Employees">\r
+      <Association Name="FK_Employees_0" Member="ReportsToEmployees" Storage="_reportsToEmployees" Type="Employees" ThisKey="ReportsTo" OtherKey="EmployeeID" IsForeignKey="true" />\r
+      <Association Name="FK_Employees_0" Member="EmployeeIDEmployees" Storage="_employeeIdeMployees" Type="Employees" ThisKey="EmployeeID" OtherKey="ReportsTo" DeleteRule="NO ACTION" />\r
+      <Association Name="FK_Orders_1" Member="Orders" Storage="_orders" Type="Orders" ThisKey="EmployeeID" OtherKey="EmployeeID" DeleteRule="NO ACTION" />\r
+      <Association Name="FK_EmployeeTerritories_1" Member="EmployeeTerritories" Storage="_employeeTerritories" Type="EmployeeTerritories" ThisKey="EmployeeID" OtherKey="EmployeeID" DeleteRule="NO ACTION" />\r
+      <Column Name="Address" Member="Address" Storage="_address" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="BirthDate" Member="BirthDate" Storage="_birthDate" Type="System.DateTime" DbType="datetime" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="City" Member="City" Storage="_city" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Country" Member="Country" Storage="_country" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="EmployeeID" Member="EmployeeID" Storage="_employeeID" Type="System.Int64" DbType="integer" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="Extension" Member="Extension" Storage="_extension" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="FirstName" Member="FirstName" Storage="_firstName" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="HireDate" Member="HireDate" Storage="_hireDate" Type="System.DateTime" DbType="datetime" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="HomePhone" Member="HomePhone" Storage="_homePhone" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="LastName" Member="LastName" Storage="_lastName" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="Notes" Member="Notes" Storage="_notes" Type="System.String" DbType="ntext" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Photo" Member="Photo" Storage="_photo" Type="System.Byte[]" DbType="image" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="PhotoPath" Member="PhotoPath" Storage="_photoPath" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="PostalCode" Member="PostalCode" Storage="_postalCode" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Region" Member="Region" Storage="_region" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ReportsTo" Member="ReportsTo" Storage="_reportsTo" Type="System.Int64" DbType="integer" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Title" Member="Title" Storage="_title" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="TitleOfCourtesy" Member="TitleOfCourtesy" Storage="_titleOfCourtesy" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="EmployeeTerritories" Member="EmployeeTerritories">\r
+    <Type Name="EmployeeTerritories">\r
+      <Association Name="FK_EmployeeTerritories_0" Member="Territories" Storage="_territories" Type="Territories" ThisKey="TerritoryID" OtherKey="TerritoryID" IsForeignKey="true" />\r
+      <Association Name="FK_EmployeeTerritories_1" Member="Employees" Storage="_employees" Type="Employees" ThisKey="EmployeeID" OtherKey="EmployeeID" IsForeignKey="true" />\r
+      <Column Name="EmployeeID" Member="EmployeeID" Storage="_employeeID" Type="System.Int64" DbType="integer" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="TerritoryID" Member="TerritoryID" Storage="_territoryID" Type="System.String" DbType="nvarchar" IsPrimaryKey="true" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="Order Details" Member="OrderDetails">\r
+    <Type Name="OrderDetails">\r
+      <Association Name="FK_Order Details_0" Member="Products" Storage="_products" Type="Products" ThisKey="ProductID" OtherKey="ProductID" IsForeignKey="true" />\r
+      <Association Name="FK_Order Details_1" Member="Orders" Storage="_orders" Type="Orders" ThisKey="OrderID" OtherKey="OrderID" IsForeignKey="true" />\r
+      <Column Name="Discount" Member="Discount" Storage="_discount" Type="System.Single" DbType="real" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="OrderID" Member="OrderID" Storage="_orderID" Type="System.Int64" DbType="integer" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="ProductID" Member="ProductID" Storage="_productID" Type="System.Int64" DbType="integer" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="Quantity" Member="Quantity" Storage="_quantity" Type="System.Int16" DbType="smallint" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="UnitPrice" Member="UnitPrice" Storage="_unitPrice" Type="System.Decimal" DbType="money" IsPrimaryKey="false" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="Orders" Member="Orders">\r
+    <Type Name="Orders">\r
+      <Association Name="FK_Orders_0" Member="Shippers" Storage="_shippers" Type="Shippers" ThisKey="ShipVia" OtherKey="ShipperID" IsForeignKey="true" />\r
+      <Association Name="FK_Orders_1" Member="Employees" Storage="_employees" Type="Employees" ThisKey="EmployeeID" OtherKey="EmployeeID" IsForeignKey="true" />\r
+      <Association Name="FK_Orders_2" Member="Customers" Storage="_customers" Type="Customers" ThisKey="CustomerID" OtherKey="CustomerID" IsForeignKey="true" />\r
+      <Association Name="FK_Order Details_1" Member="OrderDetails" Storage="_orderDetails" Type="OrderDetails" ThisKey="OrderID" OtherKey="OrderID" DeleteRule="NO ACTION" />\r
+      <Column Name="CustomerID" Member="CustomerID" Storage="_customerID" Type="System.String" DbType="nchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="EmployeeID" Member="EmployeeID" Storage="_employeeID" Type="System.Int64" DbType="integer" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Freight" Member="Freight" Storage="_freight" Type="System.Decimal" DbType="money" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="OrderDate" Member="OrderDate" Storage="_orderDate" Type="System.DateTime" DbType="datetime" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="OrderID" Member="OrderID" Storage="_orderID" Type="System.Int64" DbType="integer" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="RequiredDate" Member="RequiredDate" Storage="_requiredDate" Type="System.DateTime" DbType="datetime" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ShipAddress" Member="ShipAddress" Storage="_shipAddress" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ShipCity" Member="ShipCity" Storage="_shipCity" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ShipCountry" Member="ShipCountry" Storage="_shipCountry" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ShipName" Member="ShipName" Storage="_shipName" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ShippedDate" Member="ShippedDate" Storage="_shippedDate" Type="System.DateTime" DbType="datetime" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ShipPostalCode" Member="ShipPostalCode" Storage="_shipPostalCode" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ShipRegion" Member="ShipRegion" Storage="_shipRegion" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ShipVia" Member="ShipVia" Storage="_shipVia" Type="System.Int64" DbType="integer" IsPrimaryKey="false" CanBeNull="true" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="Products" Member="Products">\r
+    <Type Name="Products">\r
+      <Association Name="FK_Products_0" Member="Suppliers" Storage="_suppliers" Type="Suppliers" ThisKey="SupplierID" OtherKey="SupplierID" IsForeignKey="true" />\r
+      <Association Name="FK_Products_1" Member="Categories" Storage="_categories" Type="Categories" ThisKey="CategoryID" OtherKey="CategoryID" IsForeignKey="true" />\r
+      <Association Name="FK_Order Details_0" Member="OrderDetails" Storage="_orderDetails" Type="OrderDetails" ThisKey="ProductID" OtherKey="ProductID" DeleteRule="NO ACTION" />\r
+      <Column Name="CategoryID" Member="CategoryID" Storage="_categoryID" Type="System.Int64" DbType="integer" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Discontinued" Member="Discontinued" Storage="_discontinued" Type="System.Boolean" DbType="bit" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="ProductID" Member="ProductID" Storage="_productID" Type="System.Int64" DbType="integer" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="ProductName" Member="ProductName" Storage="_productName" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="QuantityPerUnit" Member="QuantityPerUnit" Storage="_quantityPerUnit" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ReorderLevel" Member="ReorderLevel" Storage="_reorderLevel" Type="System.Int16" DbType="smallint" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="SupplierID" Member="SupplierID" Storage="_supplierID" Type="System.Int64" DbType="integer" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="UnitPrice" Member="UnitPrice" Storage="_unitPrice" Type="System.Decimal" DbType="money" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="UnitsInStock" Member="UnitsInStock" Storage="_unitsInStock" Type="System.Int16" DbType="smallint" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="UnitsOnOrder" Member="UnitsOnOrder" Storage="_unitsOnOrder" Type="System.Int16" DbType="smallint" IsPrimaryKey="false" CanBeNull="true" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="Region" Member="Region">\r
+    <Type Name="Region">\r
+      <Association Name="FK_Territories_0" Member="Territories" Storage="_territories" Type="Territories" ThisKey="RegionID" OtherKey="RegionID" DeleteRule="NO ACTION" />\r
+      <Column Name="RegionDescription" Member="RegionDescription" Storage="_regionDescription" Type="System.String" DbType="nchar" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="RegionID" Member="RegionID" Storage="_regionID" Type="System.Int64" DbType="integer" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="Shippers" Member="Shippers">\r
+    <Type Name="Shippers">\r
+      <Association Name="FK_Orders_0" Member="Orders" Storage="_orders" Type="Orders" ThisKey="ShipperID" OtherKey="ShipVia" DeleteRule="NO ACTION" />\r
+      <Column Name="CompanyName" Member="CompanyName" Storage="_companyName" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="Phone" Member="Phone" Storage="_phone" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ShipperID" Member="ShipperID" Storage="_shipperID" Type="System.Int64" DbType="integer" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="Suppliers" Member="Suppliers">\r
+    <Type Name="Suppliers">\r
+      <Association Name="FK_Products_0" Member="Products" Storage="_products" Type="Products" ThisKey="SupplierID" OtherKey="SupplierID" DeleteRule="NO ACTION" />\r
+      <Column Name="Address" Member="Address" Storage="_address" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="City" Member="City" Storage="_city" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="CompanyName" Member="CompanyName" Storage="_companyName" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="ContactName" Member="ContactName" Storage="_contactName" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ContactTitle" Member="ContactTitle" Storage="_contactTitle" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Country" Member="Country" Storage="_country" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Fax" Member="Fax" Storage="_fax" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="HomePage" Member="HomePage" Storage="_homePage" Type="System.String" DbType="ntext" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Phone" Member="Phone" Storage="_phone" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="PostalCode" Member="PostalCode" Storage="_postalCode" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Region" Member="Region" Storage="_region" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="SupplierID" Member="SupplierID" Storage="_supplierID" Type="System.Int64" DbType="integer" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="Territories" Member="Territories">\r
+    <Type Name="Territories">\r
+      <Association Name="FK_Territories_0" Member="Region" Storage="_region" Type="Region" ThisKey="RegionID" OtherKey="RegionID" IsForeignKey="true" />\r
+      <Association Name="FK_EmployeeTerritories_0" Member="EmployeeTerritories" Storage="_employeeTerritories" Type="EmployeeTerritories" ThisKey="TerritoryID" OtherKey="TerritoryID" DeleteRule="NO ACTION" />\r
+      <Column Name="RegionID" Member="RegionID" Storage="_regionID" Type="System.Int64" DbType="integer" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="TerritoryDescription" Member="TerritoryDescription" Storage="_territoryDescription" Type="System.String" DbType="nchar" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="TerritoryID" Member="TerritoryID" Storage="_territoryID" Type="System.String" DbType="nvarchar" IsPrimaryKey="true" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+</Database>
\ No newline at end of file
index 1474d2b070cf70b6a8ffe266fec31b10dfa340ee..12413849806b73bbf9630001c460a86c96c3a7cc 100755 (executable)
-#region Auto-generated classes for Northwind database on [TIMESTAMP]\r
-\r
-//\r
-//  ____  _     __  __      _        _\r
+// \r
+//  ____  _     __  __      _        _ \r
 // |  _ \| |__ |  \/  | ___| |_ __ _| |\r
 // | | | | '_ \| |\/| |/ _ \ __/ _` | |\r
 // | |_| | |_) | |  | |  __/ || (_| | |\r
 // |____/|_.__/|_|  |_|\___|\__\__,_|_|\r
 //\r
-// Auto-generated from Northwind on [TIMESTAMP]\r
-// Please visit http://linq.to/db for more information\r
-\r
-#endregion\r
-\r
-using System;\r
-using System.Data;\r
-using System.Data.Linq.Mapping;\r
-using System.Diagnostics;\r
-using System.Reflection;\r
-using System.Data.Linq;\r
-using System.ComponentModel;\r
-\r
+// Auto-generated from Northwind on [TIMESTAMP].\r
+// Please visit http://code.google.com/p/dblinq2007/ for more information.\r
+//\r
 namespace nwind\r
 {\r
+       using System;\r
+       using System.ComponentModel;\r
+       using System.Data;\r
+       using System.Data.Linq;\r
+       using System.Data.Linq.Mapping;\r
+       using System.Diagnostics;\r
+       \r
+       \r
        public partial class Northwind : DataContext\r
        {\r
-               #region Extensibility Method Definitions\r
-\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
-\r
                #endregion\r
-\r
-               public Northwind(string connectionString)\r
-                       : base(connectionString)\r
-               {\r
-                       OnCreated();\r
-               }\r
-\r
-               public Northwind(IDbConnection connection)\r
-                       : base(connection)\r
-               {\r
-                       OnCreated();\r
-               }\r
-\r
-               public Northwind(string connection, MappingSource mappingSource)\r
-                       : base(connection, mappingSource)\r
-               {\r
-                       OnCreated();\r
-               }\r
-\r
-               public Northwind(IDbConnection connection, MappingSource mappingSource)\r
-                       : base(connection, mappingSource)\r
-               {\r
-                       OnCreated();\r
-               }\r
-\r
-               public Table<Category> Categories { get { return GetTable<Category>(); } }\r
-               public Table<Customer> Customers { get { return GetTable<Customer>(); } }\r
-               public Table<CustomerCustomerDemo> CustomerCustomerDemo { get { return GetTable<CustomerCustomerDemo>(); } }\r
-               public Table<CustomerDemographic> CustomerDemographics { get { return GetTable<CustomerDemographic>(); } }\r
-               public Table<Employee> Employees { get { return GetTable<Employee>(); } }\r
-               public Table<EmployeeTerritory> EmployeeTerritories { get { return GetTable<EmployeeTerritory>(); } }\r
-               public Table<Order> Orders { get { return GetTable<Order>(); } }\r
-               public Table<OrderDetail> OrderDetails { get { return GetTable<OrderDetail>(); } }\r
-               public Table<Product> Products { get { return GetTable<Product>(); } }\r
-               public Table<Region> Regions { get { return GetTable<Region>(); } }\r
-               public Table<Shipper> Shippers { get { return GetTable<Shipper>(); } }\r
-               public Table<Supplier> Suppliers { get { return GetTable<Supplier>(); } }\r
-               public Table<Territory> Territories { get { return GetTable<Territory>(); } }\r
-\r
-       }\r
-\r
-       [Table(Name = "Categories")]\r
-       public partial class Category : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
+               \r
+               \r
+               public Northwind(string connectionString) : \r
+                               base(connectionString)\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               public Northwind(IDbConnection connection) : \r
+                               base(connection)\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               public Northwind(string connection, MappingSource mappingSource) : \r
+                               base(connection, mappingSource)\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               public Northwind(IDbConnection connection, MappingSource mappingSource) : \r
+                               base(connection, mappingSource)\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               public Table<Category> Categories\r
                {\r
-                       if (PropertyChanging != null)\r
+                       get\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               return this.GetTable<Category>();\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
+               \r
+               public Table<Customer> Customers\r
                {\r
-                       if (PropertyChanged != null)\r
+                       get\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               return this.GetTable<Customer>();\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+               \r
+               public Table<CustomerCustomerDemo> CustomerCustomerDemo\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<CustomerCustomerDemo>();\r
+                       }\r
+               }\r
+               \r
+               public Table<CustomerDemographic> CustomerDemographics\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<CustomerDemographic>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Employee> Employees\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Employee>();\r
+                       }\r
+               }\r
+               \r
+               public Table<EmployeeTerritory> EmployeeTerritories\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<EmployeeTerritory>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Order> Orders\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Order>();\r
+                       }\r
+               }\r
+               \r
+               public Table<OrderDetail> OrderDetails\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<OrderDetail>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Product> Products\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Product>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Region> Regions\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Region>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Shipper> Shippers\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Shipper>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Supplier> Suppliers\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Supplier>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Territory> Territories\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Territory>();\r
+                       }\r
+               }\r
+       }\r
+       \r
+       [Table(Name="Categories")]\r
+       public partial class Category : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Category>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private long _categoryID;\r
+               \r
+               private string _categoryName;\r
+               \r
+               private string _description;\r
+               \r
+               private byte[] _picture;\r
+               \r
+               private EntitySet<Product> _products;\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnCategoryIDChanged();\r
+               \r
                partial void OnCategoryIDChanging(long value);\r
+               \r
                partial void OnCategoryNameChanged();\r
+               \r
                partial void OnCategoryNameChanging(string value);\r
+               \r
                partial void OnDescriptionChanged();\r
+               \r
                partial void OnDescriptionChanging(string value);\r
+               \r
                partial void OnPictureChanged();\r
-               partial void OnPictureChanging(Byte[] value);\r
-\r
+               \r
+               partial void OnPictureChanging(byte[] value);\r
                #endregion\r
-\r
-               #region long CategoryID\r
-\r
-               private long _categoryID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_categoryID", Name = "CategoryID", DbType = "integer", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never)]\r
+               \r
+               \r
+               public Category()\r
+               {\r
+                       _products = new EntitySet<Product>(new Action<Product>(this.Products_Attach), new Action<Product>(this.Products_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_categoryID", Name="CategoryID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long CategoryID\r
                {\r
                        get\r
                        {\r
-                               return _categoryID;\r
+                               return this._categoryID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _categoryID)\r
+                               if ((_categoryID != value))\r
                                {\r
-                                       OnCategoryIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _categoryID = value;\r
-                                       SendPropertyChanged("CategoryID");\r
-                                       OnCategoryIDChanged();\r
+                                       this.OnCategoryIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._categoryID = value;\r
+                                       this.SendPropertyChanged("CategoryID");\r
+                                       this.OnCategoryIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string CategoryName\r
-\r
-               private string _categoryName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_categoryName", Name = "CategoryName", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_categoryName", Name="CategoryName", DbType="nvarchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CategoryName\r
                {\r
                        get\r
                        {\r
-                               return _categoryName;\r
+                               return this._categoryName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _categoryName)\r
+                               if (((_categoryName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCategoryNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _categoryName = value;\r
-                                       SendPropertyChanged("CategoryName");\r
-                                       OnCategoryNameChanged();\r
+                                       this.OnCategoryNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._categoryName = value;\r
+                                       this.SendPropertyChanged("CategoryName");\r
+                                       this.OnCategoryNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Description\r
-\r
-               private string _description;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_description", Name = "Description", DbType = "ntext", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_description", Name="Description", DbType="ntext", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Description\r
                {\r
                        get\r
                        {\r
-                               return _description;\r
+                               return this._description;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _description)\r
+                               if (((_description == value) \r
+                                                       == false))\r
                                {\r
-                                       OnDescriptionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _description = value;\r
-                                       SendPropertyChanged("Description");\r
-                                       OnDescriptionChanged();\r
+                                       this.OnDescriptionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._description = value;\r
+                                       this.SendPropertyChanged("Description");\r
+                                       this.OnDescriptionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region Byte[] Picture\r
-\r
-               private Byte[] _picture;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_picture", Name = "Picture", DbType = "image", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public Byte[] Picture\r
+               \r
+               [Column(Storage="_picture", Name="Picture", DbType="image", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public byte[] Picture\r
                {\r
                        get\r
                        {\r
-                               return _picture;\r
+                               return this._picture;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _picture)\r
+                               if (((_picture == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPictureChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _picture = value;\r
-                                       SendPropertyChanged("Picture");\r
-                                       OnPictureChanged();\r
+                                       this.OnPictureChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._picture = value;\r
+                                       this.SendPropertyChanged("Picture");\r
+                                       this.OnPictureChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<Product> _products;\r
-               [Association(Storage = "_products", OtherKey = "CategoryID", ThisKey = "CategoryID", Name = "FK_Products_1")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_products", OtherKey="CategoryID", ThisKey="CategoryID", Name="FK_Products_1")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Product> Products\r
                {\r
                        get\r
                        {\r
-                               return _products;\r
+                               return this._products;\r
                        }\r
                        set\r
                        {\r
-                               _products = value;\r
+                               this._products = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void Products_Attach(Product entity)\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
                {\r
-                       entity.Category = this;\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
                }\r
-\r
-               private void Products_Detach(Product entity)\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       entity.Category = null;\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Category()\r
+               \r
+               public override int GetHashCode()\r
                {\r
-                       _products = new EntitySet<Product>(Products_Attach, Products_Detach);\r
-                       OnCreated();\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_categoryID.GetHashCode() * 1));\r
+                       return hc;\r
                }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "Customers")]\r
-       public partial class Customer : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
+               \r
+               public override bool Equals(object value)\r
                {\r
-                       if (PropertyChanging != null)\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               return false;\r
                        }\r
+                       Category other = ((Category)(value));\r
+                       return this.Equals(other);\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
+               \r
+               public virtual bool Equals(Category value)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               return false;\r
                        }\r
+                       return System.Collections.Generic.EqualityComparer<long>.Default.Equals(this._categoryID, value._categoryID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void Products_Attach(Product entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Category = this;\r
+               }\r
+               \r
+               private void Products_Detach(Product entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Category = null;\r
                }\r
-\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="Customers")]\r
+       public partial class Customer : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Customer>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _address;\r
+               \r
+               private string _city;\r
+               \r
+               private string _companyName;\r
+               \r
+               private string _contactName;\r
+               \r
+               private string _contactTitle;\r
+               \r
+               private string _country;\r
+               \r
+               private string _customerID;\r
+               \r
+               private string _fax;\r
+               \r
+               private string _phone;\r
+               \r
+               private string _postalCode;\r
+               \r
+               private string _region;\r
+               \r
+               private EntitySet<Order> _orders;\r
+               \r
+               private EntitySet<CustomerCustomerDemo> _customerCustomerDemo;\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnAddressChanged();\r
+               \r
                partial void OnAddressChanging(string value);\r
+               \r
                partial void OnCityChanged();\r
+               \r
                partial void OnCityChanging(string value);\r
+               \r
                partial void OnCompanyNameChanged();\r
+               \r
                partial void OnCompanyNameChanging(string value);\r
+               \r
                partial void OnContactNameChanged();\r
+               \r
                partial void OnContactNameChanging(string value);\r
+               \r
                partial void OnContactTitleChanged();\r
+               \r
                partial void OnContactTitleChanging(string value);\r
+               \r
                partial void OnCountryChanged();\r
+               \r
                partial void OnCountryChanging(string value);\r
+               \r
                partial void OnCustomerIDChanged();\r
+               \r
                partial void OnCustomerIDChanging(string value);\r
+               \r
                partial void OnFaxChanged();\r
+               \r
                partial void OnFaxChanging(string value);\r
+               \r
                partial void OnPhoneChanged();\r
+               \r
                partial void OnPhoneChanging(string value);\r
+               \r
                partial void OnPostalCodeChanged();\r
+               \r
                partial void OnPostalCodeChanging(string value);\r
+               \r
                partial void OnRegionChanged();\r
+               \r
                partial void OnRegionChanging(string value);\r
-\r
                #endregion\r
-\r
-               #region string Address\r
-\r
-               private string _address;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_address", Name = "Address", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               \r
+               public Customer()\r
+               {\r
+                       _orders = new EntitySet<Order>(new Action<Order>(this.Orders_Attach), new Action<Order>(this.Orders_Detach));\r
+                       _customerCustomerDemo = new EntitySet<CustomerCustomerDemo>(new Action<CustomerCustomerDemo>(this.CustomerCustomerDemo_Attach), new Action<CustomerCustomerDemo>(this.CustomerCustomerDemo_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_address", Name="Address", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Address\r
                {\r
                        get\r
                        {\r
-                               return _address;\r
+                               return this._address;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _address)\r
+                               if (((_address == value) \r
+                                                       == false))\r
                                {\r
-                                       OnAddressChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _address = value;\r
-                                       SendPropertyChanged("Address");\r
-                                       OnAddressChanged();\r
+                                       this.OnAddressChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._address = value;\r
+                                       this.SendPropertyChanged("Address");\r
+                                       this.OnAddressChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string City\r
-\r
-               private string _city;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_city", Name = "City", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_city", Name="City", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string City\r
                {\r
                        get\r
                        {\r
-                               return _city;\r
+                               return this._city;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _city)\r
+                               if (((_city == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _city = value;\r
-                                       SendPropertyChanged("City");\r
-                                       OnCityChanged();\r
+                                       this.OnCityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._city = value;\r
+                                       this.SendPropertyChanged("City");\r
+                                       this.OnCityChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string CompanyName\r
-\r
-               private string _companyName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_companyName", Name = "CompanyName", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_companyName", Name="CompanyName", DbType="nvarchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CompanyName\r
                {\r
                        get\r
                        {\r
-                               return _companyName;\r
+                               return this._companyName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _companyName)\r
+                               if (((_companyName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCompanyNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _companyName = value;\r
-                                       SendPropertyChanged("CompanyName");\r
-                                       OnCompanyNameChanged();\r
+                                       this.OnCompanyNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._companyName = value;\r
+                                       this.SendPropertyChanged("CompanyName");\r
+                                       this.OnCompanyNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ContactName\r
-\r
-               private string _contactName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_contactName", Name = "ContactName", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_contactName", Name="ContactName", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ContactName\r
                {\r
                        get\r
                        {\r
-                               return _contactName;\r
+                               return this._contactName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _contactName)\r
+                               if (((_contactName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnContactNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _contactName = value;\r
-                                       SendPropertyChanged("ContactName");\r
-                                       OnContactNameChanged();\r
+                                       this.OnContactNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._contactName = value;\r
+                                       this.SendPropertyChanged("ContactName");\r
+                                       this.OnContactNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ContactTitle\r
-\r
-               private string _contactTitle;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_contactTitle", Name = "ContactTitle", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_contactTitle", Name="ContactTitle", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ContactTitle\r
                {\r
                        get\r
                        {\r
-                               return _contactTitle;\r
+                               return this._contactTitle;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _contactTitle)\r
+                               if (((_contactTitle == value) \r
+                                                       == false))\r
                                {\r
-                                       OnContactTitleChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _contactTitle = value;\r
-                                       SendPropertyChanged("ContactTitle");\r
-                                       OnContactTitleChanged();\r
+                                       this.OnContactTitleChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._contactTitle = value;\r
+                                       this.SendPropertyChanged("ContactTitle");\r
+                                       this.OnContactTitleChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Country\r
-\r
-               private string _country;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_country", Name = "Country", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_country", Name="Country", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Country\r
                {\r
                        get\r
                        {\r
-                               return _country;\r
+                               return this._country;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _country)\r
+                               if (((_country == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCountryChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _country = value;\r
-                                       SendPropertyChanged("Country");\r
-                                       OnCountryChanged();\r
+                                       this.OnCountryChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._country = value;\r
+                                       this.SendPropertyChanged("Country");\r
+                                       this.OnCountryChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string CustomerID\r
-\r
-               private string _customerID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerID", Name = "CustomerID", DbType = "nchar", IsPrimaryKey = true, AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_customerID", Name="CustomerID", DbType="nchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CustomerID\r
                {\r
                        get\r
                        {\r
-                               return _customerID;\r
+                               return this._customerID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerID)\r
+                               if (((_customerID == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCustomerIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerID = value;\r
-                                       SendPropertyChanged("CustomerID");\r
-                                       OnCustomerIDChanged();\r
+                                       this.OnCustomerIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerID = value;\r
+                                       this.SendPropertyChanged("CustomerID");\r
+                                       this.OnCustomerIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Fax\r
-\r
-               private string _fax;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_fax", Name = "Fax", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_fax", Name="Fax", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Fax\r
                {\r
                        get\r
                        {\r
-                               return _fax;\r
+                               return this._fax;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _fax)\r
+                               if (((_fax == value) \r
+                                                       == false))\r
                                {\r
-                                       OnFaxChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _fax = value;\r
-                                       SendPropertyChanged("Fax");\r
-                                       OnFaxChanged();\r
+                                       this.OnFaxChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._fax = value;\r
+                                       this.SendPropertyChanged("Fax");\r
+                                       this.OnFaxChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Phone\r
-\r
-               private string _phone;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_phone", Name = "Phone", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_phone", Name="Phone", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Phone\r
                {\r
                        get\r
                        {\r
-                               return _phone;\r
+                               return this._phone;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _phone)\r
+                               if (((_phone == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPhoneChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _phone = value;\r
-                                       SendPropertyChanged("Phone");\r
-                                       OnPhoneChanged();\r
+                                       this.OnPhoneChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._phone = value;\r
+                                       this.SendPropertyChanged("Phone");\r
+                                       this.OnPhoneChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string PostalCode\r
-\r
-               private string _postalCode;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_postalCode", Name = "PostalCode", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_postalCode", Name="PostalCode", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string PostalCode\r
                {\r
                        get\r
                        {\r
-                               return _postalCode;\r
+                               return this._postalCode;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _postalCode)\r
+                               if (((_postalCode == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPostalCodeChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _postalCode = value;\r
-                                       SendPropertyChanged("PostalCode");\r
-                                       OnPostalCodeChanged();\r
+                                       this.OnPostalCodeChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._postalCode = value;\r
+                                       this.SendPropertyChanged("PostalCode");\r
+                                       this.OnPostalCodeChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Region\r
-\r
-               private string _region;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_region", Name = "Region", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_region", Name="Region", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Region\r
                {\r
                        get\r
                        {\r
-                               return _region;\r
+                               return this._region;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _region)\r
+                               if (((_region == value) \r
+                                                       == false))\r
                                {\r
-                                       OnRegionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _region = value;\r
-                                       SendPropertyChanged("Region");\r
-                                       OnRegionChanged();\r
+                                       this.OnRegionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._region = value;\r
+                                       this.SendPropertyChanged("Region");\r
+                                       this.OnRegionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<Order> _orders;\r
-               [Association(Storage = "_orders", OtherKey = "CustomerID", ThisKey = "CustomerID", Name = "FK_Orders_2")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_orders", OtherKey="CustomerID", ThisKey="CustomerID", Name="FK_Orders_2")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Order> Orders\r
                {\r
                        get\r
                        {\r
-                               return _orders;\r
+                               return this._orders;\r
                        }\r
                        set\r
                        {\r
-                               _orders = value;\r
+                               this._orders = value;\r
                        }\r
                }\r
-\r
-               private EntitySet<CustomerCustomerDemo> _customerCustomerDemo;\r
-               [Association(Storage = "_customerCustomerDemo", OtherKey = "CustomerID", ThisKey = "CustomerID", Name = "FK_CustomerCustomerDemo_0")]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_customerCustomerDemo", OtherKey="CustomerID", ThisKey="CustomerID", Name="FK_CustomerCustomerDemo_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<CustomerCustomerDemo> CustomerCustomerDemo\r
                {\r
                        get\r
                        {\r
-                               return _customerCustomerDemo;\r
+                               return this._customerCustomerDemo;\r
                        }\r
                        set\r
                        {\r
-                               _customerCustomerDemo = value;\r
+                               this._customerCustomerDemo = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       if ((_customerID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_customerID.GetHashCode() * 1));\r
+                       }\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Customer other = ((Customer)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Customer value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._customerID, value._customerID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
                private void Orders_Attach(Order entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Customer = this;\r
                }\r
-\r
+               \r
                private void Orders_Detach(Order entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Customer = null;\r
                }\r
-\r
+               \r
                private void CustomerCustomerDemo_Attach(CustomerCustomerDemo entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Customer = this;\r
                }\r
-\r
+               \r
                private void CustomerCustomerDemo_Detach(CustomerCustomerDemo entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Customer = null;\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region ctor\r
-\r
-               public Customer()\r
-               {\r
-                       _orders = new EntitySet<Order>(Orders_Attach, Orders_Detach);\r
-                       _customerCustomerDemo = new EntitySet<CustomerCustomerDemo>(CustomerCustomerDemo_Attach, CustomerCustomerDemo_Detach);\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
        }\r
-\r
-       [Table(Name = "CustomerCustomerDemo")]\r
-       public partial class CustomerCustomerDemo : INotifyPropertyChanging, INotifyPropertyChanged\r
+       \r
+       [Table(Name="CustomerCustomerDemo")]\r
+       public partial class CustomerCustomerDemo : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<CustomerCustomerDemo>\r
        {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _customerID;\r
+               \r
+               private string _customerTypeID;\r
+               \r
+               private EntityRef<Customer> _customer = new EntityRef<Customer>();\r
+               \r
+               private EntityRef<CustomerDemographic> _customerDemographic = new EntityRef<CustomerDemographic>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnCustomerIDChanged();\r
+               \r
                partial void OnCustomerIDChanging(string value);\r
+               \r
                partial void OnCustomerTypeIDChanged();\r
+               \r
                partial void OnCustomerTypeIDChanging(string value);\r
-\r
                #endregion\r
-\r
-               #region string CustomerID\r
-\r
-               private string _customerID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerID", Name = "CustomerID", DbType = "nchar", IsPrimaryKey = true, AutoSync = AutoSync.Never)]\r
+               \r
+               \r
+               public CustomerCustomerDemo()\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_customerID", Name="CustomerID", DbType="nchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CustomerID\r
                {\r
                        get\r
                        {\r
-                               return _customerID;\r
+                               return this._customerID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerID)\r
+                               if (((_customerID == value) \r
+                                                       == false))\r
                                {\r
                                        if (_customer.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnCustomerIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerID = value;\r
-                                       SendPropertyChanged("CustomerID");\r
-                                       OnCustomerIDChanged();\r
+                                       this.OnCustomerIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerID = value;\r
+                                       this.SendPropertyChanged("CustomerID");\r
+                                       this.OnCustomerIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string CustomerTypeID\r
-\r
-               private string _customerTypeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerTypeID", Name = "CustomerTypeID", DbType = "nchar", IsPrimaryKey = true, AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_customerTypeID", Name="CustomerTypeID", DbType="nchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CustomerTypeID\r
                {\r
                        get\r
                        {\r
-                               return _customerTypeID;\r
+                               return this._customerTypeID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerTypeID)\r
+                               if (((_customerTypeID == value) \r
+                                                       == false))\r
                                {\r
                                        if (_customerDemographic.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnCustomerTypeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerTypeID = value;\r
-                                       SendPropertyChanged("CustomerTypeID");\r
-                                       OnCustomerTypeIDChanged();\r
+                                       this.OnCustomerTypeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerTypeID = value;\r
+                                       this.SendPropertyChanged("CustomerTypeID");\r
+                                       this.OnCustomerTypeIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Customer> _customer;\r
-               [Association(Storage = "_customer", OtherKey = "CustomerID", ThisKey = "CustomerID", Name = "FK_CustomerCustomerDemo_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_customer", OtherKey="CustomerID", ThisKey="CustomerID", Name="FK_CustomerCustomerDemo_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Customer Customer\r
                {\r
                        get\r
                        {\r
-                               return _customer.Entity;\r
+                               return this._customer.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customer.Entity)\r
+                               if (((this._customer.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_customer.Entity != null)\r
+                                       if ((this._customer.Entity != null))\r
                                        {\r
-                                               var previousCustomer = _customer.Entity;\r
-                                               _customer.Entity = null;\r
+                                               Customer previousCustomer = this._customer.Entity;\r
+                                               this._customer.Entity = null;\r
                                                previousCustomer.CustomerCustomerDemo.Remove(this);\r
                                        }\r
-                                       _customer.Entity = value;\r
-                                       if (value != null)\r
+                                       this._customer.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.CustomerCustomerDemo.Add(this);\r
                                                _customerID = value.CustomerID;\r
@@ -822,28 +931,28 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-               private EntityRef<CustomerDemographic> _customerDemographic;\r
-               [Association(Storage = "_customerDemographic", OtherKey = "CustomerTypeID", ThisKey = "CustomerTypeID", Name = "FK_CustomerCustomerDemo_1", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_customerDemographic", OtherKey="CustomerTypeID", ThisKey="CustomerTypeID", Name="FK_CustomerCustomerDemo_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public CustomerDemographic CustomerDemographic\r
                {\r
                        get\r
                        {\r
-                               return _customerDemographic.Entity;\r
+                               return this._customerDemographic.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerDemographic.Entity)\r
+                               if (((this._customerDemographic.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_customerDemographic.Entity != null)\r
+                                       if ((this._customerDemographic.Entity != null))\r
                                        {\r
-                                               var previousCustomerDemographic = _customerDemographic.Entity;\r
-                                               _customerDemographic.Entity = null;\r
+                                               CustomerDemographic previousCustomerDemographic = this._customerDemographic.Entity;\r
+                                               this._customerDemographic.Entity = null;\r
                                                previousCustomerDemographic.CustomerCustomerDemo.Remove(this);\r
                                        }\r
-                                       _customerDemographic.Entity = value;\r
-                                       if (value != null)\r
+                                       this._customerDemographic.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.CustomerCustomerDemo.Add(this);\r
                                                _customerTypeID = value.CustomerTypeID;\r
@@ -855,783 +964,831 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public CustomerCustomerDemo()\r
-               {\r
-                       _customer = new EntityRef<Customer>();\r
-                       _customerDemographic = new EntityRef<CustomerDemographic>();\r
-                       OnCreated();\r
-               }\r
-\r
                #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "CustomerDemographics")]\r
-       public partial class CustomerDemographic : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
                protected virtual void SendPropertyChanging()\r
                {\r
-                       if (PropertyChanging != null)\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               h(this, emptyChangingEventArgs);\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
+               \r
                protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       if ((_customerID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_customerID.GetHashCode() * 1));\r
+                       }\r
+                       if ((_customerTypeID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_customerTypeID.GetHashCode() * 65536));\r
+                       }\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       CustomerCustomerDemo other = ((CustomerCustomerDemo)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(CustomerCustomerDemo value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return (System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._customerID, value._customerID) && System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._customerTypeID, value._customerTypeID));\r
+               }\r
+       }\r
+       \r
+       [Table(Name="CustomerDemographics")]\r
+       public partial class CustomerDemographic : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<CustomerDemographic>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _customerDesc;\r
+               \r
+               private string _customerTypeID;\r
+               \r
+               private EntitySet<CustomerCustomerDemo> _customerCustomerDemo;\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnCustomerDescChanged();\r
+               \r
                partial void OnCustomerDescChanging(string value);\r
+               \r
                partial void OnCustomerTypeIDChanged();\r
+               \r
                partial void OnCustomerTypeIDChanging(string value);\r
-\r
                #endregion\r
-\r
-               #region string CustomerDesc\r
-\r
-               private string _customerDesc;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerDesc", Name = "CustomerDesc", DbType = "ntext", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               \r
+               public CustomerDemographic()\r
+               {\r
+                       _customerCustomerDemo = new EntitySet<CustomerCustomerDemo>(new Action<CustomerCustomerDemo>(this.CustomerCustomerDemo_Attach), new Action<CustomerCustomerDemo>(this.CustomerCustomerDemo_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_customerDesc", Name="CustomerDesc", DbType="ntext", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string CustomerDesc\r
                {\r
                        get\r
                        {\r
-                               return _customerDesc;\r
+                               return this._customerDesc;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerDesc)\r
+                               if (((_customerDesc == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCustomerDescChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerDesc = value;\r
-                                       SendPropertyChanged("CustomerDesc");\r
-                                       OnCustomerDescChanged();\r
+                                       this.OnCustomerDescChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerDesc = value;\r
+                                       this.SendPropertyChanged("CustomerDesc");\r
+                                       this.OnCustomerDescChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string CustomerTypeID\r
-\r
-               private string _customerTypeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerTypeID", Name = "CustomerTypeID", DbType = "nchar", IsPrimaryKey = true, AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_customerTypeID", Name="CustomerTypeID", DbType="nchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CustomerTypeID\r
                {\r
                        get\r
                        {\r
-                               return _customerTypeID;\r
+                               return this._customerTypeID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerTypeID)\r
+                               if (((_customerTypeID == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCustomerTypeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerTypeID = value;\r
-                                       SendPropertyChanged("CustomerTypeID");\r
-                                       OnCustomerTypeIDChanged();\r
+                                       this.OnCustomerTypeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerTypeID = value;\r
+                                       this.SendPropertyChanged("CustomerTypeID");\r
+                                       this.OnCustomerTypeIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<CustomerCustomerDemo> _customerCustomerDemo;\r
-               [Association(Storage = "_customerCustomerDemo", OtherKey = "CustomerTypeID", ThisKey = "CustomerTypeID", Name = "FK_CustomerCustomerDemo_1")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_customerCustomerDemo", OtherKey="CustomerTypeID", ThisKey="CustomerTypeID", Name="FK_CustomerCustomerDemo_1")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<CustomerCustomerDemo> CustomerCustomerDemo\r
                {\r
                        get\r
                        {\r
-                               return _customerCustomerDemo;\r
+                               return this._customerCustomerDemo;\r
                        }\r
                        set\r
                        {\r
-                               _customerCustomerDemo = value;\r
+                               this._customerCustomerDemo = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void CustomerCustomerDemo_Attach(CustomerCustomerDemo entity)\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
                {\r
-                       entity.CustomerDemographic = this;\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
                }\r
-\r
-               private void CustomerCustomerDemo_Detach(CustomerCustomerDemo entity)\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       entity.CustomerDemographic = null;\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public CustomerDemographic()\r
+               \r
+               public override int GetHashCode()\r
                {\r
-                       _customerCustomerDemo = new EntitySet<CustomerCustomerDemo>(CustomerCustomerDemo_Attach, CustomerCustomerDemo_Detach);\r
-                       OnCreated();\r
+                       int hc = 0;\r
+                       if ((_customerTypeID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_customerTypeID.GetHashCode() * 1));\r
+                       }\r
+                       return hc;\r
                }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "Employees")]\r
-       public partial class Employee : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
+               \r
+               public override bool Equals(object value)\r
                {\r
-                       if (PropertyChanging != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               return false;\r
                        }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       CustomerDemographic other = ((CustomerDemographic)(value));\r
+                       return this.Equals(other);\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
+               \r
+               public virtual bool Equals(CustomerDemographic value)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               return false;\r
                        }\r
+                       return System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._customerTypeID, value._customerTypeID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void CustomerCustomerDemo_Attach(CustomerCustomerDemo entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.CustomerDemographic = this;\r
+               }\r
+               \r
+               private void CustomerCustomerDemo_Detach(CustomerCustomerDemo entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.CustomerDemographic = null;\r
                }\r
-\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="Employees")]\r
+       public partial class Employee : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Employee>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _address;\r
+               \r
+               private System.Nullable<System.DateTime> _birthDate;\r
+               \r
+               private string _city;\r
+               \r
+               private string _country;\r
+               \r
+               private long _employeeID;\r
+               \r
+               private string _extension;\r
+               \r
+               private string _firstName;\r
+               \r
+               private System.Nullable<System.DateTime> _hireDate;\r
+               \r
+               private string _homePhone;\r
+               \r
+               private string _lastName;\r
+               \r
+               private string _notes;\r
+               \r
+               private byte[] _photo;\r
+               \r
+               private string _photoPath;\r
+               \r
+               private string _postalCode;\r
+               \r
+               private string _region;\r
+               \r
+               private System.Nullable<long> _reportsTo;\r
+               \r
+               private string _title;\r
+               \r
+               private string _titleOfCourtesy;\r
+               \r
+               private EntitySet<Employee> _employees;\r
+               \r
+               private EntitySet<Order> _orders;\r
+               \r
+               private EntitySet<EmployeeTerritory> _employeeTerritories;\r
+               \r
+               private EntityRef<Employee> _reportsToEmployee = new EntityRef<Employee>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnAddressChanged();\r
+               \r
                partial void OnAddressChanging(string value);\r
+               \r
                partial void OnBirthDateChanged();\r
-               partial void OnBirthDateChanging(DateTime? value);\r
+               \r
+               partial void OnBirthDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
                partial void OnCityChanged();\r
+               \r
                partial void OnCityChanging(string value);\r
+               \r
                partial void OnCountryChanged();\r
+               \r
                partial void OnCountryChanging(string value);\r
+               \r
                partial void OnEmployeeIDChanged();\r
+               \r
                partial void OnEmployeeIDChanging(long value);\r
+               \r
                partial void OnExtensionChanged();\r
+               \r
                partial void OnExtensionChanging(string value);\r
+               \r
                partial void OnFirstNameChanged();\r
+               \r
                partial void OnFirstNameChanging(string value);\r
+               \r
                partial void OnHireDateChanged();\r
-               partial void OnHireDateChanging(DateTime? value);\r
+               \r
+               partial void OnHireDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
                partial void OnHomePhoneChanged();\r
+               \r
                partial void OnHomePhoneChanging(string value);\r
+               \r
                partial void OnLastNameChanged();\r
+               \r
                partial void OnLastNameChanging(string value);\r
+               \r
                partial void OnNotesChanged();\r
+               \r
                partial void OnNotesChanging(string value);\r
+               \r
                partial void OnPhotoChanged();\r
-               partial void OnPhotoChanging(Byte[] value);\r
+               \r
+               partial void OnPhotoChanging(byte[] value);\r
+               \r
                partial void OnPhotoPathChanged();\r
+               \r
                partial void OnPhotoPathChanging(string value);\r
+               \r
                partial void OnPostalCodeChanged();\r
+               \r
                partial void OnPostalCodeChanging(string value);\r
+               \r
                partial void OnRegionChanged();\r
+               \r
                partial void OnRegionChanging(string value);\r
+               \r
                partial void OnReportsToChanged();\r
-               partial void OnReportsToChanging(long? value);\r
+               \r
+               partial void OnReportsToChanging(System.Nullable<long> value);\r
+               \r
                partial void OnTitleChanged();\r
+               \r
                partial void OnTitleChanging(string value);\r
+               \r
                partial void OnTitleOfCourtesyChanged();\r
+               \r
                partial void OnTitleOfCourtesyChanging(string value);\r
-\r
                #endregion\r
-\r
-               #region string Address\r
-\r
-               private string _address;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_address", Name = "Address", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               \r
+               public Employee()\r
+               {\r
+                       _employees = new EntitySet<Employee>(new Action<Employee>(this.Employees_Attach), new Action<Employee>(this.Employees_Detach));\r
+                       _orders = new EntitySet<Order>(new Action<Order>(this.Orders_Attach), new Action<Order>(this.Orders_Detach));\r
+                       _employeeTerritories = new EntitySet<EmployeeTerritory>(new Action<EmployeeTerritory>(this.EmployeeTerritories_Attach), new Action<EmployeeTerritory>(this.EmployeeTerritories_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_address", Name="Address", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Address\r
                {\r
                        get\r
                        {\r
-                               return _address;\r
+                               return this._address;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _address)\r
+                               if (((_address == value) \r
+                                                       == false))\r
                                {\r
-                                       OnAddressChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _address = value;\r
-                                       SendPropertyChanged("Address");\r
-                                       OnAddressChanged();\r
+                                       this.OnAddressChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._address = value;\r
+                                       this.SendPropertyChanged("Address");\r
+                                       this.OnAddressChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? BirthDate\r
-\r
-               private DateTime? _birthDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_birthDate", Name = "BirthDate", DbType = "datetime", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public DateTime? BirthDate\r
+               \r
+               [Column(Storage="_birthDate", Name="BirthDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> BirthDate\r
                {\r
                        get\r
                        {\r
-                               return _birthDate;\r
+                               return this._birthDate;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _birthDate)\r
+                               if ((_birthDate != value))\r
                                {\r
-                                       OnBirthDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _birthDate = value;\r
-                                       SendPropertyChanged("BirthDate");\r
-                                       OnBirthDateChanged();\r
+                                       this.OnBirthDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._birthDate = value;\r
+                                       this.SendPropertyChanged("BirthDate");\r
+                                       this.OnBirthDateChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string City\r
-\r
-               private string _city;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_city", Name = "City", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_city", Name="City", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string City\r
                {\r
                        get\r
                        {\r
-                               return _city;\r
+                               return this._city;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _city)\r
+                               if (((_city == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _city = value;\r
-                                       SendPropertyChanged("City");\r
-                                       OnCityChanged();\r
+                                       this.OnCityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._city = value;\r
+                                       this.SendPropertyChanged("City");\r
+                                       this.OnCityChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Country\r
-\r
-               private string _country;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_country", Name = "Country", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_country", Name="Country", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Country\r
                {\r
                        get\r
                        {\r
-                               return _country;\r
+                               return this._country;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _country)\r
+                               if (((_country == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCountryChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _country = value;\r
-                                       SendPropertyChanged("Country");\r
-                                       OnCountryChanged();\r
+                                       this.OnCountryChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._country = value;\r
+                                       this.SendPropertyChanged("Country");\r
+                                       this.OnCountryChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long EmployeeID\r
-\r
-               private long _employeeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_employeeID", Name = "EmployeeID", DbType = "integer", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_employeeID", Name="EmployeeID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long EmployeeID\r
                {\r
                        get\r
                        {\r
-                               return _employeeID;\r
+                               return this._employeeID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _employeeID)\r
+                               if ((_employeeID != value))\r
                                {\r
-                                       OnEmployeeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _employeeID = value;\r
-                                       SendPropertyChanged("EmployeeID");\r
-                                       OnEmployeeIDChanged();\r
+                                       this.OnEmployeeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._employeeID = value;\r
+                                       this.SendPropertyChanged("EmployeeID");\r
+                                       this.OnEmployeeIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Extension\r
-\r
-               private string _extension;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_extension", Name = "Extension", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_extension", Name="Extension", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Extension\r
                {\r
                        get\r
                        {\r
-                               return _extension;\r
+                               return this._extension;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _extension)\r
+                               if (((_extension == value) \r
+                                                       == false))\r
                                {\r
-                                       OnExtensionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _extension = value;\r
-                                       SendPropertyChanged("Extension");\r
-                                       OnExtensionChanged();\r
+                                       this.OnExtensionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._extension = value;\r
+                                       this.SendPropertyChanged("Extension");\r
+                                       this.OnExtensionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string FirstName\r
-\r
-               private string _firstName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_firstName", Name = "FirstName", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_firstName", Name="FirstName", DbType="nvarchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string FirstName\r
                {\r
                        get\r
                        {\r
-                               return _firstName;\r
+                               return this._firstName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _firstName)\r
+                               if (((_firstName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnFirstNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _firstName = value;\r
-                                       SendPropertyChanged("FirstName");\r
-                                       OnFirstNameChanged();\r
+                                       this.OnFirstNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._firstName = value;\r
+                                       this.SendPropertyChanged("FirstName");\r
+                                       this.OnFirstNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? HireDate\r
-\r
-               private DateTime? _hireDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_hireDate", Name = "HireDate", DbType = "datetime", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public DateTime? HireDate\r
+               \r
+               [Column(Storage="_hireDate", Name="HireDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> HireDate\r
                {\r
                        get\r
                        {\r
-                               return _hireDate;\r
+                               return this._hireDate;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _hireDate)\r
+                               if ((_hireDate != value))\r
                                {\r
-                                       OnHireDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _hireDate = value;\r
-                                       SendPropertyChanged("HireDate");\r
-                                       OnHireDateChanged();\r
+                                       this.OnHireDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._hireDate = value;\r
+                                       this.SendPropertyChanged("HireDate");\r
+                                       this.OnHireDateChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string HomePhone\r
-\r
-               private string _homePhone;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_homePhone", Name = "HomePhone", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_homePhone", Name="HomePhone", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string HomePhone\r
                {\r
                        get\r
                        {\r
-                               return _homePhone;\r
+                               return this._homePhone;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _homePhone)\r
+                               if (((_homePhone == value) \r
+                                                       == false))\r
                                {\r
-                                       OnHomePhoneChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _homePhone = value;\r
-                                       SendPropertyChanged("HomePhone");\r
-                                       OnHomePhoneChanged();\r
+                                       this.OnHomePhoneChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._homePhone = value;\r
+                                       this.SendPropertyChanged("HomePhone");\r
+                                       this.OnHomePhoneChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string LastName\r
-\r
-               private string _lastName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_lastName", Name = "LastName", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_lastName", Name="LastName", DbType="nvarchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string LastName\r
                {\r
                        get\r
                        {\r
-                               return _lastName;\r
+                               return this._lastName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _lastName)\r
+                               if (((_lastName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnLastNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _lastName = value;\r
-                                       SendPropertyChanged("LastName");\r
-                                       OnLastNameChanged();\r
+                                       this.OnLastNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._lastName = value;\r
+                                       this.SendPropertyChanged("LastName");\r
+                                       this.OnLastNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Notes\r
-\r
-               private string _notes;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_notes", Name = "Notes", DbType = "ntext", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_notes", Name="Notes", DbType="ntext", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Notes\r
                {\r
                        get\r
                        {\r
-                               return _notes;\r
+                               return this._notes;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _notes)\r
+                               if (((_notes == value) \r
+                                                       == false))\r
                                {\r
-                                       OnNotesChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _notes = value;\r
-                                       SendPropertyChanged("Notes");\r
-                                       OnNotesChanged();\r
+                                       this.OnNotesChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._notes = value;\r
+                                       this.SendPropertyChanged("Notes");\r
+                                       this.OnNotesChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region Byte[] Photo\r
-\r
-               private Byte[] _photo;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_photo", Name = "Photo", DbType = "image", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public Byte[] Photo\r
+               \r
+               [Column(Storage="_photo", Name="Photo", DbType="image", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public byte[] Photo\r
                {\r
                        get\r
                        {\r
-                               return _photo;\r
+                               return this._photo;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _photo)\r
+                               if (((_photo == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPhotoChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _photo = value;\r
-                                       SendPropertyChanged("Photo");\r
-                                       OnPhotoChanged();\r
+                                       this.OnPhotoChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._photo = value;\r
+                                       this.SendPropertyChanged("Photo");\r
+                                       this.OnPhotoChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string PhotoPath\r
-\r
-               private string _photoPath;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_photoPath", Name = "PhotoPath", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_photoPath", Name="PhotoPath", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string PhotoPath\r
                {\r
                        get\r
                        {\r
-                               return _photoPath;\r
+                               return this._photoPath;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _photoPath)\r
+                               if (((_photoPath == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPhotoPathChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _photoPath = value;\r
-                                       SendPropertyChanged("PhotoPath");\r
-                                       OnPhotoPathChanged();\r
+                                       this.OnPhotoPathChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._photoPath = value;\r
+                                       this.SendPropertyChanged("PhotoPath");\r
+                                       this.OnPhotoPathChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string PostalCode\r
-\r
-               private string _postalCode;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_postalCode", Name = "PostalCode", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_postalCode", Name="PostalCode", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string PostalCode\r
                {\r
                        get\r
                        {\r
-                               return _postalCode;\r
+                               return this._postalCode;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _postalCode)\r
+                               if (((_postalCode == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPostalCodeChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _postalCode = value;\r
-                                       SendPropertyChanged("PostalCode");\r
-                                       OnPostalCodeChanged();\r
+                                       this.OnPostalCodeChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._postalCode = value;\r
+                                       this.SendPropertyChanged("PostalCode");\r
+                                       this.OnPostalCodeChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Region\r
-\r
-               private string _region;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_region", Name = "Region", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_region", Name="Region", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Region\r
                {\r
                        get\r
                        {\r
-                               return _region;\r
+                               return this._region;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _region)\r
+                               if (((_region == value) \r
+                                                       == false))\r
                                {\r
-                                       OnRegionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _region = value;\r
-                                       SendPropertyChanged("Region");\r
-                                       OnRegionChanged();\r
+                                       this.OnRegionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._region = value;\r
+                                       this.SendPropertyChanged("Region");\r
+                                       this.OnRegionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long? ReportsTo\r
-\r
-               private long? _reportsTo;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_reportsTo", Name = "ReportsTo", DbType = "integer", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public long? ReportsTo\r
+               \r
+               [Column(Storage="_reportsTo", Name="ReportsTo", DbType="integer", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<long> ReportsTo\r
                {\r
                        get\r
                        {\r
-                               return _reportsTo;\r
+                               return this._reportsTo;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _reportsTo)\r
+                               if ((_reportsTo != value))\r
                                {\r
                                        if (_reportsToEmployee.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnReportsToChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _reportsTo = value;\r
-                                       SendPropertyChanged("ReportsTo");\r
-                                       OnReportsToChanged();\r
+                                       this.OnReportsToChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._reportsTo = value;\r
+                                       this.SendPropertyChanged("ReportsTo");\r
+                                       this.OnReportsToChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Title\r
-\r
-               private string _title;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_title", Name = "Title", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_title", Name="Title", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Title\r
                {\r
                        get\r
                        {\r
-                               return _title;\r
+                               return this._title;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _title)\r
+                               if (((_title == value) \r
+                                                       == false))\r
                                {\r
-                                       OnTitleChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _title = value;\r
-                                       SendPropertyChanged("Title");\r
-                                       OnTitleChanged();\r
+                                       this.OnTitleChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._title = value;\r
+                                       this.SendPropertyChanged("Title");\r
+                                       this.OnTitleChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string TitleOfCourtesy\r
-\r
-               private string _titleOfCourtesy;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_titleOfCourtesy", Name = "TitleOfCourtesy", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_titleOfCourtesy", Name="TitleOfCourtesy", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string TitleOfCourtesy\r
                {\r
                        get\r
                        {\r
-                               return _titleOfCourtesy;\r
+                               return this._titleOfCourtesy;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _titleOfCourtesy)\r
+                               if (((_titleOfCourtesy == value) \r
+                                                       == false))\r
                                {\r
-                                       OnTitleOfCourtesyChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _titleOfCourtesy = value;\r
-                                       SendPropertyChanged("TitleOfCourtesy");\r
-                                       OnTitleOfCourtesyChanged();\r
+                                       this.OnTitleOfCourtesyChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._titleOfCourtesy = value;\r
+                                       this.SendPropertyChanged("TitleOfCourtesy");\r
+                                       this.OnTitleOfCourtesyChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<Employee> _employees;\r
-               [Association(Storage = "_employees", OtherKey = "ReportsTo", ThisKey = "EmployeeID", Name = "FK_Employees_0")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_employees", OtherKey="ReportsTo", ThisKey="EmployeeID", Name="FK_Employees_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Employee> Employees\r
                {\r
                        get\r
                        {\r
-                               return _employees;\r
+                               return this._employees;\r
                        }\r
                        set\r
                        {\r
-                               _employees = value;\r
+                               this._employees = value;\r
                        }\r
                }\r
-\r
-               private EntitySet<Order> _orders;\r
-               [Association(Storage = "_orders", OtherKey = "EmployeeID", ThisKey = "EmployeeID", Name = "FK_Orders_1")]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_orders", OtherKey="EmployeeID", ThisKey="EmployeeID", Name="FK_Orders_1")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Order> Orders\r
                {\r
                        get\r
                        {\r
-                               return _orders;\r
+                               return this._orders;\r
                        }\r
                        set\r
                        {\r
-                               _orders = value;\r
+                               this._orders = value;\r
                        }\r
                }\r
-\r
-               private EntitySet<EmployeeTerritory> _employeeTerritories;\r
-               [Association(Storage = "_employeeTerritories", OtherKey = "EmployeeID", ThisKey = "EmployeeID", Name = "FK_EmployeeTerritories_1")]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_employeeTerritories", OtherKey="EmployeeID", ThisKey="EmployeeID", Name="FK_EmployeeTerritories_1")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<EmployeeTerritory> EmployeeTerritories\r
                {\r
                        get\r
                        {\r
-                               return _employeeTerritories;\r
+                               return this._employeeTerritories;\r
                        }\r
                        set\r
                        {\r
-                               _employeeTerritories = value;\r
+                               this._employeeTerritories = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Employee> _reportsToEmployee;\r
-               [Association(Storage = "_reportsToEmployee", OtherKey = "EmployeeID", ThisKey = "ReportsTo", Name = "FK_Employees_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_reportsToEmployee", OtherKey="EmployeeID", ThisKey="ReportsTo", Name="FK_Employees_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Employee ReportsToEmployee\r
                {\r
                        get\r
                        {\r
-                               return _reportsToEmployee.Entity;\r
+                               return this._reportsToEmployee.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _reportsToEmployee.Entity)\r
+                               if (((this._reportsToEmployee.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_reportsToEmployee.Entity != null)\r
+                                       if ((this._reportsToEmployee.Entity != null))\r
                                        {\r
-                                               var previousEmployee = _reportsToEmployee.Entity;\r
-                                               _reportsToEmployee.Entity = null;\r
+                                               Employee previousEmployee = this._reportsToEmployee.Entity;\r
+                                               this._reportsToEmployee.Entity = null;\r
                                                previousEmployee.Employees.Remove(this);\r
                                        }\r
-                                       _reportsToEmployee.Entity = value;\r
-                                       if (value != null)\r
+                                       this._reportsToEmployee.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Employees.Add(this);\r
                                                _reportsTo = value.EmployeeID;\r
@@ -1643,185 +1800,206 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_employeeID.GetHashCode() * 1));\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Employee other = ((Employee)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Employee value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<long>.Default.Equals(this._employeeID, value._employeeID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
                private void Employees_Attach(Employee entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.ReportsToEmployee = this;\r
                }\r
-\r
+               \r
                private void Employees_Detach(Employee entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.ReportsToEmployee = null;\r
                }\r
-\r
+               \r
                private void Orders_Attach(Order entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Employee = this;\r
                }\r
-\r
+               \r
                private void Orders_Detach(Order entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Employee = null;\r
                }\r
-\r
+               \r
                private void EmployeeTerritories_Attach(EmployeeTerritory entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Employee = this;\r
                }\r
-\r
+               \r
                private void EmployeeTerritories_Detach(EmployeeTerritory entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Employee = null;\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region ctor\r
-\r
-               public Employee()\r
-               {\r
-                       _employees = new EntitySet<Employee>(Employees_Attach, Employees_Detach);\r
-                       _orders = new EntitySet<Order>(Orders_Attach, Orders_Detach);\r
-                       _employeeTerritories = new EntitySet<EmployeeTerritory>(EmployeeTerritories_Attach, EmployeeTerritories_Detach);\r
-                       _reportsToEmployee = new EntityRef<Employee>();\r
-                       OnCreated();\r
-               }\r
-\r
-               #endregion\r
-\r
        }\r
-\r
-       [Table(Name = "EmployeeTerritories")]\r
-       public partial class EmployeeTerritory : INotifyPropertyChanging, INotifyPropertyChanged\r
+       \r
+       [Table(Name="EmployeeTerritories")]\r
+       public partial class EmployeeTerritory : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<EmployeeTerritory>\r
        {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
-               {\r
-                       if (PropertyChanging != null)\r
-                       {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
-               {\r
-                       if (PropertyChanged != null)\r
-                       {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
-                       }\r
-               }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private long _employeeID;\r
+               \r
+               private string _territoryID;\r
+               \r
+               private EntityRef<Territory> _territory = new EntityRef<Territory>();\r
+               \r
+               private EntityRef<Employee> _employee = new EntityRef<Employee>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnEmployeeIDChanged();\r
+               \r
                partial void OnEmployeeIDChanging(long value);\r
+               \r
                partial void OnTerritoryIDChanged();\r
+               \r
                partial void OnTerritoryIDChanging(string value);\r
-\r
                #endregion\r
-\r
-               #region long EmployeeID\r
-\r
-               private long _employeeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_employeeID", Name = "EmployeeID", DbType = "integer", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never)]\r
+               \r
+               \r
+               public EmployeeTerritory()\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_employeeID", Name="EmployeeID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long EmployeeID\r
                {\r
                        get\r
                        {\r
-                               return _employeeID;\r
+                               return this._employeeID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _employeeID)\r
+                               if ((_employeeID != value))\r
                                {\r
                                        if (_employee.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnEmployeeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _employeeID = value;\r
-                                       SendPropertyChanged("EmployeeID");\r
-                                       OnEmployeeIDChanged();\r
+                                       this.OnEmployeeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._employeeID = value;\r
+                                       this.SendPropertyChanged("EmployeeID");\r
+                                       this.OnEmployeeIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string TerritoryID\r
-\r
-               private string _territoryID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_territoryID", Name = "TerritoryID", DbType = "nvarchar", IsPrimaryKey = true, AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_territoryID", Name="TerritoryID", DbType="nvarchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string TerritoryID\r
                {\r
                        get\r
                        {\r
-                               return _territoryID;\r
+                               return this._territoryID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _territoryID)\r
+                               if (((_territoryID == value) \r
+                                                       == false))\r
                                {\r
                                        if (_territory.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnTerritoryIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _territoryID = value;\r
-                                       SendPropertyChanged("TerritoryID");\r
-                                       OnTerritoryIDChanged();\r
+                                       this.OnTerritoryIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._territoryID = value;\r
+                                       this.SendPropertyChanged("TerritoryID");\r
+                                       this.OnTerritoryIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Territory> _territory;\r
-               [Association(Storage = "_territory", OtherKey = "TerritoryID", ThisKey = "TerritoryID", Name = "FK_EmployeeTerritories_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_territory", OtherKey="TerritoryID", ThisKey="TerritoryID", Name="FK_EmployeeTerritories_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Territory Territory\r
                {\r
                        get\r
                        {\r
-                               return _territory.Entity;\r
+                               return this._territory.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _territory.Entity)\r
+                               if (((this._territory.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_territory.Entity != null)\r
+                                       if ((this._territory.Entity != null))\r
                                        {\r
-                                               var previousTerritory = _territory.Entity;\r
-                                               _territory.Entity = null;\r
+                                               Territory previousTerritory = this._territory.Entity;\r
+                                               this._territory.Entity = null;\r
                                                previousTerritory.EmployeeTerritories.Remove(this);\r
                                        }\r
-                                       _territory.Entity = value;\r
-                                       if (value != null)\r
+                                       this._territory.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.EmployeeTerritories.Add(this);\r
                                                _territoryID = value.TerritoryID;\r
@@ -1833,28 +2011,28 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-               private EntityRef<Employee> _employee;\r
-               [Association(Storage = "_employee", OtherKey = "EmployeeID", ThisKey = "EmployeeID", Name = "FK_EmployeeTerritories_1", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_employee", OtherKey="EmployeeID", ThisKey="EmployeeID", Name="FK_EmployeeTerritories_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Employee Employee\r
                {\r
                        get\r
                        {\r
-                               return _employee.Entity;\r
+                               return this._employee.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _employee.Entity)\r
+                               if (((this._employee.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_employee.Entity != null)\r
+                                       if ((this._employee.Entity != null))\r
                                        {\r
-                                               var previousEmployee = _employee.Entity;\r
-                                               _employee.Entity = null;\r
+                                               Employee previousEmployee = this._employee.Entity;\r
+                                               this._employee.Entity = null;\r
                                                previousEmployee.EmployeeTerritories.Remove(this);\r
                                        }\r
-                                       _employee.Entity = value;\r
-                                       if (value != null)\r
+                                       this._employee.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.EmployeeTerritories.Add(this);\r
                                                _employeeID = value.EmployeeID;\r
@@ -1866,508 +2044,528 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public EmployeeTerritory()\r
-               {\r
-                       _territory = new EntityRef<Territory>();\r
-                       _employee = new EntityRef<Employee>();\r
-                       OnCreated();\r
-               }\r
-\r
                #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "Orders")]\r
-       public partial class Order : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
                protected virtual void SendPropertyChanging()\r
                {\r
-                       if (PropertyChanging != null)\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               h(this, emptyChangingEventArgs);\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
+               \r
                protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_employeeID.GetHashCode() * 1));\r
+                       if ((_territoryID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_territoryID.GetHashCode() * 65536));\r
+                       }\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       EmployeeTerritory other = ((EmployeeTerritory)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(EmployeeTerritory value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return (System.Collections.Generic.EqualityComparer<long>.Default.Equals(this._employeeID, value._employeeID) && System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._territoryID, value._territoryID));\r
+               }\r
+       }\r
+       \r
+       [Table(Name="Orders")]\r
+       public partial class Order : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Order>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _customerID;\r
+               \r
+               private System.Nullable<long> _employeeID;\r
+               \r
+               private System.Nullable<decimal> _freight;\r
+               \r
+               private System.Nullable<System.DateTime> _orderDate;\r
+               \r
+               private long _orderID;\r
+               \r
+               private System.Nullable<System.DateTime> _requiredDate;\r
+               \r
+               private string _shipAddress;\r
+               \r
+               private string _shipCity;\r
+               \r
+               private string _shipCountry;\r
+               \r
+               private string _shipName;\r
+               \r
+               private System.Nullable<System.DateTime> _shippedDate;\r
+               \r
+               private string _shipPostalCode;\r
+               \r
+               private string _shipRegion;\r
+               \r
+               private System.Nullable<long> _shipVia;\r
+               \r
+               private EntitySet<OrderDetail> _orderDetails;\r
+               \r
+               private EntityRef<Shipper> _shipper = new EntityRef<Shipper>();\r
+               \r
+               private EntityRef<Employee> _employee = new EntityRef<Employee>();\r
+               \r
+               private EntityRef<Customer> _customer = new EntityRef<Customer>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnCustomerIDChanged();\r
+               \r
                partial void OnCustomerIDChanging(string value);\r
+               \r
                partial void OnEmployeeIDChanged();\r
-               partial void OnEmployeeIDChanging(long? value);\r
+               \r
+               partial void OnEmployeeIDChanging(System.Nullable<long> value);\r
+               \r
                partial void OnFreightChanged();\r
-               partial void OnFreightChanging(decimal? value);\r
+               \r
+               partial void OnFreightChanging(System.Nullable<decimal> value);\r
+               \r
                partial void OnOrderDateChanged();\r
-               partial void OnOrderDateChanging(DateTime? value);\r
+               \r
+               partial void OnOrderDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
                partial void OnOrderIDChanged();\r
+               \r
                partial void OnOrderIDChanging(long value);\r
+               \r
                partial void OnRequiredDateChanged();\r
-               partial void OnRequiredDateChanging(DateTime? value);\r
+               \r
+               partial void OnRequiredDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
                partial void OnShipAddressChanged();\r
+               \r
                partial void OnShipAddressChanging(string value);\r
+               \r
                partial void OnShipCityChanged();\r
+               \r
                partial void OnShipCityChanging(string value);\r
+               \r
                partial void OnShipCountryChanged();\r
+               \r
                partial void OnShipCountryChanging(string value);\r
+               \r
                partial void OnShipNameChanged();\r
+               \r
                partial void OnShipNameChanging(string value);\r
+               \r
                partial void OnShippedDateChanged();\r
-               partial void OnShippedDateChanging(DateTime? value);\r
+               \r
+               partial void OnShippedDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
                partial void OnShipPostalCodeChanged();\r
+               \r
                partial void OnShipPostalCodeChanging(string value);\r
+               \r
                partial void OnShipRegionChanged();\r
+               \r
                partial void OnShipRegionChanging(string value);\r
+               \r
                partial void OnShipViaChanged();\r
-               partial void OnShipViaChanging(long? value);\r
-\r
+               \r
+               partial void OnShipViaChanging(System.Nullable<long> value);\r
                #endregion\r
-\r
-               #region string CustomerID\r
-\r
-               private string _customerID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_customerID", Name = "CustomerID", DbType = "nchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               \r
+               public Order()\r
+               {\r
+                       _orderDetails = new EntitySet<OrderDetail>(new Action<OrderDetail>(this.OrderDetails_Attach), new Action<OrderDetail>(this.OrderDetails_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_customerID", Name="CustomerID", DbType="nchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string CustomerID\r
                {\r
                        get\r
                        {\r
-                               return _customerID;\r
+                               return this._customerID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customerID)\r
+                               if (((_customerID == value) \r
+                                                       == false))\r
                                {\r
                                        if (_customer.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnCustomerIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _customerID = value;\r
-                                       SendPropertyChanged("CustomerID");\r
-                                       OnCustomerIDChanged();\r
+                                       this.OnCustomerIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerID = value;\r
+                                       this.SendPropertyChanged("CustomerID");\r
+                                       this.OnCustomerIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long? EmployeeID\r
-\r
-               private long? _employeeID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_employeeID", Name = "EmployeeID", DbType = "integer", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public long? EmployeeID\r
+               \r
+               [Column(Storage="_employeeID", Name="EmployeeID", DbType="integer", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<long> EmployeeID\r
                {\r
                        get\r
                        {\r
-                               return _employeeID;\r
+                               return this._employeeID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _employeeID)\r
+                               if ((_employeeID != value))\r
                                {\r
                                        if (_employee.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnEmployeeIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _employeeID = value;\r
-                                       SendPropertyChanged("EmployeeID");\r
-                                       OnEmployeeIDChanged();\r
+                                       this.OnEmployeeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._employeeID = value;\r
+                                       this.SendPropertyChanged("EmployeeID");\r
+                                       this.OnEmployeeIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region decimal? Freight\r
-\r
-               private decimal? _freight;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_freight", Name = "Freight", DbType = "money", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public decimal? Freight\r
+               \r
+               [Column(Storage="_freight", Name="Freight", DbType="money", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<decimal> Freight\r
                {\r
                        get\r
                        {\r
-                               return _freight;\r
+                               return this._freight;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _freight)\r
+                               if ((_freight != value))\r
                                {\r
-                                       OnFreightChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _freight = value;\r
-                                       SendPropertyChanged("Freight");\r
-                                       OnFreightChanged();\r
+                                       this.OnFreightChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._freight = value;\r
+                                       this.SendPropertyChanged("Freight");\r
+                                       this.OnFreightChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? OrderDate\r
-\r
-               private DateTime? _orderDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_orderDate", Name = "OrderDate", DbType = "datetime", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public DateTime? OrderDate\r
+               \r
+               [Column(Storage="_orderDate", Name="OrderDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> OrderDate\r
                {\r
                        get\r
                        {\r
-                               return _orderDate;\r
+                               return this._orderDate;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _orderDate)\r
+                               if ((_orderDate != value))\r
                                {\r
-                                       OnOrderDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _orderDate = value;\r
-                                       SendPropertyChanged("OrderDate");\r
-                                       OnOrderDateChanged();\r
+                                       this.OnOrderDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._orderDate = value;\r
+                                       this.SendPropertyChanged("OrderDate");\r
+                                       this.OnOrderDateChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long OrderID\r
-\r
-               private long _orderID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_orderID", Name = "OrderID", DbType = "integer", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_orderID", Name="OrderID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long OrderID\r
                {\r
                        get\r
                        {\r
-                               return _orderID;\r
+                               return this._orderID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _orderID)\r
+                               if ((_orderID != value))\r
                                {\r
-                                       OnOrderIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _orderID = value;\r
-                                       SendPropertyChanged("OrderID");\r
-                                       OnOrderIDChanged();\r
+                                       this.OnOrderIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._orderID = value;\r
+                                       this.SendPropertyChanged("OrderID");\r
+                                       this.OnOrderIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? RequiredDate\r
-\r
-               private DateTime? _requiredDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_requiredDate", Name = "RequiredDate", DbType = "datetime", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public DateTime? RequiredDate\r
+               \r
+               [Column(Storage="_requiredDate", Name="RequiredDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> RequiredDate\r
                {\r
                        get\r
                        {\r
-                               return _requiredDate;\r
+                               return this._requiredDate;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _requiredDate)\r
+                               if ((_requiredDate != value))\r
                                {\r
-                                       OnRequiredDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _requiredDate = value;\r
-                                       SendPropertyChanged("RequiredDate");\r
-                                       OnRequiredDateChanged();\r
+                                       this.OnRequiredDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._requiredDate = value;\r
+                                       this.SendPropertyChanged("RequiredDate");\r
+                                       this.OnRequiredDateChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ShipAddress\r
-\r
-               private string _shipAddress;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipAddress", Name = "ShipAddress", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_shipAddress", Name="ShipAddress", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ShipAddress\r
                {\r
                        get\r
                        {\r
-                               return _shipAddress;\r
+                               return this._shipAddress;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipAddress)\r
+                               if (((_shipAddress == value) \r
+                                                       == false))\r
                                {\r
-                                       OnShipAddressChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipAddress = value;\r
-                                       SendPropertyChanged("ShipAddress");\r
-                                       OnShipAddressChanged();\r
+                                       this.OnShipAddressChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipAddress = value;\r
+                                       this.SendPropertyChanged("ShipAddress");\r
+                                       this.OnShipAddressChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ShipCity\r
-\r
-               private string _shipCity;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipCity", Name = "ShipCity", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_shipCity", Name="ShipCity", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ShipCity\r
                {\r
                        get\r
                        {\r
-                               return _shipCity;\r
+                               return this._shipCity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipCity)\r
+                               if (((_shipCity == value) \r
+                                                       == false))\r
                                {\r
-                                       OnShipCityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipCity = value;\r
-                                       SendPropertyChanged("ShipCity");\r
-                                       OnShipCityChanged();\r
+                                       this.OnShipCityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipCity = value;\r
+                                       this.SendPropertyChanged("ShipCity");\r
+                                       this.OnShipCityChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ShipCountry\r
-\r
-               private string _shipCountry;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipCountry", Name = "ShipCountry", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_shipCountry", Name="ShipCountry", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ShipCountry\r
                {\r
                        get\r
                        {\r
-                               return _shipCountry;\r
+                               return this._shipCountry;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipCountry)\r
+                               if (((_shipCountry == value) \r
+                                                       == false))\r
                                {\r
-                                       OnShipCountryChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipCountry = value;\r
-                                       SendPropertyChanged("ShipCountry");\r
-                                       OnShipCountryChanged();\r
+                                       this.OnShipCountryChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipCountry = value;\r
+                                       this.SendPropertyChanged("ShipCountry");\r
+                                       this.OnShipCountryChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ShipName\r
-\r
-               private string _shipName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipName", Name = "ShipName", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_shipName", Name="ShipName", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ShipName\r
                {\r
                        get\r
                        {\r
-                               return _shipName;\r
+                               return this._shipName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipName)\r
+                               if (((_shipName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnShipNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipName = value;\r
-                                       SendPropertyChanged("ShipName");\r
-                                       OnShipNameChanged();\r
+                                       this.OnShipNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipName = value;\r
+                                       this.SendPropertyChanged("ShipName");\r
+                                       this.OnShipNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region DateTime? ShippedDate\r
-\r
-               private DateTime? _shippedDate;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shippedDate", Name = "ShippedDate", DbType = "datetime", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public DateTime? ShippedDate\r
+               \r
+               [Column(Storage="_shippedDate", Name="ShippedDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> ShippedDate\r
                {\r
                        get\r
                        {\r
-                               return _shippedDate;\r
+                               return this._shippedDate;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shippedDate)\r
+                               if ((_shippedDate != value))\r
                                {\r
-                                       OnShippedDateChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shippedDate = value;\r
-                                       SendPropertyChanged("ShippedDate");\r
-                                       OnShippedDateChanged();\r
+                                       this.OnShippedDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shippedDate = value;\r
+                                       this.SendPropertyChanged("ShippedDate");\r
+                                       this.OnShippedDateChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ShipPostalCode\r
-\r
-               private string _shipPostalCode;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipPostalCode", Name = "ShipPostalCode", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_shipPostalCode", Name="ShipPostalCode", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ShipPostalCode\r
                {\r
                        get\r
                        {\r
-                               return _shipPostalCode;\r
+                               return this._shipPostalCode;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipPostalCode)\r
+                               if (((_shipPostalCode == value) \r
+                                                       == false))\r
                                {\r
-                                       OnShipPostalCodeChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipPostalCode = value;\r
-                                       SendPropertyChanged("ShipPostalCode");\r
-                                       OnShipPostalCodeChanged();\r
+                                       this.OnShipPostalCodeChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipPostalCode = value;\r
+                                       this.SendPropertyChanged("ShipPostalCode");\r
+                                       this.OnShipPostalCodeChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ShipRegion\r
-\r
-               private string _shipRegion;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipRegion", Name = "ShipRegion", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_shipRegion", Name="ShipRegion", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ShipRegion\r
                {\r
                        get\r
                        {\r
-                               return _shipRegion;\r
+                               return this._shipRegion;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipRegion)\r
+                               if (((_shipRegion == value) \r
+                                                       == false))\r
                                {\r
-                                       OnShipRegionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipRegion = value;\r
-                                       SendPropertyChanged("ShipRegion");\r
-                                       OnShipRegionChanged();\r
+                                       this.OnShipRegionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipRegion = value;\r
+                                       this.SendPropertyChanged("ShipRegion");\r
+                                       this.OnShipRegionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long? ShipVia\r
-\r
-               private long? _shipVia;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipVia", Name = "ShipVia", DbType = "integer", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public long? ShipVia\r
+               \r
+               [Column(Storage="_shipVia", Name="ShipVia", DbType="integer", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<long> ShipVia\r
                {\r
                        get\r
                        {\r
-                               return _shipVia;\r
+                               return this._shipVia;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipVia)\r
+                               if ((_shipVia != value))\r
                                {\r
                                        if (_shipper.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnShipViaChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipVia = value;\r
-                                       SendPropertyChanged("ShipVia");\r
-                                       OnShipViaChanged();\r
+                                       this.OnShipViaChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipVia = value;\r
+                                       this.SendPropertyChanged("ShipVia");\r
+                                       this.OnShipViaChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<OrderDetail> _orderDetails;\r
-               [Association(Storage = "_orderDetails", OtherKey = "OrderID", ThisKey = "OrderID", Name = "\"FK_Order Details_1\"")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_orderDetails", OtherKey="OrderID", ThisKey="OrderID", Name="FK_Order Details_1")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<OrderDetail> OrderDetails\r
                {\r
                        get\r
                        {\r
-                               return _orderDetails;\r
+                               return this._orderDetails;\r
                        }\r
                        set\r
                        {\r
-                               _orderDetails = value;\r
+                               this._orderDetails = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Shipper> _shipper;\r
-               [Association(Storage = "_shipper", OtherKey = "ShipperID", ThisKey = "ShipVia", Name = "FK_Orders_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_shipper", OtherKey="ShipperID", ThisKey="ShipVia", Name="FK_Orders_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Shipper Shipper\r
                {\r
                        get\r
                        {\r
-                               return _shipper.Entity;\r
+                               return this._shipper.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipper.Entity)\r
+                               if (((this._shipper.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_shipper.Entity != null)\r
+                                       if ((this._shipper.Entity != null))\r
                                        {\r
-                                               var previousShipper = _shipper.Entity;\r
-                                               _shipper.Entity = null;\r
+                                               Shipper previousShipper = this._shipper.Entity;\r
+                                               this._shipper.Entity = null;\r
                                                previousShipper.Orders.Remove(this);\r
                                        }\r
-                                       _shipper.Entity = value;\r
-                                       if (value != null)\r
+                                       this._shipper.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Orders.Add(this);\r
                                                _shipVia = value.ShipperID;\r
@@ -2379,28 +2577,28 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-               private EntityRef<Employee> _employee;\r
-               [Association(Storage = "_employee", OtherKey = "EmployeeID", ThisKey = "EmployeeID", Name = "FK_Orders_1", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_employee", OtherKey="EmployeeID", ThisKey="EmployeeID", Name="FK_Orders_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Employee Employee\r
                {\r
                        get\r
                        {\r
-                               return _employee.Entity;\r
+                               return this._employee.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _employee.Entity)\r
+                               if (((this._employee.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_employee.Entity != null)\r
+                                       if ((this._employee.Entity != null))\r
                                        {\r
-                                               var previousEmployee = _employee.Entity;\r
-                                               _employee.Entity = null;\r
+                                               Employee previousEmployee = this._employee.Entity;\r
+                                               this._employee.Entity = null;\r
                                                previousEmployee.Orders.Remove(this);\r
                                        }\r
-                                       _employee.Entity = value;\r
-                                       if (value != null)\r
+                                       this._employee.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Orders.Add(this);\r
                                                _employeeID = value.EmployeeID;\r
@@ -2412,28 +2610,28 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-               private EntityRef<Customer> _customer;\r
-               [Association(Storage = "_customer", OtherKey = "CustomerID", ThisKey = "CustomerID", Name = "FK_Orders_2", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_customer", OtherKey="CustomerID", ThisKey="CustomerID", Name="FK_Orders_2", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Customer Customer\r
                {\r
                        get\r
                        {\r
-                               return _customer.Entity;\r
+                               return this._customer.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _customer.Entity)\r
+                               if (((this._customer.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_customer.Entity != null)\r
+                                       if ((this._customer.Entity != null))\r
                                        {\r
-                                               var previousCustomer = _customer.Entity;\r
-                                               _customer.Entity = null;\r
+                                               Customer previousCustomer = this._customer.Entity;\r
+                                               this._customer.Entity = null;\r
                                                previousCustomer.Orders.Remove(this);\r
                                        }\r
-                                       _customer.Entity = value;\r
-                                       if (value != null)\r
+                                       this._customer.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Orders.Add(this);\r
                                                _customerID = value.CustomerID;\r
@@ -2445,249 +2643,262 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void OrderDetails_Attach(OrderDetail entity)\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
                {\r
-                       entity.Order = this;\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
                }\r
-\r
-               private void OrderDetails_Detach(OrderDetail entity)\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       entity.Order = null;\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Order()\r
+               \r
+               public override int GetHashCode()\r
                {\r
-                       _orderDetails = new EntitySet<OrderDetail>(OrderDetails_Attach, OrderDetails_Detach);\r
-                       _shipper = new EntityRef<Shipper>();\r
-                       _employee = new EntityRef<Employee>();\r
-                       _customer = new EntityRef<Customer>();\r
-                       OnCreated();\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_orderID.GetHashCode() * 1));\r
+                       return hc;\r
                }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "\"Order Details\"")]\r
-       public partial class OrderDetail : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
+               \r
+               public override bool Equals(object value)\r
                {\r
-                       if (PropertyChanging != null)\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               return false;\r
                        }\r
+                       Order other = ((Order)(value));\r
+                       return this.Equals(other);\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
+               \r
+               public virtual bool Equals(Order value)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               return false;\r
                        }\r
+                       return System.Collections.Generic.EqualityComparer<long>.Default.Equals(this._orderID, value._orderID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void OrderDetails_Attach(OrderDetail entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Order = this;\r
+               }\r
+               \r
+               private void OrderDetails_Detach(OrderDetail entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Order = null;\r
                }\r
-\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="Order Details")]\r
+       public partial class OrderDetail : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<OrderDetail>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private float _discount;\r
+               \r
+               private long _orderID;\r
+               \r
+               private long _productID;\r
+               \r
+               private short _quantity;\r
+               \r
+               private decimal _unitPrice;\r
+               \r
+               private EntityRef<Product> _product = new EntityRef<Product>();\r
+               \r
+               private EntityRef<Order> _order = new EntityRef<Order>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnDiscountChanged();\r
+               \r
                partial void OnDiscountChanging(float value);\r
+               \r
                partial void OnOrderIDChanged();\r
+               \r
                partial void OnOrderIDChanging(long value);\r
+               \r
                partial void OnProductIDChanged();\r
+               \r
                partial void OnProductIDChanging(long value);\r
+               \r
                partial void OnQuantityChanged();\r
+               \r
                partial void OnQuantityChanging(short value);\r
+               \r
                partial void OnUnitPriceChanged();\r
+               \r
                partial void OnUnitPriceChanging(decimal value);\r
-\r
                #endregion\r
-\r
-               #region float Discount\r
-\r
-               private float _discount;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_discount", Name = "Discount", DbType = "real", AutoSync = AutoSync.Never)]\r
+               \r
+               \r
+               public OrderDetail()\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_discount", Name="Discount", DbType="real", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public float Discount\r
                {\r
                        get\r
                        {\r
-                               return _discount;\r
+                               return this._discount;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _discount)\r
+                               if ((_discount != value))\r
                                {\r
-                                       OnDiscountChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _discount = value;\r
-                                       SendPropertyChanged("Discount");\r
-                                       OnDiscountChanged();\r
+                                       this.OnDiscountChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._discount = value;\r
+                                       this.SendPropertyChanged("Discount");\r
+                                       this.OnDiscountChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long OrderID\r
-\r
-               private long _orderID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_orderID", Name = "OrderID", DbType = "integer", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_orderID", Name="OrderID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long OrderID\r
                {\r
                        get\r
                        {\r
-                               return _orderID;\r
+                               return this._orderID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _orderID)\r
+                               if ((_orderID != value))\r
                                {\r
                                        if (_order.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnOrderIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _orderID = value;\r
-                                       SendPropertyChanged("OrderID");\r
-                                       OnOrderIDChanged();\r
+                                       this.OnOrderIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._orderID = value;\r
+                                       this.SendPropertyChanged("OrderID");\r
+                                       this.OnOrderIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long ProductID\r
-\r
-               private long _productID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_productID", Name = "ProductID", DbType = "integer", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_productID", Name="ProductID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long ProductID\r
                {\r
                        get\r
                        {\r
-                               return _productID;\r
+                               return this._productID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _productID)\r
+                               if ((_productID != value))\r
                                {\r
                                        if (_product.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnProductIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _productID = value;\r
-                                       SendPropertyChanged("ProductID");\r
-                                       OnProductIDChanged();\r
+                                       this.OnProductIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._productID = value;\r
+                                       this.SendPropertyChanged("ProductID");\r
+                                       this.OnProductIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region short Quantity\r
-\r
-               private short _quantity;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_quantity", Name = "Quantity", DbType = "smallint", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_quantity", Name="Quantity", DbType="smallint", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public short Quantity\r
                {\r
                        get\r
                        {\r
-                               return _quantity;\r
+                               return this._quantity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _quantity)\r
+                               if ((_quantity != value))\r
                                {\r
-                                       OnQuantityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _quantity = value;\r
-                                       SendPropertyChanged("Quantity");\r
-                                       OnQuantityChanged();\r
+                                       this.OnQuantityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._quantity = value;\r
+                                       this.SendPropertyChanged("Quantity");\r
+                                       this.OnQuantityChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region decimal UnitPrice\r
-\r
-               private decimal _unitPrice;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_unitPrice", Name = "UnitPrice", DbType = "money", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_unitPrice", Name="UnitPrice", DbType="money", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public decimal UnitPrice\r
                {\r
                        get\r
                        {\r
-                               return _unitPrice;\r
+                               return this._unitPrice;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _unitPrice)\r
+                               if ((_unitPrice != value))\r
                                {\r
-                                       OnUnitPriceChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _unitPrice = value;\r
-                                       SendPropertyChanged("UnitPrice");\r
-                                       OnUnitPriceChanged();\r
+                                       this.OnUnitPriceChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._unitPrice = value;\r
+                                       this.SendPropertyChanged("UnitPrice");\r
+                                       this.OnUnitPriceChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Product> _product;\r
-               [Association(Storage = "_product", OtherKey = "ProductID", ThisKey = "ProductID", Name = "\"FK_Order Details_0\"", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_product", OtherKey="ProductID", ThisKey="ProductID", Name="FK_Order Details_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Product Product\r
                {\r
                        get\r
                        {\r
-                               return _product.Entity;\r
+                               return this._product.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _product.Entity)\r
+                               if (((this._product.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_product.Entity != null)\r
+                                       if ((this._product.Entity != null))\r
                                        {\r
-                                               var previousProduct = _product.Entity;\r
-                                               _product.Entity = null;\r
+                                               Product previousProduct = this._product.Entity;\r
+                                               this._product.Entity = null;\r
                                                previousProduct.OrderDetails.Remove(this);\r
                                        }\r
-                                       _product.Entity = value;\r
-                                       if (value != null)\r
+                                       this._product.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.OrderDetails.Add(this);\r
                                                _productID = value.ProductID;\r
@@ -2699,28 +2910,28 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-               private EntityRef<Order> _order;\r
-               [Association(Storage = "_order", OtherKey = "OrderID", ThisKey = "OrderID", Name = "\"FK_Order Details_1\"", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_order", OtherKey="OrderID", ThisKey="OrderID", Name="FK_Order Details_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Order Order\r
                {\r
                        get\r
                        {\r
-                               return _order.Entity;\r
+                               return this._order.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _order.Entity)\r
+                               if (((this._order.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_order.Entity != null)\r
+                                       if ((this._order.Entity != null))\r
                                        {\r
-                                               var previousOrder = _order.Entity;\r
-                                               _order.Entity = null;\r
+                                               Order previousOrder = this._order.Entity;\r
+                                               this._order.Entity = null;\r
                                                previousOrder.OrderDetails.Remove(this);\r
                                        }\r
-                                       _order.Entity = value;\r
-                                       if (value != null)\r
+                                       this._order.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.OrderDetails.Add(this);\r
                                                _orderID = value.OrderID;\r
@@ -2732,392 +2943,406 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region ctor\r
-\r
-               public OrderDetail()\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
                {\r
-                       _product = new EntityRef<Product>();\r
-                       _order = new EntityRef<Order>();\r
-                       OnCreated();\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
                }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "Products")]\r
-       public partial class Product : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       if (PropertyChanging != null)\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_orderID.GetHashCode() * 1));\r
+                       hc = (hc \r
+                                               | (_productID.GetHashCode() * 65536));\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               return false;\r
                        }\r
+                       OrderDetail other = ((OrderDetail)(value));\r
+                       return this.Equals(other);\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
+               \r
+               public virtual bool Equals(OrderDetail value)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               return false;\r
                        }\r
+                       return (System.Collections.Generic.EqualityComparer<long>.Default.Equals(this._orderID, value._orderID) && System.Collections.Generic.EqualityComparer<long>.Default.Equals(this._productID, value._productID));\r
                }\r
-\r
-               #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="Products")]\r
+       public partial class Product : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Product>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private System.Nullable<long> _categoryID;\r
+               \r
+               private bool _discontinued;\r
+               \r
+               private long _productID;\r
+               \r
+               private string _productName;\r
+               \r
+               private string _quantityPerUnit;\r
+               \r
+               private System.Nullable<short> _reorderLevel;\r
+               \r
+               private System.Nullable<long> _supplierID;\r
+               \r
+               private System.Nullable<decimal> _unitPrice;\r
+               \r
+               private System.Nullable<short> _unitsInStock;\r
+               \r
+               private System.Nullable<short> _unitsOnOrder;\r
+               \r
+               private EntitySet<OrderDetail> _orderDetails;\r
+               \r
+               private EntityRef<Supplier> _supplier = new EntityRef<Supplier>();\r
+               \r
+               private EntityRef<Category> _category = new EntityRef<Category>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnCategoryIDChanged();\r
-               partial void OnCategoryIDChanging(long? value);\r
+               \r
+               partial void OnCategoryIDChanging(System.Nullable<long> value);\r
+               \r
                partial void OnDiscontinuedChanged();\r
+               \r
                partial void OnDiscontinuedChanging(bool value);\r
+               \r
                partial void OnProductIDChanged();\r
+               \r
                partial void OnProductIDChanging(long value);\r
+               \r
                partial void OnProductNameChanged();\r
+               \r
                partial void OnProductNameChanging(string value);\r
+               \r
                partial void OnQuantityPerUnitChanged();\r
+               \r
                partial void OnQuantityPerUnitChanging(string value);\r
+               \r
                partial void OnReorderLevelChanged();\r
-               partial void OnReorderLevelChanging(short? value);\r
+               \r
+               partial void OnReorderLevelChanging(System.Nullable<short> value);\r
+               \r
                partial void OnSupplierIDChanged();\r
-               partial void OnSupplierIDChanging(long? value);\r
+               \r
+               partial void OnSupplierIDChanging(System.Nullable<long> value);\r
+               \r
                partial void OnUnitPriceChanged();\r
-               partial void OnUnitPriceChanging(decimal? value);\r
+               \r
+               partial void OnUnitPriceChanging(System.Nullable<decimal> value);\r
+               \r
                partial void OnUnitsInStockChanged();\r
-               partial void OnUnitsInStockChanging(short? value);\r
+               \r
+               partial void OnUnitsInStockChanging(System.Nullable<short> value);\r
+               \r
                partial void OnUnitsOnOrderChanged();\r
-               partial void OnUnitsOnOrderChanging(short? value);\r
-\r
+               \r
+               partial void OnUnitsOnOrderChanging(System.Nullable<short> value);\r
                #endregion\r
-\r
-               #region long? CategoryID\r
-\r
-               private long? _categoryID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_categoryID", Name = "CategoryID", DbType = "integer", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public long? CategoryID\r
+               \r
+               \r
+               public Product()\r
+               {\r
+                       _orderDetails = new EntitySet<OrderDetail>(new Action<OrderDetail>(this.OrderDetails_Attach), new Action<OrderDetail>(this.OrderDetails_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_categoryID", Name="CategoryID", DbType="integer", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<long> CategoryID\r
                {\r
                        get\r
                        {\r
-                               return _categoryID;\r
+                               return this._categoryID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _categoryID)\r
+                               if ((_categoryID != value))\r
                                {\r
                                        if (_category.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnCategoryIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _categoryID = value;\r
-                                       SendPropertyChanged("CategoryID");\r
-                                       OnCategoryIDChanged();\r
+                                       this.OnCategoryIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._categoryID = value;\r
+                                       this.SendPropertyChanged("CategoryID");\r
+                                       this.OnCategoryIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region bool Discontinued\r
-\r
-               private bool _discontinued;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_discontinued", Name = "Discontinued", DbType = "bit", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_discontinued", Name="Discontinued", DbType="bit", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public bool Discontinued\r
                {\r
                        get\r
                        {\r
-                               return _discontinued;\r
+                               return this._discontinued;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _discontinued)\r
+                               if ((_discontinued != value))\r
                                {\r
-                                       OnDiscontinuedChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _discontinued = value;\r
-                                       SendPropertyChanged("Discontinued");\r
-                                       OnDiscontinuedChanged();\r
+                                       this.OnDiscontinuedChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._discontinued = value;\r
+                                       this.SendPropertyChanged("Discontinued");\r
+                                       this.OnDiscontinuedChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long ProductID\r
-\r
-               private long _productID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_productID", Name = "ProductID", DbType = "integer", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_productID", Name="ProductID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long ProductID\r
                {\r
                        get\r
                        {\r
-                               return _productID;\r
+                               return this._productID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _productID)\r
+                               if ((_productID != value))\r
                                {\r
-                                       OnProductIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _productID = value;\r
-                                       SendPropertyChanged("ProductID");\r
-                                       OnProductIDChanged();\r
+                                       this.OnProductIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._productID = value;\r
+                                       this.SendPropertyChanged("ProductID");\r
+                                       this.OnProductIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ProductName\r
-\r
-               private string _productName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_productName", Name = "ProductName", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_productName", Name="ProductName", DbType="nvarchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string ProductName\r
                {\r
                        get\r
                        {\r
-                               return _productName;\r
+                               return this._productName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _productName)\r
+                               if (((_productName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnProductNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _productName = value;\r
-                                       SendPropertyChanged("ProductName");\r
-                                       OnProductNameChanged();\r
+                                       this.OnProductNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._productName = value;\r
+                                       this.SendPropertyChanged("ProductName");\r
+                                       this.OnProductNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string QuantityPerUnit\r
-\r
-               private string _quantityPerUnit;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_quantityPerUnit", Name = "QuantityPerUnit", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_quantityPerUnit", Name="QuantityPerUnit", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string QuantityPerUnit\r
                {\r
                        get\r
                        {\r
-                               return _quantityPerUnit;\r
+                               return this._quantityPerUnit;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _quantityPerUnit)\r
+                               if (((_quantityPerUnit == value) \r
+                                                       == false))\r
                                {\r
-                                       OnQuantityPerUnitChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _quantityPerUnit = value;\r
-                                       SendPropertyChanged("QuantityPerUnit");\r
-                                       OnQuantityPerUnitChanged();\r
+                                       this.OnQuantityPerUnitChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._quantityPerUnit = value;\r
+                                       this.SendPropertyChanged("QuantityPerUnit");\r
+                                       this.OnQuantityPerUnitChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region short? ReorderLevel\r
-\r
-               private short? _reorderLevel;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_reorderLevel", Name = "ReorderLevel", DbType = "smallint", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public short? ReorderLevel\r
+               \r
+               [Column(Storage="_reorderLevel", Name="ReorderLevel", DbType="smallint", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<short> ReorderLevel\r
                {\r
                        get\r
                        {\r
-                               return _reorderLevel;\r
+                               return this._reorderLevel;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _reorderLevel)\r
+                               if ((_reorderLevel != value))\r
                                {\r
-                                       OnReorderLevelChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _reorderLevel = value;\r
-                                       SendPropertyChanged("ReorderLevel");\r
-                                       OnReorderLevelChanged();\r
+                                       this.OnReorderLevelChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._reorderLevel = value;\r
+                                       this.SendPropertyChanged("ReorderLevel");\r
+                                       this.OnReorderLevelChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long? SupplierID\r
-\r
-               private long? _supplierID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_supplierID", Name = "SupplierID", DbType = "integer", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public long? SupplierID\r
+               \r
+               [Column(Storage="_supplierID", Name="SupplierID", DbType="integer", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<long> SupplierID\r
                {\r
                        get\r
                        {\r
-                               return _supplierID;\r
+                               return this._supplierID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _supplierID)\r
+                               if ((_supplierID != value))\r
                                {\r
                                        if (_supplier.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnSupplierIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _supplierID = value;\r
-                                       SendPropertyChanged("SupplierID");\r
-                                       OnSupplierIDChanged();\r
+                                       this.OnSupplierIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._supplierID = value;\r
+                                       this.SendPropertyChanged("SupplierID");\r
+                                       this.OnSupplierIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region decimal? UnitPrice\r
-\r
-               private decimal? _unitPrice;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_unitPrice", Name = "UnitPrice", DbType = "money", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public decimal? UnitPrice\r
+               \r
+               [Column(Storage="_unitPrice", Name="UnitPrice", DbType="money", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<decimal> UnitPrice\r
                {\r
                        get\r
                        {\r
-                               return _unitPrice;\r
+                               return this._unitPrice;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _unitPrice)\r
+                               if ((_unitPrice != value))\r
                                {\r
-                                       OnUnitPriceChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _unitPrice = value;\r
-                                       SendPropertyChanged("UnitPrice");\r
-                                       OnUnitPriceChanged();\r
+                                       this.OnUnitPriceChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._unitPrice = value;\r
+                                       this.SendPropertyChanged("UnitPrice");\r
+                                       this.OnUnitPriceChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region short? UnitsInStock\r
-\r
-               private short? _unitsInStock;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_unitsInStock", Name = "UnitsInStock", DbType = "smallint", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public short? UnitsInStock\r
+               \r
+               [Column(Storage="_unitsInStock", Name="UnitsInStock", DbType="smallint", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<short> UnitsInStock\r
                {\r
                        get\r
                        {\r
-                               return _unitsInStock;\r
+                               return this._unitsInStock;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _unitsInStock)\r
+                               if ((_unitsInStock != value))\r
                                {\r
-                                       OnUnitsInStockChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _unitsInStock = value;\r
-                                       SendPropertyChanged("UnitsInStock");\r
-                                       OnUnitsInStockChanged();\r
+                                       this.OnUnitsInStockChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._unitsInStock = value;\r
+                                       this.SendPropertyChanged("UnitsInStock");\r
+                                       this.OnUnitsInStockChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region short? UnitsOnOrder\r
-\r
-               private short? _unitsOnOrder;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_unitsOnOrder", Name = "UnitsOnOrder", DbType = "smallint", AutoSync = AutoSync.Never, CanBeNull = true)]\r
-               public short? UnitsOnOrder\r
+               \r
+               [Column(Storage="_unitsOnOrder", Name="UnitsOnOrder", DbType="smallint", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<short> UnitsOnOrder\r
                {\r
                        get\r
                        {\r
-                               return _unitsOnOrder;\r
+                               return this._unitsOnOrder;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _unitsOnOrder)\r
+                               if ((_unitsOnOrder != value))\r
                                {\r
-                                       OnUnitsOnOrderChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _unitsOnOrder = value;\r
-                                       SendPropertyChanged("UnitsOnOrder");\r
-                                       OnUnitsOnOrderChanged();\r
+                                       this.OnUnitsOnOrderChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._unitsOnOrder = value;\r
+                                       this.SendPropertyChanged("UnitsOnOrder");\r
+                                       this.OnUnitsOnOrderChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<OrderDetail> _orderDetails;\r
-               [Association(Storage = "_orderDetails", OtherKey = "ProductID", ThisKey = "ProductID", Name = "\"FK_Order Details_0\"")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_orderDetails", OtherKey="ProductID", ThisKey="ProductID", Name="FK_Order Details_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<OrderDetail> OrderDetails\r
                {\r
                        get\r
                        {\r
-                               return _orderDetails;\r
+                               return this._orderDetails;\r
                        }\r
                        set\r
                        {\r
-                               _orderDetails = value;\r
+                               this._orderDetails = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Supplier> _supplier;\r
-               [Association(Storage = "_supplier", OtherKey = "SupplierID", ThisKey = "SupplierID", Name = "FK_Products_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_supplier", OtherKey="SupplierID", ThisKey="SupplierID", Name="FK_Products_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Supplier Supplier\r
                {\r
                        get\r
                        {\r
-                               return _supplier.Entity;\r
+                               return this._supplier.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _supplier.Entity)\r
+                               if (((this._supplier.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_supplier.Entity != null)\r
+                                       if ((this._supplier.Entity != null))\r
                                        {\r
-                                               var previousSupplier = _supplier.Entity;\r
-                                               _supplier.Entity = null;\r
+                                               Supplier previousSupplier = this._supplier.Entity;\r
+                                               this._supplier.Entity = null;\r
                                                previousSupplier.Products.Remove(this);\r
                                        }\r
-                                       _supplier.Entity = value;\r
-                                       if (value != null)\r
+                                       this._supplier.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Products.Add(this);\r
                                                _supplierID = value.SupplierID;\r
@@ -3129,28 +3354,28 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-               private EntityRef<Category> _category;\r
-               [Association(Storage = "_category", OtherKey = "CategoryID", ThisKey = "CategoryID", Name = "FK_Products_1", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               \r
+               [Association(Storage="_category", OtherKey="CategoryID", ThisKey="CategoryID", Name="FK_Products_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Category Category\r
                {\r
                        get\r
                        {\r
-                               return _category.Entity;\r
+                               return this._category.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _category.Entity)\r
+                               if (((this._category.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_category.Entity != null)\r
+                                       if ((this._category.Entity != null))\r
                                        {\r
-                                               var previousCategory = _category.Entity;\r
-                                               _category.Entity = null;\r
+                                               Category previousCategory = this._category.Entity;\r
+                                               this._category.Entity = null;\r
                                                previousCategory.Products.Remove(this);\r
                                        }\r
-                                       _category.Entity = value;\r
-                                       if (value != null)\r
+                                       this._category.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Products.Add(this);\r
                                                _categoryID = value.CategoryID;\r
@@ -3162,939 +3387,1008 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void OrderDetails_Attach(OrderDetail entity)\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
                {\r
-                       entity.Product = this;\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
                }\r
-\r
-               private void OrderDetails_Detach(OrderDetail entity)\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       entity.Product = null;\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Product()\r
+               \r
+               public override int GetHashCode()\r
                {\r
-                       _orderDetails = new EntitySet<OrderDetail>(OrderDetails_Attach, OrderDetails_Detach);\r
-                       _supplier = new EntityRef<Supplier>();\r
-                       _category = new EntityRef<Category>();\r
-                       OnCreated();\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_productID.GetHashCode() * 1));\r
+                       return hc;\r
                }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "Region")]\r
-       public partial class Region : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
+               \r
+               public override bool Equals(object value)\r
                {\r
-                       if (PropertyChanging != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               return false;\r
                        }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Product other = ((Product)(value));\r
+                       return this.Equals(other);\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
+               \r
+               public virtual bool Equals(Product value)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               return false;\r
                        }\r
+                       return System.Collections.Generic.EqualityComparer<long>.Default.Equals(this._productID, value._productID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void OrderDetails_Attach(OrderDetail entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Product = this;\r
+               }\r
+               \r
+               private void OrderDetails_Detach(OrderDetail entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Product = null;\r
                }\r
-\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="Region")]\r
+       public partial class Region : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Region>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _regionDescription;\r
+               \r
+               private long _regionID;\r
+               \r
+               private EntitySet<Territory> _territories;\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnRegionDescriptionChanged();\r
+               \r
                partial void OnRegionDescriptionChanging(string value);\r
+               \r
                partial void OnRegionIDChanged();\r
+               \r
                partial void OnRegionIDChanging(long value);\r
-\r
                #endregion\r
-\r
-               #region string RegionDescription\r
-\r
-               private string _regionDescription;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_regionDescription", Name = "RegionDescription", DbType = "nchar", AutoSync = AutoSync.Never)]\r
+               \r
+               \r
+               public Region()\r
+               {\r
+                       _territories = new EntitySet<Territory>(new Action<Territory>(this.Territories_Attach), new Action<Territory>(this.Territories_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_regionDescription", Name="RegionDescription", DbType="nchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string RegionDescription\r
                {\r
                        get\r
                        {\r
-                               return _regionDescription;\r
+                               return this._regionDescription;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _regionDescription)\r
+                               if (((_regionDescription == value) \r
+                                                       == false))\r
                                {\r
-                                       OnRegionDescriptionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _regionDescription = value;\r
-                                       SendPropertyChanged("RegionDescription");\r
-                                       OnRegionDescriptionChanged();\r
+                                       this.OnRegionDescriptionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._regionDescription = value;\r
+                                       this.SendPropertyChanged("RegionDescription");\r
+                                       this.OnRegionDescriptionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long RegionID\r
-\r
-               private long _regionID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_regionID", Name = "RegionID", DbType = "integer", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_regionID", Name="RegionID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long RegionID\r
                {\r
                        get\r
                        {\r
-                               return _regionID;\r
+                               return this._regionID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _regionID)\r
+                               if ((_regionID != value))\r
                                {\r
-                                       OnRegionIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _regionID = value;\r
-                                       SendPropertyChanged("RegionID");\r
-                                       OnRegionIDChanged();\r
+                                       this.OnRegionIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._regionID = value;\r
+                                       this.SendPropertyChanged("RegionID");\r
+                                       this.OnRegionIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<Territory> _territories;\r
-               [Association(Storage = "_territories", OtherKey = "RegionID", ThisKey = "RegionID", Name = "FK_Territories_0")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_territories", OtherKey="RegionID", ThisKey="RegionID", Name="FK_Territories_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Territory> Territories\r
                {\r
                        get\r
                        {\r
-                               return _territories;\r
+                               return this._territories;\r
                        }\r
                        set\r
                        {\r
-                               _territories = value;\r
+                               this._territories = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void Territories_Attach(Territory entity)\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
                {\r
-                       entity.Region = this;\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
                }\r
-\r
-               private void Territories_Detach(Territory entity)\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       entity.Region = null;\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Region()\r
+               \r
+               public override int GetHashCode()\r
                {\r
-                       _territories = new EntitySet<Territory>(Territories_Attach, Territories_Detach);\r
-                       OnCreated();\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_regionID.GetHashCode() * 1));\r
+                       return hc;\r
                }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "Shippers")]\r
-       public partial class Shipper : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
+               \r
+               public override bool Equals(object value)\r
                {\r
-                       if (PropertyChanging != null)\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               return false;\r
                        }\r
+                       Region other = ((Region)(value));\r
+                       return this.Equals(other);\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
+               \r
+               public virtual bool Equals(Region value)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               return false;\r
                        }\r
+                       return System.Collections.Generic.EqualityComparer<long>.Default.Equals(this._regionID, value._regionID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void Territories_Attach(Territory entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Region = this;\r
+               }\r
+               \r
+               private void Territories_Detach(Territory entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Region = null;\r
                }\r
-\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="Shippers")]\r
+       public partial class Shipper : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Shipper>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _companyName;\r
+               \r
+               private string _phone;\r
+               \r
+               private long _shipperID;\r
+               \r
+               private EntitySet<Order> _orders;\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnCompanyNameChanged();\r
+               \r
                partial void OnCompanyNameChanging(string value);\r
+               \r
                partial void OnPhoneChanged();\r
+               \r
                partial void OnPhoneChanging(string value);\r
+               \r
                partial void OnShipperIDChanged();\r
+               \r
                partial void OnShipperIDChanging(long value);\r
-\r
                #endregion\r
-\r
-               #region string CompanyName\r
-\r
-               private string _companyName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_companyName", Name = "CompanyName", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               \r
+               public Shipper()\r
+               {\r
+                       _orders = new EntitySet<Order>(new Action<Order>(this.Orders_Attach), new Action<Order>(this.Orders_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_companyName", Name="CompanyName", DbType="nvarchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CompanyName\r
                {\r
                        get\r
                        {\r
-                               return _companyName;\r
+                               return this._companyName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _companyName)\r
+                               if (((_companyName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCompanyNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _companyName = value;\r
-                                       SendPropertyChanged("CompanyName");\r
-                                       OnCompanyNameChanged();\r
+                                       this.OnCompanyNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._companyName = value;\r
+                                       this.SendPropertyChanged("CompanyName");\r
+                                       this.OnCompanyNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Phone\r
-\r
-               private string _phone;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_phone", Name = "Phone", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_phone", Name="Phone", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Phone\r
                {\r
                        get\r
                        {\r
-                               return _phone;\r
+                               return this._phone;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _phone)\r
+                               if (((_phone == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPhoneChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _phone = value;\r
-                                       SendPropertyChanged("Phone");\r
-                                       OnPhoneChanged();\r
+                                       this.OnPhoneChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._phone = value;\r
+                                       this.SendPropertyChanged("Phone");\r
+                                       this.OnPhoneChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long ShipperID\r
-\r
-               private long _shipperID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_shipperID", Name = "ShipperID", DbType = "integer", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_shipperID", Name="ShipperID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long ShipperID\r
                {\r
                        get\r
                        {\r
-                               return _shipperID;\r
+                               return this._shipperID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _shipperID)\r
+                               if ((_shipperID != value))\r
                                {\r
-                                       OnShipperIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _shipperID = value;\r
-                                       SendPropertyChanged("ShipperID");\r
-                                       OnShipperIDChanged();\r
+                                       this.OnShipperIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipperID = value;\r
+                                       this.SendPropertyChanged("ShipperID");\r
+                                       this.OnShipperIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<Order> _orders;\r
-               [Association(Storage = "_orders", OtherKey = "ShipVia", ThisKey = "ShipperID", Name = "FK_Orders_0")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_orders", OtherKey="ShipVia", ThisKey="ShipperID", Name="FK_Orders_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Order> Orders\r
                {\r
                        get\r
                        {\r
-                               return _orders;\r
+                               return this._orders;\r
                        }\r
                        set\r
                        {\r
-                               _orders = value;\r
+                               this._orders = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void Orders_Attach(Order entity)\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
                {\r
-                       entity.Shipper = this;\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
                }\r
-\r
-               private void Orders_Detach(Order entity)\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       entity.Shipper = null;\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Shipper()\r
+               \r
+               public override int GetHashCode()\r
                {\r
-                       _orders = new EntitySet<Order>(Orders_Attach, Orders_Detach);\r
-                       OnCreated();\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_shipperID.GetHashCode() * 1));\r
+                       return hc;\r
                }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "Suppliers")]\r
-       public partial class Supplier : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
+               \r
+               public override bool Equals(object value)\r
                {\r
-                       if (PropertyChanging != null)\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               return false;\r
                        }\r
+                       Shipper other = ((Shipper)(value));\r
+                       return this.Equals(other);\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
+               \r
+               public virtual bool Equals(Shipper value)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               return false;\r
                        }\r
+                       return System.Collections.Generic.EqualityComparer<long>.Default.Equals(this._shipperID, value._shipperID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void Orders_Attach(Order entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Shipper = this;\r
+               }\r
+               \r
+               private void Orders_Detach(Order entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Shipper = null;\r
                }\r
-\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="Suppliers")]\r
+       public partial class Supplier : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Supplier>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _address;\r
+               \r
+               private string _city;\r
+               \r
+               private string _companyName;\r
+               \r
+               private string _contactName;\r
+               \r
+               private string _contactTitle;\r
+               \r
+               private string _country;\r
+               \r
+               private string _fax;\r
+               \r
+               private string _homePage;\r
+               \r
+               private string _phone;\r
+               \r
+               private string _postalCode;\r
+               \r
+               private string _region;\r
+               \r
+               private long _supplierID;\r
+               \r
+               private EntitySet<Product> _products;\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnAddressChanged();\r
+               \r
                partial void OnAddressChanging(string value);\r
+               \r
                partial void OnCityChanged();\r
+               \r
                partial void OnCityChanging(string value);\r
+               \r
                partial void OnCompanyNameChanged();\r
+               \r
                partial void OnCompanyNameChanging(string value);\r
+               \r
                partial void OnContactNameChanged();\r
+               \r
                partial void OnContactNameChanging(string value);\r
+               \r
                partial void OnContactTitleChanged();\r
+               \r
                partial void OnContactTitleChanging(string value);\r
+               \r
                partial void OnCountryChanged();\r
+               \r
                partial void OnCountryChanging(string value);\r
+               \r
                partial void OnFaxChanged();\r
+               \r
                partial void OnFaxChanging(string value);\r
+               \r
                partial void OnHomePageChanged();\r
+               \r
                partial void OnHomePageChanging(string value);\r
+               \r
                partial void OnPhoneChanged();\r
+               \r
                partial void OnPhoneChanging(string value);\r
+               \r
                partial void OnPostalCodeChanged();\r
+               \r
                partial void OnPostalCodeChanging(string value);\r
+               \r
                partial void OnRegionChanged();\r
+               \r
                partial void OnRegionChanging(string value);\r
+               \r
                partial void OnSupplierIDChanged();\r
+               \r
                partial void OnSupplierIDChanging(long value);\r
-\r
                #endregion\r
-\r
-               #region string Address\r
-\r
-               private string _address;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_address", Name = "Address", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               \r
+               public Supplier()\r
+               {\r
+                       _products = new EntitySet<Product>(new Action<Product>(this.Products_Attach), new Action<Product>(this.Products_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_address", Name="Address", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Address\r
                {\r
                        get\r
                        {\r
-                               return _address;\r
+                               return this._address;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _address)\r
+                               if (((_address == value) \r
+                                                       == false))\r
                                {\r
-                                       OnAddressChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _address = value;\r
-                                       SendPropertyChanged("Address");\r
-                                       OnAddressChanged();\r
+                                       this.OnAddressChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._address = value;\r
+                                       this.SendPropertyChanged("Address");\r
+                                       this.OnAddressChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string City\r
-\r
-               private string _city;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_city", Name = "City", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_city", Name="City", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string City\r
                {\r
                        get\r
                        {\r
-                               return _city;\r
+                               return this._city;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _city)\r
+                               if (((_city == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCityChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _city = value;\r
-                                       SendPropertyChanged("City");\r
-                                       OnCityChanged();\r
+                                       this.OnCityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._city = value;\r
+                                       this.SendPropertyChanged("City");\r
+                                       this.OnCityChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string CompanyName\r
-\r
-               private string _companyName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_companyName", Name = "CompanyName", DbType = "nvarchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_companyName", Name="CompanyName", DbType="nvarchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string CompanyName\r
                {\r
                        get\r
                        {\r
-                               return _companyName;\r
+                               return this._companyName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _companyName)\r
+                               if (((_companyName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCompanyNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _companyName = value;\r
-                                       SendPropertyChanged("CompanyName");\r
-                                       OnCompanyNameChanged();\r
+                                       this.OnCompanyNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._companyName = value;\r
+                                       this.SendPropertyChanged("CompanyName");\r
+                                       this.OnCompanyNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ContactName\r
-\r
-               private string _contactName;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_contactName", Name = "ContactName", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_contactName", Name="ContactName", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ContactName\r
                {\r
                        get\r
                        {\r
-                               return _contactName;\r
+                               return this._contactName;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _contactName)\r
+                               if (((_contactName == value) \r
+                                                       == false))\r
                                {\r
-                                       OnContactNameChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _contactName = value;\r
-                                       SendPropertyChanged("ContactName");\r
-                                       OnContactNameChanged();\r
+                                       this.OnContactNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._contactName = value;\r
+                                       this.SendPropertyChanged("ContactName");\r
+                                       this.OnContactNameChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string ContactTitle\r
-\r
-               private string _contactTitle;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_contactTitle", Name = "ContactTitle", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_contactTitle", Name="ContactTitle", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string ContactTitle\r
                {\r
                        get\r
                        {\r
-                               return _contactTitle;\r
+                               return this._contactTitle;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _contactTitle)\r
+                               if (((_contactTitle == value) \r
+                                                       == false))\r
                                {\r
-                                       OnContactTitleChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _contactTitle = value;\r
-                                       SendPropertyChanged("ContactTitle");\r
-                                       OnContactTitleChanged();\r
+                                       this.OnContactTitleChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._contactTitle = value;\r
+                                       this.SendPropertyChanged("ContactTitle");\r
+                                       this.OnContactTitleChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Country\r
-\r
-               private string _country;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_country", Name = "Country", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_country", Name="Country", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Country\r
                {\r
                        get\r
                        {\r
-                               return _country;\r
+                               return this._country;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _country)\r
+                               if (((_country == value) \r
+                                                       == false))\r
                                {\r
-                                       OnCountryChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _country = value;\r
-                                       SendPropertyChanged("Country");\r
-                                       OnCountryChanged();\r
+                                       this.OnCountryChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._country = value;\r
+                                       this.SendPropertyChanged("Country");\r
+                                       this.OnCountryChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Fax\r
-\r
-               private string _fax;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_fax", Name = "Fax", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_fax", Name="Fax", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Fax\r
                {\r
                        get\r
                        {\r
-                               return _fax;\r
+                               return this._fax;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _fax)\r
+                               if (((_fax == value) \r
+                                                       == false))\r
                                {\r
-                                       OnFaxChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _fax = value;\r
-                                       SendPropertyChanged("Fax");\r
-                                       OnFaxChanged();\r
+                                       this.OnFaxChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._fax = value;\r
+                                       this.SendPropertyChanged("Fax");\r
+                                       this.OnFaxChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string HomePage\r
-\r
-               private string _homePage;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_homePage", Name = "HomePage", DbType = "ntext", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_homePage", Name="HomePage", DbType="ntext", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string HomePage\r
                {\r
                        get\r
                        {\r
-                               return _homePage;\r
+                               return this._homePage;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _homePage)\r
+                               if (((_homePage == value) \r
+                                                       == false))\r
                                {\r
-                                       OnHomePageChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _homePage = value;\r
-                                       SendPropertyChanged("HomePage");\r
-                                       OnHomePageChanged();\r
+                                       this.OnHomePageChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._homePage = value;\r
+                                       this.SendPropertyChanged("HomePage");\r
+                                       this.OnHomePageChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Phone\r
-\r
-               private string _phone;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_phone", Name = "Phone", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_phone", Name="Phone", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Phone\r
                {\r
                        get\r
                        {\r
-                               return _phone;\r
+                               return this._phone;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _phone)\r
+                               if (((_phone == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPhoneChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _phone = value;\r
-                                       SendPropertyChanged("Phone");\r
-                                       OnPhoneChanged();\r
+                                       this.OnPhoneChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._phone = value;\r
+                                       this.SendPropertyChanged("Phone");\r
+                                       this.OnPhoneChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string PostalCode\r
-\r
-               private string _postalCode;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_postalCode", Name = "PostalCode", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_postalCode", Name="PostalCode", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string PostalCode\r
                {\r
                        get\r
                        {\r
-                               return _postalCode;\r
+                               return this._postalCode;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _postalCode)\r
+                               if (((_postalCode == value) \r
+                                                       == false))\r
                                {\r
-                                       OnPostalCodeChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _postalCode = value;\r
-                                       SendPropertyChanged("PostalCode");\r
-                                       OnPostalCodeChanged();\r
+                                       this.OnPostalCodeChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._postalCode = value;\r
+                                       this.SendPropertyChanged("PostalCode");\r
+                                       this.OnPostalCodeChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string Region\r
-\r
-               private string _region;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_region", Name = "Region", DbType = "nvarchar", AutoSync = AutoSync.Never, CanBeNull = true)]\r
+               \r
+               [Column(Storage="_region", Name="Region", DbType="nvarchar", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
                public string Region\r
                {\r
                        get\r
                        {\r
-                               return _region;\r
+                               return this._region;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _region)\r
+                               if (((_region == value) \r
+                                                       == false))\r
                                {\r
-                                       OnRegionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _region = value;\r
-                                       SendPropertyChanged("Region");\r
-                                       OnRegionChanged();\r
+                                       this.OnRegionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._region = value;\r
+                                       this.SendPropertyChanged("Region");\r
+                                       this.OnRegionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region long SupplierID\r
-\r
-               private long _supplierID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_supplierID", Name = "SupplierID", DbType = "integer", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_supplierID", Name="SupplierID", DbType="integer", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long SupplierID\r
                {\r
                        get\r
                        {\r
-                               return _supplierID;\r
+                               return this._supplierID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _supplierID)\r
+                               if ((_supplierID != value))\r
                                {\r
-                                       OnSupplierIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _supplierID = value;\r
-                                       SendPropertyChanged("SupplierID");\r
-                                       OnSupplierIDChanged();\r
+                                       this.OnSupplierIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._supplierID = value;\r
+                                       this.SendPropertyChanged("SupplierID");\r
+                                       this.OnSupplierIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<Product> _products;\r
-               [Association(Storage = "_products", OtherKey = "SupplierID", ThisKey = "SupplierID", Name = "FK_Products_0")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_products", OtherKey="SupplierID", ThisKey="SupplierID", Name="FK_Products_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<Product> Products\r
                {\r
                        get\r
                        {\r
-                               return _products;\r
+                               return this._products;\r
                        }\r
                        set\r
                        {\r
-                               _products = value;\r
+                               this._products = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
-               private void Products_Attach(Product entity)\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
                {\r
-                       entity.Supplier = this;\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
                }\r
-\r
-               private void Products_Detach(Product entity)\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
                {\r
-                       entity.Supplier = null;\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Supplier()\r
+               \r
+               public override int GetHashCode()\r
                {\r
-                       _products = new EntitySet<Product>(Products_Attach, Products_Detach);\r
-                       OnCreated();\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_supplierID.GetHashCode() * 1));\r
+                       return hc;\r
                }\r
-\r
-               #endregion\r
-\r
-       }\r
-\r
-       [Table(Name = "Territories")]\r
-       public partial class Territory : INotifyPropertyChanging, INotifyPropertyChanged\r
-       {\r
-               #region INotifyPropertyChanging handling\r
-\r
-               public event PropertyChangingEventHandler PropertyChanging;\r
-\r
-               private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs("");\r
-               protected virtual void SendPropertyChanging()\r
+               \r
+               public override bool Equals(object value)\r
                {\r
-                       if (PropertyChanging != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanging(this, emptyChangingEventArgs);\r
+                               return false;\r
                        }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Supplier other = ((Supplier)(value));\r
+                       return this.Equals(other);\r
                }\r
-\r
-               #endregion\r
-\r
-               #region INotifyPropertyChanged handling\r
-\r
-               public event PropertyChangedEventHandler PropertyChanged;\r
-\r
-               protected virtual void SendPropertyChanged(string propertyName)\r
+               \r
+               public virtual bool Equals(Supplier value)\r
                {\r
-                       if (PropertyChanged != null)\r
+                       if ((value == null))\r
                        {\r
-                               PropertyChanged(this, new PropertyChangedEventArgs(propertyName));\r
+                               return false;\r
                        }\r
+                       return System.Collections.Generic.EqualityComparer<long>.Default.Equals(this._supplierID, value._supplierID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void Products_Attach(Product entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Supplier = this;\r
+               }\r
+               \r
+               private void Products_Detach(Product entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Supplier = null;\r
                }\r
-\r
                #endregion\r
-\r
-               #region Extensibility Method Definitions\r
-\r
+       }\r
+       \r
+       [Table(Name="Territories")]\r
+       public partial class Territory : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Territory>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private long _regionID;\r
+               \r
+               private string _territoryDescription;\r
+               \r
+               private string _territoryID;\r
+               \r
+               private EntitySet<EmployeeTerritory> _employeeTerritories;\r
+               \r
+               private EntityRef<Region> _region = new EntityRef<Region>();\r
+               \r
+               #region Extensibility Method Declarations\r
                partial void OnCreated();\r
+               \r
                partial void OnRegionIDChanged();\r
+               \r
                partial void OnRegionIDChanging(long value);\r
+               \r
                partial void OnTerritoryDescriptionChanged();\r
+               \r
                partial void OnTerritoryDescriptionChanging(string value);\r
+               \r
                partial void OnTerritoryIDChanged();\r
+               \r
                partial void OnTerritoryIDChanging(string value);\r
-\r
                #endregion\r
-\r
-               #region long RegionID\r
-\r
-               private long _regionID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_regionID", Name = "RegionID", DbType = "integer", AutoSync = AutoSync.Never)]\r
+               \r
+               \r
+               public Territory()\r
+               {\r
+                       _employeeTerritories = new EntitySet<EmployeeTerritory>(new Action<EmployeeTerritory>(this.EmployeeTerritories_Attach), new Action<EmployeeTerritory>(this.EmployeeTerritories_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_regionID", Name="RegionID", DbType="integer", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public long RegionID\r
                {\r
                        get\r
                        {\r
-                               return _regionID;\r
+                               return this._regionID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _regionID)\r
+                               if ((_regionID != value))\r
                                {\r
                                        if (_region.HasLoadedOrAssignedValue)\r
                                        {\r
                                                throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
                                        }\r
-                                       OnRegionIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _regionID = value;\r
-                                       SendPropertyChanged("RegionID");\r
-                                       OnRegionIDChanged();\r
+                                       this.OnRegionIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._regionID = value;\r
+                                       this.SendPropertyChanged("RegionID");\r
+                                       this.OnRegionIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string TerritoryDescription\r
-\r
-               private string _territoryDescription;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_territoryDescription", Name = "TerritoryDescription", DbType = "nchar", AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_territoryDescription", Name="TerritoryDescription", DbType="nchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string TerritoryDescription\r
                {\r
                        get\r
                        {\r
-                               return _territoryDescription;\r
+                               return this._territoryDescription;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _territoryDescription)\r
+                               if (((_territoryDescription == value) \r
+                                                       == false))\r
                                {\r
-                                       OnTerritoryDescriptionChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _territoryDescription = value;\r
-                                       SendPropertyChanged("TerritoryDescription");\r
-                                       OnTerritoryDescriptionChanged();\r
+                                       this.OnTerritoryDescriptionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._territoryDescription = value;\r
+                                       this.SendPropertyChanged("TerritoryDescription");\r
+                                       this.OnTerritoryDescriptionChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
-               #region string TerritoryID\r
-\r
-               private string _territoryID;\r
-               [DebuggerNonUserCode]\r
-               [Column(Storage = "_territoryID", Name = "TerritoryID", DbType = "nvarchar", IsPrimaryKey = true, AutoSync = AutoSync.Never)]\r
+               \r
+               [Column(Storage="_territoryID", Name="TerritoryID", DbType="nvarchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
                public string TerritoryID\r
                {\r
                        get\r
                        {\r
-                               return _territoryID;\r
+                               return this._territoryID;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _territoryID)\r
+                               if (((_territoryID == value) \r
+                                                       == false))\r
                                {\r
-                                       OnTerritoryIDChanging(value);\r
-                                       SendPropertyChanging();\r
-                                       _territoryID = value;\r
-                                       SendPropertyChanged("TerritoryID");\r
-                                       OnTerritoryIDChanged();\r
+                                       this.OnTerritoryIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._territoryID = value;\r
+                                       this.SendPropertyChanged("TerritoryID");\r
+                                       this.OnTerritoryIDChanged();\r
                                }\r
                        }\r
                }\r
-\r
-               #endregion\r
-\r
+               \r
                #region Children\r
-\r
-               private EntitySet<EmployeeTerritory> _employeeTerritories;\r
-               [Association(Storage = "_employeeTerritories", OtherKey = "TerritoryID", ThisKey = "TerritoryID", Name = "FK_EmployeeTerritories_0")]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_employeeTerritories", OtherKey="TerritoryID", ThisKey="TerritoryID", Name="FK_EmployeeTerritories_0")]\r
+               [DebuggerNonUserCode()]\r
                public EntitySet<EmployeeTerritory> EmployeeTerritories\r
                {\r
                        get\r
                        {\r
-                               return _employeeTerritories;\r
+                               return this._employeeTerritories;\r
                        }\r
                        set\r
                        {\r
-                               _employeeTerritories = value;\r
+                               this._employeeTerritories = value;\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
+               \r
                #region Parents\r
-\r
-               private EntityRef<Region> _region;\r
-               [Association(Storage = "_region", OtherKey = "RegionID", ThisKey = "RegionID", Name = "FK_Territories_0", IsForeignKey = true)]\r
-               [DebuggerNonUserCode]\r
+               [Association(Storage="_region", OtherKey="RegionID", ThisKey="RegionID", Name="FK_Territories_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
                public Region Region\r
                {\r
                        get\r
                        {\r
-                               return _region.Entity;\r
+                               return this._region.Entity;\r
                        }\r
                        set\r
                        {\r
-                               if (value != _region.Entity)\r
+                               if (((this._region.Entity == value) \r
+                                                       == false))\r
                                {\r
-                                       if (_region.Entity != null)\r
+                                       if ((this._region.Entity != null))\r
                                        {\r
-                                               var previousRegion = _region.Entity;\r
-                                               _region.Entity = null;\r
+                                               Region previousRegion = this._region.Entity;\r
+                                               this._region.Entity = null;\r
                                                previousRegion.Territories.Remove(this);\r
                                        }\r
-                                       _region.Entity = value;\r
-                                       if (value != null)\r
+                                       this._region.Entity = value;\r
+                                       if ((value != null))\r
                                        {\r
                                                value.Territories.Add(this);\r
                                                _regionID = value.RegionID;\r
@@ -4106,35 +4400,77 @@ namespace nwind
                                }\r
                        }\r
                }\r
-\r
-\r
                #endregion\r
-\r
-               #region Attachement handlers\r
-\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       if ((_territoryID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_territoryID.GetHashCode() * 1));\r
+                       }\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Territory other = ((Territory)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Territory value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._territoryID, value._territoryID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
                private void EmployeeTerritories_Attach(EmployeeTerritory entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Territory = this;\r
                }\r
-\r
+               \r
                private void EmployeeTerritories_Detach(EmployeeTerritory entity)\r
                {\r
+                       this.SendPropertyChanging();\r
                        entity.Territory = null;\r
                }\r
-\r
-\r
-               #endregion\r
-\r
-               #region ctor\r
-\r
-               public Territory()\r
-               {\r
-                       _employeeTerritories = new EntitySet<EmployeeTerritory>(EmployeeTerritories_Attach, EmployeeTerritories_Detach);\r
-                       _region = new EntityRef<Region>();\r
-                       OnCreated();\r
-               }\r
-\r
                #endregion\r
-\r
        }\r
 }\r
diff --git a/mcs/class/System.Data.Linq/tests/expected/Northwind.Sqlite+DbSchemaLoader-sqlmetal.dbml b/mcs/class/System.Data.Linq/tests/expected/Northwind.Sqlite+DbSchemaLoader-sqlmetal.dbml
new file mode 100755 (executable)
index 0000000..c8b443a
--- /dev/null
@@ -0,0 +1,169 @@
+<?xml version="1.0"?>\r
+<Database xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Name="main" Class="Main" BaseType="System.Data.Linq.DataContext" xmlns="http://schemas.microsoft.com/linqtosql/dbml/2007">\r
+  <Table Name="Categories" Member="Categories">\r
+    <Type Name="Categories">\r
+      <Association Name="FK_Products_1" Member="Products" Storage="_products" Type="Products" ThisKey="CategoryID" OtherKey="CategoryID" DeleteRule="NO ACTION" />\r
+      <Column Name="CategoryID" Member="CategoryID" Storage="_categoryID" Type="System.Int64" DbType="integer" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="CategoryName" Member="CategoryName" Storage="_categoryName" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="Description" Member="Description" Storage="_description" Type="System.String" DbType="ntext" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Picture" Member="Picture" Storage="_picture" Type="System.Byte[]" DbType="image" IsPrimaryKey="false" CanBeNull="true" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="CustomerCustomerDemo" Member="CustomerCustomerDemo">\r
+    <Type Name="CustomerCustomerDemo">\r
+      <Association Name="FK_CustomerCustomerDemo_0" Member="Customers" Storage="_customers" Type="Customers" ThisKey="CustomerID" OtherKey="CustomerID" IsForeignKey="true" />\r
+      <Association Name="FK_CustomerCustomerDemo_1" Member="CustomerDemographics" Storage="_customerDemographics" Type="CustomerDemographics" ThisKey="CustomerTypeID" OtherKey="CustomerTypeID" IsForeignKey="true" />\r
+      <Column Name="CustomerID" Member="CustomerID" Storage="_customerID" Type="System.String" DbType="nchar" IsPrimaryKey="true" CanBeNull="false" />\r
+      <Column Name="CustomerTypeID" Member="CustomerTypeID" Storage="_customerTypeID" Type="System.String" DbType="nchar" IsPrimaryKey="true" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="CustomerDemographics" Member="CustomerDemographics">\r
+    <Type Name="CustomerDemographics">\r
+      <Association Name="FK_CustomerCustomerDemo_1" Member="CustomerCustomerDemo" Storage="_customerCustomerDemo" Type="CustomerCustomerDemo" ThisKey="CustomerTypeID" OtherKey="CustomerTypeID" DeleteRule="NO ACTION" />\r
+      <Column Name="CustomerDesc" Member="CustomerDesc" Storage="_customerDesc" Type="System.String" DbType="ntext" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="CustomerTypeID" Member="CustomerTypeID" Storage="_customerTypeID" Type="System.String" DbType="nchar" IsPrimaryKey="true" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="Customers" Member="Customers">\r
+    <Type Name="Customers">\r
+      <Association Name="FK_Orders_2" Member="Orders" Storage="_orders" Type="Orders" ThisKey="CustomerID" OtherKey="CustomerID" DeleteRule="NO ACTION" />\r
+      <Association Name="FK_CustomerCustomerDemo_0" Member="CustomerCustomerDemo" Storage="_customerCustomerDemo" Type="CustomerCustomerDemo" ThisKey="CustomerID" OtherKey="CustomerID" DeleteRule="NO ACTION" />\r
+      <Column Name="Address" Member="Address" Storage="_address" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="City" Member="City" Storage="_city" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="CompanyName" Member="CompanyName" Storage="_companyName" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="ContactName" Member="ContactName" Storage="_contactName" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ContactTitle" Member="ContactTitle" Storage="_contactTitle" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Country" Member="Country" Storage="_country" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="CustomerID" Member="CustomerID" Storage="_customerID" Type="System.String" DbType="nchar" IsPrimaryKey="true" CanBeNull="false" />\r
+      <Column Name="Fax" Member="Fax" Storage="_fax" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Phone" Member="Phone" Storage="_phone" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="PostalCode" Member="PostalCode" Storage="_postalCode" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Region" Member="Region" Storage="_region" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="Employees" Member="Employees">\r
+    <Type Name="Employees">\r
+      <Association Name="FK_Employees_0" Member="ReportsToEmployees" Storage="_reportsToEmployees" Type="Employees" ThisKey="ReportsTo" OtherKey="EmployeeID" IsForeignKey="true" />\r
+      <Association Name="FK_Employees_0" Member="EmployeeIDEmployees" Storage="_employeeIdeMployees" Type="Employees" ThisKey="EmployeeID" OtherKey="ReportsTo" DeleteRule="NO ACTION" />\r
+      <Association Name="FK_Orders_1" Member="Orders" Storage="_orders" Type="Orders" ThisKey="EmployeeID" OtherKey="EmployeeID" DeleteRule="NO ACTION" />\r
+      <Association Name="FK_EmployeeTerritories_1" Member="EmployeeTerritories" Storage="_employeeTerritories" Type="EmployeeTerritories" ThisKey="EmployeeID" OtherKey="EmployeeID" DeleteRule="NO ACTION" />\r
+      <Column Name="Address" Member="Address" Storage="_address" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="BirthDate" Member="BirthDate" Storage="_birthDate" Type="System.DateTime" DbType="datetime" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="City" Member="City" Storage="_city" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Country" Member="Country" Storage="_country" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="EmployeeID" Member="EmployeeID" Storage="_employeeID" Type="System.Int64" DbType="integer" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="Extension" Member="Extension" Storage="_extension" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="FirstName" Member="FirstName" Storage="_firstName" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="HireDate" Member="HireDate" Storage="_hireDate" Type="System.DateTime" DbType="datetime" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="HomePhone" Member="HomePhone" Storage="_homePhone" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="LastName" Member="LastName" Storage="_lastName" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="Notes" Member="Notes" Storage="_notes" Type="System.String" DbType="ntext" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Photo" Member="Photo" Storage="_photo" Type="System.Byte[]" DbType="image" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="PhotoPath" Member="PhotoPath" Storage="_photoPath" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="PostalCode" Member="PostalCode" Storage="_postalCode" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Region" Member="Region" Storage="_region" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ReportsTo" Member="ReportsTo" Storage="_reportsTo" Type="System.Int64" DbType="integer" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Title" Member="Title" Storage="_title" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="TitleOfCourtesy" Member="TitleOfCourtesy" Storage="_titleOfCourtesy" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="EmployeeTerritories" Member="EmployeeTerritories">\r
+    <Type Name="EmployeeTerritories">\r
+      <Association Name="FK_EmployeeTerritories_0" Member="Territories" Storage="_territories" Type="Territories" ThisKey="TerritoryID" OtherKey="TerritoryID" IsForeignKey="true" />\r
+      <Association Name="FK_EmployeeTerritories_1" Member="Employees" Storage="_employees" Type="Employees" ThisKey="EmployeeID" OtherKey="EmployeeID" IsForeignKey="true" />\r
+      <Column Name="EmployeeID" Member="EmployeeID" Storage="_employeeID" Type="System.Int64" DbType="integer" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="TerritoryID" Member="TerritoryID" Storage="_territoryID" Type="System.String" DbType="nvarchar" IsPrimaryKey="true" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="Order Details" Member="OrderDetails">\r
+    <Type Name="OrderDetails">\r
+      <Association Name="FK_Order Details_0" Member="Products" Storage="_products" Type="Products" ThisKey="ProductID" OtherKey="ProductID" IsForeignKey="true" />\r
+      <Association Name="FK_Order Details_1" Member="Orders" Storage="_orders" Type="Orders" ThisKey="OrderID" OtherKey="OrderID" IsForeignKey="true" />\r
+      <Column Name="Discount" Member="Discount" Storage="_discount" Type="System.Single" DbType="real" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="OrderID" Member="OrderID" Storage="_orderID" Type="System.Int64" DbType="integer" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="ProductID" Member="ProductID" Storage="_productID" Type="System.Int64" DbType="integer" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="Quantity" Member="Quantity" Storage="_quantity" Type="System.Int16" DbType="smallint" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="UnitPrice" Member="UnitPrice" Storage="_unitPrice" Type="System.Decimal" DbType="money" IsPrimaryKey="false" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="Orders" Member="Orders">\r
+    <Type Name="Orders">\r
+      <Association Name="FK_Orders_0" Member="Shippers" Storage="_shippers" Type="Shippers" ThisKey="ShipVia" OtherKey="ShipperID" IsForeignKey="true" />\r
+      <Association Name="FK_Orders_1" Member="Employees" Storage="_employees" Type="Employees" ThisKey="EmployeeID" OtherKey="EmployeeID" IsForeignKey="true" />\r
+      <Association Name="FK_Orders_2" Member="Customers" Storage="_customers" Type="Customers" ThisKey="CustomerID" OtherKey="CustomerID" IsForeignKey="true" />\r
+      <Association Name="FK_Order Details_1" Member="OrderDetails" Storage="_orderDetails" Type="OrderDetails" ThisKey="OrderID" OtherKey="OrderID" DeleteRule="NO ACTION" />\r
+      <Column Name="CustomerID" Member="CustomerID" Storage="_customerID" Type="System.String" DbType="nchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="EmployeeID" Member="EmployeeID" Storage="_employeeID" Type="System.Int64" DbType="integer" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Freight" Member="Freight" Storage="_freight" Type="System.Decimal" DbType="money" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="OrderDate" Member="OrderDate" Storage="_orderDate" Type="System.DateTime" DbType="datetime" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="OrderID" Member="OrderID" Storage="_orderID" Type="System.Int64" DbType="integer" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="RequiredDate" Member="RequiredDate" Storage="_requiredDate" Type="System.DateTime" DbType="datetime" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ShipAddress" Member="ShipAddress" Storage="_shipAddress" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ShipCity" Member="ShipCity" Storage="_shipCity" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ShipCountry" Member="ShipCountry" Storage="_shipCountry" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ShipName" Member="ShipName" Storage="_shipName" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ShippedDate" Member="ShippedDate" Storage="_shippedDate" Type="System.DateTime" DbType="datetime" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ShipPostalCode" Member="ShipPostalCode" Storage="_shipPostalCode" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ShipRegion" Member="ShipRegion" Storage="_shipRegion" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ShipVia" Member="ShipVia" Storage="_shipVia" Type="System.Int64" DbType="integer" IsPrimaryKey="false" CanBeNull="true" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="Products" Member="Products">\r
+    <Type Name="Products">\r
+      <Association Name="FK_Products_0" Member="Suppliers" Storage="_suppliers" Type="Suppliers" ThisKey="SupplierID" OtherKey="SupplierID" IsForeignKey="true" />\r
+      <Association Name="FK_Products_1" Member="Categories" Storage="_categories" Type="Categories" ThisKey="CategoryID" OtherKey="CategoryID" IsForeignKey="true" />\r
+      <Association Name="FK_Order Details_0" Member="OrderDetails" Storage="_orderDetails" Type="OrderDetails" ThisKey="ProductID" OtherKey="ProductID" DeleteRule="NO ACTION" />\r
+      <Column Name="CategoryID" Member="CategoryID" Storage="_categoryID" Type="System.Int64" DbType="integer" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Discontinued" Member="Discontinued" Storage="_discontinued" Type="System.Boolean" DbType="bit" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="ProductID" Member="ProductID" Storage="_productID" Type="System.Int64" DbType="integer" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="ProductName" Member="ProductName" Storage="_productName" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="QuantityPerUnit" Member="QuantityPerUnit" Storage="_quantityPerUnit" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ReorderLevel" Member="ReorderLevel" Storage="_reorderLevel" Type="System.Int16" DbType="smallint" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="SupplierID" Member="SupplierID" Storage="_supplierID" Type="System.Int64" DbType="integer" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="UnitPrice" Member="UnitPrice" Storage="_unitPrice" Type="System.Decimal" DbType="money" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="UnitsInStock" Member="UnitsInStock" Storage="_unitsInStock" Type="System.Int16" DbType="smallint" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="UnitsOnOrder" Member="UnitsOnOrder" Storage="_unitsOnOrder" Type="System.Int16" DbType="smallint" IsPrimaryKey="false" CanBeNull="true" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="Region" Member="Region">\r
+    <Type Name="Region">\r
+      <Association Name="FK_Territories_0" Member="Territories" Storage="_territories" Type="Territories" ThisKey="RegionID" OtherKey="RegionID" DeleteRule="NO ACTION" />\r
+      <Column Name="RegionDescription" Member="RegionDescription" Storage="_regionDescription" Type="System.String" DbType="nchar" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="RegionID" Member="RegionID" Storage="_regionID" Type="System.Int64" DbType="integer" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="Shippers" Member="Shippers">\r
+    <Type Name="Shippers">\r
+      <Association Name="FK_Orders_0" Member="Orders" Storage="_orders" Type="Orders" ThisKey="ShipperID" OtherKey="ShipVia" DeleteRule="NO ACTION" />\r
+      <Column Name="CompanyName" Member="CompanyName" Storage="_companyName" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="Phone" Member="Phone" Storage="_phone" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ShipperID" Member="ShipperID" Storage="_shipperID" Type="System.Int64" DbType="integer" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="Suppliers" Member="Suppliers">\r
+    <Type Name="Suppliers">\r
+      <Association Name="FK_Products_0" Member="Products" Storage="_products" Type="Products" ThisKey="SupplierID" OtherKey="SupplierID" DeleteRule="NO ACTION" />\r
+      <Column Name="Address" Member="Address" Storage="_address" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="City" Member="City" Storage="_city" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="CompanyName" Member="CompanyName" Storage="_companyName" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="ContactName" Member="ContactName" Storage="_contactName" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="ContactTitle" Member="ContactTitle" Storage="_contactTitle" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Country" Member="Country" Storage="_country" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Fax" Member="Fax" Storage="_fax" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="HomePage" Member="HomePage" Storage="_homePage" Type="System.String" DbType="ntext" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Phone" Member="Phone" Storage="_phone" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="PostalCode" Member="PostalCode" Storage="_postalCode" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="Region" Member="Region" Storage="_region" Type="System.String" DbType="nvarchar" IsPrimaryKey="false" CanBeNull="true" />\r
+      <Column Name="SupplierID" Member="SupplierID" Storage="_supplierID" Type="System.Int64" DbType="integer" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="Territories" Member="Territories">\r
+    <Type Name="Territories">\r
+      <Association Name="FK_Territories_0" Member="Region" Storage="_region" Type="Region" ThisKey="RegionID" OtherKey="RegionID" IsForeignKey="true" />\r
+      <Association Name="FK_EmployeeTerritories_0" Member="EmployeeTerritories" Storage="_employeeTerritories" Type="EmployeeTerritories" ThisKey="TerritoryID" OtherKey="TerritoryID" DeleteRule="NO ACTION" />\r
+      <Column Name="RegionID" Member="RegionID" Storage="_regionID" Type="System.Int64" DbType="integer" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="TerritoryDescription" Member="TerritoryDescription" Storage="_territoryDescription" Type="System.String" DbType="nchar" IsPrimaryKey="false" CanBeNull="false" />\r
+      <Column Name="TerritoryID" Member="TerritoryID" Storage="_territoryID" Type="System.String" DbType="nvarchar" IsPrimaryKey="true" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+</Database>
\ No newline at end of file
diff --git a/mcs/class/System.Data.Linq/tests/expected/Northwind.Sqlite-DbMetal.cs b/mcs/class/System.Data.Linq/tests/expected/Northwind.Sqlite-DbMetal.cs
new file mode 100755 (executable)
index 0000000..bdca1d9
--- /dev/null
@@ -0,0 +1,4517 @@
+// \r
+//  ____  _     __  __      _        _ \r
+// |  _ \| |__ |  \/  | ___| |_ __ _| |\r
+// | | | | '_ \| |\/| |/ _ \ __/ _` | |\r
+// | |_| | |_) | |  | |  __/ || (_| | |\r
+// |____/|_.__/|_|  |_|\___|\__\__,_|_|\r
+//\r
+// Auto-generated from Northwind on [TIMESTAMP].\r
+// Please visit http://code.google.com/p/dblinq2007/ for more information.\r
+//\r
+namespace nwind\r
+{\r
+       using System;\r
+       using System.ComponentModel;\r
+       using System.Data;\r
+#if MONO_STRICT\r
+       using System.Data.Linq;\r
+#else   // MONO_STRICT\r
+       using DbLinq.Data.Linq;\r
+       using DbLinq.Vendor;\r
+#endif  // MONO_STRICT\r
+       using System.Data.Linq.Mapping;\r
+       using System.Diagnostics;\r
+       \r
+       \r
+       public partial class Northwind : DataContext\r
+       {\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               #endregion\r
+               \r
+               \r
+               public Northwind(string connectionString) : \r
+                               base(connectionString)\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               public Northwind(string connection, MappingSource mappingSource) : \r
+                               base(connection, mappingSource)\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               public Northwind(IDbConnection connection, MappingSource mappingSource) : \r
+                               base(connection, mappingSource)\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               public Table<Category> Categories\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Category>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Customer> Customers\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Customer>();\r
+                       }\r
+               }\r
+               \r
+               public Table<CustomerCustomerDemo> CustomerCustomerDemo\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<CustomerCustomerDemo>();\r
+                       }\r
+               }\r
+               \r
+               public Table<CustomerDemographic> CustomerDemographics\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<CustomerDemographic>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Employee> Employees\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Employee>();\r
+                       }\r
+               }\r
+               \r
+               public Table<EmployeeTerritory> EmployeeTerritories\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<EmployeeTerritory>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Order> Orders\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Order>();\r
+                       }\r
+               }\r
+               \r
+               public Table<OrderDetail> OrderDetails\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<OrderDetail>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Product> Products\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Product>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Region> Regions\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Region>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Shipper> Shippers\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Shipper>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Supplier> Suppliers\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Supplier>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Territory> Territories\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Territory>();\r
+                       }\r
+               }\r
+       }\r
+       \r
+       #region Start MONO_STRICT\r
+#if MONO_STRICT\r
+\r
+       public partial class Northwind\r
+       {\r
+               \r
+               public Northwind(IDbConnection connection) : \r
+                               base(connection)\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+       }\r
+       #region End MONO_STRICT\r
+       #endregion\r
+#else     // MONO_STRICT\r
+       \r
+       public partial class Northwind\r
+       {\r
+               \r
+               public Northwind(IDbConnection connection) : \r
+                               base(connection, new DbLinq.Sqlite.SqliteVendor())\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               public Northwind(IDbConnection connection, IVendor sqlDialect) : \r
+                               base(connection, sqlDialect)\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               public Northwind(IDbConnection connection, MappingSource mappingSource, IVendor sqlDialect) : \r
+                               base(connection, mappingSource, sqlDialect)\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+       }\r
+       #region End Not MONO_STRICT\r
+       #endregion\r
+#endif     // MONO_STRICT\r
+       #endregion\r
+       \r
+       [Table(Name="main.Categories")]\r
+       public partial class Category : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Category>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private int _categoryID;\r
+               \r
+               private string _categoryName;\r
+               \r
+               private string _description;\r
+               \r
+               private byte[] _picture;\r
+               \r
+               private EntitySet<Product> _products;\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnCategoryIDChanged();\r
+               \r
+               partial void OnCategoryIDChanging(int value);\r
+               \r
+               partial void OnCategoryNameChanged();\r
+               \r
+               partial void OnCategoryNameChanging(string value);\r
+               \r
+               partial void OnDescriptionChanged();\r
+               \r
+               partial void OnDescriptionChanging(string value);\r
+               \r
+               partial void OnPictureChanged();\r
+               \r
+               partial void OnPictureChanging(byte[] value);\r
+               #endregion\r
+               \r
+               \r
+               public Category()\r
+               {\r
+                       _products = new EntitySet<Product>(new Action<Product>(this.Products_Attach), new Action<Product>(this.Products_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_categoryID", Name="CategoryID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int CategoryID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._categoryID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_categoryID != value))\r
+                               {\r
+                                       this.OnCategoryIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._categoryID = value;\r
+                                       this.SendPropertyChanged("CategoryID");\r
+                                       this.OnCategoryIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_categoryName", Name="CategoryName", DbType="nvarchar (15)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string CategoryName\r
+               {\r
+                       get\r
+                       {\r
+                               return this._categoryName;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_categoryName == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCategoryNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._categoryName = value;\r
+                                       this.SendPropertyChanged("CategoryName");\r
+                                       this.OnCategoryNameChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_description", Name="Description", DbType="ntext", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Description\r
+               {\r
+                       get\r
+                       {\r
+                               return this._description;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_description == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnDescriptionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._description = value;\r
+                                       this.SendPropertyChanged("Description");\r
+                                       this.OnDescriptionChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_picture", Name="Picture", DbType="image", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public byte[] Picture\r
+               {\r
+                       get\r
+                       {\r
+                               return this._picture;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_picture == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnPictureChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._picture = value;\r
+                                       this.SendPropertyChanged("Picture");\r
+                                       this.OnPictureChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Children\r
+               [Association(Storage="_products", OtherKey="CategoryID", ThisKey="CategoryID", Name="fk_Products_1")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<Product> Products\r
+               {\r
+                       get\r
+                       {\r
+                               return this._products;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._products = value;\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_categoryID.GetHashCode() * 1));\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Category other = ((Category)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Category value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<int>.Default.Equals(this._categoryID, value._categoryID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void Products_Attach(Product entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Category = this;\r
+               }\r
+               \r
+               private void Products_Detach(Product entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Category = null;\r
+               }\r
+               #endregion\r
+       }\r
+       \r
+       [Table(Name="main.Customers")]\r
+       public partial class Customer : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Customer>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _address;\r
+               \r
+               private string _city;\r
+               \r
+               private string _companyName;\r
+               \r
+               private string _contactName;\r
+               \r
+               private string _contactTitle;\r
+               \r
+               private string _country;\r
+               \r
+               private string _customerID;\r
+               \r
+               private string _fax;\r
+               \r
+               private string _phone;\r
+               \r
+               private string _postalCode;\r
+               \r
+               private string _region;\r
+               \r
+               private EntitySet<CustomerCustomerDemo> _customerCustomerDemo;\r
+               \r
+               private EntitySet<Order> _orders;\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnAddressChanged();\r
+               \r
+               partial void OnAddressChanging(string value);\r
+               \r
+               partial void OnCityChanged();\r
+               \r
+               partial void OnCityChanging(string value);\r
+               \r
+               partial void OnCompanyNameChanged();\r
+               \r
+               partial void OnCompanyNameChanging(string value);\r
+               \r
+               partial void OnContactNameChanged();\r
+               \r
+               partial void OnContactNameChanging(string value);\r
+               \r
+               partial void OnContactTitleChanged();\r
+               \r
+               partial void OnContactTitleChanging(string value);\r
+               \r
+               partial void OnCountryChanged();\r
+               \r
+               partial void OnCountryChanging(string value);\r
+               \r
+               partial void OnCustomerIDChanged();\r
+               \r
+               partial void OnCustomerIDChanging(string value);\r
+               \r
+               partial void OnFaxChanged();\r
+               \r
+               partial void OnFaxChanging(string value);\r
+               \r
+               partial void OnPhoneChanged();\r
+               \r
+               partial void OnPhoneChanging(string value);\r
+               \r
+               partial void OnPostalCodeChanged();\r
+               \r
+               partial void OnPostalCodeChanging(string value);\r
+               \r
+               partial void OnRegionChanged();\r
+               \r
+               partial void OnRegionChanging(string value);\r
+               #endregion\r
+               \r
+               \r
+               public Customer()\r
+               {\r
+                       _customerCustomerDemo = new EntitySet<CustomerCustomerDemo>(new Action<CustomerCustomerDemo>(this.CustomerCustomerDemo_Attach), new Action<CustomerCustomerDemo>(this.CustomerCustomerDemo_Detach));\r
+                       _orders = new EntitySet<Order>(new Action<Order>(this.Orders_Attach), new Action<Order>(this.Orders_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_address", Name="Address", DbType="nvarchar (60)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Address\r
+               {\r
+                       get\r
+                       {\r
+                               return this._address;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_address == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnAddressChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._address = value;\r
+                                       this.SendPropertyChanged("Address");\r
+                                       this.OnAddressChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_city", Name="City", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string City\r
+               {\r
+                       get\r
+                       {\r
+                               return this._city;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_city == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._city = value;\r
+                                       this.SendPropertyChanged("City");\r
+                                       this.OnCityChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_companyName", Name="CompanyName", DbType="nvarchar (40)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string CompanyName\r
+               {\r
+                       get\r
+                       {\r
+                               return this._companyName;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_companyName == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCompanyNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._companyName = value;\r
+                                       this.SendPropertyChanged("CompanyName");\r
+                                       this.OnCompanyNameChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_contactName", Name="ContactName", DbType="nvarchar (30)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string ContactName\r
+               {\r
+                       get\r
+                       {\r
+                               return this._contactName;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_contactName == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnContactNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._contactName = value;\r
+                                       this.SendPropertyChanged("ContactName");\r
+                                       this.OnContactNameChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_contactTitle", Name="ContactTitle", DbType="nvarchar (30)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string ContactTitle\r
+               {\r
+                       get\r
+                       {\r
+                               return this._contactTitle;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_contactTitle == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnContactTitleChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._contactTitle = value;\r
+                                       this.SendPropertyChanged("ContactTitle");\r
+                                       this.OnContactTitleChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_country", Name="Country", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Country\r
+               {\r
+                       get\r
+                       {\r
+                               return this._country;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_country == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCountryChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._country = value;\r
+                                       this.SendPropertyChanged("Country");\r
+                                       this.OnCountryChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_customerID", Name="CustomerID", DbType="nchar (5)", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string CustomerID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customerID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_customerID == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCustomerIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerID = value;\r
+                                       this.SendPropertyChanged("CustomerID");\r
+                                       this.OnCustomerIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_fax", Name="Fax", DbType="nvarchar (24)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Fax\r
+               {\r
+                       get\r
+                       {\r
+                               return this._fax;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_fax == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnFaxChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._fax = value;\r
+                                       this.SendPropertyChanged("Fax");\r
+                                       this.OnFaxChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_phone", Name="Phone", DbType="nvarchar (24)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Phone\r
+               {\r
+                       get\r
+                       {\r
+                               return this._phone;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_phone == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnPhoneChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._phone = value;\r
+                                       this.SendPropertyChanged("Phone");\r
+                                       this.OnPhoneChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_postalCode", Name="PostalCode", DbType="nvarchar (10)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string PostalCode\r
+               {\r
+                       get\r
+                       {\r
+                               return this._postalCode;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_postalCode == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnPostalCodeChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._postalCode = value;\r
+                                       this.SendPropertyChanged("PostalCode");\r
+                                       this.OnPostalCodeChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_region", Name="Region", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Region\r
+               {\r
+                       get\r
+                       {\r
+                               return this._region;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_region == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnRegionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._region = value;\r
+                                       this.SendPropertyChanged("Region");\r
+                                       this.OnRegionChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Children\r
+               [Association(Storage="_customerCustomerDemo", OtherKey="CustomerID", ThisKey="CustomerID", Name="fk_CustomerCustomerDemo_0")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<CustomerCustomerDemo> CustomerCustomerDemo\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customerCustomerDemo;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._customerCustomerDemo = value;\r
+                       }\r
+               }\r
+               \r
+               [Association(Storage="_orders", OtherKey="CustomerID", ThisKey="CustomerID", Name="fk_Orders_2")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<Order> Orders\r
+               {\r
+                       get\r
+                       {\r
+                               return this._orders;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._orders = value;\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       if ((_customerID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_customerID.GetHashCode() * 1));\r
+                       }\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Customer other = ((Customer)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Customer value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._customerID, value._customerID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void CustomerCustomerDemo_Attach(CustomerCustomerDemo entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Customer = this;\r
+               }\r
+               \r
+               private void CustomerCustomerDemo_Detach(CustomerCustomerDemo entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Customer = null;\r
+               }\r
+               \r
+               private void Orders_Attach(Order entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Customer = this;\r
+               }\r
+               \r
+               private void Orders_Detach(Order entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Customer = null;\r
+               }\r
+               #endregion\r
+       }\r
+       \r
+       [Table(Name="main.CustomerCustomerDemo")]\r
+       public partial class CustomerCustomerDemo : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<CustomerCustomerDemo>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _customerID;\r
+               \r
+               private string _customerTypeID;\r
+               \r
+               private EntityRef<Customer> _customer = new EntityRef<Customer>();\r
+               \r
+               private EntityRef<CustomerDemographic> _customerDemographic = new EntityRef<CustomerDemographic>();\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnCustomerIDChanged();\r
+               \r
+               partial void OnCustomerIDChanging(string value);\r
+               \r
+               partial void OnCustomerTypeIDChanged();\r
+               \r
+               partial void OnCustomerTypeIDChanging(string value);\r
+               #endregion\r
+               \r
+               \r
+               public CustomerCustomerDemo()\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_customerID", Name="CustomerID", DbType="nchar (5)", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string CustomerID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customerID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_customerID == value) \r
+                                                       == false))\r
+                               {\r
+                                       if (_customer.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnCustomerIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerID = value;\r
+                                       this.SendPropertyChanged("CustomerID");\r
+                                       this.OnCustomerIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_customerTypeID", Name="CustomerTypeID", DbType="nchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string CustomerTypeID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customerTypeID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_customerTypeID == value) \r
+                                                       == false))\r
+                               {\r
+                                       if (_customerDemographic.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnCustomerTypeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerTypeID = value;\r
+                                       this.SendPropertyChanged("CustomerTypeID");\r
+                                       this.OnCustomerTypeIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Parents\r
+               [Association(Storage="_customer", OtherKey="CustomerID", ThisKey="CustomerID", Name="fk_CustomerCustomerDemo_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Customer Customer\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customer.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._customer.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._customer.Entity != null))\r
+                                       {\r
+                                               Customer previousCustomer = this._customer.Entity;\r
+                                               this._customer.Entity = null;\r
+                                               previousCustomer.CustomerCustomerDemo.Remove(this);\r
+                                       }\r
+                                       this._customer.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.CustomerCustomerDemo.Add(this);\r
+                                               _customerID = value.CustomerID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _customerID = default(string);\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Association(Storage="_customerDemographic", OtherKey="CustomerTypeID", ThisKey="CustomerTypeID", Name="fk_CustomerCustomerDemo_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public CustomerDemographic CustomerDemographic\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customerDemographic.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._customerDemographic.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._customerDemographic.Entity != null))\r
+                                       {\r
+                                               CustomerDemographic previousCustomerDemographic = this._customerDemographic.Entity;\r
+                                               this._customerDemographic.Entity = null;\r
+                                               previousCustomerDemographic.CustomerCustomerDemo.Remove(this);\r
+                                       }\r
+                                       this._customerDemographic.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.CustomerCustomerDemo.Add(this);\r
+                                               _customerTypeID = value.CustomerTypeID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _customerTypeID = default(string);\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       if ((_customerID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_customerID.GetHashCode() * 1));\r
+                       }\r
+                       if ((_customerTypeID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_customerTypeID.GetHashCode() * 65536));\r
+                       }\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       CustomerCustomerDemo other = ((CustomerCustomerDemo)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(CustomerCustomerDemo value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return (System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._customerID, value._customerID) && System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._customerTypeID, value._customerTypeID));\r
+               }\r
+       }\r
+       \r
+       [Table(Name="main.CustomerDemographics")]\r
+       public partial class CustomerDemographic : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<CustomerDemographic>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _customerDesc;\r
+               \r
+               private string _customerTypeID;\r
+               \r
+               private EntitySet<CustomerCustomerDemo> _customerCustomerDemo;\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnCustomerDescChanged();\r
+               \r
+               partial void OnCustomerDescChanging(string value);\r
+               \r
+               partial void OnCustomerTypeIDChanged();\r
+               \r
+               partial void OnCustomerTypeIDChanging(string value);\r
+               #endregion\r
+               \r
+               \r
+               public CustomerDemographic()\r
+               {\r
+                       _customerCustomerDemo = new EntitySet<CustomerCustomerDemo>(new Action<CustomerCustomerDemo>(this.CustomerCustomerDemo_Attach), new Action<CustomerCustomerDemo>(this.CustomerCustomerDemo_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_customerDesc", Name="CustomerDesc", DbType="ntext", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string CustomerDesc\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customerDesc;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_customerDesc == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCustomerDescChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerDesc = value;\r
+                                       this.SendPropertyChanged("CustomerDesc");\r
+                                       this.OnCustomerDescChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_customerTypeID", Name="CustomerTypeID", DbType="nchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string CustomerTypeID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customerTypeID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_customerTypeID == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCustomerTypeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerTypeID = value;\r
+                                       this.SendPropertyChanged("CustomerTypeID");\r
+                                       this.OnCustomerTypeIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Children\r
+               [Association(Storage="_customerCustomerDemo", OtherKey="CustomerTypeID", ThisKey="CustomerTypeID", Name="fk_CustomerCustomerDemo_1")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<CustomerCustomerDemo> CustomerCustomerDemo\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customerCustomerDemo;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._customerCustomerDemo = value;\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       if ((_customerTypeID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_customerTypeID.GetHashCode() * 1));\r
+                       }\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       CustomerDemographic other = ((CustomerDemographic)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(CustomerDemographic value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._customerTypeID, value._customerTypeID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void CustomerCustomerDemo_Attach(CustomerCustomerDemo entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.CustomerDemographic = this;\r
+               }\r
+               \r
+               private void CustomerCustomerDemo_Detach(CustomerCustomerDemo entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.CustomerDemographic = null;\r
+               }\r
+               #endregion\r
+       }\r
+       \r
+       [Table(Name="main.Employees")]\r
+       public partial class Employee : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Employee>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _address;\r
+               \r
+               private System.Nullable<System.DateTime> _birthDate;\r
+               \r
+               private string _city;\r
+               \r
+               private string _country;\r
+               \r
+               private int _employeeID;\r
+               \r
+               private string _extension;\r
+               \r
+               private string _firstName;\r
+               \r
+               private System.Nullable<System.DateTime> _hireDate;\r
+               \r
+               private string _homePhone;\r
+               \r
+               private string _lastName;\r
+               \r
+               private string _notes;\r
+               \r
+               private byte[] _photo;\r
+               \r
+               private string _photoPath;\r
+               \r
+               private string _postalCode;\r
+               \r
+               private string _region;\r
+               \r
+               private System.Nullable<int> _reportsTo;\r
+               \r
+               private string _title;\r
+               \r
+               private string _titleOfCourtesy;\r
+               \r
+               private EntitySet<EmployeeTerritory> _employeeTerritories;\r
+               \r
+               private EntitySet<Employee> _employees;\r
+               \r
+               private EntitySet<Order> _orders;\r
+               \r
+               private EntityRef<Employee> _reportsToEmployee = new EntityRef<Employee>();\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnAddressChanged();\r
+               \r
+               partial void OnAddressChanging(string value);\r
+               \r
+               partial void OnBirthDateChanged();\r
+               \r
+               partial void OnBirthDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
+               partial void OnCityChanged();\r
+               \r
+               partial void OnCityChanging(string value);\r
+               \r
+               partial void OnCountryChanged();\r
+               \r
+               partial void OnCountryChanging(string value);\r
+               \r
+               partial void OnEmployeeIDChanged();\r
+               \r
+               partial void OnEmployeeIDChanging(int value);\r
+               \r
+               partial void OnExtensionChanged();\r
+               \r
+               partial void OnExtensionChanging(string value);\r
+               \r
+               partial void OnFirstNameChanged();\r
+               \r
+               partial void OnFirstNameChanging(string value);\r
+               \r
+               partial void OnHireDateChanged();\r
+               \r
+               partial void OnHireDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
+               partial void OnHomePhoneChanged();\r
+               \r
+               partial void OnHomePhoneChanging(string value);\r
+               \r
+               partial void OnLastNameChanged();\r
+               \r
+               partial void OnLastNameChanging(string value);\r
+               \r
+               partial void OnNotesChanged();\r
+               \r
+               partial void OnNotesChanging(string value);\r
+               \r
+               partial void OnPhotoChanged();\r
+               \r
+               partial void OnPhotoChanging(byte[] value);\r
+               \r
+               partial void OnPhotoPathChanged();\r
+               \r
+               partial void OnPhotoPathChanging(string value);\r
+               \r
+               partial void OnPostalCodeChanged();\r
+               \r
+               partial void OnPostalCodeChanging(string value);\r
+               \r
+               partial void OnRegionChanged();\r
+               \r
+               partial void OnRegionChanging(string value);\r
+               \r
+               partial void OnReportsToChanged();\r
+               \r
+               partial void OnReportsToChanging(System.Nullable<int> value);\r
+               \r
+               partial void OnTitleChanged();\r
+               \r
+               partial void OnTitleChanging(string value);\r
+               \r
+               partial void OnTitleOfCourtesyChanged();\r
+               \r
+               partial void OnTitleOfCourtesyChanging(string value);\r
+               #endregion\r
+               \r
+               \r
+               public Employee()\r
+               {\r
+                       _employeeTerritories = new EntitySet<EmployeeTerritory>(new Action<EmployeeTerritory>(this.EmployeeTerritories_Attach), new Action<EmployeeTerritory>(this.EmployeeTerritories_Detach));\r
+                       _employees = new EntitySet<Employee>(new Action<Employee>(this.Employees_Attach), new Action<Employee>(this.Employees_Detach));\r
+                       _orders = new EntitySet<Order>(new Action<Order>(this.Orders_Attach), new Action<Order>(this.Orders_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_address", Name="Address", DbType="nvarchar (60)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Address\r
+               {\r
+                       get\r
+                       {\r
+                               return this._address;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_address == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnAddressChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._address = value;\r
+                                       this.SendPropertyChanged("Address");\r
+                                       this.OnAddressChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_birthDate", Name="BirthDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> BirthDate\r
+               {\r
+                       get\r
+                       {\r
+                               return this._birthDate;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_birthDate != value))\r
+                               {\r
+                                       this.OnBirthDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._birthDate = value;\r
+                                       this.SendPropertyChanged("BirthDate");\r
+                                       this.OnBirthDateChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_city", Name="City", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string City\r
+               {\r
+                       get\r
+                       {\r
+                               return this._city;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_city == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._city = value;\r
+                                       this.SendPropertyChanged("City");\r
+                                       this.OnCityChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_country", Name="Country", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Country\r
+               {\r
+                       get\r
+                       {\r
+                               return this._country;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_country == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCountryChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._country = value;\r
+                                       this.SendPropertyChanged("Country");\r
+                                       this.OnCountryChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_employeeID", Name="EmployeeID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int EmployeeID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._employeeID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_employeeID != value))\r
+                               {\r
+                                       this.OnEmployeeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._employeeID = value;\r
+                                       this.SendPropertyChanged("EmployeeID");\r
+                                       this.OnEmployeeIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_extension", Name="Extension", DbType="nvarchar (4)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Extension\r
+               {\r
+                       get\r
+                       {\r
+                               return this._extension;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_extension == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnExtensionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._extension = value;\r
+                                       this.SendPropertyChanged("Extension");\r
+                                       this.OnExtensionChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_firstName", Name="FirstName", DbType="nvarchar (10)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string FirstName\r
+               {\r
+                       get\r
+                       {\r
+                               return this._firstName;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_firstName == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnFirstNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._firstName = value;\r
+                                       this.SendPropertyChanged("FirstName");\r
+                                       this.OnFirstNameChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_hireDate", Name="HireDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> HireDate\r
+               {\r
+                       get\r
+                       {\r
+                               return this._hireDate;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_hireDate != value))\r
+                               {\r
+                                       this.OnHireDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._hireDate = value;\r
+                                       this.SendPropertyChanged("HireDate");\r
+                                       this.OnHireDateChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_homePhone", Name="HomePhone", DbType="nvarchar (24)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string HomePhone\r
+               {\r
+                       get\r
+                       {\r
+                               return this._homePhone;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_homePhone == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnHomePhoneChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._homePhone = value;\r
+                                       this.SendPropertyChanged("HomePhone");\r
+                                       this.OnHomePhoneChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_lastName", Name="LastName", DbType="nvarchar (20)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string LastName\r
+               {\r
+                       get\r
+                       {\r
+                               return this._lastName;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_lastName == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnLastNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._lastName = value;\r
+                                       this.SendPropertyChanged("LastName");\r
+                                       this.OnLastNameChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_notes", Name="Notes", DbType="ntext", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Notes\r
+               {\r
+                       get\r
+                       {\r
+                               return this._notes;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_notes == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnNotesChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._notes = value;\r
+                                       this.SendPropertyChanged("Notes");\r
+                                       this.OnNotesChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_photo", Name="Photo", DbType="image", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public byte[] Photo\r
+               {\r
+                       get\r
+                       {\r
+                               return this._photo;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_photo == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnPhotoChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._photo = value;\r
+                                       this.SendPropertyChanged("Photo");\r
+                                       this.OnPhotoChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_photoPath", Name="PhotoPath", DbType="nvarchar (255)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string PhotoPath\r
+               {\r
+                       get\r
+                       {\r
+                               return this._photoPath;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_photoPath == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnPhotoPathChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._photoPath = value;\r
+                                       this.SendPropertyChanged("PhotoPath");\r
+                                       this.OnPhotoPathChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_postalCode", Name="PostalCode", DbType="nvarchar (10)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string PostalCode\r
+               {\r
+                       get\r
+                       {\r
+                               return this._postalCode;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_postalCode == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnPostalCodeChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._postalCode = value;\r
+                                       this.SendPropertyChanged("PostalCode");\r
+                                       this.OnPostalCodeChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_region", Name="Region", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Region\r
+               {\r
+                       get\r
+                       {\r
+                               return this._region;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_region == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnRegionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._region = value;\r
+                                       this.SendPropertyChanged("Region");\r
+                                       this.OnRegionChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_reportsTo", Name="ReportsTo", DbType="INTEGER", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<int> ReportsTo\r
+               {\r
+                       get\r
+                       {\r
+                               return this._reportsTo;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_reportsTo != value))\r
+                               {\r
+                                       if (_reportsToEmployee.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnReportsToChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._reportsTo = value;\r
+                                       this.SendPropertyChanged("ReportsTo");\r
+                                       this.OnReportsToChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_title", Name="Title", DbType="nvarchar (30)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Title\r
+               {\r
+                       get\r
+                       {\r
+                               return this._title;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_title == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnTitleChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._title = value;\r
+                                       this.SendPropertyChanged("Title");\r
+                                       this.OnTitleChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_titleOfCourtesy", Name="TitleOfCourtesy", DbType="nvarchar (25)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string TitleOfCourtesy\r
+               {\r
+                       get\r
+                       {\r
+                               return this._titleOfCourtesy;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_titleOfCourtesy == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnTitleOfCourtesyChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._titleOfCourtesy = value;\r
+                                       this.SendPropertyChanged("TitleOfCourtesy");\r
+                                       this.OnTitleOfCourtesyChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Children\r
+               [Association(Storage="_employeeTerritories", OtherKey="EmployeeID", ThisKey="EmployeeID", Name="fk_EmployeeTerritories_1")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<EmployeeTerritory> EmployeeTerritories\r
+               {\r
+                       get\r
+                       {\r
+                               return this._employeeTerritories;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._employeeTerritories = value;\r
+                       }\r
+               }\r
+               \r
+               [Association(Storage="_employees", OtherKey="ReportsTo", ThisKey="EmployeeID", Name="fk_Employees_0")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<Employee> Employees\r
+               {\r
+                       get\r
+                       {\r
+                               return this._employees;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._employees = value;\r
+                       }\r
+               }\r
+               \r
+               [Association(Storage="_orders", OtherKey="EmployeeID", ThisKey="EmployeeID", Name="fk_Orders_1")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<Order> Orders\r
+               {\r
+                       get\r
+                       {\r
+                               return this._orders;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._orders = value;\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               #region Parents\r
+               [Association(Storage="_reportsToEmployee", OtherKey="EmployeeID", ThisKey="ReportsTo", Name="fk_Employees_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Employee ReportsToEmployee\r
+               {\r
+                       get\r
+                       {\r
+                               return this._reportsToEmployee.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._reportsToEmployee.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._reportsToEmployee.Entity != null))\r
+                                       {\r
+                                               Employee previousEmployee = this._reportsToEmployee.Entity;\r
+                                               this._reportsToEmployee.Entity = null;\r
+                                               previousEmployee.Employees.Remove(this);\r
+                                       }\r
+                                       this._reportsToEmployee.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.Employees.Add(this);\r
+                                               _reportsTo = value.EmployeeID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _reportsTo = null;\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_employeeID.GetHashCode() * 1));\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Employee other = ((Employee)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Employee value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<int>.Default.Equals(this._employeeID, value._employeeID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void EmployeeTerritories_Attach(EmployeeTerritory entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Employee = this;\r
+               }\r
+               \r
+               private void EmployeeTerritories_Detach(EmployeeTerritory entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Employee = null;\r
+               }\r
+               \r
+               private void Employees_Attach(Employee entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.ReportsToEmployee = this;\r
+               }\r
+               \r
+               private void Employees_Detach(Employee entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.ReportsToEmployee = null;\r
+               }\r
+               \r
+               private void Orders_Attach(Order entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Employee = this;\r
+               }\r
+               \r
+               private void Orders_Detach(Order entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Employee = null;\r
+               }\r
+               #endregion\r
+       }\r
+       \r
+       [Table(Name="main.EmployeeTerritories")]\r
+       public partial class EmployeeTerritory : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<EmployeeTerritory>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private int _employeeID;\r
+               \r
+               private string _territoryID;\r
+               \r
+               private EntityRef<Territory> _territory = new EntityRef<Territory>();\r
+               \r
+               private EntityRef<Employee> _employee = new EntityRef<Employee>();\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnEmployeeIDChanged();\r
+               \r
+               partial void OnEmployeeIDChanging(int value);\r
+               \r
+               partial void OnTerritoryIDChanged();\r
+               \r
+               partial void OnTerritoryIDChanging(string value);\r
+               #endregion\r
+               \r
+               \r
+               public EmployeeTerritory()\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_employeeID", Name="EmployeeID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int EmployeeID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._employeeID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_employeeID != value))\r
+                               {\r
+                                       if (_employee.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnEmployeeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._employeeID = value;\r
+                                       this.SendPropertyChanged("EmployeeID");\r
+                                       this.OnEmployeeIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_territoryID", Name="TerritoryID", DbType="nvarchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string TerritoryID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._territoryID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_territoryID == value) \r
+                                                       == false))\r
+                               {\r
+                                       if (_territory.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnTerritoryIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._territoryID = value;\r
+                                       this.SendPropertyChanged("TerritoryID");\r
+                                       this.OnTerritoryIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Parents\r
+               [Association(Storage="_territory", OtherKey="TerritoryID", ThisKey="TerritoryID", Name="fk_EmployeeTerritories_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Territory Territory\r
+               {\r
+                       get\r
+                       {\r
+                               return this._territory.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._territory.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._territory.Entity != null))\r
+                                       {\r
+                                               Territory previousTerritory = this._territory.Entity;\r
+                                               this._territory.Entity = null;\r
+                                               previousTerritory.EmployeeTerritories.Remove(this);\r
+                                       }\r
+                                       this._territory.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.EmployeeTerritories.Add(this);\r
+                                               _territoryID = value.TerritoryID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _territoryID = default(string);\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Association(Storage="_employee", OtherKey="EmployeeID", ThisKey="EmployeeID", Name="fk_EmployeeTerritories_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Employee Employee\r
+               {\r
+                       get\r
+                       {\r
+                               return this._employee.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._employee.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._employee.Entity != null))\r
+                                       {\r
+                                               Employee previousEmployee = this._employee.Entity;\r
+                                               this._employee.Entity = null;\r
+                                               previousEmployee.EmployeeTerritories.Remove(this);\r
+                                       }\r
+                                       this._employee.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.EmployeeTerritories.Add(this);\r
+                                               _employeeID = value.EmployeeID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _employeeID = default(int);\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_employeeID.GetHashCode() * 1));\r
+                       if ((_territoryID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_territoryID.GetHashCode() * 65536));\r
+                       }\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       EmployeeTerritory other = ((EmployeeTerritory)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(EmployeeTerritory value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return (System.Collections.Generic.EqualityComparer<int>.Default.Equals(this._employeeID, value._employeeID) && System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._territoryID, value._territoryID));\r
+               }\r
+       }\r
+       \r
+       [Table(Name="main.Orders")]\r
+       public partial class Order : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Order>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _customerID;\r
+               \r
+               private System.Nullable<int> _employeeID;\r
+               \r
+               private System.Nullable<decimal> _freight;\r
+               \r
+               private System.Nullable<System.DateTime> _orderDate;\r
+               \r
+               private int _orderID;\r
+               \r
+               private System.Nullable<System.DateTime> _requiredDate;\r
+               \r
+               private string _shipAddress;\r
+               \r
+               private string _shipCity;\r
+               \r
+               private string _shipCountry;\r
+               \r
+               private string _shipName;\r
+               \r
+               private System.Nullable<System.DateTime> _shippedDate;\r
+               \r
+               private string _shipPostalCode;\r
+               \r
+               private string _shipRegion;\r
+               \r
+               private System.Nullable<int> _shipVia;\r
+               \r
+               private EntitySet<OrderDetail> _orderDetails;\r
+               \r
+               private EntityRef<Shipper> _shipper = new EntityRef<Shipper>();\r
+               \r
+               private EntityRef<Employee> _employee = new EntityRef<Employee>();\r
+               \r
+               private EntityRef<Customer> _customer = new EntityRef<Customer>();\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnCustomerIDChanged();\r
+               \r
+               partial void OnCustomerIDChanging(string value);\r
+               \r
+               partial void OnEmployeeIDChanged();\r
+               \r
+               partial void OnEmployeeIDChanging(System.Nullable<int> value);\r
+               \r
+               partial void OnFreightChanged();\r
+               \r
+               partial void OnFreightChanging(System.Nullable<decimal> value);\r
+               \r
+               partial void OnOrderDateChanged();\r
+               \r
+               partial void OnOrderDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
+               partial void OnOrderIDChanged();\r
+               \r
+               partial void OnOrderIDChanging(int value);\r
+               \r
+               partial void OnRequiredDateChanged();\r
+               \r
+               partial void OnRequiredDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
+               partial void OnShipAddressChanged();\r
+               \r
+               partial void OnShipAddressChanging(string value);\r
+               \r
+               partial void OnShipCityChanged();\r
+               \r
+               partial void OnShipCityChanging(string value);\r
+               \r
+               partial void OnShipCountryChanged();\r
+               \r
+               partial void OnShipCountryChanging(string value);\r
+               \r
+               partial void OnShipNameChanged();\r
+               \r
+               partial void OnShipNameChanging(string value);\r
+               \r
+               partial void OnShippedDateChanged();\r
+               \r
+               partial void OnShippedDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
+               partial void OnShipPostalCodeChanged();\r
+               \r
+               partial void OnShipPostalCodeChanging(string value);\r
+               \r
+               partial void OnShipRegionChanged();\r
+               \r
+               partial void OnShipRegionChanging(string value);\r
+               \r
+               partial void OnShipViaChanged();\r
+               \r
+               partial void OnShipViaChanging(System.Nullable<int> value);\r
+               #endregion\r
+               \r
+               \r
+               public Order()\r
+               {\r
+                       _orderDetails = new EntitySet<OrderDetail>(new Action<OrderDetail>(this.OrderDetails_Attach), new Action<OrderDetail>(this.OrderDetails_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_customerID", Name="CustomerID", DbType="nchar (5)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string CustomerID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customerID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_customerID == value) \r
+                                                       == false))\r
+                               {\r
+                                       if (_customer.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnCustomerIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerID = value;\r
+                                       this.SendPropertyChanged("CustomerID");\r
+                                       this.OnCustomerIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_employeeID", Name="EmployeeID", DbType="INTEGER", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<int> EmployeeID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._employeeID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_employeeID != value))\r
+                               {\r
+                                       if (_employee.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnEmployeeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._employeeID = value;\r
+                                       this.SendPropertyChanged("EmployeeID");\r
+                                       this.OnEmployeeIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_freight", Name="Freight", DbType="money", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<decimal> Freight\r
+               {\r
+                       get\r
+                       {\r
+                               return this._freight;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_freight != value))\r
+                               {\r
+                                       this.OnFreightChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._freight = value;\r
+                                       this.SendPropertyChanged("Freight");\r
+                                       this.OnFreightChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_orderDate", Name="OrderDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> OrderDate\r
+               {\r
+                       get\r
+                       {\r
+                               return this._orderDate;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_orderDate != value))\r
+                               {\r
+                                       this.OnOrderDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._orderDate = value;\r
+                                       this.SendPropertyChanged("OrderDate");\r
+                                       this.OnOrderDateChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_orderID", Name="OrderID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int OrderID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._orderID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_orderID != value))\r
+                               {\r
+                                       this.OnOrderIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._orderID = value;\r
+                                       this.SendPropertyChanged("OrderID");\r
+                                       this.OnOrderIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_requiredDate", Name="RequiredDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> RequiredDate\r
+               {\r
+                       get\r
+                       {\r
+                               return this._requiredDate;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_requiredDate != value))\r
+                               {\r
+                                       this.OnRequiredDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._requiredDate = value;\r
+                                       this.SendPropertyChanged("RequiredDate");\r
+                                       this.OnRequiredDateChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_shipAddress", Name="ShipAddress", DbType="nvarchar (60)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string ShipAddress\r
+               {\r
+                       get\r
+                       {\r
+                               return this._shipAddress;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_shipAddress == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnShipAddressChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipAddress = value;\r
+                                       this.SendPropertyChanged("ShipAddress");\r
+                                       this.OnShipAddressChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_shipCity", Name="ShipCity", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string ShipCity\r
+               {\r
+                       get\r
+                       {\r
+                               return this._shipCity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_shipCity == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnShipCityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipCity = value;\r
+                                       this.SendPropertyChanged("ShipCity");\r
+                                       this.OnShipCityChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_shipCountry", Name="ShipCountry", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string ShipCountry\r
+               {\r
+                       get\r
+                       {\r
+                               return this._shipCountry;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_shipCountry == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnShipCountryChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipCountry = value;\r
+                                       this.SendPropertyChanged("ShipCountry");\r
+                                       this.OnShipCountryChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_shipName", Name="ShipName", DbType="nvarchar (40)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string ShipName\r
+               {\r
+                       get\r
+                       {\r
+                               return this._shipName;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_shipName == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnShipNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipName = value;\r
+                                       this.SendPropertyChanged("ShipName");\r
+                                       this.OnShipNameChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_shippedDate", Name="ShippedDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> ShippedDate\r
+               {\r
+                       get\r
+                       {\r
+                               return this._shippedDate;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_shippedDate != value))\r
+                               {\r
+                                       this.OnShippedDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shippedDate = value;\r
+                                       this.SendPropertyChanged("ShippedDate");\r
+                                       this.OnShippedDateChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_shipPostalCode", Name="ShipPostalCode", DbType="nvarchar (10)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string ShipPostalCode\r
+               {\r
+                       get\r
+                       {\r
+                               return this._shipPostalCode;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_shipPostalCode == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnShipPostalCodeChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipPostalCode = value;\r
+                                       this.SendPropertyChanged("ShipPostalCode");\r
+                                       this.OnShipPostalCodeChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_shipRegion", Name="ShipRegion", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string ShipRegion\r
+               {\r
+                       get\r
+                       {\r
+                               return this._shipRegion;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_shipRegion == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnShipRegionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipRegion = value;\r
+                                       this.SendPropertyChanged("ShipRegion");\r
+                                       this.OnShipRegionChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_shipVia", Name="ShipVia", DbType="INTEGER", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<int> ShipVia\r
+               {\r
+                       get\r
+                       {\r
+                               return this._shipVia;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_shipVia != value))\r
+                               {\r
+                                       if (_shipper.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnShipViaChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipVia = value;\r
+                                       this.SendPropertyChanged("ShipVia");\r
+                                       this.OnShipViaChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Children\r
+               [Association(Storage="_orderDetails", OtherKey="OrderID", ThisKey="OrderID", Name="fk_Order Details_1")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<OrderDetail> OrderDetails\r
+               {\r
+                       get\r
+                       {\r
+                               return this._orderDetails;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._orderDetails = value;\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               #region Parents\r
+               [Association(Storage="_shipper", OtherKey="ShipperID", ThisKey="ShipVia", Name="fk_Orders_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Shipper Shipper\r
+               {\r
+                       get\r
+                       {\r
+                               return this._shipper.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._shipper.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._shipper.Entity != null))\r
+                                       {\r
+                                               Shipper previousShipper = this._shipper.Entity;\r
+                                               this._shipper.Entity = null;\r
+                                               previousShipper.Orders.Remove(this);\r
+                                       }\r
+                                       this._shipper.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.Orders.Add(this);\r
+                                               _shipVia = value.ShipperID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _shipVia = null;\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Association(Storage="_employee", OtherKey="EmployeeID", ThisKey="EmployeeID", Name="fk_Orders_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Employee Employee\r
+               {\r
+                       get\r
+                       {\r
+                               return this._employee.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._employee.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._employee.Entity != null))\r
+                                       {\r
+                                               Employee previousEmployee = this._employee.Entity;\r
+                                               this._employee.Entity = null;\r
+                                               previousEmployee.Orders.Remove(this);\r
+                                       }\r
+                                       this._employee.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.Orders.Add(this);\r
+                                               _employeeID = value.EmployeeID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _employeeID = null;\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Association(Storage="_customer", OtherKey="CustomerID", ThisKey="CustomerID", Name="fk_Orders_2", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Customer Customer\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customer.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._customer.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._customer.Entity != null))\r
+                                       {\r
+                                               Customer previousCustomer = this._customer.Entity;\r
+                                               this._customer.Entity = null;\r
+                                               previousCustomer.Orders.Remove(this);\r
+                                       }\r
+                                       this._customer.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.Orders.Add(this);\r
+                                               _customerID = value.CustomerID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _customerID = null;\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_orderID.GetHashCode() * 1));\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Order other = ((Order)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Order value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<int>.Default.Equals(this._orderID, value._orderID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void OrderDetails_Attach(OrderDetail entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Order = this;\r
+               }\r
+               \r
+               private void OrderDetails_Detach(OrderDetail entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Order = null;\r
+               }\r
+               #endregion\r
+       }\r
+       \r
+       [Table(Name="main.Order Details")]\r
+       public partial class OrderDetail : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<OrderDetail>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private float _discount;\r
+               \r
+               private int _orderID;\r
+               \r
+               private int _productID;\r
+               \r
+               private short _quantity;\r
+               \r
+               private decimal _unitPrice;\r
+               \r
+               private EntityRef<Product> _product = new EntityRef<Product>();\r
+               \r
+               private EntityRef<Order> _order = new EntityRef<Order>();\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnDiscountChanged();\r
+               \r
+               partial void OnDiscountChanging(float value);\r
+               \r
+               partial void OnOrderIDChanged();\r
+               \r
+               partial void OnOrderIDChanging(int value);\r
+               \r
+               partial void OnProductIDChanged();\r
+               \r
+               partial void OnProductIDChanging(int value);\r
+               \r
+               partial void OnQuantityChanged();\r
+               \r
+               partial void OnQuantityChanging(short value);\r
+               \r
+               partial void OnUnitPriceChanged();\r
+               \r
+               partial void OnUnitPriceChanging(decimal value);\r
+               #endregion\r
+               \r
+               \r
+               public OrderDetail()\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_discount", Name="Discount", DbType="real", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public float Discount\r
+               {\r
+                       get\r
+                       {\r
+                               return this._discount;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_discount != value))\r
+                               {\r
+                                       this.OnDiscountChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._discount = value;\r
+                                       this.SendPropertyChanged("Discount");\r
+                                       this.OnDiscountChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_orderID", Name="OrderID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int OrderID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._orderID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_orderID != value))\r
+                               {\r
+                                       if (_order.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnOrderIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._orderID = value;\r
+                                       this.SendPropertyChanged("OrderID");\r
+                                       this.OnOrderIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_productID", Name="ProductID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int ProductID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._productID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_productID != value))\r
+                               {\r
+                                       if (_product.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnProductIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._productID = value;\r
+                                       this.SendPropertyChanged("ProductID");\r
+                                       this.OnProductIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_quantity", Name="Quantity", DbType="smallint", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public short Quantity\r
+               {\r
+                       get\r
+                       {\r
+                               return this._quantity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_quantity != value))\r
+                               {\r
+                                       this.OnQuantityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._quantity = value;\r
+                                       this.SendPropertyChanged("Quantity");\r
+                                       this.OnQuantityChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_unitPrice", Name="UnitPrice", DbType="money", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public decimal UnitPrice\r
+               {\r
+                       get\r
+                       {\r
+                               return this._unitPrice;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_unitPrice != value))\r
+                               {\r
+                                       this.OnUnitPriceChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._unitPrice = value;\r
+                                       this.SendPropertyChanged("UnitPrice");\r
+                                       this.OnUnitPriceChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Parents\r
+               [Association(Storage="_product", OtherKey="ProductID", ThisKey="ProductID", Name="fk_Order Details_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Product Product\r
+               {\r
+                       get\r
+                       {\r
+                               return this._product.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._product.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._product.Entity != null))\r
+                                       {\r
+                                               Product previousProduct = this._product.Entity;\r
+                                               this._product.Entity = null;\r
+                                               previousProduct.OrderDetails.Remove(this);\r
+                                       }\r
+                                       this._product.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.OrderDetails.Add(this);\r
+                                               _productID = value.ProductID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _productID = default(int);\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Association(Storage="_order", OtherKey="OrderID", ThisKey="OrderID", Name="fk_Order Details_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Order Order\r
+               {\r
+                       get\r
+                       {\r
+                               return this._order.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._order.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._order.Entity != null))\r
+                                       {\r
+                                               Order previousOrder = this._order.Entity;\r
+                                               this._order.Entity = null;\r
+                                               previousOrder.OrderDetails.Remove(this);\r
+                                       }\r
+                                       this._order.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.OrderDetails.Add(this);\r
+                                               _orderID = value.OrderID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _orderID = default(int);\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_orderID.GetHashCode() * 1));\r
+                       hc = (hc \r
+                                               | (_productID.GetHashCode() * 65536));\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       OrderDetail other = ((OrderDetail)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(OrderDetail value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return (System.Collections.Generic.EqualityComparer<int>.Default.Equals(this._orderID, value._orderID) && System.Collections.Generic.EqualityComparer<int>.Default.Equals(this._productID, value._productID));\r
+               }\r
+       }\r
+       \r
+       [Table(Name="main.Products")]\r
+       public partial class Product : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Product>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private System.Nullable<int> _categoryID;\r
+               \r
+               private bool _discontinued;\r
+               \r
+               private int _productID;\r
+               \r
+               private string _productName;\r
+               \r
+               private string _quantityPerUnit;\r
+               \r
+               private System.Nullable<short> _reorderLevel;\r
+               \r
+               private System.Nullable<int> _supplierID;\r
+               \r
+               private System.Nullable<decimal> _unitPrice;\r
+               \r
+               private System.Nullable<short> _unitsInStock;\r
+               \r
+               private System.Nullable<short> _unitsOnOrder;\r
+               \r
+               private EntitySet<OrderDetail> _orderDetails;\r
+               \r
+               private EntityRef<Supplier> _supplier = new EntityRef<Supplier>();\r
+               \r
+               private EntityRef<Category> _category = new EntityRef<Category>();\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnCategoryIDChanged();\r
+               \r
+               partial void OnCategoryIDChanging(System.Nullable<int> value);\r
+               \r
+               partial void OnDiscontinuedChanged();\r
+               \r
+               partial void OnDiscontinuedChanging(bool value);\r
+               \r
+               partial void OnProductIDChanged();\r
+               \r
+               partial void OnProductIDChanging(int value);\r
+               \r
+               partial void OnProductNameChanged();\r
+               \r
+               partial void OnProductNameChanging(string value);\r
+               \r
+               partial void OnQuantityPerUnitChanged();\r
+               \r
+               partial void OnQuantityPerUnitChanging(string value);\r
+               \r
+               partial void OnReorderLevelChanged();\r
+               \r
+               partial void OnReorderLevelChanging(System.Nullable<short> value);\r
+               \r
+               partial void OnSupplierIDChanged();\r
+               \r
+               partial void OnSupplierIDChanging(System.Nullable<int> value);\r
+               \r
+               partial void OnUnitPriceChanged();\r
+               \r
+               partial void OnUnitPriceChanging(System.Nullable<decimal> value);\r
+               \r
+               partial void OnUnitsInStockChanged();\r
+               \r
+               partial void OnUnitsInStockChanging(System.Nullable<short> value);\r
+               \r
+               partial void OnUnitsOnOrderChanged();\r
+               \r
+               partial void OnUnitsOnOrderChanging(System.Nullable<short> value);\r
+               #endregion\r
+               \r
+               \r
+               public Product()\r
+               {\r
+                       _orderDetails = new EntitySet<OrderDetail>(new Action<OrderDetail>(this.OrderDetails_Attach), new Action<OrderDetail>(this.OrderDetails_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_categoryID", Name="CategoryID", DbType="INTEGER", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<int> CategoryID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._categoryID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_categoryID != value))\r
+                               {\r
+                                       if (_category.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnCategoryIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._categoryID = value;\r
+                                       this.SendPropertyChanged("CategoryID");\r
+                                       this.OnCategoryIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_discontinued", Name="Discontinued", DbType="bit", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public bool Discontinued\r
+               {\r
+                       get\r
+                       {\r
+                               return this._discontinued;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_discontinued != value))\r
+                               {\r
+                                       this.OnDiscontinuedChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._discontinued = value;\r
+                                       this.SendPropertyChanged("Discontinued");\r
+                                       this.OnDiscontinuedChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_productID", Name="ProductID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int ProductID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._productID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_productID != value))\r
+                               {\r
+                                       this.OnProductIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._productID = value;\r
+                                       this.SendPropertyChanged("ProductID");\r
+                                       this.OnProductIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_productName", Name="ProductName", DbType="nvarchar (40)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string ProductName\r
+               {\r
+                       get\r
+                       {\r
+                               return this._productName;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_productName == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnProductNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._productName = value;\r
+                                       this.SendPropertyChanged("ProductName");\r
+                                       this.OnProductNameChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_quantityPerUnit", Name="QuantityPerUnit", DbType="nvarchar (20)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string QuantityPerUnit\r
+               {\r
+                       get\r
+                       {\r
+                               return this._quantityPerUnit;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_quantityPerUnit == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnQuantityPerUnitChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._quantityPerUnit = value;\r
+                                       this.SendPropertyChanged("QuantityPerUnit");\r
+                                       this.OnQuantityPerUnitChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_reorderLevel", Name="ReorderLevel", DbType="smallint", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<short> ReorderLevel\r
+               {\r
+                       get\r
+                       {\r
+                               return this._reorderLevel;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_reorderLevel != value))\r
+                               {\r
+                                       this.OnReorderLevelChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._reorderLevel = value;\r
+                                       this.SendPropertyChanged("ReorderLevel");\r
+                                       this.OnReorderLevelChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_supplierID", Name="SupplierID", DbType="INTEGER", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<int> SupplierID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._supplierID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_supplierID != value))\r
+                               {\r
+                                       if (_supplier.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnSupplierIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._supplierID = value;\r
+                                       this.SendPropertyChanged("SupplierID");\r
+                                       this.OnSupplierIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_unitPrice", Name="UnitPrice", DbType="money", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<decimal> UnitPrice\r
+               {\r
+                       get\r
+                       {\r
+                               return this._unitPrice;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_unitPrice != value))\r
+                               {\r
+                                       this.OnUnitPriceChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._unitPrice = value;\r
+                                       this.SendPropertyChanged("UnitPrice");\r
+                                       this.OnUnitPriceChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_unitsInStock", Name="UnitsInStock", DbType="smallint", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<short> UnitsInStock\r
+               {\r
+                       get\r
+                       {\r
+                               return this._unitsInStock;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_unitsInStock != value))\r
+                               {\r
+                                       this.OnUnitsInStockChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._unitsInStock = value;\r
+                                       this.SendPropertyChanged("UnitsInStock");\r
+                                       this.OnUnitsInStockChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_unitsOnOrder", Name="UnitsOnOrder", DbType="smallint", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<short> UnitsOnOrder\r
+               {\r
+                       get\r
+                       {\r
+                               return this._unitsOnOrder;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_unitsOnOrder != value))\r
+                               {\r
+                                       this.OnUnitsOnOrderChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._unitsOnOrder = value;\r
+                                       this.SendPropertyChanged("UnitsOnOrder");\r
+                                       this.OnUnitsOnOrderChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Children\r
+               [Association(Storage="_orderDetails", OtherKey="ProductID", ThisKey="ProductID", Name="fk_Order Details_0")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<OrderDetail> OrderDetails\r
+               {\r
+                       get\r
+                       {\r
+                               return this._orderDetails;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._orderDetails = value;\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               #region Parents\r
+               [Association(Storage="_supplier", OtherKey="SupplierID", ThisKey="SupplierID", Name="fk_Products_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Supplier Supplier\r
+               {\r
+                       get\r
+                       {\r
+                               return this._supplier.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._supplier.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._supplier.Entity != null))\r
+                                       {\r
+                                               Supplier previousSupplier = this._supplier.Entity;\r
+                                               this._supplier.Entity = null;\r
+                                               previousSupplier.Products.Remove(this);\r
+                                       }\r
+                                       this._supplier.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.Products.Add(this);\r
+                                               _supplierID = value.SupplierID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _supplierID = null;\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Association(Storage="_category", OtherKey="CategoryID", ThisKey="CategoryID", Name="fk_Products_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Category Category\r
+               {\r
+                       get\r
+                       {\r
+                               return this._category.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._category.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._category.Entity != null))\r
+                                       {\r
+                                               Category previousCategory = this._category.Entity;\r
+                                               this._category.Entity = null;\r
+                                               previousCategory.Products.Remove(this);\r
+                                       }\r
+                                       this._category.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.Products.Add(this);\r
+                                               _categoryID = value.CategoryID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _categoryID = null;\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_productID.GetHashCode() * 1));\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Product other = ((Product)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Product value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<int>.Default.Equals(this._productID, value._productID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void OrderDetails_Attach(OrderDetail entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Product = this;\r
+               }\r
+               \r
+               private void OrderDetails_Detach(OrderDetail entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Product = null;\r
+               }\r
+               #endregion\r
+       }\r
+       \r
+       [Table(Name="main.Region")]\r
+       public partial class Region : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Region>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _regionDescription;\r
+               \r
+               private int _regionID;\r
+               \r
+               private EntitySet<Territory> _territories;\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnRegionDescriptionChanged();\r
+               \r
+               partial void OnRegionDescriptionChanging(string value);\r
+               \r
+               partial void OnRegionIDChanged();\r
+               \r
+               partial void OnRegionIDChanging(int value);\r
+               #endregion\r
+               \r
+               \r
+               public Region()\r
+               {\r
+                       _territories = new EntitySet<Territory>(new Action<Territory>(this.Territories_Attach), new Action<Territory>(this.Territories_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_regionDescription", Name="RegionDescription", DbType="nchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string RegionDescription\r
+               {\r
+                       get\r
+                       {\r
+                               return this._regionDescription;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_regionDescription == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnRegionDescriptionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._regionDescription = value;\r
+                                       this.SendPropertyChanged("RegionDescription");\r
+                                       this.OnRegionDescriptionChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_regionID", Name="RegionID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int RegionID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._regionID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_regionID != value))\r
+                               {\r
+                                       this.OnRegionIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._regionID = value;\r
+                                       this.SendPropertyChanged("RegionID");\r
+                                       this.OnRegionIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Children\r
+               [Association(Storage="_territories", OtherKey="RegionID", ThisKey="RegionID", Name="fk_Territories_0")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<Territory> Territories\r
+               {\r
+                       get\r
+                       {\r
+                               return this._territories;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._territories = value;\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_regionID.GetHashCode() * 1));\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Region other = ((Region)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Region value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<int>.Default.Equals(this._regionID, value._regionID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void Territories_Attach(Territory entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Region = this;\r
+               }\r
+               \r
+               private void Territories_Detach(Territory entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Region = null;\r
+               }\r
+               #endregion\r
+       }\r
+       \r
+       [Table(Name="main.Shippers")]\r
+       public partial class Shipper : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Shipper>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _companyName;\r
+               \r
+               private string _phone;\r
+               \r
+               private int _shipperID;\r
+               \r
+               private EntitySet<Order> _orders;\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnCompanyNameChanged();\r
+               \r
+               partial void OnCompanyNameChanging(string value);\r
+               \r
+               partial void OnPhoneChanged();\r
+               \r
+               partial void OnPhoneChanging(string value);\r
+               \r
+               partial void OnShipperIDChanged();\r
+               \r
+               partial void OnShipperIDChanging(int value);\r
+               #endregion\r
+               \r
+               \r
+               public Shipper()\r
+               {\r
+                       _orders = new EntitySet<Order>(new Action<Order>(this.Orders_Attach), new Action<Order>(this.Orders_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_companyName", Name="CompanyName", DbType="nvarchar (40)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string CompanyName\r
+               {\r
+                       get\r
+                       {\r
+                               return this._companyName;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_companyName == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCompanyNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._companyName = value;\r
+                                       this.SendPropertyChanged("CompanyName");\r
+                                       this.OnCompanyNameChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_phone", Name="Phone", DbType="nvarchar (24)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Phone\r
+               {\r
+                       get\r
+                       {\r
+                               return this._phone;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_phone == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnPhoneChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._phone = value;\r
+                                       this.SendPropertyChanged("Phone");\r
+                                       this.OnPhoneChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_shipperID", Name="ShipperID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int ShipperID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._shipperID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_shipperID != value))\r
+                               {\r
+                                       this.OnShipperIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipperID = value;\r
+                                       this.SendPropertyChanged("ShipperID");\r
+                                       this.OnShipperIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Children\r
+               [Association(Storage="_orders", OtherKey="ShipVia", ThisKey="ShipperID", Name="fk_Orders_0")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<Order> Orders\r
+               {\r
+                       get\r
+                       {\r
+                               return this._orders;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._orders = value;\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_shipperID.GetHashCode() * 1));\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Shipper other = ((Shipper)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Shipper value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<int>.Default.Equals(this._shipperID, value._shipperID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void Orders_Attach(Order entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Shipper = this;\r
+               }\r
+               \r
+               private void Orders_Detach(Order entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Shipper = null;\r
+               }\r
+               #endregion\r
+       }\r
+       \r
+       [Table(Name="main.Suppliers")]\r
+       public partial class Supplier : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Supplier>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _address;\r
+               \r
+               private string _city;\r
+               \r
+               private string _companyName;\r
+               \r
+               private string _contactName;\r
+               \r
+               private string _contactTitle;\r
+               \r
+               private string _country;\r
+               \r
+               private string _fax;\r
+               \r
+               private string _homePage;\r
+               \r
+               private string _phone;\r
+               \r
+               private string _postalCode;\r
+               \r
+               private string _region;\r
+               \r
+               private int _supplierID;\r
+               \r
+               private EntitySet<Product> _products;\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnAddressChanged();\r
+               \r
+               partial void OnAddressChanging(string value);\r
+               \r
+               partial void OnCityChanged();\r
+               \r
+               partial void OnCityChanging(string value);\r
+               \r
+               partial void OnCompanyNameChanged();\r
+               \r
+               partial void OnCompanyNameChanging(string value);\r
+               \r
+               partial void OnContactNameChanged();\r
+               \r
+               partial void OnContactNameChanging(string value);\r
+               \r
+               partial void OnContactTitleChanged();\r
+               \r
+               partial void OnContactTitleChanging(string value);\r
+               \r
+               partial void OnCountryChanged();\r
+               \r
+               partial void OnCountryChanging(string value);\r
+               \r
+               partial void OnFaxChanged();\r
+               \r
+               partial void OnFaxChanging(string value);\r
+               \r
+               partial void OnHomePageChanged();\r
+               \r
+               partial void OnHomePageChanging(string value);\r
+               \r
+               partial void OnPhoneChanged();\r
+               \r
+               partial void OnPhoneChanging(string value);\r
+               \r
+               partial void OnPostalCodeChanged();\r
+               \r
+               partial void OnPostalCodeChanging(string value);\r
+               \r
+               partial void OnRegionChanged();\r
+               \r
+               partial void OnRegionChanging(string value);\r
+               \r
+               partial void OnSupplierIDChanged();\r
+               \r
+               partial void OnSupplierIDChanging(int value);\r
+               #endregion\r
+               \r
+               \r
+               public Supplier()\r
+               {\r
+                       _products = new EntitySet<Product>(new Action<Product>(this.Products_Attach), new Action<Product>(this.Products_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_address", Name="Address", DbType="nvarchar (60)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Address\r
+               {\r
+                       get\r
+                       {\r
+                               return this._address;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_address == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnAddressChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._address = value;\r
+                                       this.SendPropertyChanged("Address");\r
+                                       this.OnAddressChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_city", Name="City", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string City\r
+               {\r
+                       get\r
+                       {\r
+                               return this._city;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_city == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._city = value;\r
+                                       this.SendPropertyChanged("City");\r
+                                       this.OnCityChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_companyName", Name="CompanyName", DbType="nvarchar (40)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string CompanyName\r
+               {\r
+                       get\r
+                       {\r
+                               return this._companyName;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_companyName == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCompanyNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._companyName = value;\r
+                                       this.SendPropertyChanged("CompanyName");\r
+                                       this.OnCompanyNameChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_contactName", Name="ContactName", DbType="nvarchar (30)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string ContactName\r
+               {\r
+                       get\r
+                       {\r
+                               return this._contactName;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_contactName == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnContactNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._contactName = value;\r
+                                       this.SendPropertyChanged("ContactName");\r
+                                       this.OnContactNameChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_contactTitle", Name="ContactTitle", DbType="nvarchar (30)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string ContactTitle\r
+               {\r
+                       get\r
+                       {\r
+                               return this._contactTitle;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_contactTitle == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnContactTitleChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._contactTitle = value;\r
+                                       this.SendPropertyChanged("ContactTitle");\r
+                                       this.OnContactTitleChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_country", Name="Country", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Country\r
+               {\r
+                       get\r
+                       {\r
+                               return this._country;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_country == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCountryChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._country = value;\r
+                                       this.SendPropertyChanged("Country");\r
+                                       this.OnCountryChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_fax", Name="Fax", DbType="nvarchar (24)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Fax\r
+               {\r
+                       get\r
+                       {\r
+                               return this._fax;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_fax == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnFaxChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._fax = value;\r
+                                       this.SendPropertyChanged("Fax");\r
+                                       this.OnFaxChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_homePage", Name="HomePage", DbType="ntext", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string HomePage\r
+               {\r
+                       get\r
+                       {\r
+                               return this._homePage;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_homePage == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnHomePageChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._homePage = value;\r
+                                       this.SendPropertyChanged("HomePage");\r
+                                       this.OnHomePageChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_phone", Name="Phone", DbType="nvarchar (24)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Phone\r
+               {\r
+                       get\r
+                       {\r
+                               return this._phone;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_phone == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnPhoneChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._phone = value;\r
+                                       this.SendPropertyChanged("Phone");\r
+                                       this.OnPhoneChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_postalCode", Name="PostalCode", DbType="nvarchar (10)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string PostalCode\r
+               {\r
+                       get\r
+                       {\r
+                               return this._postalCode;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_postalCode == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnPostalCodeChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._postalCode = value;\r
+                                       this.SendPropertyChanged("PostalCode");\r
+                                       this.OnPostalCodeChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_region", Name="Region", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Region\r
+               {\r
+                       get\r
+                       {\r
+                               return this._region;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_region == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnRegionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._region = value;\r
+                                       this.SendPropertyChanged("Region");\r
+                                       this.OnRegionChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_supplierID", Name="SupplierID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int SupplierID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._supplierID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_supplierID != value))\r
+                               {\r
+                                       this.OnSupplierIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._supplierID = value;\r
+                                       this.SendPropertyChanged("SupplierID");\r
+                                       this.OnSupplierIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Children\r
+               [Association(Storage="_products", OtherKey="SupplierID", ThisKey="SupplierID", Name="fk_Products_0")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<Product> Products\r
+               {\r
+                       get\r
+                       {\r
+                               return this._products;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._products = value;\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_supplierID.GetHashCode() * 1));\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Supplier other = ((Supplier)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Supplier value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<int>.Default.Equals(this._supplierID, value._supplierID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void Products_Attach(Product entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Supplier = this;\r
+               }\r
+               \r
+               private void Products_Detach(Product entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Supplier = null;\r
+               }\r
+               #endregion\r
+       }\r
+       \r
+       [Table(Name="main.Territories")]\r
+       public partial class Territory : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Territory>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private int _regionID;\r
+               \r
+               private string _territoryDescription;\r
+               \r
+               private string _territoryID;\r
+               \r
+               private EntitySet<EmployeeTerritory> _employeeTerritories;\r
+               \r
+               private EntityRef<Region> _region = new EntityRef<Region>();\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnRegionIDChanged();\r
+               \r
+               partial void OnRegionIDChanging(int value);\r
+               \r
+               partial void OnTerritoryDescriptionChanged();\r
+               \r
+               partial void OnTerritoryDescriptionChanging(string value);\r
+               \r
+               partial void OnTerritoryIDChanged();\r
+               \r
+               partial void OnTerritoryIDChanging(string value);\r
+               #endregion\r
+               \r
+               \r
+               public Territory()\r
+               {\r
+                       _employeeTerritories = new EntitySet<EmployeeTerritory>(new Action<EmployeeTerritory>(this.EmployeeTerritories_Attach), new Action<EmployeeTerritory>(this.EmployeeTerritories_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_regionID", Name="RegionID", DbType="INTEGER", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int RegionID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._regionID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_regionID != value))\r
+                               {\r
+                                       if (_region.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnRegionIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._regionID = value;\r
+                                       this.SendPropertyChanged("RegionID");\r
+                                       this.OnRegionIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_territoryDescription", Name="TerritoryDescription", DbType="nchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string TerritoryDescription\r
+               {\r
+                       get\r
+                       {\r
+                               return this._territoryDescription;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_territoryDescription == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnTerritoryDescriptionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._territoryDescription = value;\r
+                                       this.SendPropertyChanged("TerritoryDescription");\r
+                                       this.OnTerritoryDescriptionChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_territoryID", Name="TerritoryID", DbType="nvarchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string TerritoryID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._territoryID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_territoryID == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnTerritoryIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._territoryID = value;\r
+                                       this.SendPropertyChanged("TerritoryID");\r
+                                       this.OnTerritoryIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Children\r
+               [Association(Storage="_employeeTerritories", OtherKey="TerritoryID", ThisKey="TerritoryID", Name="fk_EmployeeTerritories_0")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<EmployeeTerritory> EmployeeTerritories\r
+               {\r
+                       get\r
+                       {\r
+                               return this._employeeTerritories;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._employeeTerritories = value;\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               #region Parents\r
+               [Association(Storage="_region", OtherKey="RegionID", ThisKey="RegionID", Name="fk_Territories_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Region Region\r
+               {\r
+                       get\r
+                       {\r
+                               return this._region.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._region.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._region.Entity != null))\r
+                                       {\r
+                                               Region previousRegion = this._region.Entity;\r
+                                               this._region.Entity = null;\r
+                                               previousRegion.Territories.Remove(this);\r
+                                       }\r
+                                       this._region.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.Territories.Add(this);\r
+                                               _regionID = value.RegionID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _regionID = default(int);\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       if ((_territoryID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_territoryID.GetHashCode() * 1));\r
+                       }\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Territory other = ((Territory)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Territory value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._territoryID, value._territoryID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void EmployeeTerritories_Attach(EmployeeTerritory entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Territory = this;\r
+               }\r
+               \r
+               private void EmployeeTerritories_Detach(EmployeeTerritory entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Territory = null;\r
+               }\r
+               #endregion\r
+       }\r
+}\r
diff --git a/mcs/class/System.Data.Linq/tests/expected/Northwind.Sqlite-DbMetal.dbml b/mcs/class/System.Data.Linq/tests/expected/Northwind.Sqlite-DbMetal.dbml
new file mode 100755 (executable)
index 0000000..41249a0
--- /dev/null
@@ -0,0 +1,169 @@
+<?xml version="1.0"?>\r
+<Database xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Name="main" Class="Main" BaseType="DbLinq.Data.Linq.DataContext" Provider="Sqlite" xmlns="http://schemas.microsoft.com/linqtosql/dbml/2007">\r
+  <Table Name="main.Categories" Member="Categories">\r
+    <Type Name="Categories">\r
+      <Association Name="fk_Products_1" Member="Products" Storage="_products" Type="Products" ThisKey="CategoryID" OtherKey="CategoryID" DeleteRule="NO ACTION" />\r
+      <Column Name="CategoryID" Member="CategoryID" Storage="_categoryID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="CategoryName" Member="CategoryName" Storage="_categoryName" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="Description" Member="Description" Storage="_description" Type="System.String" DbType="ntext" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Picture" Member="Picture" Storage="_picture" Type="System.Byte[]" DbType="image" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.CustomerCustomerDemo" Member="CustomerCustomerDemo">\r
+    <Type Name="CustomerCustomerDemo">\r
+      <Association Name="fk_CustomerCustomerDemo_0" Member="Customers" Storage="_customers" Type="Customers" ThisKey="CustomerID" OtherKey="CustomerID" IsForeignKey="true" />\r
+      <Association Name="fk_CustomerCustomerDemo_1" Member="CustomerDemographics" Storage="_customerDemographics" Type="CustomerDemographics" ThisKey="CustomerTypeID" OtherKey="CustomerTypeID" IsForeignKey="true" />\r
+      <Column Name="CustomerID" Member="CustomerID" Storage="_customerID" Type="System.String" DbType="nchar (5)" IsPrimaryKey="true" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="CustomerTypeID" Member="CustomerTypeID" Storage="_customerTypeID" Type="System.String" DbType="nchar" IsPrimaryKey="true" IsDbGenerated="false" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.CustomerDemographics" Member="CustomerDemographics">\r
+    <Type Name="CustomerDemographics">\r
+      <Association Name="fk_CustomerCustomerDemo_1" Member="CustomerCustomerDemo" Storage="_customerCustomerDemo" Type="CustomerCustomerDemo" ThisKey="CustomerTypeID" OtherKey="CustomerTypeID" DeleteRule="NO ACTION" />\r
+      <Column Name="CustomerDesc" Member="CustomerDesc" Storage="_customerDesc" Type="System.String" DbType="ntext" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="CustomerTypeID" Member="CustomerTypeID" Storage="_customerTypeID" Type="System.String" DbType="nchar" IsPrimaryKey="true" IsDbGenerated="false" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.Customers" Member="Customers">\r
+    <Type Name="Customers">\r
+      <Association Name="fk_CustomerCustomerDemo_0" Member="CustomerCustomerDemo" Storage="_customerCustomerDemo" Type="CustomerCustomerDemo" ThisKey="CustomerID" OtherKey="CustomerID" DeleteRule="NO ACTION" />\r
+      <Association Name="fk_Orders_2" Member="Orders" Storage="_orders" Type="Orders" ThisKey="CustomerID" OtherKey="CustomerID" DeleteRule="NO ACTION" />\r
+      <Column Name="Address" Member="Address" Storage="_address" Type="System.String" DbType="nvarchar (60)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="City" Member="City" Storage="_city" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="CompanyName" Member="CompanyName" Storage="_companyName" Type="System.String" DbType="nvarchar (40)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="ContactName" Member="ContactName" Storage="_contactName" Type="System.String" DbType="nvarchar (30)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ContactTitle" Member="ContactTitle" Storage="_contactTitle" Type="System.String" DbType="nvarchar (30)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Country" Member="Country" Storage="_country" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="CustomerID" Member="CustomerID" Storage="_customerID" Type="System.String" DbType="nchar (5)" IsPrimaryKey="true" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="Fax" Member="Fax" Storage="_fax" Type="System.String" DbType="nvarchar (24)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Phone" Member="Phone" Storage="_phone" Type="System.String" DbType="nvarchar (24)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="PostalCode" Member="PostalCode" Storage="_postalCode" Type="System.String" DbType="nvarchar (10)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Region" Member="Region" Storage="_region" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.Employees" Member="Employees">\r
+    <Type Name="Employees">\r
+      <Association Name="fk_EmployeeTerritories_1" Member="EmployeeTerritories" Storage="_employeeTerritories" Type="EmployeeTerritories" ThisKey="EmployeeID" OtherKey="EmployeeID" DeleteRule="NO ACTION" />\r
+      <Association Name="fk_Employees_0" Member="ReportsToEmployees" Storage="_reportsToEmployees" Type="Employees" ThisKey="ReportsTo" OtherKey="EmployeeID" IsForeignKey="true" />\r
+      <Association Name="fk_Employees_0" Member="EmployeeIDEmployees" Storage="_employeeIdeMployees" Type="Employees" ThisKey="EmployeeID" OtherKey="ReportsTo" DeleteRule="NO ACTION" />\r
+      <Association Name="fk_Orders_1" Member="Orders" Storage="_orders" Type="Orders" ThisKey="EmployeeID" OtherKey="EmployeeID" DeleteRule="NO ACTION" />\r
+      <Column Name="Address" Member="Address" Storage="_address" Type="System.String" DbType="nvarchar (60)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="BirthDate" Member="BirthDate" Storage="_birthDate" Type="System.DateTime" DbType="datetime" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="City" Member="City" Storage="_city" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Country" Member="Country" Storage="_country" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="EmployeeID" Member="EmployeeID" Storage="_employeeID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="Extension" Member="Extension" Storage="_extension" Type="System.String" DbType="nvarchar (4)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="FirstName" Member="FirstName" Storage="_firstName" Type="System.String" DbType="nvarchar (10)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="HireDate" Member="HireDate" Storage="_hireDate" Type="System.DateTime" DbType="datetime" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="HomePhone" Member="HomePhone" Storage="_homePhone" Type="System.String" DbType="nvarchar (24)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="LastName" Member="LastName" Storage="_lastName" Type="System.String" DbType="nvarchar (20)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="Notes" Member="Notes" Storage="_notes" Type="System.String" DbType="ntext" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Photo" Member="Photo" Storage="_photo" Type="System.Byte[]" DbType="image" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="PhotoPath" Member="PhotoPath" Storage="_photoPath" Type="System.String" DbType="nvarchar (255)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="PostalCode" Member="PostalCode" Storage="_postalCode" Type="System.String" DbType="nvarchar (10)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Region" Member="Region" Storage="_region" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ReportsTo" Member="ReportsTo" Storage="_reportsTo" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Title" Member="Title" Storage="_title" Type="System.String" DbType="nvarchar (30)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="TitleOfCourtesy" Member="TitleOfCourtesy" Storage="_titleOfCourtesy" Type="System.String" DbType="nvarchar (25)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.EmployeeTerritories" Member="EmployeeTerritories">\r
+    <Type Name="EmployeeTerritories">\r
+      <Association Name="fk_EmployeeTerritories_0" Member="Territories" Storage="_territories" Type="Territories" ThisKey="TerritoryID" OtherKey="TerritoryID" IsForeignKey="true" />\r
+      <Association Name="fk_EmployeeTerritories_1" Member="Employees" Storage="_employees" Type="Employees" ThisKey="EmployeeID" OtherKey="EmployeeID" IsForeignKey="true" />\r
+      <Column Name="EmployeeID" Member="EmployeeID" Storage="_employeeID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="TerritoryID" Member="TerritoryID" Storage="_territoryID" Type="System.String" DbType="nvarchar" IsPrimaryKey="true" IsDbGenerated="false" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.Order Details" Member="OrderDetails">\r
+    <Type Name="OrderDetails">\r
+      <Association Name="fk_Order Details_0" Member="Products" Storage="_products" Type="Products" ThisKey="ProductID" OtherKey="ProductID" IsForeignKey="true" />\r
+      <Association Name="fk_Order Details_1" Member="Orders" Storage="_orders" Type="Orders" ThisKey="OrderID" OtherKey="OrderID" IsForeignKey="true" />\r
+      <Column Name="Discount" Member="Discount" Storage="_discount" Type="System.Single" DbType="real" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="OrderID" Member="OrderID" Storage="_orderID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="ProductID" Member="ProductID" Storage="_productID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="Quantity" Member="Quantity" Storage="_quantity" Type="System.Int16" DbType="smallint" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="UnitPrice" Member="UnitPrice" Storage="_unitPrice" Type="System.Decimal" DbType="money" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.Orders" Member="Orders">\r
+    <Type Name="Orders">\r
+      <Association Name="fk_Order Details_1" Member="OrderDetails" Storage="_orderDetails" Type="OrderDetails" ThisKey="OrderID" OtherKey="OrderID" DeleteRule="NO ACTION" />\r
+      <Association Name="fk_Orders_0" Member="Shippers" Storage="_shippers" Type="Shippers" ThisKey="ShipVia" OtherKey="ShipperID" IsForeignKey="true" />\r
+      <Association Name="fk_Orders_1" Member="Employees" Storage="_employees" Type="Employees" ThisKey="EmployeeID" OtherKey="EmployeeID" IsForeignKey="true" />\r
+      <Association Name="fk_Orders_2" Member="Customers" Storage="_customers" Type="Customers" ThisKey="CustomerID" OtherKey="CustomerID" IsForeignKey="true" />\r
+      <Column Name="CustomerID" Member="CustomerID" Storage="_customerID" Type="System.String" DbType="nchar (5)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="EmployeeID" Member="EmployeeID" Storage="_employeeID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Freight" Member="Freight" Storage="_freight" Type="System.Decimal" DbType="money" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="OrderDate" Member="OrderDate" Storage="_orderDate" Type="System.DateTime" DbType="datetime" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="OrderID" Member="OrderID" Storage="_orderID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="RequiredDate" Member="RequiredDate" Storage="_requiredDate" Type="System.DateTime" DbType="datetime" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ShipAddress" Member="ShipAddress" Storage="_shipAddress" Type="System.String" DbType="nvarchar (60)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ShipCity" Member="ShipCity" Storage="_shipCity" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ShipCountry" Member="ShipCountry" Storage="_shipCountry" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ShipName" Member="ShipName" Storage="_shipName" Type="System.String" DbType="nvarchar (40)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ShippedDate" Member="ShippedDate" Storage="_shippedDate" Type="System.DateTime" DbType="datetime" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ShipPostalCode" Member="ShipPostalCode" Storage="_shipPostalCode" Type="System.String" DbType="nvarchar (10)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ShipRegion" Member="ShipRegion" Storage="_shipRegion" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ShipVia" Member="ShipVia" Storage="_shipVia" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.Products" Member="Products">\r
+    <Type Name="Products">\r
+      <Association Name="fk_Order Details_0" Member="OrderDetails" Storage="_orderDetails" Type="OrderDetails" ThisKey="ProductID" OtherKey="ProductID" DeleteRule="NO ACTION" />\r
+      <Association Name="fk_Products_0" Member="Suppliers" Storage="_suppliers" Type="Suppliers" ThisKey="SupplierID" OtherKey="SupplierID" IsForeignKey="true" />\r
+      <Association Name="fk_Products_1" Member="Categories" Storage="_categories" Type="Categories" ThisKey="CategoryID" OtherKey="CategoryID" IsForeignKey="true" />\r
+      <Column Name="CategoryID" Member="CategoryID" Storage="_categoryID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Discontinued" Member="Discontinued" Storage="_discontinued" Type="System.Boolean" DbType="bit" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="ProductID" Member="ProductID" Storage="_productID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="ProductName" Member="ProductName" Storage="_productName" Type="System.String" DbType="nvarchar (40)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="QuantityPerUnit" Member="QuantityPerUnit" Storage="_quantityPerUnit" Type="System.String" DbType="nvarchar (20)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ReorderLevel" Member="ReorderLevel" Storage="_reorderLevel" Type="System.Int16" DbType="smallint" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="SupplierID" Member="SupplierID" Storage="_supplierID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="UnitPrice" Member="UnitPrice" Storage="_unitPrice" Type="System.Decimal" DbType="money" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="UnitsInStock" Member="UnitsInStock" Storage="_unitsInStock" Type="System.Int16" DbType="smallint" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="UnitsOnOrder" Member="UnitsOnOrder" Storage="_unitsOnOrder" Type="System.Int16" DbType="smallint" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.Region" Member="Region">\r
+    <Type Name="Region">\r
+      <Association Name="fk_Territories_0" Member="Territories" Storage="_territories" Type="Territories" ThisKey="RegionID" OtherKey="RegionID" DeleteRule="NO ACTION" />\r
+      <Column Name="RegionDescription" Member="RegionDescription" Storage="_regionDescription" Type="System.String" DbType="nchar" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="RegionID" Member="RegionID" Storage="_regionID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.Shippers" Member="Shippers">\r
+    <Type Name="Shippers">\r
+      <Association Name="fk_Orders_0" Member="Orders" Storage="_orders" Type="Orders" ThisKey="ShipperID" OtherKey="ShipVia" DeleteRule="NO ACTION" />\r
+      <Column Name="CompanyName" Member="CompanyName" Storage="_companyName" Type="System.String" DbType="nvarchar (40)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="Phone" Member="Phone" Storage="_phone" Type="System.String" DbType="nvarchar (24)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ShipperID" Member="ShipperID" Storage="_shipperID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.Suppliers" Member="Suppliers">\r
+    <Type Name="Suppliers">\r
+      <Association Name="fk_Products_0" Member="Products" Storage="_products" Type="Products" ThisKey="SupplierID" OtherKey="SupplierID" DeleteRule="NO ACTION" />\r
+      <Column Name="Address" Member="Address" Storage="_address" Type="System.String" DbType="nvarchar (60)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="City" Member="City" Storage="_city" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="CompanyName" Member="CompanyName" Storage="_companyName" Type="System.String" DbType="nvarchar (40)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="ContactName" Member="ContactName" Storage="_contactName" Type="System.String" DbType="nvarchar (30)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ContactTitle" Member="ContactTitle" Storage="_contactTitle" Type="System.String" DbType="nvarchar (30)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Country" Member="Country" Storage="_country" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Fax" Member="Fax" Storage="_fax" Type="System.String" DbType="nvarchar (24)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="HomePage" Member="HomePage" Storage="_homePage" Type="System.String" DbType="ntext" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Phone" Member="Phone" Storage="_phone" Type="System.String" DbType="nvarchar (24)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="PostalCode" Member="PostalCode" Storage="_postalCode" Type="System.String" DbType="nvarchar (10)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Region" Member="Region" Storage="_region" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="SupplierID" Member="SupplierID" Storage="_supplierID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.Territories" Member="Territories">\r
+    <Type Name="Territories">\r
+      <Association Name="fk_EmployeeTerritories_0" Member="EmployeeTerritories" Storage="_employeeTerritories" Type="EmployeeTerritories" ThisKey="TerritoryID" OtherKey="TerritoryID" DeleteRule="NO ACTION" />\r
+      <Association Name="fk_Territories_0" Member="Region" Storage="_region" Type="Region" ThisKey="RegionID" OtherKey="RegionID" IsForeignKey="true" />\r
+      <Column Name="RegionID" Member="RegionID" Storage="_regionID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="TerritoryDescription" Member="TerritoryDescription" Storage="_territoryDescription" Type="System.String" DbType="nchar" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="TerritoryID" Member="TerritoryID" Storage="_territoryID" Type="System.String" DbType="nvarchar" IsPrimaryKey="true" IsDbGenerated="false" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+</Database>
\ No newline at end of file
diff --git a/mcs/class/System.Data.Linq/tests/expected/Northwind.Sqlite-sqlmetal.cs b/mcs/class/System.Data.Linq/tests/expected/Northwind.Sqlite-sqlmetal.cs
new file mode 100755 (executable)
index 0000000..53472a0
--- /dev/null
@@ -0,0 +1,4476 @@
+// \r
+//  ____  _     __  __      _        _ \r
+// |  _ \| |__ |  \/  | ___| |_ __ _| |\r
+// | | | | '_ \| |\/| |/ _ \ __/ _` | |\r
+// | |_| | |_) | |  | |  __/ || (_| | |\r
+// |____/|_.__/|_|  |_|\___|\__\__,_|_|\r
+//\r
+// Auto-generated from Northwind on [TIMESTAMP].\r
+// Please visit http://code.google.com/p/dblinq2007/ for more information.\r
+//\r
+namespace nwind\r
+{\r
+       using System;\r
+       using System.ComponentModel;\r
+       using System.Data;\r
+       using System.Data.Linq;\r
+       using System.Data.Linq.Mapping;\r
+       using System.Diagnostics;\r
+       \r
+       \r
+       public partial class Northwind : DataContext\r
+       {\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               #endregion\r
+               \r
+               \r
+               public Northwind(string connectionString) : \r
+                               base(connectionString)\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               public Northwind(IDbConnection connection) : \r
+                               base(connection)\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               public Northwind(string connection, MappingSource mappingSource) : \r
+                               base(connection, mappingSource)\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               public Northwind(IDbConnection connection, MappingSource mappingSource) : \r
+                               base(connection, mappingSource)\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               public Table<Category> Categories\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Category>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Customer> Customers\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Customer>();\r
+                       }\r
+               }\r
+               \r
+               public Table<CustomerCustomerDemo> CustomerCustomerDemo\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<CustomerCustomerDemo>();\r
+                       }\r
+               }\r
+               \r
+               public Table<CustomerDemographic> CustomerDemographics\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<CustomerDemographic>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Employee> Employees\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Employee>();\r
+                       }\r
+               }\r
+               \r
+               public Table<EmployeeTerritory> EmployeeTerritories\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<EmployeeTerritory>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Order> Orders\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Order>();\r
+                       }\r
+               }\r
+               \r
+               public Table<OrderDetail> OrderDetails\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<OrderDetail>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Product> Products\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Product>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Region> Regions\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Region>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Shipper> Shippers\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Shipper>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Supplier> Suppliers\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Supplier>();\r
+                       }\r
+               }\r
+               \r
+               public Table<Territory> Territories\r
+               {\r
+                       get\r
+                       {\r
+                               return this.GetTable<Territory>();\r
+                       }\r
+               }\r
+       }\r
+       \r
+       [Table(Name="main.Categories")]\r
+       public partial class Category : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Category>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private int _categoryID;\r
+               \r
+               private string _categoryName;\r
+               \r
+               private string _description;\r
+               \r
+               private byte[] _picture;\r
+               \r
+               private EntitySet<Product> _products;\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnCategoryIDChanged();\r
+               \r
+               partial void OnCategoryIDChanging(int value);\r
+               \r
+               partial void OnCategoryNameChanged();\r
+               \r
+               partial void OnCategoryNameChanging(string value);\r
+               \r
+               partial void OnDescriptionChanged();\r
+               \r
+               partial void OnDescriptionChanging(string value);\r
+               \r
+               partial void OnPictureChanged();\r
+               \r
+               partial void OnPictureChanging(byte[] value);\r
+               #endregion\r
+               \r
+               \r
+               public Category()\r
+               {\r
+                       _products = new EntitySet<Product>(new Action<Product>(this.Products_Attach), new Action<Product>(this.Products_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_categoryID", Name="CategoryID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int CategoryID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._categoryID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_categoryID != value))\r
+                               {\r
+                                       this.OnCategoryIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._categoryID = value;\r
+                                       this.SendPropertyChanged("CategoryID");\r
+                                       this.OnCategoryIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_categoryName", Name="CategoryName", DbType="nvarchar (15)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string CategoryName\r
+               {\r
+                       get\r
+                       {\r
+                               return this._categoryName;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_categoryName == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCategoryNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._categoryName = value;\r
+                                       this.SendPropertyChanged("CategoryName");\r
+                                       this.OnCategoryNameChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_description", Name="Description", DbType="ntext", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Description\r
+               {\r
+                       get\r
+                       {\r
+                               return this._description;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_description == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnDescriptionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._description = value;\r
+                                       this.SendPropertyChanged("Description");\r
+                                       this.OnDescriptionChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_picture", Name="Picture", DbType="image", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public byte[] Picture\r
+               {\r
+                       get\r
+                       {\r
+                               return this._picture;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_picture == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnPictureChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._picture = value;\r
+                                       this.SendPropertyChanged("Picture");\r
+                                       this.OnPictureChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Children\r
+               [Association(Storage="_products", OtherKey="CategoryID", ThisKey="CategoryID", Name="fk_Products_1")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<Product> Products\r
+               {\r
+                       get\r
+                       {\r
+                               return this._products;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._products = value;\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_categoryID.GetHashCode() * 1));\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Category other = ((Category)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Category value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<int>.Default.Equals(this._categoryID, value._categoryID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void Products_Attach(Product entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Category = this;\r
+               }\r
+               \r
+               private void Products_Detach(Product entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Category = null;\r
+               }\r
+               #endregion\r
+       }\r
+       \r
+       [Table(Name="main.Customers")]\r
+       public partial class Customer : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Customer>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _address;\r
+               \r
+               private string _city;\r
+               \r
+               private string _companyName;\r
+               \r
+               private string _contactName;\r
+               \r
+               private string _contactTitle;\r
+               \r
+               private string _country;\r
+               \r
+               private string _customerID;\r
+               \r
+               private string _fax;\r
+               \r
+               private string _phone;\r
+               \r
+               private string _postalCode;\r
+               \r
+               private string _region;\r
+               \r
+               private EntitySet<CustomerCustomerDemo> _customerCustomerDemo;\r
+               \r
+               private EntitySet<Order> _orders;\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnAddressChanged();\r
+               \r
+               partial void OnAddressChanging(string value);\r
+               \r
+               partial void OnCityChanged();\r
+               \r
+               partial void OnCityChanging(string value);\r
+               \r
+               partial void OnCompanyNameChanged();\r
+               \r
+               partial void OnCompanyNameChanging(string value);\r
+               \r
+               partial void OnContactNameChanged();\r
+               \r
+               partial void OnContactNameChanging(string value);\r
+               \r
+               partial void OnContactTitleChanged();\r
+               \r
+               partial void OnContactTitleChanging(string value);\r
+               \r
+               partial void OnCountryChanged();\r
+               \r
+               partial void OnCountryChanging(string value);\r
+               \r
+               partial void OnCustomerIDChanged();\r
+               \r
+               partial void OnCustomerIDChanging(string value);\r
+               \r
+               partial void OnFaxChanged();\r
+               \r
+               partial void OnFaxChanging(string value);\r
+               \r
+               partial void OnPhoneChanged();\r
+               \r
+               partial void OnPhoneChanging(string value);\r
+               \r
+               partial void OnPostalCodeChanged();\r
+               \r
+               partial void OnPostalCodeChanging(string value);\r
+               \r
+               partial void OnRegionChanged();\r
+               \r
+               partial void OnRegionChanging(string value);\r
+               #endregion\r
+               \r
+               \r
+               public Customer()\r
+               {\r
+                       _customerCustomerDemo = new EntitySet<CustomerCustomerDemo>(new Action<CustomerCustomerDemo>(this.CustomerCustomerDemo_Attach), new Action<CustomerCustomerDemo>(this.CustomerCustomerDemo_Detach));\r
+                       _orders = new EntitySet<Order>(new Action<Order>(this.Orders_Attach), new Action<Order>(this.Orders_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_address", Name="Address", DbType="nvarchar (60)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Address\r
+               {\r
+                       get\r
+                       {\r
+                               return this._address;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_address == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnAddressChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._address = value;\r
+                                       this.SendPropertyChanged("Address");\r
+                                       this.OnAddressChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_city", Name="City", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string City\r
+               {\r
+                       get\r
+                       {\r
+                               return this._city;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_city == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._city = value;\r
+                                       this.SendPropertyChanged("City");\r
+                                       this.OnCityChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_companyName", Name="CompanyName", DbType="nvarchar (40)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string CompanyName\r
+               {\r
+                       get\r
+                       {\r
+                               return this._companyName;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_companyName == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCompanyNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._companyName = value;\r
+                                       this.SendPropertyChanged("CompanyName");\r
+                                       this.OnCompanyNameChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_contactName", Name="ContactName", DbType="nvarchar (30)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string ContactName\r
+               {\r
+                       get\r
+                       {\r
+                               return this._contactName;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_contactName == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnContactNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._contactName = value;\r
+                                       this.SendPropertyChanged("ContactName");\r
+                                       this.OnContactNameChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_contactTitle", Name="ContactTitle", DbType="nvarchar (30)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string ContactTitle\r
+               {\r
+                       get\r
+                       {\r
+                               return this._contactTitle;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_contactTitle == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnContactTitleChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._contactTitle = value;\r
+                                       this.SendPropertyChanged("ContactTitle");\r
+                                       this.OnContactTitleChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_country", Name="Country", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Country\r
+               {\r
+                       get\r
+                       {\r
+                               return this._country;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_country == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCountryChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._country = value;\r
+                                       this.SendPropertyChanged("Country");\r
+                                       this.OnCountryChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_customerID", Name="CustomerID", DbType="nchar (5)", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string CustomerID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customerID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_customerID == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCustomerIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerID = value;\r
+                                       this.SendPropertyChanged("CustomerID");\r
+                                       this.OnCustomerIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_fax", Name="Fax", DbType="nvarchar (24)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Fax\r
+               {\r
+                       get\r
+                       {\r
+                               return this._fax;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_fax == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnFaxChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._fax = value;\r
+                                       this.SendPropertyChanged("Fax");\r
+                                       this.OnFaxChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_phone", Name="Phone", DbType="nvarchar (24)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Phone\r
+               {\r
+                       get\r
+                       {\r
+                               return this._phone;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_phone == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnPhoneChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._phone = value;\r
+                                       this.SendPropertyChanged("Phone");\r
+                                       this.OnPhoneChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_postalCode", Name="PostalCode", DbType="nvarchar (10)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string PostalCode\r
+               {\r
+                       get\r
+                       {\r
+                               return this._postalCode;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_postalCode == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnPostalCodeChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._postalCode = value;\r
+                                       this.SendPropertyChanged("PostalCode");\r
+                                       this.OnPostalCodeChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_region", Name="Region", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Region\r
+               {\r
+                       get\r
+                       {\r
+                               return this._region;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_region == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnRegionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._region = value;\r
+                                       this.SendPropertyChanged("Region");\r
+                                       this.OnRegionChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Children\r
+               [Association(Storage="_customerCustomerDemo", OtherKey="CustomerID", ThisKey="CustomerID", Name="fk_CustomerCustomerDemo_0")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<CustomerCustomerDemo> CustomerCustomerDemo\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customerCustomerDemo;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._customerCustomerDemo = value;\r
+                       }\r
+               }\r
+               \r
+               [Association(Storage="_orders", OtherKey="CustomerID", ThisKey="CustomerID", Name="fk_Orders_2")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<Order> Orders\r
+               {\r
+                       get\r
+                       {\r
+                               return this._orders;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._orders = value;\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       if ((_customerID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_customerID.GetHashCode() * 1));\r
+                       }\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Customer other = ((Customer)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Customer value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._customerID, value._customerID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void CustomerCustomerDemo_Attach(CustomerCustomerDemo entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Customer = this;\r
+               }\r
+               \r
+               private void CustomerCustomerDemo_Detach(CustomerCustomerDemo entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Customer = null;\r
+               }\r
+               \r
+               private void Orders_Attach(Order entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Customer = this;\r
+               }\r
+               \r
+               private void Orders_Detach(Order entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Customer = null;\r
+               }\r
+               #endregion\r
+       }\r
+       \r
+       [Table(Name="main.CustomerCustomerDemo")]\r
+       public partial class CustomerCustomerDemo : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<CustomerCustomerDemo>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _customerID;\r
+               \r
+               private string _customerTypeID;\r
+               \r
+               private EntityRef<Customer> _customer = new EntityRef<Customer>();\r
+               \r
+               private EntityRef<CustomerDemographic> _customerDemographic = new EntityRef<CustomerDemographic>();\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnCustomerIDChanged();\r
+               \r
+               partial void OnCustomerIDChanging(string value);\r
+               \r
+               partial void OnCustomerTypeIDChanged();\r
+               \r
+               partial void OnCustomerTypeIDChanging(string value);\r
+               #endregion\r
+               \r
+               \r
+               public CustomerCustomerDemo()\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_customerID", Name="CustomerID", DbType="nchar (5)", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string CustomerID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customerID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_customerID == value) \r
+                                                       == false))\r
+                               {\r
+                                       if (_customer.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnCustomerIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerID = value;\r
+                                       this.SendPropertyChanged("CustomerID");\r
+                                       this.OnCustomerIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_customerTypeID", Name="CustomerTypeID", DbType="nchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string CustomerTypeID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customerTypeID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_customerTypeID == value) \r
+                                                       == false))\r
+                               {\r
+                                       if (_customerDemographic.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnCustomerTypeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerTypeID = value;\r
+                                       this.SendPropertyChanged("CustomerTypeID");\r
+                                       this.OnCustomerTypeIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Parents\r
+               [Association(Storage="_customer", OtherKey="CustomerID", ThisKey="CustomerID", Name="fk_CustomerCustomerDemo_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Customer Customer\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customer.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._customer.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._customer.Entity != null))\r
+                                       {\r
+                                               Customer previousCustomer = this._customer.Entity;\r
+                                               this._customer.Entity = null;\r
+                                               previousCustomer.CustomerCustomerDemo.Remove(this);\r
+                                       }\r
+                                       this._customer.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.CustomerCustomerDemo.Add(this);\r
+                                               _customerID = value.CustomerID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _customerID = default(string);\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Association(Storage="_customerDemographic", OtherKey="CustomerTypeID", ThisKey="CustomerTypeID", Name="fk_CustomerCustomerDemo_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public CustomerDemographic CustomerDemographic\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customerDemographic.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._customerDemographic.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._customerDemographic.Entity != null))\r
+                                       {\r
+                                               CustomerDemographic previousCustomerDemographic = this._customerDemographic.Entity;\r
+                                               this._customerDemographic.Entity = null;\r
+                                               previousCustomerDemographic.CustomerCustomerDemo.Remove(this);\r
+                                       }\r
+                                       this._customerDemographic.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.CustomerCustomerDemo.Add(this);\r
+                                               _customerTypeID = value.CustomerTypeID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _customerTypeID = default(string);\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       if ((_customerID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_customerID.GetHashCode() * 1));\r
+                       }\r
+                       if ((_customerTypeID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_customerTypeID.GetHashCode() * 65536));\r
+                       }\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       CustomerCustomerDemo other = ((CustomerCustomerDemo)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(CustomerCustomerDemo value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return (System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._customerID, value._customerID) && System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._customerTypeID, value._customerTypeID));\r
+               }\r
+       }\r
+       \r
+       [Table(Name="main.CustomerDemographics")]\r
+       public partial class CustomerDemographic : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<CustomerDemographic>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _customerDesc;\r
+               \r
+               private string _customerTypeID;\r
+               \r
+               private EntitySet<CustomerCustomerDemo> _customerCustomerDemo;\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnCustomerDescChanged();\r
+               \r
+               partial void OnCustomerDescChanging(string value);\r
+               \r
+               partial void OnCustomerTypeIDChanged();\r
+               \r
+               partial void OnCustomerTypeIDChanging(string value);\r
+               #endregion\r
+               \r
+               \r
+               public CustomerDemographic()\r
+               {\r
+                       _customerCustomerDemo = new EntitySet<CustomerCustomerDemo>(new Action<CustomerCustomerDemo>(this.CustomerCustomerDemo_Attach), new Action<CustomerCustomerDemo>(this.CustomerCustomerDemo_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_customerDesc", Name="CustomerDesc", DbType="ntext", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string CustomerDesc\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customerDesc;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_customerDesc == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCustomerDescChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerDesc = value;\r
+                                       this.SendPropertyChanged("CustomerDesc");\r
+                                       this.OnCustomerDescChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_customerTypeID", Name="CustomerTypeID", DbType="nchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string CustomerTypeID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customerTypeID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_customerTypeID == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCustomerTypeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerTypeID = value;\r
+                                       this.SendPropertyChanged("CustomerTypeID");\r
+                                       this.OnCustomerTypeIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Children\r
+               [Association(Storage="_customerCustomerDemo", OtherKey="CustomerTypeID", ThisKey="CustomerTypeID", Name="fk_CustomerCustomerDemo_1")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<CustomerCustomerDemo> CustomerCustomerDemo\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customerCustomerDemo;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._customerCustomerDemo = value;\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       if ((_customerTypeID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_customerTypeID.GetHashCode() * 1));\r
+                       }\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       CustomerDemographic other = ((CustomerDemographic)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(CustomerDemographic value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._customerTypeID, value._customerTypeID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void CustomerCustomerDemo_Attach(CustomerCustomerDemo entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.CustomerDemographic = this;\r
+               }\r
+               \r
+               private void CustomerCustomerDemo_Detach(CustomerCustomerDemo entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.CustomerDemographic = null;\r
+               }\r
+               #endregion\r
+       }\r
+       \r
+       [Table(Name="main.Employees")]\r
+       public partial class Employee : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Employee>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _address;\r
+               \r
+               private System.Nullable<System.DateTime> _birthDate;\r
+               \r
+               private string _city;\r
+               \r
+               private string _country;\r
+               \r
+               private int _employeeID;\r
+               \r
+               private string _extension;\r
+               \r
+               private string _firstName;\r
+               \r
+               private System.Nullable<System.DateTime> _hireDate;\r
+               \r
+               private string _homePhone;\r
+               \r
+               private string _lastName;\r
+               \r
+               private string _notes;\r
+               \r
+               private byte[] _photo;\r
+               \r
+               private string _photoPath;\r
+               \r
+               private string _postalCode;\r
+               \r
+               private string _region;\r
+               \r
+               private System.Nullable<int> _reportsTo;\r
+               \r
+               private string _title;\r
+               \r
+               private string _titleOfCourtesy;\r
+               \r
+               private EntitySet<EmployeeTerritory> _employeeTerritories;\r
+               \r
+               private EntitySet<Employee> _employees;\r
+               \r
+               private EntitySet<Order> _orders;\r
+               \r
+               private EntityRef<Employee> _reportsToEmployee = new EntityRef<Employee>();\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnAddressChanged();\r
+               \r
+               partial void OnAddressChanging(string value);\r
+               \r
+               partial void OnBirthDateChanged();\r
+               \r
+               partial void OnBirthDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
+               partial void OnCityChanged();\r
+               \r
+               partial void OnCityChanging(string value);\r
+               \r
+               partial void OnCountryChanged();\r
+               \r
+               partial void OnCountryChanging(string value);\r
+               \r
+               partial void OnEmployeeIDChanged();\r
+               \r
+               partial void OnEmployeeIDChanging(int value);\r
+               \r
+               partial void OnExtensionChanged();\r
+               \r
+               partial void OnExtensionChanging(string value);\r
+               \r
+               partial void OnFirstNameChanged();\r
+               \r
+               partial void OnFirstNameChanging(string value);\r
+               \r
+               partial void OnHireDateChanged();\r
+               \r
+               partial void OnHireDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
+               partial void OnHomePhoneChanged();\r
+               \r
+               partial void OnHomePhoneChanging(string value);\r
+               \r
+               partial void OnLastNameChanged();\r
+               \r
+               partial void OnLastNameChanging(string value);\r
+               \r
+               partial void OnNotesChanged();\r
+               \r
+               partial void OnNotesChanging(string value);\r
+               \r
+               partial void OnPhotoChanged();\r
+               \r
+               partial void OnPhotoChanging(byte[] value);\r
+               \r
+               partial void OnPhotoPathChanged();\r
+               \r
+               partial void OnPhotoPathChanging(string value);\r
+               \r
+               partial void OnPostalCodeChanged();\r
+               \r
+               partial void OnPostalCodeChanging(string value);\r
+               \r
+               partial void OnRegionChanged();\r
+               \r
+               partial void OnRegionChanging(string value);\r
+               \r
+               partial void OnReportsToChanged();\r
+               \r
+               partial void OnReportsToChanging(System.Nullable<int> value);\r
+               \r
+               partial void OnTitleChanged();\r
+               \r
+               partial void OnTitleChanging(string value);\r
+               \r
+               partial void OnTitleOfCourtesyChanged();\r
+               \r
+               partial void OnTitleOfCourtesyChanging(string value);\r
+               #endregion\r
+               \r
+               \r
+               public Employee()\r
+               {\r
+                       _employeeTerritories = new EntitySet<EmployeeTerritory>(new Action<EmployeeTerritory>(this.EmployeeTerritories_Attach), new Action<EmployeeTerritory>(this.EmployeeTerritories_Detach));\r
+                       _employees = new EntitySet<Employee>(new Action<Employee>(this.Employees_Attach), new Action<Employee>(this.Employees_Detach));\r
+                       _orders = new EntitySet<Order>(new Action<Order>(this.Orders_Attach), new Action<Order>(this.Orders_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_address", Name="Address", DbType="nvarchar (60)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Address\r
+               {\r
+                       get\r
+                       {\r
+                               return this._address;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_address == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnAddressChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._address = value;\r
+                                       this.SendPropertyChanged("Address");\r
+                                       this.OnAddressChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_birthDate", Name="BirthDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> BirthDate\r
+               {\r
+                       get\r
+                       {\r
+                               return this._birthDate;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_birthDate != value))\r
+                               {\r
+                                       this.OnBirthDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._birthDate = value;\r
+                                       this.SendPropertyChanged("BirthDate");\r
+                                       this.OnBirthDateChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_city", Name="City", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string City\r
+               {\r
+                       get\r
+                       {\r
+                               return this._city;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_city == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._city = value;\r
+                                       this.SendPropertyChanged("City");\r
+                                       this.OnCityChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_country", Name="Country", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Country\r
+               {\r
+                       get\r
+                       {\r
+                               return this._country;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_country == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCountryChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._country = value;\r
+                                       this.SendPropertyChanged("Country");\r
+                                       this.OnCountryChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_employeeID", Name="EmployeeID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int EmployeeID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._employeeID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_employeeID != value))\r
+                               {\r
+                                       this.OnEmployeeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._employeeID = value;\r
+                                       this.SendPropertyChanged("EmployeeID");\r
+                                       this.OnEmployeeIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_extension", Name="Extension", DbType="nvarchar (4)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Extension\r
+               {\r
+                       get\r
+                       {\r
+                               return this._extension;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_extension == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnExtensionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._extension = value;\r
+                                       this.SendPropertyChanged("Extension");\r
+                                       this.OnExtensionChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_firstName", Name="FirstName", DbType="nvarchar (10)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string FirstName\r
+               {\r
+                       get\r
+                       {\r
+                               return this._firstName;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_firstName == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnFirstNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._firstName = value;\r
+                                       this.SendPropertyChanged("FirstName");\r
+                                       this.OnFirstNameChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_hireDate", Name="HireDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> HireDate\r
+               {\r
+                       get\r
+                       {\r
+                               return this._hireDate;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_hireDate != value))\r
+                               {\r
+                                       this.OnHireDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._hireDate = value;\r
+                                       this.SendPropertyChanged("HireDate");\r
+                                       this.OnHireDateChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_homePhone", Name="HomePhone", DbType="nvarchar (24)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string HomePhone\r
+               {\r
+                       get\r
+                       {\r
+                               return this._homePhone;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_homePhone == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnHomePhoneChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._homePhone = value;\r
+                                       this.SendPropertyChanged("HomePhone");\r
+                                       this.OnHomePhoneChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_lastName", Name="LastName", DbType="nvarchar (20)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string LastName\r
+               {\r
+                       get\r
+                       {\r
+                               return this._lastName;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_lastName == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnLastNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._lastName = value;\r
+                                       this.SendPropertyChanged("LastName");\r
+                                       this.OnLastNameChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_notes", Name="Notes", DbType="ntext", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Notes\r
+               {\r
+                       get\r
+                       {\r
+                               return this._notes;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_notes == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnNotesChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._notes = value;\r
+                                       this.SendPropertyChanged("Notes");\r
+                                       this.OnNotesChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_photo", Name="Photo", DbType="image", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public byte[] Photo\r
+               {\r
+                       get\r
+                       {\r
+                               return this._photo;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_photo == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnPhotoChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._photo = value;\r
+                                       this.SendPropertyChanged("Photo");\r
+                                       this.OnPhotoChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_photoPath", Name="PhotoPath", DbType="nvarchar (255)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string PhotoPath\r
+               {\r
+                       get\r
+                       {\r
+                               return this._photoPath;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_photoPath == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnPhotoPathChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._photoPath = value;\r
+                                       this.SendPropertyChanged("PhotoPath");\r
+                                       this.OnPhotoPathChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_postalCode", Name="PostalCode", DbType="nvarchar (10)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string PostalCode\r
+               {\r
+                       get\r
+                       {\r
+                               return this._postalCode;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_postalCode == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnPostalCodeChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._postalCode = value;\r
+                                       this.SendPropertyChanged("PostalCode");\r
+                                       this.OnPostalCodeChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_region", Name="Region", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Region\r
+               {\r
+                       get\r
+                       {\r
+                               return this._region;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_region == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnRegionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._region = value;\r
+                                       this.SendPropertyChanged("Region");\r
+                                       this.OnRegionChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_reportsTo", Name="ReportsTo", DbType="INTEGER", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<int> ReportsTo\r
+               {\r
+                       get\r
+                       {\r
+                               return this._reportsTo;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_reportsTo != value))\r
+                               {\r
+                                       if (_reportsToEmployee.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnReportsToChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._reportsTo = value;\r
+                                       this.SendPropertyChanged("ReportsTo");\r
+                                       this.OnReportsToChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_title", Name="Title", DbType="nvarchar (30)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Title\r
+               {\r
+                       get\r
+                       {\r
+                               return this._title;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_title == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnTitleChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._title = value;\r
+                                       this.SendPropertyChanged("Title");\r
+                                       this.OnTitleChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_titleOfCourtesy", Name="TitleOfCourtesy", DbType="nvarchar (25)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string TitleOfCourtesy\r
+               {\r
+                       get\r
+                       {\r
+                               return this._titleOfCourtesy;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_titleOfCourtesy == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnTitleOfCourtesyChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._titleOfCourtesy = value;\r
+                                       this.SendPropertyChanged("TitleOfCourtesy");\r
+                                       this.OnTitleOfCourtesyChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Children\r
+               [Association(Storage="_employeeTerritories", OtherKey="EmployeeID", ThisKey="EmployeeID", Name="fk_EmployeeTerritories_1")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<EmployeeTerritory> EmployeeTerritories\r
+               {\r
+                       get\r
+                       {\r
+                               return this._employeeTerritories;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._employeeTerritories = value;\r
+                       }\r
+               }\r
+               \r
+               [Association(Storage="_employees", OtherKey="ReportsTo", ThisKey="EmployeeID", Name="fk_Employees_0")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<Employee> Employees\r
+               {\r
+                       get\r
+                       {\r
+                               return this._employees;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._employees = value;\r
+                       }\r
+               }\r
+               \r
+               [Association(Storage="_orders", OtherKey="EmployeeID", ThisKey="EmployeeID", Name="fk_Orders_1")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<Order> Orders\r
+               {\r
+                       get\r
+                       {\r
+                               return this._orders;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._orders = value;\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               #region Parents\r
+               [Association(Storage="_reportsToEmployee", OtherKey="EmployeeID", ThisKey="ReportsTo", Name="fk_Employees_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Employee ReportsToEmployee\r
+               {\r
+                       get\r
+                       {\r
+                               return this._reportsToEmployee.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._reportsToEmployee.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._reportsToEmployee.Entity != null))\r
+                                       {\r
+                                               Employee previousEmployee = this._reportsToEmployee.Entity;\r
+                                               this._reportsToEmployee.Entity = null;\r
+                                               previousEmployee.Employees.Remove(this);\r
+                                       }\r
+                                       this._reportsToEmployee.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.Employees.Add(this);\r
+                                               _reportsTo = value.EmployeeID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _reportsTo = null;\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_employeeID.GetHashCode() * 1));\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Employee other = ((Employee)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Employee value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<int>.Default.Equals(this._employeeID, value._employeeID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void EmployeeTerritories_Attach(EmployeeTerritory entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Employee = this;\r
+               }\r
+               \r
+               private void EmployeeTerritories_Detach(EmployeeTerritory entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Employee = null;\r
+               }\r
+               \r
+               private void Employees_Attach(Employee entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.ReportsToEmployee = this;\r
+               }\r
+               \r
+               private void Employees_Detach(Employee entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.ReportsToEmployee = null;\r
+               }\r
+               \r
+               private void Orders_Attach(Order entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Employee = this;\r
+               }\r
+               \r
+               private void Orders_Detach(Order entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Employee = null;\r
+               }\r
+               #endregion\r
+       }\r
+       \r
+       [Table(Name="main.EmployeeTerritories")]\r
+       public partial class EmployeeTerritory : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<EmployeeTerritory>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private int _employeeID;\r
+               \r
+               private string _territoryID;\r
+               \r
+               private EntityRef<Territory> _territory = new EntityRef<Territory>();\r
+               \r
+               private EntityRef<Employee> _employee = new EntityRef<Employee>();\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnEmployeeIDChanged();\r
+               \r
+               partial void OnEmployeeIDChanging(int value);\r
+               \r
+               partial void OnTerritoryIDChanged();\r
+               \r
+               partial void OnTerritoryIDChanging(string value);\r
+               #endregion\r
+               \r
+               \r
+               public EmployeeTerritory()\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_employeeID", Name="EmployeeID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int EmployeeID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._employeeID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_employeeID != value))\r
+                               {\r
+                                       if (_employee.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnEmployeeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._employeeID = value;\r
+                                       this.SendPropertyChanged("EmployeeID");\r
+                                       this.OnEmployeeIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_territoryID", Name="TerritoryID", DbType="nvarchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string TerritoryID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._territoryID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_territoryID == value) \r
+                                                       == false))\r
+                               {\r
+                                       if (_territory.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnTerritoryIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._territoryID = value;\r
+                                       this.SendPropertyChanged("TerritoryID");\r
+                                       this.OnTerritoryIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Parents\r
+               [Association(Storage="_territory", OtherKey="TerritoryID", ThisKey="TerritoryID", Name="fk_EmployeeTerritories_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Territory Territory\r
+               {\r
+                       get\r
+                       {\r
+                               return this._territory.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._territory.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._territory.Entity != null))\r
+                                       {\r
+                                               Territory previousTerritory = this._territory.Entity;\r
+                                               this._territory.Entity = null;\r
+                                               previousTerritory.EmployeeTerritories.Remove(this);\r
+                                       }\r
+                                       this._territory.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.EmployeeTerritories.Add(this);\r
+                                               _territoryID = value.TerritoryID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _territoryID = default(string);\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Association(Storage="_employee", OtherKey="EmployeeID", ThisKey="EmployeeID", Name="fk_EmployeeTerritories_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Employee Employee\r
+               {\r
+                       get\r
+                       {\r
+                               return this._employee.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._employee.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._employee.Entity != null))\r
+                                       {\r
+                                               Employee previousEmployee = this._employee.Entity;\r
+                                               this._employee.Entity = null;\r
+                                               previousEmployee.EmployeeTerritories.Remove(this);\r
+                                       }\r
+                                       this._employee.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.EmployeeTerritories.Add(this);\r
+                                               _employeeID = value.EmployeeID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _employeeID = default(int);\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_employeeID.GetHashCode() * 1));\r
+                       if ((_territoryID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_territoryID.GetHashCode() * 65536));\r
+                       }\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       EmployeeTerritory other = ((EmployeeTerritory)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(EmployeeTerritory value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return (System.Collections.Generic.EqualityComparer<int>.Default.Equals(this._employeeID, value._employeeID) && System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._territoryID, value._territoryID));\r
+               }\r
+       }\r
+       \r
+       [Table(Name="main.Orders")]\r
+       public partial class Order : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Order>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _customerID;\r
+               \r
+               private System.Nullable<int> _employeeID;\r
+               \r
+               private System.Nullable<decimal> _freight;\r
+               \r
+               private System.Nullable<System.DateTime> _orderDate;\r
+               \r
+               private int _orderID;\r
+               \r
+               private System.Nullable<System.DateTime> _requiredDate;\r
+               \r
+               private string _shipAddress;\r
+               \r
+               private string _shipCity;\r
+               \r
+               private string _shipCountry;\r
+               \r
+               private string _shipName;\r
+               \r
+               private System.Nullable<System.DateTime> _shippedDate;\r
+               \r
+               private string _shipPostalCode;\r
+               \r
+               private string _shipRegion;\r
+               \r
+               private System.Nullable<int> _shipVia;\r
+               \r
+               private EntitySet<OrderDetail> _orderDetails;\r
+               \r
+               private EntityRef<Shipper> _shipper = new EntityRef<Shipper>();\r
+               \r
+               private EntityRef<Employee> _employee = new EntityRef<Employee>();\r
+               \r
+               private EntityRef<Customer> _customer = new EntityRef<Customer>();\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnCustomerIDChanged();\r
+               \r
+               partial void OnCustomerIDChanging(string value);\r
+               \r
+               partial void OnEmployeeIDChanged();\r
+               \r
+               partial void OnEmployeeIDChanging(System.Nullable<int> value);\r
+               \r
+               partial void OnFreightChanged();\r
+               \r
+               partial void OnFreightChanging(System.Nullable<decimal> value);\r
+               \r
+               partial void OnOrderDateChanged();\r
+               \r
+               partial void OnOrderDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
+               partial void OnOrderIDChanged();\r
+               \r
+               partial void OnOrderIDChanging(int value);\r
+               \r
+               partial void OnRequiredDateChanged();\r
+               \r
+               partial void OnRequiredDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
+               partial void OnShipAddressChanged();\r
+               \r
+               partial void OnShipAddressChanging(string value);\r
+               \r
+               partial void OnShipCityChanged();\r
+               \r
+               partial void OnShipCityChanging(string value);\r
+               \r
+               partial void OnShipCountryChanged();\r
+               \r
+               partial void OnShipCountryChanging(string value);\r
+               \r
+               partial void OnShipNameChanged();\r
+               \r
+               partial void OnShipNameChanging(string value);\r
+               \r
+               partial void OnShippedDateChanged();\r
+               \r
+               partial void OnShippedDateChanging(System.Nullable<System.DateTime> value);\r
+               \r
+               partial void OnShipPostalCodeChanged();\r
+               \r
+               partial void OnShipPostalCodeChanging(string value);\r
+               \r
+               partial void OnShipRegionChanged();\r
+               \r
+               partial void OnShipRegionChanging(string value);\r
+               \r
+               partial void OnShipViaChanged();\r
+               \r
+               partial void OnShipViaChanging(System.Nullable<int> value);\r
+               #endregion\r
+               \r
+               \r
+               public Order()\r
+               {\r
+                       _orderDetails = new EntitySet<OrderDetail>(new Action<OrderDetail>(this.OrderDetails_Attach), new Action<OrderDetail>(this.OrderDetails_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_customerID", Name="CustomerID", DbType="nchar (5)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string CustomerID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customerID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_customerID == value) \r
+                                                       == false))\r
+                               {\r
+                                       if (_customer.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnCustomerIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._customerID = value;\r
+                                       this.SendPropertyChanged("CustomerID");\r
+                                       this.OnCustomerIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_employeeID", Name="EmployeeID", DbType="INTEGER", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<int> EmployeeID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._employeeID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_employeeID != value))\r
+                               {\r
+                                       if (_employee.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnEmployeeIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._employeeID = value;\r
+                                       this.SendPropertyChanged("EmployeeID");\r
+                                       this.OnEmployeeIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_freight", Name="Freight", DbType="money", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<decimal> Freight\r
+               {\r
+                       get\r
+                       {\r
+                               return this._freight;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_freight != value))\r
+                               {\r
+                                       this.OnFreightChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._freight = value;\r
+                                       this.SendPropertyChanged("Freight");\r
+                                       this.OnFreightChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_orderDate", Name="OrderDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> OrderDate\r
+               {\r
+                       get\r
+                       {\r
+                               return this._orderDate;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_orderDate != value))\r
+                               {\r
+                                       this.OnOrderDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._orderDate = value;\r
+                                       this.SendPropertyChanged("OrderDate");\r
+                                       this.OnOrderDateChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_orderID", Name="OrderID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int OrderID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._orderID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_orderID != value))\r
+                               {\r
+                                       this.OnOrderIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._orderID = value;\r
+                                       this.SendPropertyChanged("OrderID");\r
+                                       this.OnOrderIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_requiredDate", Name="RequiredDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> RequiredDate\r
+               {\r
+                       get\r
+                       {\r
+                               return this._requiredDate;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_requiredDate != value))\r
+                               {\r
+                                       this.OnRequiredDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._requiredDate = value;\r
+                                       this.SendPropertyChanged("RequiredDate");\r
+                                       this.OnRequiredDateChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_shipAddress", Name="ShipAddress", DbType="nvarchar (60)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string ShipAddress\r
+               {\r
+                       get\r
+                       {\r
+                               return this._shipAddress;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_shipAddress == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnShipAddressChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipAddress = value;\r
+                                       this.SendPropertyChanged("ShipAddress");\r
+                                       this.OnShipAddressChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_shipCity", Name="ShipCity", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string ShipCity\r
+               {\r
+                       get\r
+                       {\r
+                               return this._shipCity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_shipCity == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnShipCityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipCity = value;\r
+                                       this.SendPropertyChanged("ShipCity");\r
+                                       this.OnShipCityChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_shipCountry", Name="ShipCountry", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string ShipCountry\r
+               {\r
+                       get\r
+                       {\r
+                               return this._shipCountry;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_shipCountry == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnShipCountryChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipCountry = value;\r
+                                       this.SendPropertyChanged("ShipCountry");\r
+                                       this.OnShipCountryChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_shipName", Name="ShipName", DbType="nvarchar (40)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string ShipName\r
+               {\r
+                       get\r
+                       {\r
+                               return this._shipName;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_shipName == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnShipNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipName = value;\r
+                                       this.SendPropertyChanged("ShipName");\r
+                                       this.OnShipNameChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_shippedDate", Name="ShippedDate", DbType="datetime", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<System.DateTime> ShippedDate\r
+               {\r
+                       get\r
+                       {\r
+                               return this._shippedDate;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_shippedDate != value))\r
+                               {\r
+                                       this.OnShippedDateChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shippedDate = value;\r
+                                       this.SendPropertyChanged("ShippedDate");\r
+                                       this.OnShippedDateChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_shipPostalCode", Name="ShipPostalCode", DbType="nvarchar (10)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string ShipPostalCode\r
+               {\r
+                       get\r
+                       {\r
+                               return this._shipPostalCode;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_shipPostalCode == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnShipPostalCodeChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipPostalCode = value;\r
+                                       this.SendPropertyChanged("ShipPostalCode");\r
+                                       this.OnShipPostalCodeChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_shipRegion", Name="ShipRegion", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string ShipRegion\r
+               {\r
+                       get\r
+                       {\r
+                               return this._shipRegion;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_shipRegion == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnShipRegionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipRegion = value;\r
+                                       this.SendPropertyChanged("ShipRegion");\r
+                                       this.OnShipRegionChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_shipVia", Name="ShipVia", DbType="INTEGER", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<int> ShipVia\r
+               {\r
+                       get\r
+                       {\r
+                               return this._shipVia;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_shipVia != value))\r
+                               {\r
+                                       if (_shipper.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnShipViaChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipVia = value;\r
+                                       this.SendPropertyChanged("ShipVia");\r
+                                       this.OnShipViaChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Children\r
+               [Association(Storage="_orderDetails", OtherKey="OrderID", ThisKey="OrderID", Name="fk_Order Details_1")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<OrderDetail> OrderDetails\r
+               {\r
+                       get\r
+                       {\r
+                               return this._orderDetails;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._orderDetails = value;\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               #region Parents\r
+               [Association(Storage="_shipper", OtherKey="ShipperID", ThisKey="ShipVia", Name="fk_Orders_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Shipper Shipper\r
+               {\r
+                       get\r
+                       {\r
+                               return this._shipper.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._shipper.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._shipper.Entity != null))\r
+                                       {\r
+                                               Shipper previousShipper = this._shipper.Entity;\r
+                                               this._shipper.Entity = null;\r
+                                               previousShipper.Orders.Remove(this);\r
+                                       }\r
+                                       this._shipper.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.Orders.Add(this);\r
+                                               _shipVia = value.ShipperID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _shipVia = null;\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Association(Storage="_employee", OtherKey="EmployeeID", ThisKey="EmployeeID", Name="fk_Orders_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Employee Employee\r
+               {\r
+                       get\r
+                       {\r
+                               return this._employee.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._employee.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._employee.Entity != null))\r
+                                       {\r
+                                               Employee previousEmployee = this._employee.Entity;\r
+                                               this._employee.Entity = null;\r
+                                               previousEmployee.Orders.Remove(this);\r
+                                       }\r
+                                       this._employee.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.Orders.Add(this);\r
+                                               _employeeID = value.EmployeeID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _employeeID = null;\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Association(Storage="_customer", OtherKey="CustomerID", ThisKey="CustomerID", Name="fk_Orders_2", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Customer Customer\r
+               {\r
+                       get\r
+                       {\r
+                               return this._customer.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._customer.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._customer.Entity != null))\r
+                                       {\r
+                                               Customer previousCustomer = this._customer.Entity;\r
+                                               this._customer.Entity = null;\r
+                                               previousCustomer.Orders.Remove(this);\r
+                                       }\r
+                                       this._customer.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.Orders.Add(this);\r
+                                               _customerID = value.CustomerID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _customerID = null;\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_orderID.GetHashCode() * 1));\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Order other = ((Order)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Order value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<int>.Default.Equals(this._orderID, value._orderID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void OrderDetails_Attach(OrderDetail entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Order = this;\r
+               }\r
+               \r
+               private void OrderDetails_Detach(OrderDetail entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Order = null;\r
+               }\r
+               #endregion\r
+       }\r
+       \r
+       [Table(Name="main.Order Details")]\r
+       public partial class OrderDetail : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<OrderDetail>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private float _discount;\r
+               \r
+               private int _orderID;\r
+               \r
+               private int _productID;\r
+               \r
+               private short _quantity;\r
+               \r
+               private decimal _unitPrice;\r
+               \r
+               private EntityRef<Product> _product = new EntityRef<Product>();\r
+               \r
+               private EntityRef<Order> _order = new EntityRef<Order>();\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnDiscountChanged();\r
+               \r
+               partial void OnDiscountChanging(float value);\r
+               \r
+               partial void OnOrderIDChanged();\r
+               \r
+               partial void OnOrderIDChanging(int value);\r
+               \r
+               partial void OnProductIDChanged();\r
+               \r
+               partial void OnProductIDChanging(int value);\r
+               \r
+               partial void OnQuantityChanged();\r
+               \r
+               partial void OnQuantityChanging(short value);\r
+               \r
+               partial void OnUnitPriceChanged();\r
+               \r
+               partial void OnUnitPriceChanging(decimal value);\r
+               #endregion\r
+               \r
+               \r
+               public OrderDetail()\r
+               {\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_discount", Name="Discount", DbType="real", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public float Discount\r
+               {\r
+                       get\r
+                       {\r
+                               return this._discount;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_discount != value))\r
+                               {\r
+                                       this.OnDiscountChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._discount = value;\r
+                                       this.SendPropertyChanged("Discount");\r
+                                       this.OnDiscountChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_orderID", Name="OrderID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int OrderID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._orderID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_orderID != value))\r
+                               {\r
+                                       if (_order.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnOrderIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._orderID = value;\r
+                                       this.SendPropertyChanged("OrderID");\r
+                                       this.OnOrderIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_productID", Name="ProductID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int ProductID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._productID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_productID != value))\r
+                               {\r
+                                       if (_product.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnProductIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._productID = value;\r
+                                       this.SendPropertyChanged("ProductID");\r
+                                       this.OnProductIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_quantity", Name="Quantity", DbType="smallint", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public short Quantity\r
+               {\r
+                       get\r
+                       {\r
+                               return this._quantity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_quantity != value))\r
+                               {\r
+                                       this.OnQuantityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._quantity = value;\r
+                                       this.SendPropertyChanged("Quantity");\r
+                                       this.OnQuantityChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_unitPrice", Name="UnitPrice", DbType="money", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public decimal UnitPrice\r
+               {\r
+                       get\r
+                       {\r
+                               return this._unitPrice;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_unitPrice != value))\r
+                               {\r
+                                       this.OnUnitPriceChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._unitPrice = value;\r
+                                       this.SendPropertyChanged("UnitPrice");\r
+                                       this.OnUnitPriceChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Parents\r
+               [Association(Storage="_product", OtherKey="ProductID", ThisKey="ProductID", Name="fk_Order Details_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Product Product\r
+               {\r
+                       get\r
+                       {\r
+                               return this._product.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._product.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._product.Entity != null))\r
+                                       {\r
+                                               Product previousProduct = this._product.Entity;\r
+                                               this._product.Entity = null;\r
+                                               previousProduct.OrderDetails.Remove(this);\r
+                                       }\r
+                                       this._product.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.OrderDetails.Add(this);\r
+                                               _productID = value.ProductID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _productID = default(int);\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Association(Storage="_order", OtherKey="OrderID", ThisKey="OrderID", Name="fk_Order Details_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Order Order\r
+               {\r
+                       get\r
+                       {\r
+                               return this._order.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._order.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._order.Entity != null))\r
+                                       {\r
+                                               Order previousOrder = this._order.Entity;\r
+                                               this._order.Entity = null;\r
+                                               previousOrder.OrderDetails.Remove(this);\r
+                                       }\r
+                                       this._order.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.OrderDetails.Add(this);\r
+                                               _orderID = value.OrderID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _orderID = default(int);\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_orderID.GetHashCode() * 1));\r
+                       hc = (hc \r
+                                               | (_productID.GetHashCode() * 65536));\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       OrderDetail other = ((OrderDetail)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(OrderDetail value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return (System.Collections.Generic.EqualityComparer<int>.Default.Equals(this._orderID, value._orderID) && System.Collections.Generic.EqualityComparer<int>.Default.Equals(this._productID, value._productID));\r
+               }\r
+       }\r
+       \r
+       [Table(Name="main.Products")]\r
+       public partial class Product : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Product>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private System.Nullable<int> _categoryID;\r
+               \r
+               private bool _discontinued;\r
+               \r
+               private int _productID;\r
+               \r
+               private string _productName;\r
+               \r
+               private string _quantityPerUnit;\r
+               \r
+               private System.Nullable<short> _reorderLevel;\r
+               \r
+               private System.Nullable<int> _supplierID;\r
+               \r
+               private System.Nullable<decimal> _unitPrice;\r
+               \r
+               private System.Nullable<short> _unitsInStock;\r
+               \r
+               private System.Nullable<short> _unitsOnOrder;\r
+               \r
+               private EntitySet<OrderDetail> _orderDetails;\r
+               \r
+               private EntityRef<Supplier> _supplier = new EntityRef<Supplier>();\r
+               \r
+               private EntityRef<Category> _category = new EntityRef<Category>();\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnCategoryIDChanged();\r
+               \r
+               partial void OnCategoryIDChanging(System.Nullable<int> value);\r
+               \r
+               partial void OnDiscontinuedChanged();\r
+               \r
+               partial void OnDiscontinuedChanging(bool value);\r
+               \r
+               partial void OnProductIDChanged();\r
+               \r
+               partial void OnProductIDChanging(int value);\r
+               \r
+               partial void OnProductNameChanged();\r
+               \r
+               partial void OnProductNameChanging(string value);\r
+               \r
+               partial void OnQuantityPerUnitChanged();\r
+               \r
+               partial void OnQuantityPerUnitChanging(string value);\r
+               \r
+               partial void OnReorderLevelChanged();\r
+               \r
+               partial void OnReorderLevelChanging(System.Nullable<short> value);\r
+               \r
+               partial void OnSupplierIDChanged();\r
+               \r
+               partial void OnSupplierIDChanging(System.Nullable<int> value);\r
+               \r
+               partial void OnUnitPriceChanged();\r
+               \r
+               partial void OnUnitPriceChanging(System.Nullable<decimal> value);\r
+               \r
+               partial void OnUnitsInStockChanged();\r
+               \r
+               partial void OnUnitsInStockChanging(System.Nullable<short> value);\r
+               \r
+               partial void OnUnitsOnOrderChanged();\r
+               \r
+               partial void OnUnitsOnOrderChanging(System.Nullable<short> value);\r
+               #endregion\r
+               \r
+               \r
+               public Product()\r
+               {\r
+                       _orderDetails = new EntitySet<OrderDetail>(new Action<OrderDetail>(this.OrderDetails_Attach), new Action<OrderDetail>(this.OrderDetails_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_categoryID", Name="CategoryID", DbType="INTEGER", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<int> CategoryID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._categoryID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_categoryID != value))\r
+                               {\r
+                                       if (_category.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnCategoryIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._categoryID = value;\r
+                                       this.SendPropertyChanged("CategoryID");\r
+                                       this.OnCategoryIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_discontinued", Name="Discontinued", DbType="bit", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public bool Discontinued\r
+               {\r
+                       get\r
+                       {\r
+                               return this._discontinued;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_discontinued != value))\r
+                               {\r
+                                       this.OnDiscontinuedChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._discontinued = value;\r
+                                       this.SendPropertyChanged("Discontinued");\r
+                                       this.OnDiscontinuedChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_productID", Name="ProductID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int ProductID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._productID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_productID != value))\r
+                               {\r
+                                       this.OnProductIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._productID = value;\r
+                                       this.SendPropertyChanged("ProductID");\r
+                                       this.OnProductIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_productName", Name="ProductName", DbType="nvarchar (40)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string ProductName\r
+               {\r
+                       get\r
+                       {\r
+                               return this._productName;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_productName == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnProductNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._productName = value;\r
+                                       this.SendPropertyChanged("ProductName");\r
+                                       this.OnProductNameChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_quantityPerUnit", Name="QuantityPerUnit", DbType="nvarchar (20)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string QuantityPerUnit\r
+               {\r
+                       get\r
+                       {\r
+                               return this._quantityPerUnit;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_quantityPerUnit == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnQuantityPerUnitChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._quantityPerUnit = value;\r
+                                       this.SendPropertyChanged("QuantityPerUnit");\r
+                                       this.OnQuantityPerUnitChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_reorderLevel", Name="ReorderLevel", DbType="smallint", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<short> ReorderLevel\r
+               {\r
+                       get\r
+                       {\r
+                               return this._reorderLevel;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_reorderLevel != value))\r
+                               {\r
+                                       this.OnReorderLevelChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._reorderLevel = value;\r
+                                       this.SendPropertyChanged("ReorderLevel");\r
+                                       this.OnReorderLevelChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_supplierID", Name="SupplierID", DbType="INTEGER", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<int> SupplierID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._supplierID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_supplierID != value))\r
+                               {\r
+                                       if (_supplier.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnSupplierIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._supplierID = value;\r
+                                       this.SendPropertyChanged("SupplierID");\r
+                                       this.OnSupplierIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_unitPrice", Name="UnitPrice", DbType="money", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<decimal> UnitPrice\r
+               {\r
+                       get\r
+                       {\r
+                               return this._unitPrice;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_unitPrice != value))\r
+                               {\r
+                                       this.OnUnitPriceChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._unitPrice = value;\r
+                                       this.SendPropertyChanged("UnitPrice");\r
+                                       this.OnUnitPriceChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_unitsInStock", Name="UnitsInStock", DbType="smallint", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<short> UnitsInStock\r
+               {\r
+                       get\r
+                       {\r
+                               return this._unitsInStock;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_unitsInStock != value))\r
+                               {\r
+                                       this.OnUnitsInStockChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._unitsInStock = value;\r
+                                       this.SendPropertyChanged("UnitsInStock");\r
+                                       this.OnUnitsInStockChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_unitsOnOrder", Name="UnitsOnOrder", DbType="smallint", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public System.Nullable<short> UnitsOnOrder\r
+               {\r
+                       get\r
+                       {\r
+                               return this._unitsOnOrder;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_unitsOnOrder != value))\r
+                               {\r
+                                       this.OnUnitsOnOrderChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._unitsOnOrder = value;\r
+                                       this.SendPropertyChanged("UnitsOnOrder");\r
+                                       this.OnUnitsOnOrderChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Children\r
+               [Association(Storage="_orderDetails", OtherKey="ProductID", ThisKey="ProductID", Name="fk_Order Details_0")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<OrderDetail> OrderDetails\r
+               {\r
+                       get\r
+                       {\r
+                               return this._orderDetails;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._orderDetails = value;\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               #region Parents\r
+               [Association(Storage="_supplier", OtherKey="SupplierID", ThisKey="SupplierID", Name="fk_Products_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Supplier Supplier\r
+               {\r
+                       get\r
+                       {\r
+                               return this._supplier.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._supplier.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._supplier.Entity != null))\r
+                                       {\r
+                                               Supplier previousSupplier = this._supplier.Entity;\r
+                                               this._supplier.Entity = null;\r
+                                               previousSupplier.Products.Remove(this);\r
+                                       }\r
+                                       this._supplier.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.Products.Add(this);\r
+                                               _supplierID = value.SupplierID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _supplierID = null;\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Association(Storage="_category", OtherKey="CategoryID", ThisKey="CategoryID", Name="fk_Products_1", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Category Category\r
+               {\r
+                       get\r
+                       {\r
+                               return this._category.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._category.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._category.Entity != null))\r
+                                       {\r
+                                               Category previousCategory = this._category.Entity;\r
+                                               this._category.Entity = null;\r
+                                               previousCategory.Products.Remove(this);\r
+                                       }\r
+                                       this._category.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.Products.Add(this);\r
+                                               _categoryID = value.CategoryID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _categoryID = null;\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_productID.GetHashCode() * 1));\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Product other = ((Product)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Product value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<int>.Default.Equals(this._productID, value._productID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void OrderDetails_Attach(OrderDetail entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Product = this;\r
+               }\r
+               \r
+               private void OrderDetails_Detach(OrderDetail entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Product = null;\r
+               }\r
+               #endregion\r
+       }\r
+       \r
+       [Table(Name="main.Region")]\r
+       public partial class Region : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Region>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _regionDescription;\r
+               \r
+               private int _regionID;\r
+               \r
+               private EntitySet<Territory> _territories;\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnRegionDescriptionChanged();\r
+               \r
+               partial void OnRegionDescriptionChanging(string value);\r
+               \r
+               partial void OnRegionIDChanged();\r
+               \r
+               partial void OnRegionIDChanging(int value);\r
+               #endregion\r
+               \r
+               \r
+               public Region()\r
+               {\r
+                       _territories = new EntitySet<Territory>(new Action<Territory>(this.Territories_Attach), new Action<Territory>(this.Territories_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_regionDescription", Name="RegionDescription", DbType="nchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string RegionDescription\r
+               {\r
+                       get\r
+                       {\r
+                               return this._regionDescription;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_regionDescription == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnRegionDescriptionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._regionDescription = value;\r
+                                       this.SendPropertyChanged("RegionDescription");\r
+                                       this.OnRegionDescriptionChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_regionID", Name="RegionID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int RegionID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._regionID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_regionID != value))\r
+                               {\r
+                                       this.OnRegionIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._regionID = value;\r
+                                       this.SendPropertyChanged("RegionID");\r
+                                       this.OnRegionIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Children\r
+               [Association(Storage="_territories", OtherKey="RegionID", ThisKey="RegionID", Name="fk_Territories_0")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<Territory> Territories\r
+               {\r
+                       get\r
+                       {\r
+                               return this._territories;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._territories = value;\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_regionID.GetHashCode() * 1));\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Region other = ((Region)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Region value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<int>.Default.Equals(this._regionID, value._regionID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void Territories_Attach(Territory entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Region = this;\r
+               }\r
+               \r
+               private void Territories_Detach(Territory entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Region = null;\r
+               }\r
+               #endregion\r
+       }\r
+       \r
+       [Table(Name="main.Shippers")]\r
+       public partial class Shipper : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Shipper>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _companyName;\r
+               \r
+               private string _phone;\r
+               \r
+               private int _shipperID;\r
+               \r
+               private EntitySet<Order> _orders;\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnCompanyNameChanged();\r
+               \r
+               partial void OnCompanyNameChanging(string value);\r
+               \r
+               partial void OnPhoneChanged();\r
+               \r
+               partial void OnPhoneChanging(string value);\r
+               \r
+               partial void OnShipperIDChanged();\r
+               \r
+               partial void OnShipperIDChanging(int value);\r
+               #endregion\r
+               \r
+               \r
+               public Shipper()\r
+               {\r
+                       _orders = new EntitySet<Order>(new Action<Order>(this.Orders_Attach), new Action<Order>(this.Orders_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_companyName", Name="CompanyName", DbType="nvarchar (40)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string CompanyName\r
+               {\r
+                       get\r
+                       {\r
+                               return this._companyName;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_companyName == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCompanyNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._companyName = value;\r
+                                       this.SendPropertyChanged("CompanyName");\r
+                                       this.OnCompanyNameChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_phone", Name="Phone", DbType="nvarchar (24)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Phone\r
+               {\r
+                       get\r
+                       {\r
+                               return this._phone;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_phone == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnPhoneChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._phone = value;\r
+                                       this.SendPropertyChanged("Phone");\r
+                                       this.OnPhoneChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_shipperID", Name="ShipperID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int ShipperID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._shipperID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_shipperID != value))\r
+                               {\r
+                                       this.OnShipperIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._shipperID = value;\r
+                                       this.SendPropertyChanged("ShipperID");\r
+                                       this.OnShipperIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Children\r
+               [Association(Storage="_orders", OtherKey="ShipVia", ThisKey="ShipperID", Name="fk_Orders_0")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<Order> Orders\r
+               {\r
+                       get\r
+                       {\r
+                               return this._orders;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._orders = value;\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_shipperID.GetHashCode() * 1));\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Shipper other = ((Shipper)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Shipper value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<int>.Default.Equals(this._shipperID, value._shipperID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void Orders_Attach(Order entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Shipper = this;\r
+               }\r
+               \r
+               private void Orders_Detach(Order entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Shipper = null;\r
+               }\r
+               #endregion\r
+       }\r
+       \r
+       [Table(Name="main.Suppliers")]\r
+       public partial class Supplier : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Supplier>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private string _address;\r
+               \r
+               private string _city;\r
+               \r
+               private string _companyName;\r
+               \r
+               private string _contactName;\r
+               \r
+               private string _contactTitle;\r
+               \r
+               private string _country;\r
+               \r
+               private string _fax;\r
+               \r
+               private string _homePage;\r
+               \r
+               private string _phone;\r
+               \r
+               private string _postalCode;\r
+               \r
+               private string _region;\r
+               \r
+               private int _supplierID;\r
+               \r
+               private EntitySet<Product> _products;\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnAddressChanged();\r
+               \r
+               partial void OnAddressChanging(string value);\r
+               \r
+               partial void OnCityChanged();\r
+               \r
+               partial void OnCityChanging(string value);\r
+               \r
+               partial void OnCompanyNameChanged();\r
+               \r
+               partial void OnCompanyNameChanging(string value);\r
+               \r
+               partial void OnContactNameChanged();\r
+               \r
+               partial void OnContactNameChanging(string value);\r
+               \r
+               partial void OnContactTitleChanged();\r
+               \r
+               partial void OnContactTitleChanging(string value);\r
+               \r
+               partial void OnCountryChanged();\r
+               \r
+               partial void OnCountryChanging(string value);\r
+               \r
+               partial void OnFaxChanged();\r
+               \r
+               partial void OnFaxChanging(string value);\r
+               \r
+               partial void OnHomePageChanged();\r
+               \r
+               partial void OnHomePageChanging(string value);\r
+               \r
+               partial void OnPhoneChanged();\r
+               \r
+               partial void OnPhoneChanging(string value);\r
+               \r
+               partial void OnPostalCodeChanged();\r
+               \r
+               partial void OnPostalCodeChanging(string value);\r
+               \r
+               partial void OnRegionChanged();\r
+               \r
+               partial void OnRegionChanging(string value);\r
+               \r
+               partial void OnSupplierIDChanged();\r
+               \r
+               partial void OnSupplierIDChanging(int value);\r
+               #endregion\r
+               \r
+               \r
+               public Supplier()\r
+               {\r
+                       _products = new EntitySet<Product>(new Action<Product>(this.Products_Attach), new Action<Product>(this.Products_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_address", Name="Address", DbType="nvarchar (60)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Address\r
+               {\r
+                       get\r
+                       {\r
+                               return this._address;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_address == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnAddressChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._address = value;\r
+                                       this.SendPropertyChanged("Address");\r
+                                       this.OnAddressChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_city", Name="City", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string City\r
+               {\r
+                       get\r
+                       {\r
+                               return this._city;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_city == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCityChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._city = value;\r
+                                       this.SendPropertyChanged("City");\r
+                                       this.OnCityChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_companyName", Name="CompanyName", DbType="nvarchar (40)", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string CompanyName\r
+               {\r
+                       get\r
+                       {\r
+                               return this._companyName;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_companyName == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCompanyNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._companyName = value;\r
+                                       this.SendPropertyChanged("CompanyName");\r
+                                       this.OnCompanyNameChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_contactName", Name="ContactName", DbType="nvarchar (30)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string ContactName\r
+               {\r
+                       get\r
+                       {\r
+                               return this._contactName;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_contactName == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnContactNameChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._contactName = value;\r
+                                       this.SendPropertyChanged("ContactName");\r
+                                       this.OnContactNameChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_contactTitle", Name="ContactTitle", DbType="nvarchar (30)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string ContactTitle\r
+               {\r
+                       get\r
+                       {\r
+                               return this._contactTitle;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_contactTitle == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnContactTitleChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._contactTitle = value;\r
+                                       this.SendPropertyChanged("ContactTitle");\r
+                                       this.OnContactTitleChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_country", Name="Country", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Country\r
+               {\r
+                       get\r
+                       {\r
+                               return this._country;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_country == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnCountryChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._country = value;\r
+                                       this.SendPropertyChanged("Country");\r
+                                       this.OnCountryChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_fax", Name="Fax", DbType="nvarchar (24)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Fax\r
+               {\r
+                       get\r
+                       {\r
+                               return this._fax;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_fax == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnFaxChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._fax = value;\r
+                                       this.SendPropertyChanged("Fax");\r
+                                       this.OnFaxChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_homePage", Name="HomePage", DbType="ntext", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string HomePage\r
+               {\r
+                       get\r
+                       {\r
+                               return this._homePage;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_homePage == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnHomePageChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._homePage = value;\r
+                                       this.SendPropertyChanged("HomePage");\r
+                                       this.OnHomePageChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_phone", Name="Phone", DbType="nvarchar (24)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Phone\r
+               {\r
+                       get\r
+                       {\r
+                               return this._phone;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_phone == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnPhoneChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._phone = value;\r
+                                       this.SendPropertyChanged("Phone");\r
+                                       this.OnPhoneChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_postalCode", Name="PostalCode", DbType="nvarchar (10)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string PostalCode\r
+               {\r
+                       get\r
+                       {\r
+                               return this._postalCode;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_postalCode == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnPostalCodeChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._postalCode = value;\r
+                                       this.SendPropertyChanged("PostalCode");\r
+                                       this.OnPostalCodeChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_region", Name="Region", DbType="nvarchar (15)", AutoSync=AutoSync.Never)]\r
+               [DebuggerNonUserCode()]\r
+               public string Region\r
+               {\r
+                       get\r
+                       {\r
+                               return this._region;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_region == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnRegionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._region = value;\r
+                                       this.SendPropertyChanged("Region");\r
+                                       this.OnRegionChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_supplierID", Name="SupplierID", DbType="INTEGER", IsPrimaryKey=true, IsDbGenerated=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int SupplierID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._supplierID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_supplierID != value))\r
+                               {\r
+                                       this.OnSupplierIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._supplierID = value;\r
+                                       this.SendPropertyChanged("SupplierID");\r
+                                       this.OnSupplierIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Children\r
+               [Association(Storage="_products", OtherKey="SupplierID", ThisKey="SupplierID", Name="fk_Products_0")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<Product> Products\r
+               {\r
+                       get\r
+                       {\r
+                               return this._products;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._products = value;\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       hc = (hc \r
+                                               | (_supplierID.GetHashCode() * 1));\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Supplier other = ((Supplier)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Supplier value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<int>.Default.Equals(this._supplierID, value._supplierID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void Products_Attach(Product entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Supplier = this;\r
+               }\r
+               \r
+               private void Products_Detach(Product entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Supplier = null;\r
+               }\r
+               #endregion\r
+       }\r
+       \r
+       [Table(Name="main.Territories")]\r
+       public partial class Territory : System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged, System.IEquatable<Territory>\r
+       {\r
+               \r
+               private static System.ComponentModel.PropertyChangingEventArgs emptyChangingEventArgs = new System.ComponentModel.PropertyChangingEventArgs("");\r
+               \r
+               private int _regionID;\r
+               \r
+               private string _territoryDescription;\r
+               \r
+               private string _territoryID;\r
+               \r
+               private EntitySet<EmployeeTerritory> _employeeTerritories;\r
+               \r
+               private EntityRef<Region> _region = new EntityRef<Region>();\r
+               \r
+               #region Extensibility Method Declarations\r
+               partial void OnCreated();\r
+               \r
+               partial void OnRegionIDChanged();\r
+               \r
+               partial void OnRegionIDChanging(int value);\r
+               \r
+               partial void OnTerritoryDescriptionChanged();\r
+               \r
+               partial void OnTerritoryDescriptionChanging(string value);\r
+               \r
+               partial void OnTerritoryIDChanged();\r
+               \r
+               partial void OnTerritoryIDChanging(string value);\r
+               #endregion\r
+               \r
+               \r
+               public Territory()\r
+               {\r
+                       _employeeTerritories = new EntitySet<EmployeeTerritory>(new Action<EmployeeTerritory>(this.EmployeeTerritories_Attach), new Action<EmployeeTerritory>(this.EmployeeTerritories_Detach));\r
+                       this.OnCreated();\r
+               }\r
+               \r
+               [Column(Storage="_regionID", Name="RegionID", DbType="INTEGER", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public int RegionID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._regionID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if ((_regionID != value))\r
+                               {\r
+                                       if (_region.HasLoadedOrAssignedValue)\r
+                                       {\r
+                                               throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();\r
+                                       }\r
+                                       this.OnRegionIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._regionID = value;\r
+                                       this.SendPropertyChanged("RegionID");\r
+                                       this.OnRegionIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_territoryDescription", Name="TerritoryDescription", DbType="nchar", AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string TerritoryDescription\r
+               {\r
+                       get\r
+                       {\r
+                               return this._territoryDescription;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_territoryDescription == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnTerritoryDescriptionChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._territoryDescription = value;\r
+                                       this.SendPropertyChanged("TerritoryDescription");\r
+                                       this.OnTerritoryDescriptionChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               [Column(Storage="_territoryID", Name="TerritoryID", DbType="nvarchar", IsPrimaryKey=true, AutoSync=AutoSync.Never, CanBeNull=false)]\r
+               [DebuggerNonUserCode()]\r
+               public string TerritoryID\r
+               {\r
+                       get\r
+                       {\r
+                               return this._territoryID;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((_territoryID == value) \r
+                                                       == false))\r
+                               {\r
+                                       this.OnTerritoryIDChanging(value);\r
+                                       this.SendPropertyChanging();\r
+                                       this._territoryID = value;\r
+                                       this.SendPropertyChanged("TerritoryID");\r
+                                       this.OnTerritoryIDChanged();\r
+                               }\r
+                       }\r
+               }\r
+               \r
+               #region Children\r
+               [Association(Storage="_employeeTerritories", OtherKey="TerritoryID", ThisKey="TerritoryID", Name="fk_EmployeeTerritories_0")]\r
+               [DebuggerNonUserCode()]\r
+               public EntitySet<EmployeeTerritory> EmployeeTerritories\r
+               {\r
+                       get\r
+                       {\r
+                               return this._employeeTerritories;\r
+                       }\r
+                       set\r
+                       {\r
+                               this._employeeTerritories = value;\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               #region Parents\r
+               [Association(Storage="_region", OtherKey="RegionID", ThisKey="RegionID", Name="fk_Territories_0", IsForeignKey=true)]\r
+               [DebuggerNonUserCode()]\r
+               public Region Region\r
+               {\r
+                       get\r
+                       {\r
+                               return this._region.Entity;\r
+                       }\r
+                       set\r
+                       {\r
+                               if (((this._region.Entity == value) \r
+                                                       == false))\r
+                               {\r
+                                       if ((this._region.Entity != null))\r
+                                       {\r
+                                               Region previousRegion = this._region.Entity;\r
+                                               this._region.Entity = null;\r
+                                               previousRegion.Territories.Remove(this);\r
+                                       }\r
+                                       this._region.Entity = value;\r
+                                       if ((value != null))\r
+                                       {\r
+                                               value.Territories.Add(this);\r
+                                               _regionID = value.RegionID;\r
+                                       }\r
+                                       else\r
+                                       {\r
+                                               _regionID = default(int);\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               #endregion\r
+               \r
+               public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;\r
+               \r
+               public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;\r
+               \r
+               protected virtual void SendPropertyChanging()\r
+               {\r
+                       System.ComponentModel.PropertyChangingEventHandler h = this.PropertyChanging;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, emptyChangingEventArgs);\r
+                       }\r
+               }\r
+               \r
+               protected virtual void SendPropertyChanged(string propertyName)\r
+               {\r
+                       System.ComponentModel.PropertyChangedEventHandler h = this.PropertyChanged;\r
+                       if ((h != null))\r
+                       {\r
+                               h(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));\r
+                       }\r
+               }\r
+               \r
+               public override int GetHashCode()\r
+               {\r
+                       int hc = 0;\r
+                       if ((_territoryID != null))\r
+                       {\r
+                               hc = (hc \r
+                                                       | (_territoryID.GetHashCode() * 1));\r
+                       }\r
+                       return hc;\r
+               }\r
+               \r
+               public override bool Equals(object value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       if (((value.GetType() == this.GetType()) \r
+                                               == false))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       Territory other = ((Territory)(value));\r
+                       return this.Equals(other);\r
+               }\r
+               \r
+               public virtual bool Equals(Territory value)\r
+               {\r
+                       if ((value == null))\r
+                       {\r
+                               return false;\r
+                       }\r
+                       return System.Collections.Generic.EqualityComparer<string>.Default.Equals(this._territoryID, value._territoryID);\r
+               }\r
+               \r
+               #region Attachment handlers\r
+               private void EmployeeTerritories_Attach(EmployeeTerritory entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Territory = this;\r
+               }\r
+               \r
+               private void EmployeeTerritories_Detach(EmployeeTerritory entity)\r
+               {\r
+                       this.SendPropertyChanging();\r
+                       entity.Territory = null;\r
+               }\r
+               #endregion\r
+       }\r
+}\r
diff --git a/mcs/class/System.Data.Linq/tests/expected/Northwind.Sqlite-sqlmetal.dbml b/mcs/class/System.Data.Linq/tests/expected/Northwind.Sqlite-sqlmetal.dbml
new file mode 100755 (executable)
index 0000000..62f3189
--- /dev/null
@@ -0,0 +1,169 @@
+<?xml version="1.0"?>\r
+<Database xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Name="main" Class="Main" BaseType="System.Data.Linq.DataContext" Provider="Sqlite" xmlns="http://schemas.microsoft.com/linqtosql/dbml/2007">\r
+  <Table Name="main.Categories" Member="Categories">\r
+    <Type Name="Categories">\r
+      <Association Name="fk_Products_1" Member="Products" Storage="_products" Type="Products" ThisKey="CategoryID" OtherKey="CategoryID" DeleteRule="NO ACTION" />\r
+      <Column Name="CategoryID" Member="CategoryID" Storage="_categoryID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="CategoryName" Member="CategoryName" Storage="_categoryName" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="Description" Member="Description" Storage="_description" Type="System.String" DbType="ntext" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Picture" Member="Picture" Storage="_picture" Type="System.Byte[]" DbType="image" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.CustomerCustomerDemo" Member="CustomerCustomerDemo">\r
+    <Type Name="CustomerCustomerDemo">\r
+      <Association Name="fk_CustomerCustomerDemo_0" Member="Customers" Storage="_customers" Type="Customers" ThisKey="CustomerID" OtherKey="CustomerID" IsForeignKey="true" />\r
+      <Association Name="fk_CustomerCustomerDemo_1" Member="CustomerDemographics" Storage="_customerDemographics" Type="CustomerDemographics" ThisKey="CustomerTypeID" OtherKey="CustomerTypeID" IsForeignKey="true" />\r
+      <Column Name="CustomerID" Member="CustomerID" Storage="_customerID" Type="System.String" DbType="nchar (5)" IsPrimaryKey="true" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="CustomerTypeID" Member="CustomerTypeID" Storage="_customerTypeID" Type="System.String" DbType="nchar" IsPrimaryKey="true" IsDbGenerated="false" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.CustomerDemographics" Member="CustomerDemographics">\r
+    <Type Name="CustomerDemographics">\r
+      <Association Name="fk_CustomerCustomerDemo_1" Member="CustomerCustomerDemo" Storage="_customerCustomerDemo" Type="CustomerCustomerDemo" ThisKey="CustomerTypeID" OtherKey="CustomerTypeID" DeleteRule="NO ACTION" />\r
+      <Column Name="CustomerDesc" Member="CustomerDesc" Storage="_customerDesc" Type="System.String" DbType="ntext" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="CustomerTypeID" Member="CustomerTypeID" Storage="_customerTypeID" Type="System.String" DbType="nchar" IsPrimaryKey="true" IsDbGenerated="false" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.Customers" Member="Customers">\r
+    <Type Name="Customers">\r
+      <Association Name="fk_CustomerCustomerDemo_0" Member="CustomerCustomerDemo" Storage="_customerCustomerDemo" Type="CustomerCustomerDemo" ThisKey="CustomerID" OtherKey="CustomerID" DeleteRule="NO ACTION" />\r
+      <Association Name="fk_Orders_2" Member="Orders" Storage="_orders" Type="Orders" ThisKey="CustomerID" OtherKey="CustomerID" DeleteRule="NO ACTION" />\r
+      <Column Name="Address" Member="Address" Storage="_address" Type="System.String" DbType="nvarchar (60)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="City" Member="City" Storage="_city" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="CompanyName" Member="CompanyName" Storage="_companyName" Type="System.String" DbType="nvarchar (40)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="ContactName" Member="ContactName" Storage="_contactName" Type="System.String" DbType="nvarchar (30)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ContactTitle" Member="ContactTitle" Storage="_contactTitle" Type="System.String" DbType="nvarchar (30)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Country" Member="Country" Storage="_country" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="CustomerID" Member="CustomerID" Storage="_customerID" Type="System.String" DbType="nchar (5)" IsPrimaryKey="true" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="Fax" Member="Fax" Storage="_fax" Type="System.String" DbType="nvarchar (24)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Phone" Member="Phone" Storage="_phone" Type="System.String" DbType="nvarchar (24)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="PostalCode" Member="PostalCode" Storage="_postalCode" Type="System.String" DbType="nvarchar (10)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Region" Member="Region" Storage="_region" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.Employees" Member="Employees">\r
+    <Type Name="Employees">\r
+      <Association Name="fk_EmployeeTerritories_1" Member="EmployeeTerritories" Storage="_employeeTerritories" Type="EmployeeTerritories" ThisKey="EmployeeID" OtherKey="EmployeeID" DeleteRule="NO ACTION" />\r
+      <Association Name="fk_Employees_0" Member="ReportsToEmployees" Storage="_reportsToEmployees" Type="Employees" ThisKey="ReportsTo" OtherKey="EmployeeID" IsForeignKey="true" />\r
+      <Association Name="fk_Employees_0" Member="EmployeeIDEmployees" Storage="_employeeIdeMployees" Type="Employees" ThisKey="EmployeeID" OtherKey="ReportsTo" DeleteRule="NO ACTION" />\r
+      <Association Name="fk_Orders_1" Member="Orders" Storage="_orders" Type="Orders" ThisKey="EmployeeID" OtherKey="EmployeeID" DeleteRule="NO ACTION" />\r
+      <Column Name="Address" Member="Address" Storage="_address" Type="System.String" DbType="nvarchar (60)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="BirthDate" Member="BirthDate" Storage="_birthDate" Type="System.DateTime" DbType="datetime" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="City" Member="City" Storage="_city" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Country" Member="Country" Storage="_country" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="EmployeeID" Member="EmployeeID" Storage="_employeeID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="Extension" Member="Extension" Storage="_extension" Type="System.String" DbType="nvarchar (4)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="FirstName" Member="FirstName" Storage="_firstName" Type="System.String" DbType="nvarchar (10)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="HireDate" Member="HireDate" Storage="_hireDate" Type="System.DateTime" DbType="datetime" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="HomePhone" Member="HomePhone" Storage="_homePhone" Type="System.String" DbType="nvarchar (24)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="LastName" Member="LastName" Storage="_lastName" Type="System.String" DbType="nvarchar (20)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="Notes" Member="Notes" Storage="_notes" Type="System.String" DbType="ntext" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Photo" Member="Photo" Storage="_photo" Type="System.Byte[]" DbType="image" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="PhotoPath" Member="PhotoPath" Storage="_photoPath" Type="System.String" DbType="nvarchar (255)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="PostalCode" Member="PostalCode" Storage="_postalCode" Type="System.String" DbType="nvarchar (10)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Region" Member="Region" Storage="_region" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ReportsTo" Member="ReportsTo" Storage="_reportsTo" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Title" Member="Title" Storage="_title" Type="System.String" DbType="nvarchar (30)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="TitleOfCourtesy" Member="TitleOfCourtesy" Storage="_titleOfCourtesy" Type="System.String" DbType="nvarchar (25)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.EmployeeTerritories" Member="EmployeeTerritories">\r
+    <Type Name="EmployeeTerritories">\r
+      <Association Name="fk_EmployeeTerritories_0" Member="Territories" Storage="_territories" Type="Territories" ThisKey="TerritoryID" OtherKey="TerritoryID" IsForeignKey="true" />\r
+      <Association Name="fk_EmployeeTerritories_1" Member="Employees" Storage="_employees" Type="Employees" ThisKey="EmployeeID" OtherKey="EmployeeID" IsForeignKey="true" />\r
+      <Column Name="EmployeeID" Member="EmployeeID" Storage="_employeeID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="TerritoryID" Member="TerritoryID" Storage="_territoryID" Type="System.String" DbType="nvarchar" IsPrimaryKey="true" IsDbGenerated="false" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.Order Details" Member="OrderDetails">\r
+    <Type Name="OrderDetails">\r
+      <Association Name="fk_Order Details_0" Member="Products" Storage="_products" Type="Products" ThisKey="ProductID" OtherKey="ProductID" IsForeignKey="true" />\r
+      <Association Name="fk_Order Details_1" Member="Orders" Storage="_orders" Type="Orders" ThisKey="OrderID" OtherKey="OrderID" IsForeignKey="true" />\r
+      <Column Name="Discount" Member="Discount" Storage="_discount" Type="System.Single" DbType="real" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="OrderID" Member="OrderID" Storage="_orderID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="ProductID" Member="ProductID" Storage="_productID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="Quantity" Member="Quantity" Storage="_quantity" Type="System.Int16" DbType="smallint" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="UnitPrice" Member="UnitPrice" Storage="_unitPrice" Type="System.Decimal" DbType="money" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.Orders" Member="Orders">\r
+    <Type Name="Orders">\r
+      <Association Name="fk_Order Details_1" Member="OrderDetails" Storage="_orderDetails" Type="OrderDetails" ThisKey="OrderID" OtherKey="OrderID" DeleteRule="NO ACTION" />\r
+      <Association Name="fk_Orders_0" Member="Shippers" Storage="_shippers" Type="Shippers" ThisKey="ShipVia" OtherKey="ShipperID" IsForeignKey="true" />\r
+      <Association Name="fk_Orders_1" Member="Employees" Storage="_employees" Type="Employees" ThisKey="EmployeeID" OtherKey="EmployeeID" IsForeignKey="true" />\r
+      <Association Name="fk_Orders_2" Member="Customers" Storage="_customers" Type="Customers" ThisKey="CustomerID" OtherKey="CustomerID" IsForeignKey="true" />\r
+      <Column Name="CustomerID" Member="CustomerID" Storage="_customerID" Type="System.String" DbType="nchar (5)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="EmployeeID" Member="EmployeeID" Storage="_employeeID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Freight" Member="Freight" Storage="_freight" Type="System.Decimal" DbType="money" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="OrderDate" Member="OrderDate" Storage="_orderDate" Type="System.DateTime" DbType="datetime" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="OrderID" Member="OrderID" Storage="_orderID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="RequiredDate" Member="RequiredDate" Storage="_requiredDate" Type="System.DateTime" DbType="datetime" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ShipAddress" Member="ShipAddress" Storage="_shipAddress" Type="System.String" DbType="nvarchar (60)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ShipCity" Member="ShipCity" Storage="_shipCity" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ShipCountry" Member="ShipCountry" Storage="_shipCountry" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ShipName" Member="ShipName" Storage="_shipName" Type="System.String" DbType="nvarchar (40)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ShippedDate" Member="ShippedDate" Storage="_shippedDate" Type="System.DateTime" DbType="datetime" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ShipPostalCode" Member="ShipPostalCode" Storage="_shipPostalCode" Type="System.String" DbType="nvarchar (10)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ShipRegion" Member="ShipRegion" Storage="_shipRegion" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ShipVia" Member="ShipVia" Storage="_shipVia" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.Products" Member="Products">\r
+    <Type Name="Products">\r
+      <Association Name="fk_Order Details_0" Member="OrderDetails" Storage="_orderDetails" Type="OrderDetails" ThisKey="ProductID" OtherKey="ProductID" DeleteRule="NO ACTION" />\r
+      <Association Name="fk_Products_0" Member="Suppliers" Storage="_suppliers" Type="Suppliers" ThisKey="SupplierID" OtherKey="SupplierID" IsForeignKey="true" />\r
+      <Association Name="fk_Products_1" Member="Categories" Storage="_categories" Type="Categories" ThisKey="CategoryID" OtherKey="CategoryID" IsForeignKey="true" />\r
+      <Column Name="CategoryID" Member="CategoryID" Storage="_categoryID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Discontinued" Member="Discontinued" Storage="_discontinued" Type="System.Boolean" DbType="bit" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="ProductID" Member="ProductID" Storage="_productID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+      <Column Name="ProductName" Member="ProductName" Storage="_productName" Type="System.String" DbType="nvarchar (40)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="QuantityPerUnit" Member="QuantityPerUnit" Storage="_quantityPerUnit" Type="System.String" DbType="nvarchar (20)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ReorderLevel" Member="ReorderLevel" Storage="_reorderLevel" Type="System.Int16" DbType="smallint" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="SupplierID" Member="SupplierID" Storage="_supplierID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="UnitPrice" Member="UnitPrice" Storage="_unitPrice" Type="System.Decimal" DbType="money" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="UnitsInStock" Member="UnitsInStock" Storage="_unitsInStock" Type="System.Int16" DbType="smallint" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="UnitsOnOrder" Member="UnitsOnOrder" Storage="_unitsOnOrder" Type="System.Int16" DbType="smallint" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.Region" Member="Region">\r
+    <Type Name="Region">\r
+      <Association Name="fk_Territories_0" Member="Territories" Storage="_territories" Type="Territories" ThisKey="RegionID" OtherKey="RegionID" DeleteRule="NO ACTION" />\r
+      <Column Name="RegionDescription" Member="RegionDescription" Storage="_regionDescription" Type="System.String" DbType="nchar" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="RegionID" Member="RegionID" Storage="_regionID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.Shippers" Member="Shippers">\r
+    <Type Name="Shippers">\r
+      <Association Name="fk_Orders_0" Member="Orders" Storage="_orders" Type="Orders" ThisKey="ShipperID" OtherKey="ShipVia" DeleteRule="NO ACTION" />\r
+      <Column Name="CompanyName" Member="CompanyName" Storage="_companyName" Type="System.String" DbType="nvarchar (40)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="Phone" Member="Phone" Storage="_phone" Type="System.String" DbType="nvarchar (24)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ShipperID" Member="ShipperID" Storage="_shipperID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.Suppliers" Member="Suppliers">\r
+    <Type Name="Suppliers">\r
+      <Association Name="fk_Products_0" Member="Products" Storage="_products" Type="Products" ThisKey="SupplierID" OtherKey="SupplierID" DeleteRule="NO ACTION" />\r
+      <Column Name="Address" Member="Address" Storage="_address" Type="System.String" DbType="nvarchar (60)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="City" Member="City" Storage="_city" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="CompanyName" Member="CompanyName" Storage="_companyName" Type="System.String" DbType="nvarchar (40)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="ContactName" Member="ContactName" Storage="_contactName" Type="System.String" DbType="nvarchar (30)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="ContactTitle" Member="ContactTitle" Storage="_contactTitle" Type="System.String" DbType="nvarchar (30)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Country" Member="Country" Storage="_country" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Fax" Member="Fax" Storage="_fax" Type="System.String" DbType="nvarchar (24)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="HomePage" Member="HomePage" Storage="_homePage" Type="System.String" DbType="ntext" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Phone" Member="Phone" Storage="_phone" Type="System.String" DbType="nvarchar (24)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="PostalCode" Member="PostalCode" Storage="_postalCode" Type="System.String" DbType="nvarchar (10)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="Region" Member="Region" Storage="_region" Type="System.String" DbType="nvarchar (15)" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="true" />\r
+      <Column Name="SupplierID" Member="SupplierID" Storage="_supplierID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+  <Table Name="main.Territories" Member="Territories">\r
+    <Type Name="Territories">\r
+      <Association Name="fk_EmployeeTerritories_0" Member="EmployeeTerritories" Storage="_employeeTerritories" Type="EmployeeTerritories" ThisKey="TerritoryID" OtherKey="TerritoryID" DeleteRule="NO ACTION" />\r
+      <Association Name="fk_Territories_0" Member="Region" Storage="_region" Type="Region" ThisKey="RegionID" OtherKey="RegionID" IsForeignKey="true" />\r
+      <Column Name="RegionID" Member="RegionID" Storage="_regionID" Type="System.Int32" DbType="INTEGER" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="TerritoryDescription" Member="TerritoryDescription" Storage="_territoryDescription" Type="System.String" DbType="nchar" IsPrimaryKey="false" IsDbGenerated="false" CanBeNull="false" />\r
+      <Column Name="TerritoryID" Member="TerritoryID" Storage="_territoryID" Type="System.String" DbType="nvarchar" IsPrimaryKey="true" IsDbGenerated="false" CanBeNull="false" />\r
+    </Type>\r
+  </Table>\r
+</Database>
\ No newline at end of file
index 22dccc68f7a4d8eb434eacb50095edb1e09f5837..0842a2ae138815962c8fc7aaad1f30ba49de0439 100644 (file)
@@ -1,3 +1,7 @@
+2010-04-03  Jb Evain  <jbevain@novell.com>
+
+       * Makefile: System.Data.Services is a .net 3.5 assembly.
+
 2009-11-07  Zoltan Varga  <vargaz@gmail.com>
 
        *: Move .cs files to the System.Data.Services subdir to match their namespace,
index cb4482befcbadece701c294aed22e18d6d0ae103..db307f0e67acc4f64e697c2fa5a9bc50ee84033a 100644 (file)
@@ -7,7 +7,8 @@ LIBRARY = System.Data.Services.dll
 LIBRARY_SNK = ../mono.snk
 LIBRARY_PACKAGE = none
 
-LIB_MCS_FLAGS = \
+LIB_MCS_FLAGS = \\r
+       -d:NET_3_5      \
        -r:System.dll \
        -r:System.Core.dll \
        -r:System.ServiceModel.dll \
index 5f732499b2afc96d7c8c4a11a9e3d29caa7b87fc..dbab2e7dbd171544804e2bd3ca4b89db68e647a8 100644 (file)
@@ -1,3 +1,10 @@
+2010-03-26  Veerapuram Varadhan  <vvaradhan@novell.com>
+
+    ** Fixes #564833/580736
+    * DbDataAdapter.cs (*Command): Fix for .NET compatibility which
+    supports both type of adapters with/without discrete command
+    instances.
+               
 2009-10-28  Veerapuram Varadhan  <vvaradhan@novell.com>
 
        ** Fixes #385028/#385029
index f6699ea93b3c0d5e1579aa6951fae00ffb0136e3..3fdc3ca11052a0f53df4ee8ba5d95bd44fef5082 100644 (file)
@@ -85,51 +85,83 @@ namespace System.Data.Common
                }
 
                IDbCommand IDbDataAdapter.SelectCommand {
-                       get { return _selectCommand; }
-                       set { _selectCommand = value; }
+                   get { return ((DbDataAdapter)this).SelectCommand; }
+                   set { ((DbDataAdapter)this).SelectCommand = (DbCommand)value; }
                }
 
                IDbCommand IDbDataAdapter.UpdateCommand{
-                       get { return _updateCommand; }
-                       set { _updateCommand = value; }
+                   get { return ((DbDataAdapter)this).UpdateCommand; }
+                   set { ((DbDataAdapter)this).UpdateCommand = (DbCommand)value; }
                }
-
+               
                IDbCommand IDbDataAdapter.DeleteCommand{
-                       get { return _deleteCommand; }
-                       set { _deleteCommand = value; }
+                   get { return ((DbDataAdapter)this).DeleteCommand; }
+                   set { ((DbDataAdapter)this).DeleteCommand = (DbCommand)value; }
                }
 
                IDbCommand IDbDataAdapter.InsertCommand{
-                       get { return _insertCommand; }
-                       set { _insertCommand = value; }
+                   get { return ((DbDataAdapter)this).InsertCommand; }
+                   set { ((DbDataAdapter)this).InsertCommand = (DbCommand)value; }
                }
                
                [Browsable (false)]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                public DbCommand SelectCommand {
-                       get { return (DbCommand) _selectCommand; }
-                       set { _selectCommand = value; }
+                   get {
+                                       return (DbCommand) _selectCommand;
+                                       //return (DbCommand) ((IDbDataAdapter)this).SelectCommand; 
+                       }
+                   set {
+                                       if (_selectCommand != value) {
+                                               _selectCommand = value;
+                                               ((IDbDataAdapter)this).SelectCommand = value; 
+                                       }
+                       }
                }
 
                [Browsable (false)]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                public DbCommand DeleteCommand {
-                       get { return (DbCommand) _deleteCommand; }
-                       set { _deleteCommand = value; }
+                   get {
+                                       return (DbCommand) _deleteCommand;
+                                       //return (DbCommand) ((IDbDataAdapter)this).DeleteCommand; 
+                       }
+                   set {
+                                       if (_deleteCommand != value) {
+                                               _deleteCommand = value;
+                                               ((IDbDataAdapter)this).DeleteCommand = value; 
+                                       }
+                       }
                }
 
                [Browsable (false)]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                public DbCommand InsertCommand {
-                       get { return (DbCommand)_insertCommand; }
-                       set { _insertCommand = value; }
+                   get {
+                                       return (DbCommand) _insertCommand;
+                                       //return (DbCommand) ((IDbDataAdapter)this).InsertCommand; 
+                       }
+                   set {
+                                       if (_insertCommand != value) {
+                                               _insertCommand = value;
+                                               ((IDbDataAdapter)this).InsertCommand = value; 
+                                       }
+                       }
                }
 
                [Browsable (false)]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                public DbCommand UpdateCommand {
-                       get { return (DbCommand)_updateCommand; }
-                       set { _updateCommand = value; }
+                   get {
+                                       return (DbCommand) _updateCommand;
+                                       //return (DbCommand) ((IDbDataAdapter)this).DeleteCommand; 
+                       }
+                   set {
+                                       if (_updateCommand != value) {
+                                               _updateCommand = value;
+                                               ((IDbDataAdapter)this).UpdateCommand = value; 
+                                       }
+                       }
                }
 
                [DefaultValue (1)]
index 09279a138a9f14c0606469afa0a45a9432558b82..658095b3926a892a75d26a8dd494fa43ff988408 100644 (file)
@@ -1,3 +1,7 @@
+2010-03-26  Veerapuram Varadhan  <vvaradhan@novell.com>
+
+       * SqlDataAdapter.cs: 2.0 profile changes
+       
 2009-12-03  Jonathan Pobst  <monkey@jpobst.com>
 
        * SortOrder.cs: Add enum.
index d14df461f0a64ad92fe2fa03433ddf3042468ac5..a8bc4aef436ec07f0100ddd642a6843e8abee108 100644 (file)
@@ -97,11 +97,7 @@ namespace System.Data.SqlClient {
 #endif
                [DefaultValue (null)]
                [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DBCommandEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
-               public
-#if ONLY_1_1
-               new 
-#endif 
-               SqlCommand DeleteCommand {
+               public new SqlCommand DeleteCommand {
                        get { 
 #if NET_2_0
                                return (SqlCommand)base.DeleteCommand; 
@@ -123,11 +119,7 @@ namespace System.Data.SqlClient {
 #endif
                [DefaultValue (null)]
                [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DBCommandEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
-               public
-#if ONLY_1_1
-               new 
-#endif 
-               SqlCommand InsertCommand {
+               public new SqlCommand InsertCommand {
                        get { 
 #if NET_2_0                            
                                return (SqlCommand)base.InsertCommand; 
@@ -149,11 +141,7 @@ namespace System.Data.SqlClient {
 #endif
                [DefaultValue (null)]
                [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DBCommandEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
-               public
-#if ONLY_1_1
-               new 
-#endif 
-               SqlCommand SelectCommand {
+               public new SqlCommand SelectCommand {
                        get { 
 #if NET_2_0
                                return (SqlCommand)base.SelectCommand; 
@@ -175,11 +163,7 @@ namespace System.Data.SqlClient {
 #endif
                [DefaultValue (null)]
                [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DBCommandEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
-               public
-#if ONLY_1_1
-               new 
-#endif 
-               SqlCommand UpdateCommand {
+               public new  SqlCommand UpdateCommand {
                        get { 
 #if NET_2_0
                                return (SqlCommand)base.UpdateCommand; 
index 666aa0f4dc5a5db1fcc9149befbc3c752145360e..82240e38714b92405fc6cd902c03ca0635920e42 100644 (file)
@@ -1,3 +1,25 @@
+2010-04-11  Veerapuram Varadhan  <vvaradhan@novell.com>
+
+       ** Fixes #591443
+       * DataColumn.cs (Clone): Use propert to clone Expression as it builds 
+       compiled expression also, if any. 
+       
+2010-04-10  Veerapuram Varadhan  <vvaradhan@novell.com>
+       
+       ** Fixes #589482
+       * DataColumn.cs (set_DataType): Preserve autoIncrement value 
+       for Decimal types as well.
+       
+2010-04-09  Veerapuram Varadhan  <vvaradhan@novell.com>
+
+       ** Fixes #576520 - Based on a patch by Greg SIROU <gspam@secway.fr>
+       * DataSet.cs (WriteColumnAsElement): Handle system.object types sanely.
+
+2010-04-09  Veerapuram Varadhan  <vvaradhan@novell.com>
+
+       ** Fixes #590232
+       * DataColumn.cs (Clone): Clone extended properties as well
+       
 2010-02-10  Marek Habersack  <mhabersack@novell.com>
 
        * XmlSchemaDataImporter.cs: the <connections> element might be
index ecdc4a5f194dc6698cc0c4926fe1703ba6e47b71..f5d84c562206660cb3fd31da5f5c509a2422bf12 100644 (file)
@@ -405,15 +405,9 @@ namespace System.Data {
 \r
                                //Check AutoIncrement status, make compatible datatype\r
                                if(AutoIncrement == true) {\r
-                                       // we want to check that the datatype is supported?\r
-                                       // TODO: Is this the same as CanAutoIncrement or was the omission of Decimal intended?\r
-                                       TypeCode typeCode = Type.GetTypeCode(value);\r
-\r
-                                       if (typeCode != TypeCode.Int16 &&\r
-                                           typeCode != TypeCode.Int32 &&\r
-                                           typeCode != TypeCode.Int64) {\r
+                                       // we want to check that the datatype is supported?                                     \r
+                                       if (!CanAutoIncrement (value))\r
                                                AutoIncrement = false;\r
-                                       }\r
                                }\r
 \r
                                if (DefaultValue != GetDefaultValueForType (prevType))\r
@@ -707,7 +701,8 @@ namespace System.Data {
                        //Copy.Container\r
                        copy.DataType = DataType;\r
                        copy._defaultValue = _defaultValue;\r
-                       copy._expression = _expression;\r
+                       // Use the property to set the expression as it updates compiledExpression, if any.\r
+                       copy.Expression = _expression;\r
                        //Copy.ExtendedProperties\r
                        copy._maxLength = _maxLength;\r
                        copy._nameSpace = _nameSpace;\r
@@ -720,6 +715,7 @@ namespace System.Data {
                        if (DataType == typeof (DateTime))\r
                                copy.DateTimeMode = _datetimeMode;\r
 #endif\r
+                       copy._extendedProperties = _extendedProperties;\r
 \r
                        return copy;\r
                }\r
index cb447a2c41cd4b56d756bb78fe2b4aee99d3e2a4..b62aff1e4d7847ae0836161b9f48aadd6d63d6ca 100644 (file)
@@ -1402,8 +1402,12 @@ namespace System.Data
 \r
                        //TODO check if I can get away with write element string\r
                        WriteStartElement (writer, mode, colnspc, col.Prefix, XmlHelper.Encode (col.ColumnName));       \r
-                       if (typeof (IXmlSerializable).IsAssignableFrom (col.DataType)) {\r
-                               ((IXmlSerializable)rowObject).WriteXml (writer);\r
+                       if (typeof (IXmlSerializable).IsAssignableFrom (col.DataType) \r
+                           || col.DataType == typeof (object)) {\r
+                               IXmlSerializable serializableObj = rowObject as IXmlSerializable;\r
+                               if (serializableObj == null)\r
+                                       throw new InvalidOperationException ();\r
+                               ((IXmlSerializable)rowObject).WriteXml (writer);                                \r
                        } else {\r
                                writer.WriteString (WriteObjectXml (rowObject));\r
                        }\r
index ef4dab6eb63fc7e3b05fc00407b2f1fa66c8ff03..579c7219b6832b36353112383b40662ab9dabc9f 100644 (file)
@@ -1,3 +1,7 @@
+2010-04-21  Veerapuram Varadhan  <vvaradhan@novell.com>
+
+       * SqlParameterTest.cs: Add test for bug#595918.
+       
 2009-08-01  Gert Driesen  <drieseng@users.sourceforge.net>
 
        * SqlDataReaderTest.cs: Fixes for SQL Server 7.0 / TDS 7. Avoid
index e0e987246cdeba71d1f8df8b9e8dc2590390d7ce..f521d3e369e7e768a7cbbc2bf2eabc7281a82887 100644 (file)
@@ -402,6 +402,96 @@ namespace MonoTests.System.Data.SqlClient
                        }
                }
 
+               [Test] // bug #595918
+               public void DecimalDefaultScaleTest ()
+               {
+                       string create_tbl = "CREATE TABLE #decimalScaleCheck (decsclcheck DECIMAL (19, 5) null)";
+                       string create_sp = "CREATE PROCEDURE #sp_bug595918(@decsclcheck decimal(19,5) OUT)"
+                               + "AS " + Environment.NewLine
+                               + "BEGIN" + Environment.NewLine
+                               + "INSERT INTO #decimalScaleCheck values (@decsclcheck)" + Environment.NewLine
+                               + "SELECT @decsclcheck=decsclcheck from #decimalScaleCheck" + Environment.NewLine
+                               + "END";
+                       
+                       cmd = new SqlCommand (create_tbl, conn);
+                       cmd.ExecuteNonQuery ();
+                       
+                       cmd.CommandText = create_sp;
+                       cmd.ExecuteNonQuery ();
+                       
+                       cmd.CommandText = "[#sp_bug595918]";
+                       cmd.CommandType = CommandType.StoredProcedure;
+                       SqlParameter pValue = new SqlParameter("@decsclcheck", SqlDbType.Decimal);
+                       pValue.Value = 128.425;
+                       pValue.Precision = 19;
+                       pValue.Scale = 3;
+                       pValue.Direction = ParameterDirection.InputOutput;
+                       cmd.Parameters.Add(pValue);
+                       cmd.ExecuteNonQuery();
+
+                       Assert.AreEqual (128.425, pValue.Value, "Stored decimal value is incorrect - DS - Bug#595918");
+               }
+               
+               [Test] // bug #595918
+               public void DecimalGreaterScaleTest ()
+               {
+                       string create_tbl = "CREATE TABLE #decimalScaleCheck (decsclcheck DECIMAL (19, 5) null)";
+                       string create_sp = "CREATE PROCEDURE #sp_bug595918(@decsclcheck decimal(19,5) OUT)"
+                               + "AS " + Environment.NewLine
+                               + "BEGIN" + Environment.NewLine
+                               + "INSERT INTO #decimalScaleCheck values (@decsclcheck)" + Environment.NewLine
+                               + "SELECT @decsclcheck=decsclcheck from #decimalScaleCheck" + Environment.NewLine
+                               + "END";
+                       
+                       cmd = new SqlCommand (create_tbl, conn);
+                       cmd.ExecuteNonQuery ();
+                       
+                       cmd.CommandText = create_sp;
+                       cmd.ExecuteNonQuery ();
+                       
+                       cmd.CommandText = "[#sp_bug595918]";
+                       cmd.CommandType = CommandType.StoredProcedure;
+                       SqlParameter pValue = new SqlParameter("@decsclcheck", SqlDbType.Decimal);
+                       pValue.Value = 128.425;
+                       pValue.Precision = 19;
+                       pValue.Scale = 5;
+                       pValue.Direction = ParameterDirection.InputOutput;
+                       cmd.Parameters.Add(pValue);
+                       cmd.ExecuteNonQuery();
+
+                       Assert.AreEqual (128.42500, pValue.Value, "Stored decimal value is incorrect - GS - Bug#595918");
+               }
+
+               [Test] // bug #595918
+               public void DecimalLesserScaleTest ()
+               {
+                       string create_tbl = "CREATE TABLE #decimalScaleCheck (decsclcheck DECIMAL (19, 5) null)";
+                       string create_sp = "CREATE PROCEDURE #sp_bug595918(@decsclcheck decimal(19,5) OUT)"
+                               + "AS " + Environment.NewLine
+                               + "BEGIN" + Environment.NewLine
+                               + "INSERT INTO #decimalScaleCheck values (@decsclcheck)" + Environment.NewLine
+                               + "SELECT @decsclcheck=decsclcheck from #decimalScaleCheck" + Environment.NewLine
+                               + "END";
+                       
+                       cmd = new SqlCommand (create_tbl, conn);
+                       cmd.ExecuteNonQuery ();
+                       
+                       cmd.CommandText = create_sp;
+                       cmd.ExecuteNonQuery ();
+                       
+                       cmd.CommandText = "[#sp_bug595918]";
+                       cmd.CommandType = CommandType.StoredProcedure;
+                       SqlParameter pValue = new SqlParameter("@decsclcheck", SqlDbType.Decimal);
+                       pValue.Value = 128.425;
+                       pValue.Precision = 19;
+                       pValue.Scale = 2;
+                       pValue.Direction = ParameterDirection.InputOutput;
+                       cmd.Parameters.Add(pValue);
+                       cmd.ExecuteNonQuery();
+
+                       Assert.AreEqual (128.42, pValue.Value, "Stored decimal value is incorrect - LS - Bug#595918");
+               }
+
                int ClientVersion {
                        get {
                                return (engine.ClientVersion);
index 9553bd2ee1145c2f9d44f3f5854c2c23fdf4d886..a7d90214dacf2b905a166611ae8b98f3136c5ede 100644 (file)
@@ -73,7 +73,7 @@
                        <connection
                                name="sqlserver-tds"
                                factory="System.Data.SqlClient"
-                               connectionString="server=164.99.99.212;database=monotest;user id=monotester;password=monotester;"
+                               connectionString="server=164.99.116.64;database=monotest;user id=monotester;password=monotester;"
                                engine="sqlserver2005" />
                        <connection
                                name="sqlserver-odbc"
index 13b841378995cd828022bd2301abe73b5bbec424..3782149ab0f95604a46eb0890b6d229e97e1fe11 100644 (file)
@@ -1,3 +1,15 @@
+2010-04-01  Miguel de Icaza  <miguel@novell.com>
+
+       * JsonValue.cs: We need to use Convert.ToXXXX for numbers as we
+       always end up reporting the value JsonType.Number regardless of
+       the underlying storage (int, long or decimal).   The parser
+       picks the best storage suitable for the data, and can end up using
+       "ints" for values that sometimes use longs. 
+
+       This causes problems when derefercing the data for example, if you
+       have an int and try to get it out as a long you end up with an
+       invalid cast exception.
+
 2010-03-10  Atsushi Enomoto  <atsushi@ximian.com>
 
        * System.Json.dll.sources : remove JsonReader.cs.
index 35e61de526c8327fd13f259c4c987b91b5496c06..7b7d9a3717d30d74c66f7a701800716182f831d6 100644 (file)
@@ -322,70 +322,70 @@ namespace System.Json
                {
                        if (value == null)
                                throw new ArgumentNullException ("value");
-                       return (bool) ((JsonPrimitive) value).Value;
+                       return Convert.ToBoolean (((JsonPrimitive) value).Value);
                }
 
                public static implicit operator byte (JsonValue value)
                {
                        if (value == null)
                                throw new ArgumentNullException ("value");
-                       return (byte) ((JsonPrimitive) value).Value;
+                       return Convert.ToByte (((JsonPrimitive) value).Value);
                }
 
                public static implicit operator char (JsonValue value)
                {
                        if (value == null)
                                throw new ArgumentNullException ("value");
-                       return (char) ((JsonPrimitive) value).Value;
+                       return Convert.ToChar (((JsonPrimitive) value).Value);
                }
 
                public static implicit operator decimal (JsonValue value)
                {
                        if (value == null)
                                throw new ArgumentNullException ("value");
-                       return (decimal) ((JsonPrimitive) value).Value;
+                       return Convert.ToDecimal (((JsonPrimitive) value).Value);
                }
 
                public static implicit operator double (JsonValue value)
                {
                        if (value == null)
                                throw new ArgumentNullException ("value");
-                       return (double) ((JsonPrimitive) value).Value;
+                       return Convert.ToDouble (((JsonPrimitive) value).Value);
                }
 
                public static implicit operator float (JsonValue value)
                {
                        if (value == null)
                                throw new ArgumentNullException ("value");
-                       return (float) ((JsonPrimitive) value).Value;
+                       return Convert.ToSingle (((JsonPrimitive) value).Value);
                }
 
                public static implicit operator int (JsonValue value)
                {
                        if (value == null)
                                throw new ArgumentNullException ("value");
-                       return (int) ((JsonPrimitive) value).Value;
+                       return Convert.ToInt32 (((JsonPrimitive) value).Value);
                }
 
                public static implicit operator long (JsonValue value)
                {
                        if (value == null)
                                throw new ArgumentNullException ("value");
-                       return (long) ((JsonPrimitive) value).Value;
+                       return Convert.ToInt64 (((JsonPrimitive) value).Value);
                }
 
                public static implicit operator sbyte (JsonValue value)
                {
                        if (value == null)
                                throw new ArgumentNullException ("value");
-                       return (sbyte) ((JsonPrimitive) value).Value;
+                       return Convert.ToSByte (((JsonPrimitive) value).Value);
                }
 
                public static implicit operator short (JsonValue value)
                {
                        if (value == null)
                                throw new ArgumentNullException ("value");
-                       return (short) ((JsonPrimitive) value).Value;
+                       return Convert.ToInt16 (((JsonPrimitive) value).Value);
                }
 
                public static implicit operator string (JsonValue value)
@@ -399,21 +399,21 @@ namespace System.Json
                {
                        if (value == null)
                                throw new ArgumentNullException ("value");
-                       return (uint) ((JsonPrimitive) value).Value;
+                       return Convert.ToUInt16 (((JsonPrimitive) value).Value);
                }
 
                public static implicit operator ulong (JsonValue value)
                {
                        if (value == null)
                                throw new ArgumentNullException ("value");
-                       return (ulong) ((JsonPrimitive) value).Value;
+                       return Convert.ToUInt64(((JsonPrimitive) value).Value);
                }
 
                public static implicit operator ushort (JsonValue value)
                {
                        if (value == null)
                                throw new ArgumentNullException ("value");
-                       return (ushort) ((JsonPrimitive) value).Value;
+                       return Convert.ToUInt16 (((JsonPrimitive) value).Value);
                }
 
                public static implicit operator DateTime (JsonValue value)
index db2a5875fd9c924d0763c0bff1adf6d6d431e0be..b6f43ac63bc140d1d97b942f04d946a9e8b1d2fd 100644 (file)
@@ -1,3 +1,17 @@
+2010-04-21  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * moonlight_raw_System.Net.dll.sources: Add System.Net.Sockets/
+       SocketClientAccessPolicyProtocol.cs to the build
+
+2010-04-05  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * moonlight_raw_System.Net.dll.sources: Move InternalWebRequest
+       StreamWrapper.cs back to System.Windows.dll
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * net_2_1_*.dll.sources: rename to moonlight_*.dll.sources.
+
 2010-03-10  Sebastien Pouliot  <sebastien@ximian.com>
 
        * net_2_1_raw_System.Net.dll.sources: Add types from (new internal)
index 3eda246ad4125c3899c33d5905419e0473da1527..ec35c24781e8e424855ee91da82a05103192b8a0 100644 (file)
@@ -128,12 +128,7 @@ namespace System.Net.Policy {
                        }
                }
 
-               public bool IsAllowed (WebRequest request)
-               {
-                       return IsAllowed (request.RequestUri, request.Headers.AllKeys);
-               }
-
-               abstract public bool IsAllowed (Uri uri, params string [] headerKeys);
+               abstract public bool IsAllowed (WebRequest request);
        }
 }
 
index 06bd21c8177acda321dd0be34557f3d9be22b2a6..3866d2b4f72ef749e30f7f25c0b57a49dbe89d2c 100644 (file)
@@ -1,3 +1,50 @@
+2010-04-13  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * CrossDomainPolicyManager.cs: Fix previous change since it 
+       breaks several valid cases (e.g. text/*, text/xml; charset=utf-8)
+       and does not completely covers the application/xml case.
+       Avoid possible ArgumentException while adding policies since it 
+       confuse the logs.
+
+2010-04-13  Andreia Gaita  <avidigal@novell.com>
+
+       * CrossDomainPolicyManager.cs: make the contentType detection
+       look for /xml at the end, it's more reliable
+       (fixes olympics for moonlight)
+
+2010-04-07  Sebastien Pouliot  <sebastien@ximian.com> 
+
+       * ClientAccessPolicy.cs: Fake a "GET" method when applying a 
+       policy to sockets
+
+2010-04-07  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * BaseDomainPolicy.cs: Abstract-fy IsAllowed(WebRequest) and 
+       remove abstract IsAllowed(Uri,string[]) since it cannot provide
+       enough information for the client access policy.
+       * ClientAccessPolicy.cs: Replace IsAllowed(Uri,string[]) with
+       IsAllowed(WebRequest) and add logic for AllowAnyMethod
+       * ClientAccessPolicyParser.cs: Read "http-methods" attribute (new
+       in SL3) and set the new AllowAnyMethod property if the value is
+       "*" (the only legal value if the attribute is present).
+       * FlashCrossDomainPolicy.cs: Add IsAllowed(WebRequest) since it's
+       not part of BaseDomainPolicy anymore.
+
+2010-04-06  Sebastien Pouliot  <sebastien@ximian.com> 
+
+       * ClientAccessPolicyParser.cs: Don't forget "http-request-headers"
+       as a valid attribute
+
+2010-04-06  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * ClientAccessPolicyParser.cs: Catch extra attributes that
+       leads to an invalid (no-access) policy. Fix parts of DRT#666
+       * CrossDomainPolicyManager.cs: Ignore policies sent with a 
+       Content-Type different than "text/*". Fix DRT#667
+       * FlashCrossDomainPolicyParser.cs: Catch extra attributes and
+       the case where a second policy is present (invalid xml). Fix 
+       parts of DRT#666
+
 2010-03-10  Sebastien Pouliot  <sebastien@ximian.com>
 
        * BaseDomainPolicy.cs, ClientAccessPolicy[Parser].cs, 
index 576dddc1fe6b2fe1c098686dfcc3d063cbaf3875..3e223a911a093b14dd405b2ca67cb4cbe5d768a2 100644 (file)
@@ -74,7 +74,8 @@ namespace System.Net.Policy {
                        foreach (AccessPolicy policy in AccessPolicyList) {
                                // does something allow our URI in this policy ?
                                foreach (AllowFrom af in policy.AllowedServices) {
-                                       if (af.IsAllowed (ApplicationUri, null)) {
+                                       // fake "GET" as method as this does not apply to sockets
+                                       if (af.IsAllowed (ApplicationUri, "GET", null)) {
                                                // if so, is our request port allowed ?
                                                if (policy.PortAllowed (endpoint.Port))
                                                        return true;
@@ -114,7 +115,12 @@ namespace System.Net.Policy {
                        return true;
                }
 
-               public override bool IsAllowed (Uri uri, params string [] headerKeys)
+               public override bool IsAllowed (WebRequest request)
+               {
+                       return IsAllowed (request.RequestUri, request.Method, request.Headers.AllKeys);
+               }
+
+               public bool IsAllowed (Uri uri, string method, params string [] headerKeys)
                {
                        // at this stage the URI has removed the "offending" characters so we need to look at the original
                        if (!CheckOriginalPath (uri)) 
@@ -124,7 +130,7 @@ namespace System.Net.Policy {
                                // does something allow our URI in this policy ?
                                foreach (AllowFrom af in policy.AllowedServices) {
                                        // is the application (XAP) URI allowed by the policy ?
-                                       if (af.IsAllowed (ApplicationUri, headerKeys)) {
+                                       if (af.IsAllowed (ApplicationUri, method, headerKeys)) {
                                                foreach (GrantTo gt in policy.GrantedResources) {
                                                        // is the requested access to the Uri granted under this policy ?
                                                        if (gt.IsGranted (uri))
@@ -152,9 +158,11 @@ namespace System.Net.Policy {
 
                        public Headers HttpRequestHeaders { get; private set; }
 
+                       public bool AllowAnyMethod { get; set; }
+
                        public string Scheme { get; internal set; }
 
-                       public bool IsAllowed (Uri uri, string [] headerKeys)
+                       public bool IsAllowed (Uri uri, string method, string [] headerKeys)
                        {
                                // check headers
                                if (!HttpRequestHeaders.IsAllowed (headerKeys))
@@ -173,6 +181,16 @@ namespace System.Net.Policy {
                                                return false;
                                        }
                                }
+                               // check methods
+                               if (!AllowAnyMethod) {
+                                       // if not all methods are allowed (*) then only GET and POST request are possible
+                                       // further restriction exists in the Client http stack
+                                       if ((String.Compare (method, "GET", StringComparison.OrdinalIgnoreCase) != 0) &&
+                                               (String.Compare (method, "POST", StringComparison.OrdinalIgnoreCase) != 0)) {
+                                               return false;
+                                       }
+                               }
+
                                // check domains
                                if (AllowAnyDomain)
                                        return true;
index 52001176febcc540a171e8c59ec46e52f566e07c..f1cd5edb4085a97792a17d5dfa280633d33d41ac 100644 (file)
@@ -5,7 +5,7 @@
 //     Atsushi Enomoto <atsushi@ximian.com>
 //     Moonlight List (moonlight-list@lists.ximian.com)
 //
-// Copyright (C) 2009 Novell, Inc.  http://www.novell.com
+// Copyright (C) 2009-2010 Novell, Inc.  http://www.novell.com
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -97,14 +97,22 @@ namespace System.Net.Policy {
                                for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
                                        if (reader.NodeType != XmlNodeType.Element)
                                                throw new XmlException (String.Format ("Unexpected access-policy content: {0}", reader.NodeType));
-                                       if (reader.IsEmptyElement) {
+
+                                       if ((reader.LocalName != "cross-domain-access") || reader.IsEmptyElement) {
                                                reader.Skip ();
                                                continue;
                                        }
+
                                        reader.ReadStartElement ("cross-domain-access", String.Empty);
                                        for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
                                                if (reader.NodeType != XmlNodeType.Element)
                                                        throw new XmlException (String.Format ("Unexpected access-policy content: {0}", reader.NodeType));
+
+                                               if ((reader.Name != "policy") || reader.IsEmptyElement) {
+                                                       reader.Skip ();
+                                                       continue;
+                                               }
+
                                                ReadPolicyElement (reader, cap);
                                        }
                                        reader.ReadEndElement ();
@@ -116,22 +124,19 @@ namespace System.Net.Policy {
 
                static void ReadPolicyElement (XmlReader reader, ClientAccessPolicy cap)
                {
-                       if (reader.IsEmptyElement) {
+                       if (reader.HasAttributes || reader.IsEmptyElement) {
                                reader.Skip ();
                                return;
                        }
 
                        var policy = new AccessPolicy ();
-                       cap.AccessPolicyList.Add (policy);
+                       bool valid = true;
 
                        reader.ReadStartElement ("policy", String.Empty);
                        for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
                                if (reader.NodeType != XmlNodeType.Element)
                                        throw new XmlException (String.Format ("Unexpected policy content: {0}", reader.NodeType));
-                               if (reader.IsEmptyElement || !String.IsNullOrEmpty (reader.NamespaceURI)) {
-                                       reader.Skip ();
-                                       continue;
-                               }
+
                                switch (reader.LocalName) {
                                case "allow-from":
                                        ReadAllowFromElement (reader, policy);
@@ -140,24 +145,41 @@ namespace System.Net.Policy {
                                        ReadGrantToElement (reader, policy);
                                        break;
                                default:
+                                       valid = false;
                                        reader.Skip ();
-                                       continue;
+                                       break;
                                }
                        }
+
+                       if (valid)
+                               cap.AccessPolicyList.Add (policy);
                        reader.ReadEndElement ();
                }
 
                static void ReadAllowFromElement (XmlReader reader, AccessPolicy policy)
                {
-                       var v = new AllowFrom ();
-                       policy.AllowedServices.Add (v);
-
                        if (reader.IsEmptyElement) {
                                reader.Skip ();
                                return;
                        }
 
-                       v.HttpRequestHeaders.SetHeaders (reader.GetAttribute ("http-request-headers"));
+                       bool valid = true;
+                       string headers = null;
+                       string methods = null;          // new in SL3
+                       if (reader.HasAttributes) {
+                               int n = reader.AttributeCount;
+                               headers = reader.GetAttribute ("http-request-headers");
+                               if (headers != null)
+                                       n--;
+                               methods = reader.GetAttribute ("http-methods");
+                               if (methods != null)
+                                       n--;
+                               valid = (n == 0);
+                       }
+
+                       var v = new AllowFrom ();
+                       v.HttpRequestHeaders.SetHeaders (headers);
+                       v.AllowAnyMethod = (methods == "*"); // only legal value defined, otherwise restricted to GET and POST
                        reader.ReadStartElement ("allow-from", String.Empty);
                        for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
                                if (reader.NodeType != XmlNodeType.Element)
@@ -189,19 +211,41 @@ namespace System.Net.Policy {
                                        reader.Skip ();
                                        break;
                                default:
+                                       valid = false;
                                        reader.Skip ();
                                        continue;
                                }
                        }
+                       if (valid)
+                               policy.AllowedServices.Add (v);
                        reader.ReadEndElement ();
                }
 
+               // only "path" and "include-subpaths" attributes are allowed - anything else is not considered
+               static Resource CreateResource (XmlReader reader)
+               {
+                       int n = reader.AttributeCount;
+                       string path = reader.GetAttribute ("path");
+                       if (path != null)
+                               n--;
+                       string subpaths = reader.GetAttribute ("include-subpaths");
+                       if (subpaths != null)
+                               n--;
+                       if ((n != 0) || !reader.IsEmptyElement)
+                               return null;
+
+                       return new Resource () { 
+                               Path = path,
+                               IncludeSubpaths = subpaths == null ? false : XmlConvert.ToBoolean (subpaths)
+                       };
+               }
+
                static void ReadGrantToElement (XmlReader reader, AccessPolicy policy)
                {
                        var v = new GrantTo ();
-                       policy.GrantedResources.Add (v);
+                       bool valid = true;
 
-                       if (reader.IsEmptyElement) {
+                       if (reader.HasAttributes || reader.IsEmptyElement) {
                                reader.Skip ();
                                return;
                        }
@@ -214,15 +258,14 @@ namespace System.Net.Policy {
                                        reader.Skip ();
                                        continue;
                                }
+
                                switch (reader.LocalName) {
                                case "resource":
-                                       var r = new Resource ();
-                                       v.Resources.Add (r);
-                                       r.Path = reader.GetAttribute ("path");
-                                       if (reader.MoveToAttribute ("include-subpaths")) {
-                                               r.IncludeSubpaths = XmlConvert.ToBoolean (reader.Value);
-                                               reader.MoveToElement ();
-                                       }
+                                       var r = CreateResource (reader);
+                                       if (r == null)
+                                               valid = false;
+                                       else
+                                               v.Resources.Add (r);
                                        break;
                                case "socket-resource":
                                        // ignore everything that is not TCP
@@ -231,9 +274,14 @@ namespace System.Net.Policy {
                                        // we can merge them all together inside a policy
                                        policy.PortMask |= ParsePorts (reader.GetAttribute ("port"));
                                        break;
+                               default:
+                                       valid = false;
+                                       break;
                                }
                                reader.Skip ();
                        }
+                       if (valid)
+                               policy.GrantedResources.Add (v);
                        reader.ReadEndElement ();
                }
 
index 87848f6e71ad846f717ac7a4b234a02cadf69108..87acfea903569bbb4a08726e0647c0c0041f2683 100644 (file)
@@ -95,18 +95,34 @@ namespace System.Net.Policy {
                private static void AddPolicy (Uri responseUri, ICrossDomainPolicy policy)
                {
                        string root = GetRoot (responseUri);
-                       try {
-                               policies.Add (root, policy);
-                       }
-                       catch (ArgumentException) {
-                               // it's possible another request already added this root
+                       policies [root] = policy;
+               }
+
+               // see moon/test/2.0/WebPolicies/Pages.xaml.cs for all test cases
+               private static bool CheckContentType (string contentType)
+               {
+                       const string application_xml = "application/xml";
+
+                       // most common case: all text/* are accepted
+                       if (contentType.StartsWith ("text/"))
+                               return true;
+
+                       // special case (e.g. used in nbcolympics)
+                       if (contentType.StartsWith (application_xml)) {
+                               if (application_xml.Length == contentType.Length)
+                                       return true; // exact match
+
+                               // e.g. "application/xml; charset=x" - we do not care what comes after ';'
+                               if (contentType.Length > application_xml.Length)
+                                       return contentType [application_xml.Length] == ';';
                        }
+                       return false;
                }
 
                public static ICrossDomainPolicy BuildSilverlightPolicy (HttpWebResponse response)
                {
                        // return null if no Silverlight policy was found, since we offer a second chance with a flash policy
-                       if (response.StatusCode != HttpStatusCode.OK)
+                       if ((response.StatusCode != HttpStatusCode.OK) || !CheckContentType (response.ContentType))
                                return null;
 
                        ICrossDomainPolicy policy = null;
@@ -125,7 +141,7 @@ namespace System.Net.Policy {
                public static ICrossDomainPolicy BuildFlashPolicy (HttpWebResponse response)
                {
                        ICrossDomainPolicy policy = null;
-                       if (response.StatusCode == HttpStatusCode.OK) {
+                       if ((response.StatusCode == HttpStatusCode.OK) && CheckContentType (response.ContentType)) {
                                try {
                                        policy = FlashCrossDomainPolicy.FromStream (response.GetResponseStream ());
                                } catch (Exception ex) {
@@ -225,9 +241,30 @@ namespace System.Net.Policy {
                        return ms;
                }
 
-               public static ClientAccessPolicy CreateForEndPoint (IPEndPoint endpoint)
+               static Stream GetPolicyStream (Uri uri)
+               {
+                       // FIXME
+                       throw new NotSupportedException ("Fetching socket policy from " + uri.ToString () + " is not yet available in moonlight");
+               }
+
+               public static ClientAccessPolicy CreateForEndPoint (IPEndPoint endpoint, SocketClientAccessPolicyProtocol protocol)
                {
-                       Stream s = GetPolicyStream (endpoint);
+                       Stream s = null;
+
+                       switch (protocol) {
+                       case SocketClientAccessPolicyProtocol.Tcp:
+                               s = GetPolicyStream (endpoint);
+                               break;
+                       case SocketClientAccessPolicyProtocol.Http:
+                               // <quote>It will NOT attempt to download the policy via the custom TCP protocol if the 
+                               // policy check fails.</quote>
+                               // http://blogs.msdn.com/ncl/archive/2010/04/15/silverlight-4-socket-policy-changes.aspx
+                               string url = String.Format ("http://{0}:80{1}", endpoint.Address.ToString (), 
+                                       CrossDomainPolicyManager.ClientAccessPolicyFile);
+                               s = GetPolicyStream (new Uri (url));
+                               break;
+                       }
+
                        if (s == null)
                                return null;
 
@@ -243,7 +280,7 @@ namespace System.Net.Policy {
                        return policy;
                }
 
-               static public bool CheckEndPoint (EndPoint endpoint)
+               static public bool CheckEndPoint (EndPoint endpoint, SocketClientAccessPolicyProtocol protocol)
                {
                        // if needed transform the DnsEndPoint into a usable IPEndPoint
                        IPEndPoint ip = (endpoint as IPEndPoint);
@@ -254,7 +291,7 @@ namespace System.Net.Policy {
                        string address = ip.Address.ToString ();
                        ClientAccessPolicy policy = null;
                        if (!socket_policies.TryGetValue (address, out policy)) {
-                               policy = CreateForEndPoint (ip);
+                               policy = CreateForEndPoint (ip, protocol);
                                socket_policies.Add (address, policy);
                        }
 
index ee90aebb058bb00c5a0121e3eb10fa51081ad00b..fd15eeb8ae19e8d33da48ae596b6f30fdb43e504 100644 (file)
@@ -54,7 +54,12 @@ namespace System.Net.Policy {
                        set { site_control = value; }
                }
 
-               public override bool IsAllowed (Uri uri, string [] headerKeys)
+               public override bool IsAllowed (WebRequest request)
+               {
+                       return IsAllowed (request.RequestUri, request.Headers.AllKeys);
+               }
+
+               public bool IsAllowed (Uri uri, string [] headerKeys)
                {
                        switch (SiteControl) {
                        case "all":
index 22a6f966256645c2dac4cfb4df1fce3ff1908e52..5189455ac8a71bd9ae494661762922a72fa4dfa7 100644 (file)
@@ -83,9 +83,9 @@ namespace System.Net.Policy {
 
        partial class FlashCrossDomainPolicy {
 
-               static bool ReadBooleanAttribute (XmlReader reader, string attribute)
+               static bool ReadBooleanAttribute (string attribute)
                {
-                       switch (reader.GetAttribute (attribute)) {
+                       switch (attribute) {
                        case null:
                        case "true":
                                return true;
@@ -96,6 +96,55 @@ namespace System.Net.Policy {
                        }
                }
 
+               // only "domain" and "secure" attributes are allowed - anything else is considered invalid
+               static AllowAccessFrom CreateAllowAccessFrom (XmlReader reader)
+               {
+                       int n = reader.AttributeCount;
+                       string domain = reader.GetAttribute ("domain");
+                       if (domain != null)
+                               n--;
+                       string secure = reader.GetAttribute ("secure");
+                       if (secure != null)
+                               n--;
+                       if (n != 0)
+                               throw new XmlException ("unknown/unsupported attributes");
+
+                       return new AllowAccessFrom () { Domain = domain, Secure = ReadBooleanAttribute (secure) };
+               }
+
+               // only "domain", "secure" and "headers" attributes are allowed - anything else is considered invalid
+               static AllowHttpRequestHeadersFrom CreateAllowHttpRequestHeadersFrom (XmlReader reader)
+               {
+                       int n = reader.AttributeCount;
+                       string domain = reader.GetAttribute ("domain");
+                       if (domain != null)
+                               n--;
+                       string secure = reader.GetAttribute ("secure");
+                       if (secure != null)
+                               n--;
+                       string headers = reader.GetAttribute ("headers");
+                       if (headers != null)
+                               n--;
+                       if (n != 0)
+                               throw new XmlException ("unknown/unsupported attributes");
+
+                       var h = new AllowHttpRequestHeadersFrom () { Domain = domain, Secure = ReadBooleanAttribute (secure) };
+                       h.Headers.SetHeaders (headers);
+                       return h;
+               }
+
+               // only "permitted-cross-domain-policies" attribute is allowed - anything else is considered invalid
+               static string GetSiteControl (XmlReader reader)
+               {
+                       int n = reader.AttributeCount;
+                       string site = reader.GetAttribute ("permitted-cross-domain-policies");
+                       if (site != null)
+                               n--;
+                       if (n != 0)
+                               throw new XmlException ("unknown/unsupported attributes");
+                       return site;
+               }
+
                static public ICrossDomainPolicy FromStream (Stream stream)
                {
                        FlashCrossDomainPolicy cdp = new FlashCrossDomainPolicy ();
@@ -110,48 +159,39 @@ namespace System.Net.Policy {
                        using (XmlReader reader = XmlReader.Create (sr, policy_settings)) {
 
                                reader.MoveToContent ();
-                               if (reader.IsEmptyElement) {
+                               if (reader.HasAttributes || reader.IsEmptyElement) {
                                        reader.Skip ();
                                        return null;
                                }
 
-                               reader.ReadStartElement ("cross-domain-policy", String.Empty);
-                               for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
-                                       if (reader.NodeType != XmlNodeType.Element)
-                                               throw new XmlException (String.Format ("Unexpected cross-domain-policy content: {0}", reader.NodeType));
-                                       switch (reader.LocalName) {
-                                       case "site-control":
-                                               cdp.SiteControl = reader.GetAttribute ("permitted-cross-domain-policies");
-                                               reader.Skip ();
-                                               break;
-                                       case "allow-access-from":
-                                               var a = new AllowAccessFrom () {
-                                                       Domain = reader.GetAttribute ("domain"),
-                                                       Secure = ReadBooleanAttribute (reader, "secure") };
-/* Silverlight policies are used for sockets
-                                               var p = reader.GetAttribute ("to-ports");
-                                               if (p == "*")
-                                                       a.AllowAnyPort = true;
-                                               else if (p != null)
-                                                       a.ToPorts = Array.ConvertAll<string, int> (p.Split (','), s => XmlConvert.ToInt32 (s));
-*/
-                                               cdp.AllowedAccesses.Add (a);
-                                               reader.Skip ();
-                                               break;
-                                       case "allow-http-request-headers-from":
-                                               var h = new AllowHttpRequestHeadersFrom () {
-                                                       Domain = reader.GetAttribute ("domain"),
-                                                       Secure = ReadBooleanAttribute (reader, "secure") };
-                                               h.Headers.SetHeaders (reader.GetAttribute ("headers"));
-                                               cdp.AllowedHttpRequestHeaders.Add (h);
-                                               reader.Skip ();
-                                               break;
-                                       default:
-                                               reader.Skip ();
-                                               continue;
+                               while (!reader.EOF) {
+                                       reader.ReadStartElement ("cross-domain-policy", String.Empty);
+                                       for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
+                                               if (reader.NodeType != XmlNodeType.Element)
+                                                       throw new XmlException (String.Format ("Unexpected cross-domain-policy content: {0}", reader.NodeType));
+                                               switch (reader.LocalName) {
+                                               case "site-control":
+                                                       cdp.SiteControl = GetSiteControl (reader);
+                                                       reader.Skip ();
+                                                       break;
+                                               case "allow-access-from":
+                                                       var a = CreateAllowAccessFrom (reader);
+                                                       cdp.AllowedAccesses.Add (a);
+                                                       reader.Skip ();
+                                                       break;
+                                               case "allow-http-request-headers-from":
+                                                       var h = CreateAllowHttpRequestHeadersFrom (reader);
+                                                       cdp.AllowedHttpRequestHeaders.Add (h);
+                                                       reader.Skip ();
+                                                       break;
+                                               default:
+                                                       reader.Skip ();
+                                                       return null;
+                                               }
                                        }
+                                       reader.ReadEndElement ();
+                                       reader.MoveToContent ();
                                }
-                               reader.ReadEndElement ();
                        }
 
                        // if none supplied set a default for headers
index 382f28b43fc8a4cdf3774edd66e11f08d643b385..adc52712b6ae6a5a60f463f2ebb981accaecf24e 100644 (file)
@@ -1,3 +1,12 @@
+2010-04-21  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * SocketClientAccessPolicyProtocol.cs: New SL4 enum to select TCP
+       (default) or HTTP (new) to retrieve the socket xdomain policy
+
+2010-03-19  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * SocketException_2_1.cs: Add extra ctor (soon to be used)
+
 2009-04-28  Sebastien Pouliot  <sebastien@ximian.com>
 
        * SocketException_2_1.cs: Remove extra ctor and property unused in 2.1
diff --git a/mcs/class/System.Net/System.Net.Sockets/SocketClientAccessPolicyProtocol.cs b/mcs/class/System.Net/System.Net.Sockets/SocketClientAccessPolicyProtocol.cs
new file mode 100644 (file)
index 0000000..c34dc4f
--- /dev/null
@@ -0,0 +1,31 @@
+//
+// SocketClientAccessPolicyProtocol.cs (Silverlight specific)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+namespace System.Net.Sockets {
+
+       public enum SocketClientAccessPolicyProtocol {
+               Tcp,
+               Http
+       }
+}
+
index 9d040c2c5651654216b4c86d341c752d4d0147da..133ec798dc255020fe68faf44d1dc5c5707d089f 100644 (file)
@@ -48,6 +48,12 @@ namespace System.Net.Sockets {
                        error_code = error;
                }
 
+               internal SocketException (int error, string message)
+                       : base (message)
+               {
+                       error_code = error;
+               }
+
                public int ErrorCode {
                        get { return error_code; }
                }
index 8dab13acca7e5b40bd6c97836644a846c1b26c85..d7066e11f1ef8e1865cc38316e8e04b1eba650f8 100644 (file)
@@ -1,3 +1,46 @@
+2010-04-21  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * HttpWebResponse_2_1.cs: Method, StatusCode and StatusDescription
+       property getters are now virtual (instead of abstract) and throw
+       NIE in SL4 (final) API.
+       * WebRequest_2_1.cs: Added ContentLength (SL4) property to throw
+       NIE. Implement (SL4) CreateHttp methods. Rework stack registration
+       logic.
+       * WebResponse_2_1.cs: default Headers getter throws NIE
+
+2010-04-05  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * InternalWebResponseStreamWrapper.cs: Move back to 
+       System.Windows.dll
+
+2010-03-19  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * HttpWebRequest_2_1.cs: AllowWriteStreamBuffering getter/setter
+       throws NIE by default (must be overridden). Revert Accept and
+       ContentType behavior to SL2 (identical to SL4 but different from
+       SL3). 
+       * WebClient_2_1.cs: Initialize UseDefaultCredentials to true. Set
+       the properties when creating a new WebRequest
+
+2010-03-18  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * HttpWebRequest_2_1.cs: Add SL4 RC AllowWriteStreamBuffering and
+       SupportsCookieContainer properties.
+       * WebClient_2_1.cs: Add SL4 RC AllowWriteStreamBuffering and 
+       UseDefaultCredentials properties.
+       * WebHeaderCollection_2_1.cs: Authorization and Proxy-Authorization
+       are valid (i.e. usable) headers in SL4 (in both stacks)
+
+2010-03-16  Rolf Bjarne Kvinge  <RKvinge@novell.com>
+
+       * WebRequest_2_1.cs: Added UseDefaultCredentials property.
+
+2010-03-12  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * WebClient_2_1.cs: Directly set 'progress' delegate field
+       * WebRequest_2_1.cs: Avoid using reflection (since it was not 
+       really needed anyway)
+
 2010-03-03  Andreia Gaita  <avidigal@novell.com>
 
        * InternalWebRequestStreamWrapper.cs: don't add a newline to the
index 4f980982895959cd5a1cd8aab24450fad0ba16c9..e2fccc637c47b6d8beebe2548834221c022baadf 100644 (file)
@@ -53,13 +53,7 @@ namespace System.Net {
                public string Accept {
                        get { return Headers [HttpRequestHeader.Accept]; }
                        // this header cannot be set directly inside the collection (hence the helper)
-                       set {
-                               if (value == null)
-                                       throw new ArgumentNullException ("Accept");
-                               if (value.Length == 0)
-                                       throw new ArgumentException ("Accept");
-                               Headers.SetHeader ("accept", value);
-                       }
+                       set { Headers.SetHeader ("accept", value); }
                }
 
                public virtual bool AllowReadStreamBuffering {
@@ -67,16 +61,16 @@ namespace System.Net {
                        set { throw NotImplemented (); }
                }
 
+               // new in SL4 RC
+               public virtual bool AllowWriteStreamBuffering {
+                       get { throw NotImplemented (); }
+                       set { throw NotImplemented (); }
+               }
+
                public override string ContentType {
                        get { return Headers [HttpRequestHeader.ContentType]; }
                        // this header cannot be set directly inside the collection (hence the helper)
-                       set {
-                               if (value == null)
-                                       throw new ArgumentNullException ("ContentType");
-                               if (value.Length == 0)
-                                       throw new ArgumentException ("ContentType");
-                               Headers.SetHeader ("content-type", value);
-                       }
+                       set { Headers.SetHeader ("content-type", value); }
                }
 
                public virtual bool HaveResponse {
@@ -119,6 +113,10 @@ namespace System.Net {
                        get { throw NotImplemented (); }
                }
 
+               // new in SL4 RC
+               public virtual bool SupportsCookieContainer {
+                       get { return false; }
+               }
 
                public override void Abort ()
                {
index 53dd52fe813a160134a8fc0b36f3720f557676dc..d26af21025023478d58626d169e8921651806e6d 100644 (file)
@@ -35,9 +35,17 @@ namespace System.Net {
 
        public abstract class HttpWebResponse : WebResponse {
 
-               public abstract string Method { get; }
-               public abstract HttpStatusCode StatusCode { get; }
-               public abstract string StatusDescription { get; }
+               public virtual string Method {
+                       get { throw NotImplemented (); }
+               }
+
+               public virtual HttpStatusCode StatusCode {
+                       get { throw NotImplemented (); }
+               }
+
+               public virtual string StatusDescription {
+                       get { throw NotImplemented (); }
+               }
 
                public virtual CookieCollection Cookies { 
                        get { throw NotImplemented (); }
diff --git a/mcs/class/System.Net/System.Net/InternalWebResponseStreamWrapper.cs b/mcs/class/System.Net/System.Net/InternalWebResponseStreamWrapper.cs
deleted file mode 100644 (file)
index 00d44fa..0000000
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * InternalWebResponseStreamWrapper.cs.
- *
- * Contact:
- *   Moonlight List (moonlight-list@lists.ximian.com)
- *
- * Copyright 2008,2010 Novell, Inc. (http://www.novell.com)
- *
- * See the LICENSE file included with the distribution for details.
- * 
- */
-
-using System.IO;
-
-namespace System.Net {
-
-       // simply a read-only wrapper around a stream + a no-op Close
-       internal sealed class InternalWebResponseStreamWrapper : Stream {
-
-               private Stream stream;
-               
-               internal InternalWebResponseStreamWrapper (Stream s)
-               {
-                       stream = s;
-               }
-
-               public override bool CanRead {
-                       get {
-                                return stream.CanRead;
-                       }
-               }
-
-               public override bool CanSeek {
-                       get {
-                                return stream.CanSeek;
-                       }
-               }
-
-               public override bool CanWrite {
-                       get {
-                                return false;
-                       }
-               }
-
-               public override long Length {
-                       get {
-                                return stream.Length;
-                       }
-               }
-
-               public override long Position {
-                       get {
-                                return stream.Position;
-                       }
-                       set {
-                               stream.Position = value;
-                       }
-               }
-
-               public override void Flush ()
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override void Close ()
-               {
-                       // We cannot call "stream.Close" on a memory stream since it deletes the data
-               }
-
-               public override void SetLength (long value)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override int Read (byte [] buffer, int offset, int count)
-               {
-                       return stream.Read (buffer, offset, count);
-               }
-
-               public override void Write (byte [] buffer, int offset, int count)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override void WriteByte (byte value)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               public override long Seek (long offset, SeekOrigin origin)
-               {
-                       return stream.Seek (offset, origin);
-               }
-
-               internal Stream InnerStream {
-                       get { return stream; }
-               }
-       }
-}
-
index 0fc7bf404e6f2d368f57500597211b2899abdee4..1487adc40b62382f791f2bfd94b73d82e2829099 100644 (file)
@@ -47,6 +47,7 @@ namespace System.Net {
                bool is_busy;
                Encoding encoding = Encoding.UTF8;
                bool allow_read_buffering = true;
+               bool allow_write_buffering = true;
                WebRequest request;
                object locker;
                CallbackData callback_data;
@@ -59,6 +60,7 @@ namespace System.Net {
                        // but it happens that MS SL2 also has this default .ctor as SSC :-)
                        baseAddress = (AppDomain.CurrentDomain.GetData ("xap_uri") as string);
                        locker = new object ();
+                       UseDefaultCredentials = true;
                }
                
                // Properties
@@ -115,6 +117,17 @@ namespace System.Net {
                        set { allow_read_buffering = value; }
                }
 
+               // new in SL4 RC
+               [MonoTODO ("value is unused, current implementation always works like it's true (default)")]
+               public bool AllowWriteStreamBuffering {
+                       get { return allow_write_buffering; }
+                       set { allow_write_buffering = value; }
+               }
+
+               public bool UseDefaultCredentials {
+                       get; set;
+               }
+
                // Methods
 
                void CheckBusy ()
@@ -536,14 +549,17 @@ namespace System.Net {
                        // if the URI is relative then we use our base address URI to make an absolute one
                        Uri uri = address.IsAbsoluteUri ? address : new Uri (new Uri (baseAddress), address);
 
-                       WebRequest request = WebRequest.Create (uri);
+                       HttpWebRequest request = (HttpWebRequest) WebRequest.Create (uri);
+                       request.AllowReadStreamBuffering = AllowReadStreamBuffering;
+                       request.AllowWriteStreamBuffering = AllowWriteStreamBuffering;
+                       request.UseDefaultCredentials = UseDefaultCredentials;
 
-                       request.SetupProgressDelegate (delegate (long read, long length) {
+                       request.progress = delegate (long read, long length) {
                                callback_data.sync_context.Post (delegate (object sender) {
                                        OnDownloadProgressChanged (new DownloadProgressChangedEventArgs (read, length, callback_data.user_token));
                                }, null);
 
-                       });
+                       };
                        return request;
                }
 
index 61274562a4d91770a19a1139a9adcd7712d2b914..c12528ccddeb2a8461803005a3e3d176a34c4272 100644 (file)
@@ -220,13 +220,11 @@ namespace System.Net {
                        case "accept-charset":
                        case "accept-encoding":
                        case "accept-language":
-                       case "authorization":
                        case "cookie":
                        case "expect":
                        case "host":
                        case "if-modified-since":
                        case "max-forwards":
-                       case "proxy-authorization":
                        case "referer":
                        case "te":
                        case "user-agent":
index 68b18aa63b29346a40a346161412b9cc3a51b3cf..8edf07bc1be57dcf25f8c4eaf639f5a8118612e3 100644 (file)
 
 #if NET_2_1
 
-using System;
 using System.Collections.Generic;
 using System.IO;
-using System.Reflection;
 
 namespace System.Net {
 
        public abstract class WebRequest {
 
+               const string SystemWindows = "System.Windows, PublicKey=00240000048000009400000006020000002400005253413100040000010001008D56C76F9E8649383049F383C44BE0EC204181822A6C31CF5EB7EF486944D032188EA1D3920763712CCB12D75FB77E9811149E6148E5D32FBAAB37611C1878DDC19E20EF135D0CB2CFF2BFEC3D115810C3D9069638FE4BE215DBF795861920E5AB6F7DB2E2CEEF136AC23D5DD2BF031700AEC232F6C6B1C785B4305C123B37AB";
+               const string BrowserStack = "System.Net.Browser.BrowserHttpWebRequestCreator, " + SystemWindows;
+               const string ClientStack = "System.Net.Browser.ClientHttpWebRequestCreator, " + SystemWindows;
+
                static IWebRequestCreate default_creator;
+               static IWebRequestCreate browser_creator;
+               static IWebRequestCreate client_creator;
                static Dictionary<string, IWebRequestCreate> registred_prefixes;
 
+               internal Action<long,long> progress;
+
                public abstract string ContentType { get; set; }
                public abstract WebHeaderCollection Headers { get; set; }
                public abstract string Method { get; set; }
                public abstract Uri RequestUri { get; }
 
+               public virtual long ContentLength {
+                       get { throw NotImplemented (); }
+                       set { throw NotImplemented (); }
+               }
+
                // custom registered prefixes return null (unless they override this)
                public virtual IWebRequestCreate CreatorInstance { 
                        get { return null; }
@@ -58,9 +69,17 @@ namespace System.Net {
                        set { throw NotImplemented (); }
                }
 
+               public virtual bool UseDefaultCredentials {
+                       get { throw NotImplemented (); }
+                       set { throw NotImplemented (); }
+               }
+
                static WebRequest ()
                {
                        registred_prefixes = new Dictionary<string, IWebRequestCreate> (StringComparer.OrdinalIgnoreCase);
+                       browser_creator = (IWebRequestCreate) Activator.CreateInstance (Type.GetType (BrowserStack));
+                       client_creator = (IWebRequestCreate) Activator.CreateInstance (Type.GetType (ClientStack));
+                       default_creator = browser_creator;
                }
 
                protected WebRequest ()
@@ -118,9 +137,26 @@ namespace System.Net {
                        return creator.Create (uri);
                }
 
-               internal static void RegisterDefaultStack (IWebRequestCreate creator)
+               public static HttpWebRequest CreateHttp (string requestUriString)
+               {
+                       return CreateHttp (new Uri (requestUriString));
+               }
+
+               public static HttpWebRequest CreateHttp (Uri uri)
                {
-                       default_creator = creator;
+                       if (uri == null)
+                               throw new ArgumentNullException ("uri");
+                       if (!uri.IsAbsoluteUri)
+                               throw new InvalidOperationException ("Uri is not absolute.");
+
+                       // we do not check the registred prefixes from CreateHttp and *always* use the client HTTP stack
+                       switch (uri.Scheme) {
+                       case "http":
+                       case "https":
+                               return (HttpWebRequest) client_creator.Create (uri);
+                       default:
+                               throw new NotSupportedException (string.Format ("Scheme {0} not supported", uri.Scheme));
+                       }
                }
 
                // We can register for
@@ -150,13 +186,6 @@ namespace System.Net {
                        return true;
                }
 
-               internal void SetupProgressDelegate (Action<long,long> progress)
-               {
-                       FieldInfo fi = GetType ().GetField ("progress", BindingFlags.Instance | BindingFlags.NonPublic);
-                       if (fi != null)
-                               fi.SetValue (this, progress);
-               }
-
                static Exception NotImplemented ()
                {
                        // hide the "normal" NotImplementedException from corcompare-like tools
index b1205b11aa194a482e24fd9c3f8951e177f7d685..4431d2e19965a65875a39bcd29d74163d42b14ff 100644 (file)
@@ -30,7 +30,6 @@
 
 #if NET_2_1
 
-using System;
 using System.IO;
 
 namespace System.Net {
@@ -41,7 +40,14 @@ namespace System.Net {
                public abstract string ContentType { get; }
                public abstract Uri ResponseUri { get; }
 
-               public virtual WebHeaderCollection Headers { get; internal set; }
+               public virtual WebHeaderCollection Headers {
+                       get { throw NotImplemented (); }
+                       internal set { ; }
+               }
+
+               public virtual bool SupportsHeaders {
+                       get { return false; }
+               }
 
                protected WebResponse ()
                {
@@ -54,6 +60,12 @@ namespace System.Net {
                {
                        Close ();
                }
+
+               static Exception NotImplemented ()
+               {
+                       // hide the "normal" NotImplementedException from corcompare-like tools
+                       return new NotImplementedException ();
+               }
        }
 }
 
diff --git a/mcs/class/System.Net/moonlight_raw_System.Net.dll.sources b/mcs/class/System.Net/moonlight_raw_System.Net.dll.sources
new file mode 100644 (file)
index 0000000..5a6bebc
--- /dev/null
@@ -0,0 +1,75 @@
+Assembly/AssemblyInfo.cs
+System.Net/Dns_2_1.cs
+System.Net/HttpWebRequest_2_1.cs
+System.Net/HttpWebResponse_2_1.cs
+System.Net/InternalWebRequestStreamWrapper.cs
+System.Net/WebExceptionStatus_2_1.cs
+System.Net/WebHeaderCollection_2_1.cs
+System.Net/WebClient_2_1.cs
+System.Net/WebRequest_2_1.cs
+System.Net/WebResponse_2_1.cs
+System.Net/WriteStreamClosedEventArgs_2_1.cs
+System.Net/WriteStreamClosedEventHandler_2_1.cs
+System.Net.Sockets/AddressFamily_2_1.cs
+System.Net.Sockets/ProtocolType_2_1.cs
+System.Net.Sockets/SocketClientAccessPolicyProtocol.cs
+System.Net.Sockets/SocketAsyncOperation_2_1.cs
+System.Net.Sockets/SocketException_2_1.cs
+System.Net.Sockets/SocketType_2_1.cs
+System.Net.Sockets/UdpAnySourceMulticastClient.cs
+System.Net.Sockets/UdpSingleSourceMulticastClient.cs
+System.Net.NetworkInformation/NetworkChange_2_1.cs
+System.Net.NetworkInformation/NetworkInterface_2_1.cs
+System.Net.Policy/BaseDomainPolicy.cs
+System.Net.Policy/ClientAccessPolicy.cs
+System.Net.Policy/ClientAccessPolicyParser.cs
+System.Net.Policy/CrossDomainPolicyManager.cs
+System.Net.Policy/FlashCrossDomainPolicy.cs
+System.Net.Policy/FlashCrossDomainPolicyParser.cs
+System.Net.Policy/ICrossDomainPolicy.cs
+System.Net.Policy/NoAccessPolicy.cs
+System.Net.Policy/PolicyDownloadPolicy.cs
+System.Net.Policy/SiteOfOriginPolicy.cs
+../System/System.Net/Cookie.cs
+../System/System.Net/CookieCollection.cs
+../System/System.Net/CookieContainer.cs
+../System/System.Net/CookieException.cs
+../System/System.Net/DnsEndPoint.cs
+../System/System.Net/EndPoint.cs
+../System/System.Net/HttpRequestHeader.cs
+../System/System.Net/HttpResponseHeader.cs
+../System/System.Net/HttpStatusCode.cs
+../System/System.Net/ICredentialLookup.cs
+../System/System.Net/IPAddress.cs
+../System/System.Net/IPEndPoint.cs
+../System/System.Net/IPHostEntry.cs
+../System/System.Net/IPv6Address.cs
+../System/System.Net/IWebRequestCreate.cs
+../System/System.Net/NetworkCredential.cs
+../System/System.Net/ProtocolViolationException.cs
+../System/System.Net/SocketAddress.cs
+../System/System.Net.Sockets/LingerOption.cs
+../System/System.Net.Sockets/MulticastOption.cs
+../System/System.Net.Sockets/ProtocolFamily.cs
+../System/System.Net.Sockets/SelectMode.cs
+../System/System.Net.Sockets/Socket_2_1.cs
+../System/System.Net.Sockets/SocketError.cs
+../System/System.Net.Sockets/SocketFlags.cs
+../System/System.Net.Sockets/SocketOptionLevel.cs
+../System/System.Net.Sockets/SocketOptionName.cs
+../System/System.Net.Sockets/SocketShutdown.cs
+../System/System.Net.Sockets/SocketAsyncEventArgs.cs
+../System/System.Net/WebException.cs
+../System/System.Net/DownloadProgressChangedEventArgs.cs
+../System/System.Net/DownloadProgressChangedEventHandler.cs
+../System/System.Net/DownloadStringCompletedEventArgs.cs
+../System/System.Net/DownloadStringCompletedEventHandler.cs
+../System/System.Net/OpenReadCompletedEventArgs.cs
+../System/System.Net/OpenReadCompletedEventHandler.cs
+../System/System.Net/OpenWriteCompletedEventArgs.cs
+../System/System.Net/OpenWriteCompletedEventHandler.cs
+../System/System.Net/UploadProgressChangedEventArgs.cs
+../System/System.Net/UploadProgressChangedEventHandler.cs
+../System/System.Net/UploadStringCompletedEventArgs.cs
+../System/System.Net/UploadStringCompletedEventHandler.cs
+../System/System.Net.NetworkInformation/NetworkAddressChangedEventHandler.cs
diff --git a/mcs/class/System.Net/net_2_1_raw_System.Net.dll.sources b/mcs/class/System.Net/net_2_1_raw_System.Net.dll.sources
deleted file mode 100644 (file)
index 85566a0..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-Assembly/AssemblyInfo.cs
-System.Net/Dns_2_1.cs
-System.Net/HttpWebRequest_2_1.cs
-System.Net/HttpWebResponse_2_1.cs
-System.Net/InternalWebRequestStreamWrapper.cs
-System.Net/InternalWebResponseStreamWrapper.cs
-System.Net/WebExceptionStatus_2_1.cs
-System.Net/WebHeaderCollection_2_1.cs
-System.Net/WebClient_2_1.cs
-System.Net/WebRequest_2_1.cs
-System.Net/WebResponse_2_1.cs
-System.Net/WriteStreamClosedEventArgs_2_1.cs
-System.Net/WriteStreamClosedEventHandler_2_1.cs
-System.Net.Sockets/AddressFamily_2_1.cs
-System.Net.Sockets/SocketException_2_1.cs
-System.Net.Sockets/ProtocolType_2_1.cs
-System.Net.Sockets/SocketAsyncOperation_2_1.cs
-System.Net.Sockets/SocketType_2_1.cs
-System.Net.Sockets/UdpAnySourceMulticastClient.cs
-System.Net.Sockets/UdpSingleSourceMulticastClient.cs
-System.Net.NetworkInformation/NetworkChange_2_1.cs
-System.Net.NetworkInformation/NetworkInterface_2_1.cs
-System.Net.Policy/BaseDomainPolicy.cs
-System.Net.Policy/ClientAccessPolicy.cs
-System.Net.Policy/ClientAccessPolicyParser.cs
-System.Net.Policy/CrossDomainPolicyManager.cs
-System.Net.Policy/FlashCrossDomainPolicy.cs
-System.Net.Policy/FlashCrossDomainPolicyParser.cs
-System.Net.Policy/ICrossDomainPolicy.cs
-System.Net.Policy/NoAccessPolicy.cs
-System.Net.Policy/PolicyDownloadPolicy.cs
-System.Net.Policy/SiteOfOriginPolicy.cs
-../System/System.Net/Cookie.cs
-../System/System.Net/CookieCollection.cs
-../System/System.Net/CookieContainer.cs
-../System/System.Net/CookieException.cs
-../System/System.Net/DnsEndPoint.cs
-../System/System.Net/EndPoint.cs
-../System/System.Net/HttpRequestHeader.cs
-../System/System.Net/HttpResponseHeader.cs
-../System/System.Net/HttpStatusCode.cs
-../System/System.Net/ICredentialLookup.cs
-../System/System.Net/IPAddress.cs
-../System/System.Net/IPEndPoint.cs
-../System/System.Net/IPHostEntry.cs
-../System/System.Net/IPv6Address.cs
-../System/System.Net/IWebRequestCreate.cs
-../System/System.Net/NetworkCredential.cs
-../System/System.Net/ProtocolViolationException.cs
-../System/System.Net/SocketAddress.cs
-../System/System.Net.Sockets/LingerOption.cs
-../System/System.Net.Sockets/MulticastOption.cs
-../System/System.Net.Sockets/ProtocolFamily.cs
-../System/System.Net.Sockets/SelectMode.cs
-../System/System.Net.Sockets/Socket_2_1.cs
-../System/System.Net.Sockets/SocketError.cs
-../System/System.Net.Sockets/SocketFlags.cs
-../System/System.Net.Sockets/SocketOptionLevel.cs
-../System/System.Net.Sockets/SocketOptionName.cs
-../System/System.Net.Sockets/SocketShutdown.cs
-../System/System.Net.Sockets/SocketAsyncEventArgs.cs
-../System/System.Net/WebException.cs
-../System/System.Net/DownloadProgressChangedEventArgs.cs
-../System/System.Net/DownloadProgressChangedEventHandler.cs
-../System/System.Net/DownloadStringCompletedEventArgs.cs
-../System/System.Net/DownloadStringCompletedEventHandler.cs
-../System/System.Net/OpenReadCompletedEventArgs.cs
-../System/System.Net/OpenReadCompletedEventHandler.cs
-../System/System.Net/OpenWriteCompletedEventArgs.cs
-../System/System.Net/OpenWriteCompletedEventHandler.cs
-../System/System.Net/UploadProgressChangedEventArgs.cs
-../System/System.Net/UploadProgressChangedEventHandler.cs
-../System/System.Net/UploadStringCompletedEventArgs.cs
-../System/System.Net/UploadStringCompletedEventHandler.cs
-../System/System.Net.NetworkInformation/NetworkAddressChangedEventHandler.cs
index 5a833c6403a9c5b637b78913d1b1dbd0bdb30ef3..01204baf424425609b3004a0ca3ef82752eeb246 100644 (file)
@@ -1,3 +1,7 @@
+2010-04-23  Marek Safar <marek.safar@gmail.com>
+
+       * Complex.cs: Add explicit BigInteger operator.
+
 2010-03-06 Rodrigo Kumpera  <rkumpera@novell.com>
 
        * BigInteger.cs: Simply Parse/TryParse.
index 86090e249786f4eb02e625b75f79fb98d659e167..c5d94e0970e09144a8404f63200aaf2ec61bc632 100644 (file)
@@ -5,7 +5,7 @@
 //   Miguel de Icaza (miguel@gnome.org)
 //   Marek Safar (marek.safar@gmail.com)
 //
-// Copyright 2009 Novell, Inc.
+// Copyright 2009, 2010 Novell, Inc.
 //
 //
 //
@@ -179,10 +179,10 @@ namespace System.Numerics {
                        return new Complex ((double) value, 0);
                }
 
-               //public static explicit operator Complex (BigInteger value)
-               //{
-               //      return new Complex ((double) value, 0);
-               //}
+               public static explicit operator Complex (BigInteger value)
+               {
+                       return new Complex ((double) value, 0);
+               }
 
                public override string ToString ()
                {
diff --git a/mcs/class/System.Runtime.Caching/Assembly/AssemblyInfo.cs b/mcs/class/System.Runtime.Caching/Assembly/AssemblyInfo.cs
new file mode 100644 (file)
index 0000000..b5d614f
--- /dev/null
@@ -0,0 +1,70 @@
+//
+// AssemblyInfo.cs
+//
+// Author:
+//   Andreas Nahr (ClassDevelopment@A-SoftTech.com)
+//
+// (C) 2003 Ximian, Inc.  http://www.ximian.com
+// (C) 2010 Novell, Inc (http://novell.com/)
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Reflection;
+using System.Resources;
+using System.Security;
+using System.Security.Permissions;
+using System.Diagnostics;
+using System.Runtime;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+
+[assembly: AssemblyTitle ("System.Runtime.Caching.dll")]
+[assembly: AssemblyDescription ("System.Runtime.Caching.dll")]
+[assembly: AssemblyDefaultAlias ("System.Runtime.Caching.dll")]
+
+[assembly: AssemblyCompany (Consts.MonoCompany)]
+[assembly: AssemblyProduct (Consts.MonoProduct)]
+[assembly: AssemblyCopyright (Consts.MonoCopyright)]
+[assembly: AssemblyVersion (Consts.FxVersion)]
+[assembly: SatelliteContractVersion (Consts.FxVersion)]
+[assembly: AssemblyInformationalVersion (Consts.FxFileVersion)]
+[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
+
+[assembly: NeutralResourcesLanguage ("en-US")]
+[assembly: CLSCompliant (true)]
+[assembly: AssemblyDelaySign (true)]
+
+[assembly: ComVisible (false)]
+
+[assembly: CompilationRelaxations (CompilationRelaxations.NoStringInterning)]
+[assembly: RuntimeCompatibility (WrapNonExceptionThrows = true)]
+[assembly: SecurityPermission (SecurityAction.RequestMinimum, SkipVerification = true)]
+
+[assembly: AssemblyKeyFile ("../msfinal.pub")]
+
+[assembly: AssemblyTargetedPatchBand ("1.0.21-0")]
+[assembly: Debuggable (DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
+[assembly: AllowPartiallyTrustedCallers]
+[assembly: SecurityRules (SecurityRuleSet.Level2, SkipVerificationInFullTrust=true)]
diff --git a/mcs/class/System.Runtime.Caching/Assembly/ChangeLog b/mcs/class/System.Runtime.Caching/Assembly/ChangeLog
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/mcs/class/System.Runtime.Caching/ChangeLog b/mcs/class/System.Runtime.Caching/ChangeLog
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/mcs/class/System.Runtime.Caching/Makefile b/mcs/class/System.Runtime.Caching/Makefile
new file mode 100644 (file)
index 0000000..e72dfce
--- /dev/null
@@ -0,0 +1,23 @@
+thisdir = class/System.Runtime.Caching
+SUBDIRS = 
+include ../../build/rules.make
+
+LIBRARY = System.Runtime.Caching.dll
+LIB_MCS_FLAGS = -r:System.dll \
+               -r:System.Data.dll \
+               -r:System.Configuration.dll \
+               -r:System.Core.dll
+
+TEST_MCS_FLAGS = $(LIB_MCS_FLAGS)
+
+EXTRA_DISTFILES = $(RESOURCE_FILES)
+
+VALID_PROFILE := $(filter 4.0, $(FRAMEWORK_VERSION))
+ifndef VALID_PROFILE
+LIBRARY_NAME = dummy-System.Runtime.Caching.dll
+NO_INSTALL = yes
+NO_SIGN_ASSEMBLY = yes
+NO_TEST = yes
+endif
+
+include ../../build/library.make
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching.Configuration/CachingSectionGroup.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching.Configuration/CachingSectionGroup.cs
new file mode 100644 (file)
index 0000000..41bf83c
--- /dev/null
@@ -0,0 +1,44 @@
+//
+// CachingSectionGroup.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Configuration;
+
+namespace System.Runtime.Caching.Configuration
+{
+       public sealed class CachingSectionGroup : ConfigurationSectionGroup
+       {
+               [ConfigurationProperty ("memoryCache")]
+               public MemoryCacheSection MemoryCaches {
+                       get { return Sections ["memoryCache"] as MemoryCacheSection; }
+               }
+               
+               public CachingSectionGroup ()
+               {
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching.Configuration/ChangeLog b/mcs/class/System.Runtime.Caching/System.Runtime.Caching.Configuration/ChangeLog
new file mode 100644 (file)
index 0000000..408ba9d
--- /dev/null
@@ -0,0 +1,5 @@
+2010-04-24  Marek Habersack  <mhabersack@novell.com>
+
+       * MemoryCacheSettingsCollection.cs: added and implemented methods
+       which appeared in .NET 4.0 final.
+
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching.Configuration/MemoryCacheElement.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching.Configuration/MemoryCacheElement.cs
new file mode 100644 (file)
index 0000000..f7f3336
--- /dev/null
@@ -0,0 +1,110 @@
+//
+// MemoryCacheElement.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.ComponentModel;
+using System.Configuration;
+
+namespace System.Runtime.Caching.Configuration
+{
+       public sealed class MemoryCacheElement : ConfigurationElement
+       {
+               static ConfigurationProperty cacheMemoryLimitMegabytesProp;
+               static ConfigurationProperty nameProp;
+               static ConfigurationProperty physicalMemoryLimitPercentageProp;
+               static ConfigurationProperty pollingIntervalProp;
+               static ConfigurationPropertyCollection properties;
+               
+               [ConfigurationProperty ("cacheMemoryLimitMegabytes", DefaultValue = 0)]
+               [IntegerValidator (MinValue = 1)]
+               public int CacheMemoryLimitMegabytes {
+                       get { return (int) base [cacheMemoryLimitMegabytesProp]; }
+                       set { base [cacheMemoryLimitMegabytesProp] = value; }
+               }
+
+               [ConfigurationProperty ("name", DefaultValue = "", IsRequired = true, IsKey = true)]
+               [TypeConverter (typeof(WhiteSpaceTrimStringConverter))]
+               [StringValidator (MinLength = 1)]
+               public string Name {
+                       get { return (string) base [nameProp]; }
+                       set { base [nameProp] = value; }
+               }
+
+               [ConfigurationProperty ("physicalMemoryLimitPercentage", DefaultValue = 0)]
+               [IntegerValidator (MinValue = 1, MaxValue = 100)]
+               public int PhysicalMemoryLimitPercentage {
+                       get { return (int) base [physicalMemoryLimitPercentageProp]; }
+                       set { base [physicalMemoryLimitPercentageProp] = value; }
+               }
+               
+               [ConfigurationProperty ("pollingInterval", DefaultValue = "00:02:00")]
+               [TypeConverter (typeof(InfiniteTimeSpanConverter))]
+               public TimeSpan PollingInterval {
+                       get { return (TimeSpan) base [pollingIntervalProp]; }
+                       set { base [pollingIntervalProp] = value; }
+               }
+
+               protected override ConfigurationPropertyCollection Properties {
+                       get { return properties; }
+               }
+               
+               static MemoryCacheElement ()
+               {
+                       cacheMemoryLimitMegabytesProp = new ConfigurationProperty ("cacheMemoryLimitMegabytes", typeof (int), 0,
+                                                                                  TypeDescriptor.GetConverter (typeof (int)),
+                                                                                  new IntegerValidator (1, Int32.MaxValue),
+                                                                                  ConfigurationPropertyOptions.None);
+                       nameProp = new ConfigurationProperty ("name", typeof (string), String.Empty,
+                                                             TypeDescriptor.GetConverter (typeof (string)),
+                                                             new NullableStringValidator (1),
+                                                             ConfigurationPropertyOptions.IsKey | ConfigurationPropertyOptions.IsRequired);
+                       physicalMemoryLimitPercentageProp = new ConfigurationProperty ("physicalMemoryLimitPercentage", typeof (int), 0,
+                                                                                      TypeDescriptor.GetConverter (typeof (int)),
+                                                                                      new IntegerValidator (1, 100),
+                                                                                      ConfigurationPropertyOptions.None);
+                       pollingIntervalProp = new ConfigurationProperty ("pollingInterval", typeof (TimeSpan), TimeSpan.FromMinutes (2),
+                                                                        new InfiniteTimeSpanConverter (),
+                                                                        new DefaultValidator (),
+                                                                        ConfigurationPropertyOptions.None);
+
+                       properties = new ConfigurationPropertyCollection ();
+                       properties.Add (cacheMemoryLimitMegabytesProp);
+                       properties.Add (nameProp);
+                       properties.Add (physicalMemoryLimitPercentageProp);
+                       properties.Add (pollingIntervalProp);
+               }
+
+               internal MemoryCacheElement ()
+               {
+               }
+               
+               public MemoryCacheElement (string name)
+               {
+                       this.Name = name;
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching.Configuration/MemoryCacheSection.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching.Configuration/MemoryCacheSection.cs
new file mode 100644 (file)
index 0000000..a84f3a7
--- /dev/null
@@ -0,0 +1,59 @@
+//
+// MemoryCacheSection.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Configuration;
+
+namespace System.Runtime.Caching.Configuration
+{
+       public sealed class MemoryCacheSection : ConfigurationSection
+       {
+               static ConfigurationProperty namedCachesProp;
+               static ConfigurationPropertyCollection properties;
+               
+               static MemoryCacheSection ()
+               {
+                       namedCachesProp = new ConfigurationProperty ("namedCaches", typeof (MemoryCacheSettingsCollection), null);
+
+                       properties = new ConfigurationPropertyCollection ();
+                       properties.Add (namedCachesProp);
+               }
+               
+               public MemoryCacheSection ()
+               {
+               }
+
+               [ConfigurationProperty ("namedCaches")]
+               public MemoryCacheSettingsCollection NamedCaches {
+                       get { return base [namedCachesProp] as MemoryCacheSettingsCollection; }
+               }
+
+               protected override ConfigurationPropertyCollection Properties {
+                       get { return properties; }
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching.Configuration/MemoryCacheSettingsCollection.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching.Configuration/MemoryCacheSettingsCollection.cs
new file mode 100644 (file)
index 0000000..5ef8ad1
--- /dev/null
@@ -0,0 +1,124 @@
+//
+// MemoryCacheSettingsCollection.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Configuration;
+
+namespace System.Runtime.Caching.Configuration
+{
+       [ConfigurationCollection (typeof(MemoryCacheElement), CollectionType = ConfigurationElementCollectionType.AddRemoveClearMap)]
+       public sealed class MemoryCacheSettingsCollection : ConfigurationElementCollection
+       {
+               static ConfigurationPropertyCollection properties;
+               
+               public override ConfigurationElementCollectionType CollectionType {
+                       get { return ConfigurationElementCollectionType.AddRemoveClearMap; }
+               }
+
+               public MemoryCacheElement this[int index] {
+                       get { return BaseGet (index) as MemoryCacheElement; }
+                       set {
+                               if (BaseGet (index) != null)
+                                       BaseRemoveAt (index);
+                               BaseAdd (index, value);
+                       }
+               }
+
+               public new MemoryCacheElement this[string key] {
+                       get {
+                               foreach (MemoryCacheElement mce in this) {
+                                       if (String.Compare (key, mce.Name, StringComparison.Ordinal) == 0)
+                                               return mce;
+                               }
+
+                               return null;
+                       }
+               }
+
+               protected override ConfigurationPropertyCollection Properties {
+                       get { return properties; }
+               }
+               
+               static MemoryCacheSettingsCollection ()
+               {
+                       properties = new ConfigurationPropertyCollection ();
+               }
+               
+               public MemoryCacheSettingsCollection ()
+               {
+               }
+
+               public void Add (MemoryCacheElement cache)
+               {
+                       BaseAdd (cache);
+               }
+
+               public void Clear ()
+               {
+                       BaseClear ();
+               }
+               
+               protected override ConfigurationElement CreateNewElement ()
+               {
+                       return new MemoryCacheElement ();
+               }
+
+               protected override ConfigurationElement CreateNewElement (string elementName)
+               {
+                       return new MemoryCacheElement (elementName);
+               }
+               
+               protected override object GetElementKey (ConfigurationElement element)
+               {
+                       if (element == null)
+                               return null;
+
+                       return ((MemoryCacheElement)element).Name;
+               }
+
+               public int IndexOf (MemoryCacheElement cache)
+               {
+                       if (cache == null)
+                               return -1;
+
+                       return BaseIndexOf (cache);
+               }
+
+               public void Remove (MemoryCacheElement cache)
+               {
+                       if (cache == null)
+                               return;
+
+                       BaseRemove (GetElementKey (cache));
+               }
+
+               public void RemoveAt (int index)
+               {
+                       BaseRemoveAt (index);
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching.Hosting/ChangeLog b/mcs/class/System.Runtime.Caching/System.Runtime.Caching.Hosting/ChangeLog
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching.Hosting/IApplicationIdentifier.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching.Hosting/IApplicationIdentifier.cs
new file mode 100644 (file)
index 0000000..17b59dd
--- /dev/null
@@ -0,0 +1,36 @@
+//
+// IApplicationIdentifier.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Runtime.Caching.Hosting
+{
+       public interface IApplicationIdentifier
+       {
+               string GetApplicationId ();
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching.Hosting/IFileChangeNotificationSystem.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching.Hosting/IFileChangeNotificationSystem.cs
new file mode 100644 (file)
index 0000000..fa46c2f
--- /dev/null
@@ -0,0 +1,37 @@
+//
+// IFileChangeNotificationSystem.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Runtime.Caching.Hosting
+{
+       public interface IFileChangeNotificationSystem
+       {
+               void StartMonitoring (string filePath, OnChangedCallback onChangedCallback, out object state, out DateTimeOffset lastWriteTime, out long fileSize);
+               void StopMonitoring (string filePath, object state);
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching.Hosting/IMemoryCacheManager.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching.Hosting/IMemoryCacheManager.cs
new file mode 100644 (file)
index 0000000..1e01b3e
--- /dev/null
@@ -0,0 +1,38 @@
+//
+// IMemoryCacheManager.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Runtime.Caching;
+
+namespace System.Runtime.Caching.Hosting
+{
+       public interface IMemoryCacheManager
+       {
+               void ReleaseCache (MemoryCache cache);
+               void UpdateCacheSize (long size, MemoryCache cache);
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching.dll.sources b/mcs/class/System.Runtime.Caching/System.Runtime.Caching.dll.sources
new file mode 100644 (file)
index 0000000..2278e3e
--- /dev/null
@@ -0,0 +1,41 @@
+../../build/common/Consts.cs
+../../build/common/Locale.cs
+../../build/common/MonoTODOAttribute.cs
+../System.Web/System.Web.Configuration_2.0/NullableStringValidator.cs
+
+Assembly/AssemblyInfo.cs
+System.Runtime.Caching/CacheEntryChangeMonitor.cs
+System.Runtime.Caching/CacheEntryRemovedArguments.cs
+System.Runtime.Caching/CacheEntryRemovedCallback.cs
+System.Runtime.Caching/CacheEntryRemovedReason.cs
+System.Runtime.Caching/CacheEntryUpdateArguments.cs
+System.Runtime.Caching/CacheEntryUpdateCallback.cs
+System.Runtime.Caching/CacheItem.cs
+System.Runtime.Caching/CacheItemPolicy.cs
+System.Runtime.Caching/CacheItemPriority.cs
+System.Runtime.Caching/ChangeMonitor.cs
+System.Runtime.Caching/DefaultCacheCapabilities.cs
+System.Runtime.Caching/FileChangeMonitor.cs
+System.Runtime.Caching/FileChangeNotificationSystem.cs
+System.Runtime.Caching/FileChangeNotificationSystemEntry.cs
+System.Runtime.Caching/Helpers.cs
+System.Runtime.Caching/HostFileChangeMonitor.cs
+System.Runtime.Caching/MemoryCache.cs
+System.Runtime.Caching/MemoryCacheContainer.cs
+System.Runtime.Caching/MemoryCacheEntry.cs
+System.Runtime.Caching/MemoryCacheEntryChangeMonitor.cs
+System.Runtime.Caching/MemoryCacheLRU.cs
+System.Runtime.Caching/MemoryCachePerformanceCounters.cs
+System.Runtime.Caching/MemoryCacheEntryPriorityQueue.cs
+System.Runtime.Caching/ObjectCache.cs
+System.Runtime.Caching/OnChangedCallback.cs
+System.Runtime.Caching/SqlChangeMonitor.cs
+
+System.Runtime.Caching.Configuration/CachingSectionGroup.cs
+System.Runtime.Caching.Configuration/MemoryCacheSection.cs
+System.Runtime.Caching.Configuration/MemoryCacheSettingsCollection.cs
+System.Runtime.Caching.Configuration/MemoryCacheElement.cs
+
+System.Runtime.Caching.Hosting/IApplicationIdentifier.cs
+System.Runtime.Caching.Hosting/IFileChangeNotificationSystem.cs
+System.Runtime.Caching.Hosting/IMemoryCacheManager.cs
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheEntryChangeMonitor.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheEntryChangeMonitor.cs
new file mode 100644 (file)
index 0000000..a56c9ab
--- /dev/null
@@ -0,0 +1,43 @@
+//
+// CacheEntryChangeMonitor.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.ObjectModel;
+
+namespace System.Runtime.Caching
+{
+       public abstract class CacheEntryChangeMonitor : ChangeMonitor
+       {
+               public abstract ReadOnlyCollection<string> CacheKeys { get; }
+               public abstract DateTimeOffset LastModified { get; }
+               public abstract string RegionName { get; }
+               
+               protected CacheEntryChangeMonitor ()
+               {
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheEntryRemovedArguments.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheEntryRemovedArguments.cs
new file mode 100644 (file)
index 0000000..ef57ee2
--- /dev/null
@@ -0,0 +1,51 @@
+//
+// CacheEntryRemovedArguments.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Runtime.Caching
+{
+       public class CacheEntryRemovedArguments
+       {
+               public CacheItem CacheItem { get; private set; }
+               public CacheEntryRemovedReason RemovedReason { get; private set; }
+               public ObjectCache Source { get; private set; }
+               
+               public CacheEntryRemovedArguments (ObjectCache source, CacheEntryRemovedReason reason, CacheItem cacheItem)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       if (cacheItem == null)
+                               throw new ArgumentNullException ("cacheItem");
+                       
+                       this.CacheItem = cacheItem;
+                       this.RemovedReason = reason;
+                       this.Source = source;
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheEntryRemovedCallback.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheEntryRemovedCallback.cs
new file mode 100644 (file)
index 0000000..600f406
--- /dev/null
@@ -0,0 +1,33 @@
+//
+// CacheEntryRemovedCallback.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Runtime.Caching
+{
+       public delegate void CacheEntryRemovedCallback (CacheEntryRemovedArguments arguments);
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheEntryRemovedReason.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheEntryRemovedReason.cs
new file mode 100644 (file)
index 0000000..b04e1e1
--- /dev/null
@@ -0,0 +1,40 @@
+//
+// CacheEntryRemoveReason.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Runtime.Caching
+{
+       public enum CacheEntryRemovedReason
+       {
+               Removed,
+               Expired,
+               Evicted,
+               ChangeMonitorChanged,
+               CacheSpecificEviction
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheEntryUpdateArguments.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheEntryUpdateArguments.cs
new file mode 100644 (file)
index 0000000..2fae528
--- /dev/null
@@ -0,0 +1,55 @@
+//
+// CacheEntryUpdateArguments.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Runtime.Caching
+{
+       public class CacheEntryUpdateArguments
+       {
+               public string Key { get; private set; }
+               public string RegionName { get; private set; }
+               public CacheEntryRemovedReason RemovedReason { get; private set; }
+               public ObjectCache Source { get; private set; }
+               public CacheItem UpdatedCacheItem { get; set; }
+               public CacheItemPolicy UpdatedCacheItemPolicy { get; set; }
+               
+               public CacheEntryUpdateArguments (ObjectCache source, CacheEntryRemovedReason reason, string key, string regionName)
+               {
+                       if (source == null)
+                               throw new ArgumentNullException ("source");
+
+                       if (key == null)
+                               throw new ArgumentNullException ("key");
+
+                       this.Key = key;
+                       this.RegionName = regionName;
+                       this.RemovedReason = reason;
+                       this.Source = source;   
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheEntryUpdateCallback.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheEntryUpdateCallback.cs
new file mode 100644 (file)
index 0000000..0de0cc5
--- /dev/null
@@ -0,0 +1,33 @@
+//
+// CacheEntryUpdateCallback.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Runtime.Caching
+{
+       public delegate void CacheEntryUpdateCallback (CacheEntryUpdateArguments arguments);
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheItem.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheItem.cs
new file mode 100644 (file)
index 0000000..42eba2d
--- /dev/null
@@ -0,0 +1,53 @@
+//
+// CacheItem.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Runtime.Caching
+{
+       public class CacheItem
+       {
+               public string Key { get; set; }
+               public string RegionName { get; set; }
+               public object Value { get; set; }
+
+               public CacheItem (string key) : this (key, null, null)
+               {
+               }
+
+               public CacheItem (string key, object value) : this (key, value, null)
+               {
+               }
+
+               public CacheItem (string key, object value, string regionName)
+               {
+                       this.Key = key;
+                       this.RegionName = regionName;
+                       this.Value = value;
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheItemPolicy.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheItemPolicy.cs
new file mode 100644 (file)
index 0000000..3c0a7fa
--- /dev/null
@@ -0,0 +1,60 @@
+//
+// CacheItemPolicy.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.ObjectModel;
+
+namespace System.Runtime.Caching
+{
+       public class CacheItemPolicy
+       {
+               Collection<ChangeMonitor> changeMonitors;
+               
+               public DateTimeOffset AbsoluteExpiration { get; set; }
+
+               public Collection<ChangeMonitor> ChangeMonitors {
+                       get {
+                               if (changeMonitors == null)
+                                       changeMonitors = new Collection <ChangeMonitor> ();
+
+                               return changeMonitors;
+                       }
+               }
+
+               public CacheItemPriority Priority { get; set; }
+               public CacheEntryRemovedCallback RemovedCallback { get; set; }
+               public TimeSpan SlidingExpiration { get; set; }
+               public CacheEntryUpdateCallback UpdateCallback { get; set; }
+               
+               public CacheItemPolicy ()
+               {
+                       this.AbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration;
+                       this.Priority = CacheItemPriority.Default;
+                       this.SlidingExpiration = ObjectCache.NoSlidingExpiration;
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheItemPriority.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/CacheItemPriority.cs
new file mode 100644 (file)
index 0000000..71e5a27
--- /dev/null
@@ -0,0 +1,37 @@
+//
+// CacheItemPriority.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Runtime.Caching
+{
+       public enum CacheItemPriority
+       {
+               Default,
+               NotRemovable
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/ChangeLog b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/ChangeLog
new file mode 100644 (file)
index 0000000..3e5faff
--- /dev/null
@@ -0,0 +1,43 @@
+2010-04-26  Marek Habersack  <mhabersack@novell.com>
+
+       * MemoryCacheLRU.cs: added
+
+       * MemoryCacheContainer.cs: added LRU entry cache.
+
+       * MemoryCache.cs: added option to emulate one CPU on SMP machines
+       (for testing purposes) - "__MonoEmulateOneCPU"
+
+2010-04-24  Marek Habersack  <mhabersack@novell.com>
+
+       * ObjectCache.cs: implemented all the non-abstract methods.
+
+       * MemoryCacheContainer.cs, MemoryCacheEntry.cs,
+       MemoryCacheEntryChangeMonitor.cs,
+       MemoryCacheEntryPriorityQueue.cs,
+       MemoryCachePerformanceCounters.cs: added
+
+       * MemoryCache.cs: implemented physical memory size detection, item
+       expiration timer, indexer, reading of configuration values from
+       config files, cache memory limit calculation, the
+       AddOrGetExisting, Set, Get, Contains,
+       CreateCacheEntryChangeMonitor, Dispose, GetCacheItem, GetCount,
+       GetEnumerator, GetValues, Remove and Trim methods.
+       Implemented support for per-cpu item containers.
+       Modified parameters of several methods to match .NET 4.0 release.
+
+       * HostFileChangeMonitor.cs: implemented according to tests.
+
+       * Helpers.cs: added new properties, StringComparer and Is64bit
+
+       * FileChangeNotificationSystemEntry.cs: added
+
+       * FileChangeNotificationSystem.cs: implemented
+
+       * ChangeMonitor.cs: NotifyOnChanged now properly throws an
+       exception if it was called more than once.
+
+       * CacheEntryRemovedReason.cs: renamed from
+       CacheEntryRemoveReason.cs
+
+       * CacheEntryChangeMonitor.cs: renamed from CacheEntryMonitor.cs
+
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/ChangeMonitor.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/ChangeMonitor.cs
new file mode 100644 (file)
index 0000000..a0f5fcd
--- /dev/null
@@ -0,0 +1,128 @@
+//
+// ChangeMonitor.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Runtime.Caching
+{
+       public abstract class ChangeMonitor : IDisposable
+       {
+               bool initializationComplete;
+               bool notifyOnChangedCalled;
+               OnChangedCallback onChangedCallback;
+               object onChangedState;
+
+               public bool HasChanged { get; private set; }
+               public bool IsDisposed { get; private set; }
+               public abstract string UniqueId { get; }
+               
+               protected ChangeMonitor ()
+               {
+               }
+
+               public void Dispose ()
+               {
+                       if (IsDisposed)
+                               return;
+
+                       if (!initializationComplete)
+                               // TODO: check if Dispose (bool) is called in this case
+                               throw new InvalidOperationException ("Initialization is not complete in the derived change-monitor class that called the base Dispose method.");
+
+                       try {
+                               try {
+                                       InvokeOnChangedCallback (onChangedState);
+                               } catch {
+                                       // ignore
+                                       // TODO: check what happens if the callback throws an exception - is
+                                       // Dispose (true) called then?
+                               }
+               
+                               Dispose (true);
+                       } finally {     
+                               IsDisposed = true;
+                       }
+               }
+
+               protected abstract void Dispose (bool disposing);
+
+               protected void InitializationComplete ()
+               {
+                       initializationComplete = true;
+                       if (HasChanged)
+                               Dispose ();
+               }
+
+               void InvokeOnChangedCallback (object state)
+               {
+                       if (onChangedCallback == null)
+                               return;
+
+                       try {
+                               onChangedCallback (state);
+                       } finally {
+                               onChangedCallback = null;
+                               onChangedState = null;
+                       }
+               }
+               
+               public void NotifyOnChanged (OnChangedCallback onChangedCallback)
+               {
+                       if (onChangedCallback == null)
+                               throw new ArgumentNullException ("onChangedCallback");
+
+                       if (notifyOnChangedCalled)
+                               throw new InvalidOperationException ("The callback method has already been invoked.");
+
+                       notifyOnChangedCalled = true;
+                       this.onChangedCallback = onChangedCallback;
+                       if (HasChanged) {
+                               InvokeOnChangedCallback (onChangedState);
+                               return;
+                       }
+                       
+               }
+
+               protected void OnChanged (object state)
+               {
+                       HasChanged = true;
+                       try {
+                               if (onChangedCallback == null)
+                                       onChangedState = state;
+                               else
+                                       InvokeOnChangedCallback (state);
+                       } catch {
+                               // ignore
+                               // TODO: check what happens if callback throws an exception - is
+                               // Dispose below called?
+                       } finally {
+                               if (initializationComplete)
+                                       Dispose ();
+                       }
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/DefaultCacheCapabilities.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/DefaultCacheCapabilities.cs
new file mode 100644 (file)
index 0000000..2fd90c4
--- /dev/null
@@ -0,0 +1,45 @@
+//
+// DefaultCacheCapabilities.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Runtime.Caching
+{
+       [Flags]
+       public enum DefaultCacheCapabilities
+       {
+               None = 0x00,
+               InMemoryProvider = 0x01,
+               OutOfProcessProvider = 0x02,
+               CacheEntryChangeMonitors = 0x04,
+               AbsoluteExpirations = 0x08,
+               SlidingExpirations = 0x10,
+               CacheEntryUpdateCallback = 0x20,
+               CacheEntryRemovedCallback = 0x40,
+               CacheRegions = 0x80
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/FileChangeMonitor.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/FileChangeMonitor.cs
new file mode 100644 (file)
index 0000000..a3eb179
--- /dev/null
@@ -0,0 +1,42 @@
+//
+// FileChangeMonitor.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.ObjectModel;
+
+namespace System.Runtime.Caching
+{
+       public abstract class FileChangeMonitor : ChangeMonitor
+       {
+               public abstract ReadOnlyCollection<string> FilePaths { get; }
+               public abstract DateTimeOffset LastModified { get; }
+               
+               protected FileChangeMonitor ()
+               {
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/FileChangeNotificationSystem.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/FileChangeNotificationSystem.cs
new file mode 100644 (file)
index 0000000..39de267
--- /dev/null
@@ -0,0 +1,155 @@
+//
+// FileChangeNotificationSystem.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Runtime.Caching.Hosting;
+using System.Text;
+
+namespace System.Runtime.Caching
+{
+       sealed class FileChangeNotificationSystem : IFileChangeNotificationSystem, IDisposable
+       {
+               static readonly object watchers_lock = new object ();
+               
+               Dictionary <string, FileChangeNotificationSystemEntry> watchers;
+               OnChangedCallback callback;
+
+               Dictionary <string, FileChangeNotificationSystemEntry> Watchers {
+                       get {
+                               if (watchers == null)
+                                       watchers = new Dictionary <string, FileChangeNotificationSystemEntry> (Helpers.StringEqualityComparer);
+
+                               return watchers;
+                       }
+               }
+               
+               public void StartMonitoring (string filePath, OnChangedCallback onChangedCallback, out object state, out DateTimeOffset lastWriteTime, out long fileSize)
+               {
+                       if (String.IsNullOrEmpty (filePath))
+                               throw new ArgumentNullException ("filePath");
+                       
+                       callback = onChangedCallback;
+
+                       string parentDir;
+                       if (File.Exists (filePath)) {
+                               var fi = new FileInfo (filePath);
+                               lastWriteTime = DateTimeOffset.FromFileTime (fi.LastWriteTimeUtc.Ticks);
+                               fileSize = fi.Length;
+                               parentDir = Path.GetDirectoryName (filePath);
+                       } else if (Directory.Exists (filePath)) {
+                               var di = new DirectoryInfo (filePath);
+                               lastWriteTime = DateTimeOffset.FromFileTime (di.LastWriteTimeUtc.Ticks);
+                               fileSize = -1L;
+                               parentDir = filePath;
+                       } else {
+                               lastWriteTime = DateTimeOffset.MaxValue;
+                               fileSize = -1L;
+
+                               if (filePath.LastIndexOf (Path.DirectorySeparatorChar) != -1)
+                                       parentDir = Path.GetDirectoryName (filePath);
+                               else
+                                       parentDir = filePath;
+                       }
+
+                       FileChangeNotificationSystemEntry entry;
+                       lock (watchers_lock) {
+                               Dictionary <string, FileChangeNotificationSystemEntry> watchers = Watchers;
+
+                               if (!watchers.TryGetValue (parentDir, out entry)) {
+                                       entry = new FileChangeNotificationSystemEntry (parentDir, this);
+                                       watchers.Add (parentDir, entry);
+                               }
+
+                               entry.Add (filePath);
+                               entry.Start ();
+                       }
+
+                       state = entry;
+               }
+
+               public void StopMonitoring (string filePath, object state)
+               {
+                       if (String.IsNullOrEmpty (filePath))
+                               return;
+
+                       var entry = state as FileChangeNotificationSystemEntry;
+                       if (entry == null)
+                               return;
+
+                       lock (watchers_lock) {
+                               entry.Remove (filePath);
+                               if (entry.IsEmpty) {
+                                       if (watchers != null && watchers.ContainsKey (filePath))
+                                               watchers.Remove (filePath);
+                                       
+                                       entry.Stop ();
+                                       entry.Dispose ();
+                               }
+                       }
+               }
+
+               public void OnChanged (WatcherChangeTypes changeType, string filePath, string newFilePath)
+               {
+                       if (callback == null)
+                               return;
+                       
+                       FileChangeNotificationSystemEntry entry;
+
+                       if (watchers == null || !watchers.TryGetValue (filePath, out entry))
+                               entry = null;
+
+                       callback (entry);
+               }
+               
+               public void Dispose ()
+               {
+                       lock (watchers_lock) {
+                               if (watchers == null || watchers.Count == 0)
+                                       return;
+
+                               FileChangeNotificationSystemEntry entry;
+                               foreach (var de in watchers) {
+                                       entry = de.Value;
+                                       if (entry == null)
+                                               continue;
+
+                                       entry.Stop ();
+                                       entry.Dispose ();
+                               }
+
+                               watchers.Clear ();
+                       }
+               }
+
+               void IDisposable.Dispose ()
+               {
+                       Dispose ();
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/FileChangeNotificationSystemEntry.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/FileChangeNotificationSystemEntry.cs
new file mode 100644 (file)
index 0000000..0445dcb
--- /dev/null
@@ -0,0 +1,179 @@
+//
+// FileChangeNotificationSystemEntry.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Runtime.Caching.Hosting;
+using System.Text;
+
+namespace System.Runtime.Caching
+{
+       // This class is NOT thread-safe - the caller needs to assure access serialization when
+       // calling Add/Remove
+       sealed class FileChangeNotificationSystemEntry : IDisposable
+       {
+               string watchedDirPath;
+               FileChangeNotificationSystem owner;
+               FileSystemWatcher watcher;
+               SortedDictionary <string, bool> filePaths;
+
+               SortedDictionary <string, bool> FilePaths {
+                       get {
+                               if (filePaths == null)
+                                       filePaths = new SortedDictionary <string, bool> (Helpers.StringComparer);
+                               return filePaths;
+                       }
+               }
+
+               public bool IsEmpty {
+                       get { return (filePaths == null || filePaths.Count == 0); }
+               }
+               
+               public FileChangeNotificationSystemEntry (string dirPath, FileChangeNotificationSystem owner)
+               {
+                       if (String.IsNullOrEmpty (dirPath))
+                               throw new ArgumentNullException ("dirPath");
+
+                       if (owner == null)
+                               throw new ArgumentNullException ("owner");
+                       
+                       watchedDirPath = dirPath;
+                       this.owner = owner;
+               }
+               
+               public void Add (string filePath)
+               {
+                       if (String.IsNullOrEmpty (filePath))
+                               return;
+
+                       bool start = false;
+                       try {
+                               if (watcher == null) {
+                                       watcher = new FileSystemWatcher (watchedDirPath);
+                                       watcher.IncludeSubdirectories = false;
+                                       watcher.Filter = String.Empty;
+                                       watcher.NotifyFilter = NotifyFilters.FileName |
+                                               NotifyFilters.DirectoryName |
+                                               NotifyFilters.Size |
+                                               NotifyFilters.LastWrite |
+                                               NotifyFilters.CreationTime;
+                                       watcher.Changed += OnChanged;
+                                       watcher.Created += OnChanged;
+                                       watcher.Deleted += OnChanged;
+                                       watcher.Renamed += OnRenamed;
+                               } else if (watcher.EnableRaisingEvents) {
+                                       Stop ();
+                                       start = true;
+                               }
+                       
+                               SortedDictionary <string, bool> filePaths = FilePaths;
+                               if (filePaths.ContainsKey (filePath))
+                                       return;
+
+                               filePaths.Add (filePath, true);
+                       } finally {
+                               if (start)
+                                       Start ();
+                       }
+               }
+
+               public void Remove (string filePath)
+               {
+                       if (filePath == null)
+                               return;
+
+                       bool start = false;
+                       try {
+                               if (watcher != null && watcher.EnableRaisingEvents) {
+                                       Stop ();
+                                       start = true;
+                               }
+                               
+                               SortedDictionary <string, bool> filePaths = FilePaths;
+                               if (!filePaths.ContainsKey (filePath))
+                                       return;
+
+                               filePaths.Remove (filePath);
+                       } finally {
+                               if (start)
+                                       Start ();
+                       }
+               }
+               
+               public void Start ()
+               {
+                       if (watcher == null)
+                               return;
+
+                       watcher.EnableRaisingEvents = true;
+               }
+
+               public void Stop ()
+               {
+                       if (watcher == null)
+                               return;
+
+                       watcher.EnableRaisingEvents = false;
+               }
+
+               public void Dispose ()
+               {
+                       if (watcher == null)
+                               return;
+
+                       try {
+                               Stop ();
+                       } finally {     
+                               watcher.Dispose ();
+                       }
+               }
+
+               void IDisposable.Dispose ()
+               {
+                       Dispose ();
+               }
+               
+               void OnChanged (object source, FileSystemEventArgs e)
+               {
+                       string fullPath = e.FullPath;
+                       if (owner == null || filePaths == null || !filePaths.ContainsKey (fullPath))
+                               return;
+                       
+                       owner.OnChanged (e.ChangeType, fullPath, null);
+               }
+
+               void OnRenamed (object source, RenamedEventArgs e)
+               {
+                       string fullPath = e.FullPath;
+                       if (owner == null || filePaths == null || !filePaths.ContainsKey (fullPath))
+                               return;
+
+                       owner.OnChanged (e.ChangeType, e.OldFullPath, e.FullPath);
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/Helpers.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/Helpers.cs
new file mode 100644 (file)
index 0000000..0385243
--- /dev/null
@@ -0,0 +1,94 @@
+//
+// ObjectCache.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Runtime.Caching
+{
+       static class Helpers
+       {
+               public static bool CaseInsensitive {
+                       get;
+                       private set;
+               }
+
+               public static bool Is64Bit {
+                       get;
+                       private set;
+               }
+               
+               public static IEqualityComparer <string> StringEqualityComparer {
+                        get; private set;
+                }
+
+               public static IComparer <string> StringComparer {
+                       get; private set;
+               }
+               
+               public static StringComparison StringComparison {
+                        get; private set;
+                }
+
+               static Helpers ()
+               {
+                       PlatformID pid = Environment.OSVersion.Platform;
+                        bool runningOnWindows = ((int) pid != 128 && pid != PlatformID.Unix && pid != PlatformID.MacOSX);
+
+                       Is64Bit = IntPtr.Size == 8;
+                        if (runningOnWindows)
+                                CaseInsensitive = true;
+                        else {
+                                string mono_iomap = Environment.GetEnvironmentVariable ("MONO_IOMAP");
+                                if (!String.IsNullOrEmpty (mono_iomap)) {
+                                        if (mono_iomap == "all")
+                                                CaseInsensitive = true;
+                                        else {
+                                                string[] parts = mono_iomap.Split (':');
+                                                foreach (string p in parts) {
+                                                        if (p == "all" || p == "case") {
+                                                                CaseInsensitive = true;
+                                                                break;
+                                                        }
+                                                }
+                                        }
+                                }
+                        }
+
+                        if (CaseInsensitive) {
+                                StringEqualityComparer = global::System.StringComparer.OrdinalIgnoreCase;
+                               StringComparer = global::System.StringComparer.OrdinalIgnoreCase;
+                                StringComparison = global::System.StringComparison.OrdinalIgnoreCase;
+                        } else {
+                                StringEqualityComparer = global::System.StringComparer.Ordinal;
+                               StringComparer = global::System.StringComparer.Ordinal;
+                                StringComparison = global::System.StringComparison.Ordinal;
+
+                        }      
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/HostFileChangeMonitor.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/HostFileChangeMonitor.cs
new file mode 100644 (file)
index 0000000..93a8ee7
--- /dev/null
@@ -0,0 +1,195 @@
+//
+// HostFileChangeMonitor.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.IO;
+using System.Runtime.Caching.Hosting;
+using System.Text;
+
+namespace System.Runtime.Caching
+{
+       public sealed class HostFileChangeMonitor : FileChangeMonitor
+       {
+               const long INVALID_FILE_SIZE = -1L;
+               static readonly object notificationSystemLock = new object ();
+               static readonly DateTime missingFileTimeStamp = new DateTime (0x701CE1722770000);
+               static IFileChangeNotificationSystem notificationSystem;
+               static bool notificationSystemSetFromHost;
+               
+               ReadOnlyCollection <string> filePaths;
+               DateTime lastModified;
+               string uniqueId;
+               bool disposeNotificationSystem;
+
+               Dictionary <string, object> notificationStates;
+               
+               public override ReadOnlyCollection<string> FilePaths {
+                       get { return filePaths;}
+               }
+               
+               public override DateTimeOffset LastModified {
+                       get { return lastModified; }
+               }
+               
+               public override string UniqueId {
+                       get { return uniqueId; }
+               }
+               
+               public HostFileChangeMonitor (IList<string> filePaths)
+               {
+                       if (filePaths == null)
+                               throw new ArgumentNullException ("filePaths");
+
+                       if (filePaths.Count == 0)
+                               throw new ArgumentException ("filePaths contains zero items.");
+
+                       var list = new List <string> (filePaths.Count);
+                       var sb = new StringBuilder ();
+                       lastModified = DateTime.MinValue;
+                       DateTime lastWrite;
+                       long size;
+                       bool ignoreForUniqueId;
+                       
+                       foreach (string p in filePaths) {
+                               if (String.IsNullOrEmpty (p))
+                                       throw new ArgumentException ("A path in the filePaths list is null or an empty string.");
+
+                               if (!Path.IsPathRooted (p))
+                                       throw new ArgumentException ("Absolute path information is required.");
+
+                               if (list.Contains (p))
+                                       ignoreForUniqueId = true;
+                               else
+                                       ignoreForUniqueId = false;
+                               
+                               list.Add (p);
+
+                               if (ignoreForUniqueId)
+                                       continue;
+                               
+                               if (Directory.Exists (p)) {
+                                       var di = new DirectoryInfo (p);
+                                       lastWrite = di.LastWriteTimeUtc;
+                                       size = INVALID_FILE_SIZE;
+                               } else if (File.Exists (p)) {
+                                       var fi = new FileInfo (p);
+                                       lastWrite = fi.LastWriteTimeUtc;
+                                       size = fi.Length;
+                               } else {
+                                       lastWrite = missingFileTimeStamp;
+                                       size = INVALID_FILE_SIZE;
+                               }
+                               
+                               if (lastWrite > lastModified)
+                                       lastModified = lastWrite;
+
+                               sb.AppendFormat ("{0}{1:X}{2:X}", p, lastWrite.Ticks, (ulong)size);
+                       }
+
+                       this.filePaths = new ReadOnlyCollection <string> (list);
+                       this.uniqueId = sb.ToString ();
+
+                       bool initComplete = false;
+                       try {
+                               InitMonitoring ();
+                               initComplete = true;
+                       } finally {
+                               InitializationComplete ();
+                               if (!initComplete)
+                                       Dispose ();
+                       }
+               }
+
+               void InitMonitoring ()
+               {
+                       IServiceProvider host;
+                       if (!notificationSystemSetFromHost && (host = ObjectCache.Host) != null) {
+                               lock (notificationSystemLock) {
+                                       if (!notificationSystemSetFromHost) {
+                                               if (host != null)
+                                                       notificationSystem = host.GetService (typeof (IFileChangeNotificationSystem)) as IFileChangeNotificationSystem;
+
+                                               if (notificationSystem != null)
+                                                       notificationSystemSetFromHost = true;
+                                       }
+                               }
+                       }
+
+                       if (!notificationSystemSetFromHost) {
+                               notificationSystem = new FileChangeNotificationSystem ();
+                               disposeNotificationSystem = true;
+                       }
+
+                       object state;
+
+                       // TODO: what are these two used for?
+                       DateTimeOffset lastWriteTime;
+                       long fileSize;
+                       
+                       notificationStates = new Dictionary <string, object> (filePaths.Count, Helpers.StringEqualityComparer);
+                       foreach (string path in filePaths) {
+                               if (notificationStates.ContainsKey (path))
+                                       continue; // silently ignore dupes
+                               
+                               notificationSystem.StartMonitoring (path, OnChanged, out state, out lastWriteTime, out fileSize);
+                               notificationStates.Add (path, state);
+                       }
+               }
+
+               protected override void Dispose (bool disposing)
+               {
+                       if (disposing && notificationSystem != null) {
+                               object state;
+                               
+                               foreach (var de in notificationStates) {
+                                       state = de.Value;
+                                       if (state == null)
+                                               continue;
+                                       
+                                       try {
+                                               notificationSystem.StopMonitoring (de.Key, state);
+                                       } catch {
+                                               // ignore
+                                       }
+                               }
+                               
+                               if (disposeNotificationSystem) {
+                                       var fcns = notificationSystem as FileChangeNotificationSystem;
+                                       if (fcns != null) {
+                                               try {
+                                                       fcns.Dispose ();
+                                               } finally {
+                                                       notificationSystem = null;
+                                               }
+                                       }
+                               }
+                       }
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCache.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCache.cs
new file mode 100644 (file)
index 0000000..272b006
--- /dev/null
@@ -0,0 +1,600 @@
+//
+// MemoryCache.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.Specialized;
+using System.Configuration;
+using System.Diagnostics;
+using System.Reflection;
+using System.Runtime.Caching.Configuration;
+using System.Threading;
+
+namespace System.Runtime.Caching
+{
+       public class MemoryCache : ObjectCache, IEnumerable, IDisposable
+       {
+               const long DEFAULT_TIMER_PERIOD = 20000; // .NET's default, ms
+
+               static long totalPhysicalMemory = 0;
+               static int numCPUs;
+               
+               string name;
+               MemoryCacheContainer[] containers;
+               DefaultCacheCapabilities defaultCaps;
+               MemoryCachePerformanceCounters perfCounters;
+               bool noPerformanceCounters;
+               bool emulateOneCPU;
+               
+               static ulong TotalPhysicalMemory {
+                       get {
+                               if (totalPhysicalMemory == 0)
+                                       DetermineTotalPhysicalMemory ();
+
+                               return (ulong)totalPhysicalMemory;
+                       }
+               }
+
+               internal long TimerPeriod {
+                       get; private set;
+               }
+               
+               public static MemoryCache Default { get; private set; }
+
+               // LAMESPEC: this value is represented in bytes, not megabytes
+               public long CacheMemoryLimit { get; private set; }
+               
+               public override DefaultCacheCapabilities DefaultCacheCapabilities {
+                       get { return defaultCaps; }
+               }
+               
+               public override object this [string key] {
+                       [TargetedPatchingOptOut ("Performance critical to inline this type of method across NGen image boundaries")]
+                       get { return FindContainer (key).Get (key); }
+                       set { Set (key, value, ObjectCache.InfiniteAbsoluteExpiration); }
+               }
+               
+               public override string Name {
+                       [TargetedPatchingOptOut ("Performance critical to inline this type of method across NGen image boundaries")]
+                       get { return name; }
+               }
+               
+               public long PhysicalMemoryLimit { get; private set; }
+               public TimeSpan PollingInterval { get; private set; }
+
+               static MemoryCache ()
+               {
+                       numCPUs = Environment.ProcessorCount;
+                       Default = new MemoryCache ();
+               }
+
+               MemoryCache ()
+               {
+                       name = "Default";
+                       CommonInit (name);
+               }
+                       
+               public MemoryCache (string name, NameValueCollection config = null)
+               {
+                       if (name == null)
+                               throw new ArgumentNullException ("name");
+
+                       if (name.Length == 0)
+                               throw new ArgumentException ("is an empty string.", "name");
+
+                       if (String.Compare (name, "default", StringComparison.OrdinalIgnoreCase) == 0)
+                               throw new ArgumentException ("'default' is a reserved name.", "name");
+                       
+                       this.name = name;
+                       CommonInit (name, config);
+               }
+
+               void CommonInit (string name, NameValueCollection config = null)
+               {
+                       this.defaultCaps = DefaultCacheCapabilities.InMemoryProvider |
+                               DefaultCacheCapabilities.CacheEntryChangeMonitors |
+                               DefaultCacheCapabilities.AbsoluteExpirations |
+                               DefaultCacheCapabilities.SlidingExpirations |
+                               DefaultCacheCapabilities.CacheEntryRemovedCallback |
+                               DefaultCacheCapabilities.CacheEntryUpdateCallback;
+
+                       GetValuesFromConfig (name, config);
+                       containers = new MemoryCacheContainer [numCPUs];
+                       perfCounters = new MemoryCachePerformanceCounters (name.ToLowerInvariant (), noPerformanceCounters);
+               }
+               
+               static void DetermineTotalPhysicalMemory ()
+               {
+                       var pc = new PerformanceCounter ("Mono Memory", "Total Physical Memory");
+                       long memBytes = pc.RawValue;
+
+                       if (memBytes == 0)
+                               memBytes = 134217728L; // 128MB, the runtime default when it's
+                                                      // impossible to determine the physical
+                                                      // memory size
+
+                       Interlocked.CompareExchange (ref totalPhysicalMemory, memBytes, 0);
+               }
+
+               bool ParseBoolConfigValue (string paramName, string name, NameValueCollection config, bool doTrow)
+               {
+                       string value = config [name];
+                       if (String.IsNullOrEmpty (value))
+                               return false;
+
+                       try {
+                               return Boolean.Parse (value);
+                       } catch {
+                               return false;
+                       }
+               }
+               
+               bool ParseInt32ConfigValue (string paramName, string name, NameValueCollection config, int maxValue, bool doThrow,  out int parsed)
+               {
+                       parsed = -1;
+                       string value = config [name];
+                       if (String.IsNullOrEmpty (value))
+                               return false;
+                               
+                       try {
+                               parsed = (int)UInt32.Parse (value);
+                       } catch (Exception ex) {
+                               if (doThrow)
+                                       throw new ArgumentException (
+                                               String.Format ("Invalid configuration: {0}=\"{1}\". The {0} value must be a non-negative 32-bit integer", name, value),
+                                               paramName,
+                                               ex);
+                               return false;
+                       }
+
+                       if (parsed < 0 || (uint)parsed > (uint)maxValue) {
+                               if (doThrow)
+                                       throw new ArgumentException (
+                                               String.Format ("Invalid configuration: {0}=\"{1}\". The {0} value cannot be greater than '{2}'.", name, value, maxValue),
+                                               paramName);
+                               return false;
+                       }
+                       
+                       return true;
+               }
+               
+               bool ParseTimeSpanConfigValue (string paramName, string name, NameValueCollection config, out TimeSpan parsed)
+               {
+                       string value = config [name];
+                       if (String.IsNullOrEmpty (value)) {
+                               parsed = TimeSpan.MinValue;
+                               return false;
+                       }
+                       
+                       try {
+                               parsed = TimeSpan.Parse (value);
+                               return true;
+                       } catch (Exception ex) {
+                               throw new ArgumentException (
+                                       String.Format ("Invalid configuration: {0}=\"{1}\". The {0} value must be a time interval that can be parsed by System.TimeSpan.Parse", name, value),
+                                       paramName,
+                                       ex);
+                       }
+               }
+               
+               void GetValuesFromConfig (string name, NameValueCollection config)
+               {
+                       var mcs = ConfigurationManager.GetSection ("system.runtime.caching/memoryCache") as MemoryCacheSection;
+                       MemoryCacheSettingsCollection settings = mcs != null ? mcs.NamedCaches : null;
+                       MemoryCacheElement element = settings != null ? settings [name] : null;
+
+                       if (element != null && config == null) {
+                               CacheMemoryLimit = (long)element.CacheMemoryLimitMegabytes * 1048576L;
+                               PhysicalMemoryLimit = (long)element.PhysicalMemoryLimitPercentage;
+                               PollingInterval = element.PollingInterval;
+                       }
+                       
+                       if (config != null) {
+                               int parsed;
+
+                               if (ParseInt32ConfigValue ("config", "cacheMemoryLimitMegabytes", config, Int32.MaxValue, true, out parsed))
+                                       CacheMemoryLimit = parsed * 1048576L;
+                               else if (element != null)
+                                       CacheMemoryLimit = (long)element.CacheMemoryLimitMegabytes * 1048576L;
+
+                               if (ParseInt32ConfigValue ("config", "physicalMemoryLimitPercentage", config, 100, true, out parsed))
+                                       PhysicalMemoryLimit = parsed;
+                               else if (element != null)
+                                       PhysicalMemoryLimit = (long)element.PhysicalMemoryLimitPercentage;
+
+                               TimeSpan ts;
+                               if (ParseTimeSpanConfigValue ("config", "pollingInterval", config, out ts))
+                                       PollingInterval = ts;
+                               else if (element != null)
+                                       PollingInterval = element.PollingInterval;
+
+                               // Those are Mono-specific
+                               if (!String.IsNullOrEmpty (config ["__MonoDisablePerformanceCounters"]))
+                                       noPerformanceCounters = true;
+
+                               if (ParseInt32ConfigValue ("config", "__MonoTimerPeriod", config, Int32.MaxValue, false, out parsed))
+                                       TimerPeriod = (long)(parsed * 1000);
+                               else
+                                       TimerPeriod = DEFAULT_TIMER_PERIOD;
+
+                               if (ParseBoolConfigValue ("config", "__MonoEmulateOneCPU", config, false))
+                                       emulateOneCPU = true;
+                       } else
+                               TimerPeriod = DEFAULT_TIMER_PERIOD;
+
+                       if (CacheMemoryLimit == 0) {
+                               // Calculated using algorithm described in this blog entry:
+                               //
+                               //  http://blogs.msdn.com/tmarq/archive/2007/06/25/some-history-on-the-asp-net-cache-memory-limits.aspx
+                               //
+                               ulong physicalRam = TotalPhysicalMemory;
+                               ulong maxCacheSize;
+                               
+                               // Determine the upper bound
+                               if (Helpers.Is64Bit)
+                                       maxCacheSize = 0x10000000000UL; // 1TB
+                               else if (physicalRam > 0x80000000UL) // 2GB
+                                       maxCacheSize = 0x70800000UL; // 1800MB
+                               else
+                                       maxCacheSize = 0x32000000UL; // 800MB
+
+                               physicalRam = (physicalRam * 3) / 5; // 60%
+                               CacheMemoryLimit = (long)Math.Min (physicalRam, maxCacheSize);
+                       }
+
+                       if (PhysicalMemoryLimit == 0)
+                               PhysicalMemoryLimit = 98;
+
+                       if (PollingInterval == TimeSpan.Zero)
+                               PollingInterval = TimeSpan.FromMinutes (2);
+               }
+                       
+               public override CacheItem AddOrGetExisting (CacheItem item, CacheItemPolicy policy)
+               {
+                       if (item == null)
+                               throw new ArgumentNullException ("item");
+
+                       string key = item.Key;
+                       return new CacheItem (key, DoAddOrGetExisting (key, item.Value, policy));
+               }
+               
+               public override object AddOrGetExisting (string key, object value, CacheItemPolicy policy, string regionName = null)
+               {
+                       if (regionName != null)
+                               throw new NotSupportedException ("The parameter regionName must be null.");
+                       
+                       return DoAddOrGetExisting (key, value, policy, regionName);
+               }
+               
+               public override object AddOrGetExisting (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)
+               {
+                       if (regionName != null)
+                               throw new NotSupportedException ("The parameter regionName must be null.");
+                       
+                       var policy = new CacheItemPolicy ();
+                       policy.AbsoluteExpiration = absoluteExpiration;
+
+                       return DoAddOrGetExisting (key, value, policy, regionName);
+               }
+
+               object DoAddOrGetExisting (string key, object value, CacheItemPolicy policy, string regionName = null)
+               {
+                       if (key == null)
+                               throw new ArgumentNullException ("key");
+
+                       if (value == null)
+                               throw new ArgumentNullException ("value");
+                       
+                       if (policy != null) {
+                               ValidatePolicy (policy, false);
+                               if (policy.AbsoluteExpiration < DateTimeOffset.Now)
+                                       return null;
+                       }
+                       
+                       return FindContainer (key).AddOrGetExisting (key, value, policy);
+               }
+               
+               public override bool Contains (string key, string regionName = null)
+               {
+                       if (key == null)
+                               throw new ArgumentNullException ("key");
+
+                       if (regionName != null)
+                               throw new NotSupportedException ("The parameter regionName must be null.");
+                       
+                       return FindContainer (key).ContainsKey (key);
+               }
+               
+               public override CacheEntryChangeMonitor CreateCacheEntryChangeMonitor (IEnumerable <string> keys, string regionName = null)
+               {
+                       if (regionName != null)
+                               throw new NotSupportedException ("The parameter regionName must be null.");
+
+                       if (keys == null)
+                               throw new ArgumentNullException ("keys");
+
+                       int count = 0;
+                       foreach (string key in keys) {
+                               if (key == null)
+                                       throw new ArgumentException ("The collection 'keys' contains a null element.");
+                               count++;
+                       }
+                       if (count == 0)
+                               throw new ArgumentException ("The collection 'keys' is empty");
+                       
+                       return new MemoryCacheEntryChangeMonitor (this, keys);
+               }
+               
+               public void Dispose ()
+               {
+                       foreach (MemoryCacheContainer container in containers) {
+                               if (container == null)
+                                       continue;
+
+                               container.Dispose ();
+                       }
+
+                       perfCounters.Dispose ();
+               }
+
+               MemoryCacheContainer FindContainer (string key)
+               {
+                       if (key == null)
+                               throw new ArgumentNullException ("key");
+
+                       if (emulateOneCPU || numCPUs == 1) {
+                               if (containers [0] == null)
+                                       containers [0] = new MemoryCacheContainer (this, 0, perfCounters);
+
+                               return containers [0];
+                       }
+                       
+                       int containerIdx = Math.Abs (key.GetHashCode () % numCPUs);
+                       if (containers [containerIdx] == null)
+                               containers [containerIdx] = new MemoryCacheContainer (this, containerIdx, perfCounters);
+
+                       return containers [containerIdx];
+               }
+               
+               [TargetedPatchingOptOut ("Performance critical to inline this type of method across NGen image boundaries")]
+               public override object Get (string key, string regionName = null)
+               {
+                       if (regionName != null)
+                               throw new NotSupportedException ("The parameter regionName must be null.");
+
+                       if (key == null)
+                               throw new ArgumentNullException ("key");
+                       
+                       return FindContainer (key).Get (key);
+               }
+
+               internal MemoryCacheEntry GetEntry (string key)
+               {
+                       return FindContainer (key).GetEntry (key);
+               }
+               
+               public override CacheItem GetCacheItem (string key, string regionName = null)
+               {
+                       if (regionName != null)
+                               throw new NotSupportedException ("The parameter regionName must be null.");
+
+                       if (key == null)
+                               throw new ArgumentNullException ("key");
+                       
+                       object value = Get (key);
+                       if (value == null)
+                               return null;
+                       
+                       return new CacheItem (key, value);
+               }
+               
+               public override long GetCount (string regionName = null)
+               {
+                       if (regionName != null)
+                               throw new NotSupportedException ("The parameter regionName must be null.");
+                       
+                       long ret = 0;
+                       MemoryCacheContainer container;
+                       for (int i = 0; i < numCPUs; i++) {
+                               container = containers [i];
+                               if (container == null)
+                                       continue;
+
+                               ret += container.Count;
+                       }
+
+                       return ret;
+               }
+               
+               protected override IEnumerator <KeyValuePair <string,object>> GetEnumerator ()
+               {
+                       var dict = new Dictionary <string, object> ();
+
+                       CopyEntries (dict);
+                       return dict.GetEnumerator ();
+               }
+               
+               public override IDictionary <string,object> GetValues (IEnumerable <string> keys, string regionName = null)
+               {
+                       if (regionName != null)
+                               throw new NotSupportedException ("The parameter regionName must be null.");
+
+                       if (keys == null)
+                               throw new ArgumentNullException ("keys");
+
+                       MemoryCacheEntry entry;
+                       var ret = new Dictionary <string, object> ();
+                       foreach (string key in keys) {
+                               if (key == null)
+                                       throw new ArgumentException ("The collection 'keys' contains a null element.");
+
+                               entry = GetEntry (key);
+                               
+                               // LAMESPEC: MSDN says the number of items in the returned dictionary should be the same as in the 
+                               // 'keys' collection - this is not the case. The returned dictionary contains only entries for keys
+                               // that exist in the cache.
+                               if (entry == null)
+                                       continue;
+
+                               ret.Add (key, entry.Value);
+                       }
+
+                       if (ret.Count == 0)
+                               return null;
+                       
+                       return ret;
+               }
+               
+               public override object Remove (string key, string regionName = null)
+               {
+                       if (regionName != null)
+                               throw new NotSupportedException ("The parameter regionName must be null.");
+
+                       if (key == null)
+                               throw new ArgumentNullException ("key");
+                       
+                       return FindContainer (key).Remove (key);
+               }
+
+               internal void Remove (MemoryCacheEntry entry)
+               {
+                       if (entry == null)
+                               return;
+
+                       string key = entry.Key;
+                       FindContainer (key).Remove (key);
+               }
+               
+               public override void Set (CacheItem item, CacheItemPolicy policy)
+               {
+                       if (item == null)
+                               throw new ArgumentNullException ("item");
+                       
+                       Set (item.Key, item.Value, policy);
+               }
+               
+               public override void Set (string key, object value, CacheItemPolicy policy, string regionName = null)
+               {
+                       if (regionName != null)
+                               throw new NotSupportedException ("The parameter regionName must be null.");
+
+                       if (key == null)
+                               throw new ArgumentNullException ("key");
+
+                       if (value == null)
+                               throw new ArgumentNullException ("value");
+
+                       if (policy != null) {
+                               ValidatePolicy (policy, true);
+                               if (policy.AbsoluteExpiration < DateTimeOffset.Now)
+                                       return;
+                       }
+                       
+                       FindContainer (key).Set (key, value, policy);
+               }
+               
+               public override void Set (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)
+               {
+                       var policy = new CacheItemPolicy ();
+                       policy.AbsoluteExpiration = absoluteExpiration;
+
+                       Set (key, value, policy, regionName);
+               }
+               
+               IEnumerator IEnumerable.GetEnumerator ()
+               {
+                       // As weird as it is, this method doesn't call the instance GetEnumerator ()
+                       // - tests show it returns a Hashtable enumerator for some reason.
+                       var dict = new Hashtable ();
+                       
+                       CopyEntries (dict);
+                       return dict.GetEnumerator ();
+               }
+
+               void CopyEntries (IDictionary dict)
+               {
+                       foreach (MemoryCacheContainer container in containers) {
+                               if (container == null)
+                                       continue;
+
+                               container.CopyEntries (dict);
+                       }
+               }
+               
+               public long Trim (int percent)
+               {
+                       long ret = 0;
+
+                       // We should probably sort the containers by their least recently used
+                       // items, but that is a performance overkill so we'll just resort to a more
+                       // naive method - each container is trimmed independently of the others.
+                       foreach (MemoryCacheContainer container in containers) {
+                               if (container == null)
+                                       continue;
+
+                               ret += container.Trim (percent);
+                       }
+
+                       return ret;
+               }
+
+               void ValidatePolicy (CacheItemPolicy policy, bool allowUpdateCallback)
+               {
+                       CacheEntryUpdateCallback updateCallback = policy.UpdateCallback;
+                       if (!allowUpdateCallback && updateCallback != null)
+                               throw new ArgumentException ("CacheItemPolicy.UpdateCallback must be null.", "policy");
+
+                       if (updateCallback != null && policy.RemovedCallback != null)
+                               throw new ArgumentException ("Only one callback can be specified. Either RemovedCallback or UpdateCallback must be null.", "policy");
+                       
+                       DateTimeOffset absoluteExpiration = policy.AbsoluteExpiration;
+                       TimeSpan slidingExpiration = policy.SlidingExpiration;
+                               
+                       if (absoluteExpiration != ObjectCache.InfiniteAbsoluteExpiration &&
+                           slidingExpiration != TimeSpan.Zero)
+                               throw new ArgumentException (
+                                       "policy",
+                                       "'AbsoluteExpiration' must be ObjectCache.InfiniteAbsoluteExpiration or 'SlidingExpiration' must be TimeSpan.Zero"
+                               );
+
+                       long ticks = slidingExpiration.Ticks;
+                       if (ticks < 0 || ticks > 315360000000000)
+                               throw new ArgumentOutOfRangeException (
+                                       "policy",
+                                       "SlidingExpiration must be greater than or equal to '00:00:00' and less than or equal to '365.00:00:00'."
+                               );
+                               
+                       CacheItemPriority priority = policy.Priority;
+                       if (priority < CacheItemPriority.Default || priority > CacheItemPriority.NotRemovable)
+                               throw new ArgumentOutOfRangeException (
+                                       "policy",
+                                       "'Priority' must be greater than or equal to 'Default' and less than or equal to 'NotRemovable'"
+                               );
+               }               
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCacheContainer.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCacheContainer.cs
new file mode 100644 (file)
index 0000000..43de07d
--- /dev/null
@@ -0,0 +1,420 @@
+//
+// MemoryCacheContainer.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.Specialized;
+using System.Configuration;
+using System.Diagnostics;
+using System.Reflection;
+using System.Runtime.Caching.Configuration;
+using System.Threading;
+
+namespace System.Runtime.Caching
+{
+       sealed class MemoryCacheContainer : IDisposable
+       {
+               const int DEFAULT_LRU_LOWER_BOUND = 10;
+               
+               ReaderWriterLockSlim cache_lock = new ReaderWriterLockSlim ();
+               
+               SortedDictionary <string, MemoryCacheEntry> cache;
+               MemoryCache owner;
+               MemoryCachePerformanceCounters perfCounters;
+               MemoryCacheEntryPriorityQueue timedItems;
+               MemoryCacheLRU lru;
+               Timer expirationTimer;
+               
+               public int ID {
+                       get; private set;
+               }
+
+               public long Count {
+                       get { return (long)cache.Count; }
+               }
+               
+               public MemoryCacheContainer (MemoryCache owner, int id, MemoryCachePerformanceCounters perfCounters)
+               {
+                       if (owner == null)
+                               throw new ArgumentNullException ("owner");
+                       
+                       this.owner = owner;
+                       this.ID = id;
+                       this.perfCounters = perfCounters;
+                       cache = new SortedDictionary <string, MemoryCacheEntry> ();
+                       lru = new MemoryCacheLRU (this, DEFAULT_LRU_LOWER_BOUND);
+               }
+
+               bool ExpireIfNeeded (string key, MemoryCacheEntry entry, bool needsLock = true, CacheEntryRemovedReason reason = CacheEntryRemovedReason.Expired)
+               {
+                       bool locked = false;
+                       
+                       try {
+                               if (entry.IsExpired) {
+                                       if (needsLock) {
+                                               cache_lock.EnterWriteLock ();
+                                               locked = true;
+                                       }
+                                       
+                                       cache.Remove (key);
+                                       perfCounters.Decrement (MemoryCachePerformanceCounters.CACHE_ENTRIES);
+                                       entry.Removed (owner, CacheEntryRemovedReason.Expired);
+                                       
+                                       return true;
+                               }
+                       } finally {
+                               if (locked)
+                                       cache_lock.ExitWriteLock ();
+                       }
+                       
+                       return false;
+               }
+
+               public void Dispose ()
+               {
+                       if (expirationTimer != null) {
+                               expirationTimer.Dispose ();
+                               expirationTimer = null;
+                       }
+               }
+               
+               public void CopyEntries (IDictionary dict)
+               {
+                       bool locked = false;
+                       try {
+                               cache_lock.EnterWriteLock ();
+                               locked = true;
+
+                               MemoryCacheEntry entry;
+                               foreach (var de in cache) {
+                                       entry = de.Value;
+
+                                       if (entry.IsExpired)
+                                               continue;
+
+                                       dict.Add (de.Key, entry.Value);
+                               }
+                       } finally {
+                               if (locked)
+                                       cache_lock.ExitWriteLock ();
+                       }
+               }
+               
+               public bool ContainsKey (string key)
+               {
+                       bool readLocked = false;
+                       try {
+                               cache_lock.EnterUpgradeableReadLock ();
+                               readLocked = true;
+
+                               MemoryCacheEntry entry;
+                               if (cache.TryGetValue (key, out entry)) {
+                                       if (ExpireIfNeeded (key, entry))
+                                               return false;
+
+                                       return true;
+                               }
+
+                               return false;
+                       } finally {
+                               if (readLocked)
+                                       cache_lock.ExitUpgradeableReadLock ();
+                       }
+               }
+
+               // NOTE: this method _MUST_ be called with the write lock held
+               void AddToCache (string key, MemoryCacheEntry entry, bool update = false)
+               {
+                       if (update)
+                               cache [key] = entry;
+                       else
+                               cache.Add (key, entry);
+                       lru.Update (entry);
+                       entry.Added ();
+                       if (!update)
+                               perfCounters.Increment (MemoryCachePerformanceCounters.CACHE_ENTRIES);
+                       
+                       if (entry.IsExpirable)
+                               UpdateExpirable (entry);
+               }
+
+               // NOTE: this method _MUST_ be called with the write lock held
+               void UpdateExpirable (MemoryCacheEntry entry)
+               {
+                       if (timedItems == null)
+                               timedItems = new MemoryCacheEntryPriorityQueue ();
+
+                       timedItems.Enqueue (entry);
+
+                       if (expirationTimer == null)
+                               expirationTimer = new Timer (RemoveExpiredItems, null, owner.TimerPeriod, owner.TimerPeriod);
+               }
+
+               void RemoveExpiredItems (object state)
+               {
+                       DoRemoveExpiredItems (true);
+               }
+
+               long DoRemoveExpiredItems (bool needLock)
+               {
+                       long count = 0;
+                       bool locked = false;
+                       try {
+                               if (needLock) {
+                                       cache_lock.EnterWriteLock ();
+                                       locked = true;
+                               }
+
+                               if (timedItems == null)
+                                       return 0;
+                               
+                               long now = DateTime.Now.Ticks;
+                               MemoryCacheEntry entry = timedItems.Peek ();
+
+                               while (entry != null) {
+                                       if (entry.Disabled) {
+                                               timedItems.Dequeue ();
+                                               entry = timedItems.Peek ();
+                                               continue;
+                                       }
+
+                                       if (entry.ExpiresAt > now)
+                                               break;
+
+                                       timedItems.Dequeue ();
+                                       count++;
+                                       DoRemoveEntry (entry, true, entry.Key, CacheEntryRemovedReason.Expired);
+                                       entry = timedItems.Peek ();
+                               }
+
+                               if (entry == null) {
+                                       timedItems = null;
+                                       expirationTimer.Dispose ();
+                                       expirationTimer = null;
+                               }
+
+                               return count;
+                       } finally {
+                               if (locked)
+                                       cache_lock.ExitWriteLock ();
+                       }
+               }
+               
+               public object AddOrGetExisting (string key, object value, CacheItemPolicy policy)
+               {
+                       bool readLocked = false, writeLocked = false;
+                       try {
+                               cache_lock.EnterUpgradeableReadLock ();
+                               readLocked = true;
+
+                               MemoryCacheEntry entry;
+                               if (cache.TryGetValue (key, out entry) && entry != null) {
+                                       perfCounters.Increment (MemoryCachePerformanceCounters.CACHE_HITS);
+                                       return entry.Value;
+                               }
+                               perfCounters.Increment (MemoryCachePerformanceCounters.CACHE_MISSES);
+                               
+                               cache_lock.EnterWriteLock ();
+                               writeLocked = true;
+
+                               if (policy == null)
+                                       entry = new MemoryCacheEntry (owner, key, value);
+                               else
+                                       entry = new MemoryCacheEntry (owner, key, value,
+                                                                     policy.AbsoluteExpiration,
+                                                                     policy.ChangeMonitors,
+                                                                     policy.Priority,
+                                                                     policy.RemovedCallback,
+                                                                     policy.SlidingExpiration,
+                                                                     policy.UpdateCallback);
+
+                               AddToCache (key, entry);
+                               return null;
+                       } finally {
+                               if (writeLocked)
+                                       cache_lock.ExitWriteLock ();
+                               if (readLocked)
+                                       cache_lock.ExitUpgradeableReadLock ();
+                       }
+               }
+
+               public MemoryCacheEntry GetEntry (string key)
+               {
+                       bool locked = false;
+                       try {
+                               cache_lock.EnterReadLock ();
+                               locked = true;
+
+                               MemoryCacheEntry entry;
+                               if (cache.TryGetValue (key, out entry)) {
+                                       if (ExpireIfNeeded (key, entry))
+                                               return null;
+                                       
+                                       return entry;
+                               }
+                               
+                               return null;
+                       } finally {
+                               if (locked)
+                                       cache_lock.ExitReadLock ();
+                       }
+               }
+               
+               public object Get (string key)
+               {
+                       bool readLocked = false;
+                       try {
+                               cache_lock.EnterUpgradeableReadLock ();
+                               readLocked = true;
+
+                               MemoryCacheEntry entry;
+                               if (cache.TryGetValue (key, out entry)) {
+                                       if (ExpireIfNeeded (key, entry))
+                                               return null;
+                                       
+                                       perfCounters.Increment (MemoryCachePerformanceCounters.CACHE_HITS);
+                                       return entry.Value;
+                               }
+
+                               perfCounters.Increment (MemoryCachePerformanceCounters.CACHE_MISSES);
+                               return null;
+                       } finally {
+                               if (readLocked)
+                                       cache_lock.ExitUpgradeableReadLock ();
+                       }
+               }
+
+               public object Remove (string key, bool needLock = true, bool updateLRU = true)
+               {
+                       bool writeLocked = false, readLocked = false;
+                       try {
+                               if (needLock) {
+                                       cache_lock.EnterUpgradeableReadLock ();
+                                       readLocked = true;
+                               }
+
+                               MemoryCacheEntry entry;
+                               if (!cache.TryGetValue (key, out entry))
+                                       return null;
+
+                               if (needLock) {
+                                       cache_lock.EnterWriteLock ();
+                                       writeLocked = true;
+                               }
+                               
+                               object ret = entry.Value;
+                               DoRemoveEntry (entry, updateLRU, key);
+                               return ret;
+                       } finally {
+                               if (writeLocked)
+                                       cache_lock.ExitWriteLock ();
+                               if (readLocked)
+                                       cache_lock.ExitUpgradeableReadLock ();
+                       }
+               }
+               
+               // NOTE: this must be called with the write lock held
+               void DoRemoveEntry (MemoryCacheEntry entry, bool updateLRU = true, string key = null, CacheEntryRemovedReason reason = CacheEntryRemovedReason.Removed)
+               {
+                       if (key == null)
+                               key = entry.Key;
+
+                       cache.Remove (key);
+                       if (updateLRU)
+                               lru.Remove (entry);
+                       perfCounters.Decrement (MemoryCachePerformanceCounters.CACHE_ENTRIES);
+                       entry.Removed (owner, reason);
+               }
+               
+               public void Set (string key, object value, CacheItemPolicy policy)
+               {
+                       bool locked = false;
+                       try {
+                               cache_lock.EnterWriteLock ();
+                               locked = true;
+
+                               MemoryCacheEntry mce;
+                               bool update = false;
+                               if (cache.TryGetValue (key, out mce)) {
+                                       if (mce != null) {
+                                               perfCounters.Increment (MemoryCachePerformanceCounters.CACHE_HITS);
+                                               mce.Value = value;
+                                               mce.SetPolicy (policy);
+                                               if (mce.IsExpirable)
+                                                       UpdateExpirable (mce);
+                                               lru.Update (mce);
+                                               return;
+                                       }
+
+                                       update = true;
+                               }
+                               perfCounters.Increment (MemoryCachePerformanceCounters.CACHE_MISSES);
+                               if (policy != null)
+                                       mce = new MemoryCacheEntry (owner, key, value,
+                                                                   policy.AbsoluteExpiration,
+                                                                   policy.ChangeMonitors,
+                                                                   policy.Priority,
+                                                                   policy.RemovedCallback,
+                                                                   policy.SlidingExpiration,
+                                                                   policy.UpdateCallback);
+                               else
+                                       mce = new MemoryCacheEntry (owner, key, value);
+                               AddToCache (key, mce, update);
+                       } finally {
+                               if (locked)
+                                       cache_lock.ExitWriteLock ();
+                       }
+               }
+
+               public long Trim (int percent)
+               {
+                       int count = cache.Count;
+                       if (count == 0)
+                               return 0;
+
+                       long goal = (long)((count * percent) / 100);
+                       bool locked = false;
+                       long ret = 0;
+
+                       try {
+                               cache_lock.EnterWriteLock ();
+                               locked = true;
+                               ret = DoRemoveExpiredItems (false);
+
+                               goal -= ret;
+                               if (goal > 0)
+                                       ret += lru.Trim (goal);
+                       } finally {
+                               if (locked)
+                                       cache_lock.ExitWriteLock ();
+                       }
+                       
+                       return ret;
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCacheEntry.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCacheEntry.cs
new file mode 100644 (file)
index 0000000..9bae662
--- /dev/null
@@ -0,0 +1,199 @@
+//
+// MemoryCacheEntry.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+namespace System.Runtime.Caching
+{
+       sealed class MemoryCacheEntry
+       {
+               object value;
+               DateTimeOffset absoluteExpiration;
+               Collection <ChangeMonitor> monitors;            
+               CacheItemPriority priority;
+               CacheEntryRemovedCallback removedCallback;
+               TimeSpan slidingExpiration;
+               CacheEntryUpdateCallback updateCallback;
+               MemoryCache owner;
+               long expiresAt;
+               bool disabled;
+               
+               public bool Disabled {
+                       get { return disabled; }
+                       set {
+                               if (value) {
+                                       this.value = null;
+                                       this.Key = null;
+                                       this.disabled = true;
+                               } else
+                                       this.disabled = false;
+                       }
+               }
+               
+               public bool IsExpired {
+                       get {
+                               if (absoluteExpiration != ObjectCache.InfiniteAbsoluteExpiration && absoluteExpiration.UtcTicks < DateTime.UtcNow.Ticks)
+                                       return true;
+
+                               if (slidingExpiration != ObjectCache.NoSlidingExpiration && DateTime.UtcNow.Ticks - LastModified.Ticks > slidingExpiration.Ticks)
+                                       return true;
+                       
+                               return false;
+                       }
+               }
+
+               public bool IsRemovable {
+                       get { return priority != CacheItemPriority.NotRemovable; }
+               }
+
+               public bool IsExpirable {
+                       get { return expiresAt > 0; }
+               }
+               
+               public string Key {
+                       get; private set;
+               }
+
+               public DateTime LastModified {
+                       get; set;
+               }
+
+               public long ExpiresAt {
+                       get { return expiresAt; }
+               }
+               
+               public object Value {
+                       get { return value; }
+                       set {
+                               this.value = value;
+                               LastModified = DateTime.UtcNow;
+                       }
+               }
+
+               public MemoryCacheEntry (MemoryCache owner, string key, object value)
+               : this (owner, key, value, DateTimeOffset.MaxValue, null, CacheItemPriority.Default, null, TimeSpan.MaxValue, null)
+               {
+               }
+
+               public MemoryCacheEntry (MemoryCache owner, string key, object value, DateTimeOffset absoluteExpiration, Collection <ChangeMonitor> monitors,
+                                        CacheItemPriority priority, CacheEntryRemovedCallback removedCallback, TimeSpan slidingExpiration,
+                                        CacheEntryUpdateCallback updateCallback)
+               {
+                       if (value == null)
+                               throw new ArgumentNullException ("value");
+
+                       if (owner == null)
+                               throw new ArgumentNullException ("owner");
+
+                       this.owner = owner;
+                       this.Key = key;
+                       this.Value = value;
+                       this.absoluteExpiration = absoluteExpiration;
+                       this.monitors = monitors;
+                       this.priority = priority;
+                       this.removedCallback = removedCallback;
+                       this.slidingExpiration = slidingExpiration;
+                       this.updateCallback = updateCallback;
+                       this.LastModified = DateTime.UtcNow;
+
+                       if (absoluteExpiration != ObjectCache.InfiniteAbsoluteExpiration)
+                               expiresAt = absoluteExpiration.Ticks;
+                       else if (slidingExpiration != ObjectCache.NoSlidingExpiration)
+                               expiresAt = DateTime.Now.Ticks + slidingExpiration.Ticks;
+                       else
+                               expiresAt = 0;
+               }
+
+               public void Added ()
+               {
+                       Disabled = false;
+                       if (monitors == null || monitors.Count == 0)
+                               return;
+
+                       foreach (ChangeMonitor monitor in monitors)
+                               monitor.NotifyOnChanged (OnMonitorChanged);
+               }
+
+               public override int GetHashCode ()
+               {
+                       return Key.GetHashCode ();
+               }
+               
+               void OnMonitorChanged (object state)
+               {
+                       owner.Remove (this);
+               }
+               
+               public void Removed (MemoryCache owner, CacheEntryRemovedReason reason)
+               {
+                       if (removedCallback == null) {
+                               Disabled = true;
+                               return;
+                       }
+                       
+                       try {
+                               removedCallback (new CacheEntryRemovedArguments (owner, reason, new CacheItem (Key, Value)));
+                       } catch {
+                               // ignore - we don't care about the exceptions thrown inside the
+                               // handler
+                       } finally {
+                               Disabled = true;
+                       }
+               }
+
+               public void Updated (MemoryCache owner, CacheEntryRemovedReason reason)
+               {
+                       if (updateCallback == null)
+                               return;
+                       
+                       try {
+                               var args = new CacheEntryUpdateArguments (owner, reason, Key, null);
+                               updateCallback (args);
+                       } catch {
+                               // ignore - we don't care about the exceptions thrown inside the
+                               // handler
+                       }
+               }
+               
+               public void SetPolicy (CacheItemPolicy policy)
+               {
+                       if (policy == null)
+                               return;
+                       
+                       absoluteExpiration = policy.AbsoluteExpiration;
+                       monitors = policy.ChangeMonitors;
+                       priority = policy.Priority;
+                       removedCallback = policy.RemovedCallback;
+                       slidingExpiration = policy.SlidingExpiration;
+                       updateCallback = policy.UpdateCallback;
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCacheEntryChangeMonitor.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCacheEntryChangeMonitor.cs
new file mode 100644 (file)
index 0000000..4faf221
--- /dev/null
@@ -0,0 +1,100 @@
+//
+// MemoryCacheEntryChangeMonitor.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Text;
+
+namespace System.Runtime.Caching
+{
+       sealed class MemoryCacheEntryChangeMonitor : CacheEntryChangeMonitor
+       {
+               ReadOnlyCollection <string> cacheKeys;
+               DateTimeOffset lastModified;
+               MemoryCache owner;
+               string uniqueId;
+               
+               public override ReadOnlyCollection <string> CacheKeys {
+                       get { return cacheKeys; }
+               }
+
+               public override DateTimeOffset LastModified {
+                       get { return lastModified; }
+               }
+
+               public override string RegionName {
+                       get { return null; }
+               }
+
+               public override string UniqueId {
+                       get { return uniqueId; }
+               }
+               
+               public MemoryCacheEntryChangeMonitor (MemoryCache owner, IEnumerable <string> keys)
+               {
+                       this.owner = owner;
+                       this.lastModified = DateTimeOffset.MinValue;
+
+                       MemoryCacheEntry mce;
+                       var sb = new StringBuilder ();
+                       var list = new List <string> ();
+                       foreach (string key in keys) {
+                               mce = owner.GetEntry (key);
+                               list.Add (key);
+#if true
+                               // LAMESPEC: this is what's happening
+                               DateTimeOffset modtime;
+                               modtime = new DateTimeOffset (mce != null ? mce.LastModified : DateTime.MinValue);
+                               if (this.lastModified < modtime)
+                                       this.lastModified = modtime;
+#else
+                               // LAMESPEC: this is what is supposed to be happening
+                               if (mce == null) {
+                                       OnChanged (null);
+                                       sb.Append ("{0}{1:x}", key, DateTime.MinValue.Ticks);
+                                       continue;
+                               }
+                               
+                               DateTime modtime = mce.LastModified;
+                               if (this.lastModtime < modtime)
+                                       this.lastModtime = new DateTimeOffset (modtime);
+#endif
+                               sb.AppendFormat ("{0}{1:X}", key, modtime.Ticks);
+                       }
+                       this.uniqueId = sb.ToString ();
+                       this.cacheKeys = new ReadOnlyCollection <string> (list);
+
+                       // TODO: hook up to change events on MemoryCache
+               }
+
+               protected override void Dispose (bool disposing)
+               {
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCacheEntryPriorityQueue.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCacheEntryPriorityQueue.cs
new file mode 100644 (file)
index 0000000..dceb63b
--- /dev/null
@@ -0,0 +1,199 @@
+//
+// Author(s):
+//  Marek Habersack <mhabersack@novell.com>
+//
+// (C) 2009-2010 Novell, Inc (http://novell.com)
+//
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+using System.Threading;
+
+namespace System.Runtime.Caching
+{
+       sealed partial class MemoryCacheEntryPriorityQueue
+       {
+               const int INITIAL_HEAP_SIZE = 32;
+               const int HEAP_RESIZE_THRESHOLD = 8192;
+               
+               MemoryCacheEntry[] heap;
+               int heapSize = 0;
+               int heapCount = 0;
+               ReaderWriterLockSlim queueLock;
+
+               public int Count {
+                       get { return heapCount; }
+               }
+
+               public int Size {
+                       get { return heapSize; }
+               }
+               
+               public MemoryCacheEntryPriorityQueue ()
+               {
+                       queueLock = new ReaderWriterLockSlim ();
+               }
+
+               MemoryCacheEntry[] GetHeapWithGrow ()
+               {
+                       if (heap == null) {
+                               heap = new MemoryCacheEntry [INITIAL_HEAP_SIZE];
+                               heapSize = INITIAL_HEAP_SIZE;
+                               heapCount = 0;
+                               return heap;
+                       }
+
+                       if (heapCount >= heapSize) {
+                               heapSize <<= 1;
+                               Array.Resize <MemoryCacheEntry> (ref heap, heapSize);
+                       }
+
+                       return heap;
+               }
+
+               MemoryCacheEntry[] GetHeapWithShrink ()
+               {
+                       if (heap == null)
+                               return null;
+
+                       if (heapSize > HEAP_RESIZE_THRESHOLD) {
+                               int halfTheSize = heapSize >> 1;
+
+                               if (heapCount < halfTheSize)
+                                       Array.Resize <MemoryCacheEntry> (ref heap, halfTheSize + (heapCount / 3));
+                       }
+                       
+                       return heap;
+               }
+               
+               public void Enqueue (MemoryCacheEntry item)
+               {
+                       if (item == null)
+                               return;
+
+                       bool locked = false;
+                       MemoryCacheEntry[] heap;
+                       
+                       try {
+                               queueLock.EnterWriteLock ();
+                               locked = true;
+                               heap = GetHeapWithGrow ();
+                               heap [heapCount++] = item;
+                               BubbleUp (heap);
+                       } finally {
+                               if (locked)
+                                       queueLock.ExitWriteLock ();
+                       }
+               }
+
+               public MemoryCacheEntry Dequeue ()
+               {
+                       MemoryCacheEntry ret = null;
+                       MemoryCacheEntry[] heap;
+                       bool locked = false;
+                       int index;
+                       
+                       try {
+                               queueLock.EnterWriteLock ();
+                               locked = true;
+                               heap = GetHeapWithShrink ();
+                               if (heap == null || heapCount == 0)
+                                       return null;
+
+                               ret = heap [0];
+                               index = --heapCount;
+                               heap [0] = heap [index];
+                               heap [index] = null;
+                               
+                               if (heapCount > 0)
+                                       BubbleDown (heap);
+
+                               return ret;
+                       } finally {
+                               if (locked)
+                                       queueLock.ExitWriteLock ();
+                       }
+               }
+
+               public MemoryCacheEntry Peek ()
+               {
+                       bool locked = false;
+                       
+                       try {
+                               queueLock.EnterReadLock ();
+                               locked = true;
+                               if (heap == null || heapCount == 0)
+                                       return null;
+
+                               return heap [0];
+                       } finally {
+                               if (locked)
+                                       queueLock.ExitReadLock ();
+                       }
+               }
+               
+               void BubbleDown (MemoryCacheEntry[] heap)
+               {
+                       int index = 0;
+                       int left = 1;
+                       int right = 2;
+                       MemoryCacheEntry item = heap [0];
+                       int selected = (right < heapCount && heap [right].ExpiresAt < heap [left].ExpiresAt) ? 2 : 1;
+
+                       while (selected < heapCount && heap [selected].ExpiresAt < item.ExpiresAt) {
+                               heap [index] = heap [selected];
+                               index = selected;
+                               left = (index << 1) + 1;
+                               right = left + 1;
+                               selected = right < heapCount && heap [right].ExpiresAt < heap [left].ExpiresAt ? right : left;
+                       }
+                       heap [index] = item;
+               }
+               
+               void BubbleUp (MemoryCacheEntry[] heap)
+               {
+                       int index, parentIndex;
+                       MemoryCacheEntry parent, item;
+                       
+                       if (heapCount <= 1)
+                               return;
+                       
+                       index = heapCount - 1;
+                       parentIndex = (index - 1) >> 1;
+
+                       item = heap [index];
+                       while (index > 0) {
+                               parent = heap [parentIndex];
+                               if (heap [index].ExpiresAt >= parent.ExpiresAt)
+                                       break;
+                               
+                               heap [index] = parent;
+                               index = parentIndex;
+                               parentIndex = (index - 1) >> 1;
+                       }
+
+                       heap [index] = item;
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCacheLRU.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCacheLRU.cs
new file mode 100644 (file)
index 0000000..2ad420e
--- /dev/null
@@ -0,0 +1,109 @@
+//
+// MemoryCacheLRU.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Runtime.Caching
+{
+       // NOTE: all the public methods in this assume that the owner's write lock is held
+       sealed class MemoryCacheLRU
+       {
+               int trimLowerBound;
+               Dictionary <int, LinkedListNode <MemoryCacheEntry>> index;
+               LinkedList <MemoryCacheEntry> lru;
+               MemoryCacheContainer owner;
+               
+               public MemoryCacheLRU (MemoryCacheContainer owner, int trimLowerBound)
+               {
+                       this.trimLowerBound = trimLowerBound;
+                       index = new Dictionary <int, LinkedListNode <MemoryCacheEntry>> ();
+                       lru = new LinkedList <MemoryCacheEntry> ();
+                       this.owner = owner;
+               }
+
+               public void Update (MemoryCacheEntry entry)
+               {
+                       if (entry == null)
+                               return;
+
+                       int hash = entry.GetHashCode ();
+                       LinkedListNode <MemoryCacheEntry> node;
+                       
+                       if (!index.TryGetValue (hash, out node)) {
+                               node = new LinkedListNode <MemoryCacheEntry> (entry);
+                               index.Add (hash, node);
+                       } else {
+                               lru.Remove (node);
+                               node.Value = entry;
+                       }
+                       
+                       lru.AddLast (node);
+               }
+
+               public void Remove (MemoryCacheEntry entry)
+               {
+                       if (entry == null)
+                               return;
+                       
+                       int hash = entry.GetHashCode ();
+                       LinkedListNode <MemoryCacheEntry> node;
+                       
+                       if (index.TryGetValue (hash, out node)) {
+                               lru.Remove (node);
+                               index.Remove (hash);
+                       }
+               }
+
+               public long Trim (long upTo)
+               {
+                       int count = index.Count;
+                       if (count <= 10)
+                               return 0;
+
+                       // The list is used below to reproduce .NET's behavior which selects the
+                       // entries using the LRU order, but it removes them from the cache in the
+                       // MRU order
+                       var toremove = new List <MemoryCacheEntry> ((int)upTo);
+                       long removed = 0;
+                       MemoryCacheEntry entry;
+                       
+                       while (upTo > removed && count > 10) {
+                               entry = lru.First.Value;
+                               toremove.Insert (0, entry);
+                               Remove (entry);
+                               removed++;
+                               count--;
+                       }
+
+                       foreach (MemoryCacheEntry e in toremove)
+                               owner.Remove (e.Key, false);
+                       
+                       return removed;
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCachePerformanceCounters.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/MemoryCachePerformanceCounters.cs
new file mode 100644 (file)
index 0000000..4a947f3
--- /dev/null
@@ -0,0 +1,125 @@
+//
+// MemoryCache.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Diagnostics;
+
+//
+// Counters in the ".NET Memory Cache 4.0" are not documented on MSDN. They were discovered using
+// perfmon there their definition may change without any notice
+//
+namespace System.Runtime.Caching
+{
+       sealed class MemoryCachePerformanceCounters : IDisposable
+       {
+               const string dotNetCategoryName = ".NET Memory Cache 4.0";
+
+               public const int CACHE_ENTRIES = 0;
+               public const int CACHE_HIT_RATIO = 1;
+               public const int CACHE_HITS = 2;
+               public const int CACHE_MISSES = 3;
+               public const int CACHE_TRIMS = 4;
+               public const int CACHE_TURNOVER_RATE = 5;
+               const int COUNTERS_LAST = CACHE_TURNOVER_RATE;
+               
+               PerformanceCounter[] perfCounters;
+
+               public MemoryCachePerformanceCounters (string instanceName, bool noCounters)
+               {
+                       var collection = new CounterCreationDataCollection ();
+
+                       if (!noCounters) {
+                               if (!PerformanceCounterCategory.Exists (dotNetCategoryName)) {
+                                       // TODO: check:
+                                       //
+                                       //  - types of all the counters
+                                       //
+                                       CreateCounter ("Cache Entries", PerformanceCounterType.NumberOfItems64, collection);
+                                       CreateCounter ("Cache Hit Ratio", PerformanceCounterType.RawFraction, collection);
+                                       CreateCounter ("Cache Hits", PerformanceCounterType.NumberOfItems64, collection);
+                                       CreateCounter ("Cache Misses", PerformanceCounterType.NumberOfItems64, collection);
+                                       CreateCounter ("Cache Trims", PerformanceCounterType.NumberOfItems64, collection);
+                                       CreateCounter ("Cache Turnover Rate", PerformanceCounterType.RateOfCountsPerSecond64, collection);
+                       
+                                       PerformanceCounterCategory.Create (dotNetCategoryName, "System.Runtime.Caching.MemoryCache Performance Counters",
+                                                                          PerformanceCounterCategoryType.MultiInstance, collection);
+                               }
+                               
+                               perfCounters = new PerformanceCounter [COUNTERS_LAST + 1];
+                               perfCounters [CACHE_ENTRIES] = new PerformanceCounter (dotNetCategoryName, "Cache Entries", instanceName, false);
+                               perfCounters [CACHE_ENTRIES].RawValue = 0;
+                               perfCounters [CACHE_HIT_RATIO] = new PerformanceCounter (dotNetCategoryName, "Cache Hit Ratio", instanceName, false);
+                               perfCounters [CACHE_HIT_RATIO].RawValue = 0;
+                               perfCounters [CACHE_HITS] = new PerformanceCounter (dotNetCategoryName, "Cache Hits", instanceName, false);
+                               perfCounters [CACHE_HITS].RawValue = 0;
+                               perfCounters [CACHE_MISSES] = new PerformanceCounter (dotNetCategoryName, "Cache Misses", instanceName, false);
+                               perfCounters [CACHE_MISSES].RawValue = 0;
+                               perfCounters [CACHE_TRIMS] = new PerformanceCounter (dotNetCategoryName, "Cache Trims", instanceName, false);
+                               perfCounters [CACHE_TRIMS].RawValue = 0;
+                               perfCounters [CACHE_TURNOVER_RATE] = new PerformanceCounter (dotNetCategoryName, "Cache Turnover Rate", instanceName, false);
+                               perfCounters [CACHE_TURNOVER_RATE].RawValue = 0;
+                       }
+               }
+
+               public void Dispose ()
+               {
+                       foreach (PerformanceCounter counter in perfCounters) {
+                               if (counter == null)
+                                       continue;
+
+                               counter.Dispose ();
+                       }
+               }
+               
+               public void Decrement (int counteridx)
+               {
+                       if (perfCounters == null || counteridx < 0 || counteridx > COUNTERS_LAST)
+                               return;
+
+                       perfCounters [counteridx].Decrement ();
+               }
+               
+               public void Increment (int counteridx)
+               {
+                       if (perfCounters == null || counteridx < 0 || counteridx > COUNTERS_LAST)
+                               return;
+
+                       perfCounters [counteridx].Increment ();
+               }
+               
+               void CreateCounter (string name, PerformanceCounterType type, CounterCreationDataCollection collection)
+               {
+                       var ccd = new CounterCreationData ();
+
+                       ccd.CounterName = name;
+                       ccd.CounterType = type;
+                       collection.Add (ccd);
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/ObjectCache.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/ObjectCache.cs
new file mode 100644 (file)
index 0000000..1182730
--- /dev/null
@@ -0,0 +1,115 @@
+//
+// ObjectCache.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using System.Runtime;
+
+namespace System.Runtime.Caching
+{
+       public abstract class ObjectCache : IEnumerable<KeyValuePair<string, object>>, IEnumerable
+       {
+               static IServiceProvider host;
+               
+               public static readonly DateTimeOffset InfiniteAbsoluteExpiration = DateTimeOffset.MaxValue;
+               public static readonly TimeSpan NoSlidingExpiration = TimeSpan.Zero;
+
+               public static IServiceProvider Host {
+                       [TargetedPatchingOptOut ("Performance critical to inline this type of method across NGen image boundaries")]
+                       get { return host; }
+                       set {
+                               if (value == null)
+                                       throw new ArgumentNullException ("value");
+
+                               if (host != null)
+                                       throw new InvalidOperationException ("The property has already been set, and can only be set once.");
+
+                               host = value;
+                       }
+               }
+               
+               public abstract DefaultCacheCapabilities DefaultCacheCapabilities { get; }
+               public abstract object this [string key] { get; set; }
+               public abstract string Name { get; }
+               
+               [TargetedPatchingOptOut ("Performance critical to inline this type of method across NGen image boundaries")]
+               protected ObjectCache ()
+               {
+               }
+               
+               public virtual bool Add (CacheItem item, CacheItemPolicy policy)
+               {
+                       return AddOrGetExisting (item, policy) == null;
+               }
+               
+               public virtual bool Add (string key, object value, CacheItemPolicy policy, string regionName = null)
+               {
+                       return AddOrGetExisting (key, value, policy, regionName) == null;
+               }
+               
+               public virtual bool Add (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)
+               {
+                       return AddOrGetExisting (key, value, absoluteExpiration, regionName) == null;
+               }
+               
+               public abstract CacheItem AddOrGetExisting (CacheItem value, CacheItemPolicy policy);
+               public abstract object AddOrGetExisting (string key, object value, CacheItemPolicy policy, string regionName = null);
+               public abstract object AddOrGetExisting (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null);
+               public abstract bool Contains (string key, string regionName = null);
+               public abstract CacheEntryChangeMonitor CreateCacheEntryChangeMonitor (IEnumerable <string> keys, string regionName = null);
+               public abstract object Get (string key, string regionName = null);
+               public abstract CacheItem GetCacheItem (string key, string regionName = null);
+               public abstract long GetCount (string regionName = null);
+               protected abstract IEnumerator <KeyValuePair <string, object>> GetEnumerator ();
+               public abstract IDictionary <string, object> GetValues (IEnumerable <string> keys, string regionName = null);
+               
+               [TargetedPatchingOptOut ("Performance critical to inline this type of method across NGen image boundaries")]
+               public virtual IDictionary <string, object> GetValues (string regionName = null, params string[] keys)
+               {
+                       return GetValues (keys.AsEnumerable <string> (), regionName);
+               }
+               
+               public abstract object Remove (string key, string regionName = null);
+               public abstract void Set (CacheItem item, CacheItemPolicy policy);
+               public abstract void Set (string key, object value, CacheItemPolicy policy, string regionName = null);
+               public abstract void Set (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null);
+               
+               [TargetedPatchingOptOut ("Performance critical to inline this type of method across NGen image boundaries")]
+               IEnumerator <KeyValuePair <string,object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator ()
+               {
+                       return GetEnumerator ();
+               }
+               
+               IEnumerator IEnumerable.GetEnumerator ()
+               {
+                       return GetEnumerator ();
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/OnChangedCallback.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/OnChangedCallback.cs
new file mode 100644 (file)
index 0000000..bed109c
--- /dev/null
@@ -0,0 +1,33 @@
+//
+// OnChangedCallback.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Runtime.Caching
+{
+       public delegate void OnChangedCallback (object state);
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching/SqlChangeMonitor.cs b/mcs/class/System.Runtime.Caching/System.Runtime.Caching/SqlChangeMonitor.cs
new file mode 100644 (file)
index 0000000..d244426
--- /dev/null
@@ -0,0 +1,54 @@
+//
+// SqlChangeMonitor.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Data.SqlClient;
+
+namespace System.Runtime.Caching
+{
+       public sealed class SqlChangeMonitor : ChangeMonitor
+       {
+               string uniqueId;
+               
+               public override string UniqueId {
+                       get { return uniqueId; }
+               }
+               
+               public SqlChangeMonitor (SqlDependency dependency)
+               {
+                       if (dependency == null)
+                               throw new ArgumentNullException ("dependency");
+                       
+                       throw new NotImplementedException ();
+               }
+
+               protected override void Dispose (bool disposing)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/System.Runtime.Caching_test.dll.sources b/mcs/class/System.Runtime.Caching/System.Runtime.Caching_test.dll.sources
new file mode 100644 (file)
index 0000000..f555a94
--- /dev/null
@@ -0,0 +1,9 @@
+Common/AppDomainTools.cs
+Common/AssertExtensions.cs
+Common/PokerChangeMonitor.cs
+Common/PokerMemoryCache.cs
+Common/PokerObjectCache.cs
+Common/TestNotificationSystem.cs
+System.Runtime.Caching/HostFileChangeMonitorTest.cs
+System.Runtime.Caching/MemoryCacheTest.cs
+System.Runtime.Caching/ObjectCacheTest.cs
\ No newline at end of file
diff --git a/mcs/class/System.Runtime.Caching/Test/Common/AppDomainTools.cs b/mcs/class/System.Runtime.Caching/Test/Common/AppDomainTools.cs
new file mode 100644 (file)
index 0000000..5bbf8e1
--- /dev/null
@@ -0,0 +1,80 @@
+//
+// AppDomainTools.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using System.Security.Policy;
+using System.Text;
+
+using NUnit.Framework;
+
+namespace MonoTests.Common
+{
+       class AppDomainTools
+       {
+               public static void RunInSeparateDomain (Action handler, string format, params object[] parms)
+               {
+                       var setup = AppDomain.CurrentDomain.SetupInformation;
+                       setup.ShadowCopyDirectories = null;
+                       setup.ShadowCopyFiles = null;
+                       setup.ApplicationBase = Path.GetDirectoryName (typeof (AppDomainTools).Assembly.Location);
+                       var ad = AppDomain.CreateDomain ("Test", new Evidence (AppDomain.CurrentDomain.Evidence) , setup);
+                       ad.SetData ("testHandler", handler);
+                       string message;
+                       if (parms != null && parms.Length > 0)
+                               message = String.Format (format, parms);
+                       else
+                               message = format;
+                       ad.SetData ("failureMessage", message);
+                       //ad.AssemblyResolve += ResolveAssemblyEventHandler;
+                       ad.DoCallBack (RunTest);
+               }
+
+               static Assembly ResolveAssemblyEventHandler (object sender, ResolveEventArgs args)
+               {
+                       string path = Path.Combine (AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "nunit.framework.dll");
+                       if (File.Exists (path))
+                               return Assembly.LoadFrom (path);
+
+                       return null;
+               }
+
+               static void RunTest ()
+               {
+                       Action handler = AppDomain.CurrentDomain.GetData ("testHandler") as Action;
+                       if (handler == null) {
+                               string message = AppDomain.CurrentDomain.GetData ("failureMessage") as string;
+                               Assert.Fail (message);
+                       }
+
+                       handler ();
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/Test/Common/AssertExtensions.cs b/mcs/class/System.Runtime.Caching/Test/Common/AssertExtensions.cs
new file mode 100644 (file)
index 0000000..41e340b
--- /dev/null
@@ -0,0 +1,82 @@
+using System;
+using System.Collections.Generic;
+
+using NUnit.Framework;
+
+namespace MonoTests.Common
+{
+       delegate void AssertThrowsDelegate();
+
+       static class AssertExtensions
+       {
+               public static void AreEqual (byte[] expected, byte[] data, string message)
+               {
+                       if (expected == null) {
+                               if (data == null)
+                                       return;
+                               Assert.Fail ("{0}{1}Expected: null{1}Got: byte array with {2} elements and of rank {3}{1}",
+                                       message, Environment.NewLine, data.Length, data.Rank);
+                       }
+
+                       if (data == null)
+                               Assert.Fail ("{0}{1}Expected: byte array with {2} elements and rank {3}{1}Got: null{1}",
+                                       message, Environment.NewLine, expected.Length, expected.Rank);
+
+                       if (expected.Rank > 1)
+                               Assert.Fail ("Only single-dimensional arrays are supported.");
+
+                       if (expected.Rank != data.Rank || expected.Length != data.Length)
+                               Assert.Fail ("{0}{1}Expected: byte array with {2} elements and rank {3}{1}Got: byte array with {4} elements and rank {5}{1}",
+                                       message, Environment.NewLine, expected.Length, expected.Rank, data.Length, data.Rank);
+
+                       int max = expected.Length;
+                       for (int i = 0; i < max; i++) {
+                               if (expected[i] != data[i])
+                                       Assert.Fail ("{0}{1}Arrays differ at index {2}.{1}Expected 0x{3:X} got 0x{4:X}{1}",
+                                               message, Environment.NewLine, i, expected[i], data[i]);
+                       }
+               }
+
+               public static void Throws<ET> (AssertThrowsDelegate code, string message)
+               {
+                       Throws(typeof(ET), code, message);
+               }
+
+               public static void Throws(Type exceptionType, AssertThrowsDelegate code, string message)
+               {
+                       if (code == null)
+                               Assert.Fail("No code provided for the test.");
+
+                       Exception exception = null;
+                       try
+                       {
+                               code();
+                       }
+                       catch (Exception ex)
+                       {
+                               exception = ex;
+                       }
+
+                       if (exceptionType == null)
+                       {
+                               if (exception == null)
+                                       Assert.Fail("{0}{1}Expected: any exception thrown{1}But was: no exception thrown{1}",
+                                               message, Environment.NewLine);
+                               return;
+                       }
+
+                       if (exception == null || exception.GetType() != exceptionType)
+                               Assert.Fail("{0}{1}Expected: {2}{1}But was: {3}{1}{4}{1}",
+                                   message,
+                                   Environment.NewLine,
+                                   exceptionType,
+                                   exception == null ? "no exception" : exception.GetType().ToString(),
+                                   exception == null ? "no exception" : exception.ToString());
+               }
+
+               public static void Throws(AssertThrowsDelegate code, string message)
+               {
+                       Throws(null, code, message);
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/Test/Common/ChangeLog b/mcs/class/System.Runtime.Caching/Test/Common/ChangeLog
new file mode 100644 (file)
index 0000000..dbeafd6
--- /dev/null
@@ -0,0 +1,6 @@
+2010-04-24  Marek Habersack  <mhabersack@novell.com>
+
+       * AppDomainTools.cs, AssertExtensions.cs, PokerChangeMonitor.cs,
+       PokerMemoryCache.cs, PokerObjectCache.cs,
+       TestNotificationSystem.cs: added
+
diff --git a/mcs/class/System.Runtime.Caching/Test/Common/PokerChangeMonitor.cs b/mcs/class/System.Runtime.Caching/Test/Common/PokerChangeMonitor.cs
new file mode 100644 (file)
index 0000000..344f724
--- /dev/null
@@ -0,0 +1,45 @@
+using System;
+using System.Collections.Generic;
+using System.Runtime.Caching;
+using System.Text;
+
+namespace MonoTests.Common
+{
+       class PokerChangeMonitor : ChangeMonitor
+       {
+               List <string> calls;
+               string uniqueId;
+
+               public List<string> Calls
+               {
+                       get
+                       {
+                               if (calls == null)
+                                       calls = new List<string> ();
+
+                               return calls;
+                       }
+               }
+
+               public override string UniqueId
+               {
+                       get { return uniqueId; }
+               }
+
+               public PokerChangeMonitor ()
+               {
+                       uniqueId = "UniqueID";
+                       InitializationComplete ();
+               }
+
+               public void SignalChange ()
+               {
+                       OnChanged (null);
+               }
+
+               protected override void Dispose (bool disposing)
+               {
+                       Calls.Add ("Dispose (bool disposing)");
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/Test/Common/PokerMemoryCache.cs b/mcs/class/System.Runtime.Caching/Test/Common/PokerMemoryCache.cs
new file mode 100644 (file)
index 0000000..d2c0aaa
--- /dev/null
@@ -0,0 +1,158 @@
+//
+// PokerMemoryCache.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.Specialized;
+using System.Runtime.Caching;
+using System.Text;
+
+namespace MonoTests.Common
+{
+       class PokerMemoryCache : MemoryCache
+       {
+               List<string> calls;
+
+               public List<string> Calls
+               {
+                       get
+                       {
+                               if (calls == null)
+                                       calls = new List<string> ();
+                               return calls;
+                       }
+               }
+
+               public override object this [string key]
+               {
+                       get
+                       {
+                               Calls.Add ("get_this [string key]");
+                               return base [key];
+                       }
+                       set
+                       {
+                               Calls.Add ("set_this [string key]");
+                               base [key] = value;
+                       }
+               }
+
+               public PokerMemoryCache (string name, NameValueCollection config = null)
+                       : base (name, config)
+               { }
+
+               public override CacheItem AddOrGetExisting (CacheItem item, CacheItemPolicy policy)
+               {
+                       Calls.Add ("AddOrGetExisting (CacheItem item, CacheItemPolicy policy)");
+                       return base.AddOrGetExisting (item, policy);
+               }
+
+               public override object AddOrGetExisting (string key, object value, CacheItemPolicy policy, string regionName = null)
+               {
+                       Calls.Add ("AddOrGetExisting (string key, object value, CacheItemPolicy policy, string regionName = null)");
+                       return base.AddOrGetExisting (key, value, policy, regionName);
+               }
+
+               public override object AddOrGetExisting (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)
+               {
+                       Calls.Add ("AddOrGetExisting (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)");
+                       return base.AddOrGetExisting (key, value, absoluteExpiration, regionName);
+               }
+
+               public override object Get (string key, string regionName = null)
+               {
+                       Calls.Add ("Get (string key, string regionName = null)");
+                       return base.Get (key, regionName);
+               }
+
+               public override CacheItem GetCacheItem (string key, string regionName = null)
+               {
+                       Calls.Add ("GetCacheItem (string key, string regionName = null)");
+                       return base.GetCacheItem (key, regionName);
+               }
+
+               public override long GetCount (string regionName = null)
+               {
+                       Calls.Add ("GetCount (string regionName = null)");
+                       return base.GetCount (regionName);
+               }
+
+               public override bool Contains (string key, string regionName = null)
+               {
+                       Calls.Add ("Contains (string key, string regionName = null)");
+                       return base.Contains (key, regionName);
+               }
+
+               public override CacheEntryChangeMonitor CreateCacheEntryChangeMonitor (IEnumerable<string> keys, string regionName = null)
+               {
+                       Calls.Add ("CreateCacheEntryChangeMonitor (IEnumerable<string> keys, string regionName = null)");
+                       return base.CreateCacheEntryChangeMonitor (keys, regionName);
+               }
+
+               protected override IEnumerator<KeyValuePair<string, object>> GetEnumerator ()
+               {
+                       Calls.Add ("IEnumerator<KeyValuePair<string, object>> GetEnumerator ()");
+                       return base.GetEnumerator ();
+               }
+
+               public IEnumerator<KeyValuePair<string, object>> DoGetEnumerator ()
+               {
+                       return GetEnumerator ();
+               }
+
+               public override IDictionary<string, object> GetValues (IEnumerable<string> keys, string regionName = null)
+               {
+                       Calls.Add ("IDictionary<string, object> GetValues (IEnumerable<string> keys, string regionName = null)");
+                       return base.GetValues (keys, regionName);
+               }
+
+               public override IDictionary<string, object> GetValues (string regionName, params string [] keys)
+               {
+                       Calls.Add ("IDictionary<string, object> GetValues (string regionName, params string [] keys)");
+                       return base.GetValues (regionName, keys);
+               }
+
+               public override void Set (CacheItem item, CacheItemPolicy policy)
+               {
+                       Calls.Add ("Set (CacheItem item, CacheItemPolicy policy)");
+                       base.Set (item, policy);
+               }
+
+               public override void Set (string key, object value, CacheItemPolicy policy, string regionName = null)
+               {
+                       Calls.Add ("Set (string key, object value, CacheItemPolicy policy, string regionName = null)");
+                       base.Set (key, value, policy, regionName);
+               }
+
+               public override void Set (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)
+               {
+                       Calls.Add ("Set (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)");
+                       base.Set (key, value, absoluteExpiration, regionName);
+               }
+
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/Test/Common/PokerObjectCache.cs b/mcs/class/System.Runtime.Caching/Test/Common/PokerObjectCache.cs
new file mode 100644 (file)
index 0000000..1bef81e
--- /dev/null
@@ -0,0 +1,186 @@
+//
+// PokerObjectCache.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Runtime.Caching;
+
+namespace MonoTests.Common
+{
+       class PokerObjectCache : ObjectCache
+       {
+               Dictionary <string, object> cache;
+
+               Dictionary<string, object> Cache {
+                       get
+                       {
+                               if (cache == null)
+                                       cache = new Dictionary<string, object> ();
+                               return cache;
+                       }
+               }
+
+               public string MethodCalled { get; private set; }
+
+               public override object AddOrGetExisting (string key, object value, CacheItemPolicy policy, string regionName = null)
+               {
+                       MethodCalled = "AddOrGetExisting (string key, object value, CacheItemPolicy policy, string regionName = null)";
+                       if (String.IsNullOrEmpty (key) || value == null)
+                               return null;
+
+                       object item;
+                       if (Cache.TryGetValue (key, out item))
+                               return item;
+
+                       Cache.Add (key, value);
+                       return null;
+               }
+
+               public override CacheItem AddOrGetExisting (CacheItem value, CacheItemPolicy policy)
+               {
+                       MethodCalled = "AddOrGetExisting (CacheItem value, CacheItemPolicy policy)";
+                       if (value == null)
+                               return null;
+
+                       object item;
+                       if (Cache.TryGetValue (value.Key, out item))
+                               return item as CacheItem;
+
+                       Cache.Add (value.Key, value);
+                       return null;
+               }
+
+               public override object AddOrGetExisting (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)
+               {
+                       MethodCalled = "AddOrGetExisting (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)";
+                       if (String.IsNullOrEmpty (key) || value == null)
+                               return null;
+
+                       object item;
+                       if (Cache.TryGetValue (key, out item))
+                               return item;
+
+                       Cache.Add (key, value);
+                       return null;
+               }
+
+               public override bool Contains (string key, string regionName = null)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override CacheEntryChangeMonitor CreateCacheEntryChangeMonitor (IEnumerable<string> keys, string regionName = null)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override DefaultCacheCapabilities DefaultCacheCapabilities
+               {
+                       get { throw new NotImplementedException (); }
+               }
+
+               public override object Get (string key, string regionName = null)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override CacheItem GetCacheItem (string key, string regionName = null)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override long GetCount (string regionName = null)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               protected override IEnumerator<KeyValuePair<string, object>> GetEnumerator ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override IDictionary<string, object> GetValues (IEnumerable<string> keys, string regionName = null)
+               {
+                       MethodCalled = "IDictionary<string, object> GetValues (IEnumerable<string> keys, string regionName = null)";
+                       var ret = new Dictionary<string, object> ();
+                       if (keys == null)
+                               return ret;
+                       
+                       Dictionary <string, object> cache = Cache;
+                       if (cache.Count == 0)
+                               return ret;
+
+                       object value;
+                       foreach (string key in keys) {
+                               if (!cache.TryGetValue (key, out value))
+                                       continue;
+
+                               ret.Add (key, value);
+                       }
+
+                       return ret;
+               }
+
+               public override string Name
+               {
+                       get { throw new NotImplementedException (); }
+               }
+
+               public override object Remove (string key, string regionName = null)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override void Set (string key, object value, CacheItemPolicy policy, string regionName = null)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override void Set (CacheItem item, CacheItemPolicy policy)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override void Set (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override object this [string key]
+               {
+                       get
+                       {
+                               throw new NotImplementedException ();
+                       }
+                       set
+                       {
+                               throw new NotImplementedException ();
+                       }
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/Test/Common/TestNotificationSystem.cs b/mcs/class/System.Runtime.Caching/Test/Common/TestNotificationSystem.cs
new file mode 100644 (file)
index 0000000..dbd8cbb
--- /dev/null
@@ -0,0 +1,91 @@
+//
+// TestNotificationSystem.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Runtime.Caching;
+using System.Runtime.Caching.Hosting;
+
+namespace MonoTests.Common
+{
+       class TestNotificationSystem : IServiceProvider, IFileChangeNotificationSystem
+       {
+               OnChangedCallback callback;
+
+               public bool StartMonitoringCalled { get; private set; }
+               public uint StartMonitoringCallCount { get; private set; }
+               public bool StopMonitoringCalled { get; private set; }
+               public uint StopMonitoringCallCount { get; private set; }
+               public bool UseNullState { get; set; }
+
+               public object GetService (Type serviceType)
+               {
+                       return this;
+               }
+
+               object IServiceProvider.GetService (Type serviceType)
+               {
+                       return GetService (serviceType);
+               }
+
+               public void FakeChanged (string filePath)
+               {
+                       if (callback == null)
+                               return;
+
+                       callback (null);
+               }
+
+               public void StartMonitoring (string filePath, OnChangedCallback onChangedCallback, out object state, out DateTimeOffset lastWriteTime, out long fileSize)
+               {
+                       if (UseNullState)
+                               state = null;
+                       else
+                               state = filePath;
+                       lastWriteTime = DateTimeOffset.FromFileTime (DateTime.Now.Ticks);
+                       callback = onChangedCallback;
+                       fileSize = 10;
+                       StartMonitoringCalled = true;
+                       StartMonitoringCallCount++;
+               }
+
+               public void StopMonitoring (string filePath, object state)
+               {
+                       StopMonitoringCalled = true;
+                       StopMonitoringCallCount++;
+               }
+
+               void IFileChangeNotificationSystem.StartMonitoring (string filePath, OnChangedCallback onChangedCallback, out object state, out DateTimeOffset lastWriteTime, out long fileSize)
+               {
+                       StartMonitoring (filePath, onChangedCallback, out state, out lastWriteTime, out fileSize);
+               }
+
+               void IFileChangeNotificationSystem.StopMonitoring (string filePath, object state)
+               {
+                       StopMonitoring (filePath, state);
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/Test/System.Runtime.Caching/ChangeLog b/mcs/class/System.Runtime.Caching/Test/System.Runtime.Caching/ChangeLog
new file mode 100644 (file)
index 0000000..657cc7b
--- /dev/null
@@ -0,0 +1,10 @@
+2010-04-26  Marek Habersack  <mhabersack@novell.com>
+
+       * MemoryCacheTest.cs: added tests for LRU removal of entries.
+
+2010-04-24  Marek Habersack  <mhabersack@novell.com>
+
+       * MemoryCacheTest.cs, ObjectCacheTest.cs: added
+
+       * HostFileChangeMonitorTest.cs: added more tests.
+
diff --git a/mcs/class/System.Runtime.Caching/Test/System.Runtime.Caching/HostFileChangeMonitorTest.cs b/mcs/class/System.Runtime.Caching/Test/System.Runtime.Caching/HostFileChangeMonitorTest.cs
new file mode 100644 (file)
index 0000000..a52480b
--- /dev/null
@@ -0,0 +1,305 @@
+//
+// HostFileChangeMonitorTest.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Reflection;
+using System.Runtime.Caching;
+using System.Runtime.Caching.Hosting;
+using System.Text;
+
+using NUnit.Framework;
+using MonoTests.Common;
+
+namespace MonoTests.System.Runtime.Caching
+{      
+       [TestFixture]
+       public class HostFileChangeMonitorTest
+       {
+               [Test]
+               public void Constructor_Exceptions ()
+               {
+                       HostFileChangeMonitor monitor;
+                       string relPath = Path.Combine ("relative", "file", "path");
+                       var paths = new List<string> {
+                               relPath
+                       };
+
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               monitor = new HostFileChangeMonitor (paths);
+                       }, "#A1");
+
+                       paths.Clear ();
+                       paths.Add (null);
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               monitor = new HostFileChangeMonitor (paths);
+                       }, "#A2");
+
+                       paths.Clear ();
+                       paths.Add (String.Empty);
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               monitor = new HostFileChangeMonitor (paths);
+                       }, "#A3");
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               monitor = new HostFileChangeMonitor (null);
+                       }, "#A4");
+
+                       paths.Clear ();
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               monitor = new HostFileChangeMonitor (paths);
+                       }, "#A5");
+               }
+
+               [Test]
+               public void Constructor_MissingFiles ()
+               {
+                       AppDomainTools.RunInSeparateDomain (Constructor_MissingFiles_Handler, "Constructor_MissingFiles");
+               }
+
+               static void Constructor_MissingFiles_Handler ()
+               {
+                       HostFileChangeMonitor monitor;
+                       PlatformID pid = Environment.OSVersion.Platform;
+                       bool runningOnWindows = ((int) pid != 128 && pid != PlatformID.Unix && pid != PlatformID.MacOSX);
+                       string missingFile = Path.Combine ("missing", "file", "path");
+
+                       if (runningOnWindows)
+                               missingFile = "c:\\" + missingFile;
+                       else
+                               missingFile = "/" + missingFile;
+
+                       var paths = new List<string> {
+                               missingFile
+                       };
+
+                       // Actually thrown by FileSystemWatcher constructor - note that the exception message suggests the file's
+                       // parent directory is being watched, not the file itself:
+                       //
+                       // MonoTests.System.Runtime.Caching.HostFileChangeMonitorTest.Constructor_MissingFiles:
+                       // System.ArgumentException : The directory name c:\missing\file is invalid.
+                       // at System.IO.FileSystemWatcher..ctor(String path, String filter)
+                       // at System.IO.FileSystemWatcher..ctor(String path)
+                       // at System.Runtime.Caching.FileChangeNotificationSystem.System.Runtime.Caching.Hosting.IFileChangeNotificationSystem.StartMonitoring(String filePath, OnChangedCallback onChangedCallback, Object& state, DateTimeOffset& lastWriteTime, Int64& fileSize)
+                       // at System.Runtime.Caching.HostFileChangeMonitor.InitDisposableMembers()
+                       // at System.Runtime.Caching.HostFileChangeMonitor..ctor(IList`1 filePaths)
+                       // at MonoTests.System.Runtime.Caching.HostFileChangeMonitorTest.Constructor_MissingFiles() in c:\users\grendel\documents\visual studio 2010\Projects\System.Runtime.Caching.Test\System.Runtime.Caching.Test\System.Runtime.Caching\HostFileChangeMonitorTest.cs:line 68
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               monitor = new HostFileChangeMonitor (paths);
+                       }, "#A1");
+
+                       if (runningOnWindows)
+                               missingFile = "c:\\file.txt";
+                       else
+                               missingFile = "/file.txt";
+
+                       paths.Clear ();
+                       paths.Add (missingFile);
+                       monitor = new HostFileChangeMonitor (paths);
+                       Assert.AreEqual (1, monitor.FilePaths.Count, "#A2-1");
+                       Assert.AreEqual (missingFile, monitor.FilePaths [0], "#A2-2");
+                       Assert.AreEqual (missingFile + "701CE1722770000FFFFFFFFFFFFFFFF", monitor.UniqueId, "#A2-4");
+
+                       paths.Add (missingFile);
+                       monitor = new HostFileChangeMonitor (paths);
+                       Assert.AreEqual (2, monitor.FilePaths.Count, "#A3-1");
+                       Assert.AreEqual (missingFile, monitor.FilePaths [0], "#A3-2");
+                       Assert.AreEqual (missingFile, monitor.FilePaths [1], "#A3-3");
+                       Assert.AreEqual (missingFile + "701CE1722770000FFFFFFFFFFFFFFFF", monitor.UniqueId, "#A3-4");
+               }
+
+               [Test]
+               public void Constructor_Duplicates ()
+               {
+                       HostFileChangeMonitor monitor;
+                       PlatformID pid = Environment.OSVersion.Platform;
+                       bool runningOnWindows = ((int) pid != 128 && pid != PlatformID.Unix && pid != PlatformID.MacOSX);
+                       string missingFile = Path.Combine ("missing", "file", "path");
+
+                       if (runningOnWindows)
+                               missingFile = "c:\\file.txt";
+                       else
+                               missingFile = "/file.txt";
+
+                       var paths = new List<string> {
+                               missingFile,
+                               missingFile
+                       };
+
+                       // Just checks if it doesn't throw any exception for dupes
+                       monitor = new HostFileChangeMonitor (paths);
+               }
+
+               static Tuple <string, string, string, IList <string>> SetupMonitoring ()
+               {
+                       string testPath = Path.Combine (Path.GetTempPath (), "Dispose_Calls_StopMonitoring");
+                       if (!Directory.Exists (testPath))
+                               Directory.CreateDirectory (testPath);
+
+                       string firstFile = Path.Combine (testPath, "FirstFile.txt");
+                       string secondFile = Path.Combine (testPath, "SecondFile.txt");
+
+                       File.WriteAllText (firstFile, "I am the first file.");
+                       File.WriteAllText (secondFile, "I am the second file.");
+
+                       var paths = new List<string> {
+                               firstFile,
+                               secondFile
+                       };
+
+                       return new Tuple<string, string, string, IList<string>> (testPath, firstFile, secondFile, paths);
+               }
+
+               static void CleanupMonitoring (Tuple<string, string, string, IList<string>> setup)
+               {
+                       string testPath = setup != null ? setup.Item1 : null;
+                       if (String.IsNullOrEmpty (testPath) || !Directory.Exists (testPath))
+                               return;
+
+                       foreach (string f in Directory.EnumerateFiles(testPath)) {
+                               try {
+                                       File.Delete (f);
+                               } catch {
+                                       // ignore
+                               }
+                       }
+               }
+
+               [Test]
+               public void Constructor_Calls_StartMonitoring ()
+               {
+                       AppDomainTools.RunInSeparateDomain (Constructor_Calls_StartMonitoring_Handler, "Constructor_Calls_StartMonitoring_Handler");
+               }
+
+               static void Constructor_Calls_StartMonitoring_Handler ()
+               {
+                       Tuple<string, string, string, IList<string>> setup = null;
+                       try {
+                               var tns = new TestNotificationSystem ();
+                               ObjectCache.Host = tns;
+                               setup = SetupMonitoring ();
+                               var monitor = new HostFileChangeMonitor (setup.Item4);
+
+                               Assert.IsTrue (tns.StartMonitoringCalled, "#A1-1");
+                               Assert.AreEqual (2, tns.StartMonitoringCallCount, "#A1-2");
+                       } finally {
+                               CleanupMonitoring (setup);
+                       }
+               }
+
+               [Test]
+               public void Dispose_Calls_StopMonitoring ()
+               {
+                       AppDomainTools.RunInSeparateDomain (Dispose_Calls_StopMonitoring_Handler, "Dispose_Calls_StopMonitoring_Handler");
+               }
+
+               static void Dispose_Calls_StopMonitoring_Handler ()
+               {
+                       Tuple<string, string, string, IList<string>> setup = null;
+                       try {
+                               var tns = new TestNotificationSystem ();
+                               ObjectCache.Host = tns;
+                               setup = SetupMonitoring ();
+                               var monitor = new HostFileChangeMonitor (setup.Item4);
+                               tns.FakeChanged (setup.Item2);
+
+                               Assert.IsTrue (tns.StopMonitoringCalled, "#A1-1");
+                               Assert.AreEqual (2, tns.StopMonitoringCallCount, "#A1-2");
+                       } finally {
+                               CleanupMonitoring (setup);
+                       }
+               }
+
+               [Test]
+               public void Dispose_NullState_NoStopMonitoring ()
+               {
+                       AppDomainTools.RunInSeparateDomain (Dispose_NullState_NoStopMonitoring_Handler, "Dispose_NullState_NoStopMonitoring_Handler");
+               }
+
+               static void Dispose_NullState_NoStopMonitoring_Handler ()
+               {
+                       Tuple<string, string, string, IList<string>> setup = null;
+                       try {
+                               var tns = new TestNotificationSystem ();
+                               tns.UseNullState = true;
+                               ObjectCache.Host = tns;
+                               setup = SetupMonitoring ();
+                               var monitor = new HostFileChangeMonitor (setup.Item4);
+                               tns.FakeChanged (setup.Item2);
+
+                               Assert.IsFalse (tns.StopMonitoringCalled, "#A1-1");
+                               Assert.AreEqual (0, tns.StopMonitoringCallCount, "#A1-2");
+                       } finally {
+                               CleanupMonitoring (setup);
+                       }
+               }
+
+               [Test]
+               public void UniqueId ()
+               {
+                       Tuple<string, string, string, IList<string>> setup = null;
+                       try {
+                               setup = SetupMonitoring ();
+                               FileInfo fi;
+                               var monitor = new HostFileChangeMonitor (setup.Item4);
+                               var sb = new StringBuilder ();
+
+                               fi = new FileInfo (setup.Item2);
+                               sb.AppendFormat ("{0}{1:X}{2:X}",
+                                       setup.Item2,
+                                       fi.LastWriteTimeUtc.Ticks,
+                                       fi.Length);
+
+                               fi = new FileInfo (setup.Item3);
+                               sb.AppendFormat ("{0}{1:X}{2:X}",
+                                       setup.Item3,
+                                       fi.LastWriteTimeUtc.Ticks,
+                                       fi.Length);
+
+                               Assert.AreEqual (sb.ToString (), monitor.UniqueId, "#A1");
+
+                               var list = new List<string> (setup.Item4);
+                               list.Add (setup.Item1);
+
+                               monitor = new HostFileChangeMonitor (list);
+                               var di = new DirectoryInfo (setup.Item1);
+                               sb.AppendFormat ("{0}{1:X}{2:X}",
+                                       setup.Item1,
+                                       di.LastWriteTimeUtc.Ticks,
+                                       -1L);
+                               Assert.AreEqual (sb.ToString (), monitor.UniqueId, "#A2");
+
+                               list.Add (setup.Item1);
+                               monitor = new HostFileChangeMonitor (list);
+                               Assert.AreEqual (sb.ToString (), monitor.UniqueId, "#A3");
+                       } finally {
+                               CleanupMonitoring (setup);
+                       }
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/Test/System.Runtime.Caching/MemoryCacheTest.cs b/mcs/class/System.Runtime.Caching/Test/System.Runtime.Caching/MemoryCacheTest.cs
new file mode 100644 (file)
index 0000000..0039af6
--- /dev/null
@@ -0,0 +1,1240 @@
+//
+// MemoryCacheTest.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Collections.Specialized;
+using System.Runtime.Caching;
+using System.Threading;
+
+using NUnit.Framework;
+using MonoTests.Common;
+
+namespace MonoTests.System.Runtime.Caching
+{
+       [TestFixture]
+       public class MemoryCacheTest
+       {
+               [Test]
+               public void ConstructorParameters ()
+               {
+                       MemoryCache mc;
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               mc = new MemoryCache (null);
+                       }, "#A1");
+
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               mc = new MemoryCache (String.Empty);
+                       }, "#A2");
+
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               mc = new MemoryCache ("default");
+                       }, "#A3");
+
+                       var config = new NameValueCollection ();
+                       config.Add ("CacheMemoryLimitMegabytes", "invalid");
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               mc = new MemoryCache ("MyCache", config);
+                       }, "#A4-1");
+
+                       config.Clear ();
+                       config.Add ("PhysicalMemoryLimitPercentage", "invalid");
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               mc = new MemoryCache ("MyCache", config);
+                       }, "#A4-2");
+
+                       config.Clear ();
+                       config.Add ("PollingInterval", "invalid");
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               mc = new MemoryCache ("MyCache", config);
+                       }, "#A4-3");
+
+                       config.Clear ();
+                       config.Add ("CacheMemoryLimitMegabytes", "-1");
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               mc = new MemoryCache ("MyCache", config);
+                       }, "#A4-4");
+
+                       config.Clear ();
+                       config.Add ("CacheMemoryLimitMegabytes", UInt64.MaxValue.ToString ());
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               mc = new MemoryCache ("MyCache", config);
+                       }, "#A4-5");
+
+                       config.Clear ();
+                       config.Add ("PhysicalMemoryLimitPercentage", "-1");
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               mc = new MemoryCache ("MyCache", config);
+                       }, "#A4-6");
+
+                       config.Clear ();
+                       config.Add ("PhysicalMemoryLimitPercentage", UInt64.MaxValue.ToString ());
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               mc = new MemoryCache ("MyCache", config);
+                       }, "#A4-7");
+
+                       config.Clear ();
+                       config.Add ("PhysicalMemoryLimitPercentage", UInt32.MaxValue.ToString ());
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               mc = new MemoryCache ("MyCache", config);
+                       }, "#A4-8");
+
+                       config.Clear ();
+                       config.Add ("PhysicalMemoryLimitPercentage", "-10");
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               mc = new MemoryCache ("MyCache", config);
+                       }, "#A4-9");
+
+                       config.Clear ();
+                       config.Add ("PhysicalMemoryLimitPercentage", "0");
+                       // Just make sure it doesn't throw any exception
+                       mc = new MemoryCache ("MyCache", config);
+
+                       config.Clear ();
+                       config.Add ("PhysicalMemoryLimitPercentage", "101");
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               mc = new MemoryCache ("MyCache", config);
+                       }, "#A4-10");
+
+                       // Just make sure it doesn't throw any exception
+                       config.Clear ();
+                       config.Add ("UnsupportedSetting", "123");
+                       mc = new MemoryCache ("MyCache", config);
+               }
+
+               [Test]
+               public void Defaults ()
+               {
+                       var mc = new MemoryCache ("MyCache");
+                       Assert.AreEqual ("MyCache", mc.Name, "#A1");
+                       Assert.AreEqual (98, mc.PhysicalMemoryLimit, "#A2");
+                       // Value of this property is different from system to system
+                       //Assert.AreEqual (0, mc.CacheMemoryLimit, "#A3");
+                       Assert.AreEqual (TimeSpan.FromMinutes (2), mc.PollingInterval, "#A4");
+                       Assert.AreEqual (
+                               DefaultCacheCapabilities.InMemoryProvider |
+                               DefaultCacheCapabilities.CacheEntryChangeMonitors |
+                               DefaultCacheCapabilities.AbsoluteExpirations |
+                               DefaultCacheCapabilities.SlidingExpirations |
+                               DefaultCacheCapabilities.CacheEntryRemovedCallback |
+                               DefaultCacheCapabilities.CacheEntryUpdateCallback,
+                               mc.DefaultCacheCapabilities, "#A1");
+               }
+
+               [Test]
+               public void DefaultInstanceDefaults ()
+               {
+                       var mc = MemoryCache.Default;
+                       Assert.AreEqual ("Default", mc.Name, "#A1");
+                       Assert.AreEqual (98, mc.PhysicalMemoryLimit, "#A2");
+                       // Value of this property is different from system to system
+                       //Assert.AreEqual (0, mc.CacheMemoryLimit, "#A3");
+                       Assert.AreEqual (TimeSpan.FromMinutes (2), mc.PollingInterval, "#A4");
+                       Assert.AreEqual (
+                               DefaultCacheCapabilities.InMemoryProvider |
+                               DefaultCacheCapabilities.CacheEntryChangeMonitors |
+                               DefaultCacheCapabilities.AbsoluteExpirations |
+                               DefaultCacheCapabilities.SlidingExpirations |
+                               DefaultCacheCapabilities.CacheEntryRemovedCallback |
+                               DefaultCacheCapabilities.CacheEntryUpdateCallback,
+                               mc.DefaultCacheCapabilities, "#A1");
+               }
+
+               [Test]
+               public void ConstructorValues ()
+               {
+                       var config = new NameValueCollection ();
+                       config.Add ("PhysicalMemoryLimitPercentage", "0");
+                       config.Add ("CacheMemoryLimitMegabytes", "1");
+                       config.Add ("pollingInterval", "00:10:00");
+
+                       var mc = new MemoryCache ("MyCache", config);
+                       Assert.AreEqual (98, mc.PhysicalMemoryLimit, "#A1");
+                       Assert.AreEqual (1048576, mc.CacheMemoryLimit, "#A2");
+                       Assert.AreEqual (TimeSpan.FromMinutes (10), mc.PollingInterval, "#A3");
+
+                       config.Clear ();
+                       config.Add ("PhysicalMemoryLimitPercentage", "10");
+                       config.Add ("CacheMemoryLimitMegabytes", "5");
+                       config.Add ("PollingInterval", "01:10:00");
+
+                       mc = new MemoryCache ("MyCache", config);
+                       Assert.AreEqual (10, mc.PhysicalMemoryLimit, "#B1");
+                       Assert.AreEqual (5242880, mc.CacheMemoryLimit, "#B2");
+                       Assert.AreEqual (TimeSpan.FromMinutes (70), mc.PollingInterval, "#B3");
+               }
+
+               [Test]
+               public void Indexer ()
+               {
+                       var mc = new PokerMemoryCache ("MyCache");
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               mc [null] = "value";
+                       }, "#A1-1");
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               object v = mc [null];
+                       }, "#A1-2");
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               mc ["key"] = null;
+                       }, "#A1-3");
+
+                       mc.Calls.Clear ();
+                       mc ["key"] = "value";
+                       Assert.AreEqual (3, mc.Calls.Count, "#A2-1");
+                       Assert.AreEqual ("set_this [string key]", mc.Calls [0], "#A2-2");
+                       Assert.AreEqual ("Set (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)", mc.Calls [1], "#A2-3");
+                       Assert.AreEqual ("Set (string key, object value, CacheItemPolicy policy, string regionName = null)", mc.Calls [2], "#A2-4");
+                       Assert.IsTrue (mc.Contains ("key"), "#A2-5");
+
+                       mc.Calls.Clear ();
+                       object value = mc ["key"];
+                       Assert.AreEqual (1, mc.Calls.Count, "#A3-1");
+                       Assert.AreEqual ("get_this [string key]", mc.Calls [0], "#A3-2");
+                       Assert.AreEqual ("value", value, "#A3-3");
+               }
+
+               [Test]
+               public void Contains ()
+               {
+                       var mc = new PokerMemoryCache ("MyCache");
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               mc.Contains (null);
+                       }, "#A1-1");
+
+                       AssertExtensions.Throws<NotSupportedException> (() => {
+                               mc.Contains ("key", "region");
+                       }, "#A1-2");
+
+                       mc.Set ("key", "value", ObjectCache.InfiniteAbsoluteExpiration);
+                       Assert.IsTrue (mc.Contains ("key"), "#A2");
+
+                       var cip = new CacheItemPolicy ();
+                       cip.Priority = CacheItemPriority.NotRemovable;
+                       cip.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds (500);
+                       mc.Set ("key", "value", cip);
+                       Assert.IsTrue (mc.Contains ("key"), "#B1-1");
+                       Thread.Sleep (1000);
+                       // The call below removes the expired entry and returns false
+                       Assert.IsFalse (mc.Contains ("key"), "#B1-2");
+               }
+
+               [Test]
+               public void CreateCacheEntryChangeMonitor ()
+               {
+                       var mc = new PokerMemoryCache ("MyCache");
+
+                       AssertExtensions.Throws<NotSupportedException> (() => {
+                               mc.CreateCacheEntryChangeMonitor (new string [] { "key" }, "region");
+                       }, "#A1-1");
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               mc.CreateCacheEntryChangeMonitor (null);
+                       }, "#A1-2");
+
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               mc.CreateCacheEntryChangeMonitor (new string [] {});
+                       }, "#A1-3");
+
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               mc.CreateCacheEntryChangeMonitor (new string [] { "key", null });
+                       }, "#A1-4");
+
+                       mc.Set ("key1", "value1", ObjectCache.InfiniteAbsoluteExpiration);
+                       mc.Set ("key2", "value2", ObjectCache.InfiniteAbsoluteExpiration);
+                       mc.Set ("key3", "value3", ObjectCache.InfiniteAbsoluteExpiration);
+
+                       CacheEntryChangeMonitor monitor = mc.CreateCacheEntryChangeMonitor (new string [] { "key1", "key2" });
+                       Assert.IsNotNull (monitor, "#A2-1");
+                       Assert.AreEqual ("System.Runtime.Caching.MemoryCacheEntryChangeMonitor", monitor.GetType ().ToString (), "#A2-2");
+                       Assert.AreEqual (2, monitor.CacheKeys.Count, "#A2-3");
+                       Assert.AreEqual ("key1", monitor.CacheKeys [0], "#A2-3-1");
+                       Assert.AreEqual ("key2", monitor.CacheKeys [1], "#A2-3-2");
+                       Assert.IsNull (monitor.RegionName, "#A2-4");
+                       // Since this comparison can fail from time to time, leaving it commented out
+                       //Assert.AreEqual (DateTimeOffset.UtcNow.ToString (), monitor.LastModified.ToString (), "#A2-5");
+                       Assert.IsFalse (monitor.HasChanged, "#A2-5");
+
+                       // The actual unique id is constructed from key names followed by the hex value of ticks of their last modifed time
+                       Assert.IsFalse (String.IsNullOrEmpty (monitor.UniqueId), "#A2-6");
+
+                       // There seems to be a bug in .NET 4.0 regarding the code below. MSDN says that non-existing keys will cause the
+                       // returned monitor instance to be marked as changed, but instead this exception is thrown:
+                       //
+                       // MonoTests.System.Runtime.Caching.MemoryCacheTest.CreateCacheEntryChangeMonitor:
+                       // System.ArgumentOutOfRangeException : The UTC time represented when the offset is applied must be between year 0 and 10,000.
+                       // Parameter name: offset
+                       // 
+                       // at System.DateTimeOffset.ValidateDate(DateTime dateTime, TimeSpan offset)
+                       // at System.DateTimeOffset..ctor(DateTime dateTime)
+                       // at System.Runtime.Caching.MemoryCacheEntryChangeMonitor.InitDisposableMembers(MemoryCache cache)
+                       // at System.Runtime.Caching.MemoryCache.CreateCacheEntryChangeMonitor(IEnumerable`1 keys, String regionName)
+                       // at MonoTests.Common.PokerMemoryCache.CreateCacheEntryChangeMonitor(IEnumerable`1 keys, String regionName) in C:\Users\grendel\documents\visual studio 2010\Projects\System.Runtime.Caching.Test\System.Runtime.Caching.Test\Common\PokerMemoryCache.cs:line 113
+                       // at MonoTests.System.Runtime.Caching.MemoryCacheTest.CreateCacheEntryChangeMonitor() in C:\Users\grendel\documents\visual studio 2010\Projects\System.Runtime.Caching.Test\System.Runtime.Caching.Test\System.Runtime.Caching\MemoryCacheTest.cs:line 275
+                       //
+                       // It's probably caused by the code passing a DateTime.MinValue to DateTimeOffset constructor for non-existing entries.
+                       // Until this (apparent) bug is fixed, Mono is going to implement the buggy behavior.
+                       //
+#if true
+                       AssertExtensions.Throws<ArgumentOutOfRangeException> (() => {
+                               monitor = mc.CreateCacheEntryChangeMonitor (new string [] { "key1", "doesnotexist" });
+                       }, "#A3");
+#else
+                       monitor = mc.CreateCacheEntryChangeMonitor (new string [] { "key1", "doesnotexist" });
+                       Assert.IsNotNull (monitor, "#A3-1");
+                       Assert.AreEqual ("System.Runtime.Caching.MemoryCacheEntryChangeMonitor", monitor.GetType ().ToString (), "#A3-2");
+                       Assert.AreEqual (1, monitor.CacheKeys.Count, "#A3-3");
+                       Assert.AreEqual ("key1", monitor.CacheKeys [0], "#A3-3-1");
+                       Assert.IsNull (monitor.RegionName, "#A3-4");
+                       Assert.IsTrue (monitor.HasChanged, "#A3-5");
+#endif
+               }
+
+               [Test]
+               public void AddOrGetExisting_String_Object_DateTimeOffset_String ()
+               {
+                       var mc = new PokerMemoryCache ("MyCache");
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               mc.AddOrGetExisting (null, "value", DateTimeOffset.Now);
+                       }, "#A1-1");
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               mc.AddOrGetExisting ("key", null, DateTimeOffset.Now);
+                       }, "#A1-2");
+                       
+                       AssertExtensions.Throws<NotSupportedException> (() => {
+                               mc.AddOrGetExisting ("key", "value", DateTimeOffset.Now, "region");
+                       }, "#A1-3");
+
+                       object value = mc.AddOrGetExisting ("key3_A2-1", "value", DateTimeOffset.Now.AddMinutes (1));
+                       Assert.IsTrue (mc.Contains ("key3_A2-1"), "#A2-1");
+                       Assert.IsNull (value, "#A2-2");
+
+                       mc.Calls.Clear ();
+                       value = mc.AddOrGetExisting ("key3_A2-1", "value2", DateTimeOffset.Now.AddMinutes (1));
+                       Assert.IsTrue (mc.Contains ("key3_A2-1"), "#A3-1");
+                       Assert.IsNotNull (value, "#A3-2");
+                       Assert.AreEqual ("value", value, "#A3-3");
+                       Assert.AreEqual (2, mc.Calls.Count, "#A3-4");
+                       Assert.AreEqual ("AddOrGetExisting (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)", mc.Calls [0], "#A3-5");
+
+                       value = mc.AddOrGetExisting ("key_expired", "value", DateTimeOffset.MinValue);
+                       Assert.IsFalse (mc.Contains ("key_expired"), "#A4-1");
+                       Assert.IsNull (value, "#A4-1");
+               }
+
+               [Test]
+               public void AddOrGetExisting_String_Object_CacheItemPolicy_String ()
+               {
+                       var mc = new PokerMemoryCache ("MyCache");
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               mc.AddOrGetExisting (null, "value", null);
+                       }, "#A1-1");
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               mc.AddOrGetExisting ("key", null, null);
+                       }, "#A1-2");
+
+                       var cip = new CacheItemPolicy ();
+                       cip.AbsoluteExpiration = DateTime.Now.AddMinutes (1);
+                       cip.SlidingExpiration = TimeSpan.FromMinutes (1);
+
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               mc.AddOrGetExisting ("key", "value", cip);
+                       }, "#A1-3");
+
+                       cip = new CacheItemPolicy ();
+                       cip.SlidingExpiration = TimeSpan.MinValue;
+                       AssertExtensions.Throws<ArgumentOutOfRangeException> (() => {
+                               mc.AddOrGetExisting ("key3", "value", cip);
+                       }, "#A1-4");
+
+                       AssertExtensions.Throws<NotSupportedException> (() => {
+                               mc.AddOrGetExisting ("key", "value", null, "region");
+                       }, "#A1-5");
+
+                       cip = new CacheItemPolicy ();
+                       cip.SlidingExpiration = TimeSpan.FromDays (500);
+                       AssertExtensions.Throws<ArgumentOutOfRangeException> (() => {
+                               mc.AddOrGetExisting ("key3", "value", cip);
+                       }, "#A1-6");
+
+                       cip = new CacheItemPolicy ();
+                       cip.Priority = (CacheItemPriority) 20;
+                       AssertExtensions.Throws<ArgumentOutOfRangeException> (() => {
+                               mc.AddOrGetExisting ("key3", "value", cip);
+                       }, "#A1-7");
+
+                       cip = new CacheItemPolicy ();
+                       cip.SlidingExpiration = TimeSpan.FromTicks (0L);
+                       mc.AddOrGetExisting ("key3_A2-1", "value", cip);
+                       Assert.IsTrue (mc.Contains ("key3_A2-1"), "#A2-1");
+
+                       cip = new CacheItemPolicy ();
+                       cip.SlidingExpiration = TimeSpan.FromDays (365);
+                       mc.AddOrGetExisting ("key3_A2-2", "value", cip);
+                       Assert.IsTrue (mc.Contains ("key3_A2-2"), "#A2-2");
+
+                       cip = new CacheItemPolicy ();
+                       cip.RemovedCallback = (CacheEntryRemovedArguments arguments) => { };
+                       object value = mc.AddOrGetExisting ("key3_A2-3", "value", cip);
+                       Assert.IsTrue (mc.Contains ("key3_A2-3"), "#A2-3");
+                       Assert.IsNull (value, "#A2-4");
+
+                       mc.Calls.Clear ();
+                       value = mc.AddOrGetExisting ("key3_A2-3", "value2", null);
+                       Assert.IsTrue (mc.Contains ("key3_A2-3"), "#A3-1");
+                       Assert.IsNotNull (value, "#A3-2");
+                       Assert.AreEqual ("value", value, "#A3-3");
+                       Assert.AreEqual (2, mc.Calls.Count, "#A3-4");
+                       Assert.AreEqual ("AddOrGetExisting (string key, object value, CacheItemPolicy policy, string regionName = null)", mc.Calls [0], "#A3-5");
+
+                       cip = new CacheItemPolicy ();
+                       cip.AbsoluteExpiration = DateTimeOffset.MinValue;
+                       value = mc.AddOrGetExisting ("key_expired", "value", cip);
+                       Assert.IsFalse (mc.Contains ("key_expired"), "#A4-1");
+                       Assert.IsNull (value, "#A4-1");
+               }
+
+               [Test]
+               public void AddOrGetExisting_CacheItem_CacheItemPolicy ()
+               {
+                       var mc = new PokerMemoryCache ("MyCache");
+                       CacheItem ci, ci2;
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               ci = mc.AddOrGetExisting (null, new CacheItemPolicy ());
+                       }, "#A1");
+
+                       ci = new CacheItem ("key", "value");
+                       ci2 = mc.AddOrGetExisting (ci, null);
+
+                       // LAMESPEC: MSDN says it should return null if the entry does not exist yet.
+                       //
+                       Assert.IsNotNull (ci2, "#A2-1"); 
+                       Assert.AreNotEqual (ci, ci2, "#A2-2");
+                       Assert.IsNull (ci2.Value, "#A2-3");
+                       Assert.IsTrue (mc.Contains (ci.Key), "#A2-4");
+                       Assert.AreEqual (ci.Key, ci2.Key, "#A2-5");
+
+                       ci = new CacheItem ("key", "value");
+                       ci2 = mc.AddOrGetExisting (ci, null);
+                       Assert.IsNotNull (ci2, "#A3-1");
+                       Assert.AreNotEqual (ci, ci2, "#A3-2");
+                       Assert.IsNotNull (ci2.Value, "#A3-3");
+                       Assert.AreEqual (ci.Value, ci2.Value, "#A3-4");
+                       Assert.AreEqual (ci.Key, ci2.Key, "#A3-5");
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               ci = new CacheItem (null, "value");
+                               ci2 = mc.AddOrGetExisting (ci, null);
+                       }, "#A4");
+
+                       ci = new CacheItem (String.Empty, "value");
+                       ci2 = mc.AddOrGetExisting (ci, null);
+                       Assert.IsNotNull (ci2, "#A5-1");
+                       Assert.AreNotEqual (ci, ci2, "#A5-2");
+                       Assert.IsNull (ci2.Value, "#A5-3");
+                       Assert.IsTrue (mc.Contains (ci.Key), "#A5-4");
+                       Assert.AreEqual (ci.Key, ci2.Key, "#A5-5");
+
+                       ci = new CacheItem ("key2", null);
+
+                       // Thrown from:
+                       // at System.Runtime.Caching.MemoryCacheEntry..ctor(String key, Object value, DateTimeOffset absExp, TimeSpan slidingExp, CacheItemPriority priority, Collection`1 dependencies, CacheEntryRemovedCallback removedCallback, MemoryCache cache)
+                       // at System.Runtime.Caching.MemoryCache.AddOrGetExistingInternal(String key, Object value, CacheItemPolicy policy)
+                       // at System.Runtime.Caching.MemoryCache.AddOrGetExisting(CacheItem item, CacheItemPolicy policy)
+                       // at MonoTests.System.Runtime.Caching.MemoryCacheTest.AddOrGetExisting_CacheItem_CacheItemPolicy() in C:\Users\grendel\documents\visual studio 2010\Projects\System.Runtime.Caching.Test\System.Runtime.Caching.Test\System.Runtime.Caching\MemoryCacheTest.cs:line 211
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               ci2 = mc.AddOrGetExisting (ci, null);
+                       }, "#B1");
+                       
+                       ci = new CacheItem ("key3", "value");
+                       var cip = new CacheItemPolicy ();
+                       cip.UpdateCallback = (CacheEntryUpdateArguments arguments) => { };
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               ci2 = mc.AddOrGetExisting (ci, cip);
+                       }, "#B2");
+
+                       ci = new CacheItem ("key3", "value");
+                       cip = new CacheItemPolicy ();
+                       cip.AbsoluteExpiration = DateTimeOffset.Now;
+                       cip.SlidingExpiration = TimeSpan.FromTicks (DateTime.Now.Ticks);
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               mc.AddOrGetExisting (ci, cip);
+                       }, "#B3");
+
+                       ci = new CacheItem ("key3", "value");
+                       cip = new CacheItemPolicy ();
+                       cip.SlidingExpiration = TimeSpan.MinValue;
+                       AssertExtensions.Throws<ArgumentOutOfRangeException> (() => {
+                               mc.AddOrGetExisting (ci, cip);
+                       }, "#B4-1");
+
+                       ci = new CacheItem ("key4_#B4-2", "value");
+                       cip = new CacheItemPolicy ();
+                       cip.SlidingExpiration = TimeSpan.FromTicks (0L);
+                       mc.AddOrGetExisting (ci, cip);
+                       Assert.IsTrue (mc.Contains ("key4_#B4-2"), "#B4-2");
+
+                       ci = new CacheItem ("key3", "value");
+                       cip = new CacheItemPolicy ();
+                       cip.SlidingExpiration = TimeSpan.FromDays (500);
+                       AssertExtensions.Throws<ArgumentOutOfRangeException> (() => {
+                               mc.AddOrGetExisting (ci, cip);
+                       }, "#B5-1");
+
+                       ci = new CacheItem ("key5_#B5-2", "value");
+                       cip = new CacheItemPolicy ();
+                       cip.SlidingExpiration = TimeSpan.FromDays (365);
+                       mc.AddOrGetExisting (ci, cip);
+                       Assert.IsTrue (mc.Contains ("key5_#B5-2"), "#B5-2");
+
+                       ci = new CacheItem ("key3", "value");
+                       cip = new CacheItemPolicy ();
+                       cip.Priority = (CacheItemPriority)20;
+                       AssertExtensions.Throws<ArgumentOutOfRangeException> (() => {
+                               mc.AddOrGetExisting (ci, cip);
+                       }, "#B6");
+
+                       ci = new CacheItem ("key3_B7", "value");
+                       cip = new CacheItemPolicy ();
+                       cip.RemovedCallback = (CacheEntryRemovedArguments arguments) => { };
+                       ci2 = mc.AddOrGetExisting (ci, cip);
+                       Assert.IsTrue (mc.Contains ("key3_B7"), "#B7");
+
+                       // LAMESPEC: MSDN says it should return null if the entry does not exist yet.
+                       //
+                       Assert.IsNotNull (ci2, "#C1-1");
+                       Assert.AreNotEqual (ci, ci2, "#C1-2");
+                       Assert.IsNull (ci2.Value, "#C1-3");
+                       Assert.IsTrue (mc.Contains (ci.Key), "#C1-4");
+                       Assert.AreEqual (ci.Key, ci2.Key, "#C1-5");
+
+                       // The entry is never inserted as its expiration date is before now
+                       ci = new CacheItem ("key_D1", "value_D1");
+                       cip = new CacheItemPolicy ();
+                       cip.AbsoluteExpiration = DateTimeOffset.MinValue;
+                       ci2 = mc.AddOrGetExisting (ci, cip);
+                       Assert.IsFalse (mc.Contains ("key_D1"), "#D1-1");
+                       Assert.IsNotNull (ci2, "#D1-2");
+                       Assert.IsNull (ci2.Value, "#D1-3");
+                       Assert.AreEqual ("key_D1", ci2.Key, "#D1-4");
+
+                       mc.Calls.Clear ();
+                       ci = new CacheItem ("key_D2", "value_D2");
+                       cip = new CacheItemPolicy ();
+                       cip.AbsoluteExpiration = DateTimeOffset.MaxValue;
+                       mc.AddOrGetExisting (ci, cip);
+                       Assert.IsTrue (mc.Contains ("key_D2"), "#D2-1");
+                       Assert.AreEqual (2, mc.Calls.Count, "#D2-2");
+                       Assert.AreEqual ("AddOrGetExisting (CacheItem item, CacheItemPolicy policy)", mc.Calls [0], "#D2-3");
+               }
+
+               [Test]
+               public void Set_String_Object_CacheItemPolicy_String ()
+               {
+                       var mc = new PokerMemoryCache ("MyCache");
+
+                       AssertExtensions.Throws<NotSupportedException> (() => {
+                               mc.Set ("key", "value", new CacheItemPolicy (), "region");
+                       }, "#A1-1");
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               mc.Set (null, "value", new CacheItemPolicy ());
+                       }, "#A1-2");
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               mc.Set ("key", null, new CacheItemPolicy ());
+                       }, "#A1-3");
+
+                       var cip = new CacheItemPolicy ();
+                       cip.UpdateCallback = (CacheEntryUpdateArguments arguments) => { };
+                       cip.RemovedCallback = (CacheEntryRemovedArguments arguments) => { };
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               mc.Set ("key", "value", cip);
+                       }, "#A1-4");
+
+                       cip = new CacheItemPolicy ();
+                       cip.SlidingExpiration = TimeSpan.MinValue;
+                       AssertExtensions.Throws<ArgumentOutOfRangeException> (() => {
+                               mc.Set ("key", "value", cip);
+                       }, "#A1-5");
+
+                       cip = new CacheItemPolicy ();
+                       cip.SlidingExpiration = TimeSpan.FromTicks (0L);
+                       mc.Set ("key_A1-6", "value", cip);
+                       Assert.IsTrue (mc.Contains ("key_A1-6"), "#A1-6");
+
+                       cip = new CacheItemPolicy ();
+                       cip.SlidingExpiration = TimeSpan.FromDays (500);
+                       AssertExtensions.Throws<ArgumentOutOfRangeException> (() => {
+                               mc.Set ("key", "value", cip);
+                       }, "#A1-7");
+                       
+                       cip = new CacheItemPolicy ();
+                       cip.SlidingExpiration = TimeSpan.FromDays (365);
+                       mc.Set ("key_A1-8", "value", cip);
+                       Assert.IsTrue (mc.Contains ("key_A1-8"), "#A1-8");
+
+                       cip = new CacheItemPolicy ();
+                       cip.Priority = (CacheItemPriority) 20;
+                       AssertExtensions.Throws<ArgumentOutOfRangeException> (() => {
+                               mc.Set ("key", "value", cip);
+                       }, "#A1-9");
+                       
+                       cip = new CacheItemPolicy ();
+                       cip.RemovedCallback = (CacheEntryRemovedArguments arguments) => { };
+                       mc.Set ("key_A2", "value_A2", cip);
+                       Assert.IsTrue (mc.Contains ("key_A2"), "#A2");
+
+                       mc.Set ("key_A3", "value_A3", new CacheItemPolicy ());
+                       Assert.IsTrue (mc.Contains ("key_A3"), "#A3-1");
+                       Assert.AreEqual ("value_A3", mc.Get ("key_A3"), "#A3-2");
+
+                       // The entry is never inserted as its expiration date is before now
+                       cip = new CacheItemPolicy ();
+                       cip.AbsoluteExpiration = DateTimeOffset.MinValue;
+                       mc.Set ("key_A4", "value_A4", cip);
+                       Assert.IsFalse (mc.Contains ("key_A4"), "#A4");
+
+                       mc.Calls.Clear ();
+                       cip = new CacheItemPolicy ();
+                       cip.AbsoluteExpiration = DateTimeOffset.MaxValue;
+                       mc.Set ("key_A5", "value_A5", cip);
+                       Assert.IsTrue (mc.Contains ("key_A5"), "#A5-1");
+                       Assert.AreEqual (2, mc.Calls.Count, "#A5-2");
+                       Assert.AreEqual ("Set (string key, object value, CacheItemPolicy policy, string regionName = null)", mc.Calls [0], "#A5-3");
+               }
+
+               [Test]
+               public void Set_String_Object_DateTimeOffset_String ()
+               {
+                       var mc = new PokerMemoryCache ("MyCache");
+
+                       AssertExtensions.Throws<NotSupportedException> (() => {
+                               mc.Set ("key", "value", DateTimeOffset.MaxValue, "region");
+                       }, "#A1-1");
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               mc.Set (null, "value", DateTimeOffset.MaxValue);
+                       }, "#A1-2");
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               mc.Set ("key", null, DateTimeOffset.MaxValue);
+                       }, "#A1-3");
+                       
+                       // The entry is never inserted as its expiration date is before now
+                       mc.Set ("key_A2", "value_A2", DateTimeOffset.MinValue);
+                       Assert.IsFalse (mc.Contains ("key_A2"), "#A2");
+
+                       mc.Calls.Clear ();
+                       mc.Set ("key", "value", DateTimeOffset.MaxValue);
+
+                       Assert.AreEqual (2, mc.Calls.Count, "#A2-1");
+                       Assert.AreEqual ("Set (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)", mc.Calls [0], "#A2-2");
+                       Assert.AreEqual ("Set (string key, object value, CacheItemPolicy policy, string regionName = null)", mc.Calls [1], "#A2-3");
+               }
+
+               [Test]
+               public void Set_CacheItem_CacheItemPolicy ()
+               {
+                       var mc = new PokerMemoryCache ("MyCache");
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               mc.Set (null, new CacheItemPolicy ());
+                       }, "#A1-1");
+
+                       // Actually thrown from the Set (string, object, CacheItemPolicy, string) overload
+                       var ci = new CacheItem (null, "value");
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               mc.Set (ci, new CacheItemPolicy ());
+                       }, "#A1-2");
+
+                       ci = new CacheItem ("key", null);
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               mc.Set (ci, new CacheItemPolicy ());
+                       }, "#A1-3");
+
+                       ci = new CacheItem ("key", "value");
+                       var cip = new CacheItemPolicy ();
+                       cip.UpdateCallback = (CacheEntryUpdateArguments arguments) => { };
+                       cip.RemovedCallback = (CacheEntryRemovedArguments arguments) => { };
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               mc.Set (ci, cip);
+                       }, "#A1-4");
+
+                       ci = new CacheItem ("key", "value");
+                       cip = new CacheItemPolicy ();
+                       cip.SlidingExpiration = TimeSpan.MinValue;
+                       AssertExtensions.Throws<ArgumentOutOfRangeException> (() => {
+                               mc.Set (ci, cip);
+                       }, "#A1-5");
+
+                       ci = new CacheItem ("key_A1-6", "value");
+                       cip = new CacheItemPolicy ();
+                       cip.SlidingExpiration = TimeSpan.FromTicks (0L);
+                       mc.Set (ci, cip);
+                       Assert.IsTrue (mc.Contains ("key_A1-6"), "#A1-6");
+
+                       ci = new CacheItem ("key", "value");
+                       cip = new CacheItemPolicy ();
+                       cip.SlidingExpiration = TimeSpan.FromDays (500);
+                       AssertExtensions.Throws<ArgumentOutOfRangeException> (() => {
+                               mc.Set (ci, cip);
+                       }, "#A1-7");
+
+                       ci = new CacheItem ("key_A1-8", "value");
+                       cip = new CacheItemPolicy ();
+                       cip.SlidingExpiration = TimeSpan.FromDays (365);
+                       mc.Set (ci, cip);
+                       Assert.IsTrue (mc.Contains ("key_A1-8"), "#A1-8");
+
+                       ci = new CacheItem ("key", "value");
+                       cip = new CacheItemPolicy ();
+                       cip.Priority = (CacheItemPriority) 20;
+                       AssertExtensions.Throws<ArgumentOutOfRangeException> (() => {
+                               mc.Set (ci, cip);
+                       }, "#A1-9");
+
+                       ci = new CacheItem ("key_A2", "value_A2");
+                       cip = new CacheItemPolicy ();
+                       cip.RemovedCallback = (CacheEntryRemovedArguments arguments) => { };
+                       mc.Set (ci, cip);
+                       Assert.IsTrue (mc.Contains ("key_A2"), "#A2");
+
+                       ci = new CacheItem ("key_A3", "value_A3");
+                       mc.Set (ci, new CacheItemPolicy ());
+                       Assert.IsTrue (mc.Contains ("key_A3"), "#A3-1");
+                       Assert.AreEqual ("value_A3", mc.Get ("key_A3"), "#A3-2");
+
+                       // The entry is never inserted as its expiration date is before now
+                       ci = new CacheItem ("key_A4", "value");
+                       cip = new CacheItemPolicy ();
+                       cip.AbsoluteExpiration = DateTimeOffset.MinValue;
+                       mc.Set (ci, cip);
+                       Assert.IsFalse (mc.Contains ("key_A4"), "#A4");
+
+                       ci = new CacheItem ("key_A5", "value");
+                       mc.Calls.Clear ();
+                       mc.Set (ci, new CacheItemPolicy ());
+
+                       Assert.AreEqual (2, mc.Calls.Count, "#A5-1");
+                       Assert.AreEqual ("Set (CacheItem item, CacheItemPolicy policy)", mc.Calls [0], "#A5-2");
+                       Assert.AreEqual ("Set (string key, object value, CacheItemPolicy policy, string regionName = null)", mc.Calls [1], "#A5-3");
+               }
+
+               [Test]
+               public void Remove ()
+               {
+                       var mc = new PokerMemoryCache ("MyCache");
+               
+                       AssertExtensions.Throws<NotSupportedException> (() => {
+                               mc.Remove ("key", "region");
+                       }, "#A1-1");
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               mc.Remove (null);
+                       }, "#A1-2");
+
+                       bool callbackInvoked;
+                       CacheEntryRemovedReason reason = (CacheEntryRemovedReason) 1000;
+                       var cip = new CacheItemPolicy ();
+                       cip.Priority = CacheItemPriority.NotRemovable;
+                       mc.Set ("key2", "value1", cip);
+                       object value = mc.Remove ("key2");
+
+                       Assert.IsNotNull (value, "#B1-1");
+                       Assert.IsFalse (mc.Contains ("key2"), "#B1-2");
+
+                       cip = new CacheItemPolicy ();
+                       cip.RemovedCallback = (CacheEntryRemovedArguments args) => {
+                               callbackInvoked = true;
+                               reason = args.RemovedReason;
+                       };
+
+                       mc.Set ("key", "value", cip);
+                       callbackInvoked = false;
+                       reason = (CacheEntryRemovedReason) 1000;
+                       value = mc.Remove ("key");
+                       Assert.IsNotNull (value, "#C1-1");
+                       Assert.IsTrue (callbackInvoked, "#C1-2");
+                       Assert.AreEqual (CacheEntryRemovedReason.Removed, reason, "#C1-3");
+
+                       cip = new CacheItemPolicy ();
+                       cip.RemovedCallback = (CacheEntryRemovedArguments args) => {
+                               callbackInvoked = true;
+                               reason = args.RemovedReason;
+                               throw new ApplicationException ("test");
+                       };
+
+                       mc.Set ("key", "value", cip);
+                       callbackInvoked = false;
+                       reason = (CacheEntryRemovedReason) 1000;
+                       value = mc.Remove ("key");
+                       Assert.IsNotNull (value, "#C2-1");
+                       Assert.IsTrue (callbackInvoked, "#C2-2");
+                       Assert.AreEqual (CacheEntryRemovedReason.Removed, reason, "#C2-3");
+
+                       // LAMESPEC: UpdateCallback is not called on remove
+                       cip = new CacheItemPolicy ();
+                       cip.UpdateCallback = (CacheEntryUpdateArguments args) => {
+                               callbackInvoked = true;
+                               reason = args.RemovedReason;
+                       };
+
+                       mc.Set ("key", "value", cip);
+                       callbackInvoked = false;
+                       reason = (CacheEntryRemovedReason) 1000;
+                       value = mc.Remove ("key");
+                       Assert.IsNotNull (value, "#D1-1");
+                       Assert.IsFalse (callbackInvoked, "#D1-2");
+
+                       cip = new CacheItemPolicy ();
+                       cip.UpdateCallback = (CacheEntryUpdateArguments args) => {
+                               callbackInvoked = true;
+                               reason = args.RemovedReason;
+                               throw new ApplicationException ("test");
+                       };
+
+                       mc.Set ("key", "value", cip);
+                       callbackInvoked = false;
+                       reason = (CacheEntryRemovedReason) 1000;
+                       value = mc.Remove ("key");
+                       Assert.IsNotNull (value, "#D2-1");
+                       Assert.IsFalse (callbackInvoked, "#D2-2");
+               }
+
+               [Test]
+               public void TimedExpiration ()
+               {
+                       bool expired = false;
+                       CacheEntryRemovedReason reason = CacheEntryRemovedReason.CacheSpecificEviction;
+                       NameValueCollection config;
+                       int sleepPeriod;
+#if !DOTNET
+                       config = new NameValueCollection ();
+                       config.Add ("__MonoTimerPeriod", "1");
+                       sleepPeriod = 1100;
+#else
+                       config = null;
+                       sleepPeriod = 20100; // 20s is the .NET period - discovered by experimentation
+#endif
+                       var mc = new PokerMemoryCache ("MyCache", config);
+                       var cip = new CacheItemPolicy ();
+
+                       cip.RemovedCallback = (CacheEntryRemovedArguments args) => {
+                               expired = true;
+                               reason = args.RemovedReason;
+                       };
+                       cip.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds (50);
+                       mc.Set ("key", "value", cip);
+                       Thread.Sleep (100);
+
+                       Assert.IsFalse (expired, "#A1");
+                       object value = mc.Get ("key");
+
+                       Assert.IsNull (value, "#A2-1");
+                       Assert.IsTrue (expired, "#A2-2");
+                       Assert.AreEqual (CacheEntryRemovedReason.Expired, reason, "A2-3");
+
+                       expired = false;
+                       cip = new CacheItemPolicy ();
+                       cip.RemovedCallback = (CacheEntryRemovedArguments args) => {
+                               expired = true;
+                               reason = args.RemovedReason;
+                       };
+                       cip.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds (50);
+                       mc.Set ("key", "value", cip);
+                       Thread.Sleep (sleepPeriod);
+
+                       Assert.IsTrue (expired, "#A3-1");
+                       Assert.AreEqual (CacheEntryRemovedReason.Expired, reason, "#A3-2");
+
+                       int expiredCount = 0;
+                       object expiredCountLock = new object ();
+                       CacheEntryRemovedCallback removedCb = (CacheEntryRemovedArguments args) => {
+                               lock (expiredCountLock) {
+                                       expiredCount++;
+                               }
+                       };
+
+                       cip = new CacheItemPolicy ();
+                       cip.RemovedCallback = removedCb;
+                       cip.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds (20);
+                       mc.Set ("key1", "value1", cip);
+
+                       cip = new CacheItemPolicy ();
+                       cip.RemovedCallback = removedCb;
+                       cip.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds (200);
+                       mc.Set ("key2", "value2", cip);
+
+                       cip = new CacheItemPolicy ();
+                       cip.RemovedCallback = removedCb;
+                       cip.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds (600);
+                       mc.Set ("key3", "value3", cip);
+
+                       cip = new CacheItemPolicy ();
+                       cip.RemovedCallback = removedCb;
+                       cip.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds (sleepPeriod + 100);
+                       mc.Set ("key4", "value4", cip);
+                       
+                       Thread.Sleep (sleepPeriod);
+                       Assert.AreEqual (3, expiredCount, "#A4");
+               }
+
+               [Test]
+               public void GetEnumerator ()
+               {
+                       var mc = new PokerMemoryCache ("MyCache");
+
+                       // This one is a Hashtable enumerator
+                       IEnumerator enumerator = ((IEnumerable) mc).GetEnumerator ();
+
+                       // This one is a Dictionary <string, object> enumerator
+                       IEnumerator enumerator2 = mc.DoGetEnumerator ();
+
+                       Assert.IsNotNull (enumerator, "#A1-1");
+                       Assert.IsNotNull (enumerator2, "#A1-2");
+                       Assert.IsTrue (enumerator.GetType () != enumerator2.GetType (), "#A1-3");
+
+                       mc.Set ("key1", "value1", null);
+                       mc.Set ("key2", "value2", null);
+                       mc.Set ("key3", "value3", null);
+
+                       bool expired = false;
+                       var cip = new CacheItemPolicy ();
+                       cip.AbsoluteExpiration = DateTime.Now.AddMilliseconds (50);
+                       cip.RemovedCallback = (CacheEntryRemovedArguments args) => {
+                               expired = true;
+                       };
+
+                       mc.Set ("key4", "value4", cip);
+                       Thread.Sleep (100);
+
+                       enumerator = ((IEnumerable) mc).GetEnumerator ();
+                       int count = 0;
+                       while (enumerator.MoveNext ()) {
+                               count++;
+                       }
+
+                       Assert.IsFalse (expired, "#A2-1");
+                       Assert.AreEqual (3, count, "#A2-2");
+
+                       expired = false;
+                       cip = new CacheItemPolicy ();
+                       cip.AbsoluteExpiration = DateTime.Now.AddMilliseconds (50);
+                       cip.RemovedCallback = (CacheEntryRemovedArguments args) => {
+                               expired = true;
+                       };
+
+                       mc.Set ("key5", "value5", cip);
+                       Thread.Sleep (100);
+
+                       enumerator2 = mc.DoGetEnumerator ();
+                       count = 0;
+                       while (enumerator2.MoveNext ()) {
+                               count++;
+                       }
+
+                       Assert.IsFalse (expired, "#A3-1");
+                       Assert.AreEqual (3, count, "#A3-2");
+               }
+
+               [Test]
+               public void GetValues ()
+               {
+                       var mc = new PokerMemoryCache ("MyCache");
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               mc.GetValues (null);
+                       }, "#A1-1");
+
+                       AssertExtensions.Throws<NotSupportedException> (() => {
+                               mc.GetValues (new string[] {}, "region");
+                       }, "#A1-2");
+
+                       AssertExtensions.Throws<ArgumentException> (() => {
+                               mc.GetValues (new string [] { "key", null });
+                       }, "#A1-3");
+
+                       IDictionary<string, object> value = mc.GetValues (new string[] {});
+                       Assert.IsNull (value, "#A2");
+
+                       mc.Set ("key1", "value1", null);
+                       mc.Set ("key2", "value2", null);
+                       mc.Set ("key3", "value3", null);
+
+                       Assert.IsTrue (mc.Contains ("key1"), "#A3-1");
+                       Assert.IsTrue (mc.Contains ("key2"), "#A3-2");
+                       Assert.IsTrue (mc.Contains ("key3"), "#A3-2");
+
+                       value = mc.GetValues (new string [] { "key1", "key3" });
+                       Assert.IsNotNull (value, "#A4-1");
+                       Assert.AreEqual (2, value.Count, "#A4-2");
+                       Assert.AreEqual ("value1", value ["key1"], "#A4-3");
+                       Assert.AreEqual ("value3", value ["key3"], "#A4-4");
+                       Assert.AreEqual (typeof (Dictionary<string, object>), value.GetType (), "#A4-5");
+
+                       // LAMESPEC: MSDN says the number of items in the returned dictionary should be the same as in the 
+                       // 'keys' collection - this is not the case. The returned dictionary contains only entries for keys
+                       // that exist in the cache.
+                       value = mc.GetValues (new string [] { "key1", "key3", "nosuchkey" });
+                       Assert.IsNotNull (value, "#A5-1");
+                       Assert.AreEqual (2, value.Count, "#A5-2");
+                       Assert.AreEqual ("value1", value ["key1"], "#A5-3");
+                       Assert.AreEqual ("value3", value ["key3"], "#A5-4");
+                       Assert.IsFalse (value.ContainsKey ("Key1"), "#A5-5");
+               }
+
+               [Test]
+               public void Get ()
+               {
+                       var mc = new PokerMemoryCache ("MyCache");
+
+                       AssertExtensions.Throws<NotSupportedException> (() => {
+                               mc.Get ("key", "region");
+                       }, "#A1-1");
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               mc.Get (null);
+                       }, "#A1-2");
+
+                       object value;
+                       mc.Set ("key", "value", null);
+                       value = mc.Get ("key");
+                       Assert.IsNotNull (value, "#A2-1");
+                       Assert.AreEqual ("value", value, "#A2-2");
+
+                       value = mc.Get ("nosuchkey");
+                       Assert.IsNull (value, "#A3");
+
+                       var cip = new CacheItemPolicy ();
+                       bool callbackInvoked;
+                       CacheEntryRemovedReason reason = (CacheEntryRemovedReason)1000;
+
+                       cip.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds (50);
+                       cip.RemovedCallback = (CacheEntryRemovedArguments args) => {
+                               callbackInvoked = true;
+                               reason = args.RemovedReason;
+                       };
+                       mc.Set ("key", "value", cip);
+                       Thread.Sleep (500);
+
+                       callbackInvoked = false;
+                       reason = (CacheEntryRemovedReason) 1000;
+                       value = mc.Get ("key");
+                       Assert.IsNull (value, "#B1-1");
+                       Assert.IsTrue (callbackInvoked, "#B1-2");
+                       Assert.AreEqual (CacheEntryRemovedReason.Expired, reason, "#B1-3");
+
+                       cip = new CacheItemPolicy ();
+                       cip.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds (50);
+                       cip.RemovedCallback = (CacheEntryRemovedArguments args) => {
+                               callbackInvoked = true;
+                               reason = args.RemovedReason;
+                               throw new ApplicationException ("test");
+                       };
+
+                       mc.Set ("key", "value", cip);
+                       Thread.Sleep (500);
+
+                       callbackInvoked = false;
+                       reason = (CacheEntryRemovedReason) 1000;
+                       value = mc.Get ("key");
+                       Assert.IsNull (value, "#B2-1");
+                       Assert.IsTrue (callbackInvoked, "#B2-2");
+                       Assert.AreEqual (CacheEntryRemovedReason.Expired, reason, "#B2-3");
+               }
+
+               [Test]
+               public void GetCacheItem ()
+               {
+                       var mc = new PokerMemoryCache ("MyCache");
+
+                       AssertExtensions.Throws<NotSupportedException> (() => {
+                               mc.GetCacheItem ("key", "region");
+                       }, "#A1-1");
+
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               mc.GetCacheItem (null);
+                       }, "#A1-2");
+
+                       CacheItem value;
+                       mc.Set ("key", "value", null);
+                       value = mc.GetCacheItem ("key");
+                       Assert.IsNotNull (value, "#A2-1");
+                       Assert.AreEqual ("value", value.Value, "#A2-2");
+                       Assert.AreEqual ("key", value.Key, "#A2-3");
+
+                       value = mc.GetCacheItem ("doesnotexist");
+                       Assert.IsNull (value, "#A3");
+
+                       var cip = new CacheItemPolicy ();
+                       bool callbackInvoked;
+                       CacheEntryRemovedReason reason = (CacheEntryRemovedReason) 1000;
+
+                       cip.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds (50);
+                       cip.RemovedCallback = (CacheEntryRemovedArguments args) => {
+                               callbackInvoked = true;
+                               reason = args.RemovedReason;
+                       };
+                       mc.Set ("key", "value", cip);
+                       Thread.Sleep (500);
+
+                       callbackInvoked = false;
+                       reason = (CacheEntryRemovedReason) 1000;
+                       value = mc.GetCacheItem ("key");
+                       Assert.IsNull (value, "#B1-1");
+                       Assert.IsTrue (callbackInvoked, "#B1-2");
+                       Assert.AreEqual (CacheEntryRemovedReason.Expired, reason, "#B1-3");
+
+                       cip = new CacheItemPolicy ();
+                       cip.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds (50);
+                       cip.RemovedCallback = (CacheEntryRemovedArguments args) => {
+                               callbackInvoked = true;
+                               reason = args.RemovedReason;
+                               throw new ApplicationException ("test");
+                       };
+
+                       mc.Set ("key", "value", cip);
+                       Thread.Sleep (500);
+
+                       callbackInvoked = false;
+                       reason = (CacheEntryRemovedReason) 1000;
+                       value = mc.GetCacheItem ("key");
+                       Assert.IsNull (value, "#B2-1");
+                       Assert.IsTrue (callbackInvoked, "#B2-2");
+                       Assert.AreEqual (CacheEntryRemovedReason.Expired, reason, "#B2-3");
+               }
+
+               [Test]
+               public void ChangeMonitors ()
+               {
+                       bool removed = false;
+                       var mc = new PokerMemoryCache ("MyCache");
+                       var cip = new CacheItemPolicy ();
+                       var monitor = new PokerChangeMonitor ();
+                       cip.ChangeMonitors.Add (monitor);
+                       cip.RemovedCallback = (CacheEntryRemovedArguments args) => {
+                               removed = true;
+                       };
+
+                       mc.Set ("key", "value", cip);
+                       Assert.AreEqual (0, monitor.Calls.Count, "#A1");
+
+                       monitor.SignalChange ();
+                       Assert.IsTrue (removed, "#A2");
+
+                       bool onChangedCalled = false;
+                       monitor = new PokerChangeMonitor ();
+                       monitor.NotifyOnChanged ((object state) => {
+                               onChangedCalled = true;
+                       });
+
+                       cip = new CacheItemPolicy ();
+                       cip.ChangeMonitors.Add (monitor);
+
+                       // Thrown by ChangeMonitor.NotifyOnChanged
+                       AssertExtensions.Throws<InvalidOperationException> (() => {
+                               mc.Set ("key1", "value1", cip);
+                       }, "#A3");
+               }
+
+               // NOTE: on Windows with 2 or more CPUs this test will most probably fail.
+               [Test]
+               public void Trim ()
+               {
+                       var config = new NameValueCollection ();
+                       config ["__MonoEmulateOneCPU"] = "true";
+                       var mc = new MemoryCache ("MyCache", config);
+
+                       for (int i = 0; i < 10; i++)
+                               mc.Set ("key" + i.ToString (), "value" + i.ToString (), null);
+
+                       // .NET doesn't touch the freshest 10 entries
+                       Assert.AreEqual (10, mc.GetCount (), "#A1-1");
+                       long trimmed = mc.Trim (50);
+                       Assert.AreEqual (0, trimmed, "#A1-2");
+                       Assert.AreEqual (10, mc.GetCount (), "#A1-3");
+
+                       mc = new MemoryCache ("MyCache", config);
+                       // Only entries 11- are considered for removal
+                       for (int i = 0; i < 11; i++)
+                               mc.Set ("key" + i.ToString (), "value" + i.ToString (), null);
+
+                       Assert.AreEqual (11, mc.GetCount (), "#A2-1");
+                       trimmed = mc.Trim (50);
+                       Assert.AreEqual (1, trimmed, "#A2-2");
+                       Assert.AreEqual (10, mc.GetCount (), "#A2-3");
+
+                       mc = new MemoryCache ("MyCache", config);
+                       // Only entries 11- are considered for removal
+                       for (int i = 0; i < 125; i++)
+                               mc.Set ("key" + i.ToString (), "value" + i.ToString (), null);
+
+                       Assert.AreEqual (125, mc.GetCount (), "#A3-1");
+                       trimmed = mc.Trim (50);
+                       Assert.AreEqual (62, trimmed, "#A3-2");
+                       Assert.AreEqual (63, mc.GetCount (), "#A3-3");
+
+                       // Testing the removal order
+                       mc = new MemoryCache ("MyCache", config);
+                       var removed = new List <string> ();
+                       var cip = new CacheItemPolicy ();
+                       cip.RemovedCallback = (CacheEntryRemovedArguments args) => {
+                               removed.Add (args.CacheItem.Key);
+                       };
+
+                       for (int i = 0; i < 50; i++)
+                               mc.Set ("key" + i.ToString (), "value" + i.ToString (), cip);
+
+                       object value;
+                       for (int i = 0; i < 50; i++)
+                               value = mc.Get ("key" + i.ToString ());
+
+                       trimmed = mc.Trim (50);
+                       Assert.AreEqual (25, mc.GetCount (), "#A4-1");
+                       Assert.AreEqual (25, trimmed, "#A4-2");
+                       Assert.AreEqual (25, removed.Count, "#A4-3");
+
+                       // OK, this is odd... The list is correct in terms of entries removed but the entries
+                       // are removed in the _MOST_ frequently used order, within the group selected for removal.
+                       for (int i = 24; i >= 0; i--) {
+                               int idx = 24 - i;
+                               Assert.AreEqual ("key" + i.ToString (), removed [idx], "#A5-" + idx.ToString ());
+                       }
+               }
+       }
+}
diff --git a/mcs/class/System.Runtime.Caching/Test/System.Runtime.Caching/ObjectCacheTest.cs b/mcs/class/System.Runtime.Caching/Test/System.Runtime.Caching/ObjectCacheTest.cs
new file mode 100644 (file)
index 0000000..e5eefb7
--- /dev/null
@@ -0,0 +1,159 @@
+//
+// ObjectCacheTest.cs
+//
+// Authors:
+//      Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Runtime.Caching;
+
+using NUnit.Framework;
+using MonoTests.Common;
+
+namespace MonoTests.System.Runtime.Caching
+{
+       [TestFixture]
+       public class ObjectCacheTest
+       {
+               [Test]
+               public void Host ()
+               {
+                       Assert.IsTrue (ObjectCache.Host == null, "#A1");
+
+                       AppDomainTools.RunInSeparateDomain (Host_SetToNull, "Host_SetToNull");
+                       AppDomainTools.RunInSeparateDomain (Host_SetToProvider, "Host_SetToProvider");
+               }
+
+               static void Host_SetToNull ()
+               {
+                       AssertExtensions.Throws<ArgumentNullException> (() => {
+                               ObjectCache.Host = null;
+                       }, "#A2");
+               }
+
+               static void Host_SetToProvider ()
+               {
+                       var tns1 = new TestNotificationSystem ();
+                       var tns2 = new TestNotificationSystem ();
+                       ObjectCache.Host = tns1;
+                       Assert.IsNotNull (ObjectCache.Host, "#A3-1");
+                       Assert.AreEqual (tns1, ObjectCache.Host, "#A3-2");
+
+                       AssertExtensions.Throws<InvalidOperationException> (() => {
+                               ObjectCache.Host = tns2;
+                       }, "#A4");
+               }
+
+               [Test]
+               public void Add_CacheItem_CacheItemPolicy ()
+               {
+                       var poker = new PokerObjectCache ();
+                       bool ret;
+
+                       ret = poker.Add (null, null);
+                       Assert.IsTrue (ret, "#A1-1");
+                       Assert.AreEqual ("AddOrGetExisting (CacheItem value, CacheItemPolicy policy)", poker.MethodCalled, "#A1-2");
+
+                       var item = new CacheItem ("key", 1234);
+                       ret = poker.Add (item, null);
+                       Assert.IsTrue (ret, "#A2-1");
+                       Assert.AreEqual ("AddOrGetExisting (CacheItem value, CacheItemPolicy policy)", poker.MethodCalled, "#A2-2");
+
+                       ret = poker.Add (item, null);
+                       Assert.IsFalse (ret, "#A3-1");
+                       Assert.AreEqual ("AddOrGetExisting (CacheItem value, CacheItemPolicy policy)", poker.MethodCalled, "#A3-2");
+               }
+
+               [Test]
+               public void Add_String_Object_CacheItemPolicy_String ()
+               {
+                       var poker = new PokerObjectCache ();
+                       bool ret;
+
+                       ret = poker.Add (null, null, null, null);
+                       Assert.IsTrue (ret, "#A1-1");
+                       Assert.AreEqual ("AddOrGetExisting (string key, object value, CacheItemPolicy policy, string regionName = null)", poker.MethodCalled, "#A1-2");
+
+                       ret = poker.Add ("key", 1234, null, null);
+                       Assert.IsTrue (ret, "#A2-1");
+                       Assert.AreEqual ("AddOrGetExisting (string key, object value, CacheItemPolicy policy, string regionName = null)", poker.MethodCalled, "#A2-2");
+
+                       ret = poker.Add ("key", 1234, null, null);
+                       Assert.IsFalse (ret, "#A2-1");
+                       Assert.AreEqual ("AddOrGetExisting (string key, object value, CacheItemPolicy policy, string regionName = null)", poker.MethodCalled, "#A2-2");
+               }
+
+               [Test]
+               public void Add_String_Object_DateTimeOffset_String ()
+               {
+                       var poker = new PokerObjectCache ();
+                       bool ret;
+
+                       ret = poker.Add (null, null, DateTimeOffset.Now, null);
+                       Assert.IsTrue (ret, "#A1-1");
+                       Assert.AreEqual ("AddOrGetExisting (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)", poker.MethodCalled, "#A1-2");
+
+                       ret = poker.Add ("key", 1234, DateTimeOffset.Now, null);
+                       Assert.IsTrue (ret, "#A2-1");
+                       Assert.AreEqual ("AddOrGetExisting (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)", poker.MethodCalled, "#A2-2");
+
+                       ret = poker.Add ("key", 1234, DateTimeOffset.Now, null);
+                       Assert.IsFalse (ret, "#A2-1");
+                       Assert.AreEqual ("AddOrGetExisting (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)", poker.MethodCalled, "#A2-2");
+               }
+
+               [Test]
+               public void GetValues ()
+               {
+                       var poker = new PokerObjectCache ();
+
+                       IDictionary<string, object> values = poker.GetValues (null, (string []) null);
+                       Assert.IsNotNull (values, "#A1-1");
+                       Assert.AreEqual (0, values.Count, "#A1-2");
+                       Assert.AreEqual ("IDictionary<string, object> GetValues (IEnumerable<string> keys, string regionName = null)", poker.MethodCalled, "#A1-3");
+
+                       poker.Add ("key1", 1, null);
+                       poker.Add ("key2", 2, null);
+                       poker.Add ("key3", 3, null);
+
+                       values = poker.GetValues (new string [] { "key1", "key2", "key3" });
+                       Assert.IsNotNull (values, "#A2-1");
+                       Assert.AreEqual (3, values.Count, "#A2-2");
+                       Assert.AreEqual ("IDictionary<string, object> GetValues (IEnumerable<string> keys, string regionName = null)", poker.MethodCalled, "#A2-3");
+
+                       values = poker.GetValues (new string [] { "key1", "key22", "key3" });
+                       Assert.IsNotNull (values, "#A3-1");
+                       Assert.AreEqual (2, values.Count, "#A3-2");
+                       Assert.AreEqual ("IDictionary<string, object> GetValues (IEnumerable<string> keys, string regionName = null)", poker.MethodCalled, "#A3-3");
+               }
+
+               [Test]
+               public void Defaults ()
+               {
+                       Assert.AreEqual (DateTimeOffset.MaxValue, ObjectCache.InfiniteAbsoluteExpiration, "#A1");
+                       Assert.AreEqual (TimeSpan.Zero, ObjectCache.NoSlidingExpiration, "#A2");
+               }
+       }
+}
index 701f3bbfe19306382fb668d515d694bd157ac183..06bfd0b1de35d46755d21806e1bd8a69cf1e9441 100644 (file)
@@ -1,3 +1,7 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * net_2_1_*.dll.sources: rename to moonlight_*.dll.sources.
+
 2010-03-03  Atsushi Enomoto  <atsushi@ximian.com>
 
        * System.Runtime.Serialization.dll.sources:
index 497a7fb3b9d81b24481a65c2b6771d9f4e5f2cd0..7f4f2d8e3a044823ffe012930b93d363057867a0 100755 (executable)
@@ -1,3 +1,23 @@
+2010-04-05  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * DataContractExporter-new.cs : do not expect contract attribute on
+         dictionary map. Non-contract type also uses this.
+
+2010-04-05  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * SerializationMap.XsdExporter.cs, DataContractExporter-new.cs :
+         handle schema export for SharedTypeMap.
+
+2010-04-05  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * KnownTypeCollection.cs, SerializationMap.cs : split SharedTypeMap
+         .ctor() and initialization. Fixed infinite loop for some
+         [Serializable] types (such as Assembly).
+
+2010-04-02  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * DataContractSerializer : implement IsStartObject().
+
 2010-03-12  Atsushi Enomoto  <atsushi@ximian.com>
 
        * KnownTypeCollection.cs, SerializationMap.cs :
index aa34575839f0779925ba3fe07d9615e04719d853..44ab29d185956a975080389b768dceec13228a0b 100644 (file)
@@ -237,10 +237,12 @@ namespace System.Runtime.Serialization
                        get { return preserve_refs; }
                }
 
-               [MonoTODO]
                public override bool IsStartObject (XmlDictionaryReader reader)
                {
-                       throw new NotImplementedException ();
+                       if (reader == null)
+                               throw new ArgumentNullException ("reader");
+                       reader.MoveToContent ();
+                       return reader.IsStartElement (root_name, root_ns);
                }
 
                // SP1
index 037615f7e6eb99af3f49041a7d49be0dcc131cb5..62ace1948be4ee6dd1d749b8232b2f0627d93490 100644 (file)
@@ -722,9 +722,9 @@ namespace System.Runtime.Serialization
                        if (FindUserMap (qname) != null)
                                throw new InvalidOperationException (String.Format ("There is already a registered type for XML name {0}", qname));
 
-                       SharedTypeMap ret =
-                               new SharedTypeMap (type, qname, this);
+                       SharedTypeMap ret = new SharedTypeMap (type, qname, this);
                        contracts.Add (ret);
+                       ret.Initialize ();
                        return ret;
                }
 
index 4d7988d21d2927f3575ba6dff24f6a580be51738..ce950f0b1e0d0f9af2b1fb2a9e0646d980790e8b 100644 (file)
@@ -62,7 +62,7 @@ namespace System.Runtime.Serialization
        {
                public override void ExportSchemaType (XsdDataContractExporter exporter)
                {
-                       exporter.ExportStandardComplexType (RuntimeType.GetCustomAttribute<DataContractAttribute> (false), RuntimeType);
+                       exporter.ExportStandardComplexType (RuntimeType.GetCustomAttribute<DataContractAttribute> (false), RuntimeType, Members);
                }
        }
        
@@ -70,7 +70,7 @@ namespace System.Runtime.Serialization
        {
                public override void ExportSchemaType (XsdDataContractExporter exporter)
                {
-                       exporter.ExportStandardComplexType (null, RuntimeType);
+                       exporter.ExportStandardComplexType (null, RuntimeType, Members);
                }
        }
        
@@ -102,7 +102,7 @@ namespace System.Runtime.Serialization
        {
                public override void ExportSchemaType (XsdDataContractExporter exporter)
                {
-                       throw new NotImplementedException ();
+                       exporter.ExportStandardComplexType (null, RuntimeType, Members);
                }
        }
        
index c04a26d7833ecdf70607c59677fe3a61c6575712..992b1286841d8dc6e19bc2376339b4a387e16ef6 100644 (file)
@@ -968,7 +968,11 @@ namespace System.Runtime.Serialization
                        Type type, QName qname, KnownTypeCollection knownTypes)
                        : base (type, qname, knownTypes)
                {
-                       Members = GetMembers (type, XmlName, false);
+               }
+
+               public void Initialize ()
+               {
+                       Members = GetMembers (RuntimeType, XmlName, false);
                }
 
                List<DataMemberInfo> GetMembers (Type type, QName qname, bool declared_only)
index 9cce840b166277adb1eb689fc0c0a683ba15f599..27bde112d6423ac993fd8a20d11a67480cc03cbd 100644 (file)
@@ -219,67 +219,12 @@ namespace System.Runtime.Serialization
                        if (imported_types.FirstOrDefault (i => i.ClrType == type) != null)
                                return false;
 
-#if true
                        known_types.TryRegister (type);
                        var map = known_types.FindUserMap (type);
                        if (map == null)
                                return false;
                        map.ExportSchemaType (this);
                        return true;
-#else
-                       var cdca = type.GetCustomAttribute<CollectionDataContractAttribute> (true);
-                       var dicType = GetIDictionaryInterfaceType (type);
-                       if (dicType != null) {
-                               ExportDictionaryContractType (cdca, type, dicType);
-                               return true;
-                       }
-                       // not sure if contract is required
-                       if (type.IsArray && type != typeof (byte [])) {
-                               ExportListContractType (cdca, type);
-                               return true;
-                       }
-                       if (cdca != null) {
-                               ExportListContractType (cdca, type);
-                               return true;
-                       }
-
-                       var dca = type.GetCustomAttribute<DataContractAttribute> (true);
-                       if (type.IsEnum) { // regardless of DCA existence.
-                               ExportEnumContractType (dca, type);
-                               return true;
-                       }
-                       if (dca != null) {
-                               ExportStandardComplexType (dca, type);
-                               return true;
-                       }
-
-                       // FIXME: support [Serializable]
-
-                       if (rejectNonContract)
-                               throw new InvalidDataContractException ("DataContractAttribute is missing");
-
-                       return false;
-#endif
-               }
-
-               // copied from KnownTypeCollection, removing IDictionary
-               static Type GetIDictionaryInterfaceType (Type type)
-               {
-                       foreach (var iface in type.GetInterfaces ())
-                               if (iface == typeof (IDictionary) || (iface.IsGenericType && iface.GetGenericTypeDefinition () == typeof (IDictionary<,>)))
-                                       return iface;
-
-                       return null;
-               }
-               
-               // copied from KnownTypeCollection, removing IDictionary
-               static Type GetCollectionInterfaceType (Type type)
-               {
-                       foreach (var iface in type.GetInterfaces ())
-                               if (iface == typeof (IList) || (iface.IsGenericType && iface.GetGenericTypeDefinition () == typeof (ICollection<>)))
-                                       return iface;
-
-                       return null;
                }
                
                internal void ExportDictionaryContractType (CollectionDataContractAttribute attr, Type type, Type dicType)
@@ -292,8 +237,12 @@ namespace System.Runtime.Serialization
                        ExportCore (keyType, false);
                        ExportCore (valueType, false);
 
-                       var keyName = attr.KeyName ?? "Key";
-                       var valueName = attr.ValueName ?? "Value";
+                       string keyName = "Key", valueName = "Value";
+                       if (attr != null) {
+                               keyName = attr.KeyName ?? keyName;
+                               valueName = attr.ValueName ?? valueName;
+                       }
+                       string itemName = attr != null && attr.ItemName != null ? attr.ItemName : "KeyValueOf" + keyName + valueName;
 
                        var ct = CreateComplexType (qname, type);
                        var appInfo = new XmlSchemaAppInfo ();
@@ -305,7 +254,7 @@ namespace System.Runtime.Serialization
 
                        var seq = new XmlSchemaSequence ();
                        ct.Particle = seq;
-                       var el = new XmlSchemaElement () { Name = attr.ItemName ?? "KeyValueOf" + keyName + valueName, MinOccurs = 0, MaxOccursString = "unbounded" };
+                       var el = new XmlSchemaElement () { Name = itemName, MinOccurs = 0, MaxOccursString = "unbounded" };
                        seq.Items.Add (el);
 
                        var dictType = new XmlSchemaComplexType ();
@@ -378,7 +327,7 @@ namespace System.Runtime.Serialization
                        return r;
                }
 
-               internal void ExportStandardComplexType (DataContractAttribute attr, Type type)
+               internal void ExportStandardComplexType (DataContractAttribute attr, Type type, List<DataMemberInfo> members)
                {
                        var qname = attr != null && attr.Name != null ? new QName (attr.Name, attr.Namespace ?? GetXmlNamespace (type)) : GetSchemaTypeName (type);
                        var ct = CreateComplexType (qname, type);
@@ -390,10 +339,10 @@ namespace System.Runtime.Serialization
                                var xcce = new XmlSchemaComplexContentExtension ();
                                xcc.Content = xcce;
                                xcce.BaseTypeName = GetSchemaTypeName (type.BaseType);
-                               xcce.Particle = CreateMembersSequence (type, attr != null);
+                               xcce.Particle = CreateMembersSequence (type, members, attr != null);
                        }
                        else
-                               ct.Particle = CreateMembersSequence (type, attr != null);
+                               ct.Particle = CreateMembersSequence (type, members, attr != null);
                }
 
                XmlSchemaSimpleType CreateSimpleType (QName qname, Type type)
@@ -431,7 +380,8 @@ namespace System.Runtime.Serialization
                        return a1.Order == a2.Order ? String.CompareOrdinal (a1.Name ?? m1.Name, a2.Name ?? m2.Name) : a1.Order - a2.Order;
                }
 
-               XmlSchemaSequence CreateMembersSequence (Type type, bool expectContract)
+               // FIXME: use members parameter to determine which members are to be exported.
+               XmlSchemaSequence CreateMembersSequence (Type type, List<DataMemberInfo> dataMembers, bool expectContract)
                {
                        var seq = new XmlSchemaSequence ();
                        var members = new List<MemberInfo> ();
@@ -446,7 +396,8 @@ namespace System.Runtime.Serialization
                                if ((!expectContract || mi.GetCustomAttribute<DataMemberAttribute> (false) != null) && mi.GetIndexParameters ().Length == 0)
                                        members.Add (mi);
 
-                       members.Sort (CompareMembers);
+                       if (expectContract)
+                               members.Sort (CompareMembers);
 
                        foreach (var mi in members) {
                                var dma = mi.GetCustomAttribute<DataMemberAttribute> (false);
index 602d0d07a6922f581503e4f0f52ebda8cce360eb..7885b804a7c8b2cde571eaf73ef0402c89e13c8d 100644 (file)
@@ -1,2 +1,2 @@
-#include net_2_1_raw_System.Runtime.Serialization.dll.sources
+#include moonlight_raw_System.Runtime.Serialization.dll.sources
 System.Xml/OnXmlDictionaryReaderClose.cs
diff --git a/mcs/class/System.Runtime.Serialization/moonlight_raw_System.Runtime.Serialization.dll.sources b/mcs/class/System.Runtime.Serialization/moonlight_raw_System.Runtime.Serialization.dll.sources
new file mode 100644 (file)
index 0000000..59cd659
--- /dev/null
@@ -0,0 +1,46 @@
+Assembly/AssemblyInfo.cs
+System.Runtime.Serialization/CollectionDataContractAttribute.cs
+System.Runtime.Serialization/ContractNamespaceAttribute.cs
+System.Runtime.Serialization/DataContractAttribute.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/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/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
diff --git a/mcs/class/System.Runtime.Serialization/net_2_1_raw_System.Runtime.Serialization.dll.sources b/mcs/class/System.Runtime.Serialization/net_2_1_raw_System.Runtime.Serialization.dll.sources
deleted file mode 100644 (file)
index 59cd659..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-Assembly/AssemblyInfo.cs
-System.Runtime.Serialization/CollectionDataContractAttribute.cs
-System.Runtime.Serialization/ContractNamespaceAttribute.cs
-System.Runtime.Serialization/DataContractAttribute.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/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/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
index 770ffc3a8a1f877ffd145decef40338a6a9816e2..82455b4257cf5d11fab81b3c9010b0b846613578 100644 (file)
@@ -1,3 +1,7 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * Makefile: rename the net_2_1 profile to moonlight.
+
 2009-06-05  Marek Safar  <marek.safar@gmail.com>
 
        * Makefile: Fixed NET_2_0 conditional to actually handle Mono.Security
index 3d55d17cf2b8a52a7677f98d6f9225eacf71e0b6..bf261067d24d0e10f2456efba60c4678a93a89e6 100644 (file)
@@ -13,7 +13,7 @@ LIB_MCS_FLAGS += -r:Mono.Security.dll -nowarn:414
 TEST_MCS_FLAGS += -nowarn:168,183,414
 endif
 
-VALID_PROFILE := $(filter net_1_1 net_2_0 net_2_1_raw net_4_0, $(PROFILE))
+VALID_PROFILE := $(filter net_1_1 net_2_0 moonlight_raw net_4_0, $(PROFILE))
 ifndef VALID_PROFILE
 # @echo "** Warning: System.Security.dll built without parts that depend on: Mono.Security.dll "
 else
diff --git a/mcs/class/System.ServiceModel.Discovery/Assembly/AssemblyInfo.cs b/mcs/class/System.ServiceModel.Discovery/Assembly/AssemblyInfo.cs
new file mode 100644 (file)
index 0000000..fb52359
--- /dev/null
@@ -0,0 +1,61 @@
+//
+// AssemblyInfo.cs
+//
+// Author:
+//   Joel W. Reed (joelwreed@gmail.com)
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Reflection;
+using System.Resources;
+using System.Security;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about the System.ServiceModel assembly
+
+[assembly: AssemblyVersion (Consts.FxVersion)]
+[assembly: SatelliteContractVersion (Consts.FxVersion)]
+
+[assembly: AssemblyTitle ("System.ServiceModel.Discovery.dll")]
+[assembly: AssemblyDescription ("System.ServiceModel.Discovery.dll")]
+[assembly: AssemblyConfiguration ("Development version")]
+[assembly: AssemblyCompany ("MONO development team")]
+[assembly: AssemblyProduct ("MONO CLI")]
+[assembly: AssemblyCopyright ("(c) 2003 Various Authors")]
+[assembly: AssemblyTrademark ("")]
+
+[assembly: CLSCompliant (true)]
+[assembly: AssemblyDefaultAlias ("System.ServiceModel.Discovery.dll")]
+[assembly: AssemblyInformationalVersion ("3.5.594.0")]
+[assembly: NeutralResourcesLanguage ("en-US")]
+
+[assembly: ComVisible (false)]
+
+[assembly: AssemblyDelaySign (true)]
+#if NET_2_1
+[assembly: AssemblyKeyFile ("../silverlight.pub")]
+#else
+[assembly: AssemblyKeyFile("../winfx.pub")]
+#endif
diff --git a/mcs/class/System.ServiceModel.Discovery/Assembly/ChangeLog b/mcs/class/System.ServiceModel.Discovery/Assembly/ChangeLog
new file mode 100755 (executable)
index 0000000..ce289a8
--- /dev/null
@@ -0,0 +1,4 @@
+2010-03-19  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * : initial checkin (mostly stubs).
+
diff --git a/mcs/class/System.ServiceModel.Discovery/ChangeLog b/mcs/class/System.ServiceModel.Discovery/ChangeLog
new file mode 100644 (file)
index 0000000..ce289a8
--- /dev/null
@@ -0,0 +1,4 @@
+2010-03-19  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * : initial checkin (mostly stubs).
+
diff --git a/mcs/class/System.ServiceModel.Discovery/Makefile b/mcs/class/System.ServiceModel.Discovery/Makefile
new file mode 100644 (file)
index 0000000..de570d0
--- /dev/null
@@ -0,0 +1,24 @@
+thisdir = class/System.ServiceModel.Discovery
+SUBDIRS = 
+include ../../build/rules.make
+
+LIBRARY = System.ServiceModel.Discovery.dll
+LIB_MCS_FLAGS = -r:System.dll -r:System.Xml.dll -r:System.Runtime.Serialization.dll -r:System.ServiceModel.dll -r:System.Core.dll -r:System.Xml.Linq.dll
+
+ifneq (2.1, $(FRAMEWORK_VERSION))
+LIB_MCS_FLAGS += -d:NET_3_5 -d:NET_3_0         \
+                       -r:System.Configuration.dll
+endif
+
+TEST_MCS_FLAGS = $(LIB_MCS_FLAGS)
+
+EXTRA_DISTFILES = $(RESOURCE_FILES)
+
+VALID_PROFILE := $(filter 2.0 2.1 4.0, $(FRAMEWORK_VERSION))
+ifndef VALID_PROFILE
+LIBRARY_NAME = dummy-System.ServiceModel.Discovery.dll
+NO_INSTALL = yes
+NO_SIGN_ASSEMBLY = yes
+endif
+
+include ../../build/library.make
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/ChangeLog b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/ChangeLog
new file mode 100755 (executable)
index 0000000..ce289a8
--- /dev/null
@@ -0,0 +1,4 @@
+2010-03-19  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * : initial checkin (mostly stubs).
+
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/DiscoveryMessageSequenceApril2005.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/DiscoveryMessageSequenceApril2005.cs
new file mode 100755 (executable)
index 0000000..ea4791f
--- /dev/null
@@ -0,0 +1,75 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+using System.Xml;
+using System.Xml.Schema;
+using System.Xml.Serialization;
+
+namespace System.ServiceModel.Discovery.VersionApril2005
+{
+       public class DiscoveryMessageSequenceApril2005 : IXmlSerializable
+       {
+               public static DiscoveryMessageSequenceApril2005 FromDiscoveryMessageSequence (DiscoveryMessageSequence discoveryMessageSequence)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public static XmlQualifiedName GetSchema (XmlSchemaSet schemaSet)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               internal DiscoveryMessageSequenceApril2005 ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public XmlSchema GetSchema ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void ReadXml (XmlReader reader)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public DiscoveryMessageSequence ToDiscoveryMessageSequence ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void WriteXml (XmlWriter writer)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/EndpointDiscoveryMetadataApril2005.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/EndpointDiscoveryMetadataApril2005.cs
new file mode 100755 (executable)
index 0000000..526de2e
--- /dev/null
@@ -0,0 +1,70 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+using System.Xml;
+using System.Xml.Schema;
+using System.Xml.Serialization;
+
+namespace System.ServiceModel.Discovery.VersionApril2005
+{
+       public class EndpointDiscoveryMetadataApril2005 : IXmlSerializable
+       {
+               public static EndpointDiscoveryMetadataApril2005 FromEndpointDiscoveryMetadata (EndpointDiscoveryMetadata endpointDiscoveryMetadata)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public static XmlQualifiedName GetSchema (XmlSchemaSet schemaSet)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public XmlSchema GetSchema ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void ReadXml (XmlReader reader)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public EndpointDiscoveryMetadata ToEndpointDiscoveryMetadata ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void WriteXml (XmlWriter writer)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/FindCriteriaApril2005.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/FindCriteriaApril2005.cs
new file mode 100755 (executable)
index 0000000..a7603ae
--- /dev/null
@@ -0,0 +1,70 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+using System.Xml;
+using System.Xml.Schema;
+using System.Xml.Serialization;
+
+namespace System.ServiceModel.Discovery.VersionApril2005
+{
+       public class FindCriteriaApril2005 : IXmlSerializable
+       {
+               public static FindCriteriaApril2005 FromFindCriteria (FindCriteria findCriteria)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public static XmlQualifiedName GetSchema (XmlSchemaSet schemaSet)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public XmlSchema GetSchema ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void ReadXml (XmlReader reader)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public FindCriteria ToFindCriteria ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void WriteXml (XmlWriter writer)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/ResolveCriteriaApril2005.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionApril2005/ResolveCriteriaApril2005.cs
new file mode 100755 (executable)
index 0000000..0a65673
--- /dev/null
@@ -0,0 +1,70 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+using System.Xml;
+using System.Xml.Schema;
+using System.Xml.Serialization;
+
+namespace System.ServiceModel.Discovery.VersionApril2005
+{
+       public class ResolveCriteriaApril2005 : IXmlSerializable
+       {
+               public static ResolveCriteriaApril2005 FromResolveCriteria (ResolveCriteria resolveCriteria)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public static XmlQualifiedName GetSchema (XmlSchemaSet schemaSet)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public XmlSchema GetSchema ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void ReadXml (XmlReader reader)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public ResolveCriteria ToResolveCriteria ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void WriteXml (XmlWriter writer)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/ChangeLog b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/ChangeLog
new file mode 100755 (executable)
index 0000000..ce289a8
--- /dev/null
@@ -0,0 +1,4 @@
+2010-03-19  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * : initial checkin (mostly stubs).
+
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/DiscoveryMessageSequence11.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/DiscoveryMessageSequence11.cs
new file mode 100755 (executable)
index 0000000..1b88d4d
--- /dev/null
@@ -0,0 +1,75 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+using System.Xml;
+using System.Xml.Schema;
+using System.Xml.Serialization;
+
+namespace System.ServiceModel.Discovery.VersionCD1
+{
+       public class DiscoveryMessageSequence11 : IXmlSerializable
+       {
+               public static DiscoveryMessageSequence11 FromDiscoveryMessageSequence (DiscoveryMessageSequence discoveryMessageSequence)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public static XmlQualifiedName GetSchema (XmlSchemaSet schemaSet)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               internal DiscoveryMessageSequence11 ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public XmlSchema GetSchema ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void ReadXml (XmlReader reader)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public DiscoveryMessageSequence ToDiscoveryMessageSequence ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void WriteXml (XmlWriter writer)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/EndpointDiscoveryMetadata11.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/EndpointDiscoveryMetadata11.cs
new file mode 100755 (executable)
index 0000000..4d2260b
--- /dev/null
@@ -0,0 +1,70 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+using System.Xml;
+using System.Xml.Schema;
+using System.Xml.Serialization;
+
+namespace System.ServiceModel.Discovery.VersionCD1
+{
+       public class EndpointDiscoveryMetadata11 : IXmlSerializable
+       {
+               public static EndpointDiscoveryMetadata11 FromEndpointDiscoveryMetadata (EndpointDiscoveryMetadata endpointDiscoveryMetadata)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public static XmlQualifiedName GetSchema (XmlSchemaSet schemaSet)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public XmlSchema GetSchema ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void ReadXml (XmlReader reader)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public EndpointDiscoveryMetadata ToEndpointDiscoveryMetadata ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void WriteXml (XmlWriter writer)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/FindCriteria11.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/FindCriteria11.cs
new file mode 100755 (executable)
index 0000000..a82174b
--- /dev/null
@@ -0,0 +1,70 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+using System.Xml;
+using System.Xml.Schema;
+using System.Xml.Serialization;
+
+namespace System.ServiceModel.Discovery.VersionCD1
+{
+       public class FindCriteria11 : IXmlSerializable
+       {
+               public static FindCriteria11 FromFindCriteria (FindCriteria findCriteria)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public static XmlQualifiedName GetSchema (XmlSchemaSet schemaSet)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public XmlSchema GetSchema ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void ReadXml (XmlReader reader)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public FindCriteria ToFindCriteria ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void WriteXml (XmlWriter writer)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/ResolveCriteria11.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.VersionCD1/ResolveCriteria11.cs
new file mode 100755 (executable)
index 0000000..3367061
--- /dev/null
@@ -0,0 +1,70 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+using System.Xml;
+using System.Xml.Schema;
+using System.Xml.Serialization;
+
+namespace System.ServiceModel.Discovery.VersionCD1
+{
+       public class ResolveCriteria11 : IXmlSerializable
+       {
+               public static ResolveCriteria11 FromResolveCriteria (ResolveCriteria resolveCriteria)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public static XmlQualifiedName GetSchema (XmlSchemaSet schemaSet)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public XmlSchema GetSchema ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void ReadXml (XmlReader reader)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public ResolveCriteria ToResolveCriteria ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void WriteXml (XmlWriter writer)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.dll.sources b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery.dll.sources
new file mode 100644 (file)
index 0000000..4805004
--- /dev/null
@@ -0,0 +1,43 @@
+../../build/common/Consts.cs
+../../build/common/Locale.cs
+../../build/common/MonoTODOAttribute.cs
+Assembly/AssemblyInfo.cs
+System.ServiceModel.Discovery.VersionApril2005/DiscoveryMessageSequenceApril2005.cs
+System.ServiceModel.Discovery.VersionApril2005/EndpointDiscoveryMetadataApril2005.cs
+System.ServiceModel.Discovery.VersionApril2005/FindCriteriaApril2005.cs
+System.ServiceModel.Discovery.VersionApril2005/ResolveCriteriaApril2005.cs
+System.ServiceModel.Discovery.VersionCD1/DiscoveryMessageSequence11.cs
+System.ServiceModel.Discovery.VersionCD1/EndpointDiscoveryMetadata11.cs
+System.ServiceModel.Discovery.VersionCD1/FindCriteria11.cs
+System.ServiceModel.Discovery.VersionCD1/ResolveCriteria11.cs
+System.ServiceModel.Discovery/AnnouncementClient.cs
+System.ServiceModel.Discovery/AnnouncementEndpoint.cs
+System.ServiceModel.Discovery/AnnouncementEventArgs.cs
+System.ServiceModel.Discovery/AnnouncementService.cs
+System.ServiceModel.Discovery/DiscoveryClient.cs
+System.ServiceModel.Discovery/DiscoveryClientBindingElement.cs
+System.ServiceModel.Discovery/DiscoveryEndpoint.cs
+System.ServiceModel.Discovery/DiscoveryEndpointProvider.cs
+System.ServiceModel.Discovery/DiscoveryMessageSequence.cs
+System.ServiceModel.Discovery/DiscoveryMessageSequenceGenerator.cs
+System.ServiceModel.Discovery/DiscoveryOperationContextExtension.cs
+System.ServiceModel.Discovery/DiscoveryProxy.cs
+System.ServiceModel.Discovery/DiscoveryService.cs
+System.ServiceModel.Discovery/DiscoveryServiceExtension.cs
+System.ServiceModel.Discovery/DiscoveryVersion.cs
+System.ServiceModel.Discovery/DynamicEndpoint.cs
+System.ServiceModel.Discovery/EndpointDiscoveryBehavior.cs
+System.ServiceModel.Discovery/EndpointDiscoveryMetadata.cs
+System.ServiceModel.Discovery/FindCompletedEventArgs.cs
+System.ServiceModel.Discovery/FindCriteria.cs
+System.ServiceModel.Discovery/FindProgressChangedEventArgs.cs
+System.ServiceModel.Discovery/FindRequestContext.cs
+System.ServiceModel.Discovery/FindResponse.cs
+System.ServiceModel.Discovery/ResolveCompletedEventArgs.cs
+System.ServiceModel.Discovery/ResolveCriteria.cs
+System.ServiceModel.Discovery/ResolveResponse.cs
+System.ServiceModel.Discovery/ServiceDiscoveryBehavior.cs
+System.ServiceModel.Discovery/ServiceDiscoveryMode.cs
+System.ServiceModel.Discovery/UdpAnnouncementEndpoint.cs
+System.ServiceModel.Discovery/UdpDiscoveryEndpoint.cs
+System.ServiceModel.Discovery/UdpTransportSettings.cs
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/AnnouncementClient.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/AnnouncementClient.cs
new file mode 100755 (executable)
index 0000000..380e5ed
--- /dev/null
@@ -0,0 +1,183 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       [MonoTODO]
+       public sealed class AnnouncementClient : ICommunicationObject, IDisposable
+       {
+               public AnnouncementClient ()
+               {
+               }
+
+               public AnnouncementClient (AnnouncementEndpoint announcementEndpoint)
+               {
+               }
+
+               public AnnouncementClient (string endpointConfigurationName)
+               {
+               }
+
+               public ChannelFactory ChannelFactory { get; private set; }
+               public ClientCredentials ClientCredentials { get; private set; }
+               public ServiceEndpoint Endpoint { get; private set; }
+               public IClientChannel InnerChannel { get; private set; }
+               public DiscoveryMessageSequenceGenerator MessageSequenceGenerator { get; set; }
+
+               CommunicationState ICommunicationObject.State {
+                       get { return InnerChannel.State; }
+               }
+
+               public event EventHandler<AsyncCompletedEventArgs> AnnounceOfflineCompleted;
+               public event EventHandler<AsyncCompletedEventArgs> AnnounceOnlineCompleted;
+
+               event EventHandler ICommunicationObject.Closed {
+                       add { InnerChannel.Closed += value; }
+                       remove { InnerChannel.Closed -= value; }
+               }
+               event EventHandler ICommunicationObject.Closing {
+                       add { InnerChannel.Closing += value; }
+                       remove { InnerChannel.Closing -= value; }
+               }
+               event EventHandler ICommunicationObject.Faulted {
+                       add { InnerChannel.Faulted += value; }
+                       remove { InnerChannel.Faulted -= value; }
+               }
+               event EventHandler ICommunicationObject.Opened {
+                       add { InnerChannel.Opened += value; }
+                       remove { InnerChannel.Opened -= value; }
+               }
+               event EventHandler ICommunicationObject.Opening {
+                       add { InnerChannel.Opening += value; }
+                       remove { InnerChannel.Opening -= value; }
+               }
+
+               public void AnnounceOffline (EndpointDiscoveryMetadata discoveryMetadata)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void AnnounceOfflineAsync (EndpointDiscoveryMetadata discoveryMetadata)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void AnnounceOfflineAsync (EndpointDiscoveryMetadata discoveryMetadata, object userState)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void AnnounceOnline (EndpointDiscoveryMetadata discoveryMetadata)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void AnnounceOnlineAsync (EndpointDiscoveryMetadata discoveryMetadata)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void AnnounceOnlineAsync (EndpointDiscoveryMetadata discoveryMetadata, object userState)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public IAsyncResult BeginAnnounceOffline (EndpointDiscoveryMetadata discoveryMetadata, AsyncCallback callback, object state)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public IAsyncResult BeginAnnounceOnline (EndpointDiscoveryMetadata discoveryMetadata, AsyncCallback callback, object state)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void EndAnnounceOffline (IAsyncResult result)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void EndAnnounceOnline (IAsyncResult result)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void Close ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void Open ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               // explicit interface impl.
+
+               void ICommunicationObject.Open ()
+               {
+                       InnerChannel.Open ();
+               }
+
+               void ICommunicationObject.Open (TimeSpan timeout)
+               {
+                       InnerChannel.Open (timeout);
+               }
+
+               void ICommunicationObject.Close ()
+               {
+                       InnerChannel.Close ();
+               }
+
+               void ICommunicationObject.Close (TimeSpan timeout)
+               {
+                       InnerChannel.Close (timeout);
+               }
+
+               IAsyncResult ICommunicationObject.BeginOpen (AsyncCallback callback, object state)
+               {
+                       return InnerChannel.BeginOpen (callback, state);
+               }
+
+               IAsyncResult ICommunicationObject.BeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
+               {
+                       return InnerChannel.BeginOpen (timeout, callback, state);
+               }
+
+               IAsyncResult ICommunicationObject.BeginClose (AsyncCallback callback, object state)
+               {
+                       return InnerChannel.BeginClose (callback, state);
+               }
+
+               IAsyncResult ICommunicationObject.BeginClose (TimeSpan timeout, AsyncCallback callback, object state)
+               {
+                       return InnerChannel.BeginClose (timeout, callback, state);
+               }
+
+               void ICommunicationObject.EndOpen (IAsyncResult result)
+               {
+                       InnerChannel.EndOpen (result);
+               }
+
+               void ICommunicationObject.EndClose (IAsyncResult result)
+               {
+                       InnerChannel.EndClose (result);
+               }
+
+               void ICommunicationObject.Abort ()
+               {
+                       InnerChannel.Abort ();
+               }
+
+               void IDisposable.Dispose ()
+               {
+                       InnerChannel.Dispose ();
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/AnnouncementEndpoint.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/AnnouncementEndpoint.cs
new file mode 100755 (executable)
index 0000000..0de0547
--- /dev/null
@@ -0,0 +1,69 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       public class AnnouncementEndpoint : ServiceEndpoint
+       {
+               public AnnouncementEndpoint ()
+                       : this (DiscoveryVersion.WSDiscovery11)
+               {
+               }
+
+               public AnnouncementEndpoint (DiscoveryVersion discoveryVersion)
+                       : this (discoveryVersion, null, null)
+               {
+                       if (discoveryVersion == null)
+                               throw new ArgumentNullException ("discoveryVersion");
+                       DiscoveryVersion = discoveryVersion;
+               }
+
+               public AnnouncementEndpoint (Binding binding, EndpointAddress address)
+                       : this (DiscoveryVersion.WSDiscoveryApril2005, binding, address)
+               {
+               }
+
+               [MonoTODO]
+               public AnnouncementEndpoint (DiscoveryVersion discoveryVersion, Binding binding, EndpointAddress address)
+                       : base (null, binding, address)
+               {
+                       if (discoveryVersion == null)
+                               throw new ArgumentNullException ("discoveryVersion");
+                       DiscoveryVersion = discoveryVersion;
+               }
+
+               public DiscoveryVersion DiscoveryVersion { get; private set; }
+
+               [MonoTODO]
+               public TimeSpan MaxAnnouncementDelay { get; set; }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/AnnouncementEventArgs.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/AnnouncementEventArgs.cs
new file mode 100755 (executable)
index 0000000..e929544
--- /dev/null
@@ -0,0 +1,46 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       public class AnnouncementEventArgs : EventArgs
+       {
+               internal AnnouncementEventArgs (EndpointDiscoveryMetadata metadata, DiscoveryMessageSequence queue)
+               {
+                       EndpointDiscoveryMetadata = metadata;
+                       MessageSequence = queue;
+               }
+
+               public EndpointDiscoveryMetadata EndpointDiscoveryMetadata { get; private set; }
+               public DiscoveryMessageSequence MessageSequence { get; private set; }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/AnnouncementService.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/AnnouncementService.cs
new file mode 100755 (executable)
index 0000000..69f42d9
--- /dev/null
@@ -0,0 +1,46 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       [MonoTODO]
+       [ServiceBehavior (InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
+       public class AnnouncementService
+       {
+               public AnnouncementService ()
+               {
+               }
+
+               public AnnouncementService (int duplicateMessageHistoryLength)
+               {
+               }
+
+               public event EventHandler<AnnouncementEventArgs> OfflineAnnouncementReceived;
+               public event EventHandler<AnnouncementEventArgs> OnlineAnnouncementReceived;
+
+               protected virtual IAsyncResult OnBeginOfflineAnnouncement (DiscoveryMessageSequence messageSequence, EndpointDiscoveryMetadata endpointDiscoveryMetadata, AsyncCallback callback, object state)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               protected virtual IAsyncResult OnBeginOnlineAnnouncement (DiscoveryMessageSequence messageSequence, EndpointDiscoveryMetadata endpointDiscoveryMetadata, AsyncCallback callback, object state)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               protected virtual void OnEndOfflineAnnouncement (IAsyncResult result)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               protected virtual void OnEndOnlineAnnouncement (IAsyncResult result)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ChangeLog b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ChangeLog
new file mode 100755 (executable)
index 0000000..ce289a8
--- /dev/null
@@ -0,0 +1,4 @@
+2010-03-19  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * : initial checkin (mostly stubs).
+
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryClient.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryClient.cs
new file mode 100755 (executable)
index 0000000..b454c53
--- /dev/null
@@ -0,0 +1,169 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       [MonoTODO]
+       public sealed class DiscoveryClient : ICommunicationObject, IDisposable
+       {
+               public DiscoveryClient ()
+               {
+               }
+
+               public DiscoveryClient (DiscoveryEndpoint discoveryEndpoint)
+               {
+               }
+
+               public DiscoveryClient (string endpointConfigurationName)
+               {
+               }
+
+               public ChannelFactory ChannelFactory { get; private set; }
+               public ClientCredentials ClientCredentials { get; private set; }
+               public ServiceEndpoint Endpoint { get; private set; }
+               public IClientChannel InnerChannel { get; private set; }
+
+               CommunicationState ICommunicationObject.State {
+                       get { return InnerChannel.State; }
+               }
+
+               public event EventHandler<FindCompletedEventArgs> FindCompleted;
+               public event EventHandler<FindProgressChangedEventArgs> FindProgressChanged;
+               public event EventHandler<AnnouncementEventArgs> ProxyAvailable;
+               public event EventHandler<ResolveCompletedEventArgs> ResolveCompleted;
+
+               event EventHandler ICommunicationObject.Closed {
+                       add { InnerChannel.Closed += value; }
+                       remove { InnerChannel.Closed -= value; }
+               }
+               event EventHandler ICommunicationObject.Closing {
+                       add { InnerChannel.Closing += value; }
+                       remove { InnerChannel.Closing -= value; }
+               }
+               event EventHandler ICommunicationObject.Faulted {
+                       add { InnerChannel.Faulted += value; }
+                       remove { InnerChannel.Faulted -= value; }
+               }
+               event EventHandler ICommunicationObject.Opened {
+                       add { InnerChannel.Opened += value; }
+                       remove { InnerChannel.Opened -= value; }
+               }
+               event EventHandler ICommunicationObject.Opening {
+                       add { InnerChannel.Opening += value; }
+                       remove { InnerChannel.Opening -= value; }
+               }
+
+               public void CancelAsync (object userState)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void Close ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public FindResponse Find (FindCriteria criteria)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void FindAsync (FindCriteria criteria)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void FindAsync (FindCriteria criteria, object userState)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void Open ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public ResolveResponse Resolve (ResolveCriteria criteria)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void ResolveAsync (ResolveCriteria criteria)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public void ResolveAsync (ResolveCriteria criteria, object userState)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               // explicit interface impl.
+
+               void ICommunicationObject.Open ()
+               {
+                       InnerChannel.Open ();
+               }
+
+               void ICommunicationObject.Open (TimeSpan timeout)
+               {
+                       InnerChannel.Open (timeout);
+               }
+
+               void ICommunicationObject.Close ()
+               {
+                       InnerChannel.Close ();
+               }
+
+               void ICommunicationObject.Close (TimeSpan timeout)
+               {
+                       InnerChannel.Close (timeout);
+               }
+
+               IAsyncResult ICommunicationObject.BeginOpen (AsyncCallback callback, object state)
+               {
+                       return InnerChannel.BeginOpen (callback, state);
+               }
+
+               IAsyncResult ICommunicationObject.BeginOpen (TimeSpan timeout, AsyncCallback callback, object state)
+               {
+                       return InnerChannel.BeginOpen (timeout, callback, state);
+               }
+
+               IAsyncResult ICommunicationObject.BeginClose (AsyncCallback callback, object state)
+               {
+                       return InnerChannel.BeginClose (callback, state);
+               }
+
+               IAsyncResult ICommunicationObject.BeginClose (TimeSpan timeout, AsyncCallback callback, object state)
+               {
+                       return InnerChannel.BeginClose (timeout, callback, state);
+               }
+
+               void ICommunicationObject.EndOpen (IAsyncResult result)
+               {
+                       InnerChannel.EndOpen (result);
+               }
+
+               void ICommunicationObject.EndClose (IAsyncResult result)
+               {
+                       InnerChannel.EndClose (result);
+               }
+
+               void ICommunicationObject.Abort ()
+               {
+                       InnerChannel.Abort ();
+               }
+
+               void IDisposable.Dispose ()
+               {
+                       InnerChannel.Dispose ();
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryClientBindingElement.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryClientBindingElement.cs
new file mode 100755 (executable)
index 0000000..c3b2d2a
--- /dev/null
@@ -0,0 +1,60 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       [MonoTODO]
+       public sealed class DiscoveryClientBindingElement : BindingElement
+       {
+               [MonoTODO]
+               public static readonly EndpointAddress DiscoveryEndpointAddress = null;
+
+               public DiscoveryClientBindingElement ()
+               {
+               }
+
+               public DiscoveryClientBindingElement (DiscoveryEndpointProvider discoveryEndpointProvider, FindCriteria findCriteria)
+               {
+                       DiscoveryEndpointProvider = discoveryEndpointProvider;
+                       FindCriteria = findCriteria;
+               }
+
+               public DiscoveryEndpointProvider DiscoveryEndpointProvider { get; set; }
+               public FindCriteria FindCriteria { get; set; }
+
+               public override IChannelFactory<TChannel> BuildChannelFactory<TChannel> (BindingContext context)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override IChannelListener<TChannel> BuildChannelListener<TChannel> (BindingContext context)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override bool CanBuildChannelFactory<TChannel> (BindingContext context)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override bool CanBuildChannelListener<TChannel> (BindingContext context)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override BindingElement Clone ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override T GetProperty<T> (BindingContext context)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryEndpoint.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryEndpoint.cs
new file mode 100755 (executable)
index 0000000..5b3d8b8
--- /dev/null
@@ -0,0 +1,66 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       public class DiscoveryEndpoint : ServiceEndpoint
+       {
+               public DiscoveryEndpoint ()
+                       : this (null, null)
+               {
+               }
+
+               public DiscoveryEndpoint (Binding binding, EndpointAddress endpointAddress)
+                       : this (DiscoveryVersion.WSDiscoveryApril2005, ServiceDiscoveryMode.Managed, binding, endpointAddress)
+               {
+               }
+
+               public DiscoveryEndpoint (DiscoveryVersion discoveryVersion, ServiceDiscoveryMode discoveryMode)
+                       : this (discoveryVersion, discoveryMode, null, null)
+               {
+               }
+
+               public DiscoveryEndpoint (DiscoveryVersion discoveryVersion, ServiceDiscoveryMode discoveryMode, Binding binding, EndpointAddress endpointAddress)
+                       : base (null, binding, endpointAddress)
+               {
+                       if (discoveryVersion == null)
+                               throw new ArgumentNullException ("discoveryVersion");
+                       DiscoveryVersion = discoveryVersion;
+                       DiscoveryMode = discoveryMode;
+               }
+
+               public ServiceDiscoveryMode DiscoveryMode { get; private set; }
+               public DiscoveryVersion DiscoveryVersion { get; private set; }
+               [MonoTODO]
+               public TimeSpan MaxResponseDelay { get; set; }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryEndpointProvider.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryEndpointProvider.cs
new file mode 100755 (executable)
index 0000000..46cff0d
--- /dev/null
@@ -0,0 +1,39 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       public abstract class DiscoveryEndpointProvider
+       {
+               public abstract DiscoveryEndpoint GetDiscoveryEndpoint ();
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryMessageSequence.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryMessageSequence.cs
new file mode 100755 (executable)
index 0000000..7590eb1
--- /dev/null
@@ -0,0 +1,99 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       public class DiscoveryMessageSequence : IComparable<DiscoveryMessageSequence>, IEquatable<DiscoveryMessageSequence>
+       {
+               internal DiscoveryMessageSequence (long instanceId, Uri sequenceId, long messageNumber)
+               {
+                       InstanceId = instanceId;
+                       SequenceId = sequenceId;
+                       MessageNumber = messageNumber;
+               }
+
+               public long InstanceId { get; private set; }
+               public long MessageNumber { get; private set; }
+               public Uri SequenceId { get; private set; }
+
+               [MonoTODO]
+               public bool CanCompareTo (DiscoveryMessageSequence other)
+               {
+                       if (other == null)
+                               return false;
+                       return InstanceId == other.InstanceId && SequenceId.Equals (other.SequenceId);
+               }
+
+               [MonoTODO]
+               public int CompareTo (DiscoveryMessageSequence other)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public bool Equals (DiscoveryMessageSequence other)
+               {
+                       if (other == null)
+                               return false;
+                       return  InstanceId == other.InstanceId &&
+                               SequenceId.Equals (other.SequenceId) &&
+                               MessageNumber == other.MessageNumber;
+               }
+
+               public override bool Equals (object obj)
+               {
+                       var s = obj as DiscoveryMessageSequence;
+                       return s != null && Equals (s);
+               }
+
+               [MonoTODO]
+               public override int GetHashCode ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               [MonoTODO]
+               public override string ToString ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public static bool operator == (DiscoveryMessageSequence messageSequence1, DiscoveryMessageSequence messageSequence2)
+               {
+                       return messageSequence1 != null ? messageSequence1.Equals (messageSequence2) : messageSequence2 == null;
+               }
+
+               public static bool operator != (DiscoveryMessageSequence messageSequence1, DiscoveryMessageSequence messageSequence2)
+               {
+                       return messageSequence1 == null ? messageSequence2 != null : !messageSequence1.Equals (messageSequence2);
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryMessageSequenceGenerator.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryMessageSequenceGenerator.cs
new file mode 100755 (executable)
index 0000000..f960a4a
--- /dev/null
@@ -0,0 +1,57 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       public class DiscoveryMessageSequenceGenerator
+       {
+               [MonoTODO ("default values?")]
+               public DiscoveryMessageSequenceGenerator ()
+               {
+               }
+
+               public DiscoveryMessageSequenceGenerator (long instanceId, Uri sequenceId)
+               {
+                       instance_id = instanceId;
+                       sequence_id = sequenceId;
+               }
+
+               long instance_id, message_count;
+               Uri sequence_id;
+
+               [MonoTODO ("default number?")]
+               public DiscoveryMessageSequence Next ()
+               {
+                       return new DiscoveryMessageSequence (instance_id, sequence_id, message_count++);
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryOperationContextExtension.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryOperationContextExtension.cs
new file mode 100755 (executable)
index 0000000..ccc6489
--- /dev/null
@@ -0,0 +1,26 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       [MonoTODO]
+       public class DiscoveryOperationContextExtension : IExtension<OperationContext>
+       {
+               internal DiscoveryOperationContextExtension ()
+               {
+               }
+
+               void IExtension<OperationContext>.Attach (OperationContext owner)
+               {
+               }
+
+               void IExtension<OperationContext>.Detach (OperationContext owner)
+               {
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryProxy.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryProxy.cs
new file mode 100755 (executable)
index 0000000..33a3ffb
--- /dev/null
@@ -0,0 +1,56 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       [MonoTODO]
+       public abstract class DiscoveryProxy
+       {
+               protected DiscoveryProxy ()
+               {
+               }
+
+               protected DiscoveryProxy (DiscoveryMessageSequenceGenerator messageSequenceGenerator)
+               {
+               }
+
+               protected DiscoveryProxy (DiscoveryMessageSequenceGenerator messageSequenceGenerator, int duplicateMessageHistoryLength)
+               {
+               }
+
+               protected virtual IAsyncResult BeginShouldRedirectFind (FindCriteria resolveCriteria, AsyncCallback callback, Object state)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               protected virtual IAsyncResult BeginShouldRedirectResolve (ResolveCriteria findCriteria, AsyncCallback callback, Object state)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               protected virtual bool EndShouldRedirectFind (IAsyncResult result, out Collection<EndpointDiscoveryMetadata> redirectionEndpoints)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               protected virtual bool EndShouldRedirectResolve (IAsyncResult result, out Collection<EndpointDiscoveryMetadata> redirectionEndpoints)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               protected abstract IAsyncResult OnBeginFind (FindRequestContext findRequestContext, AsyncCallback callback, Object state);
+               protected abstract IAsyncResult OnBeginOfflineAnnouncement (DiscoveryMessageSequence messageSequence, EndpointDiscoveryMetadata endpointDiscoveryMetadata, AsyncCallback callback, Object state);
+               protected abstract IAsyncResult OnBeginOnlineAnnouncement (DiscoveryMessageSequence messageSequence, EndpointDiscoveryMetadata endpointDiscoveryMetadata, AsyncCallback callback, Object state);
+               protected abstract IAsyncResult OnBeginResolve (ResolveCriteria resolveCriteria, AsyncCallback callback, Object state);
+               protected abstract void OnEndFind (IAsyncResult result);
+               protected abstract void OnEndOfflineAnnouncement (IAsyncResult result);
+               protected abstract void OnEndOnlineAnnouncement (IAsyncResult result);
+               protected abstract EndpointDiscoveryMetadata OnEndResolve (IAsyncResult result);
+
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryService.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryService.cs
new file mode 100755 (executable)
index 0000000..1bd1c9a
--- /dev/null
@@ -0,0 +1,34 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       [MonoTODO]
+       public abstract class DiscoveryService
+       {
+               protected DiscoveryService ()
+               {
+               }
+
+               protected DiscoveryService (DiscoveryMessageSequenceGenerator discoveryMessageSequenceGenerator)
+               {
+               }
+
+               protected DiscoveryService (DiscoveryMessageSequenceGenerator discoveryMessageSequenceGenerator, int duplicateMessageHistoryLength)
+               {
+               }
+
+               protected abstract IAsyncResult OnBeginFind (FindRequestContext findRequestContext, AsyncCallback callback, Object state);
+
+               protected abstract IAsyncResult OnBeginResolve (ResolveCriteria resolveCriteria, AsyncCallback callback, Object state);
+
+               protected abstract void OnEndFind (IAsyncResult result);
+
+               protected abstract EndpointDiscoveryMetadata OnEndResolve (IAsyncResult result);
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryServiceExtension.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryServiceExtension.cs
new file mode 100755 (executable)
index 0000000..a55f145
--- /dev/null
@@ -0,0 +1,24 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       [MonoTODO]
+       public abstract class DiscoveryServiceExtension : IExtension<ServiceHostBase>
+       {
+               protected abstract DiscoveryService GetDiscoveryService ();
+
+               void IExtension<ServiceHostBase>.Attach (ServiceHostBase owner)
+               {
+               }
+
+               void IExtension<ServiceHostBase>.Detach (ServiceHostBase owner)
+               {
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryVersion.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DiscoveryVersion.cs
new file mode 100755 (executable)
index 0000000..ac106cc
--- /dev/null
@@ -0,0 +1,89 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       public sealed class DiscoveryVersion
+       {
+               static DiscoveryVersion ()
+               {
+                       v11 = new DiscoveryVersion ("WSDiscovery11");
+                       april2005 = new DiscoveryVersion ("WSDiscoveryApril2005");
+                       cd1 = new DiscoveryVersion ("WSDiscoveryCD1");
+               }
+
+               static readonly DiscoveryVersion v11, april2005, cd1;
+
+               public static DiscoveryVersion WSDiscovery11 {
+                       get { return v11; }
+               }
+
+               public static DiscoveryVersion WSDiscoveryApril2005 {
+                       get { return april2005; }
+               }
+
+               public static DiscoveryVersion WSDiscoveryCD1 {
+                       get { return cd1; }
+               }
+
+               public static DiscoveryVersion FromName (string name)
+               {
+                       if (name == null)
+                               throw new ArgumentNullException ("name");
+                       switch (name) {
+                       case "WSDiscovery11":
+                               return v11;
+                       case "WSDiscoveryApril2005":
+                               return april2005;
+                       case "WSDiscoveryCD1":
+                               return cd1;
+                       default:
+                               throw new ArgumentNullException (String.Format ("Invalid version name: {0}", name));
+                       }
+               }
+
+               internal DiscoveryVersion (string name)
+               {
+                       this.Name = name;
+               }
+
+               public Uri AdhocAddress { get; private set; }
+               public MessageVersion MessageVersion { get; private set; }
+               public string Name { get; private set; }
+               public string Namespace { get; private set; }
+
+               public override string ToString ()
+               {
+                       return Name;
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DynamicEndpoint.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/DynamicEndpoint.cs
new file mode 100755 (executable)
index 0000000..80f1d81
--- /dev/null
@@ -0,0 +1,22 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       [MonoTODO]
+       public class DynamicEndpoint : ServiceEndpoint
+       {
+               public DynamicEndpoint (ContractDescription contract, Binding binding)
+                       : base (contract, binding, null)
+               {
+               }
+
+               public DiscoveryEndpointProvider DiscoveryEndpointProvider { get; set; }
+               public FindCriteria FindCriteria { get; set; }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/EndpointDiscoveryBehavior.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/EndpointDiscoveryBehavior.cs
new file mode 100755 (executable)
index 0000000..334c944
--- /dev/null
@@ -0,0 +1,30 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       [MonoTODO]
+       public class EndpointDiscoveryBehavior : IEndpointBehavior
+       {
+               void IEndpointBehavior.AddBindingParameters (ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
+               {
+               }
+
+               void IEndpointBehavior.ApplyClientBehavior (ServiceEndpoint endpoint, ClientRuntime clientRuntime)
+               {
+               }
+
+               void IEndpointBehavior.ApplyDispatchBehavior (ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
+               {
+               }
+
+               void IEndpointBehavior.Validate (ServiceEndpoint endpoint)
+               {
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/EndpointDiscoveryMetadata.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/EndpointDiscoveryMetadata.cs
new file mode 100755 (executable)
index 0000000..a905159
--- /dev/null
@@ -0,0 +1,33 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+using System.Xml;
+using System.Xml.Linq;
+
+namespace System.ServiceModel.Discovery
+{
+       [MonoTODO]
+       public class EndpointDiscoveryMetadata
+       {
+               public static EndpointDiscoveryMetadata FromServiceEndpoint (ServiceEndpoint endpoint)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public static EndpointDiscoveryMetadata FromServiceEndpoint (ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public EndpointAddress Address { get; set; }
+               public Collection<XmlQualifiedName> ContractTypeNames { get; private set; }
+               public Collection<XElement> Extensions { get; private set; }
+               public Collection<Uri> ListenUris { get; private set; }
+               public Collection<Uri> Scopes { get; private set; }
+               public int Version { get; set; }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/FindCompletedEventArgs.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/FindCompletedEventArgs.cs
new file mode 100755 (executable)
index 0000000..7abcfb4
--- /dev/null
@@ -0,0 +1,46 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       public class FindCompletedEventArgs : AsyncCompletedEventArgs
+       {
+               internal FindCompletedEventArgs (FindResponse result, Exception error, bool cancelled, object userState)
+                       : base (error, cancelled, userState)
+               {
+                       this.Result = result;
+               }
+
+               public FindResponse Result { get; private set; }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/FindCriteria.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/FindCriteria.cs
new file mode 100755 (executable)
index 0000000..12c79fd
--- /dev/null
@@ -0,0 +1,91 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+using System.Xml;
+using System.Xml.Linq;
+
+namespace System.ServiceModel.Discovery
+{
+       public class FindCriteria
+       {
+               public static readonly Uri ScopeMatchByExact = new Uri ("http://docs.oasis-open.org/ws-dd/ns/discovery/2009/01/strcmp0");
+               public static readonly Uri ScopeMatchByLdap = new Uri ("http://docs.oasis-open.org/ws-dd/ns/discovery/2009/01/ldap");
+               public static readonly Uri ScopeMatchByNone = new Uri ("http://docs.oasis-open.org/ws-dd/ns/discovery/2009/01/none");
+               public static readonly Uri ScopeMatchByPrefix = new Uri ("http://docs.oasis-open.org/ws-dd/ns/discovery/2009/01/rfc3986");
+               public static readonly Uri ScopeMatchByUuid = new Uri ("http://docs.oasis-open.org/ws-dd/ns/discovery/2009/01/uuid");
+
+               public static FindCriteria CreateMetadataExchangeEndpointCriteria ()
+               {
+                       return CreateMetadataExchangeEndpointCriteria (typeof (IMetadataExchange));
+               }
+
+               public static FindCriteria CreateMetadataExchangeEndpointCriteria (IEnumerable<XmlQualifiedName> contractTypeNames)
+               {
+                       var fc = new FindCriteria ();
+                       foreach (var type in contractTypeNames)
+                               fc.ContractTypeNames.Add (type);
+                       return fc;
+               }
+
+               public static FindCriteria CreateMetadataExchangeEndpointCriteria (Type contractType)
+               {
+                       return new FindCriteria (contractType);
+               }
+
+               public FindCriteria ()
+               {
+                       ContractTypeNames = new Collection<XmlQualifiedName> ();
+                       Extensions = new Collection<XElement> ();
+                       Scopes = new Collection<Uri> ();
+               }
+
+               [MonoTODO]
+               public FindCriteria (Type contractType)
+                       : this ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public Collection<XmlQualifiedName> ContractTypeNames { get; private set; }
+               public TimeSpan Duration { get; set; }
+               public Collection<XElement> Extensions { get; private set; }
+               [MonoTODO]
+               public int MaxResults { get; set; }
+               public Uri ScopeMatchBy { get; set; }
+               public Collection<Uri> Scopes { get; private set; }
+
+               [MonoTODO]
+               public bool IsMatch (EndpointDiscoveryMetadata endpointDiscoveryMetadata)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/FindProgressChangedEventArgs.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/FindProgressChangedEventArgs.cs
new file mode 100755 (executable)
index 0000000..d01affd
--- /dev/null
@@ -0,0 +1,48 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       public class FindProgressChangedEventArgs : ProgressChangedEventArgs
+       {
+               internal FindProgressChangedEventArgs (EndpointDiscoveryMetadata metadata, DiscoveryMessageSequence sequence, int progressPercentage, object userState)
+                       : base (progressPercentage, userState)
+               {
+                       EndpointDiscoveryMetadata = metadata;
+                       MessageSequence = sequence;
+               }
+
+               public EndpointDiscoveryMetadata EndpointDiscoveryMetadata { get;private set; }
+               public DiscoveryMessageSequence MessageSequence { get; private set; }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/FindRequestContext.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/FindRequestContext.cs
new file mode 100755 (executable)
index 0000000..06ab140
--- /dev/null
@@ -0,0 +1,58 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       public class FindRequestContext
+       {
+               protected FindRequestContext (FindCriteria criteria)
+               {
+                       if (criteria == null)
+                               throw new ArgumentNullException ("criteria");
+                       Criteria = criteria;
+               }
+
+               public FindCriteria Criteria { get; private set; }
+
+               [MonoTODO]
+               public void AddMatchingEndpoint (EndpointDiscoveryMetadata matchingEndpoint)
+               {
+                       OnAddMatchingEndpoint (matchingEndpoint);
+               }
+
+               [MonoTODO]
+               protected virtual void OnAddMatchingEndpoint (EndpointDiscoveryMetadata matchingEndpoint)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/FindResponse.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/FindResponse.cs
new file mode 100755 (executable)
index 0000000..451d3d2
--- /dev/null
@@ -0,0 +1,50 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       public class FindResponse
+       {
+               internal FindResponse ()
+               {
+                       Endpoints = new Collection<EndpointDiscoveryMetadata> ();
+               }
+
+               public Collection<EndpointDiscoveryMetadata> Endpoints { get; private set; }
+
+               [MonoTODO]
+               public DiscoveryMessageSequence GetMessageSequence (EndpointDiscoveryMetadata endpointDiscoveryMetadata)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ResolveCompletedEventArgs.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ResolveCompletedEventArgs.cs
new file mode 100755 (executable)
index 0000000..220fb96
--- /dev/null
@@ -0,0 +1,46 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       public class ResolveCompletedEventArgs : AsyncCompletedEventArgs
+       {
+               internal ResolveCompletedEventArgs (ResolveResponse result, Exception error, bool cancelled, object userState)
+                       : base (error, cancelled, userState)
+               {
+                       this.Result = result;
+               }
+
+               public ResolveResponse Result { get; private set; }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ResolveCriteria.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ResolveCriteria.cs
new file mode 100755 (executable)
index 0000000..11731ef
--- /dev/null
@@ -0,0 +1,54 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+using System.Xml.Linq;
+
+namespace System.ServiceModel.Discovery
+{
+       public class ResolveCriteria
+       {
+               public ResolveCriteria ()
+               {
+                       Extensions = new Collection<XElement> ();
+               }
+
+               public ResolveCriteria (EndpointAddress address)
+                       : this ()
+               {
+                       Address = address;
+               }
+
+               public EndpointAddress Address { get; set; }
+               [MonoTODO]
+               public TimeSpan Duration { get; set; }
+               public Collection<XElement> Extensions { get; private set; }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ResolveResponse.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ResolveResponse.cs
new file mode 100755 (executable)
index 0000000..6a1b4f1
--- /dev/null
@@ -0,0 +1,46 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       public class ResolveResponse
+       {
+               internal ResolveResponse (EndpointDiscoveryMetadata metadata, DiscoveryMessageSequence sequence)
+               {
+                       EndpointDiscoveryMetadata = metadata;
+                       MessageSequence = sequence;
+               }
+
+               public EndpointDiscoveryMetadata EndpointDiscoveryMetadata { get; private set; }
+               public DiscoveryMessageSequence MessageSequence { get; private set; }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ServiceDiscoveryBehavior.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ServiceDiscoveryBehavior.cs
new file mode 100755 (executable)
index 0000000..22599e3
--- /dev/null
@@ -0,0 +1,26 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       [MonoTODO]
+       public class ServiceDiscoveryBehavior : IServiceBehavior
+       {
+               void IServiceBehavior.AddBindingParameters (ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
+               {
+               }
+
+               void IServiceBehavior.ApplyDispatchBehavior (ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
+               {
+               }
+
+               void IServiceBehavior.Validate (ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
+               {
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ServiceDiscoveryMode.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/ServiceDiscoveryMode.cs
new file mode 100755 (executable)
index 0000000..3b65b64
--- /dev/null
@@ -0,0 +1,32 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+namespace System.ServiceModel.Discovery
+{
+       public enum ServiceDiscoveryMode
+       {
+               Adhoc,
+               Managed
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/UdpAnnouncementEndpoint.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/UdpAnnouncementEndpoint.cs
new file mode 100755 (executable)
index 0000000..95823a6
--- /dev/null
@@ -0,0 +1,83 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       public class UdpAnnouncementEndpoint : AnnouncementEndpoint
+       {
+               [MonoTODO]
+               public static readonly Uri DefaultIPv4MulticastAddress;
+               [MonoTODO]
+               public static readonly Uri DefaultIPv6MulticastAddress;
+
+               // (1)->(2)
+               public UdpAnnouncementEndpoint ()
+                       : this (DiscoveryVersion.WSDiscovery11)
+               {
+               }
+
+               // (2), everything falls to here.
+               public UdpAnnouncementEndpoint (DiscoveryVersion discoveryVersion)
+                       : base (discoveryVersion)
+               {
+                       TransportSettings = new UdpTransportSettings ();
+               }
+
+               // (3)->(4)
+               public UdpAnnouncementEndpoint (string multicastAddress)
+                       : this (new Uri (multicastAddress))
+               {
+               }
+
+               // (4)->(5)
+               public UdpAnnouncementEndpoint (Uri multicastAddress)
+                       : this (DiscoveryVersion.WSDiscovery11, multicastAddress)
+               {
+               }
+
+               // (5)->(6)
+               public UdpAnnouncementEndpoint (DiscoveryVersion discoveryVersion, string multicastAddress)
+                       : this (discoveryVersion, new Uri (multicastAddress))
+               {
+               }
+
+               // (6)->(2)
+               public UdpAnnouncementEndpoint (DiscoveryVersion discoveryVersion, Uri multicastAddress)
+                       : this (discoveryVersion)
+               {
+                       MulticastAddress = multicastAddress;
+               }
+
+               public Uri MulticastAddress { get; set; }
+               public UdpTransportSettings TransportSettings { get; private set; }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/UdpDiscoveryEndpoint.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/UdpDiscoveryEndpoint.cs
new file mode 100755 (executable)
index 0000000..72c57b7
--- /dev/null
@@ -0,0 +1,83 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       public class UdpDiscoveryEndpoint : DiscoveryEndpoint
+       {
+               [MonoTODO]
+               public static readonly Uri DefaultIPv4MulticastAddress;
+               [MonoTODO]
+               public static readonly Uri DefaultIPv6MulticastAddress;
+
+               // (1)->(2)
+               public UdpDiscoveryEndpoint ()
+                       : this (DiscoveryVersion.WSDiscovery11)
+               {
+               }
+
+               // (2), everything falls to here.
+               public UdpDiscoveryEndpoint (DiscoveryVersion discoveryVersion)
+                       : base (discoveryVersion, ServiceDiscoveryMode.Adhoc)
+               {
+                       TransportSettings = new UdpTransportSettings ();
+               }
+
+               // (3)->(4)
+               public UdpDiscoveryEndpoint (string multicastAddress)
+                       : this (new Uri (multicastAddress))
+               {
+               }
+
+               // (4)->(5)
+               public UdpDiscoveryEndpoint (Uri multicastAddress)
+                       : this (DiscoveryVersion.WSDiscovery11, multicastAddress)
+               {
+               }
+
+               // (5)->(6)
+               public UdpDiscoveryEndpoint (DiscoveryVersion discoveryVersion, string multicastAddress)
+                       : this (discoveryVersion, new Uri (multicastAddress))
+               {
+               }
+
+               // (6)->(2)
+               public UdpDiscoveryEndpoint (DiscoveryVersion discoveryVersion, Uri multicastAddress)
+                       : this (discoveryVersion)
+               {
+                       MulticastAddress = multicastAddress;
+               }
+
+               public Uri MulticastAddress { get; set; }
+               public UdpTransportSettings TransportSettings { get; private set; }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/UdpTransportSettings.cs b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery/UdpTransportSettings.cs
new file mode 100755 (executable)
index 0000000..e0f2171
--- /dev/null
@@ -0,0 +1,51 @@
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
+
+namespace System.ServiceModel.Discovery
+{
+       public class UdpTransportSettings
+       {
+               internal UdpTransportSettings ()
+               {
+               }
+
+               public int DuplicateMessageHistoryLength { get; set; }
+               public long MaxBufferPoolSize { get; set; }
+               public int MaxMulticastRetransmitCount { get; set; }
+               public int MaxPendingMessageCount { get; set; }
+               public long MaxReceivedMessageSize { get; set; }
+               public int MaxUnicastRetransmitCount { get; set; }
+               public string MulticastInterfaceId { get; set; }
+               public int SocketReceiveBufferSize { get; set; }
+               public int TimeToLive { get; set; }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery_test.dll.sources b/mcs/class/System.ServiceModel.Discovery/System.ServiceModel.Discovery_test.dll.sources
new file mode 100644 (file)
index 0000000..ffd63d3
--- /dev/null
@@ -0,0 +1,2 @@
+System.ServiceModel.Discovery/DiscoveryVersionTest.cs
+System.ServiceModel.Discovery/FindCriteriaTest.cs
diff --git a/mcs/class/System.ServiceModel.Discovery/Test/System.ServiceModel.Discovery/ChangeLog b/mcs/class/System.ServiceModel.Discovery/Test/System.ServiceModel.Discovery/ChangeLog
new file mode 100755 (executable)
index 0000000..ce289a8
--- /dev/null
@@ -0,0 +1,4 @@
+2010-03-19  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * : initial checkin (mostly stubs).
+
diff --git a/mcs/class/System.ServiceModel.Discovery/Test/System.ServiceModel.Discovery/DiscoveryVersionTest.cs b/mcs/class/System.ServiceModel.Discovery/Test/System.ServiceModel.Discovery/DiscoveryVersionTest.cs
new file mode 100755 (executable)
index 0000000..3e73e0b
--- /dev/null
@@ -0,0 +1,45 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Discovery;
+using System.ServiceModel.Dispatcher;
+using NUnit.Framework;
+
+namespace MonoTests.System.ServiceModel.Discovery
+{
+       [TestFixture]
+       public class DiscoveryVersionTest
+       {
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void NullName ()
+               {
+                       DiscoveryVersion.FromName (null);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentOutOfRangeException))]
+               public void EmptyName ()
+               {
+                       DiscoveryVersion.FromName (String.Empty);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentOutOfRangeException))]
+               public void InvalidName ()
+               {
+                       DiscoveryVersion.FromName ("foobar");
+               }
+
+               [Test]
+               public void ValidName ()
+               {
+                       DiscoveryVersion.FromName ("WSDiscovery11");
+                       DiscoveryVersion.FromName ("WSDiscoveryApril2005");
+                       DiscoveryVersion.FromName ("WSDiscoveryCD1");
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel.Discovery/Test/System.ServiceModel.Discovery/FindCriteriaTest.cs b/mcs/class/System.ServiceModel.Discovery/Test/System.ServiceModel.Discovery/FindCriteriaTest.cs
new file mode 100755 (executable)
index 0000000..53bf01b
--- /dev/null
@@ -0,0 +1,27 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Discovery;
+using System.ServiceModel.Dispatcher;
+using NUnit.Framework;
+
+namespace MonoTests.System.ServiceModel.Discovery
+{
+       [TestFixture]
+       public class FindCriteriaTest
+       {
+               [Test]
+               [Ignore ("huh? should they really return Uri like 'http://schemas.microsoft.com/ws/2008/06/discovery/strcmp0' ?")]
+               public void StaticUris ()
+               {
+                       Assert.AreEqual ("http://docs.oasis-open.org/ws-dd/ns/discovery/2009/01/strcmp0", FindCriteria.ScopeMatchByExact.ToString (), "#1");
+                       Assert.AreEqual ("http://docs.oasis-open.org/ws-dd/ns/discovery/2009/01/none", FindCriteria.ScopeMatchByLdap.ToString (), "#2");
+                       Assert.AreEqual ("http://docs.oasis-open.org/ws-dd/ns/discovery/2009/01/none", FindCriteria.ScopeMatchByNone.ToString (), "#3");
+                       Assert.AreEqual ("http://docs.oasis-open.org/ws-dd/ns/discovery/2009/01/rfc3986", FindCriteria.ScopeMatchByPrefix.ToString (), "#4");
+                       Assert.AreEqual ("http://docs.oasis-open.org/ws-dd/ns/discovery/2009/01/uuid", FindCriteria.ScopeMatchByUuid.ToString (), "#5");
+               }
+       }
+}
index bfa93fd472e766960ec68abbf4c156790c1a2449..d0c60882654ecd60063a8aca2578a7149af817bd 100644 (file)
@@ -1,3 +1,9 @@
+2010-03-12  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * net_2_0_System.ServiceModel.Web.dll.sources,
+         common_System.ServiceModel.Web.dll.sources : UriTemplates are
+         moved to Sys.SM.dll in 4.0 profile.
+
 2010-03-12  Atsushi Enomoto  <atsushi@ximian.com>
 
        * monotouch_System.ServiceModel.Web.dll.sources :
index ef28ea94c9fabfb6fa4b7ea407ffe3ba6fc4dd07..4c38b06db2d44f9cf156ff0e21aecf857f21da98 100644 (file)
@@ -1,3 +1,18 @@
+2010-04-24  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * JsonSerializationReader.cs : use List<T> if the contract member
+         type is interface.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * DataContractJsonSerializer.cs: use MOONLIGHT symbol to
+       disambiguate MonoTouch and Moonlight code.
+
+2010-03-13  Kornél Pál  <kornelpal@gmail.com>
+
+       * JavaScriptReader.cs: Deserialize "false" correctly.
+         Fixed bug #586712.
+
 2010-03-10  Atsushi Enomoto  <atsushi@ximian.com>
 
        * JavaScriptReader.cs : moved from Sys.Json/JsonReader.cs.
index d5ea4db36a6fa9773e6e00abe96a36ccaeb0c7b4..355ea31dadb87c57ef8a008949b9fc245fbf2cfe 100644 (file)
@@ -91,7 +91,7 @@ namespace System.Runtime.Serialization.Json
                        always_emit_type = alwaysEmitTypeInformation;
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public DataContractJsonSerializer (Type type, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, IDataContractSurrogate dataContractSurrogate, bool alwaysEmitTypeInformation)
             : this (type, default_root_name, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, alwaysEmitTypeInformation)
                {
@@ -117,7 +117,7 @@ namespace System.Runtime.Serialization.Json
                int max_items;
                bool ignore_extension;
                bool always_emit_type;
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                IDataContractSurrogate surrogate;
 
                [MonoTODO]
index b3be29ae8d9c21a1f54d33bfc96dc6bc9a1ca9c0..746030825a73557a29b684190e8d19ecfe7de2af 100644 (file)
@@ -86,7 +86,7 @@ namespace System.Runtime.Serialization.Json
                                return true;
                        case 'f':
                                Expect ("false");
-                               return true;
+                               return false;
                        case 'n':
                                Expect ("null");
                                // FIXME: what should we return?
index f57d2068b8cf3f1ef1ca557e519516a0b3ec6cee..87cb0dc1e2648706b139b82b21b369c47bda0bb3 100644 (file)
@@ -259,6 +259,8 @@ namespace System.Runtime.Serialization.Json
                {
                        reader.ReadStartElement ();
                        object ret;
+                       if (collectionType.IsInterface)
+                               collectionType = typeof (List<>).MakeGenericType (elementType);
                        if (typeof (IList).IsAssignableFrom (collectionType)) {
 #if NET_2_1
                                Type listType = collectionType.IsArray ? typeof (List<>).MakeGenericType (elementType) : null;
index 2cf709207df2e0ba08e520ca649f4511ec0d8e08..cea57d025061afc6a6e2bb97c6c17991e97f7b75 100644 (file)
@@ -1,3 +1,13 @@
+2010-03-19  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * WebHttpBehavior.cs : set FilterPriority to make it in higher
+         priority than conflicting endpoints (such as mex endpoint).
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * WebHttpBehavior.cs: use MOONLIGHT symbol to
+       disambiguate MonoTouch and Moonlight code.
+
 2009-10-23  Atsushi Enomoto  <atsushi@ximian.com>
 
        * WebHttpBehavior.cs : add experimental monotouch build.
index cc4609ac62076929138c84756bb8d3c06d7903f2..c17c78899c908a01b62c9cc5bfee0dc5302ce79d 100644 (file)
@@ -102,7 +102,7 @@ namespace System.ServiceModel.Description
                public virtual void ApplyClientBehavior (ServiceEndpoint endpoint, ClientRuntime clientRuntime)
                {
                        AddClientErrorInspector (endpoint, clientRuntime);
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        throw new NotSupportedException ("Due to the lack of ClientRuntime.Operations, Silverlight cannot support this binding.");
 #else
                        foreach (ClientOperation oper in clientRuntime.Operations) {
@@ -118,6 +118,7 @@ namespace System.ServiceModel.Description
                {
                        endpointDispatcher.DispatchRuntime.OperationSelector = GetOperationSelector (endpoint);
                        // FIXME: get HostNameComparisonMode from WebHttpBinding by some means.
+                       endpointDispatcher.FilterPriority = 1; // It is to take higher priority than that of ServiceMetadataExtension (whose URL likely conflicts with this one).
                        endpointDispatcher.AddressFilter = new PrefixEndpointAddressMessageFilter (endpoint.Address);
                        endpointDispatcher.ContractFilter = new MatchAllMessageFilter ();
                        AddServerErrorHandlers (endpoint, endpointDispatcher);
index 8c770f141e19a925a6a0faaffcee856fce2552ee..e99209a6f13be4c03cc00fb8b4faf26d10e73762 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * WebMessageFormatter.cs: use MOONLIGHT symbol to
+       disambiguate MonoTouch and Moonlight code.
+
 2009-10-23  Atsushi Enomoto  <atsushi@ximian.com>
 
        * JsonQueryStringConverter.cs
index 0eefabf073d755ef8116edb70ab15cc0a7f4199e..ba802e34c03f25d2d796988115b5910655f8fc9a 100644 (file)
@@ -158,7 +158,7 @@ namespace System.ServiceModel.Description
                                break;
                        case WebContentFormat.Json:
                                // FIXME: after name argument they are hack
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                                if (IsResponseBodyWrapped)
                                        return GetSerializer (ref json_serializer, p => new DataContractJsonSerializer (p.Type, BodyName ?? p.Name, null, 0x100000, false, null, true));
                                else
index 72b72095aaba4d1c0f9e2a1013836e2bf31e19e8..0b7aa1e74fde7687e2cf3765ca64ff231fbc6b53 100644 (file)
@@ -1,3 +1,8 @@
+2010-04-05  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * DataContractJsonSerializerTest.cs : don't use ToUniversalTime()
+         which makes test results timezone dependent.
+
 2010-03-10  Atsushi Enomoto  <atsushi@ximian.com>
 
        * DataContractJsonSerializerTest.cs : oops, the test was careless.
index e6ba1c108c2dcc2348412cf06f215e259084ae06..a6e09f9d1598a6a5692bb98b4d8b66842612b449 100644 (file)
@@ -1349,11 +1349,11 @@ 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).ToUniversalTime (),
-                               EndDate = new DateTime (2010, 4, 5, 6, 7, 8).ToUniversalTime ()
+                               StartDate = new DateTime (2010, 3, 4, 5, 6, 7),
+                               EndDate = new DateTime (2010, 4, 5, 6, 7, 8)
                                };
                        serializer.WriteObject (ms, query);
-                       Assert.AreEqual ("{\"StartDate\":\"\\/Date(1267646767000)\\/\",\"EndDate\":\"\\/Date(1270415228000)\\/\"}", Encoding.UTF8.GetString (ms.ToArray ()), "#1");
+                       Assert.AreEqual ("{\"StartDate\":\"\\/Date(1267679167000)\\/\",\"EndDate\":\"\\/Date(1270447628000)\\/\"}", Encoding.UTF8.GetString (ms.ToArray ()), "#1");
                        ms.Position = 0;
                        Console.WriteLine (new StreamReader (ms).ReadToEnd ());
                        ms.Position = 0;
index ae726bc6b951d234d1aafc80d185f2f51724a5c1..04dbe4f9bd70b8f571c93fa6bede68d9d4f9cc90 100644 (file)
@@ -37,8 +37,3 @@ System.ServiceModel.Web/WebServiceHost.cs
 System.ServiceModel/WebHttpBinding.cs
 System.ServiceModel/WebHttpSecurity.cs
 System.ServiceModel/WebHttpSecurityMode.cs
-System/UriTemplate.cs
-System/UriTemplateEquivalenceComparer.cs
-System/UriTemplateMatch.cs
-System/UriTemplateMatchException.cs
-System/UriTemplateTable.cs
diff --git a/mcs/class/System.ServiceModel.Web/moonlight_raw_System.ServiceModel.Web.dll.sources b/mcs/class/System.ServiceModel.Web/moonlight_raw_System.ServiceModel.Web.dll.sources
new file mode 100644 (file)
index 0000000..07c6038
--- /dev/null
@@ -0,0 +1,12 @@
+Assembly/AssemblyInfo.cs
+System.Runtime.Serialization.Json/DataContractJsonSerializer_2_1.cs
+System.Runtime.Serialization.Json/IXmlJsonReaderInitializer.cs
+System.Runtime.Serialization.Json/IXmlJsonWriterInitializer.cs
+System.Runtime.Serialization.Json/JavaScriptObjectDeserializer.cs
+System.Runtime.Serialization.Json/JavaScriptReader.cs
+System.Runtime.Serialization.Json/JsonReader.cs
+System.Runtime.Serialization.Json/JsonReaderWriterFactory.cs
+System.Runtime.Serialization.Json/JsonSerializationReader.cs
+System.Runtime.Serialization.Json/JsonSerializationWriter.cs
+System.Runtime.Serialization.Json/JsonWriter.cs
+System.Runtime.Serialization.Json/TypeMap.cs
index 27493ec82015c07487c19a064eaf5d3f222fc23d..effcff77237905f5b0f1423c6010f7c07f6391c9 100644 (file)
@@ -46,3 +46,8 @@ System.ServiceModel.Syndication/TextSyndicationContentKind.cs
 System.ServiceModel.Syndication/UrlSyndicationContent.cs
 System.ServiceModel.Syndication/Workspace.cs
 System.ServiceModel.Syndication/XmlSyndicationContent.cs
+System/UriTemplate.cs
+System/UriTemplateEquivalenceComparer.cs
+System/UriTemplateMatch.cs
+System/UriTemplateMatchException.cs
+System/UriTemplateTable.cs
diff --git a/mcs/class/System.ServiceModel.Web/net_2_1_raw_System.ServiceModel.Web.dll.sources b/mcs/class/System.ServiceModel.Web/net_2_1_raw_System.ServiceModel.Web.dll.sources
deleted file mode 100644 (file)
index 07c6038..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-Assembly/AssemblyInfo.cs
-System.Runtime.Serialization.Json/DataContractJsonSerializer_2_1.cs
-System.Runtime.Serialization.Json/IXmlJsonReaderInitializer.cs
-System.Runtime.Serialization.Json/IXmlJsonWriterInitializer.cs
-System.Runtime.Serialization.Json/JavaScriptObjectDeserializer.cs
-System.Runtime.Serialization.Json/JavaScriptReader.cs
-System.Runtime.Serialization.Json/JsonReader.cs
-System.Runtime.Serialization.Json/JsonReaderWriterFactory.cs
-System.Runtime.Serialization.Json/JsonSerializationReader.cs
-System.Runtime.Serialization.Json/JsonSerializationWriter.cs
-System.Runtime.Serialization.Json/JsonWriter.cs
-System.Runtime.Serialization.Json/TypeMap.cs
index d2293ebdb7c2ff24e16559d4e2524d4d77289466..0bb3d5ac1c3d0912c2ac7fa6577128a1619b4f91 100755 (executable)
@@ -1,3 +1,63 @@
+2010-04-23  Astushi Enomoto  <atsushi@ximian.com>
+
+       * Http_listener_notes.txt: update comment, as I have fixed one issue
+         with lengthy explanation.
+
+2010-04-21  Astushi Enomoto  <atsushi@ximian.com>
+
+       * Http_listener_notes.txt: more comment.
+
+2010-04-20  Astushi Enomoto  <atsushi@ximian.com>
+
+       * Http_listener_notes.txt: added explanation on *why* it is SO hard
+         to solve.
+
+2010-04-05  Astushi Enomoto  <atsushi@ximian.com>
+
+       * System.ServiceModel.dll.sources : add some new config types and
+         ChannelTerminatedException.cs.
+
+2010-04-02  Astushi Enomoto  <atsushi@ximian.com>
+
+       * System.ServiceModel_test.dll.sources : add some new fault tests.
+
+2010-03-24  Astushi Enomoto  <atsushi@ximian.com>
+
+       * System.ServiceModel.dll.sources : move back all the Features tests
+         that were once disabled (now we can handle mannerless tests).
+
+2010-03-19  Astushi Enomoto  <atsushi@ximian.com>
+
+       * System.ServiceModel.dll.sources : remove unused class.
+       * HTTP_listener_notes.txt : add some more comments.
+
+2010-03-18  Astushi Enomoto  <atsushi@ximian.com>
+
+       * System.ServiceModel_test.dll.sources :
+         Add Constants.cs and XPathMessageContextTest.cs.
+
+2010-03-18  Astushi Enomoto  <atsushi@ximian.com>
+
+       * System.ServiceModel.dll.sources : added some missing types.
+
+2010-03-17  Astushi Enomoto  <atsushi@ximian.com>
+
+       * System.ServiceModel_test.dll.sources :
+         add MetadataExchangeBindingsTest.cs.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * net_2_1_*.dll.sources: rename to moonlight_*.dll.sources.
+
+2010-03-15  Astushi Enomoto  <atsushi@ximian.com>
+
+       * net_4_0_System.ServiceModel.dll.sources:
+         more types from Sys.SM.Web.dll in 4.0 profile here.
+
+2010-03-15  Astushi Enomoto  <atsushi@ximian.com>
+
+       * Dummy_2_1.cs : added cosmetic silverlight sdk compatibility stuff.
+
 2010-03-11  Astushi Enomoto  <atsushi@ximian.com>
 
        * System.ServiceModel.dll.sources,
index a3aa98d78e4c578a4fbd71b2e6155dcb9000f612..4c90120ed87cf2259e6012161a40487f3bf5b491 100644 (file)
@@ -1,3 +1,4 @@
+using System.Reflection;
 using System.Runtime.Serialization;
 
 namespace System.ServiceModel
@@ -7,6 +8,19 @@ namespace System.ServiceModel
        {
                public InstanceContext (object dummy) {}
        }
+       // introduced for silverlight sdk compatibility
+       internal class OperationFormatStyleHelper
+       {
+               public static bool IsDefined (OperationFormatStyle style)
+               {
+                       switch (style) {
+                       case OperationFormatStyle.Document:
+                       case OperationFormatStyle.Rpc:
+                               return true;
+                       }
+                       return false;
+               }
+       }
 }
 namespace System.ServiceModel.Channels
 {
@@ -23,6 +37,41 @@ namespace System.ServiceModel.Description
        public interface IWsdlExportExtension {}
        public interface IWsdlImportExtension {}
        public interface IContractBehavior {}
+
+       // introduced for silverlight sdk compatibility
+       internal class ServiceReflector
+       {
+               public static T GetSingleAttribute<T> (ICustomAttributeProvider p, Type [] types)
+               {
+                       T ret = default (T);
+                       foreach (Type t in types) {
+                               foreach (object att in p.GetCustomAttributes (t, false)) {
+                                       if (att is T) {
+                                               if (ret != null)
+                                                       throw new InvalidOperationException (String.Format ("More than one {0} attributes are found in the argument types", typeof (T)));
+                                               ret = (T) att;
+                                       }
+                               }
+                       }
+                       return ret;
+               }
+       }
+}
+namespace System.ServiceModel.DiagnosticUtility
+{
+       // introduced for silverlight sdk compatibility
+       internal class ExceptionUtility
+       {
+               public static Exception ThrowHelperError (Exception error)
+               {
+                       return error;
+               }
+
+               public static Exception ThrowHelperArgumentNull (string arg)
+               {
+                       return new ArgumentNullException (arg);
+               }
+       }
 }
 namespace System.ServiceModel.Dispatcher
 {
index 0a04e518873466d447db72115fd48852a3ee0d70..54374d7a5de6d3c09e2b44515fd6a3fae2551c12 100644 (file)
@@ -11,10 +11,11 @@ This mostly explains what our WCF does, and does not explain what I think it rea
 -- IChannelListener only has methods for receiving requests that must be explicitly invoked for each request (i.e. to repeatedly process requests it must invoke receiver methods every time, unlike ServiceHost.Open() method).
 - Inside the service loop, IChannelListener invokes [Begin]AcceptChannel() to get a channel such as HttpSimpleReplyChannel`1 or AspNetReplyChannel`1. Channels can be created as much as the service throttle limitation (ServiceThrottle) allows.
 - Then the loop manager invokes the channel's [Begin]TryReceiveRequest().
-- When WSDLs are enabled, ServiceMetadataExtension populates another ChannelDispatcher that serves HTTP requests to WSDLs.
--- It is important to understand that during this process it populates HTTP channel listener onto the same port and even possibly onto the same target URL, differentiating only by the request parameter (e.g. "?wsdl"). This causes a lot of confusion on both IHttpHandler (for ASP.NET) and HttpListener (for non-ASP.NET).
+- When WSDLs are enabled, ServiceMetadataExtension populates another ChannelDispatcher (yes, not just an EndpointDispatcher) that serves HTTP requests to WSDLs.
+-- It is important to understand that during this process it populates HTTP channel listener onto the *same* port and even possibly onto the same target URL, differentiating only by the request parameter (e.g. "?wsdl"). This causes a lot of confusion on both IHttpHandler (for ASP.NET) and HttpListener (for non-ASP.NET).
 - Inside (abstract) HttpChannelListener`1, it internally has (abstract) HttpListenerManager which manages the actual HTTP listeners.
 -- This intermediate stuff is required to manage HTTP listeners across the actual HttpChannelListeners because more than one channel listeners might use the identical HTTP listener; only one HttpListener can listen to a specific URI prefix, while (as explained above) WSDL support dispatcher may listen to the same URI only differentiating the query parameter.
+- While building ChannelDispatcher inside ServiceHostBase, we have a tricky code that sets ChannelDispatcher to HttpChannelListener. It is to make sure to apply ServiceMetadataExtension to the listener internals. Without that info, it is not possible to handle wsdl requests precisely (or if you have any simpler idea to achieve this safely, we would glad to hear it).
 
 
 ** non-ASP.NET-specific process flow
@@ -47,10 +48,22 @@ This mostly explains what our WCF does, and does not explain what I think it rea
 locking: TBD
 
 
+** Some notes
+
+- WebHttpBinding creates HTTP channel listeners that share an identical endpoint URI, which could also be mapped by ServiceMetadataExtension. It brings problem on dispatching HTTP request to correct listener. FilterPriority is used to resolve the issue (possibly to some extent) that requests to wsdl/mex are treated in lower priority.
+- While multiple channel dispatchers' endpoints could indicate an identical HTTP URI, it is not allowed to use the same HTTP URI across more than one ServiceHostBase and attempt to create such endpoints will result in InvalidOperationException for conflict with existing listeners.
+- Actually, .NET seems to reject duplicate listen URI at HttpChannelListener level (precisely to say, equivalent to that of mono, ones from HttpTransportBindingElement.BuildChannelListener()). We don't reject that (bug).
+
+
 ** Bugs
 
 There is not a few bugs on service implementations and there often are reasons:
 
 -- TCP duplex channels used to fail to serve requests when the throttle is 1. It was due to failure in managing closed channels (while it is duplex and hence it has to maintain channels until it is explicitly closed, clients often, or mostly, disconnects without any notice. So it had to be changed to explicitly check if the connection is available at any beginning of the request processing).
--- When there is more than one endpoint definition in web.config, it somehow fails to build appropriate HttpHandler chain (bug #573795).
+-- If there are more than one endpoint with the identical listen URI, it will fail to dispatch requests to correct listener even if the endpoints have appropriately configured FilterPriority. part of bug #573795.
 - ASP.NET listener ends up to dump ThreadAbort during its shutdown. It's mostly harmless though.
+
+** Required changes
+
+- HttpChannelListeners (Simple-, AspNet-) need an owner ChannelDispatcher. It has to be set probably at ICommunicationObject.Opening event.
+- After having ChannelDispatcher to manage a HttpChannelListener for each endpoint URI (create new or reuse), the listener has to differentiate HTTP requests to an appropriate channel, by EndpointDispatcher.FilterPriority.
index a090d8cc0da3713355d046d789599ab81a3cbe90..6bb0e3c915b5a1ca3dd02b389b795004d134e006 100755 (executable)
@@ -31,7 +31,7 @@ LIB_MCS_FLAGS += /d:NET_3_0   \
                        /r:Mono.Security.dll
 endif
 
-ifeq (net_2_1_raw, $(PROFILE))
+ifeq (moonlight_raw, $(PROFILE))
 LIB_MCS_FLAGS += /r:System.Net
 endif
 
index 6b45f5d4ced45b9bc51467273151fc53b25d6ffa..1983e3a91e2e606bac5d76817da3dd2cd7ba4436 100644 (file)
@@ -34,24 +34,29 @@ namespace System.ServiceModel.Channels
        {
                string name;
                string address;
+               string fault_ns;
 
-               AddressingVersion (string name, string address)
+               AddressingVersion (string name, string address, string faultNS)
                {
                        this.name = name;
                        this.address = address;
+                       this.fault_ns = faultNS;
                }
 
                static AddressingVersion addressing200408 = new AddressingVersion (
                        "Addressing200408",
-                       "http://schemas.xmlsoap.org/ws/2004/08/addressing");
+                       "http://schemas.xmlsoap.org/ws/2004/08/addressing",
+                       "http://schemas.xmlsoap.org/ws/2004/08/addressing/fault");
 
                static AddressingVersion addressing1_0 = new AddressingVersion (
                        "Addressing10",
-                       "http://www.w3.org/2005/08/addressing");
+                       "http://www.w3.org/2005/08/addressing",
+                       "http://www.w3.org/2005/08/addressing/fault");
 
                static AddressingVersion none = new AddressingVersion (
                        "AddressingNone",
-                       "http://schemas.microsoft.com/ws/2005/05/addressing/none");
+                       "http://schemas.microsoft.com/ws/2005/05/addressing/none",
+                       null);
 
                public static AddressingVersion WSAddressing10 {
                        get { return addressing1_0; }
@@ -69,6 +74,10 @@ namespace System.ServiceModel.Channels
                        get { return address; }
                }
 
+               internal string FaultNamespace {
+                       get { return fault_ns; }
+               }
+
                internal string ActionNotSupported {
                        get { return "ActionNotSupported"; }
                }
index 75cf52ce010905483037ed1489643c0317ea7fc4..8b083f5e9847f3d5eb19f145ae39ee9a6ade9558 100644 (file)
@@ -54,7 +54,7 @@ namespace System.ServiceModel.Channels
                        if (http_context == null)
                                return;
                        try {
-                               listener.HttpHandler.EndRequest (listener, http_context);
+                               ((AspNetListenerManager) listener.ListenerManager).HttpHandler.EndRequest (listener, http_context);
                        } finally {
                                http_context = null;
                        }
@@ -65,7 +65,7 @@ namespace System.ServiceModel.Channels
                        lock (waiting)
                                foreach (HttpContext ctx in waiting)
                                        try {
-                                               listener.HttpHandler.EndRequest (listener, ctx);
+                                               ((AspNetListenerManager) listener.ListenerManager).HttpHandler.EndRequest (listener, ctx);
                                        } catch {
                                        }
                }
index 9cbb4bf3c5812f05c5adee308633377e650b190f..59bf2bbcbca05e200cfbf9c1d0496c275717bd63 100644 (file)
@@ -74,6 +74,8 @@ namespace System.ServiceModel.Channels {
                                if (hp.SuppressEntityBody)
                                        suppressEntityBody = true;
                        }
+                       if (msg.IsFault)
+                               ctx.Response.StatusCode = 500;
                        if (!suppressEntityBody) {
                                ctx.Response.AddHeader ("Content-Length", ms.Length.ToString (CultureInfo.InvariantCulture));
                                ctx.Response.OutputStream.Write (ms.GetBuffer (), 0, (int) ms.Length);
index 1dac543ba51fb0136abe4be34486ae5316befa53..8a051867f5963bea30c2b816843e41e47a3d158b 100644 (file)
@@ -155,7 +155,10 @@ namespace System.ServiceModel.Channels
                {
                        bool restore = PrepareElements ();
                        try {
-                               return DequeueBindingElement ().BuildChannelListener<TChannel> (this);
+                               var be = DequeueBindingElement (false);
+                               if (be == null)
+                                       throw new InvalidOperationException ("There is likely no TransportBindingElement that can build a channel listener in this binding context");
+                               return be.BuildChannelListener<TChannel> (this);
                        } finally {
                                if (restore)
                                        elements = empty_collection;
@@ -181,8 +184,10 @@ namespace System.ServiceModel.Channels
                {
                        bool restore = PrepareElements ();
                        try {
-                               return elements.Count > 0 &&
-                                       DequeueBindingElement ().CanBuildChannelListener<TChannel> (this);
+                               var be = DequeueBindingElement (false);
+                               if (be == null)
+                                       throw new InvalidOperationException ("There is likely no TransportBindingElement that can build a channel listener in this binding context");
+                               return be.CanBuildChannelListener<TChannel> (this);
                        } finally {
                                if (restore)
                                        elements = empty_collection;
index 7fbcdcebc540a33478a057206f0678bd932c5e59..1f9cf98f7b4abaece7bedc9d6132d58b2db5aabb 100644 (file)
@@ -57,7 +57,6 @@ namespace System.ServiceModel.Channels
                        OnWriteBodyContents (writer);
                }
 
-               [MonoTODO ("use maxBufferSize somewhere")]
                protected virtual BodyWriter OnCreateBufferedCopy (
                        int maxBufferSize)
                {
@@ -67,10 +66,33 @@ namespace System.ServiceModel.Channels
                        StringWriter sw = new StringWriter ();
                        using (XmlDictionaryWriter w = XmlDictionaryWriter.CreateDictionaryWriter (XmlWriter.Create (sw, s)))
                                WriteBodyContents (w);
-                       return new XmlReaderBodyWriter (sw.ToString ());
+                       var xml = sw.ToString ();
+                       if (xml.Length > 0)
+                               return new XmlReaderBodyWriter (xml, maxBufferSize, null);
+                       else
+                               return new EmptyBodyWriter ();
                }
 
                protected abstract void OnWriteBodyContents (
                        XmlDictionaryWriter writer);
+
+               class EmptyBodyWriter : BodyWriter
+               {
+                       public EmptyBodyWriter ()
+                               : base (true)
+                       {
+                       }
+
+                       protected override BodyWriter OnCreateBufferedCopy (
+                               int maxBufferSize)
+                       {
+                               return new EmptyBodyWriter ();
+                       }
+
+                       protected override void OnWriteBodyContents (XmlDictionaryWriter writer)
+                       {
+                               // nothing to do
+                       }
+               }
        }
 }
index 9078b9d1cdd368e02a8b65c222577d42b1791466..ae295d08b0ae930f88dd87961ac223d617294bdb 100644 (file)
@@ -1,9 +1,38 @@
 //
-// BufferManager.cs
+// BufferManager.cs:
+//    This class suffers from an engineering problem in its
+//    design: when this API is used to limit the total pool
+//    size it will throw, but no user code is designed to
+//    cope with that.
 //
-// Author: Atsushi Enomoto (atsushi@ximian.com)
+//    Instead of the Microsoft strategy, we allow allocation
+//    to go as far as it wants to go and merely allow this
+//    to be a pool that can be used recycle buffers.
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+//    This still gives us the main benefit of this class, while
+//    avoiding the potential crashing scenarios and simplifies
+//    the implementation significantly from what has been
+//    document in the blogosphere.
+//
+//    There are a few problems: for example, if we do not find
+//    a buffer of the proper size in the expected slot, say
+//    a 31k buffer in the slot for [32k-64k] values, we will
+//    allocate a new buffer, even if there might have been a
+//    buffer for 128k.
+//
+// A few considerations:
+//
+//    The size of an empty array is either 16 on 32 bit systems
+//    and 32 bytes in 64 bit systems.
+//
+//    We take this information into account for the minimum allocation
+//    pools.
+//
+// Authors:
+//   Atsushi Enomoto (atsushi@ximian.com)
+//   Miguel de Icaza (miguel@gnome.org)
+//
+// Copyright (C) 2005, 2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -25,6 +54,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 using System;
+using System.Collections.Generic;
 using System.IO;
 using System.Collections.ObjectModel;
 using System.ServiceModel;
@@ -39,26 +69,71 @@ namespace System.ServiceModel.Channels
 
                public abstract void Clear ();
 
-               [MonoTODO]
                public static BufferManager CreateBufferManager (
                        long maxBufferPoolSize, int maxBufferSize)
                {
-                       return new DefaultBufferManager (maxBufferPoolSize,
-                               maxBufferSize);
+                       return new DefaultBufferManager (maxBufferPoolSize, maxBufferSize);
                }
 
                public abstract void ReturnBuffer (byte[] buffer);
 
                public abstract byte[] TakeBuffer (int bufferSize);
 
+#if DEBUG_BUFFER
+               internal abstract void DumpStats ();
+#endif
+               
                class DefaultBufferManager : BufferManager
                {
+                       const int log_min = 5;   // Anything smaller than 1 << log_cut goes into the first bucket
                        long max_pool_size;
                        int max_size;
-                       byte [] buffer;
+                       List<byte []> [] buffers = new List<byte []> [32-log_min];
 
-                       public DefaultBufferManager (long maxBufferPoolSize,
-                               int maxBufferSize)
+#if DEBUG_BUFFER
+                       internal override void DumpStats ()
+                       {
+                               Console.WriteLine ("- hit={0} miss={1}-", hits, miss);
+                               for (int i = 0; i < buffers.Length; i++){
+                                       if (buffers [i] == null)
+                                               continue;
+                                       
+                                       Console.Write ("Slot {0} - {1} [", i, buffers [i].Count);
+                                       byte [][] arr = buffers [i].ToArray ();
+                                       
+                                       for (int j = 0; j < Math.Min (3, arr.Length); j++)
+                                               Console.Write ("{0} ", arr [j].Length);
+                                       Console.WriteLine ("]");
+                               }
+                       }
+#endif
+                       
+                       static int log2 (uint n)
+                       {
+                               int pos = 0;
+                               if (n >= 1<<16) {
+                                       n >>= 16;
+                                       pos += 16;
+                               }
+                               if (n >= 1<< 8) {
+                                       n >>=  8;
+                                       pos +=  8;
+                               }
+                               if (n >= 1<< 4) {
+                                       n >>=  4;
+                                       pos +=  4;
+                               }
+                               if (n >= 1<< 2) {
+                                       n >>=  2;
+                                       pos +=  2;
+                               }
+                               if (n >= 1<< 1) 
+                                       pos +=  1;
+
+                               return ((n == 0) ? (-1) : pos);
+                       }
+                       
+                       public DefaultBufferManager (long maxBufferPoolSize, int maxBufferSize)
                        {
                                this.max_pool_size = maxBufferPoolSize;
                                this.max_size = maxBufferSize;
@@ -66,28 +141,85 @@ namespace System.ServiceModel.Channels
 
                        public override void Clear ()
                        {
-                               if (buffer != null)
-                                       Array.Clear (buffer, 0, buffer.Length);
+                               foreach (var stack in buffers){
+                                       if (stack == null)
+                                               continue;
+                                       stack.Clear ();
+                               }
+                               Array.Clear (buffers, 0, buffers.Length);
                        }
 
                        public override void ReturnBuffer (byte [] buffer)
                        {
-                               // is this correct?
-
-                               if (this.buffer == null)
+                               if (buffer == null)
                                        return;
-                               Array.Copy (this.buffer, buffer, this.buffer.Length);
+
+                               uint size = (uint) buffer.Length;
+                               int l2 = log2 (size);
+                               if (l2 > log_min)
+                                       l2 -= log_min;
+
+                               List<byte []> returned = buffers [l2];
+                               if (returned == null)
+                                       returned = buffers [l2] = new List<byte []> ();
+
+                               returned.Add (buffer);
                        }
 
+                       int hits, miss;
+                       
                        public override byte [] TakeBuffer (int bufferSize)
                        {
-                               if (bufferSize > max_size)
+                               if (bufferSize < 0 || (max_size >= 0 && bufferSize > max_size))
                                        throw new ArgumentOutOfRangeException ();
 
-                               if (buffer == null || buffer.Length < bufferSize)
-                                       buffer = new byte [bufferSize];
-                               return buffer;
+                               int l2 = log2 ((uint) bufferSize);
+                               if (l2 > log_min)
+                                       l2 -= log_min;
+
+                               List<byte []> returned = buffers [l2];
+                               if (returned == null || returned.Count == 0)
+                                       return new byte [bufferSize];
+                               
+                               foreach (var e in returned){
+                                       if (e.Length >= bufferSize){
+                                               hits++;
+                                               returned.Remove (e);
+                                               return e;
+                                       }
+                               }
+                               return new byte [bufferSize];
+                       }
+               }
+       }
+
+#if DEBUG_BUFFER
+       class Foo {
+               static void Main ()
+               {
+                       var a = BufferManager.CreateBufferManager (1024*1024, 1024*1024);
+                       var rand = new Random (0);
+                       
+                       var buffs = new List<byte []> ();
+                       for (int i = 0; i < 4096; i++){
+                               a.DumpStats ();
+                               var request = rand.Next (1,1024*1024);
+                               if ((i % 2) == 0)
+                                       request = rand.Next (1024, 4096);
+                               
+                               var x = a.TakeBuffer (request);
+                               if (x.Length < request)
+                                       throw new Exception ();
+                               Console.WriteLine ("Delta={2} Requested {0} got={1} bytes ", request, x.Length, x.Length-request);
+                               if ((i % 3) == 0){
+                                       Console.WriteLine ("Return: {0}", x.Length);
+                                       a.ReturnBuffer (x);
+                               }
+                               else
+                                       buffs.Add (x);
                        }
+                       a.DumpStats ();
                }
        }
-}
+#endif
+}
\ No newline at end of file
index 863e71e8d3852c0ad9c274c1079b7331da285cb1..db7b6625f1856eaf04ef9f226cbc695a358ad44c 100755 (executable)
@@ -1,3 +1,223 @@
+2010-04-23  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * HttpListenerManager.cs : fixed the issue that mex_info is never
+         retrieved from the latest channel listener (which could be other
+         listener than the one which was set mex info).
+
+2010-04-23  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * HttpChannelListener.cs, HttpListenerManager.cs :
+         actually it should be ChannelDispatcher-to-HttpChannelListener,
+         to identify which dispatcher to send reqs.
+
+2010-04-23  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * HttpReplyChannel.cs : remove old Http Keep-Alive workaround.
+
+2010-04-23  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * HttpTransportBindingElement.cs,
+         HttpChannelListener.cs,
+         HttpListenerManager.cs : add host-to-http-listener mapping so that
+         they can be managed per host.
+
+2010-04-21  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * BindingContext.cs : require a TransportBindingElement when
+         building a channel listener.
+
+2010-04-19  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * HttpReplyChannel.cs : use local var to hold wait handle to avoid
+         possible NRE on field. Based on the patch by Matt Dargavel.
+
+2010-04-07  Miguel de Icaza  <miguel@novell.com>
+
+       *  BufferManager.cs: Implement the BufferManager. 
+
+2010-04-07  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * WSSecurityMessageHeader.cs : add FIXME comment.
+
+2010-04-06  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * HttpRequestChannel.cs : add commented note.
+
+2010-04-06  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * HttpReplyChannel.cs : fill To header only if it does not exist.
+
+2010-04-06  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * SecureMessageGenerator.cs : set ReplyTo and To, do not add.
+
+2010-04-06  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * MessageHeaders.cs : use matching addressing version.
+         Remove header item if the same ones already exist.
+
+2010-04-06 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * HttpRequestChannel.cs: don't create the wait handle unless it is
+       really needed.
+
+2010-04-02  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * HttpRequestChannel.cs : use correct max buffer size.
+
+2010-04-02  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * MessageFault.cs : check null serializer and detail.
+         Make sure to consume s12:Reason EndElement.
+
+2010-04-02  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * MessageFault.cs : when created from XmlReader, it should not
+         deserialize fault details immediately. This class itself should
+         not do that. Strongly typed FaultContractInfo may want to use the
+         reader (GetReaderAtDetailContents()) for its own deserialization.
+
+2010-04-01  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ConnectionOrientedTransportBindingElement.cs,
+         TcpTransportBindingElement.cs : implement GetProperty<T>().
+
+2010-04-01  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * HttpTransportBindingElement.cs, HttpsTransportBindingElement.cs:
+         implement HttpsTransportBindingElement.GetProperty<T>(). Extend the
+         properties type from HTTP.
+
+2010-04-01  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * FaultConverter.cs : use addressing version from the message.
+
+2010-03-30  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * FaultConverter.cs : check envelope version, not addressing version.
+
+2010-03-29  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * FaultConverter.cs : implemented TryCreateException().
+
+2010-03-29  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * MessageFault.cs : cosmetic method name clarification.
+
+2010-03-29  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XmlReaderBodyWriter.cs, Message.cs, MessageImpl.cs, BodyWriter.cs:
+         fix BodyWriter buffering that dropped in-scope namespaces and thus
+         caused problem on resolving QNames.
+
+2010-03-26  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * FaultConverter.cs : do implement OnTryCreateFaultMessage() to work
+         with certain Exception types.
+
+2010-03-26  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * Message.cs : fix explanation on CreateMessage() overloads.
+
+2010-03-26  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * MessageFault.cs : Write Subcode element correctly and fix wrong
+         Code/Value/Subcode element relationship. Give better error message.
+
+2010-03-26  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * HttpRequestChannel.cs : ok, no need for conditional code path.
+
+2010-03-26  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * AddressingVersion.cs : add fault action namespace.
+
+2010-03-26  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * HttpRequestChannel.cs: There is no WebHeaderCollection.Add 
+       method in SL API
+
+2010-03-26  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * MessageImpl.cs : pass IsFault argument in OnCreateBufferedCopy().
+
+2010-03-26  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * HttpRequestContext.cs, AspNetRequestContext.cs : return HTTP 500
+         for fault message.
+
+2010-03-26  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * HttpRequestChannel.cs : create HttpResponseMessageProperty.
+
+2010-03-25  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * HttpRequestContext.cs : removed HTTP status rewriting for
+         commented reason.
+
+2010-03-25  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * HttpRequestChannel.cs : handle only 4xx errors as to not process
+         content stream.
+
+2010-03-25  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * MessageFault.cs : do not use SOAP11 namespace for fault contents.
+
+2010-03-24  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ReplyChannelBase.cs, HttpReplyChannel.cs : add some locking.
+         Patch by Matt Dargavel.
+
+2010-03-24  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * HttpListenerManager.cs : use lock object which is subject to
+         change. Fix by Matt Dargavel.
+
+2010-03-24  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * HttpListenerManager.cs : remove consumed HttpListenerContext from
+         the pending queue. Compare "wsdl" request in case insensitive
+         manner. Patch by Matt Dargavel.
+
+2010-03-24  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * HttpRequestContext.cs : apply the patch by Matt Dargavel, which is
+         supposed to provide detailed 400 error message.
+
+2010-03-24  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * TransactionFlowBindingElement.cs: revamp the previous change to
+         not regress regarding service metadata.
+
+2010-03-24  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ChannelListenerBase.cs, TransactionFlowBindingElement.cs: fix 
+         GetProperty<T>() bug that fails to retrieve properties. (This may
+         be rewritten later if an ongoing change proposal is to take place.)
+
+2010-03-18  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ReliableSessionBindingElement.cs,
+         PrivacyNoticeBindingElement.cs,
+         RemoteEndpointMessageProperty.cs : added some missing types.
+
+2010-03-17  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * MessageHeaders.cs :
+         why does it filter out most of the headers? kill it.
+
+2010-03-17  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * SvcHttpHandler.cs, AspNetReplyChannel.cs, HttpChannelListener.cs,
+         HttpListenerManager.cs : refactoring on acquiring SvcHttpHandler
+         to not raise "not found" error (see bug #573795).
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * HttpRequestChannel.cs, HttpTransportBindingElement.cs: use
+       MOONLIGHT symbol to disambiguate MonoTouch and Moonlight code.
+
 2010-03-09  Atsushi Enomoto  <atsushi@ximian.com>
 
        * HttpListenerManager.cs : For ASP.NET, use correct GenericIdentity
index 1d3042b49ed2a0230438e0fba1103dbbfcb4c878..a932f68bf348da222ef7e9e11a30458276b3175a 100644 (file)
@@ -84,7 +84,7 @@ namespace System.ServiceModel.Channels
                        get { return timeouts.SendTimeout; }
                }
 
-               internal KeyedByTypeCollection<object> Properties {
+               internal virtual KeyedByTypeCollection<object> Properties {
                        get {
                                if (properties == null)
                                        properties = new KeyedByTypeCollection<object> ();
index 5d6024b705fecf7f531ae9fcee4f9063533bf654..8aa13507d131fe209aefbb71da3ff200d1c66fea 100644 (file)
@@ -128,5 +128,13 @@ namespace System.ServiceModel.Channels
                        }
                        return false;
                }
+
+               public override T GetProperty<T> (BindingContext context)
+               {
+                       // since this class cannot be derived (internal .ctor
+                       // only), we cannot examine what this should do.
+                       // So, handle all properties in the derived types.
+                       return base.GetProperty<T> (context);
+               }
        }
 }
index ef383290328b77c80c85f829902beec3b5d6dfec..d77e34153d77ea616844482256f0632fa82cecf9 100644 (file)
@@ -62,57 +62,93 @@ namespace System.ServiceModel.Channels
                {
                        return OnTryCreateFaultMessage (error, out message);
                }
+       }
 
-               Message CreateSimpleFaultMessage (Exception error, MessageVersion version)
+       class SimpleFaultConverter : FaultConverter
+       {
+               static readonly Dictionary<Type,string> map;
+               
+               static SimpleFaultConverter ()
                {
-                       OperationContext ctx = OperationContext.Current;
-                       // FIXME: support more fault code depending on the exception type.
-                       FaultCode fc = null;
-                       if (error is EndpointNotFoundException)
-                               fc = new FaultCode (
-                                       "DestinationUnreachable",
-                                       version.Addressing.Namespace);
+                       map = new Dictionary<Type,string> ();
+                       map [typeof (EndpointNotFoundException)] = "DestinationUnreachable";
+                       map [typeof (ActionNotSupportedException)] = "ActionNotSupported";
+               }
+
+               MessageVersion version;
+
+               public SimpleFaultConverter (MessageVersion version)
+               {
+                       this.version = version;
+               }
+
+               protected override bool OnTryCreateException (
+                       Message message, MessageFault fault, out Exception error)
+               {
+                       if (message == null)
+                               throw new ArgumentNullException ("message");
+                       if (fault == null)
+                               throw new ArgumentNullException ("fault");
+
+                       error = null;
+
+                       FaultCode fc;
+                       if (version.Envelope.Equals (EnvelopeVersion.Soap11))
+                               fc = fault.Code;
                        else
-                               fc = new FaultCode (
-                                       "FIXME_InternalError",
-                                       version.Addressing.Namespace);
+                               fc = fault.Code.SubCode;
 
-#if !NET_2_1
-                       // FIXME: set correct fault reason.
-                       if (ctx.EndpointDispatcher.ChannelDispatcher.IncludeExceptionDetailInFaults) {
-                               ExceptionDetail detail = new ExceptionDetail (error);
-                               return Message.CreateMessage (version, fc,
-                                       "error occured", detail, ctx.IncomingMessageHeaders != null ? ctx.IncomingMessageHeaders.Action : null);
+                       if (fc == null)
+                               return false;
+
+                       string msg = fault.Reason.GetMatchingTranslation ().Text;
+                       if (fc.Namespace == message.Version.Addressing.Namespace) {
+                               switch (fc.Name) {
+                               case "ActionNotSupported":
+                                       error = new ActionNotSupportedException (msg);
+                                       return true;
+                               case "DestinationUnreachable":
+                                       error = new EndpointNotFoundException (msg);
+                                       return true;
+                               }
                        }
-#endif
-                       return Message.CreateMessage (version, fc, "error occured", ctx.IncomingMessageHeaders.Action);
+
+                       return false;
                }
 
-               class SimpleFaultConverter : FaultConverter
+               protected override bool OnTryCreateFaultMessage (Exception error, out Message message)
                {
-                       MessageVersion version;
-                       public SimpleFaultConverter (MessageVersion version)
-                       {
-                               this.version = version;
+                       if (version.Envelope.Equals (EnvelopeVersion.None)) {
+                               message = null;
+                               return false;
                        }
 
-                       protected override bool OnTryCreateException (
-                               Message message, MessageFault fault, out Exception error)
-                       {
-                               error = null;
+                       string action;
+                       if (!map.TryGetValue (error.GetType (), out action)) {
+                               message = null;
                                return false;
                        }
 
-                       protected override bool OnTryCreateFaultMessage (
-                               Exception error, out Message message)
-                       {
-                               message = null;
-                               if (OperationContext.Current == null)
-                                       return false;
+                       FaultCode fc;
+                       if (version.Envelope.Equals (EnvelopeVersion.Soap12))
+                               fc = new FaultCode ("Sender", version.Envelope.Namespace, new FaultCode (action, version.Addressing.Namespace));
+                       else
+                               fc = new FaultCode (action, version.Addressing.Namespace);
 
-                               message = CreateSimpleFaultMessage (error, version);
-                               return true;
+                       OperationContext ctx = OperationContext.Current;
+                       // FIXME: support more fault code depending on the exception type.
+#if !NET_2_1
+                       // FIXME: set correct fault reason.
+                       if (ctx != null && ctx.EndpointDispatcher.ChannelDispatcher.IncludeExceptionDetailInFaults) {
+                               ExceptionDetail detail = new ExceptionDetail (error);
+                               message = Message.CreateMessage (version, fc,
+                                       error.Message, detail, version.Addressing.FaultNamespace);
                        }
+                       else
+#endif
+                               message = Message.CreateMessage (version, fc, error.Message, version.Addressing.FaultNamespace);
+
+                       return true;
                }
        }
 }
index bb268417eacc146fe9316dd4206a59324d0972d1..988d431c508e8402f8023c85f9eca6361bb680ee 100644 (file)
@@ -33,6 +33,7 @@ using System.Net;
 using System.Net.Security;
 using System.ServiceModel;
 using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
 using System.ServiceModel.Security;
 using System.Text;
 
@@ -66,7 +67,7 @@ namespace System.ServiceModel.Channels
 
                protected override HttpListenerManager CreateListenerManager ()
                {
-                       return new HttpSimpleListenerManager (this, Source, SecurityTokenManager);
+                       return new HttpSimpleListenerManager (this, Source, SecurityTokenManager, ChannelDispatcher);
                }
        }
 
@@ -79,10 +80,6 @@ namespace System.ServiceModel.Channels
                {
                }
 
-               internal SvcHttpHandler HttpHandler {
-                       get { return ((AspNetListenerManager) ListenerManager).Source; }
-               }
-
                protected override TChannel CreateChannel (TimeSpan timeout)
                {
                        if (typeof (TChannel) == typeof (IReplyChannel))
@@ -93,7 +90,7 @@ namespace System.ServiceModel.Channels
 
                protected override HttpListenerManager CreateListenerManager ()
                {
-                       return new AspNetListenerManager (this, Source, SecurityTokenManager);
+                       return new AspNetListenerManager (this, Source, SecurityTokenManager, ChannelDispatcher);
                }
        }
 
@@ -104,10 +101,15 @@ namespace System.ServiceModel.Channels
                MessageEncoder encoder;
                HttpListenerManager httpChannelManager;
 
+               internal static HttpChannelListenerBase<TChannel>CurrentHttpChannelListener;
+
                public HttpChannelListenerBase (HttpTransportBindingElement source,
                        BindingContext context)
                        : base (context)
                {
+                       if (ServiceHostBase.CurrentServiceHostHack != null)
+                               DispatcherBuilder.ChannelDispatcherSetter = delegate (ChannelDispatcher cd) { this.ChannelDispatcher = cd; };
+
                        this.Source = source;
                        // The null Uri check looks weird, but it seems the listener can be built without it.
                        // See HttpTransportBindingElementTest.BuildChannelListenerWithoutListenUri().
@@ -128,6 +130,8 @@ namespace System.ServiceModel.Channels
                                SecurityTokenManager = new ServiceCredentialsSecurityTokenManager ((ServiceCredentials) context.BindingParameters [typeof (ServiceCredentials)]);
                }
 
+               internal ChannelDispatcher ChannelDispatcher { get; set; }
+
                public HttpTransportBindingElement Source { get; private set; }
 
                public HttpListenerManager ListenerManager {
index 51b1272bef92368f1cd8bbadacdb2ec9549a6d78..927ed06c85e1697e8876b41f367e4fa1e8ac04b9 100644 (file)
@@ -33,6 +33,7 @@ using System.Collections.Specialized;
 using System.IdentityModel.Selectors;
 using System.IdentityModel.Tokens;
 using System.ServiceModel.Description;
+using System.ServiceModel.Dispatcher;
 using System.ServiceModel.Security;
 using System.Security.Principal;
 using System.Text;
@@ -140,17 +141,19 @@ namespace System.ServiceModel.Channels
 
        internal class HttpSimpleListenerManager : HttpListenerManager
        {
-               static Dictionary<Uri, HttpListener> opened_listeners;
-               HttpListener http_listener;
+               static Dictionary<object,Dictionary<Uri,HttpListener>> http_listeners_table = new Dictionary<object,Dictionary<Uri,HttpListener>> ();
 
-               static HttpSimpleListenerManager ()
-               {
-                       opened_listeners = new Dictionary<Uri, HttpListener> ();
-               }
+               Dictionary<Uri, HttpListener> opened_listeners;
+               HttpListener http_listener;
 
-               public HttpSimpleListenerManager (IChannelListener channelListener, HttpTransportBindingElement source, ServiceCredentialsSecurityTokenManager securityTokenManager)
-                       : base (channelListener, source, securityTokenManager)
+               public HttpSimpleListenerManager (IChannelListener channelListener, HttpTransportBindingElement source, ServiceCredentialsSecurityTokenManager securityTokenManager, ChannelDispatcher dispatcher)
+                       : base (channelListener, source, securityTokenManager, dispatcher)
                {
+                       object key = dispatcher != null ? dispatcher.Host : new object (); // so that HttpChannelListener without ServiceHost is always assigned a new table.
+                       if (!http_listeners_table.TryGetValue (key, out opened_listeners)) {
+                               opened_listeners = new Dictionary<Uri, HttpListener> ();
+                               http_listeners_table [key] = opened_listeners;
+                       }
                }
 
                protected override void OnRegister (IChannelListener channelListener, TimeSpan timeout)
@@ -209,15 +212,13 @@ namespace System.ServiceModel.Channels
        {
                SvcHttpHandler http_handler;
 
-               public AspNetListenerManager (IChannelListener channelListener, HttpTransportBindingElement source, ServiceCredentialsSecurityTokenManager securityTokenManager)
-                       : base (channelListener, source, securityTokenManager)
+               public AspNetListenerManager (IChannelListener channelListener, HttpTransportBindingElement source, ServiceCredentialsSecurityTokenManager securityTokenManager, ChannelDispatcher dispatcher)
+                       : base (channelListener, source, securityTokenManager, dispatcher)
                {
-                       http_handler = SvcHttpHandlerFactory.GetHandlerForListener (channelListener);
+                       http_handler = SvcHttpHandler.Current;
                }
 
-               public SvcHttpHandler Source {
-                       get { return http_handler; }
-               }
+               internal SvcHttpHandler HttpHandler { get { return http_handler; } }
 
                protected override void OnRegister (IChannelListener channelListener, TimeSpan timeout)
                {
@@ -253,6 +254,7 @@ namespace System.ServiceModel.Channels
 
                public MetadataPublishingInfo MexInfo { get { return mex_info; } }
                public HttpTransportBindingElement Source { get; private set; }
+               public ChannelDispatcher Dispatcher { get; private set; }
 
                SecurityTokenAuthenticator security_token_authenticator;
                SecurityTokenResolver security_token_resolver;
@@ -262,11 +264,11 @@ namespace System.ServiceModel.Channels
                        registered_channels = new Dictionary<Uri, List<IChannelListener>> ();
                }
 
-               protected HttpListenerManager (IChannelListener channelListener, HttpTransportBindingElement source, ServiceCredentialsSecurityTokenManager securityTokenManager)
+               protected HttpListenerManager (IChannelListener channelListener, HttpTransportBindingElement source, ServiceCredentialsSecurityTokenManager securityTokenManager, ChannelDispatcher dispatcher)
                {
+                       this.Dispatcher = dispatcher;
                        this.channel_listener = channelListener;
-                       // FIXME: this cast should not be required, but current JIT somehow causes an internal error.
-                       mex_info = ((IChannelListener) channelListener).GetProperty<MetadataPublishingInfo> ();
+                       mex_info = Dispatcher.Listener.GetProperty<MetadataPublishingInfo> ();
                        wsdl_instance = mex_info != null ? mex_info.Instance : null;
                        Source = source;
 
@@ -334,6 +336,7 @@ namespace System.ServiceModel.Channels
                        lock (pending) {
                                foreach (var pctx in pending) {
                                        if (FilterHttpContext (pctx)) {
+                                               pending.Remove (pctx);
                                                callback (pctx);
                                                return;
                                        }
@@ -382,7 +385,7 @@ namespace System.ServiceModel.Channels
                                }
                        }
 
-                       lock (registered_channels) {
+                       lock (pending) {
                                pending.Add (ctx);
                                // FIXME: this should not be required, but it somehow saves some failures wrt concurrent calls.
                                Thread.Sleep (100);
@@ -406,7 +409,7 @@ namespace System.ServiceModel.Channels
                        if (wsdl_instance.WsdlUrl != null && Uri.Compare (ctx.RequestUrl, wsdl_instance.WsdlUrl, cmpflag, fmtflag, StringComparison.Ordinal) == 0) {
                                if (mex_info == null)
                                        return false; // Do not handle this at normal dispatcher.
-                               if (ctx.QueryString [null] == "wsdl")
+                               if (String.Compare (ctx.QueryString [null], "wsdl", StringComparison.OrdinalIgnoreCase) == 0)
                                        return mex_info.SupportsMex; // wsdl dispatcher should handle this.
                                if (!wsdl_instance.HelpUrl.Equals (wsdl_instance.WsdlUrl))
                                        return true; // in case help URL is not equivalent to WSDL URL, it anyways returns WSDL regardless of ?wsdl existence.
index 28a6fc7329296c3a8b450696fd7e56ea64920c01..3cf3ec29891d7e12e8ef39c421dc7891715017b2 100644 (file)
@@ -121,11 +121,6 @@ namespace System.ServiceModel.Channels
 
                        Message msg = null;
 
-                       // FIXME: our HttpConnection (under HttpListener) 
-                       // somehow breaks when the underlying connection is
-                       // reused. Remove it when it gets fixed.
-                       ctx.Response.KeepAlive = false;
-
                        if (ctx.Request.HttpMethod == "POST") {
                                if (!Encoder.IsContentTypeSupported (ctx.Request.ContentType)) {
                                        ctx.Response.StatusCode = (int) HttpStatusCode.UnsupportedMediaType;
@@ -151,16 +146,14 @@ namespace System.ServiceModel.Channels
                        } else if (ctx.Request.HttpMethod == "GET") {
                                msg = Message.CreateMessage (MessageVersion, null);
                        }
-                       msg.Headers.To = ctx.Request.Url;
+                       if (msg.Headers.To == null)
+                               msg.Headers.To = ctx.Request.Url;
                        msg.Properties.Add ("Via", LocalAddress.Uri);
                        msg.Properties.Add (HttpRequestMessageProperty.Name, CreateRequestProperty (ctx.Request.HttpMethod, ctx.Request.Url.Query, ctx.Request.Headers));
 /*
 MessageBuffer buf = msg.CreateBufferedCopy (0x10000);
 msg = buf.CreateMessage ();
-System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter (Console.Out);
-w.Formatting = System.Xml.Formatting.Indented;
-buf.CreateMessage ().WriteMessage (w);
-w.Close ();
+Console.WriteLine (buf.CreateMessage ());
 */
                        context = new HttpRequestContext (this, msg, ctx);
                        reqctx = context;
@@ -174,11 +167,10 @@ w.Close ();
                        if (wait != null)
                                throw new InvalidOperationException ("Another wait operation is in progress");
                        try {
-                               wait = new AutoResetEvent (false);
+                               var wait_ = new AutoResetEvent (false);
+                               wait = wait_;   // wait can be set to null if HttpContextAcquired runs to completion before we do WaitOne
                                source.ListenerManager.GetHttpContextAsync (timeout, HttpContextAcquired);
-                               if (wait != null) // in case callback is done before WaitOne() here.
-                                       return wait.WaitOne (timeout, false);
-                               return waiting.Count > 0;
+                               return wait_.WaitOne (timeout, false) && waiting.Count > 0;
                        } catch (HttpListenerException e) {
                                // FIXME: does this make sense? I doubt.
                                if ((uint) e.ErrorCode == 0x80004005) // invalid handle. Happens during shutdown.
@@ -197,7 +189,8 @@ w.Close ();
                                throw new InvalidOperationException ("WaitForRequest operation has not started");
                        var sctx = (HttpListenerContextInfo) ctx;
                        if (State == CommunicationState.Opened && ctx != null)
-                               waiting.Add (sctx.Source);
+                               lock (waiting)
+                                       waiting.Add (sctx.Source);
                        SignalAsyncWait ();
                }
        }
index 8e700f3c0c3c8092a708a112407d485565ab9fe5..4bae6026237252bad1bf95b9c5ccf720bea05541 100644 (file)
@@ -43,9 +43,6 @@ namespace System.ServiceModel.Channels
 
                WebRequest web_request;
 
-               // FIXME: supply maxSizeOfHeaders.
-               int max_headers = 0x10000;
-
                // Constructor
 
                public HttpRequestChannel (HttpChannelFactory<IRequestChannel> factory,
@@ -55,10 +52,6 @@ namespace System.ServiceModel.Channels
                        this.source = factory;
                }
 
-               public int MaxSizeOfHeaders {
-                       get { return max_headers; }
-               }
-
                public MessageEncoder Encoder {
                        get { return source.MessageEncoder; }
                }
@@ -93,7 +86,7 @@ namespace System.ServiceModel.Channels
                                ((HttpWebRequest) web_request).CookieContainer = cmgr.CookieContainer;
 #endif
 
-#if !NET_2_1 || MONOTOUCH // until we support NetworkCredential like SL4 will do.
+#if !MOONLIGHT // until we support NetworkCredential like SL4 will do.
                        // client authentication (while SL3 has NetworkCredential class, it is not implemented yet. So, it is non-SL only.)
                        var httpbe = (HttpTransportBindingElement) source.Transport;
                        string authType = null;
@@ -153,6 +146,13 @@ namespace System.ServiceModel.Channels
                        }
 #endif
 
+/*
+// FIXME: this causes invalid message security.
+var mb = message.CreateBufferedCopy (0x10000);
+message = mb.CreateMessage ();
+Console.WriteLine (mb.CreateMessage ());
+*/
+
                        if (!suppressEntityBody && String.Compare (web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) {
                                MemoryStream buffer = new MemoryStream ();
                                Encoder.WriteMessage (message, buffer);
@@ -205,7 +205,7 @@ namespace System.ServiceModel.Channels
                        }
 
                        var hrr = (HttpWebResponse) res;
-                       if ((int) hrr.StatusCode >= 400) {
+                       if ((int) hrr.StatusCode >= 400 && (int) hrr.StatusCode < 500) {
                                channelResult.Complete (new WebException (String.Format ("There was an error on processing web request: Status code {0}({1}): {2}", (int) hrr.StatusCode, hrr.StatusCode, hrr.StatusDescription)));
                        }
 
@@ -223,9 +223,12 @@ namespace System.ServiceModel.Channels
                                        }
                                        ms.Seek (0, SeekOrigin.Begin);
 
-                                       channelResult.Response = Encoder.ReadMessage (
-                                               //responseStream, MaxSizeOfHeaders);
-                                               ms, MaxSizeOfHeaders, res.ContentType);
+                                       Message ret = Encoder.ReadMessage (
+                                               ms, (int) source.Transport.MaxReceivedMessageSize, res.ContentType);
+                                       var rp = new HttpResponseMessageProperty () { StatusCode = hrr.StatusCode, StatusDescription = hrr.StatusDescription };
+                                       foreach (var key in hrr.Headers.AllKeys)
+                                               rp.Headers [key] = hrr.Headers [key];
+                                       ret.Properties.Add (HttpResponseMessageProperty.Name, rp);
 /*
 MessageBuffer buf = ret.CreateBufferedCopy (0x10000);
 ret = buf.CreateMessage ();
@@ -234,6 +237,7 @@ w.Formatting = System.Xml.Formatting.Indented;
 buf.CreateMessage ().WriteMessage (w);
 w.Close ();
 */
+                                       channelResult.Response = ret;
                                        channelResult.Complete ();
                                }
                        } catch (Exception ex) {
@@ -320,16 +324,15 @@ w.Close ();
                        AsyncCallback callback;
                        ManualResetEvent wait;
                        Exception error;
+                       object locker = new object ();
+                       bool is_completed;
 
                        public HttpChannelRequestAsyncResult (Message message, TimeSpan timeout, AsyncCallback callback, object state)
                        {
-                               CompletedSynchronously = true;
                                Message = message;
                                Timeout = timeout;
                                this.callback = callback;
                                AsyncState = state;
-
-                               wait = new ManualResetEvent (false);
                        }
 
                        public Message Response {
@@ -337,7 +340,13 @@ w.Close ();
                        }
 
                        public WaitHandle AsyncWaitHandle {
-                               get { return wait; }
+                               get {
+                                       lock (locker) {
+                                               if (wait == null)
+                                                       wait = new ManualResetEvent (is_completed);
+                                       }
+                                       return wait;
+                               }
                        }
 
                        public object AsyncState {
@@ -358,7 +367,6 @@ w.Close ();
                                error = error ?? ex;
 
                                IsCompleted = true;
-                               wait.Set ();
                                if (callback != null)
                                        callback (this);
                        }
@@ -368,7 +376,14 @@ w.Close ();
                        }
 
                        public bool IsCompleted {
-                               get; private set;
+                               get { return is_completed; }
+                               set {
+                                       is_completed = value;
+                                       lock (locker) {
+                                               if (is_completed && wait != null)
+                                                       wait.Set ();
+                                       }
+                               }
                        }
 
                        public void WaitEnd ()
@@ -377,11 +392,11 @@ w.Close ();
                                        // FIXME: Do we need to use the timeout? If so, what happens when the timeout is reached.
                                        // Is the current request cancelled and an exception thrown? If so we need to pass the
                                        // exception to the Complete () method and allow the result to complete 'normally'.
-#if NET_2_1 || MONOTOUCH
+#if NET_2_1
                                        // neither Moonlight nor MonoTouch supports contexts (WaitOne default to false)
-                                       bool result = wait.WaitOne (Timeout);
+                                       bool result = AsyncWaitHandle.WaitOne (Timeout);
 #else
-                                       bool result = wait.WaitOne (Timeout, true);
+                                       bool result = AsyncWaitHandle.WaitOne (Timeout, true);
 #endif
                                        if (!result)
                                                throw new TimeoutException ();
index 2919454e8be9b7213b74ff1f68934c8e8657eb64..4f3c424ecf3b6ef46b978f0e8b7bde3303ebc3d3 100644 (file)
@@ -56,18 +56,12 @@ namespace System.ServiceModel.Channels
                        if (msg == null)
                                throw new ArgumentNullException ("msg");
 
-                       // Handle DestinationUnreacheable as 400 (it is what .NET does).
-                       if (msg.IsFault) {
-                               // FIXME: isn't there any better way?
-                               var mb = msg.CreateBufferedCopy (0x10000);
-                               var fault = MessageFault.CreateFault (mb.CreateMessage (), 0x10000);
-                               if (fault.Code.Name == "DestinationUnreachable") {
-                                       ctx.Response.StatusCode = 400;
-                                       return;
-                               }
-                               else
-                                       msg = mb.CreateMessage ();
-                       }
+                       // FIXME: probably in WebHttpBinding land, there should 
+                       // be some additional code (probably IErrorHandler) that
+                       // treats DestinationUnreachable (and possibly any other)
+                       // errors as HTTP 400 or something appropriate. 
+                       // I originally rewrote the HTTP status here, but it 
+                       // was wrong.
 
                        // FIXME: should this be done here?
                        if (channel.MessageVersion.Addressing.Equals (AddressingVersion.None))
@@ -91,6 +85,8 @@ namespace System.ServiceModel.Channels
                                if (hp.SuppressEntityBody)
                                        suppressEntityBody = true;
                        }
+                       if (msg.IsFault)
+                               ctx.Response.StatusCode = 500;
                        if (!suppressEntityBody) {
                                ctx.Response.ContentLength64 = ms.Length;
                                ctx.Response.OutputStream.Write (ms.GetBuffer (), 0, (int) ms.Length);
index 977243d1430feb7d9842729f1feb1eb22e31ce16..f364d618c5b3095830936fbf0c6a80042411a8f0 100644 (file)
@@ -47,7 +47,7 @@ namespace System.ServiceModel.Channels
                string realm = String.Empty;
                TransferMode transfer_mode;
                IDefaultCommunicationTimeouts timeouts;
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                AuthenticationSchemes auth_scheme =
                        AuthenticationSchemes.Anonymous;
                AuthenticationSchemes proxy_auth_scheme =
@@ -75,13 +75,13 @@ namespace System.ServiceModel.Channels
                        transfer_mode = other.transfer_mode;
                        // FIXME: it does not look safe
                        timeouts = other.timeouts;
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        auth_scheme = other.auth_scheme;
                        proxy_auth_scheme = other.proxy_auth_scheme;
 #endif
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public AuthenticationSchemes AuthenticationScheme {
                        get { return auth_scheme; }
                        set { auth_scheme = value; }
@@ -170,6 +170,8 @@ namespace System.ServiceModel.Channels
                }
 
 #if !NET_2_1
+               internal static object ListenerBuildLock = new object ();
+
                public override IChannelListener<TChannel> BuildChannelListener<TChannel> (
                        BindingContext context)
                {
@@ -223,61 +225,63 @@ namespace System.ServiceModel.Channels
                {
                        throw new NotImplementedException ();
                }
+#endif
+       }
 
-               class HttpBindingProperties : ISecurityCapabilities, IBindingDeliveryCapabilities
-               {
-                       HttpTransportBindingElement source;
+#if !NET_2_1
+       class HttpBindingProperties : ISecurityCapabilities, IBindingDeliveryCapabilities
+       {
+               HttpTransportBindingElement source;
 
-                       public HttpBindingProperties (HttpTransportBindingElement source)
-                       {
-                               this.source = source;
-                       }
+               public HttpBindingProperties (HttpTransportBindingElement source)
+               {
+                       this.source = source;
+               }
 
-                       public bool AssuresOrderedDelivery {
-                               get { return false; }
-                       }
+               public bool AssuresOrderedDelivery {
+                       get { return false; }
+               }
 
-                       public bool QueuedDelivery {
-                               get { return false; }
-                       }
+               public bool QueuedDelivery {
+                       get { return false; }
+               }
 
-                       public ProtectionLevel SupportedRequestProtectionLevel {
-                               get { return ProtectionLevel.None; }
-                       }
+               public virtual ProtectionLevel SupportedRequestProtectionLevel {
+                       get { return ProtectionLevel.None; }
+               }
 
-                       public ProtectionLevel SupportedResponseProtectionLevel {
-                               get { return ProtectionLevel.None; }
-                       }
+               public virtual ProtectionLevel SupportedResponseProtectionLevel {
+                       get { return ProtectionLevel.None; }
+               }
 
-                       public bool SupportsClientAuthentication {
-                               get { return source.AuthenticationScheme != AuthenticationSchemes.Anonymous; }
-                       }
+               public virtual bool SupportsClientAuthentication {
+                       get { return source.AuthenticationScheme != AuthenticationSchemes.Anonymous; }
+               }
 
-                       public bool SupportsServerAuthentication {
-                               get {
-                                       switch (source.AuthenticationScheme) {
-                                       case AuthenticationSchemes.Negotiate:
-                                               return true;
-                                       default:
-                                               return false;
-                                       }
+               public virtual bool SupportsServerAuthentication {
+                       get {
+                               switch (source.AuthenticationScheme) {
+                               case AuthenticationSchemes.Negotiate:
+                                       return true;
+                               default:
+                                       return false;
                                }
                        }
+               }
 
-                       public bool SupportsClientWindowsIdentity {
-                               get {
-                                       switch (source.AuthenticationScheme) {
-                                       case AuthenticationSchemes.Basic:
-                                       case AuthenticationSchemes.Digest: // hmm... why? but they return true on .NET
-                                       case AuthenticationSchemes.Negotiate:
-                                       case AuthenticationSchemes.Ntlm:
-                                               return true;
-                                       default:
-                                               return false;
-                                       }
+               public virtual bool SupportsClientWindowsIdentity {
+                       get {
+                               switch (source.AuthenticationScheme) {
+                               case AuthenticationSchemes.Basic:
+                               case AuthenticationSchemes.Digest: // hmm... why? but they return true on .NET
+                               case AuthenticationSchemes.Negotiate:
+                               case AuthenticationSchemes.Ntlm:
+                                       return true;
+                               default:
+                                       return false;
                                }
                        }
                }
-#endif
        }
+#endif
 }
index 396a4276574c4cdafebf497b1ab6ed87e9102232..ad0c83047ef8b2f289fab3683b39167aa051e51c 100644 (file)
@@ -89,6 +89,47 @@ namespace System.ServiceModel.Channels
                {
                        throw new NotImplementedException ();
                }
+
+               // overriden only in full profile
+               public override T GetProperty<T> (BindingContext context)
+               {
+                       if (typeof (T) == typeof (ISecurityCapabilities))
+                               return (T) (object) new HttpsBindingProperties (this);
+                       return base.GetProperty<T> (context);
+               }
 #endif
        }
+
+#if !NET_2_1
+       class HttpsBindingProperties : HttpBindingProperties
+       {
+               HttpsTransportBindingElement source;
+
+               public HttpsBindingProperties (HttpsTransportBindingElement source)
+                       : base (source)
+               {
+                       this.source = source;
+               }
+
+               public override ProtectionLevel SupportedRequestProtectionLevel {
+                       get { return ProtectionLevel.EncryptAndSign; }
+               }
+
+               public override ProtectionLevel SupportedResponseProtectionLevel {
+                       get { return ProtectionLevel.EncryptAndSign; }
+               }
+
+               public override bool SupportsClientAuthentication {
+                       get { return source.RequireClientCertificate || base.SupportsClientAuthentication; }
+               }
+
+               public override bool SupportsServerAuthentication {
+                       get { return true; }
+               }
+
+               public override bool SupportsClientWindowsIdentity {
+                       get { return source.RequireClientCertificate || base.SupportsClientWindowsIdentity; }
+               }
+       }
+#endif
 }
index 963d1f1499da737e0e358b3203d038e972088320..f31b1d8595ce0d7bb5e6285e4c14294d411cc2bd 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Atsushi Enomoto <atsushi@ximian.com>
 //
-// Copyright (C) 2005-2006 Novell, Inc.  http://www.novell.com
+// Copyright (C) 2005-2006,2010 Novell, Inc.  http://www.novell.com
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -212,7 +212,6 @@ namespace System.ServiceModel.Channels
                {
                }
 
-               [MonoTODO ("use maxBufferSize")]
                protected virtual MessageBuffer OnCreateBufferedCopy (
                        int maxBufferSize)
                {
@@ -224,7 +223,7 @@ namespace System.ServiceModel.Channels
                                WriteBodyContents (w);
                        var headers = new MessageHeaders (Headers);
                        var props = new MessageProperties (Properties);
-                       return new DefaultMessageBuffer (maxBufferSize, headers, props, new XmlReaderBodyWriter (sw.ToString ()), false);
+                       return new DefaultMessageBuffer (maxBufferSize, headers, props, new XmlReaderBodyWriter (sw.ToString (), maxBufferSize, null), false);
                }
 
                protected virtual string OnGetBodyAttribute (
@@ -300,26 +299,19 @@ namespace System.ServiceModel.Channels
 
                #region factory methods
 
-               //  1) fault -> 4
-               //  2) action -> 5
-               //  3) fault, action -> 10
-               //  4) version, fault -> 10
-               //  5) version, action -> EmptyMessage
-               //  6) action, body -> 12
-               //  7) action, xmlReader -> 8
-               //  8) action, reader -> 16
-               // 10) version, fault, action -> 20
-               // 11) version, action, body -> 14
-               // 12) action, body, formatter -> 14
-               // 13) version, action, body -> 14
-               // 14) version, action, body, formatter -> 20
-               // 15) version, action, xmlReader -> 16
-               // 16) version, action, reader -> 20
-               // 17) xmlReader, maxSizeOfHeaders, version -> 18
-               // 18) reader, maxSizeOfHeaders, version -> ForwardingMessage
-               // 19) action, bodyWriter -> 20
-               // 20) version, action, bodyWriter -> SimpleMessage
-
+               // 1) version, code, reason, action -> 3
+               // 2) version, code, reason, detail, action -> 3
+               // 3) version, fault, action -> SimpleMessage
+               // 4) version, action, body -> 10 or 5
+               // 5) version, action, body, formatter -> 10 or 9
+               // 6) version, action, xmlReader -> 7
+               // 7) version, action, reader -> 9
+               // 8) xmlReader, maxSizeOfHeaders, version -> 11
+               // 9) version, action, body -> SimpleMessage
+               // 10) version, action -> EmptyMessage
+               // 11) reader, maxSizeOfHeaders, version -> XmlReaderMessage
+
+               // 1)
                public static Message CreateMessage (MessageVersion version,
                        FaultCode code, string reason, string action)
                {
@@ -327,6 +319,7 @@ namespace System.ServiceModel.Channels
                        return CreateMessage (version, fault, action);
                }
 
+               // 2)
                public static Message CreateMessage (MessageVersion version,
                        FaultCode code, string reason, object detail,
                        string action)
@@ -336,6 +329,7 @@ namespace System.ServiceModel.Channels
                        return CreateMessage (version, fault, action);
                }
 
+               // 3)
                public static Message CreateMessage (MessageVersion version,
                        MessageFault fault, string action)
                {
@@ -343,6 +337,7 @@ namespace System.ServiceModel.Channels
                                new MessageFaultBodyWriter (fault, version), true);
                }
 
+               // 4)
                public static Message CreateMessage (MessageVersion version,
                        string action, object body)
                {
@@ -351,6 +346,7 @@ namespace System.ServiceModel.Channels
                                CreateMessage (version, action, body, new DataContractSerializer (body.GetType ()));
                }
 
+               // 5)
                public static Message CreateMessage (MessageVersion version,
                        string action, object body, XmlObjectSerializer xmlFormatter)
                {
@@ -361,6 +357,7 @@ namespace System.ServiceModel.Channels
                                        new XmlObjectSerializerBodyWriter (body, xmlFormatter));
                }
 
+               // 6)
                public static Message CreateMessage (MessageVersion version,
                        string action, XmlReader body)
                {
@@ -368,6 +365,7 @@ namespace System.ServiceModel.Channels
                                XmlDictionaryReader.CreateDictionaryReader (body));
                }
 
+               // 7)
                public static Message CreateMessage (MessageVersion version,
                        string action, XmlDictionaryReader body)
                {
@@ -375,6 +373,7 @@ namespace System.ServiceModel.Channels
                                new XmlReaderBodyWriter (body));
                }
 
+               // 8)
                public static Message CreateMessage (XmlReader envelopeReader,
                        int maxSizeOfHeaders, MessageVersion version)
                {
@@ -386,6 +385,7 @@ namespace System.ServiceModel.Channels
 
                // Core implementations of CreateMessage.
 
+               // 9)
                public static Message CreateMessage (MessageVersion version,
                        string action, BodyWriter body)
                {
@@ -396,6 +396,7 @@ namespace System.ServiceModel.Channels
                        return new SimpleMessage (version, action, body, false);
                }
 
+               // 10)
                public static Message CreateMessage (MessageVersion version,
                        string action)
                {
@@ -404,6 +405,7 @@ namespace System.ServiceModel.Channels
                        return new EmptyMessage (version, action);
                }
 
+               // 11)
                public static Message CreateMessage (
                        XmlDictionaryReader envelopeReader,
                        int maxSizeOfHeaders,
index 727667df90c1a0d430f75a0f5c6d1cc72b4cac13..79168b1c564d3f892472806f1321a7af5593b97f 100644 (file)
@@ -43,7 +43,7 @@ namespace System.ServiceModel.Channels
                                if (message.Version.Envelope == EnvelopeVersion.Soap11)
                                        return CreateFault11 (message, maxBufferSize);
                                else // common to None and SOAP12
-                                       return CreateFault (message, maxBufferSize, message.Version.Envelope.Namespace);
+                                       return CreateFault12 (message, maxBufferSize);
                        } catch (XmlException ex) {
                                throw new CommunicationException ("Received an invalid SOAP Fault message", ex);
                        }
@@ -68,12 +68,7 @@ namespace System.ServiceModel.Channels
                                        fr = new FaultReason (r.ReadElementContentAsString());
                                        break;
                                case "detail":
-                                       //BUGBUG: Handle children of type other than ExceptionDetail, in order to comply with 
-                                       //        FaultContractAttribute.
-                                       r.ReadStartElement ();
-                                       r.MoveToContent();
-                                       details = new DataContractSerializer (typeof (ExceptionDetail)).ReadObject (r);
-                                       break;
+                                       return new XmlReaderDetailMessageFault (message, r, fc, fr, null, null);
                                case "faultactor":
                                default:
                                        throw new NotImplementedException ();
@@ -90,26 +85,40 @@ namespace System.ServiceModel.Channels
                        return CreateFault (fc, fr, details);
                }
 
-               static MessageFault CreateFault (Message message, int maxBufferSize, string ns)
+               static MessageFault CreateFault12 (Message message, int maxBufferSize)
                {
                        FaultCode fc = null;
                        FaultReason fr = null;
+                       string node = null;
                        XmlDictionaryReader r = message.GetReaderAtBodyContents ();
-                       r.ReadStartElement ("Fault", ns);
-                       r.MoveToContent ();
+                       r.ReadStartElement ("Fault", message.Version.Envelope.Namespace);
 
-                       while (r.NodeType != XmlNodeType.EndElement) {
+                       for (r.MoveToContent (); r.NodeType != XmlNodeType.EndElement; r.MoveToContent ()) {
+                               if (r.NamespaceURI != message.Version.Envelope.Namespace) {
+                                       r.Skip ();
+                                       continue;
+                               }
                                switch (r.LocalName) {
                                case "Code":
-                                       fc = ReadFaultCode (r, ns);
+                                       fc = ReadFaultCode12 (r, message.Version.Envelope.Namespace);
                                        break;
                                case "Reason":
-                                       fr = ReadFaultReason (r, ns);
+                                       fr = ReadFaultReason12 (r, message.Version.Envelope.Namespace);
+                                       break;
+                               case "Node":
+                                       node = r.ReadElementContentAsString ();
+                                       break;
+                               case "Role":
+                                       r.Skip (); // no corresponding member to store.
+                                       break;
+                               case "Detail":
+                                       if (!r.IsEmptyElement)
+                                               return new XmlReaderDetailMessageFault (message, r, fc, fr, null, node);
+                                       r.Read ();
                                        break;
                                default:
                                        throw new XmlException (String.Format ("Unexpected node {0} name {1}", r.NodeType, r.Name));
                                }
-                               r.MoveToContent ();
                        }
 
                        if (fr == null)
@@ -117,7 +126,7 @@ namespace System.ServiceModel.Channels
 
                        r.ReadEndElement ();
 
-                       return CreateFault (fc, fr);
+                       return CreateFault (fc, fr, null, null, null, node);
                }
 
                static FaultCode ReadFaultCode11 (XmlDictionaryReader r)
@@ -142,7 +151,7 @@ namespace System.ServiceModel.Channels
                        return new FaultCode (value.Name, value.Namespace, subcode);
                }
 
-               static FaultCode ReadFaultCode (XmlDictionaryReader r, string ns)
+               static FaultCode ReadFaultCode12 (XmlDictionaryReader r, string ns)
                {
                        FaultCode subcode = null;
                        XmlQualifiedName value = XmlQualifiedName.Empty;
@@ -155,13 +164,13 @@ namespace System.ServiceModel.Channels
                        while (r.NodeType != XmlNodeType.EndElement) {
                                switch (r.LocalName) {
                                case "Subcode":
-                                       subcode = ReadFaultCode (r, ns);
+                                       subcode = ReadFaultCode12 (r, ns);
                                        break;
                                case "Value":
                                        value = (XmlQualifiedName) r.ReadElementContentAs (typeof (XmlQualifiedName), r as IXmlNamespaceResolver, "Value", ns);
                                        break;
                                default:
-                                       throw new ArgumentException ();
+                                       throw new ArgumentException (String.Format ("Unexpected Fault Code subelement: '{0}'", r.LocalName));
                                }
                                r.MoveToContent ();
                        }
@@ -170,7 +179,7 @@ namespace System.ServiceModel.Channels
                        return new FaultCode (value.Name, value.Namespace, subcode);
                }
 
-               static FaultReason ReadFaultReason (XmlDictionaryReader r, string ns)
+               static FaultReason ReadFaultReason12 (XmlDictionaryReader r, string ns)
                {
                        List<FaultReasonText> l = new List<FaultReasonText> ();
                        if (r.IsEmptyElement)
@@ -185,6 +194,8 @@ namespace System.ServiceModel.Channels
                                        throw new XmlException ("xml:lang is mandatory on fault reason Text");
                                l.Add (new FaultReasonText (r.ReadElementContentAsString ("Text", ns), lang));
                        }
+                       r.ReadEndElement ();
+
                        return new FaultReason (l);
                }
 
@@ -233,12 +244,40 @@ namespace System.ServiceModel.Channels
                }
 
                // pretty simple implementation class
-               internal class SimpleMessageFault : MessageFault
+               internal abstract class BaseMessageFault : MessageFault
                {
-                       bool has_detail;
                        string actor, node;
                        FaultCode code;
                        FaultReason reason;
+
+                       protected BaseMessageFault (FaultCode code, FaultReason reason, string actor, string node)
+                       {
+                               this.code = code;
+                               this.reason = reason;
+                               this.actor = actor;
+                               this.node = node;
+                       }
+
+                       public override string Actor {
+                               get { return actor; }
+                       }
+
+                       public override FaultCode Code {
+                               get { return code; }
+                       }
+
+                       public override string Node {
+                               get { return node; }
+                       }
+
+                       public override FaultReason Reason {
+                               get { return reason; }
+                       }
+               }
+
+               internal class SimpleMessageFault : BaseMessageFault
+               {
+                       bool has_detail;
                        object detail;
                        XmlObjectSerializer formatter;
 
@@ -255,26 +294,15 @@ namespace System.ServiceModel.Channels
                                FaultReason reason,
                                object detail, XmlObjectSerializer formatter,
                                string actor, string node)
+                               : base (code, reason, actor, node)
                        {
                                if (code == null)
                                        throw new ArgumentNullException ("code");
                                if (reason == null)
                                        throw new ArgumentNullException ("reason");
 
-                               this.code = code;
-                               this.reason = reason;
                                this.detail = detail;
                                this.formatter = formatter;
-                               this.actor = actor;
-                               this.node = node;
-                       }
-
-                       public override string Actor {
-                               get { return actor; }
-                       }
-
-                       public override FaultCode Code {
-                               get { return code; }
                        }
 
                        public override bool HasDetail {
@@ -283,27 +311,58 @@ namespace System.ServiceModel.Channels
                                get { return has_detail; }
                        }
 
-                       public override string Node {
-                               get { return node; }
+                       protected override void OnWriteDetailContents (XmlDictionaryWriter writer)
+                       {
+                               if (formatter == null && detail != null)
+                                       formatter = new DataContractSerializer (detail.GetType ());
+                               if (formatter != null)
+                                       formatter.WriteObject (writer, detail);
+                               else
+                                       throw new InvalidOperationException ("There is no fault detail to write");
                        }
 
-                       public override FaultReason Reason {
-                               get { return reason; }
+                       public object Detail {
+                               get { return detail; }
                        }
+               }
 
-                       protected override XmlDictionaryReader OnGetReaderAtDetailContents ()
+               class XmlReaderDetailMessageFault : BaseMessageFault
+               {
+                       XmlDictionaryReader reader;
+                       bool consumed;
+
+                       public XmlReaderDetailMessageFault (Message message, XmlDictionaryReader reader, FaultCode code, FaultReason reason, string actor, string node)
+                               : base (code, reason, actor, node)
                        {
-                               // FIXME: use XmlObjectSerializer
-                               return base.OnGetReaderAtDetailContents ();
+                               this.reader = reader;
                        }
 
-                       protected override void OnWriteDetailContents (XmlDictionaryWriter writer)
+                       void Consume ()
                        {
-                               formatter.WriteObject (writer, detail);
+                               if (consumed)
+                                       throw new InvalidOperationException ("The fault detail content is already consumed");
+                               consumed = true;
+                               reader.ReadStartElement (); // consume the wrapper
+                               reader.MoveToContent ();
                        }
 
-                       public object Detail {
-                               get { return detail; }
+                       public override bool HasDetail {
+                               get { return true; }
+                       }
+
+                       protected override XmlDictionaryReader OnGetReaderAtDetailContents ()
+                       {
+                               Consume ();
+                               return reader;
+                       }
+
+                       protected override void OnWriteDetailContents (XmlDictionaryWriter writer)
+                       {
+                               if (!HasDetail)
+                                       throw new InvalidOperationException ("There is no fault detail to write");
+                               Consume ();
+                               while (reader.NodeType != XmlNodeType.EndElement)
+                                       writer.WriteNode (reader, false);
                        }
                }
 
@@ -351,7 +410,7 @@ namespace System.ServiceModel.Channels
                        EnvelopeVersion version)
                {
                        writer.WriteStartElement ("Fault", version.Namespace);
-                       WriteFaultCode (writer, version, Code);
+                       WriteFaultCode (writer, version, Code, false);
                        WriteReason (writer, version);
                        if (HasDetail)
                                OnWriteDetail (writer, version);
@@ -359,23 +418,23 @@ namespace System.ServiceModel.Channels
                }
 
                private void WriteFaultCode (XmlDictionaryWriter writer, 
-                       EnvelopeVersion version, FaultCode code)
+                       EnvelopeVersion version, FaultCode code, bool sub)
                {
                        if (version == EnvelopeVersion.Soap11) {
-                               writer.WriteStartElement ("", "faultcode", version.Namespace);
-                               if (code.Namespace.Length > 0)
+                               writer.WriteStartElement ("", "faultcode", String.Empty);
+                               if (code.Namespace.Length > 0 && String.IsNullOrEmpty (writer.LookupPrefix (code.Namespace)))
                                        writer.WriteXmlnsAttribute ("a", code.Namespace);
                                writer.WriteQualifiedName (code.Name, code.Namespace);
                                writer.WriteEndElement ();
                        } else { // Soap12
-                               writer.WriteStartElement ("Code", version.Namespace);
+                               writer.WriteStartElement (sub ? "Subcode" : "Code", version.Namespace);
                                writer.WriteStartElement ("Value", version.Namespace);
-                               if (code.Namespace.Length > 0)
+                               if (code.Namespace.Length > 0 && String.IsNullOrEmpty (writer.LookupPrefix (code.Namespace)))
                                        writer.WriteXmlnsAttribute ("a", code.Namespace);
                                writer.WriteQualifiedName (code.Name, code.Namespace);
-                               if (code.SubCode != null)
-                                       WriteFaultCode (writer, version, code.SubCode);
                                writer.WriteEndElement ();
+                               if (code.SubCode != null)
+                                       WriteFaultCode (writer, version, code.SubCode, true);
                                writer.WriteEndElement ();
                        }
                }
@@ -385,7 +444,7 @@ namespace System.ServiceModel.Channels
                {
                        if (version == EnvelopeVersion.Soap11) {
                                foreach (FaultReasonText t in Reason.Translations) {
-                                       writer.WriteStartElement ("", "faultstring", version.Namespace);
+                                       writer.WriteStartElement ("", "faultstring", String.Empty);
                                        if (t.XmlLang != null)
                                                writer.WriteAttributeString ("xml", "lang", null, t.XmlLang);
                                        writer.WriteString (t.Text);
@@ -412,6 +471,8 @@ namespace System.ServiceModel.Channels
 
                protected virtual XmlDictionaryReader OnGetReaderAtDetailContents ()
                {
+                       if (!HasDetail)
+                               throw new InvalidOperationException ("There is no fault detail to read");
                        MemoryStream ms = new MemoryStream ();
                        using (XmlDictionaryWriter dw =
                                XmlDictionaryWriter.CreateDictionaryWriter (
index 8b9016b622a1690ed576c7247b43809de11c9e7f..90e889112509ce847487852d7b3d2c31c831e843 100644 (file)
@@ -267,15 +267,6 @@ namespace System.ServiceModel.Channels
                {
                        if (version.Envelope == EnvelopeVersion.None)
                                return;
-
-                       // For AddressingVersion.None, don't output the item.
-                       //
-                       // FIXME: It should even ignore Action, but for now
-                       // service dispatcher won't work without it.
-                       if (version.Addressing == AddressingVersion.None &&
-                           l [index].Name != "Action")
-                               return;
-
                        WriteStartHeader (index, writer);
                        WriteHeaderContents (index, writer);
                        writer.WriteEndElement ();
@@ -349,10 +340,14 @@ namespace System.ServiceModel.Channels
 
                public EndpointAddress FaultTo {
                        get {
-                               int idx = FindHeader ("FaultTo", Constants.WsaNamespace);
+                               int idx = FindHeader ("FaultTo", version.Addressing.Namespace);
                                return idx < 0 ? null : GetHeader<EndpointAddress> (idx);
                        }
-                       set { AddEndpointAddressHeader ("FaultTo", Constants.WsaNamespace, value); }
+                       set {
+                               RemoveAll ("FaultTo", version.Addressing.Namespace);
+                               if (value != null)
+                                       AddEndpointAddressHeader ("FaultTo", version.Addressing.Namespace, value);
+                       }
                }
 
                public EndpointAddress From {
@@ -360,7 +355,11 @@ namespace System.ServiceModel.Channels
                                int idx = FindHeader ("From", version.Addressing.Namespace);
                                return idx < 0 ? null : GetHeader<EndpointAddress> (idx);
                        }
-                       set { AddEndpointAddressHeader ("From", Constants.WsaNamespace, value); }
+                       set {
+                               RemoveAll ("From", version.Addressing.Namespace);
+                               if (value != null)
+                                       AddEndpointAddressHeader ("From", version.Addressing.Namespace, value);
+                       }
                }
 
                public MessageHeaderInfo this [int index] {
@@ -369,16 +368,16 @@ namespace System.ServiceModel.Channels
 
                public UniqueId MessageId {
                        get { 
-                               int idx = FindHeader ("MessageID", Constants.WsaNamespace);
+                               int idx = FindHeader ("MessageID", version.Addressing.Namespace);
                                return idx < 0 ? null : new UniqueId (GetHeader<string> (idx));
                        }
                        set {
                                if (version.Addressing == AddressingVersion.None && value != null)
                                        throw new InvalidOperationException ("WS-Addressing header is not allowed for AddressingVersion.None");
 
-                               RemoveAll ("MessageID", Constants.WsaNamespace);
+                               RemoveAll ("MessageID", version.Addressing.Namespace);
                                if (value != null)
-                                       Add (MessageHeader.CreateHeader ("MessageID", Constants.WsaNamespace, value));
+                                       Add (MessageHeader.CreateHeader ("MessageID", version.Addressing.Namespace, value));
                        }
                }
 
@@ -386,26 +385,30 @@ namespace System.ServiceModel.Channels
 
                public UniqueId RelatesTo {
                        get { 
-                               int idx = FindHeader ("RelatesTo", Constants.WsaNamespace);
+                               int idx = FindHeader ("RelatesTo", version.Addressing.Namespace);
                                return idx < 0 ? null : new UniqueId (GetHeader<string> (idx));
                        }
                        set {
                                if (version.Addressing == AddressingVersion.None && value != null)
                                        throw new InvalidOperationException ("WS-Addressing header is not allowed for AddressingVersion.None");
 
-                               RemoveAll ("MessageID", Constants.WsaNamespace);
+                               RemoveAll ("MessageID", version.Addressing.Namespace);
                                if (value != null)
-                                       Add (MessageHeader.CreateHeader ("RelatesTo", Constants.WsaNamespace, value));
+                                       Add (MessageHeader.CreateHeader ("RelatesTo", version.Addressing.Namespace, value));
                        }
 
                }
 
                public EndpointAddress ReplyTo {
                        get {
-                               int idx = FindHeader ("ReplyTo", Constants.WsaNamespace);
+                               int idx = FindHeader ("ReplyTo", version.Addressing.Namespace);
                                return idx < 0 ? null : GetHeader<EndpointAddress> (idx);
                        }
-                       set { AddEndpointAddressHeader ("ReplyTo", Constants.WsaNamespace, value); }
+                       set {
+                               RemoveAll ("ReplyTo", version.Addressing.Namespace);
+                               if (value != null)
+                                       AddEndpointAddressHeader ("ReplyTo", version.Addressing.Namespace, value);
+                       }
                }
 
                public Uri To {
index b3ca10f349156300dbdca0ccb64c10729f4cf900..b4c341d029722394abe3282365321c117fbe73ff 100644 (file)
@@ -60,16 +60,14 @@ namespace System.ServiceModel.Channels
 
                public override bool IsEmpty {
                        get {
-                               if (!body_started)
-                                       ReadBodyStart ();
+                               ReadBodyStart ();
                                return is_empty;
                        }
                }
 
                public override bool IsFault {
                        get {
-                               if (!body_started)
-                                       ReadBodyStart ();
+                               ReadBodyStart ();
                                return is_fault;
                        }
                }
@@ -82,6 +80,15 @@ namespace System.ServiceModel.Channels
                        get { return version; }
                }
 
+               protected override MessageBuffer OnCreateBufferedCopy (
+                       int maxBufferSize)
+               {
+                       ReadBodyStart ();
+                       var headers = new MessageHeaders (Headers);
+                       var props = new MessageProperties (Properties);
+                       return new DefaultMessageBuffer (maxBufferSize, headers, props, new XmlReaderBodyWriter (reader), IsFault);
+               }
+
                protected override string OnGetBodyAttribute (
                        string localName, string ns)
                {
@@ -96,8 +103,7 @@ namespace System.ServiceModel.Channels
                                return reader; // silly, but that's what our test expects.
                        if (body_consumed)
                                throw new InvalidOperationException ("The message body XmlReader is already consumed.");
-                       if (!body_started)
-                               ReadBodyStart ();
+                       ReadBodyStart ();
                        if (is_empty)
                                throw new InvalidOperationException ("The message body is empty.");
                        body_consumed = true;
@@ -156,6 +162,9 @@ namespace System.ServiceModel.Channels
 
                void ReadBodyStart ()
                {
+                       if (body_started)
+                               return;
+
                        // read headers in advance.
                        if (headers == null)
                                ReadHeaders ();
@@ -261,7 +270,7 @@ namespace System.ServiceModel.Channels
                {
                        var headers = new MessageHeaders (Headers);
                        var props = new MessageProperties (Properties);
-                       return new DefaultMessageBuffer (maxBufferSize, headers, props, body.CreateBufferedCopy (maxBufferSize), false);
+                       return new DefaultMessageBuffer (maxBufferSize, headers, props, body.CreateBufferedCopy (maxBufferSize), IsFault);
                }
        }
 }
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Channels/PrivacyNoticeBindingElement.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Channels/PrivacyNoticeBindingElement.cs
new file mode 100644 (file)
index 0000000..d1e1e5b
--- /dev/null
@@ -0,0 +1,67 @@
+//
+// PrivacyNoticeBindingElement.cs
+//
+// Author: Atsushi Enomoto (atsushi@ximian.com)
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.ServiceModel;
+using System.ServiceModel.Description;
+
+namespace System.ServiceModel.Channels
+{
+       public sealed class PrivacyNoticeBindingElement : BindingElement, IPolicyExportExtension
+       {
+               public PrivacyNoticeBindingElement ()
+               {
+                       // FIXME: apply configuration
+               }
+
+               public PrivacyNoticeBindingElement (PrivacyNoticeBindingElement elementToBeCloned)
+               {
+                       var e = elementToBeCloned;
+                       Url = e.Url;
+                       Version = e.Version;
+               }
+
+               [MonoTODO]
+               public Uri Url { get; set; }
+               [MonoTODO]
+               public int Version { get; set; }
+
+               public override BindingElement Clone ()
+               {
+                       return new PrivacyNoticeBindingElement (this);
+               }
+
+               public override T GetProperty<T> (BindingContext context)
+               {
+                       return context.GetInnerProperty<T> ();
+               }
+
+               void IPolicyExportExtension.ExportPolicy (MetadataExporter exporter, PolicyConversionContext context)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Channels/ReliableSessionBindingElement.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Channels/ReliableSessionBindingElement.cs
new file mode 100644 (file)
index 0000000..2a45cbd
--- /dev/null
@@ -0,0 +1,102 @@
+//
+// ReliableSessionBindingElement.cs
+//
+// Author: Atsushi Enomoto (atsushi@ximian.com)
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.ServiceModel;
+using System.ServiceModel.Description;
+
+namespace System.ServiceModel.Channels
+{
+       public sealed class ReliableSessionBindingElement : BindingElement, IPolicyExportExtension
+       {
+               public ReliableSessionBindingElement ()
+               {
+                       // FIXME: apply configuration
+               }
+
+               public ReliableSessionBindingElement (bool ordered)
+                       : this ()
+               {
+                       Ordered = ordered;
+               }
+
+               [MonoTODO]
+               public TimeSpan AcknowledgementInterval { get; set; }
+               [MonoTODO]
+               public bool FlowControlEnabled { get; set; }
+               [MonoTODO]
+               public TimeSpan InactivityTimeout { get; set; }
+               [MonoTODO]
+               public int MaxPendingChannels { get; set; }
+               [MonoTODO]
+               public int MaxRetryCount { get; set; }
+               [MonoTODO]
+               public int MaxTransferWindowSize { get; set; }
+               [MonoTODO]
+               public bool Ordered { get; set; }
+               [MonoTODO]
+               public ReliableMessagingVersion ReliableMessagingVersion { get; set; }
+
+               [MonoTODO]
+               public override IChannelFactory<TChannel> BuildChannelFactory<TChannel> (BindingContext context)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               [MonoTODO]
+               public override IChannelListener<TChannel> BuildChannelListener<TChannel> (BindingContext context)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               [MonoTODO]
+               public override bool CanBuildChannelFactory<TChannel> (BindingContext context)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               [MonoTODO]
+               public override bool CanBuildChannelListener<TChannel> (BindingContext context)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override BindingElement Clone ()
+               {
+                       return (ReliableSessionBindingElement) MemberwiseClone ();
+               }
+
+               public override T GetProperty<T> (BindingContext context)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               void IPolicyExportExtension.ExportPolicy (MetadataExporter exporter, PolicyConversionContext context)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Channels/RemoteEndpointMessageProperty.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Channels/RemoteEndpointMessageProperty.cs
new file mode 100644 (file)
index 0000000..df95178
--- /dev/null
@@ -0,0 +1,48 @@
+//
+// RemoteEndpointMessageProperty.cs
+//
+// Author: Atsushi Enomoto (atsushi@ximian.com)
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.ServiceModel;
+using System.ServiceModel.Description;
+
+namespace System.ServiceModel.Channels
+{
+       public sealed class RemoteEndpointMessageProperty
+       {
+               public static string Name {
+                       get { return "System.ServiceModel.Channels.RemoteEndpointMessageProperty"; }
+               }
+
+               public RemoteEndpointMessageProperty (string address, int port)
+               {
+                       Address = address;
+                       Port = port;
+               }
+
+               public string Address { get; private set; }
+               public int Port { get; private set; }
+       }
+}
index 580545f703f6385eb4a2b74cce4366bf11f01707..9bef1913b1aca6f9abe60f57db5666a13f36f5ad 100644 (file)
@@ -106,6 +106,7 @@ namespace System.ServiceModel.Channels
                delegate bool TryReceiveDelegate (TimeSpan timeout, out RequestContext context);
                TryReceiveDelegate try_recv_delegate;
 
+               object async_result_lock = new object ();
                protected Thread CurrentAsyncThread { get; private set; }
                protected IAsyncResult CurrentAsyncResult { get; private set; }
 
@@ -115,18 +116,26 @@ namespace System.ServiceModel.Channels
                                throw new InvalidOperationException ("Another async TryReceiveRequest operation is in progress");
                        if (try_recv_delegate == null)
                                try_recv_delegate = new TryReceiveDelegate (delegate (TimeSpan tout, out RequestContext ctx) {
-                                       if (CurrentAsyncResult != null)
-                                               CurrentAsyncThread = Thread.CurrentThread;
+                                       lock (async_result_lock) {
+                                               if (CurrentAsyncResult != null)
+                                                       CurrentAsyncThread = Thread.CurrentThread;
+                                       }
                                        try {
                                                return TryReceiveRequest (tout, out ctx);
                                        } finally {
-                                               CurrentAsyncResult = null;
-                                               CurrentAsyncThread = null;
+                                               lock (async_result_lock) {
+                                                       CurrentAsyncResult = null;
+                                                       CurrentAsyncThread = null;
+                                               }
                                        }
                                        });
                        RequestContext dummy;
-                       CurrentAsyncResult = try_recv_delegate.BeginInvoke (timeout, out dummy, callback, state);
-                       return CurrentAsyncResult;
+                       IAsyncResult result;
+                       lock (async_result_lock) {
+                               result = CurrentAsyncResult = try_recv_delegate.BeginInvoke (timeout, out dummy, callback, state);
+                       }
+                       // Note that at this point CurrentAsyncResult can be null here if delegate has run to completion
+                       return result;
                }
 
                public virtual bool EndTryReceiveRequest (IAsyncResult result)
index 23e6043de2a2ed6f4a5fb51fd88c3641bb1b0f18..487f0f0c8dfb8017b939727f363272645ec8a592 100644 (file)
@@ -278,10 +278,10 @@ if (!ShouldOutputEncryptedKey)
 
                        // FIXME: get correct ReplyTo value
                        if (Direction == MessageDirection.Input)
-                               msg.Headers.Add (MessageHeader.CreateHeader ("ReplyTo", msg.Version.Addressing.Namespace, EndpointAddress10.FromEndpointAddress (new EndpointAddress (Constants.WsaAnonymousUri))));
+                               msg.Headers.ReplyTo = new EndpointAddress (Constants.WsaAnonymousUri);
 
                        if (MessageTo != null)
-                               msg.Headers.Add (MessageHeader.CreateHeader ("To", msg.Version.Addressing.Namespace, MessageTo.Uri.AbsoluteUri, true));
+                               msg.Headers.To = MessageTo.Uri;
 
                        // wss:Security
                        WSSecurityMessageHeader header =
index 413650ba3eba8c874975e1c9549d1b2174f6842f..161b3f476b45c37473abf35b1d2fa69844a6ac3a 100644 (file)
@@ -63,6 +63,8 @@ namespace System.ServiceModel.Channels {
 
        internal class SvcHttpHandler : IHttpHandler
        {
+               internal static SvcHttpHandler Current;
+
                static object type_lock = new object ();
 
                Type type;
@@ -135,7 +137,9 @@ namespace System.ServiceModel.Channels {
                                if (best == null)
                                        best = l;
                        }
-                       return best;
+                       if (best != null)
+                               return best;
+                       throw new InvalidOperationException (String.Format ("The argument HTTP context did not match any of the registered listener manager (could be mismatch in URL, method etc.) {0}", ctx.Request.Url));
 /*
                        var actx = new AspNetHttpContextInfo (ctx);
                        foreach (var i in listeners)
@@ -194,7 +198,17 @@ namespace System.ServiceModel.Channels {
                void EnsureServiceHost ()
                {
                        lock (type_lock) {
+                               Current = this;
+                               try {
+                                       EnsureServiceHostCore ();
+                               } finally {
+                                       Current = null;
+                               }
+                       }
+               }
 
+               void EnsureServiceHostCore ()
+               {
                        if (host != null)
                                return;
 
@@ -211,8 +225,6 @@ namespace System.ServiceModel.Channels {
 
                        // Not precise, but it needs some wait time to have all channels start requesting. And it is somehow required.
                        Thread.Sleep (500);
-
-                       }
                }
        }
 }
index 07a9d8ff3f723f08bdd4c68d6f8e9bc5a414fe4b..4549bdb43d5e66a65c4e7e3d4083f033476d33e7 100644 (file)
@@ -35,7 +35,6 @@ using System.ServiceModel.Description;
 
 namespace System.ServiceModel.Channels
 {
-       [MonoTODO]
        public class TcpTransportBindingElement
                : ConnectionOrientedTransportBindingElement
        {
@@ -83,7 +82,6 @@ namespace System.ServiceModel.Channels
                        set { teredo_enabled = value; }
                }
 
-               [MonoTODO]
                public override IChannelFactory<TChannel> BuildChannelFactory<TChannel> (
                        BindingContext context)
                {
@@ -106,11 +104,29 @@ namespace System.ServiceModel.Channels
                        return new TcpTransportBindingElement (this);
                }
 
-               [MonoTODO]
                public override T GetProperty<T> (BindingContext context)
                {
-                       // FIXME: ... or return ISecurityCapabilities?
-                       return context.GetInnerProperty<T> ();
+                       if (typeof (T) == typeof (IBindingDeliveryCapabilities))
+                               return (T) (object) new TcpBindingProperties (this);
+                       return base.GetProperty<T> (context);
+               }
+       }
+
+       class TcpBindingProperties : IBindingDeliveryCapabilities
+       {
+               TcpTransportBindingElement source;
+
+               public TcpBindingProperties (TcpTransportBindingElement source)
+               {
+                       this.source = source;
+               }
+
+               public bool AssuresOrderedDelivery {
+                       get { return true; }
+               }
+
+               public bool QueuedDelivery {
+                       get { return false; }
                }
        }
 }
index 9324471fa949b58416ce9be91615240148355365..d753c885f3e19c21d6db2f85ce329807ae097e6f 100644 (file)
@@ -161,6 +161,11 @@ namespace System.ServiceModel.Channels
                        this.protocol = protocol;
                }
 
+               public override T GetProperty<T> ()
+               {
+                       return inner_listener.GetProperty<T> () ?? base.GetProperty<T> ();
+               }
+
                public override Uri Uri {
                        get { return inner_listener.Uri; }
                }
index fc02db81f6b8b2f3e2a241fd6d55e8a86222ddb3..b99bf1337022e1798396b4068dc476571dfc2747 100644 (file)
@@ -408,6 +408,8 @@ doc.PreserveWhitespace = true;
 
                protected override void OnWriteHeaderContents (XmlDictionaryWriter writer, MessageVersion version)
                {
+                       // FIXME: it should use XmlDictionaryWriter that CanCanonicalize the output (which is not possible in any built-in writer types, so we'll have to hack it).
+
                        foreach (object obj in Contents) {
                                if (obj is WsuTimestamp) {
                                        WsuTimestamp ts = (WsuTimestamp) obj;
index b2220d1b485ef9ecde03cb466533545092bf052b..1cca9653e1cc8c0268df130ae58ac15293a0565c 100644 (file)
@@ -36,12 +36,22 @@ namespace System.ServiceModel.Channels
        internal class XmlReaderBodyWriter : BodyWriter
        {
                XmlDictionaryReader reader;
-               string xml;
+               string xml_bak;
+               XmlParserContext parser_context;
+               bool consumed;
 
-               public XmlReaderBodyWriter (string xml)
+               public XmlReaderBodyWriter (string xml, int maxBufferSize, XmlParserContext ctx)
                        : base (true)
                {
-                       this.xml = xml;
+                       var settings = new XmlReaderSettings () {
+                               // FIXME: enable this line (once MaxCharactersInDocument is implemented)
+                               // MaxCharactersInDocument = maxBufferSize,
+                               ConformanceLevel = ConformanceLevel.Fragment
+                               };
+                       reader = XmlDictionaryReader.CreateDictionaryReader (XmlReader.Create (new StringReader (xml), settings, ctx));
+                       reader.MoveToContent ();
+                       xml_bak = xml;
+                       parser_context = ctx;
                }
 
                public XmlReaderBodyWriter (XmlDictionaryReader reader)
@@ -54,21 +64,60 @@ namespace System.ServiceModel.Channels
                protected override BodyWriter OnCreateBufferedCopy (
                        int maxBufferSize)
                {
-                       if (xml == null) {
-                               xml = reader.ReadOuterXml ();
+#if true
+                       if (xml_bak == null) {
+                               if (consumed)
+                                       throw new InvalidOperationException ("Body xml reader is already consumed");
+                               var sw = new StringWriter ();
+                               var xw = XmlDictionaryWriter.CreateDictionaryWriter (XmlWriter.Create (sw));
+                               xw.WriteStartElement (reader.Prefix, reader.LocalName, reader.NamespaceURI);
+                               xw.WriteAttributes (reader, false);
+
+                               var nsmgr = new XmlNamespaceManager (reader.NameTable);
+                               var inr = reader as IXmlNamespaceResolver;
+                               if (inr != null)
+                                       foreach (var p in inr.GetNamespacesInScope (XmlNamespaceScope.ExcludeXml))
+                                               if (xw.LookupPrefix (p.Value) != p.Key)
+                                                       xw.WriteXmlnsAttribute (p.Key, p.Value);
+                               if (!reader.IsEmptyElement) {
+                                       reader.Read ();
+                                       while (reader.NodeType != XmlNodeType.EndElement)
+                                               xw.WriteNode (reader, false);
+                               }
+                               xw.WriteEndElement ();
+
+                               xw.Close ();
+                               xml_bak = sw.ToString ();
                                reader = null;
                        }
-                       return new XmlReaderBodyWriter (xml);
+#else // FIXME: this should be better, but somehow doesn't work.
+                       if (xml_bak == null) {
+                               if (consumed)
+                                       throw new InvalidOperationException ("Body xml reader is already consumed");
+                               var nss = new XmlNamespaceManager (reader.NameTable);
+                               var nsr = reader as IXmlNamespaceResolver;
+                               if (nsr != null)
+                                       foreach (var p in nsr.GetNamespacesInScope (XmlNamespaceScope.ExcludeXml))
+                                               nss.AddNamespace (p.Key, p.Value);
+                               parser_context = new XmlParserContext (nss.NameTable, nss, reader.XmlLang, reader.XmlSpace);
+                               xml_bak = reader.ReadOuterXml ();
+                       }
+#endif
+                       return new XmlReaderBodyWriter (xml_bak, maxBufferSize, parser_context);
                }
 
                protected override void OnWriteBodyContents (
                        XmlDictionaryWriter writer)
                {
-                       if (reader == null && String.IsNullOrEmpty (xml))
+                       if (consumed)
+                               throw new InvalidOperationException ("Body xml reader is already consumed");
+                       if (reader == null && String.IsNullOrEmpty (xml_bak))
                                return;
-                       XmlReader r = reader ?? XmlReader.Create (new StringReader (xml));
+                       XmlReader r = xml_bak != null ? XmlReader.Create (new StringReader (xml_bak), null, parser_context) : reader;
                        r.MoveToContent ();
                        writer.WriteNode (r, false);
+                       if (xml_bak == null)
+                               consumed = true;
                }
        }
 }
index af37d8e4f92b99d9e0396c312475c160d65712d7..e2ed560321710d74a2bb485130735c5abbfa4a48 100644 (file)
@@ -65,6 +65,15 @@ namespace System.ServiceModel.Configuration
                protected override object GetElementKey (ConfigurationElement element) {
                        return ((BaseAddressElement) element).BaseAddress;
                }
+
+               protected override ConfigurationElement CreateNewElement ()
+               {
+                       return new BaseAddressElement ();
+               }
+
+               protected override bool ThrowOnDuplicate {
+                       get { return false; }
+               }
        }
 
 }
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Configuration/BaseAddressPrefixFilterElement.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Configuration/BaseAddressPrefixFilterElement.cs
new file mode 100644 (file)
index 0000000..5bf6098
--- /dev/null
@@ -0,0 +1,102 @@
+//
+// BaseAddressPrefixFilterElement.cs
+//
+// Author:
+//     Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2010 Novell, Inc.  http://www.novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Configuration;
+using System.Net;
+using System.Net.Security;
+using System.Reflection;
+using System.Security.Cryptography.X509Certificates;
+using System.Security.Principal;
+using System.IdentityModel.Claims;
+using System.IdentityModel.Policy;
+using System.IdentityModel.Tokens;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Diagnostics;
+using System.ServiceModel.Dispatcher;
+using System.ServiceModel.MsmqIntegration;
+using System.ServiceModel.PeerResolvers;
+using System.ServiceModel.Security;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Xml;
+
+namespace System.ServiceModel.Configuration
+{
+       public sealed class BaseAddressPrefixFilterElement
+                : ConfigurationElement
+       {
+               // Static Fields
+               static ConfigurationPropertyCollection properties;
+               static ConfigurationProperty prefix;
+
+               static BaseAddressPrefixFilterElement ()
+               {
+                       properties = new ConfigurationPropertyCollection ();
+                       prefix = new ConfigurationProperty ("prefix",
+                               typeof (Uri), null, new UriTypeConverter (), new StringValidator (1, int.MaxValue, null),
+                               ConfigurationPropertyOptions.IsRequired| ConfigurationPropertyOptions.IsKey);
+
+                       properties.Add (prefix);
+               }
+
+               public BaseAddressPrefixFilterElement ()
+               {
+               }
+
+               public BaseAddressPrefixFilterElement (Uri prefix)
+               {
+                       Prefix = prefix;
+               }
+
+
+               // Properties
+
+               [ConfigurationProperty ("prefix",
+                        Options = ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey,
+                       IsRequired = true,
+                       IsKey = true)]
+               public Uri Prefix {
+                       get { return (Uri) base [prefix]; }
+                       set { base [prefix] = value; }
+               }
+
+               protected override ConfigurationPropertyCollection Properties {
+                       get { return properties; }
+               }
+
+
+       }
+
+}
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Configuration/BaseAddressPrefixFilterElementCollection.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Configuration/BaseAddressPrefixFilterElementCollection.cs
new file mode 100644 (file)
index 0000000..06d293d
--- /dev/null
@@ -0,0 +1,79 @@
+//
+// BaseAddressPrefixFilterElementCollection.cs
+//
+// Author:
+//     Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2010 Novell, Inc.  http://www.novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Configuration;
+using System.Net;
+using System.Net.Security;
+using System.Reflection;
+using System.Security.Cryptography.X509Certificates;
+using System.Security.Principal;
+using System.IdentityModel.Claims;
+using System.IdentityModel.Policy;
+using System.IdentityModel.Tokens;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using System.ServiceModel.Diagnostics;
+using System.ServiceModel.Dispatcher;
+using System.ServiceModel.MsmqIntegration;
+using System.ServiceModel.PeerResolvers;
+using System.ServiceModel.Security;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Xml;
+
+namespace System.ServiceModel.Configuration
+{
+       [ConfigurationCollection (typeof (BaseAddressPrefixFilterElement),
+                AddItemName = "add",
+                RemoveItemName = "remove",
+                ClearItemsName = "clear",
+                CollectionType = ConfigurationElementCollectionType.BasicMap)]
+       public sealed class BaseAddressPrefixFilterElementCollection
+                : ServiceModelConfigurationElementCollection<BaseAddressPrefixFilterElement>,  ICollection,  IEnumerable
+       {
+               protected override object GetElementKey (ConfigurationElement element) {
+                       return ((BaseAddressPrefixFilterElement) element).Prefix;
+               }
+
+               protected override ConfigurationElement CreateNewElement ()
+               {
+                       return new BaseAddressPrefixFilterElement ();
+               }
+
+               protected override bool ThrowOnDuplicate {
+                       get { return false; }
+               }
+       }
+
+}
index 7db15e6c54cab17fdd26c6fd91cd3175219e4a99..fe1c268edb5cfec6fa2b3a807cb19d9f0a19b886 100644 (file)
@@ -224,6 +224,29 @@ namespace System.ServiceModel.Configuration
                        basicHttpBinding.TransferMode = TransferMode;
                        basicHttpBinding.UseDefaultWebProxy = UseDefaultWebProxy;
                }
+
+               protected internal override void InitializeFrom (Binding binding)
+               {
+                       BasicHttpBinding b = (BasicHttpBinding) binding;
+                       
+                       base.InitializeFrom (binding);
+                       AllowCookies = b.AllowCookies;
+                       BypassProxyOnLocal = b.BypassProxyOnLocal;
+                       HostNameComparisonMode = b.HostNameComparisonMode;
+                       MaxBufferPoolSize = b.MaxBufferPoolSize;
+                       MaxBufferSize = b.MaxBufferSize;
+                       MaxReceivedMessageSize = b.MaxReceivedMessageSize;
+                       MessageEncoding = b.MessageEncoding;
+                       ProxyAddress = b.ProxyAddress;
+
+                       ReaderQuotas.ApplyConfiguration (b.ReaderQuotas);
+
+                       Security.Mode = b.Security.Mode;
+                       Security.Transport.ApplyConfiguration (b.Security.Transport);
+                       TextEncoding = b.TextEncoding;
+                       TransferMode = b.TransferMode;
+                       UseDefaultWebProxy = b.UseDefaultWebProxy;
+               }
        }
 
 }
index ddfecf263043def035c9d11313aa7682e06ebf9d..a83fffc8b2ede9ea49d1c7a61148b3c56ec1ee6b 100644 (file)
@@ -106,11 +106,40 @@ namespace System.ServiceModel.Configuration
                        get { return (XmlDictionaryReaderQuotasElement) base ["readerQuotas"]; }
                }
 
-               [MonoTODO]
-               protected internal override BindingElement CreateBindingElement () {
-                       throw new NotImplementedException ();
+               protected internal override BindingElement CreateBindingElement ()
+               {
+                       return new BinaryMessageEncodingBindingElement ();
                }
 
+               public override void ApplyConfiguration (BindingElement element)
+               {
+                       var b = (BinaryMessageEncodingBindingElement) element;
+                       b.MaxReadPoolSize = MaxReadPoolSize;
+                       b.MaxSessionSize = MaxSessionSize;
+                       b.MaxWritePoolSize = MaxWritePoolSize;
+
+                       ReaderQuotas.ApplyConfiguration (b.ReaderQuotas);
+               }
+
+               public override void CopyFrom (ServiceModelExtensionElement element)
+               {
+                       var b = (BinaryMessageEncodingElement) element;
+                       MaxReadPoolSize = b.MaxReadPoolSize;
+                       MaxSessionSize = b.MaxSessionSize;
+                       MaxWritePoolSize = b.MaxWritePoolSize;
+
+                       ReaderQuotas.CopyFrom (b.ReaderQuotas);
+               }
+
+               protected internal override void InitializeFrom (BindingElement element)
+               {
+                       var b = (BinaryMessageEncodingBindingElement) element;
+                       MaxReadPoolSize = b.MaxReadPoolSize;
+                       MaxSessionSize = b.MaxSessionSize;
+                       MaxWritePoolSize = b.MaxWritePoolSize;
+
+                       ReaderQuotas.InitializeFrom (b.ReaderQuotas);
+               }
        }
 
 }
index 6f2e4a7a2c70cbe06611903a77cbf080fedd1df3..a5708f2b9217173f9116da4da1e1e83f9da3f007 100644 (file)
@@ -63,16 +63,12 @@ namespace System.ServiceModel.Configuration
                // Properties
                public abstract Type BindingElementType { get; }
 
-               [MonoTODO]
                public virtual void ApplyConfiguration (BindingElement bindingElement) {
-                       throw new NotImplementedException ();
                }
 
                protected internal abstract BindingElement CreateBindingElement ();
 
-               [MonoTODO]
                protected internal virtual void InitializeFrom (BindingElement bindingElement) {
-                       throw new NotImplementedException ();
                }
 
                internal override string GetConfigurationElementName () {
index 756dae16d18528f31d2f0170ae744668b52da1f2..39440be8b654d133702d8ba415034390c3ac3cc3 100755 (executable)
@@ -1,3 +1,59 @@
+2010-04-05  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * BaseAddressPrefixFilterElementCollection.cs
+         BaseAddressPrefixFilterElement.cs : new classes.
+       * ReliableSessionElement.cs
+         XmlDictionaryReaderQuotasElement.cs
+         TextMessageEncodingElement.cs
+         HostTimeoutsElement.cs
+         BaseAddressElementCollection.cs
+         BasicHttpBindingElement.cs
+         BindingElementExtensionElement.cs
+         StandardBindingElement.cs
+         BinaryMessageEncodingElement.cs : added couple of missing stuff.
+
+2010-03-23  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ConnectionOrientedTransportElement.cs, StandardBindingElement.cs, 
+         LocalClientSecuritySettingsElement.cs, CustomBindingElement.cs:
+         add couple of missing methods and TypeConverterAttributes.
+
+2010-03-17  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ServiceMetadataPublishingElement.cs : use IsNullOrEmpty(), names
+         could be "" which is equivalent to null here.
+
+2010-03-17  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ConfigUtil.cs, StandardBindingCollectionElement.cs,
+         MexHttpsBindingCollectionElement.cs,
+         MexHttpBindingCollectionElement.cs : use GetDefault() in
+         BindingCollectionElement to create a Binding, instead of activator
+         immediately. And for mex bindings, use MetadataExchangeBindings.
+
+2010-03-16  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * TcpTransportElement.cs
+         MsmqIntegrationElement.cs
+         MsmqElementBase.cs
+         NamedPipeTransportElement.cs
+         HttpsTransportElement.cs
+         TransportElement.cs
+         MsmqTransportElement.cs
+         HttpTransportElement.cs : implement missing methods.
+
+2010-03-16  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * IssuedTokenClientElement.cs, MsmqBindingElementBase.cs,
+         NamedPipeConnectionPoolSettingsElement.cs,
+         TcpConnectionPoolSettingsElement.cs,
+         StandardBindingReliableSessionElement.cs,
+         LocalServiceSecuritySettingsElement.cs : use TimeSpanConverter.
+
+2010-03-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ServiceDebugElement.cs : binding names could rather be empty.
+
 2010-03-09  Atsushi Enomoto  <atsushi@ximian.com>
 
        * XmlDictionaryReaderQuotasElement.cs : add ApplyConfiguration().
index 360fe8cf05f7933eaedc15f3d243cfae24b859c0..ba23d85f08e97240b473a31321dfb6f982297d74 100644 (file)
@@ -74,7 +74,7 @@ namespace System.ServiceModel.Configuration
                        if (section == null)
                                throw new ArgumentException (String.Format ("binding section for {0} was not found.", binding));
 
-                       Binding b = (Binding) Activator.CreateInstance (section.BindingType, new object [0]);
+                       Binding b = section.GetDefault ();
 
                        foreach (IBindingConfigurationElement el in section.ConfiguredBindings)
                                if (el.Name == bindingConfiguration)
index 59c9bb259f00559a7197237dfe5e99da2e52ff73..5ec8e8dde055f1da4a64f6ea50d7de1b4053bee7 100644 (file)
@@ -59,7 +59,8 @@ namespace System.ServiceModel.Configuration
        {
                ConfigurationPropertyCollection _properties;
 
-               protected ConnectionOrientedTransportElement () {
+               internal ConnectionOrientedTransportElement ()
+               {
                }
 
                // Properties
@@ -67,6 +68,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("channelInitializationTimeout",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:00:05")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan ChannelInitializationTimeout {
                        get { return (TimeSpan) base ["channelInitializationTimeout"]; }
                        set { base ["channelInitializationTimeout"] = value; }
@@ -105,6 +107,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("maxOutputDelay",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:00:00.2")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan MaxOutputDelay {
                        get { return (TimeSpan) base ["maxOutputDelay"]; }
                        set { base ["maxOutputDelay"] = value; }
@@ -157,7 +160,44 @@ namespace System.ServiceModel.Configuration
                        set { base ["transferMode"] = value; }
                }
 
+               public override void ApplyConfiguration (BindingElement bindingElement)
+               {
+                       var e = (ConnectionOrientedTransportBindingElement) bindingElement;
+                       e.ChannelInitializationTimeout = ChannelInitializationTimeout;
+                       e.ConnectionBufferSize = ConnectionBufferSize;
+                       e.HostNameComparisonMode = HostNameComparisonMode;
+                       e.MaxBufferSize = MaxBufferSize;
+                       e.MaxOutputDelay = MaxOutputDelay;
+                       e.MaxPendingAccepts = MaxPendingAccepts;
+                       e.MaxPendingConnections = MaxPendingConnections;
+                       e.TransferMode = TransferMode;
+               }
+
+               public override void CopyFrom (ServiceModelExtensionElement from)
+               {
+                       var e = (ConnectionOrientedTransportElement) from;
+                       ChannelInitializationTimeout = e.ChannelInitializationTimeout;
+                       ConnectionBufferSize = e.ConnectionBufferSize;
+                       HostNameComparisonMode = e.HostNameComparisonMode;
+                       MaxBufferSize = e.MaxBufferSize;
+                       MaxOutputDelay = e.MaxOutputDelay;
+                       MaxPendingAccepts = e.MaxPendingAccepts;
+                       MaxPendingConnections = e.MaxPendingConnections;
+                       TransferMode = e.TransferMode;
+               }
 
+               protected internal override void InitializeFrom (BindingElement bindingElement)
+               {
+                       var e = (ConnectionOrientedTransportBindingElement) bindingElement;
+                       ChannelInitializationTimeout = e.ChannelInitializationTimeout;
+                       ConnectionBufferSize = e.ConnectionBufferSize;
+                       HostNameComparisonMode = e.HostNameComparisonMode;
+                       MaxBufferSize = e.MaxBufferSize;
+                       MaxOutputDelay = e.MaxOutputDelay;
+                       MaxPendingAccepts = e.MaxPendingAccepts;
+                       MaxPendingConnections = e.MaxPendingConnections;
+                       TransferMode = e.TransferMode;
+               }
        }
 
 }
index afa1dd0c09e6486b2dc6a8793a45057bb8e0ef05..ccf763505ed8b86aa2fccc30b957795aea6ed298 100644 (file)
@@ -72,6 +72,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("closeTimeout",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:01:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan CloseTimeout {
                        get { return (TimeSpan) base ["closeTimeout"]; }
                        set { base ["closeTimeout"] = value; }
@@ -80,6 +81,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("openTimeout",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:01:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan OpenTimeout {
                        get { return (TimeSpan) base ["openTimeout"]; }
                        set { base ["openTimeout"] = value; }
@@ -101,6 +103,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("receiveTimeout",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:10:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan ReceiveTimeout {
                        get { return (TimeSpan) base ["receiveTimeout"]; }
                        set { base ["receiveTimeout"] = value; }
@@ -109,14 +112,27 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("sendTimeout",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:01:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan SendTimeout {
                        get { return (TimeSpan) base ["sendTimeout"]; }
                        set { base ["sendTimeout"] = value; }
                }
 
-               [MonoTODO]
-               public void ApplyConfiguration (Binding binding) {
-                       throw new NotImplementedException ();
+               [MonoTODO ("what to reject?")]
+               public override void Add (BindingElementExtensionElement element)
+               {
+                       base.Add (element);
+               }
+
+               [MonoTODO ("what to reject?")]
+               public override bool CanAdd (BindingElementExtensionElement element)
+               {
+                       return true;
+               }
+
+               public void ApplyConfiguration (Binding binding)
+               {
+                       OnApplyConfiguration (binding);
                }
 
                [MonoTODO ("implement using EvaluationContext")]
@@ -133,6 +149,19 @@ namespace System.ServiceModel.Configuration
                        return element;
                }
 
+               protected void OnApplyConfiguration (Binding binding)
+               {
+                       if (binding == null)
+                               throw new ArgumentNullException ("binding");
+                       var b = (CustomBinding) binding;
+                       b.CloseTimeout = CloseTimeout;
+                       b.OpenTimeout = OpenTimeout;
+                       b.ReceiveTimeout = ReceiveTimeout;
+                       b.SendTimeout = SendTimeout;
+
+                       foreach (var be in this)
+                               b.Elements.Add (be.CreateBindingElement ());
+               }
        }
 
 }
index 9b1e34f4c2c04fae0ea17d2a1f014db958e349a2..e987942b86dbac171da65ea1218d0d8c6b5d4953 100644 (file)
@@ -62,6 +62,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("closeTimeout",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:00:10")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan CloseTimeout {
                        get { return (TimeSpan) base ["closeTimeout"]; }
                        set { base ["closeTimeout"] = value; }
@@ -70,6 +71,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("openTimeout",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:01:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan OpenTimeout {
                        get { return (TimeSpan) base ["openTimeout"]; }
                        set { base ["openTimeout"] = value; }
index 2412b52d9bc3646cd54422e15e9eea4d1af69767..1933d25a0e805b07a76f1a253c699be5edba244c 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Atsushi Enomoto <atsushi@ximian.com>
 //
-// Copyright (C) 2006 Novell, Inc.  http://www.novell.com
+// Copyright (C) 2006,2010 Novell, Inc.  http://www.novell.com
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -192,12 +192,64 @@ namespace System.ServiceModel.Configuration
                        set { base ["useDefaultWebProxy"] = value; }
                }
 
-
-               [MonoTODO]
-               protected internal override BindingElement CreateBindingElement () {
-                       throw new NotImplementedException ();
+               public override void ApplyConfiguration (BindingElement bindingElement)
+               {
+                       var b = (HttpTransportBindingElement) bindingElement;
+                       base.ApplyConfiguration (b);
+                       b.AllowCookies = AllowCookies;
+                       b.AuthenticationScheme = AuthenticationScheme;
+                       b.BypassProxyOnLocal = BypassProxyOnLocal;
+                       b.HostNameComparisonMode = HostNameComparisonMode;
+                       b.KeepAliveEnabled = KeepAliveEnabled;
+                       b.MaxBufferSize = MaxBufferSize;
+                       b.ProxyAddress = ProxyAddress;
+                       b.ProxyAuthenticationScheme = ProxyAuthenticationScheme;
+                       b.Realm = Realm;
+                       b.TransferMode = TransferMode;
+                       b.UnsafeConnectionNtlmAuthentication = UnsafeConnectionNtlmAuthentication;
+                       b.UseDefaultWebProxy = UseDefaultWebProxy;
+               }
+
+               public override void CopyFrom (ServiceModelExtensionElement from)
+               {
+                       var e = (HttpTransportElement) from;
+                       base.CopyFrom (from);
+                       AllowCookies = e.AllowCookies;
+                       AuthenticationScheme = e.AuthenticationScheme;
+                       BypassProxyOnLocal = e.BypassProxyOnLocal;
+                       HostNameComparisonMode = e.HostNameComparisonMode;
+                       KeepAliveEnabled = e.KeepAliveEnabled;
+                       MaxBufferSize = e.MaxBufferSize;
+                       ProxyAddress = e.ProxyAddress;
+                       ProxyAuthenticationScheme = e.ProxyAuthenticationScheme;
+                       Realm = e.Realm;
+                       TransferMode = e.TransferMode;
+                       UnsafeConnectionNtlmAuthentication = e.UnsafeConnectionNtlmAuthentication;
+                       UseDefaultWebProxy = e.UseDefaultWebProxy;
+               }
+
+               protected override TransportBindingElement CreateDefaultBindingElement ()
+               {
+                       return new HttpTransportBindingElement ();
+               }
+
+               protected internal override void InitializeFrom (BindingElement bindingElement)
+               {
+                       var b = (HttpTransportBindingElement) bindingElement;
+                       base.InitializeFrom (b);
+                       AllowCookies = b.AllowCookies;
+                       AuthenticationScheme = b.AuthenticationScheme;
+                       BypassProxyOnLocal = b.BypassProxyOnLocal;
+                       HostNameComparisonMode = b.HostNameComparisonMode;
+                       KeepAliveEnabled = b.KeepAliveEnabled;
+                       MaxBufferSize = b.MaxBufferSize;
+                       ProxyAddress = b.ProxyAddress;
+                       ProxyAuthenticationScheme = b.ProxyAuthenticationScheme;
+                       Realm = b.Realm;
+                       TransferMode = b.TransferMode;
+                       UnsafeConnectionNtlmAuthentication = b.UnsafeConnectionNtlmAuthentication;
+                       UseDefaultWebProxy = b.UseDefaultWebProxy;
                }
-
        }
 
 }
index c844e56dc940dbd4a5dd0f3d0a1f8267046e37b4..a2de9b7555085f7333de6aa23d16a56ce93d99a2 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Atsushi Enomoto <atsushi@ximian.com>
 //
-// Copyright (C) 2006 Novell, Inc.  http://www.novell.com
+// Copyright (C) 2006,2010 Novell, Inc.  http://www.novell.com
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -87,7 +87,31 @@ namespace System.ServiceModel.Configuration
                        set { base ["requireClientCertificate"] = value; }
                }
 
+               public override void ApplyConfiguration (BindingElement bindingElement)
+               {
+                       var b = (HttpsTransportBindingElement) bindingElement;
+                       base.ApplyConfiguration (b);
+                       b.RequireClientCertificate = RequireClientCertificate;
+               }
+
+               public override void CopyFrom (ServiceModelExtensionElement from)
+               {
+                       var e = (HttpsTransportElement) from;
+                       base.CopyFrom (from);
+                       RequireClientCertificate = e.RequireClientCertificate;
+               }
 
+               protected override TransportBindingElement CreateDefaultBindingElement ()
+               {
+                       return new HttpsTransportBindingElement ();
+               }
+
+               protected internal override void InitializeFrom (BindingElement bindingElement)
+               {
+                       var b = (HttpsTransportBindingElement) bindingElement;
+                       base.InitializeFrom (b);
+                       RequireClientCertificate = b.RequireClientCertificate;
+               }
        }
 
 }
index 064d26ceb164fa276080e79f5282af68d0a0beb9..a6d8f55d8c35e7374c5d7323468b1bb6ce00d939 100644 (file)
@@ -96,7 +96,7 @@ namespace System.ServiceModel.Configuration
                                ConfigurationPropertyOptions.None);
 
                        max_issued_token_caching_time = new ConfigurationProperty ("maxIssuedTokenCachingTime",
-                               typeof (TimeSpan), "10675199.02:48:05.4775807", null/* FIXME: get converter for TimeSpan*/, null,
+                               typeof (TimeSpan), "10675199.02:48:05.4775807", new TimeSpanConverter (), null,
                                ConfigurationPropertyOptions.None);
 
                        properties.Add (cache_issued_tokens);
@@ -168,6 +168,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("maxIssuedTokenCachingTime",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "10675199.02:48:05.4775807")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan MaxIssuedTokenCachingTime {
                        get { return (TimeSpan) base [max_issued_token_caching_time]; }
                        set { base [max_issued_token_caching_time] = value; }
index c0dce430f196af6564b33716d950adaa3fb5306c..9055f054906b5d8caef822a8ae25628f926a36b1 100644 (file)
@@ -94,6 +94,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("maxClockSkew",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:05:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan MaxClockSkew {
                        get { return (TimeSpan) base ["maxClockSkew"]; }
                        set { base ["maxClockSkew"] = value; }
@@ -102,6 +103,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("maxCookieCachingTime",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "10675199.02:48:05.4775807")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan MaxCookieCachingTime {
                        get { return (TimeSpan) base ["maxCookieCachingTime"]; }
                        set { base ["maxCookieCachingTime"] = value; }
@@ -133,6 +135,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("replayWindow",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:05:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan ReplayWindow {
                        get { return (TimeSpan) base ["replayWindow"]; }
                        set { base ["replayWindow"] = value; }
@@ -141,6 +144,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("sessionKeyRenewalInterval",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "10:00:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan SessionKeyRenewalInterval {
                        get { return (TimeSpan) base ["sessionKeyRenewalInterval"]; }
                        set { base ["sessionKeyRenewalInterval"] = value; }
@@ -157,6 +161,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("timestampValidityDuration",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:05:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan TimestampValidityDuration {
                        get { return (TimeSpan) base ["timestampValidityDuration"]; }
                        set { base ["timestampValidityDuration"] = value; }
index 99d7649518eb8d9e8e6f84eb3aa55a93c18c4e3f..cf4bc33dc381c79cae7e5b02d50ef1bdd018cd9b 100644 (file)
@@ -83,11 +83,11 @@ namespace System.ServiceModel.Configuration
                                ConfigurationPropertyOptions.None);
 
                        inactivity_timeout = new ConfigurationProperty ("inactivityTimeout",
-                               typeof (TimeSpan), "00:02:00", null/* FIXME: get converter for TimeSpan*/, null,
+                               typeof (TimeSpan), "00:02:00", new TimeSpanConverter (), null,
                                ConfigurationPropertyOptions.None);
 
                        issued_cookie_lifetime = new ConfigurationProperty ("issuedCookieLifetime",
-                               typeof (TimeSpan), "10:00:00", null/* FIXME: get converter for TimeSpan*/, null,
+                               typeof (TimeSpan), "10:00:00", new TimeSpanConverter (), null,
                                ConfigurationPropertyOptions.None);
 
                        max_cached_cookies = new ConfigurationProperty ("maxCachedCookies",
@@ -95,7 +95,7 @@ namespace System.ServiceModel.Configuration
                                ConfigurationPropertyOptions.None);
 
                        max_clock_skew = new ConfigurationProperty ("maxClockSkew",
-                               typeof (TimeSpan), "00:05:00", null/* FIXME: get converter for TimeSpan*/, null,
+                               typeof (TimeSpan), "00:05:00", new TimeSpanConverter (), null,
                                ConfigurationPropertyOptions.None);
 
                        max_pending_sessions = new ConfigurationProperty ("maxPendingSessions",
@@ -107,7 +107,7 @@ namespace System.ServiceModel.Configuration
                                ConfigurationPropertyOptions.None);
 
                        negotiation_timeout = new ConfigurationProperty ("negotiationTimeout",
-                               typeof (TimeSpan), "00:01:00", null/* FIXME: get converter for TimeSpan*/, null,
+                               typeof (TimeSpan), "00:01:00", new TimeSpanConverter (), null,
                                ConfigurationPropertyOptions.None);
 
                        reconnect_transport_on_failure = new ConfigurationProperty ("reconnectTransportOnFailure",
@@ -119,19 +119,19 @@ namespace System.ServiceModel.Configuration
                                ConfigurationPropertyOptions.None);
 
                        replay_window = new ConfigurationProperty ("replayWindow",
-                               typeof (TimeSpan), "00:05:00", null/* FIXME: get converter for TimeSpan*/, null,
+                               typeof (TimeSpan), "00:05:00", new TimeSpanConverter (), null,
                                ConfigurationPropertyOptions.None);
 
                        session_key_renewal_interval = new ConfigurationProperty ("sessionKeyRenewalInterval",
-                               typeof (TimeSpan), "15:00:00", null/* FIXME: get converter for TimeSpan*/, null,
+                               typeof (TimeSpan), "15:00:00", new TimeSpanConverter (), null,
                                ConfigurationPropertyOptions.None);
 
                        session_key_rollover_interval = new ConfigurationProperty ("sessionKeyRolloverInterval",
-                               typeof (TimeSpan), "00:05:00", null/* FIXME: get converter for TimeSpan*/, null,
+                               typeof (TimeSpan), "00:05:00", new TimeSpanConverter (), null,
                                ConfigurationPropertyOptions.None);
 
                        timestamp_validity_duration = new ConfigurationProperty ("timestampValidityDuration",
-                               typeof (TimeSpan), "00:05:00", null/* FIXME: get converter for TimeSpan*/, null,
+                               typeof (TimeSpan), "00:05:00", new TimeSpanConverter (), null,
                                ConfigurationPropertyOptions.None);
 
                        properties.Add (detect_replays);
@@ -168,6 +168,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("inactivityTimeout",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:02:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan InactivityTimeout {
                        get { return (TimeSpan) base [inactivity_timeout]; }
                        set { base [inactivity_timeout] = value; }
@@ -176,6 +177,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("issuedCookieLifetime",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "10:00:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan IssuedCookieLifetime {
                        get { return (TimeSpan) base [issued_cookie_lifetime]; }
                        set { base [issued_cookie_lifetime] = value; }
@@ -195,6 +197,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("maxClockSkew",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:05:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan MaxClockSkew {
                        get { return (TimeSpan) base [max_clock_skew]; }
                        set { base [max_clock_skew] = value; }
@@ -225,6 +228,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("negotiationTimeout",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:01:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan NegotiationTimeout {
                        get { return (TimeSpan) base [negotiation_timeout]; }
                        set { base [negotiation_timeout] = value; }
@@ -256,6 +260,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("replayWindow",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:05:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan ReplayWindow {
                        get { return (TimeSpan) base [replay_window]; }
                        set { base [replay_window] = value; }
@@ -264,6 +269,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("sessionKeyRenewalInterval",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "15:00:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan SessionKeyRenewalInterval {
                        get { return (TimeSpan) base [session_key_renewal_interval]; }
                        set { base [session_key_renewal_interval] = value; }
@@ -272,6 +278,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("sessionKeyRolloverInterval",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:05:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan SessionKeyRolloverInterval {
                        get { return (TimeSpan) base [session_key_rollover_interval]; }
                        set { base [session_key_rollover_interval] = value; }
@@ -280,6 +287,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("timestampValidityDuration",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:05:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan TimestampValidityDuration {
                        get { return (TimeSpan) base [timestamp_validity_duration]; }
                        set { base [timestamp_validity_duration] = value; }
index d9d252e28291590fa291c0e60a51538f86b8ae58..c97a174c2b8347a3f19621f29029bb605c9910b2 100644 (file)
@@ -54,7 +54,6 @@ using System.Xml;
 
 namespace System.ServiceModel.Configuration
 {
-       [MonoTODO]
        public partial class MexHttpBindingCollectionElement
                 : MexBindingBindingCollectionElement<WSHttpBinding, MexHttpBindingElement>
        {
@@ -70,10 +69,10 @@ namespace System.ServiceModel.Configuration
                {
                }
 
-
-               // Properties
-
-
+               protected internal override Binding GetDefault ()
+               {
+                       return MetadataExchangeBindings.CreateMexHttpBinding ();
+               }
        }
 
 }
index 09eaf398e30b2934e5636c77c4e579852c3594b2..d7288f40f11937f788600e0bd771c80c7c73443c 100644 (file)
@@ -54,7 +54,6 @@ using System.Xml;
 
 namespace System.ServiceModel.Configuration
 {
-       [MonoTODO]
        public partial class MexHttpsBindingCollectionElement
                 : MexBindingBindingCollectionElement<WSHttpBinding, MexHttpsBindingElement>
        {
@@ -70,10 +69,10 @@ namespace System.ServiceModel.Configuration
                {
                }
 
-
-               // Properties
-
-
+               protected internal override Binding GetDefault ()
+               {
+                       return MetadataExchangeBindings.CreateMexHttpsBinding ();
+               }
        }
 
 }
index d4f5d86d72be26e76b1bac9e270de4d2a450af3d..a88ce844e65c2fcbd0e5de3e69f5e68ba5863a85 100644 (file)
@@ -109,11 +109,11 @@ namespace System.ServiceModel.Configuration
                                ConfigurationPropertyOptions.None);
 
                        retry_cycle_delay = new ConfigurationProperty ("retryCycleDelay",
-                               typeof (TimeSpan), "00:30:00", null/* FIXME: get converter for TimeSpan*/, null,
+                               typeof (TimeSpan), "00:30:00", new TimeSpanConverter (), null,
                                ConfigurationPropertyOptions.None);
 
                        time_to_live = new ConfigurationProperty ("timeToLive",
-                               typeof (TimeSpan), "1.00:00:00", null/* FIXME: get converter for TimeSpan*/, null,
+                               typeof (TimeSpan), "1.00:00:00", new TimeSpanConverter (), null,
                                ConfigurationPropertyOptions.None);
 
                        use_msmq_tracing = new ConfigurationProperty ("useMsmqTracing",
@@ -225,6 +225,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("retryCycleDelay",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:30:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan RetryCycleDelay {
                        get { return (TimeSpan) base [retry_cycle_delay]; }
                        set { base [retry_cycle_delay] = value; }
@@ -233,6 +234,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("timeToLive",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "1.00:00:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan TimeToLive {
                        get { return (TimeSpan) base [time_to_live]; }
                        set { base [time_to_live] = value; }
index 81d05957c9ff69827a3be519c150f44ec663f193..1ad2b2a1f3fec7ab8eef2106f3b6f10e2f273fdb 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Atsushi Enomoto <atsushi@ximian.com>
 //
-// Copyright (C) 2006 Novell, Inc.  http://www.novell.com
+// Copyright (C) 2006,2010 Novell, Inc.  http://www.novell.com
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -186,7 +186,77 @@ namespace System.ServiceModel.Configuration
                        set { base ["useSourceJournal"] = value; }
                }
 
+               public override void ApplyConfiguration (BindingElement bindingElement)
+               {
+                       var b = (System.ServiceModel.Channels.MsmqBindingElementBase) bindingElement;
+                       base.ApplyConfiguration (b);
+                       b.CustomDeadLetterQueue = CustomDeadLetterQueue;
+                       b.DeadLetterQueue = DeadLetterQueue;
+                       b.Durable = Durable;
+                       b.ExactlyOnce = ExactlyOnce;
+                       b.MaxRetryCycles = MaxRetryCycles;
+                       b.ReceiveErrorHandling = ReceiveErrorHandling;
+                       b.ReceiveRetryCount = ReceiveRetryCount;
+                       b.RetryCycleDelay = RetryCycleDelay;
+                       b.TimeToLive = TimeToLive;
+                       b.UseMsmqTracing = UseMsmqTracing;
+                       b.UseSourceJournal = UseSourceJournal;
 
+                       var bs = b.MsmqTransportSecurity;
+                       var cs = MsmqTransportSecurity;
+                       bs.MsmqAuthenticationMode = cs.MsmqAuthenticationMode;
+                       bs.MsmqEncryptionAlgorithm = cs.MsmqEncryptionAlgorithm;
+                       bs.MsmqProtectionLevel = cs.MsmqProtectionLevel;
+                       bs.MsmqSecureHashAlgorithm = cs.MsmqSecureHashAlgorithm;
+               }
+
+               public override void CopyFrom (ServiceModelExtensionElement from)
+               {
+                       var e = (MsmqElementBase) from;
+                       base.CopyFrom (from);
+                       CustomDeadLetterQueue = e.CustomDeadLetterQueue;
+                       DeadLetterQueue = e.DeadLetterQueue;
+                       Durable = e.Durable;
+                       ExactlyOnce = e.ExactlyOnce;
+                       MaxRetryCycles = e.MaxRetryCycles;
+                       ReceiveErrorHandling = e.ReceiveErrorHandling;
+                       ReceiveRetryCount = e.ReceiveRetryCount;
+                       RetryCycleDelay = e.RetryCycleDelay;
+                       TimeToLive = e.TimeToLive;
+                       UseMsmqTracing = e.UseMsmqTracing;
+                       UseSourceJournal = e.UseSourceJournal;
+
+                       var es = e.MsmqTransportSecurity;
+                       var cs = MsmqTransportSecurity;
+                       cs.MsmqAuthenticationMode = es.MsmqAuthenticationMode;
+                       cs.MsmqEncryptionAlgorithm = es.MsmqEncryptionAlgorithm;
+                       cs.MsmqProtectionLevel = es.MsmqProtectionLevel;
+                       cs.MsmqSecureHashAlgorithm = es.MsmqSecureHashAlgorithm;
+               }
+
+               protected internal override void InitializeFrom (BindingElement bindingElement)
+               {
+                       var b = (System.ServiceModel.Channels.MsmqBindingElementBase) bindingElement;
+                       base.InitializeFrom (b);
+                       CustomDeadLetterQueue = b.CustomDeadLetterQueue;
+                       DeadLetterQueue = b.DeadLetterQueue;
+                       Durable = b.Durable;
+                       ExactlyOnce = b.ExactlyOnce;
+                       MaxRetryCycles = b.MaxRetryCycles;
+                       ReceiveErrorHandling = b.ReceiveErrorHandling;
+                       ReceiveRetryCount = b.ReceiveRetryCount;
+                       RetryCycleDelay = b.RetryCycleDelay;
+                       TimeToLive = b.TimeToLive;
+                       UseMsmqTracing = b.UseMsmqTracing;
+                       UseSourceJournal = b.UseSourceJournal;
+
+                       var bs = b.MsmqTransportSecurity;
+                       var cs = MsmqTransportSecurity;
+                       cs.MsmqAuthenticationMode = bs.MsmqAuthenticationMode;
+                       cs.MsmqEncryptionAlgorithm = bs.MsmqEncryptionAlgorithm;
+                       cs.MsmqProtectionLevel = bs.MsmqProtectionLevel;
+                       cs.MsmqSecureHashAlgorithm = bs.MsmqSecureHashAlgorithm;
+               }
        }
 
 }
index 06876fdac3de3793dce577fa6d86d83d2658aabf..f1acfbd36df07f603adee7998ded6c8fea25f9d8 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Atsushi Enomoto <atsushi@ximian.com>
 //
-// Copyright (C) 2006 Novell, Inc.  http://www.novell.com
+// Copyright (C) 2006,2010 Novell, Inc.  http://www.novell.com
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -86,12 +86,31 @@ namespace System.ServiceModel.Configuration
                        set { base ["serializationFormat"] = value; }
                }
 
+               public override void ApplyConfiguration (BindingElement bindingElement)
+               {
+                       var b = (System.ServiceModel.MsmqIntegration.MsmqIntegrationBindingElement) bindingElement;
+                       base.ApplyConfiguration (b);
+                       b.SerializationFormat = SerializationFormat;
+               }
+
+               public override void CopyFrom (ServiceModelExtensionElement from)
+               {
+                       var e = (MsmqIntegrationElement) from;
+                       base.CopyFrom (from);
+                       SerializationFormat = e.SerializationFormat;
+               }
 
-               [MonoTODO]
-               protected internal override BindingElement CreateBindingElement () {
-                       throw new NotImplementedException ();
+               protected override TransportBindingElement CreateDefaultBindingElement ()
+               {
+                       return new System.ServiceModel.MsmqIntegration.MsmqIntegrationBindingElement ();
                }
 
+               protected internal override void InitializeFrom (BindingElement bindingElement)
+               {
+                       var b = (System.ServiceModel.MsmqIntegration.MsmqIntegrationBindingElement) bindingElement;
+                       base.InitializeFrom (b);
+                       SerializationFormat = b.SerializationFormat;
+               }
        }
 
 }
index 59bb88b813937c43ae8df2c5f8e53ee5a13fb6cd..f4235e85cf58ff4e271b1dd67b95bc73a7bcf49c 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Atsushi Enomoto <atsushi@ximian.com>
 //
-// Copyright (C) 2006 Novell, Inc.  http://www.novell.com
+// Copyright (C) 2006,2010 Novell, Inc.  http://www.novell.com
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -108,11 +108,37 @@ namespace System.ServiceModel.Configuration
                        set { base ["useActiveDirectory"] = value; }
                }
 
-               [MonoTODO]
-               protected internal override BindingElement CreateBindingElement () {
-                       throw new NotImplementedException ();
+               public override void ApplyConfiguration (BindingElement bindingElement)
+               {
+                       var b = (MsmqTransportBindingElement) bindingElement;
+                       base.ApplyConfiguration (b);
+                       b.MaxPoolSize = MaxPoolSize;
+                       b.QueueTransferProtocol = QueueTransferProtocol;
+                       b.UseActiveDirectory = UseActiveDirectory;
                }
 
+               public override void CopyFrom (ServiceModelExtensionElement from)
+               {
+                       var e = (MsmqTransportElement) from;
+                       base.CopyFrom (from);
+                       MaxPoolSize = e.MaxPoolSize;
+                       QueueTransferProtocol = e.QueueTransferProtocol;
+                       UseActiveDirectory = e.UseActiveDirectory;
+               }
+
+               protected override TransportBindingElement CreateDefaultBindingElement ()
+               {
+                       return new MsmqTransportBindingElement ();
+               }
+
+               protected internal override void InitializeFrom (BindingElement bindingElement)
+               {
+                       var b = (MsmqTransportBindingElement) bindingElement;
+                       base.InitializeFrom (b);
+                       MaxPoolSize = b.MaxPoolSize;
+                       QueueTransferProtocol = b.QueueTransferProtocol;
+                       UseActiveDirectory = b.UseActiveDirectory;
+               }
        }
 
 }
index e66eee7836abd56a77291bfdb902187ba9a072c3..7d29fdf1fabf158c54f117670d4575538eae2069 100644 (file)
@@ -72,7 +72,7 @@ namespace System.ServiceModel.Configuration
                                ConfigurationPropertyOptions.None);
 
                        idle_timeout = new ConfigurationProperty ("idleTimeout",
-                               typeof (TimeSpan), "00:02:00", null/* FIXME: get converter for TimeSpan*/, null,
+                               typeof (TimeSpan), "00:02:00", new TimeSpanConverter (), null,
                                ConfigurationPropertyOptions.None);
 
                        max_outbound_connections_per_endpoint = new ConfigurationProperty ("maxOutboundConnectionsPerEndpoint",
@@ -105,6 +105,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("idleTimeout",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:02:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan IdleTimeout {
                        get { return (TimeSpan) base [idle_timeout]; }
                        set { base [idle_timeout] = value; }
index d8ba18ec6b52e1d625242b4579c956aec07f5619..82f25055d4125e080ceac755dd602f4cca3c3ef5 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Atsushi Enomoto <atsushi@ximian.com>
 //
-// Copyright (C) 2006 Novell, Inc.  http://www.novell.com
+// Copyright (C) 2006,2010 Novell, Inc.  http://www.novell.com
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -54,7 +54,6 @@ using System.Xml;
 
 namespace System.ServiceModel.Configuration
 {
-       [MonoTODO]
        public sealed partial class NamedPipeTransportElement
                 : ConnectionOrientedTransportElement
        {
@@ -87,11 +86,46 @@ namespace System.ServiceModel.Configuration
                        }
                }
 
-               [MonoTODO]
-               protected internal override BindingElement CreateBindingElement () {
-                       throw new NotImplementedException ();
+               public override void ApplyConfiguration (BindingElement bindingElement)
+               {
+                       var b = (NamedPipeTransportBindingElement) bindingElement;
+                       base.ApplyConfiguration (b);
+
+                       var bs = b.ConnectionPoolSettings;
+                       var cs = ConnectionPoolSettings;
+                       bs.GroupName = cs.GroupName;
+                       bs.IdleTimeout = cs.IdleTimeout;
+                       bs.MaxOutboundConnectionsPerEndpoint = cs.MaxOutboundConnectionsPerEndpoint;
+               }
+
+               public override void CopyFrom (ServiceModelExtensionElement from)
+               {
+                       var e = (NamedPipeTransportElement) from;
+                       base.CopyFrom (from);
+
+                       var es = e.ConnectionPoolSettings;
+                       var cs = ConnectionPoolSettings;
+                       cs.GroupName = es.GroupName;
+                       cs.IdleTimeout = es.IdleTimeout;
+                       cs.MaxOutboundConnectionsPerEndpoint = es.MaxOutboundConnectionsPerEndpoint;
                }
 
+               protected override TransportBindingElement CreateDefaultBindingElement ()
+               {
+                       return new NamedPipeTransportBindingElement ();
+               }
+
+               protected internal override void InitializeFrom (BindingElement bindingElement)
+               {
+                       var b = (NamedPipeTransportBindingElement) bindingElement;
+                       base.InitializeFrom (b);
+
+                       var bs = b.ConnectionPoolSettings;
+                       var cs = ConnectionPoolSettings;
+                       cs.GroupName = bs.GroupName;
+                       cs.IdleTimeout = bs.IdleTimeout;
+                       cs.MaxOutboundConnectionsPerEndpoint = bs.MaxOutboundConnectionsPerEndpoint;
+               }
        }
 
 }
index dc241fe31e6127f9f855441d57ef9ca8f548f53c..41220685f8a117be360ec6228b90ea760877d244 100644 (file)
@@ -65,6 +65,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("acknowledgementInterval",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:00:00.2")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan AcknowledgementInterval {
                        get { return (TimeSpan) base ["acknowledgementInterval"]; }
                        set { base ["acknowledgementInterval"] = value; }
@@ -85,6 +86,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("inactivityTimeout",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:10:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan InactivityTimeout {
                        get { return (TimeSpan) base ["inactivityTimeout"]; }
                        set { base ["inactivityTimeout"] = value; }
@@ -143,9 +145,48 @@ namespace System.ServiceModel.Configuration
                        get { return base.Properties; }
                }
 
-               [MonoTODO]
-               protected internal override BindingElement CreateBindingElement () {
-                       throw new NotImplementedException ();
+               protected internal override BindingElement CreateBindingElement ()
+               {
+                       return new ReliableSessionBindingElement ();
+               }
+
+               public override void ApplyConfiguration (BindingElement element)
+               {
+                       var b = (ReliableSessionBindingElement) element;
+                       b.AcknowledgementInterval = AcknowledgementInterval;
+                       b.FlowControlEnabled = FlowControlEnabled;
+                       b.InactivityTimeout = InactivityTimeout;
+                       b.MaxPendingChannels = MaxPendingChannels;
+                       b.MaxRetryCount = MaxRetryCount;
+                       b.MaxTransferWindowSize = MaxTransferWindowSize;
+                       b.Ordered = Ordered;
+                       b.ReliableMessagingVersion = ReliableMessagingVersion;
+               }
+
+               public override void CopyFrom (ServiceModelExtensionElement element)
+               {
+                       var b = (ReliableSessionElement) element;
+                       AcknowledgementInterval = b.AcknowledgementInterval;
+                       FlowControlEnabled = b.FlowControlEnabled;
+                       InactivityTimeout = b.InactivityTimeout;
+                       MaxPendingChannels = b.MaxPendingChannels;
+                       MaxRetryCount = b.MaxRetryCount;
+                       MaxTransferWindowSize = b.MaxTransferWindowSize;
+                       Ordered = b.Ordered;
+                       ReliableMessagingVersion = b.ReliableMessagingVersion;
+               }
+
+               protected internal override void InitializeFrom (BindingElement element)
+               {
+                       var b = (ReliableSessionBindingElement) element;
+                       AcknowledgementInterval = b.AcknowledgementInterval;
+                       FlowControlEnabled = b.FlowControlEnabled;
+                       InactivityTimeout = b.InactivityTimeout;
+                       MaxPendingChannels = b.MaxPendingChannels;
+                       MaxRetryCount = b.MaxRetryCount;
+                       MaxTransferWindowSize = b.MaxTransferWindowSize;
+                       Ordered = b.Ordered;
+                       ReliableMessagingVersion = b.ReliableMessagingVersion;
                }
 
        }
index b211ad9b580acc70dcb8bb4d08e3678cabbe4f73..41c8682689e3d1ae3a3c8681c36f930661e4454b 100644 (file)
@@ -146,9 +146,9 @@ namespace System.ServiceModel.Configuration
                                HttpsHelpPageUrl = HttpsHelpPageUrl,
                                IncludeExceptionDetailInFaults = IncludeExceptionDetailInFaults,
                        };
-                       if (HttpHelpPageBinding != null)
+                       if (!String.IsNullOrEmpty (HttpHelpPageBinding))
                                ret.HttpHelpPageBinding = ConfigUtil.CreateBinding (HttpHelpPageBinding, HttpHelpPageBindingConfiguration);
-                       if (HttpsHelpPageBinding != null)
+                       if (!String.IsNullOrEmpty (HttpsHelpPageBinding))
                                ret.HttpsHelpPageBinding = ConfigUtil.CreateBinding (HttpsHelpPageBinding, HttpsHelpPageBindingConfiguration);
                        return ret;
                }
index fcd314e24d85686afe58b1a433eaf5ae2b05293d..351deef520d600d4386d3b1992e417262cd7859f 100644 (file)
@@ -137,9 +137,9 @@ namespace System.ServiceModel.Configuration
                        b.HttpsGetEnabled = HttpsGetEnabled;
                        b.HttpGetUrl = HttpGetUrl;
                        b.HttpsGetUrl = HttpsGetUrl;
-                       if (HttpGetBinding != null)
+                       if (!String.IsNullOrEmpty (HttpGetBinding))
                                b.HttpGetBinding = ConfigUtil.CreateBinding (HttpGetBinding, HttpGetBindingConfiguration);
-                       if (HttpsGetBinding != null)
+                       if (!String.IsNullOrEmpty (HttpsGetBinding))
                                b.HttpsGetBinding = ConfigUtil.CreateBinding (HttpsGetBinding, HttpsGetBindingConfiguration);
                        return b;
                }
index fd75d55dc7d679842b41541dce781c6294bb4d48..5e432e1616b5f530a8852339b72a7c49934f6734 100644 (file)
@@ -99,8 +99,9 @@ namespace System.ServiceModel.Configuration
                        throw new NotImplementedException ();
                }
 
-               protected internal override Binding GetDefault () {
-                       throw new NotImplementedException ();
+               protected internal override Binding GetDefault ()
+               {
+                       return (Binding) Activator.CreateInstance (BindingType, new object [0]);
                }
 
                protected internal override bool TryAdd (string name, Binding binding, System.Configuration.Configuration config) {
index d3bf240bbe0e5e0fabac39bce3f1380dff86747b..1e2e59d91dfe1c69f683c05743006821723a672b 100644 (file)
@@ -74,6 +74,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("closeTimeout",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:01:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan CloseTimeout {
                        get { return (TimeSpan) this ["closeTimeout"]; }
                        set { this ["closeTimeout"] = value; }
@@ -94,6 +95,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("openTimeout",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:01:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan OpenTimeout {
                        get { return (TimeSpan) this ["openTimeout"]; }
                        set { this ["openTimeout"] = value; }
@@ -116,6 +118,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("receiveTimeout",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:10:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan ReceiveTimeout {
                        get { return (TimeSpan) this ["receiveTimeout"]; }
                        set { this ["receiveTimeout"] = value; }
@@ -124,6 +127,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("sendTimeout",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:01:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan SendTimeout {
                        get { return (TimeSpan) this ["sendTimeout"]; }
                        set { this ["sendTimeout"] = value; }
@@ -138,6 +142,14 @@ namespace System.ServiceModel.Configuration
                        binding.SendTimeout = SendTimeout;
                        OnApplyConfiguration (binding);
                }
+
+               protected internal virtual void InitializeFrom (Binding binding)
+               {
+                       CloseTimeout = binding.CloseTimeout;
+                       OpenTimeout = binding.OpenTimeout;
+                       ReceiveTimeout = binding.ReceiveTimeout;
+                       SendTimeout = binding.SendTimeout;
+               }
        }
 
 }
index ce9d811ae68fed557e7e682abf941433dab13c99..f6e42409f2947f1af3ab8512bb0437b21352a066 100644 (file)
@@ -74,7 +74,7 @@ namespace System.ServiceModel.Configuration
                {
                        properties = new ConfigurationPropertyCollection ();
                        inactivity_timeout = new ConfigurationProperty ("inactivityTimeout",
-                               typeof (TimeSpan), "00:10:00", null/* FIXME: get converter for TimeSpan*/, null,
+                               typeof (TimeSpan), "00:10:00", new TimeSpanConverter (), null,
                                ConfigurationPropertyOptions.None);
 
                        ordered = new ConfigurationProperty ("ordered",
@@ -95,6 +95,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("inactivityTimeout",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:10:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan InactivityTimeout {
                        get { return (TimeSpan) base [inactivity_timeout]; }
                        set { base [inactivity_timeout] = value; }
index c5509bbb1c2559e781de99a9838a70e13af34263..ac48e04ca54047c6293f5fd7b3816c26582297c2 100644 (file)
@@ -73,11 +73,11 @@ namespace System.ServiceModel.Configuration
                                ConfigurationPropertyOptions.None);
 
                        idle_timeout = new ConfigurationProperty ("idleTimeout",
-                               typeof (TimeSpan), "00:02:00", null/* FIXME: get converter for TimeSpan*/, null,
+                               typeof (TimeSpan), "00:02:00", new TimeSpanConverter (), null,
                                ConfigurationPropertyOptions.None);
 
                        lease_timeout = new ConfigurationProperty ("leaseTimeout",
-                               typeof (TimeSpan), "00:05:00", null/* FIXME: get converter for TimeSpan*/, null,
+                               typeof (TimeSpan), "00:05:00", new TimeSpanConverter (), null,
                                ConfigurationPropertyOptions.None);
 
                        max_outbound_connections_per_endpoint = new ConfigurationProperty ("maxOutboundConnectionsPerEndpoint",
@@ -111,6 +111,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("idleTimeout",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:02:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan IdleTimeout {
                        get { return (TimeSpan) base [idle_timeout]; }
                        set { base [idle_timeout] = value; }
@@ -119,6 +120,7 @@ namespace System.ServiceModel.Configuration
                [ConfigurationProperty ("leaseTimeout",
                         Options = ConfigurationPropertyOptions.None,
                         DefaultValue = "00:05:00")]
+               [TypeConverter (typeof (TimeSpanConverter))]
                public TimeSpan LeaseTimeout {
                        get { return (TimeSpan) base [lease_timeout]; }
                        set { base [lease_timeout] = value; }
index c75adfb8e1a6f49d396e4b55e535bc6e783486d4..e11ebbebf8b83b1c062edf4aafe0113d202ca3cf 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Atsushi Enomoto <atsushi@ximian.com>
 //
-// Copyright (C) 2006 Novell, Inc.  http://www.novell.com
+// Copyright (C) 2006,2010 Novell, Inc.  http://www.novell.com
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -116,12 +116,37 @@ namespace System.ServiceModel.Configuration
                        set { base ["teredoEnabled"] = value; }
                }
 
+               public override void ApplyConfiguration (BindingElement bindingElement)
+               {
+                       var b = (TcpTransportBindingElement) bindingElement;
+                       base.ApplyConfiguration (b);
+                       b.ListenBacklog = ListenBacklog;
+                       b.PortSharingEnabled = PortSharingEnabled;
+                       b.TeredoEnabled = TeredoEnabled;
+               }
+
+               public override void CopyFrom (ServiceModelExtensionElement from)
+               {
+                       var e = (TcpTransportElement) from;
+                       base.CopyFrom (from);
+                       ListenBacklog = e.ListenBacklog;
+                       PortSharingEnabled = e.PortSharingEnabled;
+                       TeredoEnabled = e.TeredoEnabled;
+               }
 
-               [MonoTODO]
-               protected internal override BindingElement CreateBindingElement () {
-                       throw new NotImplementedException ();
+               protected override TransportBindingElement CreateDefaultBindingElement ()
+               {
+                       return new TcpTransportBindingElement ();
                }
 
+               protected internal override void InitializeFrom (BindingElement bindingElement)
+               {
+                       var b = (TcpTransportBindingElement) bindingElement;
+                       base.InitializeFrom (b);
+                       ListenBacklog = b.ListenBacklog;
+                       PortSharingEnabled = b.PortSharingEnabled;
+                       TeredoEnabled = b.TeredoEnabled;
+               }
        }
 
 }
index 06a3473ca4b6f1c4bb3d2e34b2081fceb3149226..56cfdc76f564e9d92e8430cc4de23c341c931041 100644 (file)
@@ -118,11 +118,44 @@ namespace System.ServiceModel.Configuration
                }
 
 
-               [MonoTODO]
-               protected internal override BindingElement CreateBindingElement () {
-                       throw new NotImplementedException ();
+               protected internal override BindingElement CreateBindingElement ()
+               {
+                       return new TextMessageEncodingBindingElement ();
                }
 
+
+               public override void ApplyConfiguration (BindingElement element)
+               {
+                       var b = (TextMessageEncodingBindingElement) element;
+                       b.MaxReadPoolSize = MaxReadPoolSize;
+                       b.MaxWritePoolSize = MaxWritePoolSize;
+                       b.MessageVersion = MessageVersion;
+                       b.WriteEncoding = WriteEncoding;
+
+                       ReaderQuotas.ApplyConfiguration (b.ReaderQuotas);
+               }
+
+               public override void CopyFrom (ServiceModelExtensionElement element)
+               {
+                       var b = (TextMessageEncodingElement) element;
+                       MaxReadPoolSize = b.MaxReadPoolSize;
+                       MaxWritePoolSize = b.MaxWritePoolSize;
+                       MessageVersion = b.MessageVersion;
+                       WriteEncoding = b.WriteEncoding;
+
+                       ReaderQuotas.CopyFrom (b.ReaderQuotas);
+               }
+
+               protected internal override void InitializeFrom (BindingElement element)
+               {
+                       var b = (TextMessageEncodingBindingElement) element;
+                       MaxReadPoolSize = b.MaxReadPoolSize;
+                       MaxWritePoolSize = b.MaxWritePoolSize;
+                       MessageVersion = b.MessageVersion;
+                       WriteEncoding = b.WriteEncoding;
+
+                       ReaderQuotas.InitializeFrom (b.ReaderQuotas);
+               }
        }
 
 }
index 081e2b137e37806d27a873f734e528c40c2e34c1..0ac73504b8390b35598af429dc258d77123c1220 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Atsushi Enomoto <atsushi@ximian.com>
 //
-// Copyright (C) 2006 Novell, Inc.  http://www.novell.com
+// Copyright (C) 2006,2010 Novell, Inc.  http://www.novell.com
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -108,7 +108,41 @@ namespace System.ServiceModel.Configuration
                        }
                }
 
+               public override void ApplyConfiguration (BindingElement bindingElement)
+               {
+                       var b = (TransportBindingElement) bindingElement;
+                       base.ApplyConfiguration (b);
+                       b.ManualAddressing = ManualAddressing;
+                       b.MaxBufferPoolSize = MaxBufferPoolSize;
+                       b.MaxReceivedMessageSize = MaxReceivedMessageSize;
+               }
+
+               public override void CopyFrom (ServiceModelExtensionElement from)
+               {
+                       var e = (TransportElement) from;
+                       base.CopyFrom (from);
+                       ManualAddressing = e.ManualAddressing;
+                       MaxBufferPoolSize = e.MaxBufferPoolSize;
+                       MaxReceivedMessageSize = e.MaxReceivedMessageSize;
+               }
 
+               protected internal override BindingElement CreateBindingElement ()
+               {
+                       var b = CreateDefaultBindingElement ();
+                       ApplyConfiguration (b);
+                       return b;
+               }
+
+               protected abstract TransportBindingElement CreateDefaultBindingElement ();
+
+               protected internal override void InitializeFrom (BindingElement bindingElement)
+               {
+                       var b = (TransportBindingElement) bindingElement;
+                       base.InitializeFrom (b);
+                       ManualAddressing = b.ManualAddressing;
+                       MaxBufferPoolSize = b.MaxBufferPoolSize;
+                       MaxReceivedMessageSize = b.MaxReceivedMessageSize;
+               }
        }
 
 }
index 88adca5ed7702f8d3335da1cbdc2d253b4bc8a37..cf92fdf1c678e31e73bb3037150b1a820288ba37 100644 (file)
@@ -181,6 +181,48 @@ namespace System.ServiceModel.Configuration
                        if (MaxStringContentLength > 0)
                                q.MaxStringContentLength = MaxStringContentLength;
                }
+
+               internal void ApplyConfiguration (XmlDictionaryReaderQuotasElement q)
+               {
+                       if (MaxArrayLength > 0)
+                               q.MaxArrayLength = MaxArrayLength;
+                       if (MaxBytesPerRead > 0)
+                               q.MaxBytesPerRead = MaxBytesPerRead;
+                       if (MaxDepth > 0)
+                               q.MaxDepth = MaxDepth;
+                       if (MaxNameTableCharCount > 0)
+                               q.MaxNameTableCharCount = MaxNameTableCharCount;
+                       if (MaxStringContentLength > 0)
+                               q.MaxStringContentLength = MaxStringContentLength;
+               }
+
+               internal void InitializeFrom (XmlDictionaryReaderQuotas q)
+               {
+                       if (q.MaxArrayLength > 0)
+                               MaxArrayLength = q.MaxArrayLength;
+                       if (q.MaxBytesPerRead > 0)
+                               MaxBytesPerRead = q.MaxBytesPerRead;
+                       if (q.MaxDepth > 0)
+                               MaxDepth = q.MaxDepth;
+                       if (q.MaxNameTableCharCount > 0)
+                               MaxNameTableCharCount = q.MaxNameTableCharCount;
+                       if (q.MaxStringContentLength > 0)
+                               MaxStringContentLength = q.MaxStringContentLength;
+               }
+
+               internal void CopyFrom (XmlDictionaryReaderQuotasElement q)
+               {
+                       if (q.MaxArrayLength > 0)
+                               MaxArrayLength = q.MaxArrayLength;
+                       if (q.MaxBytesPerRead > 0)
+                               MaxBytesPerRead = q.MaxBytesPerRead;
+                       if (q.MaxDepth > 0)
+                               MaxDepth = q.MaxDepth;
+                       if (q.MaxNameTableCharCount > 0)
+                               MaxNameTableCharCount = q.MaxNameTableCharCount;
+                       if (q.MaxStringContentLength > 0)
+                               MaxStringContentLength = q.MaxStringContentLength;
+               }
        }
 
 }
index 13309137d54ddf0fdcbd33952e4b1bbc18272a8a..4a6055fbf60f74e952dafc95bf8b7037594bfef0 100644 (file)
@@ -1,3 +1,64 @@
+2010-04-23  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ServiceMetadataExtension.cs : raise an error if it failed to set
+         mex info. (Make it safer.)
+
+2010-04-23  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ServiceMetadataExtension.cs : reflect DispatcherBuilder change.
+
+2010-04-02  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ContractDescriptionGenerator.cs : fill FaultDescription action,
+         name and namespace as expected.
+
+2010-04-02  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ContractDescription.cs : fill FaultContractInfos in ClientOperation.
+
+2010-04-02  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * FaultDescription.cs : fill Action.
+       * ContractDescriptionGenerator.cs : do not fill Faults from service
+         impl. method. Do this from contract method instead.
+       * OperationDescription.cs : remove extra TODOs.
+
+2010-03-24  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ServiceMetadataExtension.cs : compare "wsdl" parameter in case-
+         insensitive manner.
+
+2010-03-19  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * HostedBindingBehavior.cs : remove unused class.
+
+2010-03-17  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * WsdlExporter.cs : allow identical contract while exporting a set
+         of endpoints, while reject identical ones when calling
+         ExportEndpoint() individually.
+
+2010-03-17  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * MetadataExchangeBindings.cs : use WSHttpBinding (it works if other
+         parts gets fixed).
+
+2010-03-17  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ServiceMetadataExtension.cs, WsdlExporter.cs :
+         implement ExportEndpoints() and use it.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * ClientCredentials.cs, ContractDescription.cs,
+       IEndpointBehavior.cs: use MOONLIGHT symbol to disambiguate
+       MonoTouch and Moonlight code.
+
+2010-03-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ServiceEndpointCollection.cs : those overrides are rather to check
+         null arguments, not to skip contract duplicates.
+
 2010-03-12  Atsushi Enomoto  <atsushi@ximian.com>
 
        * MessageDescription.cs : implement MessageName.
index fad6fbdd2600d092bcebf9e98f9c839136e23785..7e2c785cdfad07c19fc8c9744aff41acc90d568c 100644 (file)
@@ -140,7 +140,7 @@ namespace System.ServiceModel.Description
                }
 #endif
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                void IEndpointBehavior.AddBindingParameters (ServiceEndpoint endpoint,
                        BindingParameterCollection parameters)
                {
index b7fd634fe5464d86da7063822cf8c4ec1090a2a8..a465525a410c379e34b7c338de42117cff14506d 100644 (file)
@@ -153,7 +153,7 @@ namespace System.ServiceModel.Description
                        foreach (OperationDescription od in Operations) {
                                if (!proxy.Operations.Contains (od.Name))
                                        PopulateClientOperation (proxy, od);
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                                foreach (IOperationBehavior ob in od.Behaviors)
                                        ob.ApplyClientBehavior (od, proxy.Operations [od.Name]);
 #endif
@@ -185,6 +185,10 @@ namespace System.ServiceModel.Description
                                    md.Body.ReturnValue.Type == typeof (Message))
                                        o.DeserializeReply = false;
                        }
+#if !NET_2_1
+                       foreach (var fd in od.Faults)
+                               o.FaultContractInfos.Add (new FaultContractInfo (fd.Action, fd.DetailType));
+#endif
                        proxy.Operations.Add (o);
                }
        }
index 1a72a535648819f71c236b8d1d625f32dba02259..1ad5843b6e7bd9654c406c06a70dc27eca2d2cba 100644 (file)
@@ -245,8 +245,16 @@ namespace System.ServiceModel.Description
                                foreach (ServiceKnownTypeAttribute a in serviceMethod.GetCustomAttributes (typeof (ServiceKnownTypeAttribute), false))
                                        foreach (Type t in a.GetTypes ())
                                                od.KnownTypes.Add (t);
-                               foreach (FaultContractAttribute a in serviceMethod.GetCustomAttributes (typeof (FaultContractAttribute), false))
-                                       od.Faults.Add (new FaultDescription (a.Action) { DetailType = a.DetailType, Name = a.Name, Namespace = a.Namespace });
+                               foreach (FaultContractAttribute a in mi.GetCustomAttributes (typeof (FaultContractAttribute), false)) {
+                                       var fname = a.Name ?? a.DetailType.Name + "Fault";
+                                       var fns = a.Namespace ?? cd.Namespace;
+                                       var fd = new FaultDescription (a.Action ?? cd.Namespace + cd.Name + "/" + od.Name + fname) { DetailType = a.DetailType, Name = fname, Namespace = fns };
+#if !NET_2_1
+                                       if (a.HasProtectionLevel)
+                                               fd.ProtectionLevel = a.ProtectionLevel;
+#endif
+                                       od.Faults.Add (fd);
+                               }
                                cd.Operations.Add (od);
                        }
                        else if (oca.AsyncPattern && od.BeginMethod != null ||
index 6621c18dbe219c027925d9034cc65098f3dc900d..8dee9eddb2916ddff779f59422a70e240b054cb6 100644 (file)
@@ -35,7 +35,6 @@ using System.ServiceModel;
 
 namespace System.ServiceModel.Description
 {
-       [MonoTODO]
        public class FaultDescription
        {
                string action, name, ns;
@@ -43,8 +42,11 @@ namespace System.ServiceModel.Description
                bool has_protection_level;
                ProtectionLevel protection_level;
 
-               public FaultDescription (string name)
+               public FaultDescription (string action)
                {
+                       if (action == null)
+                               throw new ArgumentNullException ("action");
+                       this.action = action;
                }
 
                public string Action {
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel.Description/HostedBindingBehavior.cs b/mcs/class/System.ServiceModel/System.ServiceModel.Description/HostedBindingBehavior.cs
deleted file mode 100644 (file)
index 20b73cd..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-//
-// HostedBindingBehavior.cs.cs
-//
-// Author:
-//     Atsushi Enomoto <atsushi@ximian.com>
-//
-// Copyright (C) 2005 Novell, Inc.  http://www.novell.com
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-using System.Collections.ObjectModel;
-using System.ServiceModel;
-using System.ServiceModel.Channels;
-using System.ServiceModel.Dispatcher;
-
-namespace System.ServiceModel.Description
-{
-       [MonoTODO]
-       internal sealed class HostedBindingBehavior : IServiceBehavior
-       {
-               string virtual_path;
-
-               internal HostedBindingBehavior (string virtualPath)
-               {
-                       virtual_path = virtualPath;
-               }
-
-               public string VirtualPath {
-                       get { return virtual_path; }
-               }
-
-               void IServiceBehavior.AddBindingParameters (
-                       ServiceDescription description,
-                       ServiceHostBase serviceHostBase,
-                       Collection<ServiceEndpoint> endpoints,
-                       BindingParameterCollection parameters)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               void IServiceBehavior.ApplyDispatchBehavior (
-                       ServiceDescription description,
-                       ServiceHostBase serviceHostBase)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               void IServiceBehavior.Validate (
-                       ServiceDescription description,
-                       ServiceHostBase serviceHostBase)
-               {
-                       throw new NotImplementedException ();
-               }
-       }
-}
index 1ba9d63f7e5c8d61102a060632a79c453981b05a..436dd438dc7b6c709e2eff6fd620305fe0812178 100644 (file)
@@ -33,7 +33,7 @@ namespace System.ServiceModel.Description
 {
        public interface IEndpointBehavior
        {
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                void AddBindingParameters (ServiceEndpoint endpoint,
                        BindingParameterCollection parameters);
 #if !NET_2_1
index 469be47ce78018c60f598b88fb1b32983528d34b..89fd2b3a0bb9025f326268f9c195169268d056db 100644 (file)
@@ -34,26 +34,18 @@ namespace System.ServiceModel.Description
        {
                public static Binding CreateMexHttpBinding ()
                {
-                       //FIXME: .net uses WSHttpBinding.. 
-                       return new CustomBinding (
-                               "MetadataExchangeHttpBinding",
-                               "http://schemas.microsoft.com/ws/2005/02/mex/bindings",
-                               new TextMessageEncodingBindingElement (
-                                       MessageVersion.Soap12WSAddressing10, 
-                                       Encoding.UTF8),
-                               new HttpTransportBindingElement ());
+                       var b = new WSHttpBinding (SecurityMode.None) {
+                               Name = "MetadataExchangeHttpBinding",
+                               Namespace = "http://schemas.microsoft.com/ws/2005/02/mex/bindings"};
+                       return b;
                }
 
                public static Binding CreateMexHttpsBinding ()
                {
-                       //FIXME: .net uses WSHttpBinding.. 
-                       return new CustomBinding (
-                               "MetadataExchangeHttpsBinding",
-                               "http://schemas.microsoft.com/ws/2005/02/mex/bindings",
-                               new TextMessageEncodingBindingElement (
-                                       MessageVersion.Soap12WSAddressing10, 
-                                       Encoding.UTF8),
-                               new HttpsTransportBindingElement ());
+                       var b = (WSHttpBinding) CreateMexHttpBinding ();
+                       b.Name = "MetadataExchangeHttpsBinding";
+                       b.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
+                       return b;
                }
 
                public static Binding CreateMexNamedPipeBinding ()
index 000960b2e89f28dfcb4d97f32da0591ba5c9416f..2f2b47aa09c53ccc6c44c55b897d27df0c6c3d3b 100644 (file)
@@ -64,7 +64,6 @@ namespace System.ServiceModel.Description
                        set { begin_method = value; }
                }
 
-               [MonoTODO]
                public KeyedByTypeCollection<IOperationBehavior> Behaviors {
                        get { return behaviors; }
                }
@@ -79,7 +78,6 @@ namespace System.ServiceModel.Description
                        set { end_method = value; }
                }
 
-               [MonoTODO]
                public FaultDescriptionCollection Faults {
                        get { return faults; }
                }
@@ -105,7 +103,6 @@ namespace System.ServiceModel.Description
                        set { is_terminating = value; }
                }
 
-               [MonoTODO]
                public Collection<Type> KnownTypes {
                        get { return known_types; }
                }
index 58d0024e3de8b588bd15331cbae98872dd6af249..191d411ed41c86e21abe97d4709a70aeb911dc9d 100644 (file)
@@ -107,20 +107,18 @@ namespace System.ServiceModel.Description
                        return list;
                }
 
-               [MonoTODO]
                protected override void InsertItem (int index, ServiceEndpoint item)
                {
-                       if (Find (new XmlQualifiedName (item.Contract.Name, item.Contract.Namespace)) == null)
-                               base.InsertItem (index, item);
+                       if (item == null)
+                               throw new ArgumentNullException ("item");
+                       base.InsertItem (index, item);
                }
 
-               [MonoTODO]
                protected override void SetItem (int index, ServiceEndpoint item)
                {
-                       if (Find (new XmlQualifiedName (item.Contract.Name, item.Contract.Namespace)) == null)
-                               base.SetItem (index, item);
-                       else
-                               base.RemoveItem (index);
+                       if (item == null)
+                               throw new ArgumentNullException ("item");
+                       base.SetItem (index, item);
                }
        }
 }
index 36b7fdc8f63da6dea3f72d8b1e1c0e43c0e3558f..fb39b485dfa63d8a2a8565c600c54a988c736bcb 100644 (file)
@@ -66,13 +66,8 @@ namespace System.ServiceModel.Description
                public MetadataSet Metadata {
                        get {
                                if (metadata == null) {
-                                       MetadataExporter exporter = new WsdlExporter ();
-                                       foreach (ServiceEndpoint ep in owner.Description.Endpoints) {
-                                               if (ep.Contract.Name == ServiceMetadataBehavior.MexContractName)
-                                                       continue;
-
-                                               exporter.ExportEndpoint (ep);
-                                       }
+                                       var exporter = new WsdlExporter ();
+                                       exporter.ExportEndpoints (owner.Description.Endpoints, new XmlQualifiedName (owner.Description.Name, owner.Description.Namespace));
                                        metadata = exporter.GetGeneratedMetadata ();
                                }
                                return metadata;
@@ -139,11 +134,13 @@ namespace System.ServiceModel.Description
                                ListenUri = uri,
                        };
 
-                       var channelDispatcher = new DispatcherBuilder ().BuildChannelDispatcher (owner.Description.ServiceType, se, new BindingParameterCollection ());
+                       var channelDispatcher = new DispatcherBuilder (Owner).BuildChannelDispatcher (owner.Description.ServiceType, se, new BindingParameterCollection ());
                        // add HttpGetWsdl to indicate that the ChannelDispatcher is for mex or help.
                        var listener = channelDispatcher.Listener as ChannelListenerBase;
                        if (listener != null)
                                listener.Properties.Add (new MetadataPublishingInfo () { SupportsMex = isMex, SupportsHelp = !isMex, Instance = instance });
+                       else
+                               throw new InvalidOperationException ("FIXME: attempt to use ServiceMetadataExtension to not-supported channel listener: " + listener.GetType ());
                        channelDispatcher.Endpoints [0].DispatchRuntime.InstanceContextProvider = new SingletonInstanceContextProvider (new InstanceContext (owner, instance));
 
                        dispatchers.Add (uri, channelDispatcher);
@@ -222,7 +219,7 @@ namespace System.ServiceModel.Description
                                        return CreateWsdlMessage (w);
                        }
 
-                       if (query_string [null] == "wsdl") {
+                       if (String.Compare (query_string [null], "wsdl", StringComparison.OrdinalIgnoreCase) == 0) {
                                WSServiceDescription wsdl = GetWsdl ("wsdl");
                                if (wsdl != null)
                                        return CreateWsdlMessage (wsdl);
index 10a4fe2c3f84cde4f7e08c627517075f99f75ea7..0a5e892fe75c95593b89d7d8b2af2f86ea0eff2d 100644 (file)
@@ -29,6 +29,7 @@
 using System;
 using System.Collections;
 using System.Collections.Generic;
+using System.Linq;
 using System.ServiceModel;
 using System.ServiceModel.Channels;
 using System.Web.Services.Description;
@@ -50,10 +51,24 @@ namespace System.ServiceModel.Description
        [MonoTODO]
        public class WsdlExporter : MetadataExporter
        {
+               class ContractExportMap
+               {
+                       public ContractExportMap (QName qname, ContractDescription contract, List<IWsdlExportExtension> results)
+                       {
+                               QName = qname;
+                               Contract = contract;
+                               Results = results;
+                       }
+
+                       public QName QName { get; private set; }
+                       public ContractDescription Contract { get; private set; }
+                       public List<IWsdlExportExtension> Results { get; private set; }
+               }
+
                private MetadataSet metadata;
                private ServiceDescriptionCollection wsdl_colln;
                private XsdDataContractExporter xsd_exporter;
-               private Hashtable exported_contracts;
+               private List<ContractExportMap> exported_contracts;
 
                public override MetadataSet GetGeneratedMetadata ()
                {
@@ -74,16 +89,20 @@ namespace System.ServiceModel.Description
 
                public override void ExportContract (ContractDescription contract)
                {
-                       ExportContractInternal (contract);      
+                       ExportContractInternal (contract, true);
                }
 
-               List<IWsdlExportExtension> ExportContractInternal (ContractDescription contract)
+               List<IWsdlExportExtension> ExportContractInternal (ContractDescription contract, bool rejectDuplicate)
                {
                        QName qname = new QName (contract.Name, contract.Namespace);
-                       if (ExportedContracts.ContainsKey (qname))
+                       var map = ExportedContracts.FirstOrDefault (m => m.QName == qname);
+                       if (map != null) {
+                               if (map.Results != null && !rejectDuplicate)
+                                       return null; // already exported.
                                throw new ArgumentException (String.Format (
                                        "A ContractDescription with Namespace : {0} and Name : {1} has already been exported.", 
                                        contract.Namespace, contract.Name));
+                       }
 
                        WSServiceDescription sd = GetServiceDescription (contract.Namespace);
 
@@ -150,7 +169,7 @@ namespace System.ServiceModel.Description
                        sd.Types.Schemas.Add (xs_import);
 
                        sd.PortTypes.Add (ws_port);
-                       ExportedContracts [qname] = contract;
+                       ExportedContracts.Add (new ContractExportMap (qname, contract, extensions));
 
                        WsdlContractConversionContext context = new WsdlContractConversionContext (contract, ws_port);
                        foreach (IWsdlExportExtension extn in extensions)
@@ -161,7 +180,12 @@ namespace System.ServiceModel.Description
 
                public override void ExportEndpoint (ServiceEndpoint endpoint)
                {
-                       List<IWsdlExportExtension> extensions = ExportContractInternal (endpoint.Contract);
+                       ExportEndpoint (endpoint, true);
+               }
+
+               void ExportEndpoint (ServiceEndpoint endpoint, bool rejectDuplicate)
+               {
+                       List<IWsdlExportExtension> extensions = ExportContractInternal (endpoint.Contract, rejectDuplicate);
                        
                        //FIXME: Namespace
                        WSServiceDescription sd = GetServiceDescription ("http://tempuri.org/");
@@ -251,8 +275,9 @@ namespace System.ServiceModel.Description
                        WsdlEndpointConversionContext endpoint_context = new WsdlEndpointConversionContext (
                                contract_context, endpoint, ws_port, ws_binding);
 
-                       foreach (IWsdlExportExtension extn in extensions)
-                               extn.ExportEndpoint (this, endpoint_context);
+                       if (extensions != null)
+                               foreach (IWsdlExportExtension extn in extensions)
+                                       extn.ExportEndpoint (this, endpoint_context);
 
                                
                }
@@ -327,7 +352,17 @@ namespace System.ServiceModel.Description
                        IEnumerable<ServiceEndpoint> endpoints,
                        XmlQualifiedName name)
                {
-                       throw new NotImplementedException ();
+                       if (endpoints == null)
+                               throw new ArgumentNullException ("endpoints");
+                       if (name == null)
+                               throw new ArgumentNullException ("name");
+
+                       foreach (ServiceEndpoint ep in endpoints) {
+                               if (ep.Contract.Name == ServiceMetadataBehavior.MexContractName)
+                                       continue;
+
+                               ExportEndpoint (ep, false);
+                       }
                }
 
                XsdDataContractExporter XsdExporter {
@@ -339,10 +374,10 @@ namespace System.ServiceModel.Description
                        }
                }
 
-               Hashtable ExportedContracts {
+               List<ContractExportMap> ExportedContracts {
                        get {
                                if (exported_contracts == null)
-                                       exported_contracts = new Hashtable ();
+                                       exported_contracts = new List<ContractExportMap> ();
                                return exported_contracts;
                        }
                }
index e83398f78d7bc51ec7ae60ccdb2eac33bcad3c88..363d9c6a80788ca2189a8296fb652f4d9fb09220 100644 (file)
@@ -72,10 +72,10 @@ namespace System.ServiceModel.Dispatcher
                                if (md.IsTypedMessage || md.IsUntypedMessage) {
                                        if (isRpc && !isEncoded)
                                                throw new InvalidOperationException ("Message with action {0} is either strongly-typed or untyped, but defined as RPC and encoded.");
-                                       if (hasParameter)
-                                               throw new InvalidOperationException ("This operation contains a message with parameters. Strongly-typed or untyped message can be paired only with strongly-typed, untyped or void message.");
-                                       if (hasVoid)
-                                               throw new InvalidOperationException ("This operation is defined as RPC and contains a message with void, which is not allowed.");
+                                       if (hasParameter && !md.IsVoid)
+                                               throw new InvalidOperationException (String.Format ("Operation '{0}' contains a message with parameters. Strongly-typed or untyped message can be paired only with strongly-typed, untyped or void message.", od.Name));
+                                       if (isRpc && hasVoid)
+                                               throw new InvalidOperationException (String.Format ("This operation '{0}' is defined as RPC and contains a message with void, which is not allowed.", od.Name));
                                } else {
                                        hasParameter |= !md.IsVoid;
                                        hasVoid |= md.IsVoid;
index 1424af7a9ef2d27fbbbda13a7338d19d87e14b76..820799d28ca4be7050d534007c3f8cb27f65b2bc 100644 (file)
@@ -1,3 +1,77 @@
+2010-04-20  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * OperationInvokerHandler.cs : workaround NRE issue in AsyncCallTest.
+         The original code was worse than this workaround.
+
+2010-04-05  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * EndpointAddressMessageFilter.cs : check null arg. Return false for
+         no To header case and do not result in NRE.f
+
+2010-04-05  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * BaseMessagesFormatter.cs : hasParameter check is incorrectly
+         restrictive to reject some kinds of pairs.
+
+2010-04-02  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * FaultContractInfo.cs : add serializer property.
+
+2010-04-02  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ClientOperation.cs : do not automatically fill FaultContractInfos.
+
+2010-04-02  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * OperationInvokerHandler.cs : implement FaultContractInfos support.
+       * ErrorProcessingHandler.cs : update comment. It is not relevant.
+
+2010-04-02  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * EndpointDispatcher.cs : fill FaultContractInfos.
+       * DispatchOperation.cs : do not fill them dynamically/automatically.
+       * ErrorProcessingHandler.cs : added some FIXME notes.
+
+2010-03-30  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ChannelDispatcher.cs : differentiate EndpointNotFound and
+         ActionNotSupported so that FaultConverter can create appropriate
+         fault messages. Removed extra filter condition on null To item.
+         And create fault messages on *any* server side error, do not let
+         request client infinitely wait for the response until timeout.
+
+         (RunDestinationUnreachableTest() is still not working but it works
+         when it is SOAP 1.2.)
+
+2010-03-30  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ChannelDispatcher.cs : for faults, use fault namespace, not that of
+         ReplyAction. Added FIXME comment regarding dispatcher.
+
+2010-03-25  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * OperationInvokerHandler.cs : removed unused code.
+
+2010-03-24  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ChannelDispatcher.cs : return EndpointDispatcher at initializing
+         for internal use. Add some locks. Patch by Matt Dargavel.
+
+2010-03-24  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ChannelDispatcher.cs : fix wrong method call in open_delegate.
+         Patch by Matt Dargavel.
+
+2010-03-24  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ChannelDispatcher.cs : give the actual exception message instead
+         of "error occured".
+
+2010-03-18  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XPathMessageContext.cs : implement.
+       * XPathMessageFilterTable.cs : add some missing overloads.
+
 2010-02-26  Atsushi Enomoto  <atsushi@ximian.com>
 
        * InputOrReplyRequestProcessor.cs : now ServiceRuntimeChannel is
index 713a62c2e765e1763bda63ca0c90a15a416856aa..157c08f6c8e5b26d15cd7fc9ab3022a36ea26eaa 100644 (file)
@@ -130,7 +130,7 @@ namespace System.ServiceModel.Dispatcher
                        endpoints = new EndpointDispatcherCollection (this);
                }
 
-               internal void InitializeServiceEndpoint (Type serviceType, ServiceEndpoint se)
+               internal EndpointDispatcher InitializeServiceEndpoint (Type serviceType, ServiceEndpoint se)
                {
                        this.MessageVersion = se.Binding.MessageVersion;
                        if (this.MessageVersion == null)
@@ -140,6 +140,7 @@ namespace System.ServiceModel.Dispatcher
                        EndpointDispatcher ed = new EndpointDispatcher (se.Address, se.Contract.Name, se.Contract.Namespace);
                        this.Endpoints.Add (ed);
                        ed.InitializeServiceEndpoint (false, serviceType, se);
+                       return ed;
                }
 
                public string BindingName {
@@ -264,7 +265,7 @@ namespace System.ServiceModel.Dispatcher
                        AsyncCallback callback, object state)
                {
                        if (open_delegate == null)
-                               open_delegate = new Action<TimeSpan> (OnClose);
+                               open_delegate = new Action<TimeSpan> (OnOpen);
                        return open_delegate.BeginInvoke (timeout, callback, state);
                }
 
@@ -450,7 +451,7 @@ namespace System.ServiceModel.Dispatcher
                                        LoopCore ();
                                } catch (Exception ex) {
                                        // FIXME: log it
-                                       Console.WriteLine ("ChannelDispatcher caught an exception inside dispatcher loop, which is likely thrown by the channel listener {0}", owner.Listener);
+                                       Console.WriteLine ("ListenerLoopManager caught an exception inside dispatcher loop, which is likely thrown by the channel listener {0}", owner.Listener);
                                        Console.WriteLine (ex);
                                } finally {
                                        if (stop_handle != null)
@@ -496,16 +497,19 @@ namespace System.ServiceModel.Dispatcher
                                        return;
                                }
 
-                               channels.Add (ch);
+                               lock (channels)
+                                       channels.Add (ch);
                                ch.Opened += delegate {
                                        ch.Faulted += delegate {
-                                               if (channels.Contains (ch))
-                                                       channels.Remove (ch);
+                                               lock (channels)
+                                                       if (channels.Contains (ch))
+                                                               channels.Remove (ch);
                                                throttle_wait_handle.Set (); // release loop wait lock.
                                                };
                                        ch.Closed += delegate {
-                                               if (channels.Contains (ch))
-                                                       channels.Remove (ch);
+                                               lock (channels)
+                                                       if (channels.Contains (ch))
+                                                               channels.Remove (ch);
                                                throttle_wait_handle.Set (); // release loop wait lock.
                                                };
                                        };
@@ -561,31 +565,21 @@ namespace System.ServiceModel.Dispatcher
                                        input.Close ();
                        }
 
-                       void SendEndpointNotFound (RequestContext rc, EndpointNotFoundException ex) 
-                       {
-                               try {
-
-                                       MessageVersion version = rc.RequestMessage.Version;
-                                       FaultCode fc = new FaultCode ("DestinationUnreachable", version.Addressing.Namespace);
-                                       Message res = Message.CreateMessage (version, fc, "error occured", rc.RequestMessage.Headers.Action);
-                                       rc.Reply (res);
-                               } catch (Exception e) {
-                                       // FIXME: log it
-                                       Console.WriteLine ("Error on sending DestinationUnreachable fault message: " + e);
-                               }
-                       }
-
                        void ProcessRequest (IReplyChannel reply, RequestContext rc)
                        {
+                               var req = rc.RequestMessage;
                                try {
-                                       EndpointDispatcher candidate = FindEndpointDispatcher (rc.RequestMessage);
-                                       new InputOrReplyRequestProcessor (candidate.DispatchRuntime, reply).
-                                               ProcessReply (rc);
-                               } catch (EndpointNotFoundException ex) {
-                                       SendEndpointNotFound (rc, ex);
+                                       var ed = FindEndpointDispatcher (req);
+                                       new InputOrReplyRequestProcessor (ed.DispatchRuntime, reply).ProcessReply (rc);
                                } catch (Exception ex) {
                                        // FIXME: log it.
                                        Console.WriteLine (ex);
+
+                                       var conv = reply.GetProperty<FaultConverter> () ?? FaultConverter.GetDefaultFaultConverter (rc.RequestMessage.Version);
+                                       Message res;
+                                       if (!conv.TryCreateFaultMessage (ex, out res))
+                                               res = Message.CreateMessage (req.Version, new FaultCode ("Receiver"), ex.Message, req.Version.Addressing.FaultNamespace);
+                                       rc.Reply (res);
                                } finally {
                                        if (rc != null)
                                                rc.Close ();
@@ -615,30 +609,30 @@ namespace System.ServiceModel.Dispatcher
 
                        EndpointDispatcher FindEndpointDispatcher (Message message) {
                                EndpointDispatcher candidate = null;
-                               for (int i = 0; i < owner.Endpoints.Count; i++) {
-                                       if (MessageMatchesEndpointDispatcher (message, owner.Endpoints [i])) {
-                                               var newdis = owner.Endpoints [i];
+                               bool hasEndpointMatch = false;
+                               foreach (var endpoint in owner.Endpoints) {
+                                       if (endpoint.AddressFilter.Match (message)) {
+                                               hasEndpointMatch = true;
+                                               if (!endpoint.ContractFilter.Match (message))
+                                                       continue;
+                                               var newdis = endpoint;
                                                if (candidate == null || candidate.FilterPriority < newdis.FilterPriority)
                                                        candidate = newdis;
                                                else if (candidate.FilterPriority == newdis.FilterPriority)
                                                        throw new MultipleFilterMatchesException ();
                                        }
                                }
-                               if (candidate == null && owner.Host != null)
-                                       owner.Host.OnUnknownMessageReceived (message);
-                               return candidate;
-                       }
+                               if (candidate == null && !hasEndpointMatch) {
+                                       if (owner.Host != null)
+                                               owner.Host.OnUnknownMessageReceived (message);
+                                       // we have to return a fault to the client anyways...
+                                       throw new EndpointNotFoundException ();
+                               }
+                               else if (candidate == null)
+                                       // FIXME: It is not a good place to check, but anyways detach this error from EndpointNotFoundException.
+                                       throw new ActionNotSupportedException (String.Format ("Action '{0}' did not match any operations in the target contract", message.Headers.Action));
 
-                       bool MessageMatchesEndpointDispatcher (Message req, EndpointDispatcher endpoint)
-                       {
-                               // FIXME: handle AddressFilterMode.Prefix too.
-
-                               Uri to = req.Headers.To;
-                               if (to == null)
-                                       return address_filter_mode == AddressFilterMode.Any;
-                               if (to.AbsoluteUri == Constants.WsaAnonymousUri)
-                                       return false;
-                               return endpoint.AddressFilter.Match (req) && endpoint.ContractFilter.Match (req);
+                               return candidate;
                        }
                }
 }
index f197245b5206a18a2ab272f068a3943bca2296d0..9d2c92e445beb0bd5bb5d714d2ab7b691999e6c1 100644 (file)
@@ -61,7 +61,7 @@ namespace System.ServiceModel.Dispatcher
                SynchronizedCollection<IParameterInspector> inspectors
                        = new SynchronizedCollection<IParameterInspector> ();
 #if !NET_2_1
-               SynchronizedCollection<FaultContractInfo> fault_contract_infos;
+               SynchronizedCollection<FaultContractInfo> fault_contract_infos = new SynchronizedCollection<FaultContractInfo> ();
 #endif
 
                public ClientOperation (ClientRuntime parent,
@@ -106,15 +106,7 @@ namespace System.ServiceModel.Dispatcher
 
 #if !NET_2_1
                public SynchronizedCollection<FaultContractInfo> FaultContractInfos {
-                       get {
-                               if (fault_contract_infos == null) {
-                                       var l = new SynchronizedCollection<FaultContractInfo> ();
-                                       foreach (var f in Description.Faults)
-                                               l.Add (new FaultContractInfo (f.Action, f.DetailType));
-                                       fault_contract_infos = l;
-                               }
-                               return fault_contract_infos;
-                       }
+                       get { return fault_contract_infos; }
                }
 #endif
 
index 832dc5570099375805d162fa36be13f6b0118d20..cedc7e666938e277c4fcf35f6c23aa79e13f47e7 100644 (file)
@@ -59,7 +59,8 @@ namespace System.ServiceModel.Dispatcher
                IOperationInvoker invoker;
                SynchronizedCollection<IParameterInspector> inspectors
                        = new SynchronizedCollection<IParameterInspector> ();
-               SynchronizedCollection<FaultContractInfo> fault_contract_infos;
+               SynchronizedCollection<FaultContractInfo> fault_contract_infos
+                       = new SynchronizedCollection<FaultContractInfo> ();
                SynchronizedCollection<ICallContextInitializer> ctx_initializers
                        = new SynchronizedCollection<ICallContextInitializer> ();
 
@@ -106,15 +107,7 @@ namespace System.ServiceModel.Dispatcher
                }
 
                public SynchronizedCollection<FaultContractInfo> FaultContractInfos {
-                       get {
-                               if (fault_contract_infos == null) {
-                                       var l = new SynchronizedCollection<FaultContractInfo> ();
-                                       foreach (var f in Description.Faults)
-                                               l.Add (new FaultContractInfo (f.Action, f.DetailType));
-                                       fault_contract_infos = l;
-                               }
-                               return fault_contract_infos;
-                       }
+                       get { return fault_contract_infos; }
                }
 
                public IDispatchMessageFormatter Formatter {
index 49ce5704eee276a9f3a6bba8855d88f4c54d6684..aa7dc41a0113e8ec039fbf4c18518b8061e33e78 100644 (file)
@@ -44,6 +44,8 @@ namespace System.ServiceModel.Dispatcher
                public EndpointAddressMessageFilter (EndpointAddress address,
                        bool includeHostNameInComparison)
                {
+                       if (address == null)
+                               throw new ArgumentNullException ("address");
                        this.address = address;
                        cmp_host = includeHostNameInComparison;
                }
@@ -63,10 +65,11 @@ namespace System.ServiceModel.Dispatcher
                        throw new NotImplementedException ();
                }
 
-               [MonoTODO]
                public override bool Match (Message message)
                {
                        Uri to = message.Headers.To;
+                       if (to == null)
+                               return false;
                        bool path = ((String.CompareOrdinal (to.AbsolutePath, address.Uri.AbsolutePath) == 0) && 
                                        (to.Port == address.Uri.Port));
                        bool host = IncludeHostNameInComparison
index c5c7deb28e9ec7ddd8c6929cab05f0ee07a015af..f8568b7e0781aa9f0ae501f95c6f51326338ab59 100644 (file)
@@ -159,6 +159,9 @@ namespace System.ServiceModel.Dispatcher
                                }
                        }
 
+                       foreach (var fd in od.Faults)
+                               o.FaultContractInfos.Add (new FaultContractInfo (fd.Action, fd.DetailType));
+
                        // Setup Invoker
                        o.Invoker = new DefaultOperationInvoker (od);
 
index 5157e4c7421745da71992bf78b5c646559f3c4db..baa0f4ee0fb4cc1782e4fe05452a2709c185c26f 100644 (file)
@@ -26,11 +26,14 @@ namespace System.ServiceModel.Dispatcher
                                if (handler.HandleError (ex))
                                        break;
 
+                       // FIXME: remove them. FaultConverter also covers errors like EndpointNotFoundException, which this handler never covers. And checking converter twice is extraneous, so this part is just extraneous.
+                       // FIXME: actually everything is done in OperationInvokerHandler now...
                        FaultConverter fc = FaultConverter.GetDefaultFaultConverter (dispatchRuntime.ChannelDispatcher.MessageVersion);
                        Message res = null;                     
                        if (!fc.TryCreateFaultMessage (ex, out res))
                                throw ex;
                        mrc.ReplyMessage = res;
+
                        if (duplex != null)
                                mrc.Reply (duplex, true);
                        else
index 98f44a5aef174d59f1ee3937ab2fde0842fd9967..36d3255b67db36ef77937309bfec34cab2b7969f 100644 (file)
@@ -25,6 +25,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 using System;
+using System.Runtime.Serialization;
 using System.ServiceModel;
 
 namespace System.ServiceModel.Dispatcher
@@ -41,8 +42,18 @@ namespace System.ServiceModel.Dispatcher
                        Detail = detail;
                }
 
+               DataContractSerializer serializer;
+
                public string Action { get; private set; }
 
                public Type Detail { get; private set; }
+
+               internal DataContractSerializer Serializer {
+                       get {
+                               if (serializer == null)
+                                       serializer = new DataContractSerializer (Detail);
+                               return serializer;
+                       }
+               }
        }
 }
index f5504c8c1810c09e7972deb5ee42baa4646f22a5..cd4e28ded6cd26e7cad29f29d4183a8b475e960c 100644 (file)
@@ -49,7 +49,13 @@ namespace System.ServiceModel.Dispatcher
                                object result = operation.Invoker.Invoke (instance, parameters, out outParams);
                                HandleInvokeResult (mrc, outParams, result);
                        } else {
-                               var ar = operation.Invoker.InvokeBegin (instance, parameters, null, null);
+                               AsyncCallback callback = delegate {};
+                               // FIXME: the original code passed null callback
+                               // and null state, which is very wrong :(
+                               // It is still wrong to pass dummy callback, but
+                               // wrong code without obvious issues is better
+                               // than code with an obvious issue.
+                               var ar = operation.Invoker.InvokeBegin (instance, parameters, callback, null);
                                object result = operation.Invoker.InvokeEnd (instance, out outParams, ar);
                                HandleInvokeResult (mrc, outParams, result);
                        }
@@ -98,16 +104,6 @@ namespace System.ServiceModel.Dispatcher
                        mrc.ReplyMessage = res;
                }
 
-               Message CreateActionNotSupported (Message req)
-               {
-                       FaultCode fc = new FaultCode (
-                               req.Version.Addressing.ActionNotSupported,
-                               req.Version.Addressing.Namespace);
-                       // FIXME: set correct namespace URI
-                       return Message.CreateMessage (req.Version, fc,
-                               String.Format ("action '{0}' is not supported in this service contract.", req.Headers.Action), String.Empty);
-               }
-
                void BuildInvokeParams (MessageProcessingContext mrc, out object [] parameters)
                {
                        DispatchOperation operation = mrc.Operation;
@@ -155,6 +151,14 @@ namespace System.ServiceModel.Dispatcher
 
                        var req = mrc.IncomingMessage;
 
+                       var fe = ex as FaultException;
+                       if (fe != null && fe.GetType ().IsGenericType) {
+                               var t = fe.GetType ().GetGenericArguments () [0];
+                               foreach (var fci in mrc.Operation.FaultContractInfos)
+                                       if (fci.Detail == t)
+                                               return Message.CreateMessage (req.Version, fe.CreateMessageFault (), fci.Action);
+                       }
+
                        // FIXME: set correct name
                        FaultCode fc = new FaultCode (
                                "InternalServiceFault",
index 434f459ca0ea7d99176a9d23a0ac9659cc30c9a7..3bef60dc7cf8b33c4a41ce81b6d17ce60baebdab 100644 (file)
@@ -34,22 +34,22 @@ using System.ServiceModel;
 
 namespace System.ServiceModel.Dispatcher
 {
-       [MonoTODO]
        public class XPathMessageContext : XsltContext
        {
                public XPathMessageContext ()
-                       : base ()
+                       : this (new NameTable ())
                {
                }
 
                public XPathMessageContext (NameTable nameTable)
                        : base (nameTable)
                {
+                       AddNamespace ("s11", Constants.Soap11);
+                       AddNamespace ("s12", Constants.Soap12);
                }
 
-               [MonoTODO]
                public override bool Whitespace {
-                       get { throw new NotImplementedException (); }
+                       get { return false; } // as documented.
                }
 
                public override int CompareDocument (string uri1, string uri2)
@@ -57,24 +57,21 @@ namespace System.ServiceModel.Dispatcher
                        return String.CompareOrdinal (uri1, uri2);
                }
 
-               [MonoTODO]
                public override bool PreserveWhitespace (XPathNavigator node)
                {
-                       throw new NotImplementedException ();
+                       return false; // as documented.
                }
 
-               [MonoTODO]
                public override IXsltContextFunction ResolveFunction (
                        string prefix, string name, XPathResultType [] argTypes)
                {
-                       throw new NotImplementedException ();
+                       return null;
                }
 
-               [MonoTODO]
                public override IXsltContextVariable ResolveVariable (
                        string prefix, string name)
                {
-                       throw new NotImplementedException ();
+                       return null;
                }
        }
 }
\ No newline at end of file
index b65b4e94e8b3650d9331dfe2aaaf6e92e5253241..71d7536fd34d95852b8f0af0763bfe1611f25552 100644 (file)
@@ -147,6 +147,16 @@ namespace System.ServiceModel.Dispatcher
                        throw new NotImplementedException ();
                }
 
+               public bool GetMatchingFilter (SeekableXPathNavigator navigator, out MessageFilter filter)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public bool GetMatchingFilter (XPathNavigator navigator, out MessageFilter filter)
+               {
+                       throw new NotImplementedException ();
+               }
+
                public bool GetMatchingFilters (Message message, ICollection<MessageFilter> results)
                {
                        throw new NotImplementedException ();
@@ -157,6 +167,16 @@ namespace System.ServiceModel.Dispatcher
                        throw new NotImplementedException ();
                }
 
+               public bool GetMatchingFilters (SeekableXPathNavigator navigator, ICollection<MessageFilter> results)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public bool GetMatchingFilters (XPathNavigator navigator, ICollection<MessageFilter> results)
+               {
+                       throw new NotImplementedException ();
+               }
+
                public bool GetMatchingValue (Message message, out TFilterData data)
                {
                        throw new NotImplementedException ();
@@ -167,6 +187,16 @@ namespace System.ServiceModel.Dispatcher
                        throw new NotImplementedException ();
                }
 
+               public bool GetMatchingValue (SeekableXPathNavigator navigator, out TFilterData data)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public bool GetMatchingValue (XPathNavigator navigator, out TFilterData data)
+               {
+                       throw new NotImplementedException ();
+               }
+
                public bool GetMatchingValues (Message message, ICollection<TFilterData> results)
                {
                        throw new NotImplementedException ();
@@ -177,6 +207,16 @@ namespace System.ServiceModel.Dispatcher
                        throw new NotImplementedException ();
                }
 
+               public bool GetMatchingValues (SeekableXPathNavigator navigator, ICollection<TFilterData> results)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public bool GetMatchingValues (XPathNavigator navigator, ICollection<TFilterData> results)
+               {
+                       throw new NotImplementedException ();
+               }
+
                public bool Remove (KeyValuePair<MessageFilter,TFilterData> item)
                {
                        if (dict.ContainsKey (item.Key) && dict [item.Key].Equals (item.Value)) {
@@ -188,29 +228,27 @@ namespace System.ServiceModel.Dispatcher
 
                public bool Remove (XPathMessageFilter filter)
                {
-                       throw new NotImplementedException ();
+                       return dict.Remove (filter);
                }
 
                public bool Remove (MessageFilter filter)
                {
-                       return dict.Remove (filter);
+                       return Remove ((XPathMessageFilter) filter);
                }
 
-               public bool TryGetValue (MessageFilter filter, out TFilterData filterData)
+               static Exception trim_to_size_error;
+
+               public void TrimToSize ()
                {
-                       if (dict.ContainsKey (filter)) {
-                               filterData = dict [filter];
-                               return true;
-                       } else {
-                               filterData = default (TFilterData);
-                               return false;
-                       }
+                       // This is the documented behavior: throws NIE.
+                       if (trim_to_size_error == null)
+                               trim_to_size_error = new NotImplementedException ();
+                       throw trim_to_size_error;
                }
 
-               [MonoTODO]
-               public void TrimToSize ()
+               public bool TryGetValue (MessageFilter filter, out TFilterData data)
                {
-                       throw new NotImplementedException ();
+                       return dict.TryGetValue (filter, out data);
                }
        }
 }
index 7e74bcf267e1257631cdaa724ac95f64b72f10aa..39586cfa16b74b4e24552dde05c86abcecad143e 100755 (executable)
@@ -257,7 +257,10 @@ System.ServiceModel.Channels/PeerInputChannel.cs
 System.ServiceModel.Channels/PeerOutputChannel.cs
 System.ServiceModel.Channels/PeerTransportBindingElement.cs
 System.ServiceModel.Channels/PnrpPeerResolverBindingElement.cs
+System.ServiceModel.Channels/PrivacyNoticeBindingElement.cs
+System.ServiceModel.Channels/ReliableSessionBindingElement.cs
 System.ServiceModel.Channels/ReliableSessionBindingElementImporter.cs
+System.ServiceModel.Channels/RemoteEndpointMessageProperty.cs
 System.ServiceModel.Channels/ReplyChannelBase.cs
 System.ServiceModel.Channels/RequestChannelBase.cs
 System.ServiceModel.Channels/RequestContext.cs
@@ -319,6 +322,8 @@ System.ServiceModel.Configuration/AuthorizationPolicyTypeElement.cs
 System.ServiceModel.Configuration/AuthorizationPolicyTypeElementCollection.cs
 System.ServiceModel.Configuration/BaseAddressElement.cs
 System.ServiceModel.Configuration/BaseAddressElementCollection.cs
+System.ServiceModel.Configuration/BaseAddressPrefixFilterElementCollection.cs
+System.ServiceModel.Configuration/BaseAddressPrefixFilterElement.cs
 System.ServiceModel.Configuration/BasicHttpBindingCollectionElement.cs
 System.ServiceModel.Configuration/BasicHttpBindingElement.cs
 System.ServiceModel.Configuration/BasicHttpMessageSecurityElement.cs
@@ -540,7 +545,6 @@ System.ServiceModel.Description/DataContractSerializerMessageContractImporter.cs
 System.ServiceModel.Description/DataContractSerializerOperationBehavior.cs
 System.ServiceModel.Description/FaultDescription.cs
 System.ServiceModel.Description/FaultDescriptionCollection.cs
-System.ServiceModel.Description/HostedBindingBehavior.cs
 System.ServiceModel.Description/IContractBehavior.cs
 System.ServiceModel.Description/IContractBehaviorAttribute.cs
 System.ServiceModel.Description/IEndpointBehavior.cs
@@ -801,6 +805,7 @@ System.ServiceModel/BasicHttpBinding.cs
 System.ServiceModel/BasicHttpMessageSecurity.cs
 System.ServiceModel/BasicHttpSecurity.cs
 System.ServiceModel/CallbackBehaviorAttribute.cs
+System.ServiceModel/ChannelTerminatedException.cs
 System.ServiceModel/ChannelFactory.cs
 System.ServiceModel/ChannelFactory_1.cs
 System.ServiceModel/ClientBase.cs
index d2d6c9344435729ee195f61ecdf36e9d94f14c30..dd610773554f9735138232077ea36d12cf6853ab 100755 (executable)
@@ -1,3 +1,77 @@
+2010-04-23  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ServiceHostBase.cs:
+         actually it should be ChannelDispatcher-to-HttpChannelListener,
+         to identify which dispatcher to send reqs.
+
+2010-04-23  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ServiceHostBase.cs : add host-to-http-listener mapping so that
+         they can be managed per host.
+
+2010-04-05  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ChannelTerminatedException.cs : new class.
+
+2010-04-02  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ClientRuntimeChannel.cs : hush on non-ml profile.
+
+2010-04-02  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ClientRuntimeChannel.cs :
+         use DataContractSerializer.IsStartObject() to check if the fault
+         detail reader is for the fault contract, in addition to Action.
+
+2010-04-02  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ClientRuntimeChannel.cs : fix moonlight build.
+
+2010-04-02  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ClientRuntimeChannel.cs : use FaultContractInfos to create custom
+         FaultException<T>. (It's not picking the expected FCI yet.)
+
+2010-03-30  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ClientRuntimeChannel.cs : use correct buffer size.
+
+2010-03-26  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ClientRuntimeChannel.cs : use FaultConverter as documented at:
+         http://msdn.microsoft.com/en-us/library/ms789039%28VS.100%29.aspx
+         (Though I found _no_ use of this FC class in the world...)
+
+2010-03-24  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ServiceHostBase.cs : if there is an existing ChannelDispatcher
+         for the same endpoint URI, reuse it. Patch by Matt Dargavel.
+
+2010-03-18  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * Constants.cs : add more.
+
+2010-03-18  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * Dummy.cs : removed some dummy types (not dummy anymore).
+
+2010-03-17  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ServiceHostBase.cs : use namespace for mex binding comparison, to
+         cover other bindings than http (such as https).
+       * WSHttpBindingBase.cs : add some comment.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * ClientBase.cs, ClientRuntimeChannel.cs: use MOONLIGHT symbol to
+       disambiguate MonoTouch and Moonlight code.
+
+2010-03-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ServiceHostBase.cs : do not reject endpoints with an identical
+         contract to existing ones but with different binding, address or
+         listen URI.
+
 2010-03-09  Atsushi Enomoto  <atsushi@ximian.com>
 
        * HttpTransportSecurity.cs : remove MonoTODOs.
diff --git a/mcs/class/System.ServiceModel/System.ServiceModel/ChannelTerminatedException.cs b/mcs/class/System.ServiceModel/System.ServiceModel/ChannelTerminatedException.cs
new file mode 100644 (file)
index 0000000..012b9b1
--- /dev/null
@@ -0,0 +1,43 @@
+//
+// ChannelTerminatedException.cs
+//
+// Author: Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.ObjectModel;
+using System.Runtime.Serialization;
+
+namespace System.ServiceModel
+{
+       [Serializable]
+       public class ChannelTerminatedException : CommunicationException
+       {
+               public ChannelTerminatedException () : base () {}
+               public ChannelTerminatedException (string msg) : base (msg) {}
+               public ChannelTerminatedException (string msg, Exception inner) : base (msg, inner) {}
+               protected ChannelTerminatedException (SerializationInfo info, StreamingContext context) :
+                       base (info, context) {}
+       }
+}
index 6281ba53bc8055100db54360d4a5b68ee5ed6170..d9e98a1856700aeeaee3c63f3cc801deaa1a8686 100644 (file)
@@ -39,13 +39,13 @@ namespace System.ServiceModel
 {
        [MonoTODO ("It somehow rejects classes, but dunno how we can do that besides our code wise.")]
        public abstract class ClientBase<TChannel> :
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                IDisposable,
 #endif
                ICommunicationObject where TChannel : class
        {
                static InstanceContext initialContxt = new InstanceContext (null);
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                static readonly PropertyInfo dispatcher_main_property;
                static readonly MethodInfo dispatcher_begin_invoke_method;
 
@@ -222,7 +222,7 @@ namespace System.ServiceModel
 
                void RunCompletedCallback (SendOrPostCallback callback, InvokeAsyncCompletedEventArgs args)
                {
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        callback (args);
 #else
                        object dispatcher = dispatcher_main_property.GetValue (null, null);
@@ -276,7 +276,7 @@ namespace System.ServiceModel
                }
                IAsyncResult begin_async_result;
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                void IDisposable.Dispose ()
                {
                        Close ();
@@ -402,7 +402,7 @@ namespace System.ServiceModel
                                }
                        }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        protected object Invoke (string methodName, object [] args)
                        {
                                var cd = endpoint.Contract;
index ffd858cd25669de9beb921a6eabaaf1e58f6923b..a1c9a73258bb0f4645784cd6ff4e395f96295803 100644 (file)
@@ -27,6 +27,7 @@
 //
 using System;
 using System.Reflection;
+using System.Runtime.Serialization;
 using System.ServiceModel.Channels;
 using System.ServiceModel.Description;
 using System.ServiceModel.Dispatcher;
@@ -166,7 +167,7 @@ namespace System.ServiceModel.MonoInternal
                                }
                        }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        public override bool WaitOne (int millisecondsTimeout, bool exitContext)
                        {
                                return WaitHandle.WaitAll (ResultWaitHandles, millisecondsTimeout, exitContext);
@@ -429,8 +430,10 @@ namespace System.ServiceModel.MonoInternal
                        try {
                                return DoProcess (method, operationName, parameters);
                        } catch (Exception ex) {
+#if MOONLIGHT // just for debugging
                                Console.Write ("Exception in async operation: ");
                                Console.WriteLine (ex);
+#endif
                                throw;
                        }
                }
@@ -482,20 +485,33 @@ namespace System.ServiceModel.MonoInternal
 
                        Message res = Request (req, OperationTimeout);
                        if (res.IsFault) {
-                               MessageFault fault = MessageFault.CreateFault (res, runtime.MaxFaultSize);
-                               if (fault.HasDetail && fault is MessageFault.SimpleMessageFault) {
-                                       MessageFault.SimpleMessageFault simpleFault = fault as MessageFault.SimpleMessageFault;
-                                       object detail = simpleFault.Detail;
-                                       Type t = detail.GetType ();
-                                       Type faultType = typeof (FaultException<>).MakeGenericType (t);
-                                       object [] constructorParams = new object [] { detail, fault.Reason, fault.Code, fault.Actor };
-                                       FaultException fe = (FaultException) Activator.CreateInstance (faultType, constructorParams);
-                                       throw fe;
-                               }
-                               else {
-                                       // given a MessageFault, it is hard to figure out the type of the embedded detail
-                                       throw new FaultException(fault);
+                               var resb = res.CreateBufferedCopy (runtime.MaxFaultSize);
+                               MessageFault fault = MessageFault.CreateFault (resb.CreateMessage (), runtime.MaxFaultSize);
+                               var conv = OperationChannel.GetProperty<FaultConverter> () ?? FaultConverter.GetDefaultFaultConverter (res.Version);
+                               Exception ex;
+                               if (!conv.TryCreateException (resb.CreateMessage (), fault, out ex)) {
+                                       if (fault.HasDetail) {
+                                               Type detailType = typeof (ExceptionDetail);
+                                               var freader = fault.GetReaderAtDetailContents ();
+                                               DataContractSerializer ds = null;
+#if !NET_2_1
+                                               foreach (var fci in op.FaultContractInfos)
+                                                       if (res.Headers.Action == fci.Action || fci.Serializer.IsStartObject (freader)) {
+                                                               detailType = fci.Detail;
+                                                               ds = fci.Serializer;
+                                                               break;
+                                                       }
+#endif
+                                               if (ds == null)
+                                                       ds = new DataContractSerializer (detailType);
+                                               var detail = ds.ReadObject (freader);
+                                               ex = (Exception) Activator.CreateInstance (typeof (FaultException<>).MakeGenericType (detailType), new object [] {detail, fault.Reason, fault.Code, res.Headers.Action});
+                                       }
+
+                                       if (ex == null)
+                                               ex = new FaultException (fault);
                                }
+                               throw ex;
                        }
 
                        for (int i = 0; i < inspections.Length; i++)
index 0c69185b2b77e22252aa0ce2ef788d51e9094c1d..8363da178a5e067c6d6ca08d3471010ee9c40c7a 100644 (file)
@@ -31,6 +31,9 @@ namespace System.ServiceModel
 {
        internal class Constants
        {
+               public const string Soap11 = "http://schemas.xmlsoap.org/soap/envelope/";
+               public const string Soap12 = "http://www.w3.org/2003/05/soap-envelope";
+
                public const string WSBasicSecurityProfileCore1 = "http://ws-i.org/profiles/basic-security/core/1.0";
 
                public const string WsaAnonymousUri = "http://www.w3.org/2005/08/addressing/anonymous";
index faf46e474d3faab421e84fc41b229202dbdfdc70..5a1241df70aa3e9b77c8957d1bfef1daa0c688e6 100644 (file)
@@ -17,9 +17,7 @@ namespace System.ServiceModel.Activation.Configuration
 
 namespace System.ServiceModel.Channels
 {
-       public class PrivacyNoticeBindingElement { }
        public class PrivacyNoticeBindingElementImporter { }
-       public class ReliableSessionBindingElement { }
        public class UseManagedPresentationBindingElementImporter { }
        public class XmlSerializerImportOptions { }
 }
index f799f9a3cd776e46842d86204a30c1e4eb7c64b1..81b5608aabdaa9e6acbd19776e59d7d5e5c23a3a 100644 (file)
@@ -41,6 +41,9 @@ namespace System.ServiceModel
        public abstract partial class ServiceHostBase
                : CommunicationObject, IExtensibleObject<ServiceHostBase>, IDisposable
        {
+               // It is used for mapping a ServiceHostBase to HttpChannelListener precisely.
+               internal static ServiceHostBase CurrentServiceHostHack;
+
                ServiceCredentials credentials;
                ServiceDescription description;
                UriSchemeKeyedCollection base_addresses;
@@ -197,7 +200,7 @@ namespace System.ServiceModel
                        Uri address, Uri listenUri)
                {
                        EndpointAddress ea = BuildEndpointAddress (address, binding);
-                       ContractDescription cd = GetContract (implementedContract, binding.Name == "MetadataExchangeHttpBinding");
+                       ContractDescription cd = GetContract (implementedContract, binding.Namespace == "http://schemas.microsoft.com/ws/2005/02/mex/bindings");
                        if (cd == null)
                                throw new InvalidOperationException (String.Format ("Contract '{0}' was not found in the implemented contracts in this service host.", implementedContract));
                        return AddServiceEndpointCore (cd, binding, ea, listenUri);
@@ -279,7 +282,7 @@ namespace System.ServiceModel
                        ContractDescription cd, Binding binding, EndpointAddress address, Uri listenUri)
                {
                        foreach (ServiceEndpoint e in Description.Endpoints)
-                               if (e.Contract == cd)
+                               if (e.Contract == cd && e.Binding == binding && e.Address == address && e.ListenUri.Equals (listenUri))
                                        return e;
                        ServiceEndpoint se = new ServiceEndpoint (cd, binding, address);
                        se.ListenUri = listenUri.IsAbsoluteUri ? listenUri : new Uri (address.Uri, listenUri);
@@ -287,7 +290,6 @@ namespace System.ServiceModel
                        return se;
                }
 
-               [MonoTODO]
                protected virtual void ApplyConfiguration ()
                {
                        if (Description == null)
@@ -316,7 +318,6 @@ namespace System.ServiceModel
 
                                // services
                                foreach (ServiceEndpointElement endpoint in service.Endpoints) {
-                                       // FIXME: consider BindingName as well
                                        ServiceEndpoint se = AddServiceEndpoint (
                                                endpoint.Contract,
                                                ConfigUtil.CreateBinding (endpoint.Binding, endpoint.BindingConfiguration),
@@ -377,18 +378,18 @@ namespace System.ServiceModel
                        //Build all ChannelDispatchers, one dispatcher per user configured EndPoint.
                        //We must keep thet ServiceEndpoints as a seperate collection, since the user
                        //can change the collection in the description during the behaviors events.
-                       Dictionary<ServiceEndpoint, ChannelDispatcher> endPointToDispatcher = new Dictionary<ServiceEndpoint,ChannelDispatcher>();
                        ServiceEndpoint[] endPoints = new ServiceEndpoint[Description.Endpoints.Count];
                        Description.Endpoints.CopyTo (endPoints, 0);
+                       var builder = new DispatcherBuilder (this);
                        foreach (ServiceEndpoint se in endPoints) {
 
                                var commonParams = new BindingParameterCollection ();
                                foreach (IServiceBehavior b in Description.Behaviors)
                                        b.AddBindingParameters (Description, this, Description.Endpoints, commonParams);
 
-                               var channel = new DispatcherBuilder ().BuildChannelDispatcher (Description.ServiceType, se, commonParams);
-                               ChannelDispatchers.Add (channel);
-                               endPointToDispatcher[se] = channel;
+                               var channel = builder.BuildChannelDispatcher (Description.ServiceType, se, commonParams);
+                               if (!ChannelDispatchers.Contains (channel))
+                                       ChannelDispatchers.Add (channel);
                        }
 
                        //After the ChannelDispatchers are created, and attached to the service host
@@ -396,9 +397,7 @@ namespace System.ServiceModel
                        foreach (IServiceBehavior b in Description.Behaviors)
                                b.ApplyDispatchBehavior (Description, this);
 
-                       foreach(KeyValuePair<ServiceEndpoint, ChannelDispatcher> val in endPointToDispatcher)
-                               foreach (var ed in val.Value.Endpoints)
-                                       ApplyDispatchBehavior (ed, val.Key);                    
+                       builder.ApplyDispatchBehaviors ();
                }
 
                private void ValidateDescription ()
@@ -412,19 +411,6 @@ namespace System.ServiceModel
                                throw new InvalidOperationException ("The ServiceHost must have at least one application endpoint (that does not include metadata exchange contract) defined by either configuration, behaviors or call to AddServiceEndpoint methods.");
                }
 
-               private void ApplyDispatchBehavior (EndpointDispatcher ed, ServiceEndpoint endPoint)
-               {
-                       foreach (IContractBehavior b in endPoint.Contract.Behaviors)
-                               b.ApplyDispatchBehavior (endPoint.Contract, endPoint, ed.DispatchRuntime);
-                       foreach (IEndpointBehavior b in endPoint.Behaviors)
-                               b.ApplyDispatchBehavior (endPoint, ed);
-                       foreach (OperationDescription operation in endPoint.Contract.Operations) {
-                               foreach (IOperationBehavior b in operation.Behaviors)
-                                       b.ApplyDispatchBehavior (operation, ed.DispatchRuntime.Operations [operation.Name]);
-                       }
-
-               }
-
                [MonoTODO]
                protected void LoadConfigurationSection (ServiceElement element)
                {
@@ -598,19 +584,76 @@ namespace System.ServiceModel
                */
        }
 
+       /// <summary>
+       ///  Builds ChannelDispatchers as appropriate to service the service endpoints. 
+       /// </summary>
+       /// <remarks>Will re-use ChannelDispatchers when two endpoint uris are the same</remarks>
        partial class DispatcherBuilder
        {
+               ServiceHostBase host;
+
+               public DispatcherBuilder (ServiceHostBase host)
+               {
+                       this.host = host;
+               }
+
+               List<ChannelDispatcher> built_dispatchers = new List<ChannelDispatcher> ();
+               Dictionary<ServiceEndpoint, EndpointDispatcher> ep_to_dispatcher_ep = new Dictionary<ServiceEndpoint, EndpointDispatcher> ();
+
+               internal static Action<ChannelDispatcher> ChannelDispatcherSetter;
+
                internal ChannelDispatcher BuildChannelDispatcher (Type serviceType, ServiceEndpoint se, BindingParameterCollection commonParams)
                {
                        //Let all behaviors add their binding parameters
                        AddBindingParameters (commonParams, se);
-                       //User the binding parameters to build the channel listener and Dispatcher
-                       IChannelListener lf = BuildListener (se, commonParams);
-                       ChannelDispatcher cd = new ChannelDispatcher (
-                               lf, se.Binding.Name);
-                       cd.InitializeServiceEndpoint (serviceType, se);
+                       
+                       // See if there's an existing channel that matches this endpoint
+                       ChannelDispatcher cd = FindExistingDispatcher (se);
+                       EndpointDispatcher ep;
+                       if (cd != null) {
+                               ep = cd.InitializeServiceEndpoint (serviceType, se);
+                       } else {
+                               // Use the binding parameters to build the channel listener and Dispatcher.
+                               lock (HttpTransportBindingElement.ListenerBuildLock) {
+                                       ServiceHostBase.CurrentServiceHostHack = host;
+                                       IChannelListener lf = BuildListener (se, commonParams);
+                                       cd = new ChannelDispatcher (lf, se.Binding.Name);
+                                       if (ChannelDispatcherSetter != null) {
+                                               ChannelDispatcherSetter (cd);
+                                               ChannelDispatcherSetter = null;
+                                       }
+                                       ServiceHostBase.CurrentServiceHostHack = null;
+                               }
+                               ep = cd.InitializeServiceEndpoint (serviceType, se);
+                               built_dispatchers.Add (cd);
+                       }
+                       ep_to_dispatcher_ep[se] = ep;
                        return cd;
                }
+               
+               ChannelDispatcher FindExistingDispatcher (ServiceEndpoint se)
+               {
+                       return built_dispatchers.FirstOrDefault ((ChannelDispatcher cd) => (cd.Listener.Uri.Equals (se.ListenUri)) && cd.MessageVersion.Equals (se.Binding.MessageVersion));
+               }
+
+               internal void ApplyDispatchBehaviors ()
+               {
+                       foreach (KeyValuePair<ServiceEndpoint, EndpointDispatcher> val in ep_to_dispatcher_ep)
+                               ApplyDispatchBehavior (val.Value, val.Key);
+               }
+               
+               private void ApplyDispatchBehavior (EndpointDispatcher ed, ServiceEndpoint endPoint)
+               {
+                       foreach (IContractBehavior b in endPoint.Contract.Behaviors)
+                               b.ApplyDispatchBehavior (endPoint.Contract, endPoint, ed.DispatchRuntime);
+                       foreach (IEndpointBehavior b in endPoint.Behaviors)
+                               b.ApplyDispatchBehavior (endPoint, ed);
+                       foreach (OperationDescription operation in endPoint.Contract.Operations) {
+                               foreach (IOperationBehavior b in operation.Behaviors)
+                                       b.ApplyDispatchBehavior (operation, ed.DispatchRuntime.Operations [operation.Name]);
+                       }
+
+               }
 
                private void AddBindingParameters (BindingParameterCollection commonParams, ServiceEndpoint endPoint) {
 
index 9f5fcac8879f53b5d287a39d41f8fc84383c9125..ea294883a65a756c6f5b5f9916f08e7952f3ebc0 100644 (file)
@@ -172,12 +172,13 @@ namespace System.ServiceModel
                        }
                        BindingElement tr = GetTransport ();
                        List<BindingElement> list = new List<BindingElement> ();
-                       list.Add (tx);
+                       list.Add (tx); // it is always added.
                        if (sec != null)
                                list.Add (sec);
                        list.Add (msg);
                        if (tr != null)
                                list.Add (tr);
+                       // FIXME: add ReliableSessionBindingElement
                        return new BindingElementCollection (list.ToArray ());
                }
 
index aaeadc7b8ff67b5524e5085890beb6da0ad24d90..2b8e7817b4ebcbc2f2a692d5c76d872829c4f2d9 100644 (file)
@@ -1,3 +1,37 @@
+FeatureBased/Features.Client/AsyncCallTesterProxy.cs
+FeatureBased/Features.Client/AsyncPatternServer.cs
+FeatureBased/Features.Client/DataContractTesterProxy.cs
+FeatureBased/Features.Client/ExitProcessHelperServer.cs
+FeatureBased/Features.Client/FaultsTesterProxy.cs
+FeatureBased/Features.Client/KnownTypeTesterProxy.cs
+FeatureBased/Features.Client/MessageContractTesterProxy.cs
+FeatureBased/Features.Client/OperationContractServer.cs
+FeatureBased/Features.Client/PrimitiveTester.cs
+FeatureBased/Features.Client/UntypedMessageTesterProxy.cs
+FeatureBased/Features.Contracts/AsyncCallTester.cs
+FeatureBased/Features.Contracts/AsyncPatternContract.cs
+FeatureBased/Features.Contracts/DataContractTester.cs
+FeatureBased/Features.Contracts/DualContract.cs
+FeatureBased/Features.Contracts/ExitpProcessHelper.cs
+FeatureBased/Features.Contracts/FaultsTester.cs
+FeatureBased/Features.Contracts/KnownTypeTester.cs
+FeatureBased/Features.Contracts/MessageContractTester.cs
+FeatureBased/Features.Contracts/OperationContract.cs
+FeatureBased/Features.Contracts/PrimitiveTester.cs
+FeatureBased/Features.Contracts/UntypedMessageTester.cs
+FeatureBased/Features.Serialization/AsyncCallTest.cs
+FeatureBased/Features.Serialization/AsyncPatternTester.cs
+FeatureBased/Features.Serialization/DataContractSerializerTest.cs
+FeatureBased/Features.Serialization/DualContractTester.cs
+FeatureBased/Features.Serialization/ExitProcessHelper.cs
+FeatureBased/Features.Serialization/FaultsTest.cs
+FeatureBased/Features.Serialization/KnownTypeTest.cs
+FeatureBased/Features.Serialization/MessageContractTest.cs
+FeatureBased/Features.Serialization/OperationContractTester.cs
+FeatureBased/Features.Serialization/PrimitiveTesterTest.cs
+FeatureBased/Features.Serialization/UntypedMessageTest.cs
+FeatureBased/Features.Serialization/XmlComparer.cs
+FeatureBased/TestFixtureBase.cs
 System.ServiceModel.Channels/AddressHeaderTest.cs
 System.ServiceModel.Channels/AddressingVersionTest.cs
 System.ServiceModel.Channels/AsymmetricSecurityBindingElementTest.cs
@@ -67,11 +101,13 @@ System.ServiceModel.Configuration/StandardBindingElementTest.cs
 System.ServiceModel.Configuration/UserBinding.cs
 System.ServiceModel.Description/ClientCredentialsTest.cs
 System.ServiceModel.Description/ContractDescriptionTest.cs
+System.ServiceModel.Description/FaultDescriptionTest.cs
+System.ServiceModel.Description/MetadataExchangeBindingsTest.cs
 System.ServiceModel.Description/MetadataResolverTest.cs
 System.ServiceModel.Description/OperationDescriptionTest.cs
 System.ServiceModel.Description/ServiceAuthorizationBehaviorTest.cs
-System.ServiceModel.Description/ServiceCredentialsTest.cs
 System.ServiceModel.Description/ServiceContractGeneratorTest.cs
+System.ServiceModel.Description/ServiceCredentialsTest.cs
 System.ServiceModel.Description/ServiceDebugBehaviorTest.cs
 System.ServiceModel.Description/ServiceEndpointTest.cs
 System.ServiceModel.Description/ServiceMetadataBehaviorTest.cs
@@ -80,6 +116,7 @@ System.ServiceModel.Description/TypedMessageConverterTest.cs
 System.ServiceModel.Description/WsdlExporterTest.cs
 System.ServiceModel.Description/WsdlImporterTest.cs
 System.ServiceModel.Dispatcher/ActionFilterTest.cs
+System.ServiceModel.Dispatcher/ChannelDispatcherTest.cs
 System.ServiceModel.Dispatcher/DispatchOperationTest.cs
 System.ServiceModel.Dispatcher/DispatchRuntimeTest.cs
 System.ServiceModel.Dispatcher/EndpointAddressMessageFilterTest.cs
@@ -88,7 +125,7 @@ System.ServiceModel.Dispatcher/ExceptionHandlerTest.cs
 System.ServiceModel.Dispatcher/FilterTableTest.cs
 System.ServiceModel.Dispatcher/InvalidBodyAccessExceptionTest.cs
 System.ServiceModel.Dispatcher/PrefixEndpointAddressMessageFilterTest.cs
-System.ServiceModel.Dispatcher/ChannelDispatcherTest.cs
+System.ServiceModel.Dispatcher/XPathMessageContextTest.cs
 System.ServiceModel.PeerResolvers/CustomPeerResolverServiceTest.cs
 System.ServiceModel.PeerResolvers/PeerResolverSerializationTest.cs
 System.ServiceModel.Security.Tokens/IssuedSecurityTokenParametersTest.cs
@@ -113,6 +150,7 @@ System.ServiceModel.Security/SecurityTokenSpeficicationTest.cs
 System.ServiceModel.Security/ServiceCredentialsSecurityTokenManagerTest.cs
 System.ServiceModel.Security/ServiceSecurityContextTest.cs
 System.ServiceModel.Security/SupportingTokenParametersTest.cs
+System.ServiceModel.Security/TransportSecurityBindingElementTest.cs
 System.ServiceModel.Security/WSSecurityTokenSerializerTest.cs
 System.ServiceModel/BasicHttpBindingTest.cs
 System.ServiceModel/CallbackBehaviorAttributeTest.cs
@@ -122,6 +160,7 @@ System.ServiceModel/ClientBaseTest.cs
 System.ServiceModel/ClientBase_InteractiveChannelInitializerTest.cs
 System.ServiceModel/ClientCredentialsSecurityTokenManagerTest.cs
 System.ServiceModel/CommonUseCases.cs
+System.ServiceModel/Constants.cs
 System.ServiceModel/EndpointAddress10Test.cs
 System.ServiceModel/EndpointAddressBuilderTest.cs
 System.ServiceModel/EndpointAddressTest.cs
@@ -129,12 +168,13 @@ System.ServiceModel/EndpointBehaviorCollectionTest.cs
 System.ServiceModel/EndpointIdentityTest.cs
 System.ServiceModel/ExtensionCollectionTest.cs
 System.ServiceModel/FaultCodeTest.cs
+System.ServiceModel/FaultContractAttributeTest.cs
 System.ServiceModel/FaultReasonTest.cs
 System.ServiceModel/IntegratedConnectionTest.cs
 System.ServiceModel/MessageSecurityVersionTest.cs
 System.ServiceModel/NetMsmqBindingTest.cs
-System.ServiceModel/NetTcpBindingTest.cs
 System.ServiceModel/NetPeerTcpBindingTest.cs
+System.ServiceModel/NetTcpBindingTest.cs
 System.ServiceModel/OperationContextTest.cs
 System.ServiceModel/PeerNodeAddressTest.cs
 System.ServiceModel/ServiceAssert.cs
@@ -147,23 +187,3 @@ System.ServiceModel/TransactionProtocolTest.cs
 System.ServiceModel/UriSchemeKeyedCollectionTest.cs
 System.ServiceModel/WSFederationHttpBindingTest.cs
 System.ServiceModel/WSHttpBindingTest.cs
-FeatureBased/TestFixtureBase.cs
-FeatureBased/Features.Client/DataContractTesterProxy.cs
-FeatureBased/Features.Client/PrimitiveTester.cs
-FeatureBased/Features.Contracts/DataContractTester.cs
-FeatureBased/Features.Contracts/DualContract.cs
-FeatureBased/Features.Contracts/MessageContractTester.cs
-FeatureBased/Features.Contracts/PrimitiveTester.cs
-FeatureBased/Features.Serialization/DataContractSerializerTest.cs
-FeatureBased/Features.Serialization/DualContractTester.cs
-FeatureBased/Features.Serialization/PrimitiveTesterTest.cs
-FeatureBased/Features.Client/FaultsTesterProxy.cs
-FeatureBased/Features.Client/KnownTypeTesterProxy.cs
-FeatureBased/Features.Client/MessageContractTesterProxy.cs
-FeatureBased/Features.Client/UntypedMessageTesterProxy.cs
-FeatureBased/Features.Serialization/FaultsTest.cs
-FeatureBased/Features.Contracts/FaultsTester.cs
-FeatureBased/Features.Contracts/KnownTypeTester.cs
-FeatureBased/Features.Serialization/MessageContractTest.cs
-FeatureBased/Features.Contracts/UntypedMessageTester.cs
-FeatureBased/Features.Serialization/XmlComparer.cs
index d61a3eae06b8ee0d515beec608a44d475f5bb34b..5be1171fbc5411fd33f32c12169d890b8b0a8309 100644 (file)
@@ -9,8 +9,7 @@ using System.Threading;
 namespace MonoTests.Features.Serialization
 {
        [TestFixture]
-       [Category ("NotWorking")] // Can't even build in Mono. Missing public APIs.
-    public class AsyncCallTest : TestFixtureBase<AsyncCallTesterContractClient, AsyncCallTester, MonoTests.Features.Contracts.IAsyncCallTesterContract>
+       public class AsyncCallTest : TestFixtureBase<AsyncCallTesterContractClient, AsyncCallTester, MonoTests.Features.Contracts.IAsyncCallTesterContract>
        {
                bool client_QueryCompleted;
                string s = string.Empty;
@@ -21,6 +20,7 @@ namespace MonoTests.Features.Serialization
         {
         }
                [Test]
+               [Category ("NotWorking")]
                public void TestAsyncCall ()
                {
             ev = new AutoResetEvent(false);
index 265751ed9bac3cdc81d06deb91a99153ace12600..6d6a30ff5423bd45190b6ecd6a29dd8ea7ec76ac 100644 (file)
@@ -14,7 +14,6 @@ namespace MonoTests.Features.Serialization
        {\r
 \r
                [Test]\r
-               [Category("NotWorking")]\r
                public void TestAsync () {\r
                        Assert.AreEqual (ClientProxy.AsyncMethod (), 3, "Called method with AsyncPattern=true");\r
                }\r
index a8f889a7a48545b3770018d331a1cde90755e540..c6604c5d252780d074de30c4b60dfc812aa1aec2 100644 (file)
@@ -1,3 +1,13 @@
+2010-04-21  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * AsyncCallTest.cs : disable it again, it somehow does not work with
+         the latest code from trunk (ThreadPool?).
+
+2010-04-19  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * AsyncPatternTester.cs, MessageContractTest.cs, AsyncCallTest.cs:
+         enable working tests.
+
 2009-02-24  Atsushi Enomoto  <atsushi@ximian.com>
 
        * MessageContractTest.cs:
index a429b00a32c7c7a3a8c56270814b64457cebeecf..6b6bb2f95ab9982d0c85dcf969bee73af3d873ef 100644 (file)
@@ -7,8 +7,7 @@ using NUnit.Framework;
 namespace MonoTests.Features.Serialization
 {
        [TestFixture]
-       [Category ("NotWorking")] // Serialization failure
-    public class MessageContractTest : TestFixtureBase<MessageContractTesterContractClient, MonoTests.Features.Contracts.MessageContractTester, MonoTests.Features.Contracts.IMessageContractTesterContract>
+       public class MessageContractTest : TestFixtureBase<MessageContractTesterContractClient, MonoTests.Features.Contracts.MessageContractTester, MonoTests.Features.Contracts.IMessageContractTesterContract>
        {
                [Test]
                [Ignore ("fails under .NET; I never bothered to fix the test")]
index 75c583db55a9b82be9aefcc35e1a54a4236836df..54cb53aaaac4510ac2e6ac0aa0a22f7d4bd4170c 100644 (file)
@@ -1,3 +1,51 @@
+2010-04-21  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * CustomBindingTest.cs : enable BuildChannelListener test for no-
+         transport case. Test CanBuildChannelListener too.
+
+2010-04-01  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * TcpTransportBindingElementTest.cs : GetProperty<T>() here too.
+
+2010-04-01  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * HttpsTransportBindingElementTest.cs :
+         added test for GetProperty<T>().
+
+2010-03-29  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * FaultConverterTest.cs : added more TryCreateException() tests.
+
+2010-03-29  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * MessageHeaderTest.cs : enable one, add not-working cosmetic one.
+
+2010-03-29  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * MessageBufferTest.cs : enable not-working test.
+
+2010-03-29  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * MessageFaultTest.cs : enable previous test.
+
+2010-03-29  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * FaultConverterTest.cs : enable previous test.
+
+2010-03-26  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * FaultConverterTest.cs, MessageFaultTest.cs : add new and not-working
+         tests.
+
+2010-03-26  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * MessageBufferTest.cs : add test for copy of IsFault value.
+
+2010-03-25  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * MessageTest.cs : add another IsFault tests, which exposed some
+         issues at client side.
+
 2010-01-21  Atsushi Enomoto  <atsushi@ximian.com>
 
        * SslStreamSecurityBindingElementTest.cs : reduce extra base dep.
index a3948a36c710445af8e98a10509bbb18ef118b8c..02e209690b5a4fb948c669bd96c59d29a109cf3c 100644 (file)
@@ -242,13 +242,20 @@ namespace MonoTests.System.ServiceModel.Channels
                }
 
                [Test]
-               [ExpectedException (typeof (ArgumentException))]
-               [Category ("NotWorking")]
+               [ExpectedException (typeof (InvalidOperationException))]
+               public void CanBuildChannelListenerNoTransport ()
+               {
+                       CustomBinding cb = new CustomBinding ();
+                       BindingContext ctx = new BindingContext (
+                               cb, new BindingParameterCollection ());
+                       Assert.IsFalse (new TextMessageEncodingBindingElement ().CanBuildChannelListener<IReplyChannel> (ctx), "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (InvalidOperationException))]
                public void BuildChannelListenerNoTransport ()
                {
-                       CustomBinding cb = new CustomBinding (
-                               new TextMessageEncodingBindingElement (),
-                               new CompositeDuplexBindingElement ());
+                       CustomBinding cb = new CustomBinding ();
                        BindingContext ctx = new BindingContext (
                                cb, new BindingParameterCollection ());
                        new TextMessageEncodingBindingElement ().BuildChannelListener<IReplyChannel> (ctx);
index 60587df22dcb44db3011677f36b815a517d6ba63..7df58d9954f6aaa128e47d9036c0b04018076c80 100644 (file)
@@ -38,7 +38,8 @@ namespace MonoTests.System.ServiceModel.Channels
        public class FaultConverterTest
        {
                static readonly FaultConverter s11 = FaultConverter.GetDefaultFaultConverter (MessageVersion.Soap11WSAddressing10);
-               static readonly FaultConverter s12 = FaultConverter.GetDefaultFaultConverter (MessageVersion.Default);
+               static readonly FaultConverter s12 = FaultConverter.GetDefaultFaultConverter (MessageVersion.Soap12WSAddressing10);
+               static readonly FaultConverter none = FaultConverter.GetDefaultFaultConverter (MessageVersion.None);
 
                XmlWriterSettings GetWriterSettings ()
                {
@@ -48,7 +49,7 @@ namespace MonoTests.System.ServiceModel.Channels
                }
 
                [Test]
-               public void TryCreateExceptionDefault ()
+               public void TryCreateFaultMessageDefault ()
                {
                        Message msg;
                        Assert.IsFalse (s12.TryCreateFaultMessage (new Exception ("error happened"), out msg), "#1-1");
@@ -57,11 +58,108 @@ namespace MonoTests.System.ServiceModel.Channels
 
                        Assert.IsFalse (s12.TryCreateFaultMessage (new FaultException<string> ("fault happened."), out msg), "#1-3");
 
+                       Assert.IsTrue (s12.TryCreateFaultMessage (new ActionNotSupportedException (), out msg), "#1-4");
+                       Assert.IsTrue (msg.IsFault, "#1-5");
+                       Assert.AreEqual ("http://www.w3.org/2005/08/addressing/fault", msg.Headers.Action, "#1-6");
+                       var f = MessageFault.CreateFault (msg, 1000);
+                       Assert.AreEqual ("Sender", f.Code.Name, "#1-7");
+                       Assert.AreEqual ("http://www.w3.org/2003/05/soap-envelope", f.Code.Namespace, "#1-8");
+                       Assert.AreEqual ("ActionNotSupported", f.Code.SubCode.Name, "#1-9");
+                       Assert.AreEqual ("http://www.w3.org/2005/08/addressing", f.Code.SubCode.Namespace, "#1-10");
+
                        Assert.IsFalse (s11.TryCreateFaultMessage (new Exception ("error happened"), out msg), "#2-1");
 
                        Assert.IsFalse (s11.TryCreateFaultMessage (new FaultException ("fault happened", FaultCode.CreateSenderFaultCode (new FaultCode ("IAmBroken"))), out msg), "#2-2");
 
                        Assert.IsFalse (s11.TryCreateFaultMessage (new FaultException<string> ("fault happened."), out msg), "#2-3");
+
+                       Assert.IsTrue (s11.TryCreateFaultMessage (new ActionNotSupportedException (), out msg), "#2-4");
+                       Assert.IsTrue (msg.IsFault, "#2-5");
+                       Assert.AreEqual ("http://www.w3.org/2005/08/addressing/fault", msg.Headers.Action, "#2-6");
+                       f = MessageFault.CreateFault (msg, 1000);
+                       Assert.AreEqual ("ActionNotSupported", f.Code.Name, "#2-7");
+                       Assert.AreEqual ("http://www.w3.org/2005/08/addressing", f.Code.Namespace, "#2-8");
+
+                       Assert.IsFalse (none.TryCreateFaultMessage (new Exception ("error happened"), out msg), "#3-1");
+
+                       Assert.IsFalse (none.TryCreateFaultMessage (new FaultException ("fault happened", FaultCode.CreateSenderFaultCode (new FaultCode ("IAmBroken"))), out msg), "#3-2");
+
+                       Assert.IsFalse (none.TryCreateFaultMessage (new FaultException<string> ("fault happened."), out msg), "#3-3");
+
+                       Assert.IsFalse (none.TryCreateFaultMessage (new ActionNotSupportedException (), out msg), "#3-4");
+
+                       Assert.IsFalse (none.TryCreateFaultMessage (new EndpointNotFoundException (), out msg), "#3-5");
+               }
+
+                       string xml1 = @"
+<s:Envelope xmlns:a='http://www.w3.org/2005/08/addressing' xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'>
+  <s:Header>
+    <a:Action s:mustUnderstand='1'>http://www.w3.org/2005/08/addressing/fault</a:Action>
+  </s:Header>
+  <s:Body>
+    <s:Fault>
+      <faultcode>a:ActionNotSupported</faultcode>
+      <faultstring xml:lang='en-US'>some error</faultstring>
+    </s:Fault>
+  </s:Body>
+</s:Envelope>";
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void TryCreateExceptionMessageNullDefault ()
+               {
+                       var msg = Message.CreateMessage (XmlReader.Create (new StringReader (xml1)), 0x1000, MessageVersion.Soap11WSAddressing10);
+                       var mf = MessageFault.CreateFault (msg, 1000);
+                       Exception ex;
+                       s11.TryCreateException (null, mf, out ex);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void TryCreateExceptionFaultNullDefault ()
+               {
+                       var msg = Message.CreateMessage (XmlReader.Create (new StringReader (xml1)), 0x1000, MessageVersion.Soap11WSAddressing10);
+                       Exception ex;
+                       s11.TryCreateException (msg, null, out ex);
+               }
+
+               [Test]
+               public void TryCreateExceptionDefault ()
+               {
+                       var msg = Message.CreateMessage (XmlReader.Create (new StringReader (xml1)), 0x1000, MessageVersion.Soap11WSAddressing10);
+                       var mf = MessageFault.CreateFault (msg, 1000);
+                       msg = Message.CreateMessage (XmlReader.Create (new StringReader (xml1)), 0x1000, MessageVersion.Soap11WSAddressing10);
+                       Exception ex;
+                       Assert.IsTrue (s11.TryCreateException (msg, mf, out ex), "#1");
+                       // foobar -> false
+                       Assert.IsFalse (s11.TryCreateException (msg, MessageFault.CreateFault (new FaultCode ("foobar"), new FaultReason ("foobar reason")), out ex), "#2");
+                       // SOAP 1.1 ActionNotSupported -> true
+                       Assert.IsTrue (s11.TryCreateException (msg, MessageFault.CreateFault (new FaultCode ("ActionNotSupported", Constants.WsaNamespace), new FaultReason ("foobar reason")), out ex), "#3");
+                       Assert.IsTrue (ex is ActionNotSupportedException, "#3-2");
+                       Assert.IsTrue (ex.Message.IndexOf ("foobar") >= 0, "#3-3");
+
+                       // SOAP 1.1 Sender/ActionNotSupported -> false
+                       mf = MessageFault.CreateFault (new FaultCode ("Sender", new FaultCode ("ActionNotSupported", Constants.WsaNamespace)), new FaultReason ("foobar reason"));
+                       Assert.IsFalse (s11.TryCreateException (msg, mf, out ex), "#4");
+                       // SOAP 1.2 ActionNotSupported -> false
+                       mf = MessageFault.CreateFault (new FaultCode ("ActionNotSupported", Constants.WsaNamespace), new FaultReason ("foobar reason"));
+                       Assert.IsFalse (s12.TryCreateException (msg, mf, out ex), "#5");
+                       // SOAP 1.2 Sender/ActionNotSupported -> true
+                       mf = MessageFault.CreateFault (new FaultCode ("Sender", new FaultCode ("ActionNotSupported", Constants.WsaNamespace)), new FaultReason ("foobar reason"));
+                       Assert.IsTrue (s12.TryCreateException (msg, mf, out ex), "#6");
+                       Assert.IsTrue (ex is ActionNotSupportedException, "#6-2");
+                       Assert.IsTrue (ex.Message.IndexOf ("foobar") >= 0, "#6-3");
+               }
+
+               [Test]
+               public void TryCreateException2Default ()
+               {
+                       // test buffered copy (which used to fail)
+                       var msg = Message.CreateMessage (XmlReader.Create (new StringReader (xml1)), 0x1000, MessageVersion.Soap11WSAddressing10);
+                       var mb = msg.CreateBufferedCopy (1000);
+                       var mf = MessageFault.CreateFault (mb.CreateMessage (), 1000);
+                       Exception ex;
+                       Assert.IsTrue (s11.TryCreateException (mb.CreateMessage (), mf, out ex), "#7");
                }
        }
 }
index 0e827a934bb05206bc866f9c110d01617f1b107a..caf0d7f827e50ca0e980169689a04ae70708840c 100644 (file)
@@ -62,5 +62,23 @@ namespace MonoTests.System.ServiceModel.Channels
                        b.Security.Mode = BasicHttpSecurityMode.Transport;
                        b.BuildChannelListener<IReplyChannel> (new Uri ("http://localhost:8080"));
                }
+
+               [Test]
+               public void GetProperty ()
+               {
+                       var b = new HttpsTransportBindingElement ();
+                       var s = b.GetProperty<ISecurityCapabilities> (new BindingContext (new CustomBinding (), new BindingParameterCollection ()));
+                       Assert.IsNotNull (s, "#1");
+                       Assert.AreEqual (ProtectionLevel.EncryptAndSign, s.SupportedRequestProtectionLevel, "#2");
+                       Assert.AreEqual (ProtectionLevel.EncryptAndSign, s.SupportedResponseProtectionLevel, "#3");
+                       Assert.IsFalse (s.SupportsClientAuthentication, "#4");
+                       Assert.IsFalse (s.SupportsClientWindowsIdentity, "#5");
+                       Assert.IsTrue (s.SupportsServerAuthentication, "#6");
+
+                       b.RequireClientCertificate = true;
+                       s = b.GetProperty<ISecurityCapabilities> (new BindingContext (new CustomBinding (), new BindingParameterCollection ()));
+                       Assert.IsTrue (s.SupportsClientAuthentication, "#7");
+                       Assert.IsTrue (s.SupportsClientWindowsIdentity, "#8");
+               }
        }
 }
index 7bf87c60cfcd0a53e6bee2f71be4dd1d16834ef5..70868e4be2c1fbd9015dcfd504dfda57ae115a6d 100644 (file)
@@ -66,7 +66,6 @@ namespace MonoTests.System.ServiceModel.Channels
                }
 
                [Test]
-               [Category ("NotWorking")]
                public void TestWriteMessage ()
                {
                        Message m = Message.CreateMessage (MessageVersion.Default, "action", 1);
@@ -175,6 +174,18 @@ namespace MonoTests.System.ServiceModel.Channels
                                msg.WriteMessage (w);
                        }
                }
+
+               [Test]
+               public void IsFaultCopied ()
+               {
+                       var ret = Message.CreateMessage (MessageVersion.Soap12,
+                               MessageFault.CreateFault (new FaultCode ("mycode"), "private affair"),
+                               "http://tempuri.org/IFoo/Test");
+                       Assert.IsTrue (ret.IsFault, "#1");
+                       var mb = ret.CreateBufferedCopy (0x1000);
+                       ret = mb.CreateMessage ();
+                       Assert.IsTrue (ret.IsFault, "#2");
+               }
        }
 
        internal class MyBodyWriter : BodyWriter
index 791dee7f7d95c061d804a45fa0ab8d5911dfc954..eae3d7ca74b439878c6a87619bd791926cb0cfcf 100644 (file)
@@ -58,5 +58,27 @@ namespace MonoTests.System.ServiceModel.Channels
                        var msg = Message.CreateMessage (XmlReader.Create (new StreamReader ("Test/System.ServiceModel.Channels/soap-fault-incomplete4.xml")), 0x10000, MessageVersion.Default);
                        MessageFault.CreateFault (msg, 0x10000);
                }
+
+               [Test]
+               public void CreateFaultFromMessage ()
+               {
+                       var xml = @"
+<s:Envelope xmlns:a='http://www.w3.org/2005/08/addressing' xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'>
+  <s:Header>
+    <a:Action s:mustUnderstand='1'>http://www.w3.org/2005/08/addressing/fault</a:Action>
+  </s:Header>
+  <s:Body>
+    <s:Fault>
+      <faultcode>a:ActionNotSupported</faultcode>
+      <faultstring xml:lang='en-US'>some error</faultstring>
+    </s:Fault>
+  </s:Body>
+</s:Envelope>";
+                       var msg = Message.CreateMessage (XmlReader.Create (new StringReader (xml)), 0x1000, MessageVersion.Soap11WSAddressing10);
+                       MessageFault.CreateFault (msg, 1000);
+                       msg = Message.CreateMessage (XmlReader.Create (new StringReader (xml)), 0x1000, MessageVersion.Soap11WSAddressing10);
+                       var mb = msg.CreateBufferedCopy (1000);
+                       MessageFault.CreateFault (mb.CreateMessage (), 1000);
+               }
        }
 }
index 7b3e8bfcc56c7cc4a5568d400051426e00e28d43..79d3759c9cfe62741c823159b916f43cb7bbf3d1 100644 (file)
@@ -91,13 +91,22 @@ namespace MonoTests.System.ServiceModel.Channels
                }
 
                [Test]
-               [Category ("NotWorking")]
                public void TestWriteHeaderContent ()
                {
-                       int value = 1;
+                       TestWriteHeaderContent (1, "<dummy-root>1</dummy-root>");
+               }
 
+               [Test]
+               [Category ("NotWorking")] // too cosmetic, it just does not output xmlns:i. (insignificant)
+               public void TestWriteHeaderContent2 ()
+               {
+                       TestWriteHeaderContent (new UniqueId (new byte [] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5}), "<dummy-root xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" />");
+               }
+
+               void TestWriteHeaderContent (object value, string expected)
+               {
                        MessageHeader h = MessageHeader.CreateHeader ("foo", "bar", value);
-                       XmlObjectSerializer f = new DataContractSerializer (typeof (int));
+                       XmlObjectSerializer f = new DataContractSerializer (value.GetType ());
 
                        StringBuilder sb = new StringBuilder ();
                        XmlWriterSettings settings = new XmlWriterSettings ();
@@ -109,13 +118,18 @@ namespace MonoTests.System.ServiceModel.Channels
                        h.WriteHeaderContents (w, MessageVersion.Soap12WSAddressing10);
                        w.WriteEndElement ();
                        w.Flush ();
-                       string actual = sb.ToString ();
+                       string actual2 = sb.ToString ();
 
-                       f.WriteObject (w, value);
-                       string expected = sb.ToString ();
+                       sb.Length = 0;
+                       w.WriteStartElement ("dummy-root");
+                       f.WriteObjectContent (w, value);
+                       w.WriteEndElement ();
+                       w.Flush ();
+                       string actual1 = sb.ToString ();
 
                        // the output of WriteHeaderContent is the same as XmlSerializer.Serialize
-                       Assert.AreEqual (expected, actual);
+                       Assert.AreEqual (expected, actual1, "#1");
+                       Assert.AreEqual (expected, actual2, "#2");
                }
 
                [Test]
index a54294c2674881acd397c1a4a715e8bff6987f60..992c7209fe9f4d98277999f80e23b5353f62e520 100644 (file)
@@ -320,6 +320,39 @@ namespace MonoTests.System.ServiceModel.Channels
                        Assert.IsTrue (m.IsFault, "#2");
                }
 
+               [Test]
+               public void IsFault2 ()
+               {
+                       string xml = @"
+<s:Envelope xmlns:a='http://www.w3.org/2005/08/addressing' xmlns:s='http://www.w3.org/2003/05/soap-envelope'>
+  <s:Header>
+    <a:Action s:mustUnderstand='1'>http://www.w3.org/2005/08/addressing/fault</a:Action>
+  </s:Header>
+  <s:Body>
+    <s:Fault xmlns:s='http://www.w3.org/2003/05/soap-envelope'>
+      <s:Code>
+        <s:Value>s:Sender</s:Value>
+        <s:Subcode>
+          <s:Value>a:ActionNotSupported</s:Value>
+        </s:Subcode>
+      </s:Code>
+      <s:Reason>
+        <s:Text xml:lang='ja-JP'>message</s:Text>
+      </s:Reason>
+    </s:Fault>
+  </s:Body>
+</s:Envelope>";
+                       var msg = Message.CreateMessage (MessageVersion.Soap11, "urn:foo", XmlReader.Create (new StringReader (xml)));
+                       Assert.AreEqual ("urn:foo", msg.Headers.Action, "#1");
+                       msg.ToString ();
+                       Assert.IsFalse (msg.IsFault, "#2"); // version mismatch
+
+                       msg = Message.CreateMessage (MessageVersion.Soap12, "urn:foo", XmlReader.Create (new StringReader (xml)));
+                       Assert.AreEqual ("urn:foo", msg.Headers.Action, "#3");
+                       msg.ToString ();
+                       Assert.IsFalse (msg.IsFault, "#4"); // version match, but it doesn't set as true. It is set true only when it is constructed with fault objects.
+               }
+
                [Test]
                public void State ()
                {
index 9c528514572ffc29947bf1a7992729176b6191ff..63cef539a4373a63469646bfed1993b8bc5ea176 100644 (file)
@@ -146,5 +146,22 @@ namespace MonoTests.System.ServiceModel.Channels
                        Assert.IsFalse (be.CanBuildChannelListener<IDuplexChannel> (ctx), "#11");
                        Assert.IsFalse (be.CanBuildChannelListener<IDuplexSessionChannel> (ctx), "#12");
                }
+
+               [Test]
+               public void GetPrpertyBindingDeliveryCapabilities ()
+               {
+                       var be = new TcpTransportBindingElement ();
+                       var dc = be.GetProperty<IBindingDeliveryCapabilities> (new BindingContext (new CustomBinding (), new BindingParameterCollection ()));
+                       Assert.IsTrue (dc.AssuresOrderedDelivery, "#1");
+                       Assert.IsFalse (dc.QueuedDelivery, "#2");
+               }
+
+               [Test]
+               public void GetPropertySecurityCapabilities ()
+               {
+                       var b = new TcpTransportBindingElement ();
+                       var s = b.GetProperty<ISecurityCapabilities> (new BindingContext (new CustomBinding (), new BindingParameterCollection ()));
+                       Assert.IsNull (s, "#1");
+               }
        }
 }
index a3cd0a70029c31b830e2c7b4bff44e51b945f8dc..0550b6debf1e6da5cac3cfd9272745b0a808a04f 100755 (executable)
@@ -1,3 +1,19 @@
+2010-04-05  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * WsdlExporterTest.cs : fixed and enabled some working tests.
+
+2010-04-02  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * FaultDescriptionTest.cs : add new test.
+
+2010-03-29  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * MetadataResolverTest.cs : enable working tests.
+
+2010-03-17  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * MetadataExchangeBindingsTest.cs : new test.
+
 2010-02-10  Atsushi Enomoto  <atsushi@ximian.com>
 
        * WsdlImporterTest.cs : ignore whatever make dist broke.
diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/FaultDescriptionTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/FaultDescriptionTest.cs
new file mode 100644 (file)
index 0000000..f176154
--- /dev/null
@@ -0,0 +1,74 @@
+//
+// FaultDescriptionTest.cs
+//
+// Author:
+//     Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2010 Novell, Inc.  http://www.novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.ObjectModel;
+using System.Net.Security;
+using System.Reflection;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using NUnit.Framework;
+
+namespace MonoTests.System.ServiceModel.Description
+{
+       [TestFixture]
+       public class FaultDescriptionTest
+       {
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void NullAction ()
+               {
+                       new FaultDescription (null);
+               }
+
+               [Test]
+               public void SimpleUse ()
+               {
+                       var cd = ContractDescription.GetContract (typeof (ITestContract));
+                       var od = cd.Operations [0];
+                       Assert.AreEqual (1, od.Faults.Count, "#1");
+                       var fd = od.Faults [0];
+                       // automatically filled names
+                       Assert.AreEqual ("http://tempuri.org/ITestContract/EchoMyDetailFault", fd.Action, "#2");
+                       Assert.AreEqual ("MyDetailFault", fd.Name, "#3");
+                       Assert.AreEqual ("http://tempuri.org/", fd.Namespace, "#4");
+               }
+
+               class MyDetail
+               {
+               }
+
+               [ServiceContract]
+               interface ITestContract
+               {
+                       [OperationContract]
+                       [FaultContract (typeof (MyDetail))]
+                       string Echo (string input);
+               }
+       }
+}
diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/MetadataExchangeBindingsTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Description/MetadataExchangeBindingsTest.cs
new file mode 100644 (file)
index 0000000..3b533c6
--- /dev/null
@@ -0,0 +1,59 @@
+//
+// MetadataResolverTest.cs
+//
+// Author:
+//     Atsushi Enomoto  <atsushi@ximian.com>
+//
+// Copyright (C) 2010 Novell, Inc.  http://www.novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Runtime.Serialization;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+
+using NUnit.Framework;
+
+namespace MonoTests.System.ServiceModel.Description
+{
+       [TestFixture]
+       public class MetadataExchangeBindingsTest
+       {
+               [Test]
+               public void CreateMexHttpBinding ()
+               {
+                       var b = MetadataExchangeBindings.CreateMexHttpBinding () as WSHttpBinding;
+                       Assert.IsNotNull (b, "#1");
+                       Assert.AreEqual (SecurityMode.None, b.Security.Mode, "#2");
+                       Assert.IsFalse (b.TransactionFlow, "#3");
+                       Assert.IsFalse (b.ReliableSession.Enabled, "#4");
+                       Assert.IsFalse (b.CreateBindingElements ().Any (be => be is SecurityBindingElement), "#b1");
+                       Assert.IsTrue (b.CreateBindingElements ().Any (be => be is TransactionFlowBindingElement), "#b2");
+                       Assert.IsFalse (b.CreateBindingElements ().Any (be => be is ReliableSessionBindingElement), "#b3");
+                       Assert.IsTrue (new TransactionFlowBindingElement ().TransactionProtocol == TransactionProtocol.Default, "#x1");
+               }
+       }
+}
index 30c1ffdb20002ae2b40e4f218cffffde80cdec68..75b7e27a222cd8ea3f9e19c3e5536baa1a6e17aa 100644 (file)
@@ -153,10 +153,8 @@ namespace MonoTests.System.ServiceModel.Description
 
                [Test]
                [ExpectedException (typeof (InvalidOperationException))]
-               [Category ("NotWorking")]
                public void ErrResolve2 ()
                {
-               /* Not working as HttpGet is not implemented yet */
                        //Mex cannot be fetched with HttpGet from the given url
                        MetadataResolver.Resolve (
                                typeof (IEchoService),
@@ -196,10 +194,8 @@ namespace MonoTests.System.ServiceModel.Description
 
                [Test]
                [ExpectedException (typeof (InvalidOperationException))]
-               [Category ("NotWorking")]
                public void ErrResolve5 ()
                {
-               /* Not working as HttpGet is not implemented yet */
                        ContractDescription contract = ContractDescription.GetContract (typeof (IEchoService));
                        List<ContractDescription> contracts = new List<ContractDescription> ();
                        contracts.Add (contract);
index 21551925f4ed9b4f897112d550bdb2a1ba7bff22..fafcd01f62bb16e0276220185b38407334c0ae7b 100644 (file)
@@ -224,7 +224,6 @@ namespace MonoTests.System.ServiceModel.Description
                }
 
                [Test]
-               [Category ("NotWorking")]
                public void ExportMessageContract ()
                {
                        WsdlExporter we = new WsdlExporter ();
@@ -270,18 +269,11 @@ namespace MonoTests.System.ServiceModel.Description
                }
 
                [Test]
-               //Currently throws InvalidDataContractException on mono, but once the code is
-               //moved to a IWsdlExportExtension, InvalidOperationException will get throw
-               [Category ("NotWorking")]
-               [Ignore ("fails under .NET; I never bothered to fix the test")]
                public void ExportBar1Contract ()
                {
                        WsdlExporter we = new WsdlExporter ();
                        ContractDescription cd = ContractDescription.GetContract (typeof (Bar1));
-
-                       //Cannot export as operation Foo has >1 param so Message param gets treated
-                       //as any other param, but it is not serializable!
-                       ExportContractExpectException (we, cd, typeof (InvalidOperationException), "ExportBar1Contract");
+                       we.ExportContract (cd);
                }
 
                //Helper methods
index 31051bdbee868a15df6e311e5ab47a03b42d1695..d24f785e2f7286ff663657be1760e0a97fc6bb33 100644 (file)
@@ -1,3 +1,20 @@
+2010-04-05  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * EndpointAddressMessageFilterTest.cs :
+         Add null arg case. Enable working test.
+
+2010-04-05  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * DispatchRuntimeTest.cs : enabled working tests again.
+
+2010-04-02  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * DispatchOperationTest.cs : added not-working FaultContractInfo test.
+
+2010-03-18  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XPathMessageContextTest.cs : new.
+
 2010-01-06  Atsushi Enomoto  <atsushi@ximian.com>
 
        * ChannelDispatcherTest.cs : format message correctly.
index 5b3eadec131a24f75f95478c4030aaae2406613d..37b1210c88c6d4ac931b4f9cffc456ea64dff8f4 100644 (file)
@@ -67,8 +67,7 @@ namespace MonoTests.System.ServiceModel.Dispatcher
                        Assert.IsTrue (o.DeserializeRequest, "#1");
                        Assert.IsTrue (o.SerializeReply, "#2");
                        Assert.IsNull (o.Formatter, "#3");
-                       // FIXME: FaultDetailTypes -> FaultContractInfos
-                       //Assert.AreEqual (0, o.FaultDetailTypes.Count, "#4");
+                       Assert.AreEqual (0, o.FaultContractInfos.Count, "#4");
                        Assert.IsNull (o.Invoker, "#5");
                        Assert.IsFalse (o.IsOneWay, "#6");
                        Assert.IsFalse (o.IsTerminating, "#7");
@@ -84,5 +83,59 @@ namespace MonoTests.System.ServiceModel.Dispatcher
                        return new EndpointDispatcher (
                                new EndpointAddress ("http://localhost:8080"), "IFoo", "urn:foo").DispatchRuntime;
                }
+
+               [Test]
+               public void FaultContractInfos ()
+               {
+                       var host = new ServiceHost (typeof (TestFaultContract));
+                       host.Description.Behaviors.Find<ServiceDebugBehavior> ().IncludeExceptionDetailInFaults = true;
+                       host.AddServiceEndpoint (typeof (ITestFaultContract), new BasicHttpBinding (), new Uri ("http://localhost:37564"));
+                       host.Open ();
+                       try {
+                               var cf = new ChannelFactory<ITestFaultContract> (new BasicHttpBinding (), new EndpointAddress ("http://localhost:37564"));
+                               var cli = cf.CreateChannel ();
+                               cli.Run ("test");
+                       } catch (FaultException<PrivateAffairError> ex) {
+                               var p  = ex.Detail;
+                               Assert.AreEqual (5, p.ErrorCode, "#1");
+                               Assert.AreEqual ("foobarerror", p.Text, "#2");
+                       } finally {
+                               host.Close ();
+                       }
+               }
+
+               [ServiceContract]
+               public interface ITestFaultContract
+               {
+                       [OperationContract]
+                       [FaultContract (typeof (PrivateAffairError), Action = "urn:myfault")]
+                       string Run (string input);
+               }
+
+               class TestFaultContract : ITestFaultContract
+               {
+                       public string Run (string input)
+                       {
+                               Assert.AreEqual (1, ContractDescription.GetContract (typeof (TestFaultContract)).Operations [0].Faults.Count, "s#0");
+
+                               var dr = OperationContext.Current.EndpointDispatcher.DispatchRuntime;
+                               Assert.AreEqual (1, dr.Operations.Count);
+                               var dop = dr.Operations [0];
+                               Assert.AreEqual ("Run", dop.Name, "s#1");
+                               Assert.AreEqual (1, dop.FaultContractInfos.Count, "s#2");
+                               var fci = dop.FaultContractInfos [0];
+                               Assert.AreEqual (typeof (PrivateAffairError), fci.Detail, "s#3");
+                               throw new FaultException<PrivateAffairError> (new PrivateAffairError () { ErrorCode = 5, Text = "foobarerror" });
+                       }
+               }
+
+               [DataContract]
+               class PrivateAffairError
+               {
+                       [DataMember]
+                       public int ErrorCode { get; set; }
+                       [DataMember]
+                       public string Text { get; set; }
+               }
        }
 }
\ No newline at end of file
index e6eeaacf6627dcf8eedec07f3ba4755d7b01a0bd..013d55e9a6ec5f345376f774d00570ea9ab65f89 100644 (file)
@@ -92,8 +92,7 @@ namespace MonoTests.System.ServiceModel.Dispatcher
                }
 
                [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
-               public void TestInstanceBehavior1()
+               public void TestInstanceBehavior1 ()
                {
                        
                        Result res = new Result ();
@@ -108,7 +107,6 @@ namespace MonoTests.System.ServiceModel.Dispatcher
                }
 
                [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
                public void TestInstanceBehavior2 ()
                {
                        Result res = new Result ();
@@ -123,7 +121,6 @@ namespace MonoTests.System.ServiceModel.Dispatcher
                }
 
                [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
                public void TestInstanceBehavior3 ()
                {
                        Result res = new Result ();
@@ -140,7 +137,6 @@ namespace MonoTests.System.ServiceModel.Dispatcher
                }
 
                [Test]
-               [Category ("NotWorking")]
                public void TestInstanceBehavior4 ()
                {
                        Result res = new Result ();
index b3859f2170c6c5345d1aac63e84712e3e235790a..5a5d4044ba2853397c81451bdacf7026031151d2 100644 (file)
@@ -54,7 +54,13 @@ namespace MonoTests.System.ServiceModel.Dispatcher
                }
 
                [Test]
-               [Category ("NotWorking")]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void CtorNoAddress ()
+               {
+                       new EndpointAddressMessageFilter (null, false);
+               }
+
+               [Test]
                public void Match ()
                {
                        EndpointAddressMessageFilter f =
diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Dispatcher/XPathMessageContextTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Dispatcher/XPathMessageContextTest.cs
new file mode 100644 (file)
index 0000000..6abe0e6
--- /dev/null
@@ -0,0 +1,58 @@
+//
+// XPathMessageContextTest.cs
+//
+// Author:
+//     Atsushi Enomoto  <atsushi@ximian.com>
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections.Generic;
+using System.Runtime.Serialization;
+using System.ServiceModel;
+using System.ServiceModel.Dispatcher;
+using System.Xml;
+using NUnit.Framework;
+
+namespace MonoTests.System.ServiceModel.Dispatcher
+{
+       [TestFixture]
+       public class XPathMessageContextTest
+       {
+               XPathMessageContext ctx = new XPathMessageContext ();
+
+               [Test]
+               public void PredefinedNamespaces ()
+               {
+                       Assert.AreEqual (Constants.Soap11, ctx.LookupNamespace ("s11"), "#1");
+                       Assert.AreEqual (Constants.Soap12, ctx.LookupNamespace ("s12"), "#2");
+                       // ... only them?
+
+                       foreach (char c in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
+                               Assert.IsNull (ctx.LookupNamespace (c + ""), "char:" + c);
+
+                       Assert.IsNull (ctx.LookupNamespace ("wsa"), "#3");
+                       Assert.IsNull (ctx.LookupNamespace ("wsu"), "#4");
+               }
+       }
+}
index cd47b63758d2f2910e8fb2d860eabb2e1a4248ca..306f17810d8f4b98cfa23be5f984f7f2529f79b6 100644 (file)
@@ -1,3 +1,7 @@
+2010-04-05  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * CustomPeerResolverServiceTest.cs : enabled all disabled tests.
+
 2009-12-02  Atsushi Enomoto  <atsushi@ximian.com>
 
        * CustomPeerResolverServiceTest.cs :
index fd92f7854e195a374f25001f5edca78278124200..a6bc6c5e6fc158c4b49b640646cbccddbb2ac561 100644 (file)
@@ -30,7 +30,6 @@ namespace MonoTests.System.ServiceModel.PeerResolvers
                }
 
                [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
                public void CloseTest ()
                {
                        cprs.Open ();
@@ -38,7 +37,6 @@ namespace MonoTests.System.ServiceModel.PeerResolvers
                }
 
                [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
                [ExpectedException (typeof (InvalidOperationException))]
                public void CloseTest1 ()
                {
@@ -46,7 +44,6 @@ namespace MonoTests.System.ServiceModel.PeerResolvers
                }
 
                [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
                [ExpectedException (typeof (InvalidOperationException))]
                public void GetServiceSettingsTest ()
                {
@@ -56,14 +53,6 @@ namespace MonoTests.System.ServiceModel.PeerResolvers
                }
 
                [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
-               public void OpenTest ()
-               {
-                       cprs.Open ();
-               }
-
-               [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
                [ExpectedException (typeof (ArgumentException))]
                public void OpenTest1 ()
                {
@@ -72,7 +61,6 @@ namespace MonoTests.System.ServiceModel.PeerResolvers
                }
 
                [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
                [ExpectedException (typeof (ArgumentException))]
                public void OpenTest2 ()
                {
@@ -81,7 +69,6 @@ namespace MonoTests.System.ServiceModel.PeerResolvers
                }
 
                [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
                [ExpectedException (typeof (ArgumentException))]
                public void OpenTest3 ()
                {
@@ -91,16 +78,18 @@ namespace MonoTests.System.ServiceModel.PeerResolvers
                }
 
                [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
                [ExpectedException (typeof (InvalidOperationException))]
                public void OpenTest4 ()
                {
                        cprs.Open ();
-                       cprs.Open ();
+                       try {
+                               cprs.Open ();
+                       } finally {
+                               cprs.Close ();
+                       }
                }
 
                [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
                [ExpectedException (typeof (ArgumentException))]
                public void RefreshTest ()
                {
@@ -108,7 +97,6 @@ namespace MonoTests.System.ServiceModel.PeerResolvers
                }
 
                [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
                [ExpectedException (typeof (InvalidOperationException))]
                public void RefreshTest1 ()
                {
@@ -123,7 +111,6 @@ namespace MonoTests.System.ServiceModel.PeerResolvers
                //}
 
                [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
                [ExpectedException (typeof( ArgumentException))]
                public void RegisterTest ()
                {
@@ -131,7 +118,6 @@ namespace MonoTests.System.ServiceModel.PeerResolvers
                }
 
                [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
                [ExpectedException (typeof (InvalidOperationException))]
                public void RegisterTest1 ()
                {
@@ -146,7 +132,6 @@ namespace MonoTests.System.ServiceModel.PeerResolvers
                //}
 
                [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
                [ExpectedException (typeof (ArgumentException))]
                public void ResolveTest ()
                {
@@ -154,7 +139,6 @@ namespace MonoTests.System.ServiceModel.PeerResolvers
                }
 
                [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
                [ExpectedException (typeof (InvalidOperationException))]
                public void ResolveTest1 ()
                {
@@ -169,7 +153,6 @@ namespace MonoTests.System.ServiceModel.PeerResolvers
                //}
 
                [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
                [ExpectedException (typeof (ArgumentException))]
                public void UnregisterTest ()
                {
@@ -177,7 +160,6 @@ namespace MonoTests.System.ServiceModel.PeerResolvers
                }
 
                [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
                [ExpectedException (typeof (InvalidOperationException))]
                public void UnregisterTest1 ()
                {
@@ -192,7 +174,6 @@ namespace MonoTests.System.ServiceModel.PeerResolvers
                //}
 
                [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
                [ExpectedException (typeof (ArgumentException))]
                public void UpdateTest ()
                {
@@ -200,7 +181,6 @@ namespace MonoTests.System.ServiceModel.PeerResolvers
                }
 
                [Test]
-               [Category ("NotWorking")] // It somehow stopped working properly recently in Nov. 2009, not sure where the source of the problem lies.
                [ExpectedException (typeof (InvalidOperationException))]
                public void UpdateTest1 ()
                {
index cb0ba913dc784e3460bbb2d6eb189bf7d858785e..fabab751925e652999a7c328175f6a02e4a2e234 100755 (executable)
@@ -1,3 +1,7 @@
+2010-03-24  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * TransportSecurityBindingElementTest.cs : new test.
+
 2009-12-14  Atsushi Enomoto  <atsushi@ximian.com>
 
        * WSSecurityTokenSerializerTest.cs : disable non-working test that
diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security/TransportSecurityBindingElementTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel.Security/TransportSecurityBindingElementTest.cs
new file mode 100644 (file)
index 0000000..c9d7e2a
--- /dev/null
@@ -0,0 +1,51 @@
+//
+// TransportSecurityBindingElementTest.cs
+//
+// Author:
+//     Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2009 Novell, Inc.  http://www.novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.ObjectModel;
+using System.Net;
+using System.Net.Security;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Security;
+using System.ServiceModel.Security.Tokens;
+using System.Security.Cryptography.Xml;
+using NUnit.Framework;
+
+namespace MonoTests.System.ServiceModel.Security
+{
+       [TestFixture]
+       public class TransportSecurityBindingElementTest
+       {
+               [Test]
+               public void DefaultValues ()
+               {
+                       var be = new TransportSecurityBindingElement ();
+               }
+
+       }
+}
index 8ccd21c004da11d11f2a7172f9622ff9ca123887..7b1fa57208c22d2996e730eaa0e553bb35572d8d 100644 (file)
@@ -36,7 +36,6 @@ using NUnit.Framework;
 using System.ServiceModel.Configuration;
 using System.Configuration;
 using System.Text;
-using System.Net;
 
 namespace MonoTests.System.ServiceModel
 {
index 83dc19735136a8ce4aa372499c5112ef141e4129..4cc3bec77c3cc05384eca561e085008f2cb67a88 100755 (executable)
@@ -1,3 +1,26 @@
+2010-04-01  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * FaultContractAttributeTest.cs : new test.
+
+2010-04-01  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ServiceHostBaseTest.cs : enable RunDestinationUnreachableTest()
+         and add another case for different addressing version.
+
+2010-03-29  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * EndpointIdentityTest.cs, EndpointAddress10Test.cs :
+         enable working tests.
+
+2010-03-25  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ServiceHostBaseTest.cs : add not-working ActionNotFound test by
+         Matt Dargavel.
+
+2010-03-18  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * Constants.cs : copied from the lib itself.
+
 2010-02-05  Atsushi Enomoto  <atsushi@ximian.com>
 
        * ServiceHostBaseTest.cs : on unixy filesystems "/foobar"
diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel/Constants.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel/Constants.cs
new file mode 100644 (file)
index 0000000..8363da1
--- /dev/null
@@ -0,0 +1,263 @@
+//
+// Constants.cs
+//
+// Author:
+//     Atsushi Enomoto <atsushi@ximian.com>
+//
+// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System.Xml;
+
+namespace System.ServiceModel
+{
+       internal class Constants
+       {
+               public const string Soap11 = "http://schemas.xmlsoap.org/soap/envelope/";
+               public const string Soap12 = "http://www.w3.org/2003/05/soap-envelope";
+
+               public const string WSBasicSecurityProfileCore1 = "http://ws-i.org/profiles/basic-security/core/1.0";
+
+               public const string WsaAnonymousUri = "http://www.w3.org/2005/08/addressing/anonymous";
+               public const string WsaIdentityUri = "http://schemas.xmlsoap.org/ws/2006/02/addressingidentity";
+
+               public const string MSSerialization = "http://schemas.microsoft.com/2003/10/Serialization/";
+
+               public const string WssKeyIdentifierX509Thumbptint = "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1";
+
+               public const string WssBase64BinaryEncodingType = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary";
+
+               public const string WssKeyIdentifierEncryptedKey = "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKeySHA1";
+
+               public const string XmlDsig = "http://www.w3.org/2000/09/xmldsig#";
+
+               public const string WSSSamlToken = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1";
+               public const string WSSX509Token = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3";
+               public const string WssKeyIdentifierSamlAssertion = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID";
+               public const string WSSUserNameToken = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#UsernameToken";
+               public const string WsscContextToken = "http://schemas.xmlsoap.org/ws/2005/02/sc/sct";
+               public const string WSSKerberosToken = "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#GSS_Kerberosv5_AP_REQ";
+               public const string WSSEncryptedKeyToken = "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey";
+
+               public const string WstNamespace = "http://schemas.xmlsoap.org/ws/2005/02/trust";
+               public const string WssNamespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
+               public const string Wss11Namespace = "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd";
+               public const string WspNamespace = "http://schemas.xmlsoap.org/ws/2004/09/policy";
+               public const string WsaNamespace = "http://www.w3.org/2005/08/addressing";
+               public const string WsuNamespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
+               public const string WsscNamespace = "http://schemas.xmlsoap.org/ws/2005/02/sc";
+               public const string WsidNamespace = "http://schemas.xmlsoap.org/ws/2005/05/identity";
+
+               public const string WstIssueAction = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue";
+               public const string WstRenewAction = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Renew";
+               public const string WstCancelAction = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Cancel";
+               public const string WstValidateAction = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Validate";
+               public const string WstIssueReplyAction = "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/Issue";
+               public const string WstRenewReplyAction = "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/Renew";
+               public const string WstCancelReplyAction = "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/Cancel";
+               public const string WstValidateReplyAction = "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/Validate";
+
+               public const string WsscDefaultLabel = "WS-SecureConversationWS-SecureConversation";
+
+               // .NET BUG: it requires extra white space !
+               public const string WstBinaryExchangeValueTls = " http://schemas.xmlsoap.org/ws/2005/02/trust/tlsnego";
+               public const string WstBinaryExchangeValueGss = "http://schemas.xmlsoap.org/ws/2005/02/trust/spnego";
+
+               public const string MSTlsnegoTokenContent = "http://schemas.microsoft.com/ws/2006/05/security";
+
+               public const string WstTlsnegoProofTokenType = "http://schemas.xmlsoap.org/2005/02/trust/tlsnego#TLS_Wrap";
+               public const string WstSpnegoProofTokenType = "http://schemas.xmlsoap.org/2005/02/trust/spnego#TLS_Wrap";
+
+               public const string WstIssueRequest = "http://schemas.xmlsoap.org/ws/2005/02/trust/Issue";
+               public const string WstRenewRequest = "http://schemas.xmlsoap.org/ws/2005/02/trust/Renew";
+               public const string WstCancelRequest = "http://schemas.xmlsoap.org/ws/2005/02/trust/Cancel";
+               public const string WstValidateRequest = "http://schemas.xmlsoap.org/ws/2005/02/trust/Validate";
+
+               public const string WstSymmetricKeyTypeUri = "http://schemas.xmlsoap.org/ws/2005/02/trust/SymmetricKey";
+               public const string WstAsymmetricKeyTypeUri = "http://schemas.xmlsoap.org/ws/2005/02/trust/AsymmetricKey";
+
+               public const string LifetimeFormat = "yyyy-MM-dd'T'HH:mm:ss.fffZ";
+
+               // Those OIDs except for Kerberos5 are described here:
+               // http://www.alvestrand.no/objectid/
+               // (searching web for those OIDs would give you pointers.)
+               public const string OidSpnego = "1.3.6.1.5.5.2";
+               public const string OidNtlmSsp = "1.3.6.1.4.1.311.2.2.10";
+               public const string OidKerberos5 = "1.2.840.48018.1.2.2";
+               public const string OidMIT = "1.2.840.113554.1.2.2";
+
+               // Peer resolvers
+               public const string NetPeer = "http://schemas.microsoft.com/net/2006/05/peer";
+
+               // See [MC-NBFS] in Microsoft OSP. The strings are copied from the PDF, so the actual values might be wrong.
+               static readonly string [] dict_strings = {
+                       "mustUnderstand", "Envelope",
+                       "http://www.w3.org/2003/05/soap-envelope",
+                       "http://www.w3.org/2005/08/addressing", "Header", "Action", "To", "Body", "Algorithm", "RelatesTo",
+                       "http://www.w3.org/2005/08/addressing/anonymous", "URI", "Reference", "MessageID", "Id", "Identifier",
+                       "http://schemas.xmlsoap.org/ws/2005/02/rm", "Transforms", "Transform", "DigestMethod", "DigestValue", "Address", "ReplyTo", "SequenceAcknowledgement", "AcknowledgementRange", "Upper", "Lower", "BufferRemaining",
+                       "http://schemas.microsoft.com/ws/2006/05/rm",
+                       "http://schemas.xmlsoap.org/ws/2005/02/rm/SequenceAcknowledgement", "SecurityTokenReference", "Sequence", "MessageNumber",
+                       "http://www.w3.org/2000/09/xmldsig#",
+                       "http://www.w3.org/2000/09/xmldsig#enveloped-signature", "KeyInfo",
+                       "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
+                       "http://www.w3.org/2001/04/xmlenc#",
+                       "http://schemas.xmlsoap.org/ws/2005/02/sc", "DerivedKeyToken", "Nonce", "Signature", "SignedInfo", "CanonicalizationMethod", "SignatureMethod", "SignatureValue", "DataReference", "EncryptedData", "EncryptionMethod", "CipherData", "CipherValue",
+                       "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "Security", "Timestamp", "Created", "Expires", "Length", "ReferenceList", "ValueType", "Type", "EncryptedHeader",
+                       "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd", "RequestSecurityTokenResponseCollection",
+                       "http://schemas.xmlsoap.org/ws/2005/02/trust",
+                       "http://schemas.xmlsoap.org/ws/2005/02/trust#BinarySecret",
+                       "http://schemas.microsoft.com/ws/2006/02/transactions", "s", "Fault", "MustUnderstand", "role", "relay", "Code", "Reason", "Text", "Node", "Role", "Detail", "Value", "Subcode", "NotUnderstood", "qname", "", "From", "FaultTo", "EndpointReference", "PortType", "ServiceName", "PortName", "ReferenceProperties", "RelationshipType", "Reply", "a",
+                       "http://schemas.xmlsoap.org/ws/2006/02/addressingidentity", "Identity", "Spn", "Upn", "Rsa", "Dns", "X509v3Certificate",
+                       "http://www.w3.org/2005/08/addressing/fault", "ReferenceParameters", "IsReferenceParameter",
+                       "http://www.w3.org/2005/08/addressing/reply",
+                       "http://www.w3.org/2005/08/addressing/none", "Metadata",
+                       "http://schemas.xmlsoap.org/ws/2004/08/addressing",
+                       "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous",
+                       "http://schemas.xmlsoap.org/ws/2004/08/addressing/fault",
+                       "http://schemas.xmlsoap.org/ws/2004/06/addressingex", "RedirectTo", "Via",
+                       "http://www.w3.org/2001/10/xml-exc-c14n#", "PrefixList", "InclusiveNamespaces", "ec", "SecurityContextToken", "Generation", "Label", "Offset", "Properties", "Cookie", "wsc",
+                       "http://schemas.xmlsoap.org/ws/2004/04/sc",
+                       "http://schemas.xmlsoap.org/ws/2004/04/security/sc/dk",
+                       "http://schemas.xmlsoap.org/ws/2004/04/security/sc/sct",
+                       "http://schemas.xmlsoap.org/ws/2004/04/security/trust/RST/SCT",
+                       "http://schemas.xmlsoap.org/ws/2004/04/security/trust/RSTR/SCT", "RenewNeeded", "BadContextToken", "c",
+                       "http://schemas.xmlsoap.org/ws/2005/02/sc/dk",
+                       "http://schemas.xmlsoap.org/ws/2005/02/sc/sct",
+                       "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT",
+                       "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/SCT",
+                       "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT/Renew",
+                       "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/SCT/Renew",
+                       "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT/Cancel",
+                       "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/SCT/Cancel",
+                       "http://www.w3.org/2001/04/xmlenc#aes128-cbc",
+                       "http://www.w3.org/2001/04/xmlenc#kw-aes128",
+                       "http://www.w3.org/2001/04/xmlenc#aes192-cbc",
+                       "http://www.w3.org/2001/04/xmlenc#kw-aes192",
+                       "http://www.w3.org/2001/04/xmlenc#aes256-cbc",
+                       "http://www.w3.org/2001/04/xmlenc#kw-aes256",
+                       "http://www.w3.org/2001/04/xmlenc#des-cbc",
+                       "http://www.w3.org/2000/09/xmldsig#dsa-sha1",
+                       "http://www.w3.org/2001/10/xml-exc-c14n#WithComments",
+                       "http://www.w3.org/2000/09/xmldsig#hmac-sha1",
+                       "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
+                       "http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1",
+                       "http://www.w3.org/2001/04/xmlenc#ripemd160",
+                       "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p",
+                       "http://www.w3.org/2000/09/xmldsig#rsa-sha1",
+                       "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
+                       "http://www.w3.org/2001/04/xmlenc#rsa-1_5",
+                       "http://www.w3.org/2000/09/xmldsig#sha1",
+                       "http://www.w3.org/2001/04/xmlenc#sha256",
+                       "http://www.w3.org/2001/04/xmlenc#sha512",
+                       "http://www.w3.org/2001/04/xmlenc#tripledes-cbc",
+                       "http://www.w3.org/2001/04/xmlenc#kw-tripledes",
+                       "http://schemas.xmlsoap.org/2005/02/trust/tlsnego#TLS_Wrap",
+                       "http://schemas.xmlsoap.org/2005/02/trust/spnego#GSS_Wrap",
+                       "http://schemas.microsoft.com/ws/2006/05/security", "dnse", "o", "Password", "PasswordText", "Username", "UsernameToken", "BinarySecurityToken", "EncodingType", "KeyIdentifier",
+                       "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary",
+                       "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#HexBinary",
+                       "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Text",
+                       "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509SubjectKeyIdentifier",
+                       "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#GSS_Kerberosv5_AP_REQ",
+                       "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#GSS_Kerberosv5_AP_REQ1510",
+                       "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID", "Assertion", "urn:oasis:names:tc:SAML:1.0:assertion",
+                       "http://docs.oasis-open.org/wss/oasis-wss-rel-token-profile-1.0.pdf#license", "FailedAuthentication", "InvalidSecurityToken", "InvalidSecurity", "k", "SignatureConfirmation", "TokenType",
+                       "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1",
+                       "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey",
+                       "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKeySHA1",
+                       "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1",
+                       "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0",
+                       "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLID", "AUTH-HASH", "RequestSecurityTokenResponse", "KeySize", "RequestedTokenReference", "AppliesTo", "Authenticator", "CombinedHash", "BinaryExchange", "Lifetime", "RequestedSecurityToken", "Entropy", "RequestedProofToken", "ComputedKey", "RequestSecurityToken", "RequestType", "Context", "BinarySecret",
+                       "http://schemas.xmlsoap.org/ws/2005/02/trust/spnego",
+                       "http://schemas.xmlsoap.org/ws/2005/02/trust/tlsnego", "wst",
+                       "http://schemas.xmlsoap.org/ws/2004/04/trust",
+                       "http://schemas.xmlsoap.org/ws/2004/04/security/trust/RST/Issue",
+                       "http://schemas.xmlsoap.org/ws/2004/04/security/trust/RSTR/Issue",
+                       "http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue",
+                       "http://schemas.xmlsoap.org/ws/2004/04/security/trust/CK/PSHA1",
+                       "http://schemas.xmlsoap.org/ws/2004/04/security/trust/SymmetricKey",
+                       "http://schemas.xmlsoap.org/ws/2004/04/security/trust/Nonce", "KeyType",
+                       "http://schemas.xmlsoap.org/ws/2004/04/trust/SymmetricKey",
+                       "http://schemas.xmlsoap.org/ws/2004/04/trust/PublicKey", "Claims", "InvalidRequest", "RequestFailed", "SignWith", "EncryptWith", "EncryptionAlgorithm", "CanonicalizationAlgorithm", "ComputedKeyAlgorithm", "UseKey",
+                       "http://schemas.microsoft.com/net/2004/07/secext/WS-SPNego",
+                       "http://schemas.microsoft.com/net/2004/07/secext/TLSNego", "t",
+                       "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue",
+                       "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/Issue",
+                       "http://schemas.xmlsoap.org/ws/2005/02/trust/Issue",
+                       "http://schemas.xmlsoap.org/ws/2005/02/trust/SymmetricKey",
+                       "http://schemas.xmlsoap.org/ws/2005/02/trust/CK/PSHA1",
+                       "http://schemas.xmlsoap.org/ws/2005/02/trust/Nonce", "RenewTarget", "CancelTarget", "RequestedTokenCancelled", "RequestedAttachedReference", "RequestedUnattachedReference", "IssuedTokens",
+                       "http://schemas.xmlsoap.org/ws/2005/02/trust/Renew",
+                       "http://schemas.xmlsoap.org/ws/2005/02/trust/Cancel",
+                       "http://schemas.xmlsoap.org/ws/2005/02/trust/PublicKey", "Access", "AccessDecision", "Advice", "AssertionID", "AssertionIDReference", "Attribute", "AttributeName", "AttributeNamespace", "AttributeStatement", "AttributeValue", "Audience", "AudienceRestrictionCondition", "AuthenticationInstant", "AuthenticationMethod", "AuthenticationStatement", "AuthorityBinding", "AuthorityKind", "AuthorizationDecisionStatement", "Binding", "Condition", "Conditions", "Decision", "DoNotCacheCondition", "Evidence", "IssueInstant", "Issuer", "Location", "MajorVersion", "MinorVersion", "NameIdentifier", "Format", "NameQualifier", "Namespace", "NotBefore", "NotOnOrAfter", "saml", "Statement", "Subject", "SubjectConfirmation", "SubjectConfirmationData", "ConfirmationMethod", "urn:oasis:names:tc:SAML:1.0:cm:holder-of-key", "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches", "SubjectLocality", "DNSAddress", "IPAddress", "SubjectStatement", "urn:oasis:names:tc:SAML:1.0:am:unspecified", "xmlns", "Resource", "UserName", "urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName", "EmailName", "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", "u", "ChannelInstance",
+                       "http://schemas.microsoft.com/ws/2005/02/duplex", "Encoding", "MimeType", "CarriedKeyName", "Recipient", "EncryptedKey", "KeyReference", "e",
+                       "http://www.w3.org/2001/04/xmlenc#Element",
+                       "http://www.w3.org/2001/04/xmlenc#Content", "KeyName", "MgmtData", "KeyValue", "RSAKeyValue", "Modulus", "Exponent", "X509Data", "X509IssuerSerial", "X509IssuerName", "X509SerialNumber", "X509Certificate", "AckRequested",
+                       "http://schemas.xmlsoap.org/ws/2005/02/rm/AckRequested", "AcksTo", "Accept", "CreateSequence",
+                       "http://schemas.xmlsoap.org/ws/2005/02/rm/CreateSequence", "CreateSequenceRefused", "CreateSequenceResponse",
+                       "http://schemas.xmlsoap.org/ws/2005/02/rm/CreateSequenceResponse", "FaultCode", "InvalidAcknowledgement", "LastMessage",
+                       "http://schemas.xmlsoap.org/ws/2005/02/rm/LastMessage", "LastMessageNumberExceeded", "MessageNumberRollover", "Nack", "netrm", "Offer", "r", "SequenceFault", "SequenceTerminated", "TerminateSequence",
+                       "http://schemas.xmlsoap.org/ws/2005/02/rm/TerminateSequence", "UnknownSequence",
+                       "http://schemas.microsoft.com/ws/2006/02/tx/oletx", "oletx", "OleTxTransaction", "PropagationToken",
+                       "http://schemas.xmlsoap.org/ws/2004/10/wscoor", "wscoor", "CreateCoordinationContext", "CreateCoordinationContextResponse", "CoordinationContext", "CurrentContext", "CoordinationType", "RegistrationService", "Register", "RegisterResponse", "ProtocolIdentifier", "CoordinatorProtocolService", "ParticipantProtocolService",
+                       "http://schemas.xmlsoap.org/ws/2004/10/wscoor/CreateCoordinationContext",
+                       "http://schemas.xmlsoap.org/ws/2004/10/wscoor/CreateCoordinationContextResponse",
+                       "http://schemas.xmlsoap.org/ws/2004/10/wscoor/Register",
+                       "http://schemas.xmlsoap.org/ws/2004/10/wscoor/RegisterResponse",
+                       "http://schemas.xmlsoap.org/ws/2004/10/wscoor/fault", "ActivationCoordinatorPortType", "RegistrationCoordinatorPortType", "InvalidState", "InvalidProtocol", "InvalidParameters", "NoActivity", "ContextRefused", "AlreadyRegistered",
+                       "http://schemas.xmlsoap.org/ws/2004/10/wsat", "wsat",
+                       "http://schemas.xmlsoap.org/ws/2004/10/wsat/Completion",
+                       "http://schemas.xmlsoap.org/ws/2004/10/wsat/Durable2PC",
+                       "http://schemas.xmlsoap.org/ws/2004/10/wsat/Volatile2PC", "Prepare", "Prepared", "ReadOnly", "Commit", "Rollback", "Committed", "Aborted", "Replay",
+                       "http://schemas.xmlsoap.org/ws/2004/10/wsat/Commit",
+                       "http://schemas.xmlsoap.org/ws/2004/10/wsat/Rollback",
+                       "http://schemas.xmlsoap.org/ws/2004/10/wsat/Committed",
+                       "http://schemas.xmlsoap.org/ws/2004/10/wsat/Aborted",
+                       "http://schemas.xmlsoap.org/ws/2004/10/wsat/Prepare",
+                       "http://schemas.xmlsoap.org/ws/2004/10/wsat/Prepared",
+                       "http://schemas.xmlsoap.org/ws/2004/10/wsat/ReadOnly",
+                       "http://schemas.xmlsoap.org/ws/2004/10/wsat/Replay",
+                       "http://schemas.xmlsoap.org/ws/2004/10/wsat/fault", "CompletionCoordinatorPortType", "CompletionParticipantPortType", "CoordinatorPortType", "ParticipantPortType", "InconsistentInternalState", "mstx", "Enlistment", "protocol", "LocalTransactionId", "IsolationLevel", "IsolationFlags", "Description", "Loopback", "RegisterInfo", "ContextId", "TokenId", "AccessDenied", "InvalidPolicy", "CoordinatorRegistrationFailed", "TooManyEnlistments", "Disabled", "ActivityId",
+                       "http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics",
+                       "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#Kerberosv5APREQSHA1",
+                       "http://schemas.xmlsoap.org/ws/2002/12/policy", "FloodMessage", "LinkUtility", "Hops",
+                       "http://schemas.microsoft.com/net/2006/05/peer/HopCount", "PeerVia",
+                       "http://schemas.microsoft.com/net/2006/05/peer", "PeerFlooder", "PeerTo",
+                       "http://schemas.microsoft.com/ws/2005/05/routing", "PacketRoutable",
+                       "http://schemas.microsoft.com/ws/2005/05/addressing/none",
+                       "http://schemas.microsoft.com/ws/2005/05/envelope/none",
+                       "http://www.w3.org/2001/XMLSchema-instance",
+                       "http://www.w3.org/2001/XMLSchema", "nil", "type", "char", "boolean", "byte", "unsignedByte", "short", "unsignedShort", "int", "unsignedInt", "long", "unsignedLong", "float", "double", "decimal", "dateTime", "string", "base64Binary", "anyType", "duration", "guid", "anyURI", "QName", "time", "date", "hexBinary", "gYearMonth", "gYear", "gMonthDay", "gDay", "gMonth", "integer", "positiveInteger", "negativeInteger", "nonPositiveInteger", "nonNegativeInteger", "normalizedString", "ConnectionLimitReached",
+                       "http://schemas.xmlsoap.org/soap/envelope/", "Actor", "Faultcode", "Faultstring", "Faultactor", "Detail"
+               };
+
+               static Constants ()
+               {
+                       var d = new XmlDictionary ();
+                       SoapDictionary = d;
+                       foreach (var s in dict_strings)
+                               d.Add (s);
+               }
+
+               public static XmlDictionary SoapDictionary { get; private set; }
+       }
+}
index 322f097c333bec5d32938fd0ae1c019d21f14b6b..123ae4aad91200def001f5bc36ad4fdbec6ed273 100755 (executable)
@@ -72,7 +72,6 @@ namespace MonoTests.System.ServiceModel
                }
 
                [Test]
-               [Category ("NotWorking")]
                public void SerializeDeserialize ()
                {
                        StringWriter sw = new StringWriter ();
index 0d6597053bb01040df3bafcdb2bd0d57b35a8928..da3c8b6f7b58bc2516dd5e668565f40c9ab3fa8c 100644 (file)
@@ -43,7 +43,6 @@ namespace MonoTests.System.ServiceModel
                static readonly X509Certificate2 cert = new X509Certificate2 ("Test/Resources/test.cer");
 
                [Test]
-               [Category ("NotWorking")] // DataContractSerializer+base64 issue
                public void CreateX509CertificateIdentity ()
                {
                        X509CertificateEndpointIdentity identity =
diff --git a/mcs/class/System.ServiceModel/Test/System.ServiceModel/FaultContractAttributeTest.cs b/mcs/class/System.ServiceModel/Test/System.ServiceModel/FaultContractAttributeTest.cs
new file mode 100644 (file)
index 0000000..d4df3e7
--- /dev/null
@@ -0,0 +1,26 @@
+using System;
+using System.ServiceModel;
+using System.ServiceModel.Channels;
+using System.ServiceModel.Description;
+using NUnit.Framework;
+
+namespace MonoTests.System.ServiceModel
+{
+       [TestFixture]
+       public class FaultContractAttributeTest
+       {
+               [Test]
+               public void Defaults ()
+               {
+                       var a = new FaultContractAttribute (typeof (MyDetail));
+                       Assert.AreEqual (typeof (MyDetail), a.DetailType, "#1");
+                       Assert.IsNull (a.Action, "#2");
+                       Assert.IsNull (a.Name, "#3");
+                       Assert.IsNull (a.Namespace, "#4");
+               }
+
+               class MyDetail
+               {
+               }
+       }
+}
index 5a1e9ea555189220d584bbc5f2a5bc578498c4bc..8b91324af608c3bfbed2144cebfb0119662465dc 100644 (file)
@@ -323,6 +323,44 @@ namespace MonoTests.System.ServiceModel
                        Assert.Fail ("should not open");
                }
 
+               [Test]
+               public void RunDestinationUnreachableTest ()
+               {
+                       RunDestinationUnreachableTest ("BasicHttp", new BasicHttpBinding ());
+               }
+
+               [Test]
+               public void RunDestinationUnreachableTest2 ()
+               {
+                       RunDestinationUnreachableTest ("CustomSoap12", new CustomBinding (new HttpTransportBindingElement ()));
+               }
+
+               void RunDestinationUnreachableTest (string label, Binding binding)
+               {
+                       string address = "http://localhost:37564/";
+                       var host = OpenHost (address, binding);
+                       
+                       try {
+                               var client = new DestinationUnreachableClient (binding, address);
+                               client.NotImplementedOperation ();
+                               Assert.Fail (label + " ActionNotSupportedException is expected");
+                       } catch (ActionNotSupportedException) {
+                               // catching it instead of ExpectedException to distinguish errors at service side.
+                       } finally {
+                               host.Close ();
+                       }
+               }
+               
+               ServiceHost OpenHost (string address, Binding binding)
+               {
+                       var baseAddresses = new Uri[] { new Uri(address) };
+
+                       var host = new ServiceHost (typeof (DummyService), baseAddresses);
+                       host.AddServiceEndpoint (typeof (IDummyService), binding, new Uri ("", UriKind.Relative));
+                       host.Open ();
+                       return host;
+               }
+
                #region helpers
 
                public enum Stage
@@ -606,7 +644,39 @@ namespace MonoTests.System.ServiceModel
 
                        #endregion
                }
-               #endregion
 
+               [ServiceContract]
+               public interface IDummyService
+               {
+                       [OperationContract]
+                       void DummyOperation ();
+               }
+               public class DummyService : IDummyService
+               {
+                       public void DummyOperation ()
+                       {
+                               // Do nothing
+                       }
+               }
+               [ServiceContract]
+               public interface INotImplementedService
+               {
+                       [OperationContract]
+                       void NotImplementedOperation ();
+               }
+               public class DestinationUnreachableClient : ClientBase<INotImplementedService>, INotImplementedService
+               {
+                       public void NotImplementedOperation ()
+                       {
+                               Channel.NotImplementedOperation ();
+                       }
+               
+                       public DestinationUnreachableClient (Binding binding, string address) 
+                               : base (binding, new EndpointAddress (address))
+                       {
+                       }
+               }
+
+               #endregion
        }
 }
index 2870b466997a71bdd51c11c1523baa3786b2fa0c..fbaa524eab33dbd671abc9f909d43965a62b8ddc 100644 (file)
@@ -1,3 +1,3 @@
 ../../build/common/Consts.cs
 ../../build/common/MonoTODOAttribute.cs
-#include net_2_1_raw_System.ServiceModel.dll.sources
+#include moonlight_raw_System.ServiceModel.dll.sources
diff --git a/mcs/class/System.ServiceModel/moonlight_raw_System.ServiceModel.dll.sources b/mcs/class/System.ServiceModel/moonlight_raw_System.ServiceModel.dll.sources
new file mode 100755 (executable)
index 0000000..0108213
--- /dev/null
@@ -0,0 +1,226 @@
+Assembly/AssemblyInfo.cs
+Mono.CodeGeneration/CodeAdd.cs
+Mono.CodeGeneration/CodeAnd.cs
+Mono.CodeGeneration/CodeArgument.cs
+Mono.CodeGeneration/CodeArgumentReference.cs
+Mono.CodeGeneration/CodeArithmeticOperation.cs
+Mono.CodeGeneration/CodeArrayItem.cs
+Mono.CodeGeneration/CodeArrayLength.cs
+Mono.CodeGeneration/CodeAssignment.cs
+Mono.CodeGeneration/CodeBinaryComparison.cs
+Mono.CodeGeneration/CodeBinaryOperation.cs
+Mono.CodeGeneration/CodeBlock.cs
+Mono.CodeGeneration/CodeBuilder.cs
+Mono.CodeGeneration/CodeCast.cs
+Mono.CodeGeneration/CodeClass.cs
+Mono.CodeGeneration/CodeCustomAttribute.cs
+Mono.CodeGeneration/CodeDecrement.cs
+Mono.CodeGeneration/CodeEquals.cs
+Mono.CodeGeneration/CodeExpression.cs
+Mono.CodeGeneration/CodeFieldReference.cs
+Mono.CodeGeneration/CodeFor.cs
+Mono.CodeGeneration/CodeForeach.cs
+Mono.CodeGeneration/CodeGenerationHelper.cs
+Mono.CodeGeneration/CodeIf.cs
+Mono.CodeGeneration/CodeIncrement.cs
+Mono.CodeGeneration/CodeIs.cs
+Mono.CodeGeneration/CodeItem.cs
+Mono.CodeGeneration/CodeLiteral.cs
+Mono.CodeGeneration/CodeMethod.cs
+Mono.CodeGeneration/CodeMethodCall.cs
+Mono.CodeGeneration/CodeModule.cs
+Mono.CodeGeneration/CodeNew.cs
+Mono.CodeGeneration/CodeNewArray.cs
+Mono.CodeGeneration/CodeNotEquals.cs
+Mono.CodeGeneration/CodeOr.cs
+Mono.CodeGeneration/CodeProperty.cs
+Mono.CodeGeneration/CodePropertyReference.cs
+Mono.CodeGeneration/CodeReturn.cs
+Mono.CodeGeneration/CodeSelect.cs
+Mono.CodeGeneration/CodeTryBlock.cs
+Mono.CodeGeneration/CodeSelfIncrement.cs
+Mono.CodeGeneration/CodeUnaryOperation.cs
+Mono.CodeGeneration/CodeValueReference.cs
+Mono.CodeGeneration/CodeVariableDeclaration.cs
+Mono.CodeGeneration/CodeVariableReference.cs
+Mono.CodeGeneration/CodeWhen.cs
+Mono.CodeGeneration/CodeWhile.cs
+Mono.CodeGeneration/CodeWriter.cs
+Mono.CodeGeneration/Exp.cs
+System.Collections.Generic/KeyedByTypeCollection.cs
+System.Collections.Generic/SynchronizedCollection.cs
+System.Collections.Generic/SynchronizedKeyedCollection.cs
+System.Collections.Generic/SynchronizedReadOnlyCollection.cs
+System.ServiceModel.Channels/AddressHeader.cs
+System.ServiceModel.Channels/AddressHeaderCollection.cs
+System.ServiceModel.Channels/AddressingVersion.cs
+System.ServiceModel.Channels/BinaryMessageEncoder.cs
+System.ServiceModel.Channels/BinaryMessageEncoderFactory.cs
+System.ServiceModel.Channels/BinaryMessageEncodingBindingElement.cs
+System.ServiceModel.Channels/Binding.cs
+System.ServiceModel.Channels/BindingContext.cs
+System.ServiceModel.Channels/BindingElement.cs
+System.ServiceModel.Channels/BindingElementCollection.cs
+System.ServiceModel.Channels/BindingParameterCollection.cs
+System.ServiceModel.Channels/BodyWriter.cs
+System.ServiceModel.Channels/BufferManager.cs
+System.ServiceModel.Channels/ChannelBase.cs
+System.ServiceModel.Channels/ChannelFactoryBase.cs
+System.ServiceModel.Channels/ChannelManagerBase.cs
+System.ServiceModel.Channels/ChannelParameterCollection.cs
+System.ServiceModel.Channels/ChannelPoolSettings.cs
+System.ServiceModel.Channels/CommunicationObject.cs
+System.ServiceModel.Channels/CustomBinding.cs
+System.ServiceModel.Channels/FaultConverter.cs
+System.ServiceModel.Channels/HtmlizedException.cs
+System.ServiceModel.Channels/HttpChannelFactory.cs
+System.ServiceModel.Channels/HttpCookieContainerBindingElement.cs
+System.ServiceModel.Channels/HttpRequestChannel.cs
+System.ServiceModel.Channels/HttpRequestMessageProperty.cs
+System.ServiceModel.Channels/HttpResponseMessageProperty.cs
+System.ServiceModel.Channels/HttpTransportBindingElement.cs
+System.ServiceModel.Channels/HttpsTransportBindingElement.cs
+System.ServiceModel.Channels/IBindingRuntimePreferences.cs
+System.ServiceModel.Channels/IChannel.cs
+System.ServiceModel.Channels/IChannelFactory.cs
+System.ServiceModel.Channels/IDuplexChannel.cs
+System.ServiceModel.Channels/IDuplexSession.cs
+System.ServiceModel.Channels/IDuplexSessionChannel.cs
+System.ServiceModel.Channels/IHttpCookieContainer.cs
+System.ServiceModel.Channels/IInputChannel.cs
+System.ServiceModel.Channels/IInputSession.cs
+System.ServiceModel.Channels/IInputSessionChannel.cs
+System.ServiceModel.Channels/IMessageProperty.cs
+System.ServiceModel.Channels/IOutputChannel.cs
+System.ServiceModel.Channels/IOutputSession.cs
+System.ServiceModel.Channels/IOutputSessionChannel.cs
+System.ServiceModel.Channels/IRequestChannel.cs
+System.ServiceModel.Channels/IRequestSessionChannel.cs
+System.ServiceModel.Channels/ISecurityCapabilities.cs
+System.ServiceModel.Channels/ISession.cs
+System.ServiceModel.Channels/ISessionChannel.cs
+System.ServiceModel.Channels/LayeredCommunicationObject.cs
+System.ServiceModel.Channels/LayeredOutputChannel.cs
+System.ServiceModel.Channels/LayeredRequestChannel.cs
+System.ServiceModel.Channels/LocalClientSecuritySettings.cs
+System.ServiceModel.Channels/Message.cs
+System.ServiceModel.Channels/MessageBuffer_2_1.cs
+System.ServiceModel.Channels/MessageBufferImpl.cs
+System.ServiceModel.Channels/MessageEncoder.cs
+System.ServiceModel.Channels/MessageEncoderFactory.cs
+System.ServiceModel.Channels/MessageEncodingBindingElement.cs
+System.ServiceModel.Channels/MessageFault.cs
+System.ServiceModel.Channels/MessageFaultBodyWriter.cs
+System.ServiceModel.Channels/MessageHeader.cs
+System.ServiceModel.Channels/MessageHeaderInfo.cs
+System.ServiceModel.Channels/MessageHeaders.cs
+System.ServiceModel.Channels/MessageImpl.cs
+System.ServiceModel.Channels/MessageProperties.cs
+System.ServiceModel.Channels/MessageVersion.cs
+System.ServiceModel.Channels/OutputChannelBase.cs
+System.ServiceModel.Channels/RequestChannelBase.cs
+System.ServiceModel.Channels/RequestContext.cs
+System.ServiceModel.Channels/SecurityBindingElement.cs
+System.ServiceModel.Channels/TextMessageEncoder.cs
+System.ServiceModel.Channels/TextMessageEncoderFactory.cs
+System.ServiceModel.Channels/TextMessageEncodingBindingElement.cs
+System.ServiceModel.Channels/TransportBindingElement.cs
+System.ServiceModel.Channels/TransportSecurityBindingElement.cs
+System.ServiceModel.Channels/UnderstoodHeaders.cs
+System.ServiceModel.Channels/XmlObjectSerializerBodyWriter.cs
+System.ServiceModel.Channels/XmlReaderBodyWriter.cs
+System.ServiceModel.Description/ClientCredentials.cs
+System.ServiceModel.Description/ContractDescription.cs
+System.ServiceModel.Description/ContractDescriptionGenerator.cs
+System.ServiceModel.Description/FaultDescription.cs
+System.ServiceModel.Description/FaultDescriptionCollection.cs
+System.ServiceModel.Description/IEndpointBehavior.cs
+System.ServiceModel.Description/IOperationBehavior.cs
+System.ServiceModel.Description/MessageBodyDescription.cs
+System.ServiceModel.Description/MessageDescription.cs
+System.ServiceModel.Description/MessageDescriptionCollection.cs
+System.ServiceModel.Description/MessageHeaderDescription.cs
+System.ServiceModel.Description/MessageHeaderDescriptionCollection.cs
+System.ServiceModel.Description/MessagePartDescription.cs
+System.ServiceModel.Description/MessagePartDescriptionCollection.cs
+System.ServiceModel.Description/MessagePropertyDescription.cs
+System.ServiceModel.Description/MessagePropertyDescriptionCollection.cs
+System.ServiceModel.Description/OperationDescription.cs
+System.ServiceModel.Description/OperationDescriptionCollection.cs
+System.ServiceModel.Description/ServiceEndpoint.cs
+System.ServiceModel.Description/XmlName.cs
+System.ServiceModel.Dispatcher/BaseMessagesFormatter.cs
+System.ServiceModel.Dispatcher/ClientOperation.cs
+System.ServiceModel.Dispatcher/ClientRuntime.cs
+System.ServiceModel.Dispatcher/FaultContractInfo.cs
+System.ServiceModel.Dispatcher/IChannelInitializer.cs
+System.ServiceModel.Dispatcher/IClientMessageFormatter.cs
+System.ServiceModel.Dispatcher/IClientMessageInspector.cs
+System.ServiceModel.Dispatcher/IClientOperationSelector.cs
+System.ServiceModel.Dispatcher/IDispatchMessageFormatter.cs
+System.ServiceModel.Dispatcher/IInteractiveChannelInitializer.cs
+System.ServiceModel.Dispatcher/IParameterInspector.cs
+System.ServiceModel.Security/MessageSecurityException.cs
+System.ServiceModel.Security/SecurityAccessDeniedException.cs
+System.ServiceModel.Security/UserNamePasswordClientCredential.cs
+System.ServiceModel/ActionNotSupportedException.cs
+System.ServiceModel/AllEnums.cs
+System.ServiceModel/BasicHttpBinding.cs
+System.ServiceModel/BasicHttpSecurity_2_1.cs
+System.ServiceModel/ChannelFactory.cs
+System.ServiceModel/ChannelFactory_1.cs
+System.ServiceModel/ClientBase.cs
+System.ServiceModel/ClientProxyGenerator.cs
+System.ServiceModel/ClientRuntimeChannel.cs
+System.ServiceModel/CommunicationException.cs
+System.ServiceModel/CommunicationObjectAbortedException.cs
+System.ServiceModel/CommunicationObjectFaultedException.cs
+System.ServiceModel/Constants.cs
+System.ServiceModel/DataContractFormatAttribute.cs
+System.ServiceModel/DefaultCommunicationTimeouts.cs
+System.ServiceModel/Dummy.cs
+System.ServiceModel/EndpointAddress.cs
+System.ServiceModel/EndpointAddress10.cs
+System.ServiceModel/EndpointAddressBuilder.cs
+System.ServiceModel/EndpointNotFoundException.cs
+System.ServiceModel/EnvelopeVersion.cs
+System.ServiceModel/ExceptionDetail.cs
+System.ServiceModel/ExtensionCollection.cs
+System.ServiceModel/FaultCode.cs
+System.ServiceModel/FaultContractAttribute.cs
+System.ServiceModel/FaultException.cs
+System.ServiceModel/FaultException_1.cs
+System.ServiceModel/FaultReason.cs
+System.ServiceModel/FaultReasonText.cs
+System.ServiceModel/IClientChannel.cs
+System.ServiceModel/ICommunicationObject.cs
+System.ServiceModel/IContextChannel.cs
+System.ServiceModel/IDefaultCommunicationTimeouts.cs
+System.ServiceModel/IExtensibleObject.cs
+System.ServiceModel/IExtension.cs
+System.ServiceModel/IExtensionCollection.cs
+System.ServiceModel/InvalidMessageContractException.cs
+System.ServiceModel/MessageBodyAttribute.cs
+System.ServiceModel/MessageContractAttribute.cs
+System.ServiceModel/MessageContractMemberAttribute.cs
+System.ServiceModel/MessageHeaderArrayAttribute.cs
+System.ServiceModel/MessageHeaderAttribute.cs
+System.ServiceModel/MessageHeaderException.cs
+System.ServiceModel/MessageHeader_1.cs
+System.ServiceModel/MessageParameterAttribute.cs
+System.ServiceModel/MessagePropertyAttribute.cs
+System.ServiceModel/OperationContext.cs
+System.ServiceModel/OperationContextScope.cs
+System.ServiceModel/OperationContractAttribute.cs
+System.ServiceModel/ProtocolException.cs
+System.ServiceModel/QuotaExceededException.cs
+System.ServiceModel/ServerTooBusyException.cs
+System.ServiceModel/ServiceActivationException.cs
+System.ServiceModel/ServiceContractAttribute.cs
+System.ServiceModel/ServiceKnownTypeAttribute.cs
+System.ServiceModel/SilverlightClientConfigLoader.cs
+System.ServiceModel/TransferMode.cs
+System.ServiceModel/UnknownMessageReceivedEventArgs.cs
+System.ServiceModel/UriSchemeKeyedCollection.cs
+System.ServiceModel/XmlSerializerFormatAttribute.cs
+Dummy_2_1.cs
diff --git a/mcs/class/System.ServiceModel/net_2_1_raw_System.ServiceModel.dll.sources b/mcs/class/System.ServiceModel/net_2_1_raw_System.ServiceModel.dll.sources
deleted file mode 100755 (executable)
index 0108213..0000000
+++ /dev/null
@@ -1,226 +0,0 @@
-Assembly/AssemblyInfo.cs
-Mono.CodeGeneration/CodeAdd.cs
-Mono.CodeGeneration/CodeAnd.cs
-Mono.CodeGeneration/CodeArgument.cs
-Mono.CodeGeneration/CodeArgumentReference.cs
-Mono.CodeGeneration/CodeArithmeticOperation.cs
-Mono.CodeGeneration/CodeArrayItem.cs
-Mono.CodeGeneration/CodeArrayLength.cs
-Mono.CodeGeneration/CodeAssignment.cs
-Mono.CodeGeneration/CodeBinaryComparison.cs
-Mono.CodeGeneration/CodeBinaryOperation.cs
-Mono.CodeGeneration/CodeBlock.cs
-Mono.CodeGeneration/CodeBuilder.cs
-Mono.CodeGeneration/CodeCast.cs
-Mono.CodeGeneration/CodeClass.cs
-Mono.CodeGeneration/CodeCustomAttribute.cs
-Mono.CodeGeneration/CodeDecrement.cs
-Mono.CodeGeneration/CodeEquals.cs
-Mono.CodeGeneration/CodeExpression.cs
-Mono.CodeGeneration/CodeFieldReference.cs
-Mono.CodeGeneration/CodeFor.cs
-Mono.CodeGeneration/CodeForeach.cs
-Mono.CodeGeneration/CodeGenerationHelper.cs
-Mono.CodeGeneration/CodeIf.cs
-Mono.CodeGeneration/CodeIncrement.cs
-Mono.CodeGeneration/CodeIs.cs
-Mono.CodeGeneration/CodeItem.cs
-Mono.CodeGeneration/CodeLiteral.cs
-Mono.CodeGeneration/CodeMethod.cs
-Mono.CodeGeneration/CodeMethodCall.cs
-Mono.CodeGeneration/CodeModule.cs
-Mono.CodeGeneration/CodeNew.cs
-Mono.CodeGeneration/CodeNewArray.cs
-Mono.CodeGeneration/CodeNotEquals.cs
-Mono.CodeGeneration/CodeOr.cs
-Mono.CodeGeneration/CodeProperty.cs
-Mono.CodeGeneration/CodePropertyReference.cs
-Mono.CodeGeneration/CodeReturn.cs
-Mono.CodeGeneration/CodeSelect.cs
-Mono.CodeGeneration/CodeTryBlock.cs
-Mono.CodeGeneration/CodeSelfIncrement.cs
-Mono.CodeGeneration/CodeUnaryOperation.cs
-Mono.CodeGeneration/CodeValueReference.cs
-Mono.CodeGeneration/CodeVariableDeclaration.cs
-Mono.CodeGeneration/CodeVariableReference.cs
-Mono.CodeGeneration/CodeWhen.cs
-Mono.CodeGeneration/CodeWhile.cs
-Mono.CodeGeneration/CodeWriter.cs
-Mono.CodeGeneration/Exp.cs
-System.Collections.Generic/KeyedByTypeCollection.cs
-System.Collections.Generic/SynchronizedCollection.cs
-System.Collections.Generic/SynchronizedKeyedCollection.cs
-System.Collections.Generic/SynchronizedReadOnlyCollection.cs
-System.ServiceModel.Channels/AddressHeader.cs
-System.ServiceModel.Channels/AddressHeaderCollection.cs
-System.ServiceModel.Channels/AddressingVersion.cs
-System.ServiceModel.Channels/BinaryMessageEncoder.cs
-System.ServiceModel.Channels/BinaryMessageEncoderFactory.cs
-System.ServiceModel.Channels/BinaryMessageEncodingBindingElement.cs
-System.ServiceModel.Channels/Binding.cs
-System.ServiceModel.Channels/BindingContext.cs
-System.ServiceModel.Channels/BindingElement.cs
-System.ServiceModel.Channels/BindingElementCollection.cs
-System.ServiceModel.Channels/BindingParameterCollection.cs
-System.ServiceModel.Channels/BodyWriter.cs
-System.ServiceModel.Channels/BufferManager.cs
-System.ServiceModel.Channels/ChannelBase.cs
-System.ServiceModel.Channels/ChannelFactoryBase.cs
-System.ServiceModel.Channels/ChannelManagerBase.cs
-System.ServiceModel.Channels/ChannelParameterCollection.cs
-System.ServiceModel.Channels/ChannelPoolSettings.cs
-System.ServiceModel.Channels/CommunicationObject.cs
-System.ServiceModel.Channels/CustomBinding.cs
-System.ServiceModel.Channels/FaultConverter.cs
-System.ServiceModel.Channels/HtmlizedException.cs
-System.ServiceModel.Channels/HttpChannelFactory.cs
-System.ServiceModel.Channels/HttpCookieContainerBindingElement.cs
-System.ServiceModel.Channels/HttpRequestChannel.cs
-System.ServiceModel.Channels/HttpRequestMessageProperty.cs
-System.ServiceModel.Channels/HttpResponseMessageProperty.cs
-System.ServiceModel.Channels/HttpTransportBindingElement.cs
-System.ServiceModel.Channels/HttpsTransportBindingElement.cs
-System.ServiceModel.Channels/IBindingRuntimePreferences.cs
-System.ServiceModel.Channels/IChannel.cs
-System.ServiceModel.Channels/IChannelFactory.cs
-System.ServiceModel.Channels/IDuplexChannel.cs
-System.ServiceModel.Channels/IDuplexSession.cs
-System.ServiceModel.Channels/IDuplexSessionChannel.cs
-System.ServiceModel.Channels/IHttpCookieContainer.cs
-System.ServiceModel.Channels/IInputChannel.cs
-System.ServiceModel.Channels/IInputSession.cs
-System.ServiceModel.Channels/IInputSessionChannel.cs
-System.ServiceModel.Channels/IMessageProperty.cs
-System.ServiceModel.Channels/IOutputChannel.cs
-System.ServiceModel.Channels/IOutputSession.cs
-System.ServiceModel.Channels/IOutputSessionChannel.cs
-System.ServiceModel.Channels/IRequestChannel.cs
-System.ServiceModel.Channels/IRequestSessionChannel.cs
-System.ServiceModel.Channels/ISecurityCapabilities.cs
-System.ServiceModel.Channels/ISession.cs
-System.ServiceModel.Channels/ISessionChannel.cs
-System.ServiceModel.Channels/LayeredCommunicationObject.cs
-System.ServiceModel.Channels/LayeredOutputChannel.cs
-System.ServiceModel.Channels/LayeredRequestChannel.cs
-System.ServiceModel.Channels/LocalClientSecuritySettings.cs
-System.ServiceModel.Channels/Message.cs
-System.ServiceModel.Channels/MessageBuffer_2_1.cs
-System.ServiceModel.Channels/MessageBufferImpl.cs
-System.ServiceModel.Channels/MessageEncoder.cs
-System.ServiceModel.Channels/MessageEncoderFactory.cs
-System.ServiceModel.Channels/MessageEncodingBindingElement.cs
-System.ServiceModel.Channels/MessageFault.cs
-System.ServiceModel.Channels/MessageFaultBodyWriter.cs
-System.ServiceModel.Channels/MessageHeader.cs
-System.ServiceModel.Channels/MessageHeaderInfo.cs
-System.ServiceModel.Channels/MessageHeaders.cs
-System.ServiceModel.Channels/MessageImpl.cs
-System.ServiceModel.Channels/MessageProperties.cs
-System.ServiceModel.Channels/MessageVersion.cs
-System.ServiceModel.Channels/OutputChannelBase.cs
-System.ServiceModel.Channels/RequestChannelBase.cs
-System.ServiceModel.Channels/RequestContext.cs
-System.ServiceModel.Channels/SecurityBindingElement.cs
-System.ServiceModel.Channels/TextMessageEncoder.cs
-System.ServiceModel.Channels/TextMessageEncoderFactory.cs
-System.ServiceModel.Channels/TextMessageEncodingBindingElement.cs
-System.ServiceModel.Channels/TransportBindingElement.cs
-System.ServiceModel.Channels/TransportSecurityBindingElement.cs
-System.ServiceModel.Channels/UnderstoodHeaders.cs
-System.ServiceModel.Channels/XmlObjectSerializerBodyWriter.cs
-System.ServiceModel.Channels/XmlReaderBodyWriter.cs
-System.ServiceModel.Description/ClientCredentials.cs
-System.ServiceModel.Description/ContractDescription.cs
-System.ServiceModel.Description/ContractDescriptionGenerator.cs
-System.ServiceModel.Description/FaultDescription.cs
-System.ServiceModel.Description/FaultDescriptionCollection.cs
-System.ServiceModel.Description/IEndpointBehavior.cs
-System.ServiceModel.Description/IOperationBehavior.cs
-System.ServiceModel.Description/MessageBodyDescription.cs
-System.ServiceModel.Description/MessageDescription.cs
-System.ServiceModel.Description/MessageDescriptionCollection.cs
-System.ServiceModel.Description/MessageHeaderDescription.cs
-System.ServiceModel.Description/MessageHeaderDescriptionCollection.cs
-System.ServiceModel.Description/MessagePartDescription.cs
-System.ServiceModel.Description/MessagePartDescriptionCollection.cs
-System.ServiceModel.Description/MessagePropertyDescription.cs
-System.ServiceModel.Description/MessagePropertyDescriptionCollection.cs
-System.ServiceModel.Description/OperationDescription.cs
-System.ServiceModel.Description/OperationDescriptionCollection.cs
-System.ServiceModel.Description/ServiceEndpoint.cs
-System.ServiceModel.Description/XmlName.cs
-System.ServiceModel.Dispatcher/BaseMessagesFormatter.cs
-System.ServiceModel.Dispatcher/ClientOperation.cs
-System.ServiceModel.Dispatcher/ClientRuntime.cs
-System.ServiceModel.Dispatcher/FaultContractInfo.cs
-System.ServiceModel.Dispatcher/IChannelInitializer.cs
-System.ServiceModel.Dispatcher/IClientMessageFormatter.cs
-System.ServiceModel.Dispatcher/IClientMessageInspector.cs
-System.ServiceModel.Dispatcher/IClientOperationSelector.cs
-System.ServiceModel.Dispatcher/IDispatchMessageFormatter.cs
-System.ServiceModel.Dispatcher/IInteractiveChannelInitializer.cs
-System.ServiceModel.Dispatcher/IParameterInspector.cs
-System.ServiceModel.Security/MessageSecurityException.cs
-System.ServiceModel.Security/SecurityAccessDeniedException.cs
-System.ServiceModel.Security/UserNamePasswordClientCredential.cs
-System.ServiceModel/ActionNotSupportedException.cs
-System.ServiceModel/AllEnums.cs
-System.ServiceModel/BasicHttpBinding.cs
-System.ServiceModel/BasicHttpSecurity_2_1.cs
-System.ServiceModel/ChannelFactory.cs
-System.ServiceModel/ChannelFactory_1.cs
-System.ServiceModel/ClientBase.cs
-System.ServiceModel/ClientProxyGenerator.cs
-System.ServiceModel/ClientRuntimeChannel.cs
-System.ServiceModel/CommunicationException.cs
-System.ServiceModel/CommunicationObjectAbortedException.cs
-System.ServiceModel/CommunicationObjectFaultedException.cs
-System.ServiceModel/Constants.cs
-System.ServiceModel/DataContractFormatAttribute.cs
-System.ServiceModel/DefaultCommunicationTimeouts.cs
-System.ServiceModel/Dummy.cs
-System.ServiceModel/EndpointAddress.cs
-System.ServiceModel/EndpointAddress10.cs
-System.ServiceModel/EndpointAddressBuilder.cs
-System.ServiceModel/EndpointNotFoundException.cs
-System.ServiceModel/EnvelopeVersion.cs
-System.ServiceModel/ExceptionDetail.cs
-System.ServiceModel/ExtensionCollection.cs
-System.ServiceModel/FaultCode.cs
-System.ServiceModel/FaultContractAttribute.cs
-System.ServiceModel/FaultException.cs
-System.ServiceModel/FaultException_1.cs
-System.ServiceModel/FaultReason.cs
-System.ServiceModel/FaultReasonText.cs
-System.ServiceModel/IClientChannel.cs
-System.ServiceModel/ICommunicationObject.cs
-System.ServiceModel/IContextChannel.cs
-System.ServiceModel/IDefaultCommunicationTimeouts.cs
-System.ServiceModel/IExtensibleObject.cs
-System.ServiceModel/IExtension.cs
-System.ServiceModel/IExtensionCollection.cs
-System.ServiceModel/InvalidMessageContractException.cs
-System.ServiceModel/MessageBodyAttribute.cs
-System.ServiceModel/MessageContractAttribute.cs
-System.ServiceModel/MessageContractMemberAttribute.cs
-System.ServiceModel/MessageHeaderArrayAttribute.cs
-System.ServiceModel/MessageHeaderAttribute.cs
-System.ServiceModel/MessageHeaderException.cs
-System.ServiceModel/MessageHeader_1.cs
-System.ServiceModel/MessageParameterAttribute.cs
-System.ServiceModel/MessagePropertyAttribute.cs
-System.ServiceModel/OperationContext.cs
-System.ServiceModel/OperationContextScope.cs
-System.ServiceModel/OperationContractAttribute.cs
-System.ServiceModel/ProtocolException.cs
-System.ServiceModel/QuotaExceededException.cs
-System.ServiceModel/ServerTooBusyException.cs
-System.ServiceModel/ServiceActivationException.cs
-System.ServiceModel/ServiceContractAttribute.cs
-System.ServiceModel/ServiceKnownTypeAttribute.cs
-System.ServiceModel/SilverlightClientConfigLoader.cs
-System.ServiceModel/TransferMode.cs
-System.ServiceModel/UnknownMessageReceivedEventArgs.cs
-System.ServiceModel/UriSchemeKeyedCollection.cs
-System.ServiceModel/XmlSerializerFormatAttribute.cs
-Dummy_2_1.cs
index 550ccf05bd45f2dbe38eaf0ea887a00398f28c6c..f8b48c78c8388b1483b8cce3f1effdfc43bc849e 100644 (file)
@@ -38,3 +38,8 @@
 ../System.ServiceModel.Web/System.ServiceModel.Syndication/UrlSyndicationContent.cs
 ../System.ServiceModel.Web/System.ServiceModel.Syndication/Workspace.cs
 ../System.ServiceModel.Web/System.ServiceModel.Syndication/XmlSyndicationContent.cs
+../System.ServiceModel.Web/System/UriTemplate.cs
+../System.ServiceModel.Web/System/UriTemplateEquivalenceComparer.cs
+../System.ServiceModel.Web/System/UriTemplateMatch.cs
+../System.ServiceModel.Web/System/UriTemplateMatchException.cs
+../System.ServiceModel.Web/System/UriTemplateTable.cs
index 10163bbf4acdec54d927aad6f481e067f47fc4e7..a21492a7faa4eca8bbfc1953136d7937bf42e147 100644 (file)
@@ -1,3 +1,8 @@
+2010-04-26  Marek Habersack  <mhabersack@novell.com>
+
+       * HttpContextWrapper.cs: implemented two 4.0 methods: RemapHandler
+       and SetSessionStateBehavior
+
 2010-02-18  Marek Habersack  <mhabersack@novell.com>
 
        * HttpFileCollectionWrapper.cs: Get (string) and this [string]
index 4476eaa8ebbf4a0b9a31bd51e97b358aae55ad04..66e99f2610616786a64eb56b06cf1a35646b2e95 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Atsushi Enomoto <atsushi@ximian.com>
 //
-// Copyright (C) 2008 Novell Inc. http://novell.com
+// Copyright (C) 2008-2010 Novell Inc. http://novell.com
 //
 
 //
@@ -36,6 +36,7 @@ using System.Security.Permissions;
 using System.Security.Principal;
 using System.Web.Caching;
 using System.Web.Profile;
+using System.Web.SessionState;
 
 namespace System.Web
 {
@@ -187,7 +188,12 @@ namespace System.Web
                {
                        throw new NotImplementedException ();
                }
-
+#if NET_4_0
+               public override void RemapHandler (IHttpHandler handler)
+               {
+                       w.RemapHandler (handler);
+               }
+#endif
                public override void RewritePath (string path)
                {
                        w.RewritePath (path);
@@ -207,5 +213,11 @@ namespace System.Web
                {
                        w.RewritePath (filePath, pathInfo, queryString, setClientFilePath);
                }
+#if NET_4_0
+               public override void SetSessionStateBehavior (SessionStateBehavior sessionStateBehavior)
+               {
+                       w.SetSessionStateBehavior (sessionStateBehavior);
+               }
+#endif
        }
 }
index 171a479d7fa16e1723b0df7b1faf614f3d2a37da..3815b79811d714e64872558e3ae646ba11f6b857 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-15  Marek Habersack  <mhabersack@novell.com>
+
+       * Makefile (LIBRARY_COMPAT): added - this lib is installed in the
+       compat dir.
+
 2010-02-17  Marek Habersack  <mhabersack@novell.com>
 
        * Makefile: RESX_RES is no more, it was replaced with
index bc6793722575d904a668465ebba0909d700e152f..8f8ce46a161b4b5b4fa7c79cd6f296e9f6b11674 100644 (file)
@@ -4,6 +4,7 @@ include ../../build/rules.make
 
 LIBRARY = System.Web.Mvc.dll
 LIBRARY_USE_INTERMEDIATE_FILE = yes
+LIBRARY_COMPAT = yes
 
 RESX_DIST =  System.Web.Mvc/Resources/MvcResources.resx
 
diff --git a/mcs/class/System.Web.Mvc2/ChangeLog b/mcs/class/System.Web.Mvc2/ChangeLog
new file mode 100644 (file)
index 0000000..07970aa
--- /dev/null
@@ -0,0 +1,9 @@
+2010-03-18  Marek Habersack  <mhabersack@novell.com>
+
+       * Makefile: include resources in compilation
+
+2010-02-09  Marek Habersack  <mhabersack@novell.com>
+
+       * Makefile: added references to
+       System.ComponentModel.DataAnnotations and System.Data.Linq
+
diff --git a/mcs/class/System.Web.Mvc2/GlobalSuppressions.cs b/mcs/class/System.Web.Mvc2/GlobalSuppressions.cs
new file mode 100644 (file)
index 0000000..71130ae
--- /dev/null
@@ -0,0 +1,26 @@
+// This file is used by Code Analysis to maintain SuppressMessage \r
+// attributes that are applied to this project. \r
+// Project-level suppressions either have no target or are given \r
+// a specific target and scoped to a namespace, type, member, etc. \r
+//\r
+// To add a suppression to this file, right-click the message in the \r
+// Error List, point to "Suppress Message(s)", and click \r
+// "In Project Suppression File". \r
+// You do not need to add suppressions to this file manually. \r
+\r
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Scope = "member", Target = "System.Web.Mvc.TempDataDictionary.#System.Collections.Generic.ICollection`1<System.Collections.Generic.KeyValuePair`2<System.String,System.Object>>.Contains(System.Collections.Generic.KeyValuePair`2<System.String,System.Object>)",\r
+    Justification = "There are no defined scenarios for wanting to derive from this class, but we don't want to prevent it either.")]\r
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Scope = "member", Target = "System.Web.Mvc.TempDataDictionary.#System.Collections.Generic.ICollection`1<System.Collections.Generic.KeyValuePair`2<System.String,System.Object>>.CopyTo(System.Collections.Generic.KeyValuePair`2<System.String,System.Object>[],System.Int32)",\r
+    Justification = "There are no defined scenarios for wanting to derive from this class, but we don't want to prevent it either.")]\r
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Scope = "member", Target = "System.Web.Mvc.TempDataDictionary.#System.Collections.Generic.ICollection`1<System.Collections.Generic.KeyValuePair`2<System.String,System.Object>>.IsReadOnly",\r
+    Justification = "There are no defined scenarios for wanting to derive from this class, but we don't want to prevent it either.")]\r
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "System.Web.Mvc.Ajax",\r
+    Justification = "Helpers reside within a separate namespace to support alternate helper classes.")]\r
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Web.Abstractions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35",\r
+    Justification = "MVC has a .NET Framework 3.5 SP1 dependency.")]\r
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35",\r
+    Justification = "MVC has a .NET Framework 3.5 SP1 dependency.")]\r
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.ComponentModel.DataAnnotations, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35",\r
+    Justification = "MVC has a .NET Framework 3.5 SP1 dependency.")]\r
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",\r
+    Justification = "MVC has a .NET Framework 3.5 SP1 dependency.")]\r
diff --git a/mcs/class/System.Web.Mvc2/Makefile b/mcs/class/System.Web.Mvc2/Makefile
new file mode 100644 (file)
index 0000000..5aba709
--- /dev/null
@@ -0,0 +1,50 @@
+thisdir = class/System.Web.Mvc2
+SUBDIRS = 
+include ../../build/rules.make
+
+LIBRARY = System.Web.Mvc.dll
+LIBRARY_USE_INTERMEDIATE_FILE = yes
+
+RESX_DIST =  System.Web.Mvc/Resources/MvcResources.resx
+
+LIB_MCS_FLAGS = \
+               /warnaserror- \
+               /noconfig \
+               /keyfile:../winfx.pub \
+               /r:System.dll \
+               /r:System.Core.dll \
+               /r:System.Configuration.dll \
+               /r:System.Data.dll \
+               /r:System.Xml.dll \
+               /r:System.Web.dll \
+               /r:System.Web.Abstractions.dll \
+               /r:System.Web.Routing.dll \
+               /r:System.Web.Extensions.dll \
+               /r:System.ComponentModel.DataAnnotations.dll \
+               /r:System.Data.Linq.dll \
+               $(foreach r, $(RESOURCES), /resource:$(r),System.Web.Mvc.Resources.$(notdir $(r)))
+
+ifeq (2.0, $(FRAMEWORK_VERSION))
+# This is a .NET 3.5 only assembly, but built during the 2.0 build
+LIB_MCS_FLAGS += -d:NET_3_5 -d:MONO
+endif
+
+EXTRA_DISTFILES = $(RESX_DIST)
+
+# This is a .NET 3.5+ assembly - it must be built ONLY in the 2.0 profile
+VALID_PROFILE := $(filter net_2_0, $(PROFILE))
+ifndef VALID_PROFILE
+LIBRARY_NAME = dummy-System.Web.Mvc.dll
+NO_INSTALL = yes
+NO_SIGN_ASSEMBLY = yes
+NO_TEST = yes
+else
+RESOURCES = $(RESX_DIST:.resx=.resources)
+endif
+
+include ../../build/library.make
+
+$(build_lib): $(RESOURCES)
+
+$(RESOURCES): %.resources: %.resx
+       $(RESGEN) `echo $< | $(PLATFORM_CHANGE_SEPARATOR_CMD)`
diff --git a/mcs/class/System.Web.Mvc2/Properties/AssemblyInfo.cs b/mcs/class/System.Web.Mvc2/Properties/AssemblyInfo.cs
new file mode 100644 (file)
index 0000000..4a06eb8
--- /dev/null
@@ -0,0 +1,63 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+using System;\r
+using System.Diagnostics.CodeAnalysis;\r
+using System.Reflection;\r
+using System.Resources;\r
+using System.Runtime.CompilerServices;\r
+using System.Runtime.InteropServices;\r
+using System.Security;\r
+\r
+// General Information about an assembly is controlled through the following \r
+// set of attributes. Change these attribute values to modify the information\r
+// associated with an assembly.\r
+[assembly: AssemblyTitle("System.Web.Mvc.dll")]\r
+[assembly: AssemblyDescription("System.Web.Mvc.dll")]\r
+[assembly: AssemblyConfiguration("")]\r
+[assembly: AssemblyCompany("Microsoft Corporation")]\r
+[assembly: AssemblyProduct("Microsoft® .NET Framework")]\r
+[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]\r
+[assembly: AssemblyTrademark("")]\r
+[assembly: AssemblyCulture("")]\r
+\r
+// Setting ComVisible to false makes the types in this assembly not visible \r
+// to COM components.  If you need to access a type in this assembly from \r
+// COM, set the ComVisible attribute to true on that type.\r
+[assembly: ComVisible(false)]\r
+\r
+// The following GUID is for the ID of the typelib if this project is exposed to COM\r
+[assembly: Guid("4b5f4208-c6b0-4c37-9a41-63325ffa52ad")]\r
+\r
+// Version information for an assembly consists of the following four values:\r
+//\r
+//      Major Version\r
+//      Minor Version \r
+//      Build Number\r
+//      Revision\r
+//\r
+// You can specify all the values or you can default the Build and Revision Numbers \r
+// by using the '*' as shown below:\r
+// [assembly: AssemblyVersion("1.0.*")]\r
+[assembly: AssemblyVersion("2.0.0.0")]\r
+[assembly: AssemblyFileVersion("2.0.50217.0")]\r
+\r
+[assembly: AllowPartiallyTrustedCallers]\r
+[assembly: SecurityTransparent]\r
+[assembly: CLSCompliant(true)]\r
+[assembly: NeutralResourcesLanguage("en-US")]\r
+\r
+[assembly: SuppressMessage("Microsoft.Design", "CA2210:AssembliesShouldHaveValidStrongNames",\r
+    Justification = "Assembly is delay-signed.")]\r
+
+[assembly: AssemblyDelaySign (true)]\r
+[assembly: AssemblyKeyFile("../winfx.pub")]\r
diff --git a/mcs/class/System.Web.Mvc2/Properties/ChangeLog b/mcs/class/System.Web.Mvc2/Properties/ChangeLog
new file mode 100644 (file)
index 0000000..6e4c8c6
--- /dev/null
@@ -0,0 +1,5 @@
+2010-02-09  Marek Habersack  <mhabersack@novell.com>
+
+       * AssemblyInfo.cs: added Mono-specific attributes to delay-sign
+       the assembly and use the winfs.pub key
+
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc.csproj b/mcs/class/System.Web.Mvc2/System.Web.Mvc.csproj
new file mode 100644 (file)
index 0000000..a47c382
--- /dev/null
@@ -0,0 +1,381 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">\r
+  <PropertyGroup>\r
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>\r
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>\r
+    <ProductVersion>9.0.30729</ProductVersion>\r
+    <SchemaVersion>2.0</SchemaVersion>\r
+    <ProjectGuid>{3D3FFD8A-624D-4E9B-954B-E1C105507975}</ProjectGuid>\r
+    <OutputType>Library</OutputType>\r
+    <AppDesignerFolder>Properties</AppDesignerFolder>\r
+    <RootNamespace>System.Web</RootNamespace>\r
+    <AssemblyName>System.Web.Mvc</AssemblyName>\r
+    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>\r
+    <FileAlignment>512</FileAlignment>\r
+    <ErrorReport>prompt</ErrorReport>\r
+    <WarningLevel>4</WarningLevel>\r
+    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>\r
+    <BaseAddress>1609891840</BaseAddress>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">\r
+    <DebugSymbols>true</DebugSymbols>\r
+    <DebugType>full</DebugType>\r
+    <Optimize>false</Optimize>\r
+    <OutputPath>..\..\bin\Debug\</OutputPath>\r
+    <DefineConstants>DEBUG;TRACE</DefineConstants>\r
+  </PropertyGroup>\r
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">\r
+    <DebugType>pdbonly</DebugType>\r
+    <Optimize>true</Optimize>\r
+    <OutputPath>..\..\bin\Release\</OutputPath>\r
+    <DefineConstants>TRACE</DefineConstants>\r
+  </PropertyGroup>\r
+  <ItemGroup>\r
+    <Reference Include="System" />\r
+    <Reference Include="System.ComponentModel.DataAnnotations">\r
+      <RequiredTargetFramework>3.5</RequiredTargetFramework>\r
+    </Reference>\r
+    <Reference Include="System.configuration" />\r
+    <Reference Include="System.Core">\r
+      <RequiredTargetFramework>3.5</RequiredTargetFramework>\r
+    </Reference>\r
+    <Reference Include="System.Data.Entity">\r
+      <RequiredTargetFramework>3.5</RequiredTargetFramework>\r
+    </Reference>\r
+    <Reference Include="System.Data.Linq">\r
+      <RequiredTargetFramework>3.5</RequiredTargetFramework>\r
+    </Reference>\r
+    <Reference Include="System.Web" />\r
+    <Reference Include="System.Data" />\r
+    <Reference Include="System.Web.Abstractions">\r
+      <RequiredTargetFramework>3.5</RequiredTargetFramework>\r
+    </Reference>\r
+    <Reference Include="System.Web.Extensions">\r
+      <RequiredTargetFramework>3.5</RequiredTargetFramework>\r
+    </Reference>\r
+    <Reference Include="System.Web.Routing">\r
+      <RequiredTargetFramework>3.5</RequiredTargetFramework>\r
+    </Reference>\r
+    <Reference Include="System.Xml" />\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <Compile Include="Mvc\AssociatedMetadataProvider.cs" />\r
+    <Compile Include="Mvc\ActionExecutedContext.cs" />\r
+    <Compile Include="Mvc\ActionExecutingContext.cs" />\r
+    <Compile Include="Mvc\AntiForgeryData.cs" />\r
+    <Compile Include="Mvc\AntiForgeryDataSerializer.cs" />\r
+    <Compile Include="Mvc\ClientDataTypeModelValidatorProvider.cs" />\r
+    <Compile Include="Mvc\AssociatedValidatorProvider.cs" />\r
+    <Compile Include="Mvc\Async\ActionDescriptorCreator.cs" />\r
+    <Compile Include="Mvc\Async\AsyncActionDescriptor.cs" />\r
+    <Compile Include="Mvc\Async\AsyncActionMethodSelector.cs" />\r
+    <Compile Include="Mvc\Async\AsyncControllerActionInvoker.cs" />\r
+    <Compile Include="Mvc\Async\SynchronousOperationException.cs" />\r
+    <Compile Include="Mvc\Async\AsyncManager.cs" />\r
+    <Compile Include="Mvc\AsyncTimeoutAttribute.cs" />\r
+    <Compile Include="Mvc\Async\BeginInvokeDelegate.cs" />\r
+    <Compile Include="Mvc\Async\AsyncResultWrapper.cs" />\r
+    <Compile Include="Mvc\Async\AsyncVoid.cs" />\r
+    <Compile Include="Mvc\AsyncController.cs" />\r
+    <Compile Include="Mvc\Async\AsyncUtil.cs" />\r
+    <Compile Include="Mvc\Async\IAsyncController.cs" />\r
+    <Compile Include="Mvc\Async\IAsyncActionInvoker.cs" />\r
+    <Compile Include="Mvc\Async\IAsyncManagerContainer.cs" />\r
+    <Compile Include="Mvc\UrlParameter.cs" />\r
+    <Compile Include="Mvc\FormValueProvider.cs" />\r
+    <Compile Include="Mvc\FormValueProviderFactory.cs" />\r
+    <Compile Include="Mvc\HttpFileCollectionValueProvider.cs" />\r
+    <Compile Include="Mvc\HttpFileCollectionValueProviderFactory.cs" />\r
+    <Compile Include="Mvc\QueryStringValueProvider.cs" />\r
+    <Compile Include="Mvc\QueryStringValueProviderFactory.cs" />\r
+    <Compile Include="Mvc\RangeAttributeAdapter.cs" />\r
+    <Compile Include="Mvc\RegularExpressionAttributeAdapter.cs" />\r
+    <Compile Include="Mvc\RequiredAttributeAdapter.cs" />\r
+    <Compile Include="Mvc\RouteDataValueProvider.cs" />\r
+    <Compile Include="Mvc\RouteDataValueProviderFactory.cs" />\r
+    <Compile Include="Mvc\StringLengthAttributeAdapter.cs" />\r
+    <Compile Include="Mvc\TypeCacheUtil.cs" />\r
+    <Compile Include="Mvc\TypeCacheSerializer.cs" />\r
+    <Compile Include="Mvc\Html\DisplayTextExtensions.cs" />\r
+    <Compile Include="Mvc\NoAsyncTimeoutAttribute.cs" />\r
+    <Compile Include="Mvc\Async\OperationCounter.cs" />\r
+    <Compile Include="Mvc\Async\ReflectedAsyncActionDescriptor.cs" />\r
+    <Compile Include="Mvc\Async\ReflectedAsyncControllerDescriptor.cs" />\r
+    <Compile Include="Mvc\Async\Trigger.cs" />\r
+    <Compile Include="Mvc\Async\TriggerListener.cs" />\r
+    <Compile Include="Mvc\Async\SimpleAsyncResult.cs" />\r
+    <Compile Include="Mvc\Async\EndInvokeDelegate.cs" />\r
+    <Compile Include="Mvc\Async\EndInvokeDelegate`1.cs" />\r
+    <Compile Include="Mvc\Async\SynchronizationContextUtil.cs" />\r
+    <Compile Include="Mvc\AuthorizationContext.cs" />\r
+    <Compile Include="Mvc\ByteArrayModelBinder.cs" />\r
+    <Compile Include="Mvc\ControllerContext.cs" />\r
+    <Compile Include="Mvc\Html\ChildActionExtensions.cs" />\r
+    <Compile Include="Mvc\ParameterInfoUtil.cs" />\r
+    <Compile Include="Mvc\HttpHandlerUtil.cs" />\r
+    <Compile Include="Mvc\ChildActionOnlyAttribute.cs" />\r
+    <Compile Include="Mvc\TypeDescriptorHelper.cs" />\r
+    <Compile Include="Mvc\ValueProviderFactories.cs" />\r
+    <Compile Include="Mvc\ValueProviderFactory.cs" />\r
+    <Compile Include="Mvc\ValueProviderFactoryCollection.cs" />\r
+    <Compile Include="Mvc\ValueProviderCollection.cs" />\r
+    <Compile Include="Mvc\DictionaryValueProvider`1.cs" />\r
+    <Compile Include="Mvc\NameValueCollectionValueProvider.cs" />\r
+    <Compile Include="Mvc\ValueProviderUtil.cs" />\r
+    <Compile Include="Mvc\IValueProvider.cs" />\r
+    <Compile Include="Mvc\DataErrorInfoModelValidatorProvider.cs" />\r
+    <Compile Include="Mvc\ModelValidatorProviderCollection.cs" />\r
+    <Compile Include="Mvc\DataAnnotationsModelMetadata.cs" />\r
+    <Compile Include="Mvc\HiddenInputAttribute.cs" />\r
+    <Compile Include="Mvc\HttpGetAttribute.cs" />\r
+    <Compile Include="Mvc\HttpPutAttribute.cs" />\r
+    <Compile Include="Mvc\HttpDeleteAttribute.cs" />\r
+    <Compile Include="Mvc\DynamicTypeGenerator.cs" />\r
+    <Compile Include="Mvc\ModelClientValidationRequiredRule.cs" />\r
+    <Compile Include="Mvc\ModelClientValidationRangeRule.cs" />\r
+    <Compile Include="Mvc\ModelClientValidationStringLengthRule.cs" />\r
+    <Compile Include="Mvc\MvcHtmlString.cs" />\r
+    <Compile Include="Mvc\DataAnnotationsModelValidator.cs" />\r
+    <Compile Include="Mvc\DataAnnotationsModelValidatorProvider.cs" />\r
+    <Compile Include="Mvc\DataAnnotationsModelValidator`1.cs" />\r
+    <Compile Include="Mvc\EmptyModelValidatorProvider.cs" />\r
+    <Compile Include="Mvc\ExpressionHelper.cs" />\r
+    <Compile Include="Mvc\FieldValidationMetadata.cs" />\r
+    <Compile Include="Mvc\FormContext.cs" />\r
+    <Compile Include="Mvc\JsonRequestBehavior.cs" />\r
+    <Compile Include="Mvc\ModelClientValidationRegexRule.cs" />\r
+    <Compile Include="Mvc\ModelClientValidationRule.cs" />\r
+    <Compile Include="Mvc\ModelValidationResult.cs" />\r
+    <Compile Include="Mvc\ModelValidator.cs" />\r
+    <Compile Include="Mvc\ModelValidatorProvider.cs" />\r
+    <Compile Include="Mvc\ModelValidatorProviders.cs" />\r
+    <Compile Include="Mvc\RequireHttpsAttribute.cs" />\r
+    <Compile Include="Mvc\HttpRequestExtensions.cs" />\r
+    <Compile Include="Mvc\DataAnnotationsModelMetadataProvider.cs" />\r
+    <Compile Include="Mvc\EmptyModelMetadataProvider.cs" />\r
+    <Compile Include="Mvc\ExpressionUtil\BinaryExpressionFingerprint.cs" />\r
+    <Compile Include="Mvc\ExpressionUtil\CachedExpressionCompiler.cs" />\r
+    <Compile Include="Mvc\ExpressionUtil\ExpressionParser.cs" />\r
+    <Compile Include="Mvc\ModelMetadata.cs" />\r
+    <Compile Include="Mvc\ModelMetadataProvider.cs" />\r
+    <Compile Include="Mvc\ModelMetadataProviders.cs" />\r
+    <Compile Include="Mvc\ExpressionUtil\CompiledExpressionDelegate`2.cs" />\r
+    <Compile Include="Mvc\ExpressionUtil\ConstantExpressionFingerprint.cs" />\r
+    <Compile Include="Mvc\ExpressionUtil\ConditionalExpressionFingerprint.cs" />\r
+    <Compile Include="Mvc\ExpressionUtil\MethodCallExpressionFingerprint.cs" />\r
+    <Compile Include="Mvc\ExpressionUtil\MemberExpressionFingerprint.cs" />\r
+    <Compile Include="Mvc\ExpressionUtil\UnaryExpressionFingerprint.cs" />\r
+    <Compile Include="Mvc\ExpressionUtil\ParserContext.cs" />\r
+    <Compile Include="Mvc\ExpressionUtil\ParameterExpressionFingerprint.cs" />\r
+    <Compile Include="Mvc\ExpressionUtil\HashCodeCombiner.cs" />\r
+    <Compile Include="Mvc\ExpressionUtil\ExpressionFingerprint.cs" />\r
+    <Compile Include="Mvc\ExpressionUtil\FastTrack`2.cs" />\r
+    <Compile Include="Mvc\AreaHelpers.cs" />\r
+    <Compile Include="Mvc\AreaRegistration.cs" />\r
+    <Compile Include="Mvc\AreaRegistrationContext.cs" />\r
+    <Compile Include="Mvc\Error.cs" />\r
+    <Compile Include="Mvc\IRouteWithArea.cs" />\r
+    <Compile Include="Mvc\Async\SingleEntryGate.cs" />\r
+    <Compile Include="Mvc\Html\PartialExtensions.cs" />\r
+    <Compile Include="Mvc\LinqBinaryModelBinder.cs" />\r
+    <Compile Include="Mvc\TryGetValueDelegate.cs" />\r
+    <Compile Include="Mvc\ViewDataInfo.cs" />\r
+    <Compile Include="Mvc\Html\DefaultDisplayTemplates.cs" />\r
+    <Compile Include="Mvc\Html\DefaultEditorTemplates.cs" />\r
+    <Compile Include="Mvc\Html\DisplayExtensions.cs" />\r
+    <Compile Include="Mvc\Html\EditorExtensions.cs" />\r
+    <Compile Include="Mvc\Html\LabelExtensions.cs" />\r
+    <Compile Include="Mvc\Html\TemplateHelpers.cs" />\r
+    <Compile Include="Mvc\HttpPostAttribute.cs" />\r
+    <Compile Include="Mvc\PathHelpers.cs" />\r
+    <Compile Include="Mvc\ExceptionContext.cs" />\r
+    <Compile Include="Mvc\ResultExecutedContext.cs" />\r
+    <Compile Include="Mvc\ResultExecutingContext.cs" />\r
+    <Compile Include="Mvc\TemplateInfo.cs" />\r
+    <Compile Include="Mvc\ValidateAntiForgeryTokenAttribute.cs" />\r
+    <Compile Include="Mvc\HttpAntiForgeryException.cs" />\r
+    <Compile Include="Mvc\JavaScriptResult.cs" />\r
+    <Compile Include="Mvc\ActionDescriptor.cs" />\r
+    <Compile Include="Mvc\ActionMethodDispatcher.cs" />\r
+    <Compile Include="Mvc\ActionMethodSelector.cs" />\r
+    <Compile Include="Mvc\ActionMethodSelectorAttribute.cs" />\r
+    <Compile Include="Mvc\ActionNameSelectorAttribute.cs" />\r
+    <Compile Include="Mvc\AuthorizeAttribute.cs" />\r
+    <Compile Include="Mvc\Ajax\AjaxOptions.cs" />\r
+    <Compile Include="Mvc\Ajax\AjaxExtensions.cs" />\r
+    <Compile Include="Mvc\ActionMethodDispatcherCache.cs" />\r
+    <Compile Include="Mvc\BindAttribute.cs" />\r
+    <Compile Include="Mvc\ControllerBase.cs" />\r
+    <Compile Include="Mvc\ActionNameAttribute.cs" />\r
+    <Compile Include="Mvc\AcceptVerbsAttribute.cs" />\r
+    <Compile Include="Mvc\AjaxHelper`1.cs" />\r
+    <Compile Include="Mvc\HtmlHelper`1.cs" />\r
+    <Compile Include="Mvc\DictionaryHelpers.cs" />\r
+    <Compile Include="Mvc\AjaxRequestExtensions.cs" />\r
+    <Compile Include="Mvc\ModelBinderDictionary.cs" />\r
+    <Compile Include="Mvc\ValueProviderDictionary.cs" />\r
+    <Compile Include="Mvc\ViewContext.cs" />\r
+    <Compile Include="Mvc\ViewTemplateUserControl.cs">\r
+      <SubType>ASPXCodeBehind</SubType>\r
+    </Compile>\r
+    <Compile Include="Mvc\ViewTemplateUserControl`1.cs">\r
+      <SubType>ASPXCodeBehind</SubType>\r
+    </Compile>\r
+    <Compile Include="Mvc\ViewType.cs" />\r
+    <Compile Include="Mvc\ViewTypeControlBuilder.cs" />\r
+    <Compile Include="Mvc\ViewUserControlControlBuilder.cs">\r
+    </Compile>\r
+    <Compile Include="Mvc\ViewPageControlBuilder.cs">\r
+    </Compile>\r
+    <Compile Include="Mvc\ViewTypeParserFilter.cs" />\r
+    <Compile Include="Mvc\DefaultViewLocationCache.cs" />\r
+    <Compile Include="Mvc\FormCollection.cs" />\r
+    <Compile Include="Mvc\HttpPostedFileBaseModelBinder.cs" />\r
+    <Compile Include="Mvc\NullViewLocationCache.cs" />\r
+    <Compile Include="Mvc\ValidateInputAttribute.cs" />\r
+    <Compile Include="Mvc\FileContentResult.cs" />\r
+    <Compile Include="Mvc\FilePathResult.cs" />\r
+    <Compile Include="Mvc\FileResult.cs" />\r
+    <Compile Include="Mvc\FileStreamResult.cs" />\r
+    <Compile Include="Mvc\InputType.cs" />\r
+    <Compile Include="Mvc\ControllerDescriptorCache.cs" />\r
+    <Compile Include="Mvc\ReflectedParameterBindingInfo.cs" />\r
+    <Compile Include="Mvc\ParameterBindingInfo.cs" />\r
+    <Compile Include="Mvc\ReaderWriterCache`2.cs" />\r
+    <Compile Include="Mvc\DescriptorUtil.cs" />\r
+    <Compile Include="Mvc\ReflectedControllerDescriptor.cs" />\r
+    <Compile Include="Mvc\ControllerDescriptor.cs" />\r
+    <Compile Include="Mvc\ActionSelector.cs" />\r
+    <Compile Include="Mvc\ReflectedActionDescriptor.cs" />\r
+    <Compile Include="Mvc\Html\MvcForm.cs" />\r
+    <Compile Include="Mvc\HttpVerbs.cs" />\r
+    <Compile Include="Mvc\DefaultModelBinder.cs" />\r
+    <Compile Include="Mvc\ModelBindingContext.cs" />\r
+    <Compile Include="Mvc\ParameterDescriptor.cs" />\r
+    <Compile Include="Mvc\RouteValuesHelpers.cs" />\r
+    <Compile Include="Mvc\SelectListItem.cs" />\r
+    <Compile Include="Mvc\TagRenderMode.cs" />\r
+    <Compile Include="Mvc\ReflectedParameterDescriptor.cs" />\r
+    <Compile Include="Mvc\ValueProviderResult.cs" />\r
+    <Compile Include="Mvc\CustomModelBinderAttribute.cs" />\r
+    <Compile Include="Mvc\FormMethod.cs" />\r
+    <Compile Include="Mvc\Html\FormExtensions.cs" />\r
+    <Compile Include="Mvc\Html\InputExtensions.cs">\r
+      <SubType>Code</SubType>\r
+    </Compile>\r
+    <Compile Include="Mvc\Html\RenderPartialExtensions.cs" />\r
+    <Compile Include="Mvc\Html\SelectExtensions.cs" />\r
+    <Compile Include="Mvc\Html\TextAreaExtensions.cs" />\r
+    <Compile Include="Mvc\Html\ValidationExtensions.cs" />\r
+    <Compile Include="Mvc\IModelBinder.cs" />\r
+    <Compile Include="Mvc\Html\LinkExtensions.cs" />\r
+    <Compile Include="Mvc\ModelBinderAttribute.cs" />\r
+    <Compile Include="Mvc\ModelBinders.cs" />\r
+    <Compile Include="Mvc\ModelStateDictionary.cs" />\r
+    <Compile Include="Mvc\ModelState.cs" />\r
+    <Compile Include="Mvc\ModelErrorCollection.cs" />\r
+    <Compile Include="Mvc\ModelError.cs" />\r
+    <Compile Include="Mvc\Ajax\InsertionMode.cs" />\r
+    <Compile Include="Mvc\HandleErrorAttribute.cs" />\r
+    <Compile Include="Mvc\HandleErrorInfo.cs" />\r
+    <Compile Include="Mvc\HttpUnauthorizedResult.cs" />\r
+    <Compile Include="Mvc\IActionInvoker.cs" />\r
+    <Compile Include="Mvc\IView.cs" />\r
+    <Compile Include="Mvc\IViewLocationCache.cs" />\r
+    <Compile Include="Mvc\MvcHttpHandler.cs" />\r
+    <Compile Include="Mvc\PartialViewResult.cs" />\r
+    <Compile Include="Mvc\SessionStateTempDataProvider.cs" />\r
+    <Compile Include="Mvc\ITempDataProvider.cs" />\r
+    <Compile Include="Mvc\OutputCacheAttribute.cs" />\r
+    <Compile Include="Mvc\FilterInfo.cs" />\r
+    <Compile Include="GlobalSuppressions.cs" />\r
+    <Compile Include="Mvc\ActionFilterAttribute.cs" />\r
+    <Compile Include="Mvc\ActionResult.cs" />\r
+    <Compile Include="Mvc\AjaxHelper.cs" />\r
+    <Compile Include="Mvc\BuildManagerWrapper.cs" />\r
+    <Compile Include="Mvc\Controller.cs" />\r
+    <Compile Include="Mvc\ControllerActionInvoker.cs" />\r
+    <Compile Include="Mvc\ControllerBuilder.cs" />\r
+    <Compile Include="Mvc\ControllerTypeCache.cs" />\r
+    <Compile Include="Mvc\ContentResult.cs" />\r
+    <Compile Include="Mvc\FilterAttribute.cs" />\r
+    <Compile Include="Mvc\IResultFilter.cs" />\r
+    <Compile Include="Mvc\IExceptionFilter.cs" />\r
+    <Compile Include="Mvc\IAuthorizationFilter.cs" />\r
+    <Compile Include="Mvc\JsonResult.cs" />\r
+    <Compile Include="Mvc\NameValueCollectionExtensions.cs" />\r
+    <Compile Include="Mvc\ViewDataDictionary`1.cs" />\r
+    <Compile Include="Mvc\EmptyResult.cs" />\r
+    <Compile Include="Mvc\MultiSelectList.cs" />\r
+    <Compile Include="Mvc\RedirectResult.cs" />\r
+    <Compile Include="Mvc\RedirectToRouteResult.cs" />\r
+    <Compile Include="Mvc\DefaultControllerFactory.cs" />\r
+    <Compile Include="Mvc\HtmlHelper.cs" />\r
+    <Compile Include="Mvc\IActionFilter.cs" />\r
+    <Compile Include="Mvc\IBuildManager.cs" />\r
+    <Compile Include="Mvc\IController.cs" />\r
+    <Compile Include="Mvc\IControllerFactory.cs" />\r
+    <Compile Include="Mvc\IViewDataContainer.cs" />\r
+    <Compile Include="Mvc\IViewEngine.cs" />\r
+    <Compile Include="Mvc\MvcHandler.cs" />\r
+    <Compile Include="Mvc\MvcRouteHandler.cs" />\r
+    <Compile Include="Mvc\NonActionAttribute.cs" />\r
+    <Compile Include="Mvc\RouteCollectionExtensions.cs" />\r
+    <Compile Include="Mvc\SelectList.cs" />\r
+    <Compile Include="Mvc\TagBuilder.cs" />\r
+    <Compile Include="Mvc\TempDataDictionary.cs" />\r
+    <Compile Include="Mvc\TypeHelpers.cs" />\r
+    <Compile Include="Mvc\UrlHelper.cs" />\r
+    <Compile Include="Mvc\ViewDataDictionary.cs" />\r
+    <Compile Include="Mvc\ViewEngineCollection.cs" />\r
+    <Compile Include="Mvc\ViewEngineResult.cs" />\r
+    <Compile Include="Mvc\ViewEngines.cs" />\r
+    <Compile Include="Mvc\ViewMasterPage.cs">\r
+      <SubType>ASPXCodeBehind</SubType>\r
+    </Compile>\r
+    <Compile Include="Mvc\ViewMasterPage`1.cs">\r
+      <SubType>ASPXCodeBehind</SubType>\r
+    </Compile>\r
+    <Compile Include="Mvc\ViewPage.cs">\r
+      <SubType>ASPXCodeBehind</SubType>\r
+    </Compile>\r
+    <Compile Include="Mvc\ViewPage`1.cs">\r
+      <SubType>ASPXCodeBehind</SubType>\r
+    </Compile>\r
+    <Compile Include="Mvc\ViewResult.cs" />\r
+    <Compile Include="Mvc\ViewResultBase.cs" />\r
+    <Compile Include="Mvc\ViewUserControl.cs">\r
+      <SubType>ASPXCodeBehind</SubType>\r
+    </Compile>\r
+    <Compile Include="Mvc\ViewUserControl`1.cs">\r
+      <SubType>ASPXCodeBehind</SubType>\r
+    </Compile>\r
+    <Compile Include="Mvc\VirtualPathProviderViewEngine.cs" />\r
+    <Compile Include="Mvc\WebFormView.cs" />\r
+    <Compile Include="Mvc\WebFormViewEngine.cs" />\r
+    <Compile Include="Properties\AssemblyInfo.cs" />\r
+    <Compile Include="Mvc\Resources\MvcResources.Designer.cs">\r
+      <AutoGen>True</AutoGen>\r
+      <DesignTime>True</DesignTime>\r
+      <DependentUpon>MvcResources.resx</DependentUpon>\r
+    </Compile>\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <EmbeddedResource Include="Mvc\Resources\MvcResources.resx">\r
+      <Generator>ResXFileCodeGenerator</Generator>\r
+      <LastGenOutput>MvcResources.Designer.cs</LastGenOutput>\r
+      <SubType>Designer</SubType>\r
+    </EmbeddedResource>\r
+  </ItemGroup>\r
+  <ItemGroup>\r
+    <CodeAnalysisDictionary Include="..\CustomDictionary.xml" />\r
+  </ItemGroup>\r
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />\r
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \r
+       Other similar extension points exist, see Microsoft.Common.targets.\r
+  <Target Name="BeforeBuild">\r
+  </Target>\r
+  <Target Name="AfterBuild">\r
+  </Target>\r
+  -->\r
+</Project>
\ No newline at end of file
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc.dll.sources b/mcs/class/System.Web.Mvc2/System.Web.Mvc.dll.sources
new file mode 100644 (file)
index 0000000..9ecb0aa
--- /dev/null
@@ -0,0 +1,279 @@
+../../build/common/Consts.cs
+../../build/common/MonoTODOAttribute.cs
+
+GlobalSuppressions.cs
+Properties/AssemblyInfo.cs
+System.Web.Mvc/AcceptVerbsAttribute.cs
+System.Web.Mvc/ActionDescriptor.cs
+System.Web.Mvc/ActionExecutedContext.cs
+System.Web.Mvc/ActionExecutingContext.cs
+System.Web.Mvc/ActionFilterAttribute.cs
+System.Web.Mvc/ActionMethodDispatcherCache.cs
+System.Web.Mvc/ActionMethodDispatcher.cs
+System.Web.Mvc/ActionMethodSelectorAttribute.cs
+System.Web.Mvc/ActionMethodSelector.cs
+System.Web.Mvc/ActionNameAttribute.cs
+System.Web.Mvc/ActionNameSelectorAttribute.cs
+System.Web.Mvc/ActionResult.cs
+System.Web.Mvc/ActionSelector.cs
+System.Web.Mvc/Ajax/AjaxExtensions.cs
+System.Web.Mvc/Ajax/AjaxOptions.cs
+System.Web.Mvc/AjaxHelper`1.cs
+System.Web.Mvc/AjaxHelper.cs
+System.Web.Mvc/Ajax/InsertionMode.cs
+System.Web.Mvc/AjaxRequestExtensions.cs
+System.Web.Mvc/AntiForgeryData.cs
+System.Web.Mvc/AntiForgeryDataSerializer.cs
+System.Web.Mvc/AreaHelpers.cs
+System.Web.Mvc/AreaRegistrationContext.cs
+System.Web.Mvc/AreaRegistration.cs
+System.Web.Mvc/AssociatedMetadataProvider.cs
+System.Web.Mvc/AssociatedValidatorProvider.cs
+System.Web.Mvc/Async/ActionDescriptorCreator.cs
+System.Web.Mvc/Async/AsyncActionDescriptor.cs
+System.Web.Mvc/Async/AsyncActionMethodSelector.cs
+System.Web.Mvc/Async/AsyncControllerActionInvoker.cs
+System.Web.Mvc/Async/AsyncManager.cs
+System.Web.Mvc/Async/AsyncResultWrapper.cs
+System.Web.Mvc/Async/AsyncUtil.cs
+System.Web.Mvc/Async/AsyncVoid.cs
+System.Web.Mvc/Async/BeginInvokeDelegate.cs
+System.Web.Mvc/AsyncController.cs
+System.Web.Mvc/Async/EndInvokeDelegate`1.cs
+System.Web.Mvc/Async/EndInvokeDelegate.cs
+System.Web.Mvc/Async/IAsyncActionInvoker.cs
+System.Web.Mvc/Async/IAsyncController.cs
+System.Web.Mvc/Async/IAsyncManagerContainer.cs
+System.Web.Mvc/Async/OperationCounter.cs
+System.Web.Mvc/Async/ReflectedAsyncActionDescriptor.cs
+System.Web.Mvc/Async/ReflectedAsyncControllerDescriptor.cs
+System.Web.Mvc/Async/SimpleAsyncResult.cs
+System.Web.Mvc/Async/SingleEntryGate.cs
+System.Web.Mvc/Async/SynchronizationContextUtil.cs
+System.Web.Mvc/Async/SynchronousOperationException.cs
+System.Web.Mvc/AsyncTimeoutAttribute.cs
+System.Web.Mvc/Async/Trigger.cs
+System.Web.Mvc/Async/TriggerListener.cs
+System.Web.Mvc/AuthorizationContext.cs
+System.Web.Mvc/AuthorizeAttribute.cs
+System.Web.Mvc/BindAttribute.cs
+System.Web.Mvc/BuildManagerWrapper.cs
+System.Web.Mvc/ByteArrayModelBinder.cs
+System.Web.Mvc/ChildActionOnlyAttribute.cs
+System.Web.Mvc/ClientDataTypeModelValidatorProvider.cs
+System.Web.Mvc/ContentResult.cs
+System.Web.Mvc/ControllerActionInvoker.cs
+System.Web.Mvc/ControllerBase.cs
+System.Web.Mvc/ControllerBuilder.cs
+System.Web.Mvc/ControllerContext.cs
+System.Web.Mvc/Controller.cs
+System.Web.Mvc/ControllerDescriptorCache.cs
+System.Web.Mvc/ControllerDescriptor.cs
+System.Web.Mvc/ControllerTypeCache.cs
+System.Web.Mvc/CustomModelBinderAttribute.cs
+System.Web.Mvc/DataAnnotationsModelMetadata.cs
+System.Web.Mvc/DataAnnotationsModelMetadataProvider.cs
+System.Web.Mvc/DataAnnotationsModelValidator`1.cs
+System.Web.Mvc/DataAnnotationsModelValidator.cs
+System.Web.Mvc/DataAnnotationsModelValidatorProvider.cs
+System.Web.Mvc/DataErrorInfoModelValidatorProvider.cs
+System.Web.Mvc/DefaultControllerFactory.cs
+System.Web.Mvc/DefaultModelBinder.cs
+System.Web.Mvc/DefaultViewLocationCache.cs
+System.Web.Mvc/DescriptorUtil.cs
+System.Web.Mvc/DictionaryHelpers.cs
+System.Web.Mvc/DictionaryValueProvider`1.cs
+System.Web.Mvc/DynamicTypeGenerator.cs
+System.Web.Mvc/EmptyModelMetadataProvider.cs
+System.Web.Mvc/EmptyModelValidatorProvider.cs
+System.Web.Mvc/EmptyResult.cs
+System.Web.Mvc/Error.cs
+System.Web.Mvc/ExceptionContext.cs
+System.Web.Mvc/ExpressionHelper.cs
+System.Web.Mvc/ExpressionUtil/BinaryExpressionFingerprint.cs
+System.Web.Mvc/ExpressionUtil/CachedExpressionCompiler.cs
+System.Web.Mvc/ExpressionUtil/CompiledExpressionDelegate`2.cs
+System.Web.Mvc/ExpressionUtil/ConditionalExpressionFingerprint.cs
+System.Web.Mvc/ExpressionUtil/ConstantExpressionFingerprint.cs
+System.Web.Mvc/ExpressionUtil/ExpressionFingerprint.cs
+System.Web.Mvc/ExpressionUtil/ExpressionParser.cs
+System.Web.Mvc/ExpressionUtil/FastTrack`2.cs
+System.Web.Mvc/ExpressionUtil/HashCodeCombiner.cs
+System.Web.Mvc/ExpressionUtil/MemberExpressionFingerprint.cs
+System.Web.Mvc/ExpressionUtil/MethodCallExpressionFingerprint.cs
+System.Web.Mvc/ExpressionUtil/ParameterExpressionFingerprint.cs
+System.Web.Mvc/ExpressionUtil/ParserContext.cs
+System.Web.Mvc/ExpressionUtil/UnaryExpressionFingerprint.cs
+System.Web.Mvc/FieldValidationMetadata.cs
+System.Web.Mvc/FileContentResult.cs
+System.Web.Mvc/FilePathResult.cs
+System.Web.Mvc/FileResult.cs
+System.Web.Mvc/FileStreamResult.cs
+System.Web.Mvc/FilterAttribute.cs
+System.Web.Mvc/FilterInfo.cs
+System.Web.Mvc/FormCollection.cs
+System.Web.Mvc/FormContext.cs
+System.Web.Mvc/FormMethod.cs
+System.Web.Mvc/FormValueProvider.cs
+System.Web.Mvc/FormValueProviderFactory.cs
+System.Web.Mvc/HandleErrorAttribute.cs
+System.Web.Mvc/HandleErrorInfo.cs
+System.Web.Mvc/HiddenInputAttribute.cs
+System.Web.Mvc/Html/ChildActionExtensions.cs
+System.Web.Mvc/Html/DefaultDisplayTemplates.cs
+System.Web.Mvc/Html/DefaultEditorTemplates.cs
+System.Web.Mvc/Html/DisplayExtensions.cs
+System.Web.Mvc/Html/DisplayTextExtensions.cs
+System.Web.Mvc/Html/EditorExtensions.cs
+System.Web.Mvc/Html/FormExtensions.cs
+System.Web.Mvc/HtmlHelper`1.cs
+System.Web.Mvc/HtmlHelper.cs
+System.Web.Mvc/Html/InputExtensions.cs
+System.Web.Mvc/Html/LabelExtensions.cs
+System.Web.Mvc/Html/LinkExtensions.cs
+System.Web.Mvc/Html/MvcForm.cs
+System.Web.Mvc/Html/PartialExtensions.cs
+System.Web.Mvc/Html/RenderPartialExtensions.cs
+System.Web.Mvc/Html/SelectExtensions.cs
+System.Web.Mvc/Html/TemplateHelpers.cs
+System.Web.Mvc/Html/TextAreaExtensions.cs
+System.Web.Mvc/Html/ValidationExtensions.cs
+System.Web.Mvc/HttpAntiForgeryException.cs
+System.Web.Mvc/HttpDeleteAttribute.cs
+System.Web.Mvc/HttpFileCollectionValueProvider.cs
+System.Web.Mvc/HttpFileCollectionValueProviderFactory.cs
+System.Web.Mvc/HttpGetAttribute.cs
+System.Web.Mvc/HttpHandlerUtil.cs
+System.Web.Mvc/HttpPostAttribute.cs
+System.Web.Mvc/HttpPostedFileBaseModelBinder.cs
+System.Web.Mvc/HttpPutAttribute.cs
+System.Web.Mvc/HttpRequestExtensions.cs
+System.Web.Mvc/HttpUnauthorizedResult.cs
+System.Web.Mvc/HttpVerbs.cs
+System.Web.Mvc/IActionFilter.cs
+System.Web.Mvc/IActionInvoker.cs
+System.Web.Mvc/IAuthorizationFilter.cs
+System.Web.Mvc/IBuildManager.cs
+System.Web.Mvc/IController.cs
+System.Web.Mvc/IControllerFactory.cs
+System.Web.Mvc/IExceptionFilter.cs
+System.Web.Mvc/IModelBinder.cs
+System.Web.Mvc/InputType.cs
+System.Web.Mvc/IResultFilter.cs
+System.Web.Mvc/IRouteWithArea.cs
+System.Web.Mvc/ITempDataProvider.cs
+System.Web.Mvc/IValueProvider.cs
+System.Web.Mvc/IView.cs
+System.Web.Mvc/IViewDataContainer.cs
+System.Web.Mvc/IViewEngine.cs
+System.Web.Mvc/IViewLocationCache.cs
+System.Web.Mvc/JavaScriptResult.cs
+System.Web.Mvc/JsonRequestBehavior.cs
+System.Web.Mvc/JsonResult.cs
+System.Web.Mvc/LinqBinaryModelBinder.cs
+System.Web.Mvc/ModelBinderAttribute.cs
+System.Web.Mvc/ModelBinderDictionary.cs
+System.Web.Mvc/ModelBinders.cs
+System.Web.Mvc/ModelBindingContext.cs
+System.Web.Mvc/ModelClientValidationRangeRule.cs
+System.Web.Mvc/ModelClientValidationRegexRule.cs
+System.Web.Mvc/ModelClientValidationRequiredRule.cs
+System.Web.Mvc/ModelClientValidationRule.cs
+System.Web.Mvc/ModelClientValidationStringLengthRule.cs
+System.Web.Mvc/ModelErrorCollection.cs
+System.Web.Mvc/ModelError.cs
+System.Web.Mvc/ModelMetadata.cs
+System.Web.Mvc/ModelMetadataProvider.cs
+System.Web.Mvc/ModelMetadataProviders.cs
+System.Web.Mvc/ModelState.cs
+System.Web.Mvc/ModelStateDictionary.cs
+System.Web.Mvc/ModelValidationResult.cs
+System.Web.Mvc/ModelValidator.cs
+System.Web.Mvc/ModelValidatorProviderCollection.cs
+System.Web.Mvc/ModelValidatorProvider.cs
+System.Web.Mvc/ModelValidatorProviders.cs
+System.Web.Mvc/MultiSelectList.cs
+System.Web.Mvc/MvcHandler.cs
+System.Web.Mvc/MvcHtmlString.cs
+System.Web.Mvc/MvcHttpHandler.cs
+System.Web.Mvc/MvcRouteHandler.cs
+System.Web.Mvc/NameValueCollectionExtensions.cs
+System.Web.Mvc/NameValueCollectionValueProvider.cs
+System.Web.Mvc/NoAsyncTimeoutAttribute.cs
+System.Web.Mvc/NonActionAttribute.cs
+System.Web.Mvc/NullViewLocationCache.cs
+System.Web.Mvc/OutputCacheAttribute.cs
+System.Web.Mvc/ParameterBindingInfo.cs
+System.Web.Mvc/ParameterDescriptor.cs
+System.Web.Mvc/ParameterInfoUtil.cs
+System.Web.Mvc/PartialViewResult.cs
+System.Web.Mvc/PathHelpers.cs
+System.Web.Mvc/QueryStringValueProvider.cs
+System.Web.Mvc/QueryStringValueProviderFactory.cs
+System.Web.Mvc/RangeAttributeAdapter.cs
+System.Web.Mvc/ReaderWriterCache`2.cs
+System.Web.Mvc/RedirectResult.cs
+System.Web.Mvc/RedirectToRouteResult.cs
+System.Web.Mvc/ReflectedActionDescriptor.cs
+System.Web.Mvc/ReflectedControllerDescriptor.cs
+System.Web.Mvc/ReflectedParameterBindingInfo.cs
+System.Web.Mvc/ReflectedParameterDescriptor.cs
+System.Web.Mvc/RegularExpressionAttributeAdapter.cs
+System.Web.Mvc/RequiredAttributeAdapter.cs
+System.Web.Mvc/RequireHttpsAttribute.cs
+System.Web.Mvc/Resources/MvcResources.Designer.cs
+System.Web.Mvc/ResultExecutedContext.cs
+System.Web.Mvc/ResultExecutingContext.cs
+System.Web.Mvc/RouteCollectionExtensions.cs
+System.Web.Mvc/RouteDataValueProvider.cs
+System.Web.Mvc/RouteDataValueProviderFactory.cs
+System.Web.Mvc/RouteValuesHelpers.cs
+System.Web.Mvc/SelectList.cs
+System.Web.Mvc/SelectListItem.cs
+System.Web.Mvc/SessionStateTempDataProvider.cs
+System.Web.Mvc/StringLengthAttributeAdapter.cs
+System.Web.Mvc/TagBuilder.cs
+System.Web.Mvc/TagRenderMode.cs
+System.Web.Mvc/TempDataDictionary.cs
+System.Web.Mvc/TemplateInfo.cs
+System.Web.Mvc/TryGetValueDelegate.cs
+System.Web.Mvc/TypeCacheSerializer.cs
+System.Web.Mvc/TypeCacheUtil.cs
+System.Web.Mvc/TypeDescriptorHelper.cs
+System.Web.Mvc/TypeHelpers.cs
+System.Web.Mvc/UrlHelper.cs
+System.Web.Mvc/UrlParameter.cs
+System.Web.Mvc/ValidateAntiForgeryTokenAttribute.cs
+System.Web.Mvc/ValidateInputAttribute.cs
+System.Web.Mvc/ValueProviderCollection.cs
+System.Web.Mvc/ValueProviderDictionary.cs
+System.Web.Mvc/ValueProviderFactories.cs
+System.Web.Mvc/ValueProviderFactoryCollection.cs
+System.Web.Mvc/ValueProviderFactory.cs
+System.Web.Mvc/ValueProviderResult.cs
+System.Web.Mvc/ValueProviderUtil.cs
+System.Web.Mvc/ViewContext.cs
+System.Web.Mvc/ViewDataDictionary`1.cs
+System.Web.Mvc/ViewDataDictionary.cs
+System.Web.Mvc/ViewDataInfo.cs
+System.Web.Mvc/ViewEngineCollection.cs
+System.Web.Mvc/ViewEngineResult.cs
+System.Web.Mvc/ViewEngines.cs
+System.Web.Mvc/ViewMasterPage`1.cs
+System.Web.Mvc/ViewMasterPage.cs
+System.Web.Mvc/ViewPage`1.cs
+System.Web.Mvc/ViewPageControlBuilder.cs
+System.Web.Mvc/ViewPage.cs
+System.Web.Mvc/ViewResultBase.cs
+System.Web.Mvc/ViewResult.cs
+System.Web.Mvc/ViewTemplateUserControl`1.cs
+System.Web.Mvc/ViewTemplateUserControl.cs
+System.Web.Mvc/ViewTypeControlBuilder.cs
+System.Web.Mvc/ViewType.cs
+System.Web.Mvc/ViewTypeParserFilter.cs
+System.Web.Mvc/ViewUserControl`1.cs
+System.Web.Mvc/ViewUserControlControlBuilder.cs
+System.Web.Mvc/ViewUserControl.cs
+System.Web.Mvc/VirtualPathProviderViewEngine.cs
+System.Web.Mvc/WebFormView.cs
+System.Web.Mvc/WebFormViewEngine.cs
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/AcceptVerbsAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/AcceptVerbsAttribute.cs
new file mode 100644 (file)
index 0000000..c0924a4
--- /dev/null
@@ -0,0 +1,71 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Collections.ObjectModel;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Linq;\r
+    using System.Reflection;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    [SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments",\r
+        Justification = "The accessor is exposed as an ICollection<string>.")]\r
+    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\r
+    public sealed class AcceptVerbsAttribute : ActionMethodSelectorAttribute {\r
+        public AcceptVerbsAttribute(HttpVerbs verbs)\r
+            : this(EnumToArray(verbs)) {\r
+        }\r
+\r
+        public AcceptVerbsAttribute(params string[] verbs) {\r
+            if (verbs == null || verbs.Length == 0) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "verbs");\r
+            }\r
+\r
+            Verbs = new ReadOnlyCollection<string>(verbs);\r
+        }\r
+\r
+        public ICollection<string> Verbs {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        private static void AddEntryToList(HttpVerbs verbs, HttpVerbs match, List<string> verbList, string entryText) {\r
+            if ((verbs & match) != 0) {\r
+                verbList.Add(entryText);\r
+            }\r
+        }\r
+\r
+        internal static string[] EnumToArray(HttpVerbs verbs) {\r
+            List<string> verbList = new List<string>();\r
+\r
+            AddEntryToList(verbs, HttpVerbs.Get, verbList, "GET");\r
+            AddEntryToList(verbs, HttpVerbs.Post, verbList, "POST");\r
+            AddEntryToList(verbs, HttpVerbs.Put, verbList, "PUT");\r
+            AddEntryToList(verbs, HttpVerbs.Delete, verbList, "DELETE");\r
+            AddEntryToList(verbs, HttpVerbs.Head, verbList, "HEAD");\r
+\r
+            return verbList.ToArray();\r
+        }\r
+\r
+        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) {\r
+            if (controllerContext == null) {\r
+                throw new ArgumentNullException("controllerContext");\r
+            }\r
+\r
+            string incomingVerb = controllerContext.HttpContext.Request.GetHttpMethodOverride();\r
+\r
+            return Verbs.Contains(incomingVerb, StringComparer.OrdinalIgnoreCase);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionDescriptor.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionDescriptor.cs
new file mode 100644 (file)
index 0000000..4041d79
--- /dev/null
@@ -0,0 +1,230 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+    using System.Reflection;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public abstract class ActionDescriptor : ICustomAttributeProvider {\r
+\r
+        private readonly static AllowMultipleAttributesCache _allowMultiplAttributesCache = new AllowMultipleAttributesCache();\r
+        private readonly static ActionMethodDispatcherCache _staticDispatcherCache = new ActionMethodDispatcherCache();\r
+        private ActionMethodDispatcherCache _instanceDispatcherCache;\r
+\r
+        private static readonly ActionSelector[] _emptySelectors = new ActionSelector[0];\r
+\r
+        public abstract string ActionName {\r
+            get;\r
+        }\r
+\r
+        public abstract ControllerDescriptor ControllerDescriptor {\r
+            get;\r
+        }\r
+\r
+        internal ActionMethodDispatcherCache DispatcherCache {\r
+            get {\r
+                if (_instanceDispatcherCache == null) {\r
+                    _instanceDispatcherCache = _staticDispatcherCache;\r
+                }\r
+                return _instanceDispatcherCache;\r
+            }\r
+            set {\r
+                _instanceDispatcherCache = value;\r
+            }\r
+        }\r
+\r
+        public abstract object Execute(ControllerContext controllerContext, IDictionary<string, object> parameters);\r
+\r
+        internal static object ExtractParameterFromDictionary(ParameterInfo parameterInfo, IDictionary<string, object> parameters, MethodInfo methodInfo) {\r
+            object value;\r
+\r
+            if (!parameters.TryGetValue(parameterInfo.Name, out value)) {\r
+                // the key should always be present, even if the parameter value is null\r
+                string message = String.Format(CultureInfo.CurrentUICulture, MvcResources.ReflectedActionDescriptor_ParameterNotInDictionary,\r
+                    parameterInfo.Name, parameterInfo.ParameterType, methodInfo, methodInfo.DeclaringType);\r
+                throw new ArgumentException(message, "parameters");\r
+            }\r
+\r
+            if (value == null && !TypeHelpers.TypeAllowsNullValue(parameterInfo.ParameterType)) {\r
+                // tried to pass a null value for a non-nullable parameter type\r
+                string message = String.Format(CultureInfo.CurrentUICulture, MvcResources.ReflectedActionDescriptor_ParameterCannotBeNull,\r
+                    parameterInfo.Name, parameterInfo.ParameterType, methodInfo, methodInfo.DeclaringType);\r
+                throw new ArgumentException(message, "parameters");\r
+            }\r
+\r
+            if (value != null && !parameterInfo.ParameterType.IsInstanceOfType(value)) {\r
+                // value was supplied but is not of the proper type\r
+                string message = String.Format(CultureInfo.CurrentUICulture, MvcResources.ReflectedActionDescriptor_ParameterValueHasWrongType,\r
+                    parameterInfo.Name, methodInfo, methodInfo.DeclaringType, value.GetType(), parameterInfo.ParameterType);\r
+                throw new ArgumentException(message, "parameters");\r
+            }\r
+\r
+            return value;\r
+        }\r
+\r
+        internal static object ExtractParameterOrDefaultFromDictionary(ParameterInfo parameterInfo, IDictionary<string, object> parameters) {\r
+            Type parameterType = parameterInfo.ParameterType;\r
+\r
+            object value;\r
+            parameters.TryGetValue(parameterInfo.Name, out value);\r
+\r
+            // if wrong type, replace with default instance\r
+            if (parameterType.IsInstanceOfType(value)) {\r
+                return value;\r
+            }\r
+            else {\r
+                object defaultValue;\r
+                if (ParameterInfoUtil.TryGetDefaultValue(parameterInfo, out defaultValue)) {\r
+                    return defaultValue;\r
+                }\r
+                else {\r
+                    return TypeHelpers.GetDefaultValue(parameterType);\r
+                }\r
+            }\r
+        }\r
+\r
+        public virtual object[] GetCustomAttributes(bool inherit) {\r
+            return GetCustomAttributes(typeof(object), inherit);\r
+        }\r
+\r
+        public virtual object[] GetCustomAttributes(Type attributeType, bool inherit) {\r
+            if (attributeType == null) {\r
+                throw new ArgumentNullException("attributeType");\r
+            }\r
+\r
+            return (object[])Array.CreateInstance(attributeType, 0);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",\r
+            Justification = "This method may perform non-trivial work.")]\r
+        public virtual FilterInfo GetFilters() {\r
+            return new FilterInfo();\r
+        }\r
+\r
+        internal static FilterInfo GetFilters(MethodInfo methodInfo) {\r
+            // Enumerable.OrderBy() is a stable sort, so this method preserves scope ordering.\r
+            FilterAttribute[] typeFilters = (FilterAttribute[])methodInfo.ReflectedType.GetCustomAttributes(typeof(FilterAttribute), true /* inherit */);\r
+            FilterAttribute[] methodFilters = (FilterAttribute[])methodInfo.GetCustomAttributes(typeof(FilterAttribute), true /* inherit */);\r
+            List<FilterAttribute> orderedFilters = RemoveOverriddenFilters(typeFilters.Concat(methodFilters)).OrderBy(attr => attr.Order).ToList();\r
+\r
+            FilterInfo filterInfo = new FilterInfo();\r
+            MergeFiltersIntoList(orderedFilters, filterInfo.ActionFilters);\r
+            MergeFiltersIntoList(orderedFilters, filterInfo.AuthorizationFilters);\r
+            MergeFiltersIntoList(orderedFilters, filterInfo.ExceptionFilters);\r
+            MergeFiltersIntoList(orderedFilters, filterInfo.ResultFilters);\r
+            return filterInfo;\r
+        }\r
+\r
+        public abstract ParameterDescriptor[] GetParameters();\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",\r
+            Justification = "This method may perform non-trivial work.")]\r
+        public virtual ICollection<ActionSelector> GetSelectors() {\r
+            return _emptySelectors;\r
+        }\r
+\r
+        public virtual bool IsDefined(Type attributeType, bool inherit) {\r
+            if (attributeType == null) {\r
+                throw new ArgumentNullException("attributeType");\r
+            }\r
+\r
+            return false;\r
+        }\r
+\r
+        internal static void MergeFiltersIntoList<TFilter>(IList<FilterAttribute> allFilters, IList<TFilter> destFilters) where TFilter : class {\r
+            foreach (FilterAttribute filter in allFilters) {\r
+                TFilter castFilter = filter as TFilter;\r
+                if (castFilter != null) {\r
+                    destFilters.Add(castFilter);\r
+                }\r
+            }\r
+        }\r
+\r
+        internal static IEnumerable<FilterAttribute> RemoveOverriddenFilters(IEnumerable<FilterAttribute> filters) {\r
+            // If an attribute is declared on both the controller and on an action method and that attribute's\r
+            // type has AllowMultiple = false (which is the default for attributes), we should ignore the attributes\r
+            // declared on the controller. The CLR's reflection implementation follows a similar algorithm when it\r
+            // encounters an overridden virtual method where both the base and the override contain some\r
+            // AllowMultiple = false attribute.\r
+\r
+            // Key = attribute type\r
+            // Value = -1 if AllowMultiple true, last index of this attribute type if AllowMultiple false\r
+            Dictionary<Type, int> attrsIndexes = new Dictionary<Type, int>();\r
+\r
+            FilterAttribute[] filtersList = filters.ToArray();\r
+            for (int i = 0; i < filtersList.Length; i++) {\r
+                FilterAttribute filter = filtersList[i];\r
+                Type filterType = filter.GetType();\r
+\r
+                int lastIndex;\r
+                if (attrsIndexes.TryGetValue(filterType, out lastIndex)) {\r
+                    if (lastIndex >= 0) {\r
+                        // this filter already exists and AllowMultiple = false, so clear last entry\r
+                        filtersList[lastIndex] = null;\r
+                        attrsIndexes[filterType] = i;\r
+                    }\r
+                }\r
+                else {\r
+                    // not found - add to dictionary\r
+                    // exactly one AttributeUsageAttribute will always be present\r
+                    bool allowMultiple = _allowMultiplAttributesCache.IsMultiUseAttribute(filterType);\r
+                    attrsIndexes[filterType] = (allowMultiple) ? -1 : i;\r
+                }\r
+            }\r
+\r
+            // any duplicated attributes have now been nulled out, so just return remaining attributes\r
+            return filtersList.Where(attr => attr != null);\r
+        }\r
+\r
+        internal static string VerifyActionMethodIsCallable(MethodInfo methodInfo) {\r
+            // we can't call instance methods where the 'this' parameter is a type other than ControllerBase\r
+            if (!methodInfo.IsStatic && !typeof(ControllerBase).IsAssignableFrom(methodInfo.ReflectedType)) {\r
+                return String.Format(CultureInfo.CurrentUICulture, MvcResources.ReflectedActionDescriptor_CannotCallInstanceMethodOnNonControllerType,\r
+                    methodInfo, methodInfo.ReflectedType.FullName);\r
+            }\r
+\r
+            // we can't call methods with open generic type parameters\r
+            if (methodInfo.ContainsGenericParameters) {\r
+                return String.Format(CultureInfo.CurrentUICulture, MvcResources.ReflectedActionDescriptor_CannotCallOpenGenericMethods,\r
+                    methodInfo, methodInfo.ReflectedType.FullName);\r
+            }\r
+\r
+            // we can't call methods with ref/out parameters\r
+            ParameterInfo[] parameterInfos = methodInfo.GetParameters();\r
+            foreach (ParameterInfo parameterInfo in parameterInfos) {\r
+                if (parameterInfo.IsOut || parameterInfo.ParameterType.IsByRef) {\r
+                    return String.Format(CultureInfo.CurrentUICulture, MvcResources.ReflectedActionDescriptor_CannotCallMethodsWithOutOrRefParameters,\r
+                        methodInfo, methodInfo.ReflectedType.FullName, parameterInfo);\r
+                }\r
+            }\r
+\r
+            // we can call this method\r
+            return null;\r
+        }\r
+\r
+        private sealed class AllowMultipleAttributesCache : ReaderWriterCache<Type, bool> {\r
+            public bool IsMultiUseAttribute(Type attributeType) {\r
+                return FetchOrCreateItem(attributeType, () => AttributeUsageAllowsMultiple(attributeType));\r
+            }\r
+\r
+            private static bool AttributeUsageAllowsMultiple(Type type) {\r
+                return (((AttributeUsageAttribute[])type.GetCustomAttributes(typeof(AttributeUsageAttribute), true))[0]).AllowMultiple;\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionExecutedContext.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionExecutedContext.cs
new file mode 100644 (file)
index 0000000..1dfaa17
--- /dev/null
@@ -0,0 +1,68 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+\r
+    public class ActionExecutedContext : ControllerContext {\r
+\r
+        private ActionResult _result;\r
+\r
+        // parameterless constructor used for mocking\r
+        public ActionExecutedContext() {\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors",\r
+            Justification = "The virtual property setters are only to support mocking frameworks, in which case this constructor shouldn't be called anyway.")]\r
+        public ActionExecutedContext(ControllerContext controllerContext, ActionDescriptor actionDescriptor, bool canceled, Exception exception)\r
+            : base(controllerContext) {\r
+            if (actionDescriptor == null) {\r
+                throw new ArgumentNullException("actionDescriptor");\r
+            }\r
+\r
+            ActionDescriptor = actionDescriptor;\r
+            Canceled = canceled;\r
+            Exception = exception;\r
+        }\r
+\r
+        public virtual ActionDescriptor ActionDescriptor {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public virtual bool Canceled {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public virtual Exception Exception {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public bool ExceptionHandled {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public ActionResult Result {\r
+            get {\r
+                return _result ?? EmptyResult.Instance;\r
+            }\r
+            set {\r
+                _result = value;\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionExecutingContext.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionExecutingContext.cs
new file mode 100644 (file)
index 0000000..4cc21e0
--- /dev/null
@@ -0,0 +1,57 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Diagnostics.CodeAnalysis;\r
+\r
+    public class ActionExecutingContext : ControllerContext {\r
+\r
+        // parameterless constructor used for mocking\r
+        public ActionExecutingContext() {\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors",\r
+            Justification = "The virtual property setters are only to support mocking frameworks, in which case this constructor shouldn't be called anyway.")]\r
+        public ActionExecutingContext(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary<string, object> actionParameters)\r
+            : base(controllerContext) {\r
+            if (actionDescriptor == null) {\r
+                throw new ArgumentNullException("actionDescriptor");\r
+            }\r
+            if (actionParameters == null) {\r
+                throw new ArgumentNullException("actionParameters");\r
+            }\r
+\r
+            ActionDescriptor = actionDescriptor;\r
+            ActionParameters = actionParameters;\r
+        }\r
+\r
+        public virtual ActionDescriptor ActionDescriptor {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly",\r
+            Justification = "The property setter is only here to support mocking this type and should not be called at runtime.")]\r
+        public virtual IDictionary<string, object> ActionParameters {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public ActionResult Result {\r
+            get;\r
+            set;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionFilterAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionFilterAttribute.cs
new file mode 100644 (file)
index 0000000..1069ccc
--- /dev/null
@@ -0,0 +1,34 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\r
+    public abstract class ActionFilterAttribute : FilterAttribute, IActionFilter, IResultFilter {\r
+\r
+        // The OnXxx() methods are virtual rather than abstract so that a developer need override\r
+        // only the ones that interest him.\r
+\r
+        public virtual void OnActionExecuting(ActionExecutingContext filterContext) {\r
+        }\r
+\r
+        public virtual void OnActionExecuted(ActionExecutedContext filterContext) {\r
+        }\r
+\r
+        public virtual void OnResultExecuting(ResultExecutingContext filterContext) {\r
+        }\r
+\r
+        public virtual void OnResultExecuted(ResultExecutedContext filterContext) {\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionMethodDispatcher.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionMethodDispatcher.cs
new file mode 100644 (file)
index 0000000..0adafe2
--- /dev/null
@@ -0,0 +1,86 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Linq.Expressions;\r
+    using System.Reflection;\r
+\r
+    // The methods in this class don't perform error checking; that is the responsibility of the\r
+    // caller.\r
+    internal sealed class ActionMethodDispatcher {\r
+\r
+        private delegate object ActionExecutor(ControllerBase controller, object[] parameters);\r
+        private delegate void VoidActionExecutor(ControllerBase controller, object[] parameters);\r
+\r
+        private ActionExecutor _executor;\r
+\r
+        public ActionMethodDispatcher(MethodInfo methodInfo) {\r
+            _executor = GetExecutor(methodInfo);\r
+            MethodInfo = methodInfo;\r
+        }\r
+\r
+        public MethodInfo MethodInfo {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public object Execute(ControllerBase controller, object[] parameters) {\r
+            return _executor(controller, parameters);\r
+        }\r
+\r
+        private static ActionExecutor GetExecutor(MethodInfo methodInfo) {\r
+            // Parameters to executor\r
+            ParameterExpression controllerParameter = Expression.Parameter(typeof(ControllerBase), "controller");\r
+            ParameterExpression parametersParameter = Expression.Parameter(typeof(object[]), "parameters");\r
+\r
+            // Build parameter list\r
+            List<Expression> parameters = new List<Expression>();\r
+            ParameterInfo[] paramInfos = methodInfo.GetParameters();\r
+            for (int i = 0; i < paramInfos.Length; i++) {\r
+                ParameterInfo paramInfo = paramInfos[i];\r
+                BinaryExpression valueObj = Expression.ArrayIndex(parametersParameter, Expression.Constant(i));\r
+                UnaryExpression valueCast = Expression.Convert(valueObj, paramInfo.ParameterType);\r
+\r
+                // valueCast is "(Ti) parameters[i]"\r
+                parameters.Add(valueCast);\r
+            }\r
+\r
+            // Call method\r
+            UnaryExpression instanceCast = (!methodInfo.IsStatic) ? Expression.Convert(controllerParameter, methodInfo.ReflectedType) : null;\r
+            MethodCallExpression methodCall = methodCall = Expression.Call(instanceCast, methodInfo, parameters);\r
+\r
+            // methodCall is "((TController) controller) method((T0) parameters[0], (T1) parameters[1], ...)"\r
+            // Create function\r
+            if (methodCall.Type == typeof(void)) {\r
+                Expression<VoidActionExecutor> lambda = Expression.Lambda<VoidActionExecutor>(methodCall, controllerParameter, parametersParameter);\r
+                VoidActionExecutor voidExecutor = lambda.Compile();\r
+                return WrapVoidAction(voidExecutor);\r
+            }\r
+            else {\r
+                // must coerce methodCall to match ActionExecutor signature\r
+                UnaryExpression castMethodCall = Expression.Convert(methodCall, typeof(object));\r
+                Expression<ActionExecutor> lambda = Expression.Lambda<ActionExecutor>(castMethodCall, controllerParameter, parametersParameter);\r
+                return lambda.Compile();\r
+            }\r
+        }\r
+\r
+        private static ActionExecutor WrapVoidAction(VoidActionExecutor executor) {\r
+            return delegate(ControllerBase controller, object[] parameters) {\r
+                executor(controller, parameters);\r
+                return null;\r
+            };\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionMethodDispatcherCache.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionMethodDispatcherCache.cs
new file mode 100644 (file)
index 0000000..61b5333
--- /dev/null
@@ -0,0 +1,27 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Reflection;\r
+\r
+    internal sealed class ActionMethodDispatcherCache : ReaderWriterCache<MethodInfo,ActionMethodDispatcher> {\r
+\r
+        public ActionMethodDispatcherCache() {\r
+        }\r
+\r
+        public ActionMethodDispatcher GetDispatcher(MethodInfo methodInfo) {\r
+            return FetchOrCreateItem(methodInfo, () => new ActionMethodDispatcher(methodInfo));\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionMethodSelector.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionMethodSelector.cs
new file mode 100644 (file)
index 0000000..4b765db
--- /dev/null
@@ -0,0 +1,125 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+    using System.Reflection;\r
+    using System.Text;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    internal sealed class ActionMethodSelector {\r
+\r
+        public ActionMethodSelector(Type controllerType) {\r
+            ControllerType = controllerType;\r
+            PopulateLookupTables();\r
+        }\r
+\r
+        public Type ControllerType {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public MethodInfo[] AliasedMethods {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public ILookup<string, MethodInfo> NonAliasedMethods {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        private AmbiguousMatchException CreateAmbiguousMatchException(List<MethodInfo> ambiguousMethods, string actionName) {\r
+            StringBuilder exceptionMessageBuilder = new StringBuilder();\r
+            foreach (MethodInfo methodInfo in ambiguousMethods) {\r
+                string controllerAction = Convert.ToString(methodInfo, CultureInfo.CurrentUICulture);\r
+                string controllerType = methodInfo.DeclaringType.FullName;\r
+                exceptionMessageBuilder.AppendLine();\r
+                exceptionMessageBuilder.AppendFormat(CultureInfo.CurrentUICulture, MvcResources.ActionMethodSelector_AmbiguousMatchType, controllerAction, controllerType);\r
+            }\r
+            string message = String.Format(CultureInfo.CurrentUICulture, MvcResources.ActionMethodSelector_AmbiguousMatch,\r
+                actionName, ControllerType.Name, exceptionMessageBuilder);\r
+            return new AmbiguousMatchException(message);\r
+        }\r
+\r
+        public MethodInfo FindActionMethod(ControllerContext controllerContext, string actionName) {\r
+            List<MethodInfo> methodsMatchingName = GetMatchingAliasedMethods(controllerContext, actionName);\r
+            methodsMatchingName.AddRange(NonAliasedMethods[actionName]);\r
+            List<MethodInfo> finalMethods = RunSelectionFilters(controllerContext, methodsMatchingName);\r
+\r
+            switch (finalMethods.Count) {\r
+                case 0:\r
+                    return null;\r
+\r
+                case 1:\r
+                    return finalMethods[0];\r
+\r
+                default:\r
+                    throw CreateAmbiguousMatchException(finalMethods, actionName);\r
+            }\r
+        }\r
+\r
+        internal List<MethodInfo> GetMatchingAliasedMethods(ControllerContext controllerContext, string actionName) {\r
+            // find all aliased methods which are opting in to this request\r
+            // to opt in, all attributes defined on the method must return true\r
+\r
+            var methods = from methodInfo in AliasedMethods\r
+                          let attrs = (ActionNameSelectorAttribute[])methodInfo.GetCustomAttributes(typeof(ActionNameSelectorAttribute), true /* inherit */)\r
+                          where attrs.All(attr => attr.IsValidName(controllerContext, actionName, methodInfo))\r
+                          select methodInfo;\r
+            return methods.ToList();\r
+        }\r
+\r
+        private static bool IsMethodDecoratedWithAliasingAttribute(MethodInfo methodInfo) {\r
+            return methodInfo.IsDefined(typeof(ActionNameSelectorAttribute), true /* inherit */);\r
+        }\r
+\r
+        private static bool IsValidActionMethod(MethodInfo methodInfo) {\r
+            return !(methodInfo.IsSpecialName ||\r
+                     methodInfo.GetBaseDefinition().DeclaringType.IsAssignableFrom(typeof(Controller)));\r
+        }\r
+\r
+        private void PopulateLookupTables() {\r
+            MethodInfo[] allMethods = ControllerType.GetMethods(BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public);\r
+            MethodInfo[] actionMethods = Array.FindAll(allMethods, IsValidActionMethod);\r
+\r
+            AliasedMethods = Array.FindAll(actionMethods, IsMethodDecoratedWithAliasingAttribute);\r
+            NonAliasedMethods = actionMethods.Except(AliasedMethods).ToLookup(method => method.Name, StringComparer.OrdinalIgnoreCase);\r
+        }\r
+\r
+        private static List<MethodInfo> RunSelectionFilters(ControllerContext controllerContext, List<MethodInfo> methodInfos) {\r
+            // remove all methods which are opting out of this request\r
+            // to opt out, at least one attribute defined on the method must return false\r
+\r
+            List<MethodInfo> matchesWithSelectionAttributes = new List<MethodInfo>();\r
+            List<MethodInfo> matchesWithoutSelectionAttributes = new List<MethodInfo>();\r
+\r
+            foreach (MethodInfo methodInfo in methodInfos) {\r
+                ActionMethodSelectorAttribute[] attrs = (ActionMethodSelectorAttribute[])methodInfo.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true /* inherit */);\r
+                if (attrs.Length == 0) {\r
+                    matchesWithoutSelectionAttributes.Add(methodInfo);\r
+                }\r
+                else if (attrs.All(attr => attr.IsValidForRequest(controllerContext, methodInfo))) {\r
+                    matchesWithSelectionAttributes.Add(methodInfo);\r
+                }\r
+            }\r
+\r
+            // if a matching action method had a selection attribute, consider it more specific than a matching action method\r
+            // without a selection attribute\r
+            return (matchesWithSelectionAttributes.Count > 0) ? matchesWithSelectionAttributes : matchesWithoutSelectionAttributes;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionMethodSelectorAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionMethodSelectorAttribute.cs
new file mode 100644 (file)
index 0000000..0a2fd29
--- /dev/null
@@ -0,0 +1,21 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Reflection;\r
+\r
+    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\r
+    public abstract class ActionMethodSelectorAttribute : Attribute {\r
+        public abstract bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionNameAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionNameAttribute.cs
new file mode 100644 (file)
index 0000000..46ef66a
--- /dev/null
@@ -0,0 +1,39 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Reflection;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\r
+    public sealed class ActionNameAttribute : ActionNameSelectorAttribute {\r
+\r
+        public ActionNameAttribute(string name) {\r
+            if (String.IsNullOrEmpty(name)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "name");\r
+            }\r
+\r
+            Name = name;\r
+        }\r
+\r
+        public string Name {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo) {\r
+            return String.Equals(actionName, Name, StringComparison.OrdinalIgnoreCase);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionNameSelectorAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionNameSelectorAttribute.cs
new file mode 100644 (file)
index 0000000..5ec4134
--- /dev/null
@@ -0,0 +1,21 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Reflection;\r
+\r
+    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\r
+    public abstract class ActionNameSelectorAttribute : Attribute {\r
+        public abstract bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionResult.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionResult.cs
new file mode 100644 (file)
index 0000000..11bc79c
--- /dev/null
@@ -0,0 +1,21 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+\r
+    public abstract class ActionResult {\r
+\r
+        public abstract void ExecuteResult(ControllerContext context);\r
+\r
+    }\r
+\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionSelector.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ActionSelector.cs
new file mode 100644 (file)
index 0000000..59891d6
--- /dev/null
@@ -0,0 +1,17 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+\r
+    public delegate bool ActionSelector(ControllerContext controllerContext);\r
+\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Ajax/AjaxExtensions.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Ajax/AjaxExtensions.cs
new file mode 100644 (file)
index 0000000..a34122f
--- /dev/null
@@ -0,0 +1,322 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Ajax {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.ComponentModel;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.Web;\r
+    using System.Web.Mvc;\r
+    using System.Web.Mvc.Html;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.Routing;\r
+\r
+    public static class AjaxExtensions {\r
+        private const string LinkOnClickFormat = "Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), {0});";\r
+        private const string FormOnClickValue = "Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));";\r
+        private const string FormOnSubmitFormat = "Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), {0});";\r
+        private const string _globalizationScript = @"<script type=""text/javascript"" src=""{0}""></script>";\r
+\r
+        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, AjaxOptions ajaxOptions) {\r
+            return ActionLink(ajaxHelper, linkText, actionName, (string)null /* controllerName */, ajaxOptions);\r
+        }\r
+\r
+        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, object routeValues, AjaxOptions ajaxOptions) {\r
+            return ActionLink(ajaxHelper, linkText, actionName, (string)null /* controllerName */, routeValues, ajaxOptions);\r
+        }\r
+\r
+        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes) {\r
+            return ActionLink(ajaxHelper, linkText, actionName, (string)null /* controllerName */, routeValues, ajaxOptions, htmlAttributes);\r
+        }\r
+\r
+        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions) {\r
+            return ActionLink(ajaxHelper, linkText, actionName, (string)null /* controllerName */, routeValues, ajaxOptions);\r
+        }\r
+\r
+        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes) {\r
+            return ActionLink(ajaxHelper, linkText, actionName, (string)null /* controllerName */, routeValues, ajaxOptions, htmlAttributes);\r
+        }\r
+\r
+        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, AjaxOptions ajaxOptions) {\r
+            return ActionLink(ajaxHelper, linkText, actionName, controllerName, null /* values */, ajaxOptions, null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions) {\r
+            return ActionLink(ajaxHelper, linkText, actionName, controllerName, routeValues, ajaxOptions, null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes) {\r
+            RouteValueDictionary newValues = new RouteValueDictionary(routeValues);\r
+            Dictionary<string, object> newAttributes = ObjectToCaseSensitiveDictionary(htmlAttributes);\r
+            return ActionLink(ajaxHelper, linkText, actionName, controllerName, newValues, ajaxOptions, newAttributes);\r
+        }\r
+\r
+        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions) {\r
+            return ActionLink(ajaxHelper, linkText, actionName, controllerName, routeValues, ajaxOptions, null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes) {\r
+            if (String.IsNullOrEmpty(linkText)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "linkText");\r
+            }\r
+\r
+            string targetUrl = UrlHelper.GenerateUrl(null, actionName, controllerName, routeValues, ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, true /* includeImplicitMvcValues */);\r
+\r
+            return MvcHtmlString.Create(GenerateLink(linkText, targetUrl, GetAjaxOptions(ajaxOptions), htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, string protocol, string hostName, string fragment, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes) {\r
+            RouteValueDictionary newValues = new RouteValueDictionary(routeValues);\r
+            Dictionary<string, object> newAttributes = ObjectToCaseSensitiveDictionary(htmlAttributes);\r
+            return ActionLink(ajaxHelper, linkText, actionName, controllerName, protocol, hostName, fragment, newValues, ajaxOptions, newAttributes);\r
+        }\r
+\r
+        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes) {\r
+            if (String.IsNullOrEmpty(linkText)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "linkText");\r
+            }\r
+\r
+            string targetUrl = UrlHelper.GenerateUrl(null /* routeName */, actionName, controllerName, protocol, hostName, fragment, routeValues, ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, true /* includeImplicitMvcValues */);\r
+\r
+            return MvcHtmlString.Create(GenerateLink(linkText, targetUrl, ajaxOptions, htmlAttributes));\r
+        }\r
+\r
+        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, AjaxOptions ajaxOptions) {\r
+            string formAction = ajaxHelper.ViewContext.HttpContext.Request.RawUrl;\r
+            return FormHelper(ajaxHelper, formAction, ajaxOptions, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, AjaxOptions ajaxOptions) {\r
+            return BeginForm(ajaxHelper, actionName, (string)null /* controllerName */, ajaxOptions);\r
+        }\r
+\r
+        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, object routeValues, AjaxOptions ajaxOptions) {\r
+            return BeginForm(ajaxHelper, actionName, (string)null /* controllerName */, routeValues, ajaxOptions);\r
+        }\r
+\r
+        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes) {\r
+            return BeginForm(ajaxHelper, actionName, (string)null /* controllerName */, routeValues, ajaxOptions, htmlAttributes);\r
+        }\r
+\r
+        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions) {\r
+            return BeginForm(ajaxHelper, actionName, (string)null /* controllerName */, routeValues, ajaxOptions);\r
+        }\r
+\r
+        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes) {\r
+            return BeginForm(ajaxHelper, actionName, (string)null /* controllerName */, routeValues, ajaxOptions, htmlAttributes);\r
+        }\r
+\r
+        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, string controllerName, AjaxOptions ajaxOptions) {\r
+            return BeginForm(ajaxHelper, actionName, controllerName, null /* values */, ajaxOptions, null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions) {\r
+            return BeginForm(ajaxHelper, actionName, controllerName, routeValues, ajaxOptions, null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes) {\r
+            RouteValueDictionary newValues = new RouteValueDictionary(routeValues);\r
+            Dictionary<string, object> newAttributes = ObjectToCaseSensitiveDictionary(htmlAttributes);\r
+            return BeginForm(ajaxHelper, actionName, controllerName, newValues, ajaxOptions, newAttributes);\r
+        }\r
+\r
+        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, string controllerName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions) {\r
+            return BeginForm(ajaxHelper, actionName, controllerName, routeValues, ajaxOptions, null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, string controllerName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes) {\r
+            // get target URL\r
+            string formAction = UrlHelper.GenerateUrl(null, actionName, controllerName, routeValues ?? new RouteValueDictionary(), ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, true /* includeImplicitMvcValues */);\r
+            return FormHelper(ajaxHelper, formAction, ajaxOptions, htmlAttributes);\r
+        }\r
+\r
+        public static MvcForm BeginRouteForm(this AjaxHelper ajaxHelper, string routeName, AjaxOptions ajaxOptions) {\r
+            return BeginRouteForm(ajaxHelper, routeName, null /* routeValues */, ajaxOptions, null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcForm BeginRouteForm(this AjaxHelper ajaxHelper, string routeName, object routeValues, AjaxOptions ajaxOptions) {\r
+            return BeginRouteForm(ajaxHelper, routeName, (object)routeValues, ajaxOptions, null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcForm BeginRouteForm(this AjaxHelper ajaxHelper, string routeName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes) {\r
+            Dictionary<string, object> newAttributes = ObjectToCaseSensitiveDictionary(htmlAttributes);\r
+            return BeginRouteForm(ajaxHelper, routeName, new RouteValueDictionary(routeValues), ajaxOptions, newAttributes);\r
+        }\r
+\r
+        public static MvcForm BeginRouteForm(this AjaxHelper ajaxHelper, string routeName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions) {\r
+            return BeginRouteForm(ajaxHelper, routeName, routeValues, ajaxOptions, null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcForm BeginRouteForm(this AjaxHelper ajaxHelper, string routeName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes) {\r
+            string formAction = UrlHelper.GenerateUrl(routeName, null /* actionName */, null /* controllerName */, routeValues ?? new RouteValueDictionary(), ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, false /* includeImplicitMvcValues */);\r
+            return FormHelper(ajaxHelper, formAction, ajaxOptions, htmlAttributes);\r
+        }\r
+\r
+        private static MvcForm FormHelper(this AjaxHelper ajaxHelper, string formAction, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes) {\r
+            TagBuilder builder = new TagBuilder("form");\r
+            builder.MergeAttributes(htmlAttributes);\r
+            builder.MergeAttribute("action", formAction);\r
+            builder.MergeAttribute("method", "post");\r
+            builder.MergeAttribute("onclick", FormOnClickValue);\r
+            builder.MergeAttribute("onsubmit", GenerateAjaxScript(GetAjaxOptions(ajaxOptions), FormOnSubmitFormat));\r
+\r
+            if (ajaxHelper.ViewContext.ClientValidationEnabled) {\r
+                // forms must have an ID for client validation\r
+                builder.GenerateId(ajaxHelper.ViewContext.FormIdGenerator());\r
+            }\r
+\r
+            ajaxHelper.ViewContext.Writer.Write(builder.ToString(TagRenderMode.StartTag));\r
+            MvcForm theForm = new MvcForm(ajaxHelper.ViewContext);\r
+\r
+            if (ajaxHelper.ViewContext.ClientValidationEnabled) {\r
+                ajaxHelper.ViewContext.FormContext.FormId = builder.Attributes["id"];\r
+            }\r
+\r
+            return theForm;\r
+        }\r
+\r
+        public static MvcHtmlString GlobalizationScript(this AjaxHelper ajaxHelper) {\r
+            return GlobalizationScript(ajaxHelper, CultureInfo.CurrentCulture);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "ajaxHelper",\r
+            Justification = "This is an extension method")]\r
+        public static MvcHtmlString GlobalizationScript(this AjaxHelper ajaxHelper, CultureInfo cultureInfo) {\r
+            return GlobalizationScriptHelper(AjaxHelper.GlobalizationScriptPath, cultureInfo);\r
+        }\r
+\r
+        private static MvcHtmlString GlobalizationScriptHelper(string scriptPath, CultureInfo cultureInfo) {\r
+            if (cultureInfo == null) {\r
+                throw new ArgumentNullException("cultureInfo");\r
+            }\r
+\r
+            string src = VirtualPathUtility.AppendTrailingSlash(scriptPath) + cultureInfo.Name + ".js";\r
+            string scriptWithCorrectNewLines = _globalizationScript.Replace("\r\n", Environment.NewLine);\r
+            string formatted = String.Format(CultureInfo.InvariantCulture, scriptWithCorrectNewLines, src);\r
+\r
+            return MvcHtmlString.Create(formatted);\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, object routeValues, AjaxOptions ajaxOptions) {\r
+            return RouteLink(ajaxHelper, linkText, null /* routeName */, new RouteValueDictionary(routeValues), ajaxOptions,\r
+                             new Dictionary<string, object>());\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes) {\r
+            return RouteLink(ajaxHelper, linkText, null /* routeName */, new RouteValueDictionary(routeValues), ajaxOptions,\r
+                             ObjectToCaseSensitiveDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, RouteValueDictionary routeValues, AjaxOptions ajaxOptions) {\r
+            return RouteLink(ajaxHelper, linkText, null /* routeName */, routeValues, ajaxOptions,\r
+                             new Dictionary<string, object>());\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes) {\r
+            return RouteLink(ajaxHelper, linkText, null /* routeName */, routeValues, ajaxOptions, htmlAttributes);\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, AjaxOptions ajaxOptions) {\r
+            return RouteLink(ajaxHelper, linkText, routeName, new RouteValueDictionary(), ajaxOptions,\r
+                             new Dictionary<string, object>());\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, AjaxOptions ajaxOptions, object htmlAttributes) {\r
+            return RouteLink(ajaxHelper, linkText, routeName, new RouteValueDictionary(), ajaxOptions, ObjectToCaseSensitiveDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes) {\r
+            return RouteLink(ajaxHelper, linkText, routeName, new RouteValueDictionary(), ajaxOptions, htmlAttributes);\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, object routeValues, AjaxOptions ajaxOptions) {\r
+            return RouteLink(ajaxHelper, linkText, routeName, new RouteValueDictionary(routeValues), ajaxOptions,\r
+                             new Dictionary<string, object>());\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes) {\r
+            return RouteLink(ajaxHelper, linkText, routeName, new RouteValueDictionary(routeValues), ajaxOptions,\r
+                             ObjectToCaseSensitiveDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions) {\r
+            return RouteLink(ajaxHelper, linkText, routeName, routeValues, ajaxOptions, new Dictionary<string, object>());\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes) {\r
+            if (String.IsNullOrEmpty(linkText)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "linkText");\r
+            }\r
+\r
+            string targetUrl = UrlHelper.GenerateUrl(routeName, null /* actionName */, null /* controllerName */, routeValues ?? new RouteValueDictionary(), ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, false /* includeImplicitMvcValues */);\r
+\r
+            return MvcHtmlString.Create(GenerateLink(linkText, targetUrl, GetAjaxOptions(ajaxOptions), htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes) {\r
+            if (String.IsNullOrEmpty(linkText)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "linkText");\r
+            }\r
+\r
+            string targetUrl = UrlHelper.GenerateUrl(routeName, null /* actionName */, null /* controllerName */, protocol, hostName, fragment, routeValues ?? new RouteValueDictionary(), ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, false /* includeImplicitMvcValues */);\r
+\r
+            return MvcHtmlString.Create(GenerateLink(linkText, targetUrl, GetAjaxOptions(ajaxOptions), htmlAttributes));\r
+        }\r
+\r
+        internal static string InsertionModeToString(InsertionMode insertionMode) {\r
+            switch (insertionMode) {\r
+                case InsertionMode.Replace:\r
+                    return "Sys.Mvc.InsertionMode.replace";\r
+                case InsertionMode.InsertBefore:\r
+                    return "Sys.Mvc.InsertionMode.insertBefore";\r
+                case InsertionMode.InsertAfter:\r
+                    return "Sys.Mvc.InsertionMode.insertAfter";\r
+                default:\r
+                    return ((int)insertionMode).ToString(CultureInfo.InvariantCulture);\r
+            }\r
+        }\r
+\r
+        private static Dictionary<string, object> ObjectToCaseSensitiveDictionary(object values) {\r
+            Dictionary<string, object> dict = new Dictionary<string, object>(StringComparer.Ordinal);\r
+            if (values != null) {\r
+                foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(values)) {\r
+                    object val = prop.GetValue(values);\r
+                    dict[prop.Name] = val;\r
+                }\r
+            }\r
+            return dict;\r
+        }\r
+\r
+        private static string GenerateLink(string linkText, string targetUrl, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes) {\r
+            TagBuilder tag = new TagBuilder("a") {\r
+                InnerHtml = HttpUtility.HtmlEncode(linkText)\r
+            };\r
+\r
+            tag.MergeAttributes(htmlAttributes);\r
+            tag.MergeAttribute("href", targetUrl);\r
+            tag.MergeAttribute("onclick", GenerateAjaxScript(ajaxOptions, LinkOnClickFormat));\r
+\r
+            return tag.ToString(TagRenderMode.Normal);\r
+        }\r
+\r
+        private static string GenerateAjaxScript(AjaxOptions ajaxOptions, string scriptFormat) {\r
+            string optionsString = ajaxOptions.ToJavascriptString();\r
+            return String.Format(CultureInfo.InvariantCulture, scriptFormat, optionsString);\r
+        }\r
+\r
+        private static AjaxOptions GetAjaxOptions(AjaxOptions ajaxOptions) {\r
+            return (ajaxOptions != null) ? ajaxOptions : new AjaxOptions();\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Ajax/AjaxOptions.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Ajax/AjaxOptions.cs
new file mode 100644 (file)
index 0000000..ca04c64
--- /dev/null
@@ -0,0 +1,166 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Ajax {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.Text;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public class AjaxOptions {\r
+        private string _confirm;\r
+        private string _httpMethod;\r
+        private InsertionMode _insertionMode = InsertionMode.Replace;\r
+        private string _loadingElementId;\r
+        private string _onBegin;\r
+        private string _onComplete;\r
+        private string _onFailure;\r
+        private string _onSuccess;\r
+        private string _updateTargetId;\r
+        private string _url;\r
+\r
+        public string Confirm {\r
+            get {\r
+                return _confirm ?? String.Empty;\r
+            }\r
+            set {\r
+                _confirm = value;\r
+            }\r
+        }\r
+\r
+        public string HttpMethod {\r
+            get {\r
+                return _httpMethod ?? String.Empty;\r
+            }\r
+            set {\r
+                _httpMethod = value;\r
+            }\r
+        }\r
+\r
+        public InsertionMode InsertionMode {\r
+            get {\r
+                return _insertionMode;\r
+            }\r
+            set {\r
+                switch (value) {\r
+                    case InsertionMode.Replace:\r
+                    case InsertionMode.InsertAfter:\r
+                    case InsertionMode.InsertBefore:\r
+                        _insertionMode = value;\r
+                        return;\r
+\r
+                    default:\r
+                        throw new ArgumentOutOfRangeException("value");\r
+                }\r
+            }\r
+        }\r
+\r
+        public string LoadingElementId {\r
+            get {\r
+                return _loadingElementId ?? String.Empty;\r
+            }\r
+            set {\r
+                _loadingElementId = value;\r
+            }\r
+        }\r
+\r
+        public string OnBegin {\r
+            get {\r
+                return _onBegin ?? String.Empty;\r
+            }\r
+            set {\r
+                _onBegin = value;\r
+            }\r
+        }\r
+\r
+        public string OnComplete {\r
+            get {\r
+                return _onComplete ?? String.Empty;\r
+            }\r
+            set {\r
+                _onComplete = value;\r
+            }\r
+        }\r
+\r
+        public string OnFailure {\r
+            get {\r
+                return _onFailure ?? String.Empty;\r
+            }\r
+            set {\r
+                _onFailure = value;\r
+            }\r
+        }\r
+\r
+        public string OnSuccess {\r
+            get {\r
+                return _onSuccess ?? String.Empty;\r
+            }\r
+            set {\r
+                _onSuccess = value;\r
+            }\r
+        }\r
+\r
+        public string UpdateTargetId {\r
+            get {\r
+                return _updateTargetId ?? String.Empty;\r
+            }\r
+            set {\r
+                _updateTargetId = value;\r
+            }\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings",\r
+            Justification = "This property is used by the optionsBuilder which always accepts a string.")]\r
+        public string Url {\r
+            get {\r
+                return _url ?? String.Empty;\r
+            }\r
+            set {\r
+                _url = value;\r
+            }\r
+        }\r
+\r
+        internal string ToJavascriptString() {\r
+            // creates a string of the form { key1: value1, key2 : value2, ... }\r
+            StringBuilder optionsBuilder = new StringBuilder("{");\r
+            optionsBuilder.Append(String.Format(CultureInfo.InvariantCulture, " insertionMode: {0},", AjaxExtensions.InsertionModeToString(InsertionMode)));\r
+            optionsBuilder.Append(PropertyStringIfSpecified("confirm", Confirm));\r
+            optionsBuilder.Append(PropertyStringIfSpecified("httpMethod", HttpMethod));\r
+            optionsBuilder.Append(PropertyStringIfSpecified("loadingElementId", LoadingElementId));\r
+            optionsBuilder.Append(PropertyStringIfSpecified("updateTargetId", UpdateTargetId));\r
+            optionsBuilder.Append(PropertyStringIfSpecified("url", Url));\r
+            optionsBuilder.Append(EventStringIfSpecified("onBegin", OnBegin));\r
+            optionsBuilder.Append(EventStringIfSpecified("onComplete", OnComplete));\r
+            optionsBuilder.Append(EventStringIfSpecified("onFailure", OnFailure));\r
+            optionsBuilder.Append(EventStringIfSpecified("onSuccess", OnSuccess));\r
+            optionsBuilder.Length--;\r
+            optionsBuilder.Append(" }");\r
+            return optionsBuilder.ToString();\r
+        }\r
+\r
+        private static string EventStringIfSpecified(string propertyName, string handler) {\r
+            if (!String.IsNullOrEmpty(handler)) {\r
+                return String.Format(CultureInfo.InvariantCulture, " {0}: Function.createDelegate(this, {1}),", propertyName, handler.ToString());\r
+            }\r
+            return String.Empty;\r
+        }\r
+\r
+        private static string PropertyStringIfSpecified(string propertyName, string propertyValue) {\r
+            if (!String.IsNullOrEmpty(propertyValue)) {\r
+                string escapedPropertyValue = propertyValue.Replace("'", @"\'");\r
+                return String.Format(CultureInfo.InvariantCulture, " {0}: '{1}',", propertyName, escapedPropertyValue);\r
+            }\r
+            return String.Empty;\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Ajax/InsertionMode.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Ajax/InsertionMode.cs
new file mode 100644 (file)
index 0000000..de0eb4e
--- /dev/null
@@ -0,0 +1,19 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Ajax {\r
+    public enum InsertionMode {\r
+        Replace = 0,\r
+        InsertBefore = 1,\r
+        InsertAfter = 2\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/AjaxHelper.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/AjaxHelper.cs
new file mode 100644 (file)
index 0000000..7324a52
--- /dev/null
@@ -0,0 +1,89 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Text;\r
+    using System.Web.Routing;\r
+    using System.Web.Script.Serialization;\r
+\r
+    public class AjaxHelper {\r
+\r
+        private static string _globalizationScriptPath;\r
+\r
+        public AjaxHelper(ViewContext viewContext, IViewDataContainer viewDataContainer)\r
+            : this(viewContext, viewDataContainer, RouteTable.Routes) {\r
+        }\r
+\r
+        public AjaxHelper(ViewContext viewContext, IViewDataContainer viewDataContainer, RouteCollection routeCollection) {\r
+            if (viewContext == null) {\r
+                throw new ArgumentNullException("viewContext");\r
+            }\r
+            if (viewDataContainer == null) {\r
+                throw new ArgumentNullException("viewDataContainer");\r
+            }\r
+            if (routeCollection == null) {\r
+                throw new ArgumentNullException("routeCollection");\r
+            }\r
+            ViewContext = viewContext;\r
+            ViewDataContainer = viewDataContainer;\r
+            RouteCollection = routeCollection;\r
+        }\r
+\r
+        public static string GlobalizationScriptPath {\r
+            get {\r
+                if (String.IsNullOrEmpty(_globalizationScriptPath)) {\r
+                    _globalizationScriptPath = "~/Scripts/Globalization";\r
+                }\r
+                return _globalizationScriptPath;\r
+            }\r
+            set {\r
+                _globalizationScriptPath = value;\r
+            }\r
+        }\r
+\r
+        public RouteCollection RouteCollection {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public ViewContext ViewContext {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public ViewDataDictionary ViewData {\r
+            get {\r
+                return ViewDataContainer.ViewData;\r
+            }\r
+        }\r
+\r
+        public IViewDataContainer ViewDataContainer {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic",\r
+            Justification = "Instance method for consistency with other helpers.")]\r
+        public string JavaScriptStringEncode(string message) {\r
+            if (String.IsNullOrEmpty(message)) {\r
+                return message;\r
+            }\r
+            \r
+            StringBuilder builder = new StringBuilder();\r
+            JavaScriptSerializer serializer = new JavaScriptSerializer();\r
+            serializer.Serialize(message, builder);\r
+            return builder.ToString(1, builder.Length - 2); // remove first + last quote\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/AjaxHelper`1.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/AjaxHelper`1.cs
new file mode 100644 (file)
index 0000000..1e1f2b9
--- /dev/null
@@ -0,0 +1,35 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Web.Routing;\r
+\r
+    public class AjaxHelper<TModel> : AjaxHelper {\r
+        private ViewDataDictionary<TModel> _viewData;\r
+\r
+        public AjaxHelper(ViewContext viewContext, IViewDataContainer viewDataContainer)\r
+            : this(viewContext, viewDataContainer, RouteTable.Routes) {\r
+        }\r
+\r
+        public AjaxHelper(ViewContext viewContext, IViewDataContainer viewDataContainer, RouteCollection routeCollection)\r
+            : base(viewContext, viewDataContainer, routeCollection) {\r
+\r
+            _viewData = new ViewDataDictionary<TModel>(viewDataContainer.ViewData);\r
+        }\r
+\r
+        public new ViewDataDictionary<TModel> ViewData {\r
+            get {\r
+                return _viewData;\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/AjaxRequestExtensions.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/AjaxRequestExtensions.cs
new file mode 100644 (file)
index 0000000..411c250
--- /dev/null
@@ -0,0 +1,26 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    public static class AjaxRequestExtensions {\r
+\r
+        public static bool IsAjaxRequest(this HttpRequestBase request) {\r
+            if (request == null) {\r
+                throw new ArgumentNullException("request");\r
+            }\r
+            \r
+            return (request["X-Requested-With"] == "XMLHttpRequest") || ((request.Headers != null) && (request.Headers["X-Requested-With"] == "XMLHttpRequest"));\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/AntiForgeryData.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/AntiForgeryData.cs
new file mode 100644 (file)
index 0000000..82252d4
--- /dev/null
@@ -0,0 +1,129 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Security.Cryptography;\r
+    using System.Security.Principal;\r
+    using System.Text;\r
+\r
+    internal sealed class AntiForgeryData {\r
+\r
+        private const string AntiForgeryTokenFieldName = "__RequestVerificationToken";\r
+\r
+        private const int TokenLength = 128 / 8;\r
+        private readonly static RNGCryptoServiceProvider _prng = new RNGCryptoServiceProvider();\r
+\r
+        private DateTime _creationDate = DateTime.UtcNow;\r
+        private string _salt;\r
+        private string _username;\r
+        private string _value;\r
+\r
+        public AntiForgeryData() {\r
+        }\r
+\r
+        // copy constructor\r
+        public AntiForgeryData(AntiForgeryData token) {\r
+            if (token == null) {\r
+                throw new ArgumentNullException("token");\r
+            }\r
+\r
+            CreationDate = token.CreationDate;\r
+            Salt = token.Salt;\r
+            Username = token.Username;\r
+            Value = token.Value;\r
+        }\r
+\r
+        public DateTime CreationDate {\r
+            get {\r
+                return _creationDate;\r
+            }\r
+            set {\r
+                _creationDate = value;\r
+            }\r
+        }\r
+\r
+        public string Salt {\r
+            get {\r
+                return _salt ?? String.Empty;\r
+            }\r
+            set {\r
+                _salt = value;\r
+            }\r
+        }\r
+\r
+        public string Username {\r
+            get {\r
+                return _username ?? String.Empty;\r
+            }\r
+            set {\r
+                _username = value;\r
+            }\r
+        }\r
+\r
+        public string Value {\r
+            get {\r
+                return _value ?? String.Empty;\r
+            }\r
+            set {\r
+                _value = value;\r
+            }\r
+        }\r
+\r
+        private static string Base64EncodeForCookieName(string s) {\r
+            byte[] rawBytes = Encoding.UTF8.GetBytes(s);\r
+            string base64String = Convert.ToBase64String(rawBytes);\r
+\r
+            // replace base64-specific characters with characters that are safe for a cookie name\r
+            return base64String.Replace('+', '.').Replace('/', '-').Replace('=', '_');\r
+        }\r
+\r
+        private static string GenerateRandomTokenString() {\r
+            byte[] tokenBytes = new byte[TokenLength];\r
+            _prng.GetBytes(tokenBytes);\r
+\r
+            string token = Convert.ToBase64String(tokenBytes);\r
+            return token;\r
+        }\r
+\r
+        // If the app path is provided, we're generating a cookie name rather than a field name, and the cookie names should\r
+        // be unique so that a development server cookie and an IIS cookie - both running on localhost - don't stomp on\r
+        // each other.\r
+        internal static string GetAntiForgeryTokenName(string appPath) {\r
+            if (String.IsNullOrEmpty(appPath)) {\r
+                return AntiForgeryTokenFieldName;\r
+            }\r
+            else {\r
+                return AntiForgeryTokenFieldName + "_" + Base64EncodeForCookieName(appPath);\r
+            }\r
+        }\r
+\r
+        internal static string GetUsername(IPrincipal user) {\r
+            if (user != null) {\r
+                IIdentity identity = user.Identity;\r
+                if (identity != null && identity.IsAuthenticated) {\r
+                    return identity.Name;\r
+                }\r
+            }\r
+\r
+            return String.Empty;\r
+        }\r
+\r
+        public static AntiForgeryData NewToken() {\r
+            string tokenString = GenerateRandomTokenString();\r
+            return new AntiForgeryData() {\r
+                Value = tokenString\r
+            };\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/AntiForgeryDataSerializer.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/AntiForgeryDataSerializer.cs
new file mode 100644 (file)
index 0000000..cb06831
--- /dev/null
@@ -0,0 +1,128 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.IO;\r
+    using System.Web;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.UI;\r
+\r
+    internal class AntiForgeryDataSerializer {\r
+\r
+        private IStateFormatter _formatter;\r
+\r
+        protected internal IStateFormatter Formatter {\r
+            get {\r
+                if (_formatter == null) {\r
+                    _formatter = FormatterGenerator.GetFormatter();\r
+                }\r
+                return _formatter;\r
+            }\r
+            set {\r
+                _formatter = value;\r
+            }\r
+        }\r
+\r
+        private static HttpAntiForgeryException CreateValidationException(Exception innerException) {\r
+            return new HttpAntiForgeryException(MvcResources.AntiForgeryToken_ValidationFailed, innerException);\r
+        }\r
+\r
+        public virtual AntiForgeryData Deserialize(string serializedToken) {\r
+            if (String.IsNullOrEmpty(serializedToken)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "serializedToken");\r
+            }\r
+\r
+            // call property getter outside try { } block so that exceptions bubble up for debugging\r
+            IStateFormatter formatter = Formatter;\r
+\r
+            try {\r
+                object[] deserializedObj = (object[])formatter.Deserialize(serializedToken);\r
+                return new AntiForgeryData() {\r
+                    Salt = (string)deserializedObj[0],\r
+                    Value = (string)deserializedObj[1],\r
+                    CreationDate = (DateTime)deserializedObj[2],\r
+                    Username = (string)deserializedObj[3]\r
+                };\r
+            }\r
+            catch (Exception ex) {\r
+                throw CreateValidationException(ex);\r
+            }\r
+        }\r
+\r
+        public virtual string Serialize(AntiForgeryData token) {\r
+            if (token == null) {\r
+                throw new ArgumentNullException("token");\r
+            }\r
+\r
+            object[] objToSerialize = new object[] {\r
+                token.Salt,\r
+                token.Value,\r
+                token.CreationDate,\r
+                token.Username\r
+            };\r
+\r
+            string serializedValue = Formatter.Serialize(objToSerialize);\r
+            return serializedValue;\r
+        }\r
+\r
+        // See http://www.yoda.arachsys.com/csharp/singleton.html (fifth version - fully lazy) for the singleton pattern\r
+        // used here. We need to defer the call to TokenPersister.CreateFormatterGenerator() until we're actually\r
+        // servicing a request, else HttpContext.Current might be invalid in TokenPersister.CreateFormatterGenerator().\r
+        private static class FormatterGenerator {\r
+\r
+            public static readonly Func<IStateFormatter> GetFormatter = TokenPersister.CreateFormatterGenerator();\r
+\r
+            [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline",\r
+                Justification = "This type must not be marked 'beforefieldinit'.")]\r
+            static FormatterGenerator() {\r
+            }\r
+\r
+            // This type is very difficult to unit-test because Page.ProcessRequest() requires mocking\r
+            // much of the hosting environment. For now, we can perform functional tests of this feature.\r
+            private sealed class TokenPersister : PageStatePersister {\r
+                private TokenPersister(Page page)\r
+                    : base(page) {\r
+                }\r
+\r
+                public static Func<IStateFormatter> CreateFormatterGenerator() {\r
+                    // This code instantiates a page and tricks it into thinking that it's servicing\r
+                    // a postback scenario with encrypted ViewState, which is required to make the\r
+                    // StateFormatter properly decrypt data. Specifically, this code sets the\r
+                    // internal Page.ContainsEncryptedViewState flag.\r
+                    TextWriter writer = TextWriter.Null;\r
+                    HttpResponse response = new HttpResponse(writer);\r
+                    HttpRequest request = new HttpRequest("DummyFile.aspx", HttpContext.Current.Request.Url.ToString(), "__EVENTTARGET=true&__VIEWSTATEENCRYPTED=true");\r
+                    HttpContext context = new HttpContext(request, response);\r
+\r
+                    Page page = new Page() {\r
+                        EnableViewStateMac = true,\r
+                        ViewStateEncryptionMode = ViewStateEncryptionMode.Always\r
+                    };\r
+                    page.ProcessRequest(context);\r
+\r
+                    return () => new TokenPersister(page).StateFormatter;\r
+                }\r
+\r
+                public override void Load() {\r
+                    throw new NotImplementedException();\r
+                }\r
+\r
+                public override void Save() {\r
+                    throw new NotImplementedException();\r
+                }\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/AreaHelpers.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/AreaHelpers.cs
new file mode 100644 (file)
index 0000000..723f834
--- /dev/null
@@ -0,0 +1,43 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Web.Routing;\r
+\r
+    internal static class AreaHelpers {\r
+\r
+        public static string GetAreaName(RouteBase route) {\r
+            IRouteWithArea routeWithArea = route as IRouteWithArea;\r
+            if (routeWithArea != null) {\r
+                return routeWithArea.Area;\r
+            }\r
+\r
+            Route castRoute = route as Route;\r
+            if (castRoute != null && castRoute.DataTokens != null) {\r
+                return castRoute.DataTokens["area"] as string;\r
+            }\r
+\r
+            return null;\r
+        }\r
+\r
+        public static string GetAreaName(RouteData routeData) {\r
+            object area;\r
+            if (routeData.DataTokens.TryGetValue("area", out area)) {\r
+                return area as string;\r
+            }\r
+\r
+            return GetAreaName(routeData.Route);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/AreaRegistration.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/AreaRegistration.cs
new file mode 100644 (file)
index 0000000..5725ddf
--- /dev/null
@@ -0,0 +1,62 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Web.Routing;\r
+\r
+    public abstract class AreaRegistration {\r
+\r
+        private const string _typeCacheName = "MVC-AreaRegistrationTypeCache.xml";\r
+\r
+        public abstract string AreaName {\r
+            get;\r
+        }\r
+\r
+        internal void CreateContextAndRegister(RouteCollection routes, object state) {\r
+            AreaRegistrationContext context = new AreaRegistrationContext(AreaName, routes, state);\r
+\r
+            string thisNamespace = GetType().Namespace;\r
+            if (thisNamespace != null) {\r
+                context.Namespaces.Add(thisNamespace + ".*");\r
+            }\r
+\r
+            RegisterArea(context);\r
+        }\r
+\r
+        private static bool IsAreaRegistrationType(Type type) {\r
+            return\r
+                typeof(AreaRegistration).IsAssignableFrom(type) &&\r
+                type.GetConstructor(Type.EmptyTypes) != null;\r
+        }\r
+\r
+        public static void RegisterAllAreas() {\r
+            RegisterAllAreas(null);\r
+        }\r
+\r
+        public static void RegisterAllAreas(object state) {\r
+            RegisterAllAreas(RouteTable.Routes, new BuildManagerWrapper(), state);\r
+        }\r
+\r
+        internal static void RegisterAllAreas(RouteCollection routes, IBuildManager buildManager, object state) {\r
+            List<Type> areaRegistrationTypes = TypeCacheUtil.GetFilteredTypesFromAssemblies(_typeCacheName, IsAreaRegistrationType, buildManager);\r
+            foreach (Type areaRegistrationType in areaRegistrationTypes) {\r
+                AreaRegistration registration = (AreaRegistration)Activator.CreateInstance(areaRegistrationType);\r
+                registration.CreateContextAndRegister(routes, state);\r
+            }\r
+        }\r
+\r
+        public abstract void RegisterArea(AreaRegistrationContext context);\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/AreaRegistrationContext.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/AreaRegistrationContext.cs
new file mode 100644 (file)
index 0000000..869c1ac
--- /dev/null
@@ -0,0 +1,111 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Linq;\r
+    using System.Web.Routing;\r
+\r
+    public class AreaRegistrationContext {\r
+\r
+        private readonly HashSet<string> _namespaces = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\r
+\r
+        public AreaRegistrationContext(string areaName, RouteCollection routes)\r
+            : this(areaName, routes, null) {\r
+        }\r
+\r
+        public AreaRegistrationContext(string areaName, RouteCollection routes, object state) {\r
+            if (String.IsNullOrEmpty(areaName)) {\r
+                throw Error.ParameterCannotBeNullOrEmpty("areaName");\r
+            }\r
+            if (routes == null) {\r
+                throw new ArgumentNullException("routes");\r
+            }\r
+\r
+            AreaName = areaName;\r
+            Routes = routes;\r
+            State = state;\r
+        }\r
+\r
+        public string AreaName {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public ICollection<string> Namespaces {\r
+            get {\r
+                return _namespaces;\r
+            }\r
+        }\r
+\r
+        public RouteCollection Routes {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public object State {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#",\r
+            Justification = "This is not a regular URL as it may contain special routing characters.")]\r
+        public Route MapRoute(string name, string url) {\r
+            return MapRoute(name, url, (object)null /* defaults */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#",\r
+            Justification = "This is not a regular URL as it may contain special routing characters.")]\r
+        public Route MapRoute(string name, string url, object defaults) {\r
+            return MapRoute(name, url, defaults, (object)null /* constraints */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#",\r
+            Justification = "This is not a regular URL as it may contain special routing characters.")]\r
+        public Route MapRoute(string name, string url, object defaults, object constraints) {\r
+            return MapRoute(name, url, defaults, constraints, null /* namespaces */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#",\r
+            Justification = "This is not a regular URL as it may contain special routing characters.")]\r
+        public Route MapRoute(string name, string url, string[] namespaces) {\r
+            return MapRoute(name, url, (object)null /* defaults */, namespaces);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#",\r
+            Justification = "This is not a regular URL as it may contain special routing characters.")]\r
+        public Route MapRoute(string name, string url, object defaults, string[] namespaces) {\r
+            return MapRoute(name, url, defaults, null /* constraints */, namespaces);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#",\r
+            Justification = "This is not a regular URL as it may contain special routing characters.")]\r
+        public Route MapRoute(string name, string url, object defaults, object constraints, string[] namespaces) {\r
+            if (namespaces == null && Namespaces != null) {\r
+                namespaces = Namespaces.ToArray();\r
+            }\r
+\r
+            Route route = Routes.MapRoute(name, url, defaults, constraints, namespaces);\r
+            route.DataTokens["area"] = AreaName;\r
+\r
+            // disabling the namespace lookup fallback mechanism keeps this areas from accidentally picking up\r
+            // controllers belonging to other areas\r
+            bool useNamespaceFallback = (namespaces == null || namespaces.Length == 0);\r
+            route.DataTokens["UseNamespaceFallback"] = useNamespaceFallback;\r
+\r
+            return route;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/AssociatedMetadataProvider.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/AssociatedMetadataProvider.cs
new file mode 100644 (file)
index 0000000..bd9248f
--- /dev/null
@@ -0,0 +1,95 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.ComponentModel;\r
+    using System.ComponentModel.DataAnnotations;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    // This class provides a good implementation of ModelMetadataProvider for people who will be\r
+    // using traditional classes with properties. It uses the buddy class support from\r
+    // DataAnnotations, and consolidates the three operations down to a single override\r
+    // for reading the attribute values and creating the metadata class.\r
+    public abstract class AssociatedMetadataProvider : ModelMetadataProvider {\r
+        protected abstract ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName);\r
+\r
+        protected virtual IEnumerable<Attribute> FilterAttributes(Type containerType, PropertyDescriptor propertyDescriptor, IEnumerable<Attribute> attributes) {\r
+            if (typeof(ViewPage).IsAssignableFrom(containerType) || typeof(ViewUserControl).IsAssignableFrom(containerType)) {\r
+                return attributes.Where(a => !(a is ReadOnlyAttribute));\r
+            }\r
+\r
+            return attributes;\r
+        }\r
+\r
+        public override IEnumerable<ModelMetadata> GetMetadataForProperties(object container, Type containerType) {\r
+            if (containerType == null) {\r
+                throw new ArgumentNullException("containerType");\r
+            }\r
+\r
+            return GetMetadataForPropertiesImpl(container, containerType);\r
+        }\r
+\r
+        private IEnumerable<ModelMetadata> GetMetadataForPropertiesImpl(object container, Type containerType) {\r
+            foreach (PropertyDescriptor property in GetTypeDescriptor(containerType).GetProperties()) {\r
+                Func<object> modelAccessor = container == null ? null : GetPropertyValueAccessor(container, property);\r
+                yield return GetMetadataForProperty(modelAccessor, containerType, property);\r
+            }\r
+        }\r
+\r
+        public override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, string propertyName) {\r
+            if (containerType == null) {\r
+                throw new ArgumentNullException("containerType");\r
+            }\r
+            if (String.IsNullOrEmpty(propertyName)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "propertyName");\r
+            }\r
+\r
+            ICustomTypeDescriptor typeDescriptor = GetTypeDescriptor(containerType);\r
+            PropertyDescriptor property = typeDescriptor.GetProperties().Find(propertyName, true);\r
+            if (property == null) {\r
+                throw new ArgumentException(\r
+                    String.Format(\r
+                        CultureInfo.CurrentCulture,\r
+                        MvcResources.Common_PropertyNotFound,\r
+                        containerType.FullName, propertyName));\r
+            }\r
+\r
+            return GetMetadataForProperty(modelAccessor, containerType, property);\r
+        }\r
+\r
+        protected virtual ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, PropertyDescriptor propertyDescriptor) {\r
+            IEnumerable<Attribute> attributes = FilterAttributes(containerType, propertyDescriptor, propertyDescriptor.Attributes.Cast<Attribute>());\r
+            return CreateMetadata(attributes, containerType, modelAccessor, propertyDescriptor.PropertyType, propertyDescriptor.Name);\r
+        }\r
+\r
+        public override ModelMetadata GetMetadataForType(Func<object> modelAccessor, Type modelType) {\r
+            if (modelType == null) {\r
+                throw new ArgumentNullException("modelType");\r
+            }\r
+\r
+            IEnumerable<Attribute> attributes = GetTypeDescriptor(modelType).GetAttributes().Cast<Attribute>();\r
+            return CreateMetadata(attributes, null /* containerType */, modelAccessor, modelType, null /* propertyName */);\r
+        }\r
+\r
+        private static Func<object> GetPropertyValueAccessor(object container, PropertyDescriptor property) {\r
+            return () => property.GetValue(container);\r
+        }\r
+\r
+        protected virtual ICustomTypeDescriptor GetTypeDescriptor(Type type) {\r
+            return TypeDescriptorHelper.Get(type);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/AssociatedValidatorProvider.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/AssociatedValidatorProvider.cs
new file mode 100644 (file)
index 0000000..f7b280a
--- /dev/null
@@ -0,0 +1,63 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.ComponentModel;\r
+    using System.ComponentModel.DataAnnotations;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public abstract class AssociatedValidatorProvider : ModelValidatorProvider {\r
+        protected virtual ICustomTypeDescriptor GetTypeDescriptor(Type type) {\r
+            return TypeDescriptorHelper.Get(type);\r
+        }\r
+\r
+        public override sealed IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context) {\r
+            if (metadata == null) {\r
+                throw new ArgumentNullException("metadata");\r
+            }\r
+            if (context == null) {\r
+                throw new ArgumentNullException("context");\r
+            }\r
+\r
+            if (metadata.ContainerType != null && !String.IsNullOrEmpty(metadata.PropertyName)) {\r
+                return GetValidatorsForProperty(metadata, context);\r
+            }\r
+\r
+            return GetValidatorsForType(metadata, context);\r
+        }\r
+\r
+        protected abstract IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes);\r
+\r
+        private IEnumerable<ModelValidator> GetValidatorsForProperty(ModelMetadata metadata, ControllerContext context) {\r
+            ICustomTypeDescriptor typeDescriptor = GetTypeDescriptor(metadata.ContainerType);\r
+            PropertyDescriptor property = typeDescriptor.GetProperties().Find(metadata.PropertyName, true);\r
+            if (property == null) {\r
+                throw new ArgumentException(\r
+                    String.Format(\r
+                        CultureInfo.CurrentCulture,\r
+                        MvcResources.Common_PropertyNotFound,\r
+                        metadata.ContainerType.FullName, metadata.PropertyName),\r
+                    "metadata");\r
+            }\r
+\r
+            return GetValidators(metadata, context, property.Attributes.OfType<Attribute>());\r
+        }\r
+\r
+        private IEnumerable<ModelValidator> GetValidatorsForType(ModelMetadata metadata, ControllerContext context) {\r
+            return GetValidators(metadata, context, GetTypeDescriptor(metadata.ModelType).GetAttributes().Cast<Attribute>());\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/ActionDescriptorCreator.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/ActionDescriptorCreator.cs
new file mode 100644 (file)
index 0000000..19e1179
--- /dev/null
@@ -0,0 +1,18 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+\r
+    internal delegate ActionDescriptor ActionDescriptorCreator(string actionName, ControllerDescriptor controllerDescriptor);\r
+\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncActionDescriptor.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncActionDescriptor.cs
new file mode 100644 (file)
index 0000000..2b9ff2f
--- /dev/null
@@ -0,0 +1,40 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+    using System.Collections.Generic;\r
+\r
+    public abstract class AsyncActionDescriptor : ActionDescriptor {\r
+\r
+        public abstract IAsyncResult BeginExecute(ControllerContext controllerContext, IDictionary<string, object> parameters, AsyncCallback callback, object state);\r
+\r
+        public abstract object EndExecute(IAsyncResult asyncResult);\r
+\r
+        public override object Execute(ControllerContext controllerContext, IDictionary<string, object> parameters) {\r
+            // execute an asynchronous task synchronously\r
+            IAsyncResult asyncResult = BeginExecute(controllerContext, parameters, null, null);\r
+            AsyncUtil.WaitForAsyncResultCompletion(asyncResult, controllerContext.HttpContext.ApplicationInstance); // blocks\r
+            return EndExecute(asyncResult);\r
+        }\r
+\r
+        internal static AsyncManager GetAsyncManager(ControllerBase controller) {\r
+            IAsyncManagerContainer helperContainer = controller as IAsyncManagerContainer;\r
+            if (helperContainer == null) {\r
+                throw Error.AsyncCommon_ControllerMustImplementIAsyncManagerContainer(controller.GetType());\r
+            }\r
+\r
+            return helperContainer.AsyncManager;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncActionMethodSelector.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncActionMethodSelector.cs
new file mode 100644 (file)
index 0000000..efd00b1
--- /dev/null
@@ -0,0 +1,206 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+    using System.Reflection;\r
+    using System.Text;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    internal sealed class AsyncActionMethodSelector {\r
+\r
+        public AsyncActionMethodSelector(Type controllerType) {\r
+            ControllerType = controllerType;\r
+            PopulateLookupTables();\r
+        }\r
+\r
+        public Type ControllerType {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public MethodInfo[] AliasedMethods {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public ILookup<string, MethodInfo> NonAliasedMethods {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        private AmbiguousMatchException CreateAmbiguousActionMatchException(IEnumerable<MethodInfo> ambiguousMethods, string actionName) {\r
+            string ambiguityList = CreateAmbiguousMatchList(ambiguousMethods);\r
+            string message = String.Format(CultureInfo.CurrentUICulture, MvcResources.ActionMethodSelector_AmbiguousMatch,\r
+                actionName, ControllerType.Name, ambiguityList);\r
+            return new AmbiguousMatchException(message);\r
+        }\r
+\r
+        private AmbiguousMatchException CreateAmbiguousMethodMatchException(IEnumerable<MethodInfo> ambiguousMethods, string methodName) {\r
+            string ambiguityList = CreateAmbiguousMatchList(ambiguousMethods);\r
+            string message = String.Format(CultureInfo.CurrentUICulture, MvcResources.AsyncActionMethodSelector_AmbiguousMethodMatch,\r
+                methodName, ControllerType.Name, ambiguityList);\r
+            return new AmbiguousMatchException(message);\r
+        }\r
+\r
+        private static string CreateAmbiguousMatchList(IEnumerable<MethodInfo> ambiguousMethods) {\r
+            StringBuilder exceptionMessageBuilder = new StringBuilder();\r
+            foreach (MethodInfo methodInfo in ambiguousMethods) {\r
+                exceptionMessageBuilder.AppendLine();\r
+                exceptionMessageBuilder.AppendFormat(CultureInfo.CurrentUICulture, MvcResources.ActionMethodSelector_AmbiguousMatchType, methodInfo, methodInfo.DeclaringType.FullName);\r
+            }\r
+\r
+            return exceptionMessageBuilder.ToString();\r
+        }\r
+\r
+        public ActionDescriptorCreator FindAction(ControllerContext controllerContext, string actionName) {\r
+            List<MethodInfo> methodsMatchingName = GetMatchingAliasedMethods(controllerContext, actionName);\r
+            methodsMatchingName.AddRange(NonAliasedMethods[actionName]);\r
+            List<MethodInfo> finalMethods = RunSelectionFilters(controllerContext, methodsMatchingName);\r
+\r
+            switch (finalMethods.Count) {\r
+                case 0:\r
+                    return null;\r
+\r
+                case 1:\r
+                    MethodInfo entryMethod = finalMethods[0];\r
+                    return GetActionDescriptorDelegate(entryMethod);\r
+\r
+                default:\r
+                    throw CreateAmbiguousActionMatchException(finalMethods, actionName);\r
+            }\r
+        }\r
+\r
+        private ActionDescriptorCreator GetActionDescriptorDelegate(MethodInfo entryMethod) {\r
+            // Is this the FooAsync() / FooCompleted() pattern?\r
+            if (IsAsyncSuffixedMethod(entryMethod)) {\r
+                string completionMethodName = entryMethod.Name.Substring(0, entryMethod.Name.Length - "Async".Length) + "Completed";\r
+                MethodInfo completionMethod = GetMethodByName(completionMethodName);\r
+                if (completionMethod != null) {\r
+                    return (actionName, controllerDescriptor) => new ReflectedAsyncActionDescriptor(entryMethod, completionMethod, actionName, controllerDescriptor);\r
+                }\r
+                else {\r
+                    throw Error.AsyncActionMethodSelector_CouldNotFindMethod(completionMethodName, ControllerType);\r
+                }\r
+            }\r
+\r
+            // Fallback to synchronous method\r
+            return (actionName, controllerDescriptor) => new ReflectedActionDescriptor(entryMethod, actionName, controllerDescriptor);\r
+        }\r
+\r
+        private static string GetCanonicalMethodName(MethodInfo methodInfo) {\r
+            string methodName = methodInfo.Name;\r
+            return (IsAsyncSuffixedMethod(methodInfo))\r
+                ? methodName.Substring(0, methodName.Length - "Async".Length)\r
+                : methodName;\r
+        }\r
+\r
+        internal List<MethodInfo> GetMatchingAliasedMethods(ControllerContext controllerContext, string actionName) {\r
+            // find all aliased methods which are opting in to this request\r
+            // to opt in, all attributes defined on the method must return true\r
+\r
+            var methods = from methodInfo in AliasedMethods\r
+                          let attrs = (ActionNameSelectorAttribute[])methodInfo.GetCustomAttributes(typeof(ActionNameSelectorAttribute), true /* inherit */)\r
+                          where attrs.All(attr => attr.IsValidName(controllerContext, actionName, methodInfo))\r
+                          select methodInfo;\r
+            return methods.ToList();\r
+        }\r
+\r
+        private static bool IsAsyncSuffixedMethod(MethodInfo methodInfo) {\r
+            return methodInfo.Name.EndsWith("Async", StringComparison.OrdinalIgnoreCase);\r
+        }\r
+\r
+        private static bool IsCompletedSuffixedMethod(MethodInfo methodInfo) {\r
+            return methodInfo.Name.EndsWith("Completed", StringComparison.OrdinalIgnoreCase);\r
+        }\r
+\r
+        private static bool IsMethodDecoratedWithAliasingAttribute(MethodInfo methodInfo) {\r
+            return methodInfo.IsDefined(typeof(ActionNameSelectorAttribute), true /* inherit */);\r
+        }\r
+\r
+        private MethodInfo GetMethodByName(string methodName) {\r
+            List<MethodInfo> methods = (from MethodInfo methodInfo in ControllerType.GetMember(methodName, MemberTypes.Method, BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.IgnoreCase)\r
+                                        where IsValidActionMethod(methodInfo, false /* stripInfrastructureMethods */)\r
+                                        select methodInfo).ToList();\r
+\r
+            switch (methods.Count) {\r
+                case 0:\r
+                    return null;\r
+\r
+                case 1:\r
+                    return methods[0];\r
+\r
+                default:\r
+                    throw CreateAmbiguousMethodMatchException(methods, methodName);\r
+            }\r
+        }\r
+\r
+        private static bool IsValidActionMethod(MethodInfo methodInfo) {\r
+            return IsValidActionMethod(methodInfo, true /* stripInfrastructureMethods */);\r
+        }\r
+\r
+        private static bool IsValidActionMethod(MethodInfo methodInfo, bool stripInfrastructureMethods) {\r
+            if (methodInfo.IsSpecialName) {\r
+                // not a normal method, e.g. a constructor or an event\r
+                return false;\r
+            }\r
+\r
+            if (methodInfo.GetBaseDefinition().DeclaringType.IsAssignableFrom(typeof(AsyncController))) {\r
+                // is a method on Object, ControllerBase, Controller, or AsyncController\r
+                return false;\r
+            };\r
+\r
+            if (stripInfrastructureMethods) {\r
+                if (IsCompletedSuffixedMethod(methodInfo)) {\r
+                    // do not match FooCompleted() methods, as these are infrastructure methods\r
+                    return false;\r
+                }\r
+            }\r
+\r
+            return true;\r
+        }\r
+\r
+        private void PopulateLookupTables() {\r
+            MethodInfo[] allMethods = ControllerType.GetMethods(BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public);\r
+            MethodInfo[] actionMethods = Array.FindAll(allMethods, IsValidActionMethod);\r
+\r
+            AliasedMethods = Array.FindAll(actionMethods, IsMethodDecoratedWithAliasingAttribute);\r
+            NonAliasedMethods = actionMethods.Except(AliasedMethods).ToLookup(GetCanonicalMethodName, StringComparer.OrdinalIgnoreCase);\r
+        }\r
+\r
+        private static List<MethodInfo> RunSelectionFilters(ControllerContext controllerContext, List<MethodInfo> methodInfos) {\r
+            // remove all methods which are opting out of this request\r
+            // to opt out, at least one attribute defined on the method must return false\r
+\r
+            List<MethodInfo> matchesWithSelectionAttributes = new List<MethodInfo>();\r
+            List<MethodInfo> matchesWithoutSelectionAttributes = new List<MethodInfo>();\r
+\r
+            foreach (MethodInfo methodInfo in methodInfos) {\r
+                ActionMethodSelectorAttribute[] attrs = (ActionMethodSelectorAttribute[])methodInfo.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true /* inherit */);\r
+                if (attrs.Length == 0) {\r
+                    matchesWithoutSelectionAttributes.Add(methodInfo);\r
+                }\r
+                else if (attrs.All(attr => attr.IsValidForRequest(controllerContext, methodInfo))) {\r
+                    matchesWithSelectionAttributes.Add(methodInfo);\r
+                }\r
+            }\r
+\r
+            // if a matching action method had a selection attribute, consider it more specific than a matching action method\r
+            // without a selection attribute\r
+            return (matchesWithSelectionAttributes.Count > 0) ? matchesWithSelectionAttributes : matchesWithoutSelectionAttributes;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncControllerActionInvoker.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncControllerActionInvoker.cs
new file mode 100644 (file)
index 0000000..cf1349e
--- /dev/null
@@ -0,0 +1,282 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Linq;\r
+    using System.Threading;\r
+\r
+    public class AsyncControllerActionInvoker : ControllerActionInvoker, IAsyncActionInvoker {\r
+\r
+        private static readonly object _invokeActionTag = new object();\r
+        private static readonly object _invokeActionMethodTag = new object();\r
+        private static readonly object _invokeActionMethodWithFiltersTag = new object();\r
+\r
+        public virtual IAsyncResult BeginInvokeAction(ControllerContext controllerContext, string actionName, AsyncCallback callback, object state) {\r
+            if (controllerContext == null) {\r
+                throw new ArgumentNullException("controllerContext");\r
+            }\r
+            if (String.IsNullOrEmpty(actionName)) {\r
+                throw Error.ParameterCannotBeNullOrEmpty("actionName");\r
+            }\r
+\r
+            ControllerDescriptor controllerDescriptor = GetControllerDescriptor(controllerContext);\r
+            ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName);\r
+            if (actionDescriptor != null) {\r
+                FilterInfo filterInfo = GetFilters(controllerContext, actionDescriptor);\r
+                Action continuation = null;\r
+\r
+                BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState) {\r
+                    try {\r
+                        AuthorizationContext authContext = InvokeAuthorizationFilters(controllerContext, filterInfo.AuthorizationFilters, actionDescriptor);\r
+                        if (authContext.Result != null) {\r
+                            // the auth filter signaled that we should let it short-circuit the request\r
+                            continuation = () => InvokeActionResult(controllerContext, authContext.Result);\r
+                        }\r
+                        else {\r
+                            if (controllerContext.Controller.ValidateRequest) {\r
+                                ValidateRequest(controllerContext);\r
+                            }\r
+\r
+                            IDictionary<string, object> parameters = GetParameterValues(controllerContext, actionDescriptor);\r
+                            IAsyncResult asyncResult = BeginInvokeActionMethodWithFilters(controllerContext, filterInfo.ActionFilters, actionDescriptor, parameters, asyncCallback, asyncState);\r
+                            continuation = () => {\r
+                                ActionExecutedContext postActionContext = EndInvokeActionMethodWithFilters(asyncResult);\r
+                                InvokeActionResultWithFilters(controllerContext, filterInfo.ResultFilters, postActionContext.Result);\r
+                            };\r
+                            return asyncResult;\r
+                        }\r
+                    }\r
+                    catch (ThreadAbortException) {\r
+                        // This type of exception occurs as a result of Response.Redirect(), but we special-case so that\r
+                        // the filters don't see this as an error.\r
+                        throw;\r
+                    }\r
+                    catch (Exception ex) {\r
+                        // something blew up, so execute the exception filters\r
+                        ExceptionContext exceptionContext = InvokeExceptionFilters(controllerContext, filterInfo.ExceptionFilters, ex);\r
+                        if (!exceptionContext.ExceptionHandled) {\r
+                            throw;\r
+                        }\r
+\r
+                        continuation = () => InvokeActionResult(controllerContext, exceptionContext.Result);\r
+                    }\r
+\r
+                    return BeginInvokeAction_MakeSynchronousAsyncResult(asyncCallback, asyncState);\r
+                };\r
+\r
+                EndInvokeDelegate<bool> endDelegate = delegate(IAsyncResult asyncResult) {\r
+                    try {\r
+                        continuation();\r
+                    }\r
+                    catch (ThreadAbortException) {\r
+                        // This type of exception occurs as a result of Response.Redirect(), but we special-case so that\r
+                        // the filters don't see this as an error.\r
+                        throw;\r
+                    }\r
+                    catch (Exception ex) {\r
+                        // something blew up, so execute the exception filters\r
+                        ExceptionContext exceptionContext = InvokeExceptionFilters(controllerContext, filterInfo.ExceptionFilters, ex);\r
+                        if (!exceptionContext.ExceptionHandled) {\r
+                            throw;\r
+                        }\r
+                        InvokeActionResult(controllerContext, exceptionContext.Result);\r
+                    }\r
+\r
+                    return true;\r
+                };\r
+\r
+                return AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _invokeActionTag);\r
+            }\r
+            else {\r
+                // Notify the controller that no action was found.\r
+                return BeginInvokeAction_ActionNotFound(callback, state);\r
+            }\r
+        }\r
+\r
+        private static IAsyncResult BeginInvokeAction_ActionNotFound(AsyncCallback callback, object state) {\r
+            BeginInvokeDelegate beginDelegate = BeginInvokeAction_MakeSynchronousAsyncResult;\r
+\r
+            EndInvokeDelegate<bool> endDelegate = delegate(IAsyncResult asyncResult) {\r
+                return false;\r
+            };\r
+\r
+            return AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _invokeActionTag);\r
+        }\r
+\r
+        private static IAsyncResult BeginInvokeAction_MakeSynchronousAsyncResult(AsyncCallback callback, object state) {\r
+            SimpleAsyncResult asyncResult = new SimpleAsyncResult(state);\r
+            asyncResult.MarkCompleted(true /* completedSynchronously */, callback);\r
+            return asyncResult;\r
+        }\r
+\r
+        protected internal virtual IAsyncResult BeginInvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters, AsyncCallback callback, object state) {\r
+            AsyncActionDescriptor asyncActionDescriptor = actionDescriptor as AsyncActionDescriptor;\r
+            if (asyncActionDescriptor != null) {\r
+                return BeginInvokeAsynchronousActionMethod(controllerContext, asyncActionDescriptor, parameters, callback, state);\r
+            }\r
+            else {\r
+                return BeginInvokeSynchronousActionMethod(controllerContext, actionDescriptor, parameters, callback, state);\r
+            }\r
+        }\r
+\r
+        protected internal virtual IAsyncResult BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList<IActionFilter> filters, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters, AsyncCallback callback, object state) {\r
+            Func<ActionExecutedContext> endContinuation = null;\r
+\r
+            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState) {\r
+                ActionExecutingContext preContext = new ActionExecutingContext(controllerContext, actionDescriptor, parameters);\r
+                IAsyncResult innerAsyncResult = null;\r
+\r
+                Func<Func<ActionExecutedContext>> beginContinuation = () => {\r
+                    innerAsyncResult = BeginInvokeActionMethod(controllerContext, actionDescriptor, parameters, asyncCallback, asyncState);\r
+                    return () =>\r
+                        new ActionExecutedContext(controllerContext, actionDescriptor, false /* canceled */, null /* exception */) {\r
+                            Result = EndInvokeActionMethod(innerAsyncResult)\r
+                        };\r
+                };\r
+\r
+                // need to reverse the filter list because the continuations are built up backward\r
+                Func<Func<ActionExecutedContext>> thunk = filters.Reverse().Aggregate(beginContinuation,\r
+                    (next, filter) => () => InvokeActionMethodFilterAsynchronously(filter, preContext, next));\r
+                endContinuation = thunk();\r
+\r
+                if (innerAsyncResult != null) {\r
+                    // we're just waiting for the inner result to complete\r
+                    return innerAsyncResult;\r
+                }\r
+                else {\r
+                    // something was short-circuited and the action was not called, so this was a synchronous operation\r
+                    SimpleAsyncResult newAsyncResult = new SimpleAsyncResult(asyncState);\r
+                    newAsyncResult.MarkCompleted(true /* completedSynchronously */, asyncCallback);\r
+                    return newAsyncResult;\r
+                }\r
+            };\r
+\r
+            EndInvokeDelegate<ActionExecutedContext> endDelegate = delegate(IAsyncResult asyncResult) {\r
+                return endContinuation();\r
+            };\r
+\r
+            return AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _invokeActionMethodWithFiltersTag);\r
+        }\r
+\r
+        private IAsyncResult BeginInvokeAsynchronousActionMethod(ControllerContext controllerContext, AsyncActionDescriptor actionDescriptor, IDictionary<string, object> parameters, AsyncCallback callback, object state) {\r
+            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState) {\r
+                return actionDescriptor.BeginExecute(controllerContext, parameters, asyncCallback, asyncState);\r
+            };\r
+\r
+            EndInvokeDelegate<ActionResult> endDelegate = delegate(IAsyncResult asyncResult) {\r
+                object returnValue = actionDescriptor.EndExecute(asyncResult);\r
+                ActionResult result = CreateActionResult(controllerContext, actionDescriptor, returnValue);\r
+                return result;\r
+            };\r
+\r
+            return AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _invokeActionMethodTag);\r
+        }\r
+\r
+        private IAsyncResult BeginInvokeSynchronousActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters, AsyncCallback callback, object state) {\r
+            return AsyncResultWrapper.BeginSynchronous(callback, state,\r
+                () => InvokeSynchronousActionMethod(controllerContext, actionDescriptor, parameters),\r
+                _invokeActionMethodTag);\r
+        }\r
+\r
+        public virtual bool EndInvokeAction(IAsyncResult asyncResult) {\r
+            return AsyncResultWrapper.End<bool>(asyncResult, _invokeActionTag);\r
+        }\r
+\r
+        protected internal virtual ActionResult EndInvokeActionMethod(IAsyncResult asyncResult) {\r
+            return AsyncResultWrapper.End<ActionResult>(asyncResult, _invokeActionMethodTag);\r
+        }\r
+\r
+        protected internal virtual ActionExecutedContext EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) {\r
+            return AsyncResultWrapper.End<ActionExecutedContext>(asyncResult, _invokeActionMethodWithFiltersTag);\r
+        }\r
+\r
+        protected override ControllerDescriptor GetControllerDescriptor(ControllerContext controllerContext) {\r
+            Type controllerType = controllerContext.Controller.GetType();\r
+            ControllerDescriptor controllerDescriptor = DescriptorCache.GetDescriptor(controllerType, () => new ReflectedAsyncControllerDescriptor(controllerType));\r
+            return controllerDescriptor;\r
+        }\r
+\r
+        internal static Func<ActionExecutedContext> InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func<Func<ActionExecutedContext>> nextInChain) {\r
+            filter.OnActionExecuting(preContext);\r
+            if (preContext.Result != null) {\r
+                ActionExecutedContext shortCircuitedPostContext = new ActionExecutedContext(preContext, preContext.ActionDescriptor, true /* canceled */, null /* exception */) {\r
+                    Result = preContext.Result\r
+                };\r
+                return () => shortCircuitedPostContext;\r
+            }\r
+\r
+            // There is a nested try / catch block here that contains much the same logic as the outer block.\r
+            // Since an exception can occur on either side of the asynchronous invocation, we need guards on\r
+            // on both sides. In the code below, the second side is represented by the nested delegate. This\r
+            // is really just a parallel of the synchronous ControllerActionInvoker.InvokeActionMethodFilter()\r
+            // method.\r
+\r
+            try {\r
+                Func<ActionExecutedContext> continuation = nextInChain();\r
+\r
+                // add our own continuation, then return the new function\r
+                return () => {\r
+                    ActionExecutedContext postContext;\r
+                    bool wasError = true;\r
+\r
+                    try {\r
+                        postContext = continuation();\r
+                        wasError = false;\r
+                    }\r
+                    catch (ThreadAbortException) {\r
+                        // This type of exception occurs as a result of Response.Redirect(), but we special-case so that\r
+                        // the filters don't see this as an error.\r
+                        postContext = new ActionExecutedContext(preContext, preContext.ActionDescriptor, false /* canceled */, null /* exception */);\r
+                        filter.OnActionExecuted(postContext);\r
+                        throw;\r
+                    }\r
+                    catch (Exception ex) {\r
+                        postContext = new ActionExecutedContext(preContext, preContext.ActionDescriptor, false /* canceled */, ex);\r
+                        filter.OnActionExecuted(postContext);\r
+                        if (!postContext.ExceptionHandled) {\r
+                            throw;\r
+                        }\r
+                    }\r
+                    if (!wasError) {\r
+                        filter.OnActionExecuted(postContext);\r
+                    }\r
+\r
+                    return postContext;\r
+                };\r
+            }\r
+            catch (ThreadAbortException) {\r
+                // This type of exception occurs as a result of Response.Redirect(), but we special-case so that\r
+                // the filters don't see this as an error.\r
+                ActionExecutedContext postContext = new ActionExecutedContext(preContext, preContext.ActionDescriptor, false /* canceled */, null /* exception */);\r
+                filter.OnActionExecuted(postContext);\r
+                throw;\r
+            }\r
+            catch (Exception ex) {\r
+                ActionExecutedContext postContext = new ActionExecutedContext(preContext, preContext.ActionDescriptor, false /* canceled */, ex);\r
+                filter.OnActionExecuted(postContext);\r
+                if (postContext.ExceptionHandled) {\r
+                    return () => postContext;\r
+                }\r
+                else {\r
+                    throw;\r
+                }\r
+            }\r
+        }\r
+\r
+        private ActionResult InvokeSynchronousActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters) {\r
+            return base.InvokeActionMethod(controllerContext, actionDescriptor, parameters);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncManager.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncManager.cs
new file mode 100644 (file)
index 0000000..082f460
--- /dev/null
@@ -0,0 +1,79 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Threading;\r
+\r
+    public class AsyncManager {\r
+\r
+        private readonly SynchronizationContext _syncContext;\r
+\r
+        // default timeout is 45 sec\r
+        // from: http://msdn.microsoft.com/en-us/library/system.web.ui.page.asynctimeout.aspx\r
+        private int _timeout = 45 * 1000;\r
+\r
+        public AsyncManager()\r
+            : this(null /* syncContext */) {\r
+        }\r
+\r
+        public AsyncManager(SynchronizationContext syncContext) {\r
+            _syncContext = syncContext ?? SynchronizationContextUtil.GetSynchronizationContext();\r
+\r
+            OutstandingOperations = new OperationCounter();\r
+            OutstandingOperations.Completed += delegate { Finish(); };\r
+\r
+            Parameters = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\r
+        }\r
+\r
+        public OperationCounter OutstandingOperations {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public IDictionary<string, object> Parameters {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public event EventHandler Finished;\r
+\r
+        // the developer may call this function to signal that all operations are complete instead of\r
+        // waiting for the operation counter to reach zero\r
+        public virtual void Finish() {\r
+            EventHandler handler = Finished;\r
+            if (handler != null) {\r
+                handler(this, EventArgs.Empty);\r
+            }\r
+        }\r
+\r
+        // executes a callback in the current synchronization context, which gives access to HttpContext and related items\r
+        public virtual void Sync(Action action) {\r
+            _syncContext.Sync(action);\r
+        }\r
+\r
+        // measured in milliseconds, Timeout.Infinite means 'no timeout'\r
+        public int Timeout {\r
+            get {\r
+                return _timeout;\r
+            }\r
+            set {\r
+                if (value < -1) {\r
+                    throw Error.AsyncCommon_InvalidTimeout("value");\r
+                }\r
+                _timeout = value;\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncResultWrapper.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncResultWrapper.cs
new file mode 100644 (file)
index 0000000..1f42f51
--- /dev/null
@@ -0,0 +1,265 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Threading;\r
+\r
+    // This class is used for the following pattern:\r
+\r
+    // public IAsyncResult BeginInner(..., callback, state);\r
+    // public TInnerResult EndInner(asyncResult);\r
+    // public IAsyncResult BeginOuter(..., callback, state);\r
+    // public TOuterResult EndOuter(asyncResult);\r
+\r
+    // That is, Begin/EndOuter() wrap Begin/EndInner(), potentially with pre- and post-processing.\r
+\r
+    internal static class AsyncResultWrapper {\r
+\r
+        // helper methods\r
+\r
+        private static Func<AsyncVoid> MakeVoidDelegate(Action action) {\r
+            return () => {\r
+                action();\r
+                return default(AsyncVoid);\r
+            };\r
+        }\r
+\r
+        private static EndInvokeDelegate<AsyncVoid> MakeVoidDelegate(EndInvokeDelegate endDelegate) {\r
+            return ar => {\r
+                endDelegate(ar);\r
+                return default(AsyncVoid);\r
+            };\r
+        }\r
+\r
+        // kicks off an asynchronous operation\r
+\r
+        public static IAsyncResult Begin<TResult>(AsyncCallback callback, object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate<TResult> endDelegate) {\r
+            return Begin<TResult>(callback, state, beginDelegate, endDelegate, null /* tag */);\r
+        }\r
+\r
+        public static IAsyncResult Begin<TResult>(AsyncCallback callback, object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate<TResult> endDelegate, object tag) {\r
+            return Begin<TResult>(callback, state, beginDelegate, endDelegate, tag, Timeout.Infinite);\r
+        }\r
+\r
+        public static IAsyncResult Begin<TResult>(AsyncCallback callback, object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate<TResult> endDelegate, object tag, int timeout) {\r
+            WrappedAsyncResult<TResult> asyncResult = new WrappedAsyncResult<TResult>(beginDelegate, endDelegate, tag);\r
+            asyncResult.Begin(callback, state, timeout);\r
+            return asyncResult;\r
+        }\r
+\r
+        public static IAsyncResult Begin(AsyncCallback callback, object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate) {\r
+            return Begin(callback, state, beginDelegate, endDelegate, null /* tag */);\r
+        }\r
+\r
+        public static IAsyncResult Begin(AsyncCallback callback, object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, object tag) {\r
+            return Begin(callback, state, beginDelegate, endDelegate, tag, Timeout.Infinite);\r
+        }\r
+\r
+        public static IAsyncResult Begin(AsyncCallback callback, object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, object tag, int timeout) {\r
+            return Begin<AsyncVoid>(callback, state, beginDelegate, MakeVoidDelegate(endDelegate), tag, timeout);\r
+        }\r
+\r
+        // wraps a synchronous operation in an asynchronous wrapper, but still completes synchronously\r
+\r
+        public static IAsyncResult BeginSynchronous<TResult>(AsyncCallback callback, object state, Func<TResult> func) {\r
+            return BeginSynchronous<TResult>(callback, state, func, null /* tag */);\r
+        }\r
+\r
+        public static IAsyncResult BeginSynchronous<TResult>(AsyncCallback callback, object state, Func<TResult> func, object tag) {\r
+            // Begin() doesn't perform any work on its own and returns immediately.\r
+            BeginInvokeDelegate beginDelegate = (asyncCallback, asyncState) => {\r
+                SimpleAsyncResult innerAsyncResult = new SimpleAsyncResult(asyncState);\r
+                innerAsyncResult.MarkCompleted(true /* completedSynchronously */, asyncCallback);\r
+                return innerAsyncResult;\r
+            };\r
+\r
+            // The End() method blocks.\r
+            EndInvokeDelegate<TResult> endDelegate = _ => {\r
+                return func();\r
+            };\r
+\r
+            WrappedAsyncResult<TResult> asyncResult = new WrappedAsyncResult<TResult>(beginDelegate, endDelegate, tag);\r
+            asyncResult.Begin(callback, state, Timeout.Infinite);\r
+            return asyncResult;\r
+        }\r
+\r
+        public static IAsyncResult BeginSynchronous(AsyncCallback callback, object state, Action action) {\r
+            return BeginSynchronous(callback, state, action, null /* tag */);\r
+        }\r
+\r
+        public static IAsyncResult BeginSynchronous(AsyncCallback callback, object state, Action action, object tag) {\r
+            return BeginSynchronous<AsyncVoid>(callback, state, MakeVoidDelegate(action), tag);\r
+        }\r
+\r
+        // completes an asynchronous operation\r
+\r
+        public static TResult End<TResult>(IAsyncResult asyncResult) {\r
+            return End<TResult>(asyncResult, null /* tag */);\r
+        }\r
+\r
+        public static TResult End<TResult>(IAsyncResult asyncResult, object tag) {\r
+            return WrappedAsyncResult<TResult>.Cast(asyncResult, tag).End();\r
+        }\r
+\r
+        public static void End(IAsyncResult asyncResult) {\r
+            End(asyncResult, null /* tag */);\r
+        }\r
+\r
+        public static void End(IAsyncResult asyncResult, object tag) {\r
+            End<AsyncVoid>(asyncResult, tag);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",\r
+            Justification = "The Timer will be disposed of either when it fires or when the operation completes successfully.")]\r
+        private sealed class WrappedAsyncResult<TResult> : IAsyncResult {\r
+\r
+            private readonly BeginInvokeDelegate _beginDelegate;\r
+            private readonly object _beginDelegateLockObj = new object();\r
+            private readonly EndInvokeDelegate<TResult> _endDelegate;\r
+            private readonly SingleEntryGate _endExecutedGate = new SingleEntryGate(); // prevent End() from being called twice\r
+            private readonly SingleEntryGate _handleCallbackGate = new SingleEntryGate(); // prevent callback from being handled multiple times\r
+            private IAsyncResult _innerAsyncResult;\r
+            private AsyncCallback _originalCallback;\r
+            private readonly object _tag; // prevent an instance of this type from being passed to the wrong End() method\r
+            private volatile bool _timedOut;\r
+            private Timer _timer;\r
+\r
+            public WrappedAsyncResult(BeginInvokeDelegate beginDelegate, EndInvokeDelegate<TResult> endDelegate, object tag) {\r
+                _beginDelegate = beginDelegate;\r
+                _endDelegate = endDelegate;\r
+                _tag = tag;\r
+            }\r
+\r
+            public object AsyncState {\r
+                get {\r
+                    return _innerAsyncResult.AsyncState;\r
+                }\r
+            }\r
+\r
+            public WaitHandle AsyncWaitHandle {\r
+                get {\r
+                    return _innerAsyncResult.AsyncWaitHandle;\r
+                }\r
+            }\r
+\r
+            public bool CompletedSynchronously {\r
+                get {\r
+                    return _innerAsyncResult.CompletedSynchronously;\r
+                }\r
+            }\r
+\r
+            public bool IsCompleted {\r
+                get {\r
+                    return _innerAsyncResult.IsCompleted;\r
+                }\r
+            }\r
+\r
+            // kicks off the process, instantiates a timer if requested\r
+            public void Begin(AsyncCallback callback, object state, int timeout) {\r
+                _originalCallback = callback;\r
+                bool completedSynchronously;\r
+\r
+                // Force the target Begin() operation to complete before the callback can continue,\r
+                // since the target operation might perform post-processing of the data.\r
+                lock (_beginDelegateLockObj) {\r
+                    _innerAsyncResult = _beginDelegate(HandleAsynchronousCompletion, state);\r
+\r
+                    completedSynchronously = _innerAsyncResult.CompletedSynchronously;\r
+                    if (!completedSynchronously) {\r
+                        if (timeout > Timeout.Infinite) {\r
+                            CreateTimer(timeout);\r
+                        }\r
+                    }\r
+                }\r
+\r
+                if (completedSynchronously) {\r
+                    if (callback != null) {\r
+                        callback(this);\r
+                    }\r
+                }\r
+            }\r
+\r
+            public static WrappedAsyncResult<TResult> Cast(IAsyncResult asyncResult, object tag) {\r
+                if (asyncResult == null) {\r
+                    throw new ArgumentNullException("asyncResult");\r
+                }\r
+\r
+                WrappedAsyncResult<TResult> castResult = asyncResult as WrappedAsyncResult<TResult>;\r
+                if (castResult != null && Object.Equals(castResult._tag, tag)) {\r
+                    return castResult;\r
+                }\r
+                else {\r
+                    throw Error.AsyncCommon_InvalidAsyncResult("asyncResult");\r
+                }\r
+            }\r
+\r
+            private void CreateTimer(int timeout) {\r
+                // this method should be called within a lock(_beginDelegateLockObj)\r
+                _timer = new Timer(HandleTimeout, null, timeout, Timeout.Infinite /* disable periodic signaling */);\r
+            }\r
+\r
+            public TResult End() {\r
+                if (!_endExecutedGate.TryEnter()) {\r
+                    throw Error.AsyncCommon_AsyncResultAlreadyConsumed();\r
+                }\r
+\r
+                if (_timedOut) {\r
+                    throw new TimeoutException();\r
+                }\r
+                WaitForBeginToCompleteAndDestroyTimer();\r
+\r
+                return _endDelegate(_innerAsyncResult);\r
+            }\r
+\r
+            private void ExecuteAsynchronousCallback(bool timedOut) {\r
+                WaitForBeginToCompleteAndDestroyTimer();\r
+\r
+                if (_handleCallbackGate.TryEnter()) {\r
+                    _timedOut = timedOut;\r
+                    if (_originalCallback != null) {\r
+                        _originalCallback(this);\r
+                    }\r
+                }\r
+            }\r
+\r
+            private void HandleAsynchronousCompletion(IAsyncResult asyncResult) {\r
+                if (asyncResult.CompletedSynchronously) {\r
+                    // If the operation completed synchronously, the WrappedAsyncResult.Begin() method will handle it.\r
+                    return;\r
+                }\r
+\r
+                ExecuteAsynchronousCallback(false /* timedOut */);\r
+            }\r
+\r
+            private void HandleTimeout(object state) {\r
+                ExecuteAsynchronousCallback(true /* timedOut */);\r
+            }\r
+\r
+            private void WaitForBeginToCompleteAndDestroyTimer() {\r
+                lock (_beginDelegateLockObj) {\r
+                    // Wait for the target Begin() method to complete, as it might be performing\r
+                    // post-processing. This also forces a memory barrier, so _innerAsyncResult\r
+                    // is guaranteed to be non-null at this point.\r
+\r
+                    if (_timer != null) {\r
+                        _timer.Dispose();\r
+                    }\r
+                    _timer = null;\r
+                }\r
+            }\r
+\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncUtil.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncUtil.cs
new file mode 100644 (file)
index 0000000..64484cf
--- /dev/null
@@ -0,0 +1,75 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+    using System.Threading;\r
+\r
+    internal static class AsyncUtil {\r
+\r
+        public static void WaitForAsyncResultCompletion(IAsyncResult asyncResult, HttpApplication app) {\r
+            // based on HttpServerUtility.ExecuteInternal()\r
+\r
+            if (!asyncResult.IsCompleted) {\r
+                // suspend app lock while waiting, else might deadlock\r
+                bool needToRelock = false;\r
+\r
+                try {\r
+                    // .NET 2.0+ will not allow a ThreadAbortException to be thrown while a\r
+                    // thread is inside a finally block, so this pattern ensures that the\r
+                    // value of 'needToRelock' is correct.\r
+                    try { }\r
+                    finally {\r
+                        Monitor.Exit(app);\r
+                        needToRelock = true;\r
+                    }\r
+\r
+                    WaitHandle waitHandle = asyncResult.AsyncWaitHandle;\r
+\r
+                    if (waitHandle != null) {\r
+                        waitHandle.WaitOne();\r
+                    }\r
+                    else {\r
+                        while (!asyncResult.IsCompleted) {\r
+                            Thread.Sleep(1);\r
+                        }\r
+                    }\r
+                }\r
+                finally {\r
+                    if (needToRelock) {\r
+                        Monitor.Enter(app);\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+        public static AsyncCallback WrapCallbackForSynchronizedExecution(AsyncCallback callback, SynchronizationContext syncContext) {\r
+            if (callback == null || syncContext == null) {\r
+                return callback;\r
+            }\r
+\r
+            AsyncCallback newCallback = delegate(IAsyncResult asyncResult) {\r
+                if (asyncResult.CompletedSynchronously) {\r
+                    callback(asyncResult);\r
+                }\r
+                else {\r
+                    // Only take the application lock if this request completed asynchronously,\r
+                    // else we might end up in a deadlock situation.\r
+                    syncContext.Sync(() => callback(asyncResult));\r
+                }\r
+            };\r
+\r
+            return newCallback;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncVoid.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/AsyncVoid.cs
new file mode 100644 (file)
index 0000000..95a81ce
--- /dev/null
@@ -0,0 +1,19 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+\r
+    // Dummy type used for passing something resembling 'void' to the async delegate functions\r
+    internal struct AsyncVoid {\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/BeginInvokeDelegate.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/BeginInvokeDelegate.cs
new file mode 100644 (file)
index 0000000..5d568f4
--- /dev/null
@@ -0,0 +1,17 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+\r
+    internal delegate IAsyncResult BeginInvokeDelegate(AsyncCallback callback, object state);\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/EndInvokeDelegate.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/EndInvokeDelegate.cs
new file mode 100644 (file)
index 0000000..11308df
--- /dev/null
@@ -0,0 +1,17 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+\r
+    internal delegate void EndInvokeDelegate(IAsyncResult asyncResult);\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/EndInvokeDelegate`1.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/EndInvokeDelegate`1.cs
new file mode 100644 (file)
index 0000000..9e83896
--- /dev/null
@@ -0,0 +1,17 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+\r
+    internal delegate TResult EndInvokeDelegate<TResult>(IAsyncResult asyncResult);\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/IAsyncActionInvoker.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/IAsyncActionInvoker.cs
new file mode 100644 (file)
index 0000000..acd624b
--- /dev/null
@@ -0,0 +1,20 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+\r
+    public interface IAsyncActionInvoker : IActionInvoker {\r
+        IAsyncResult BeginInvokeAction(ControllerContext controllerContext, string actionName, AsyncCallback callback, object state);\r
+        bool EndInvokeAction(IAsyncResult asyncResult);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/IAsyncController.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/IAsyncController.cs
new file mode 100644 (file)
index 0000000..fe256e8
--- /dev/null
@@ -0,0 +1,20 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System.Web.Routing;\r
+\r
+    public interface IAsyncController : IController {\r
+        IAsyncResult BeginExecute(RequestContext requestContext, AsyncCallback callback, object state);\r
+        void EndExecute(IAsyncResult asyncResult);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/IAsyncManagerContainer.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/IAsyncManagerContainer.cs
new file mode 100644 (file)
index 0000000..f9aa6ad
--- /dev/null
@@ -0,0 +1,22 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+\r
+    public interface IAsyncManagerContainer {\r
+\r
+        AsyncManager AsyncManager {\r
+            get;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/OperationCounter.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/OperationCounter.cs
new file mode 100644 (file)
index 0000000..519f6ed
--- /dev/null
@@ -0,0 +1,62 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+    using System.Threading;\r
+\r
+    public sealed class OperationCounter {\r
+\r
+        private int _count;\r
+\r
+        public int Count {\r
+            get {\r
+                return Thread.VolatileRead(ref _count);\r
+            }\r
+        }\r
+\r
+        public event EventHandler Completed;\r
+\r
+        private int AddAndExecuteCallbackIfCompleted(int value) {\r
+            int newCount = Interlocked.Add(ref _count, value);\r
+            if (newCount == 0) {\r
+                OnCompleted();\r
+            }\r
+\r
+            return newCount;\r
+        }\r
+\r
+        public int Decrement() {\r
+            return AddAndExecuteCallbackIfCompleted(-1);\r
+        }\r
+\r
+        public int Decrement(int value) {\r
+            return AddAndExecuteCallbackIfCompleted(-value);\r
+        }\r
+\r
+        public int Increment() {\r
+            return AddAndExecuteCallbackIfCompleted(1);\r
+        }\r
+\r
+        public int Increment(int value) {\r
+            return AddAndExecuteCallbackIfCompleted(value);\r
+        }\r
+\r
+        private void OnCompleted() {\r
+            EventHandler handler = Completed;\r
+            if (handler != null) {\r
+                handler(this, EventArgs.Empty);\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/ReflectedAsyncActionDescriptor.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/ReflectedAsyncActionDescriptor.cs
new file mode 100644 (file)
index 0000000..397a5a2
--- /dev/null
@@ -0,0 +1,183 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Linq;\r
+    using System.Reflection;\r
+    using System.Threading;\r
+\r
+    public class ReflectedAsyncActionDescriptor : AsyncActionDescriptor {\r
+\r
+        private readonly object _executeTag = new object();\r
+\r
+        private readonly string _actionName;\r
+        private readonly ControllerDescriptor _controllerDescriptor;\r
+        private ParameterDescriptor[] _parametersCache;\r
+\r
+        public ReflectedAsyncActionDescriptor(MethodInfo asyncMethodInfo, MethodInfo completedMethodInfo, string actionName, ControllerDescriptor controllerDescriptor)\r
+            : this(asyncMethodInfo, completedMethodInfo, actionName, controllerDescriptor, true /* validateMethods */) {\r
+        }\r
+\r
+        internal ReflectedAsyncActionDescriptor(MethodInfo asyncMethodInfo, MethodInfo completedMethodInfo, string actionName, ControllerDescriptor controllerDescriptor, bool validateMethods) {\r
+            if (asyncMethodInfo == null) {\r
+                throw new ArgumentNullException("asyncMethodInfo");\r
+            }\r
+            if (completedMethodInfo == null) {\r
+                throw new ArgumentNullException("completedMethodInfo");\r
+            }\r
+            if (String.IsNullOrEmpty(actionName)) {\r
+                throw Error.ParameterCannotBeNullOrEmpty("actionName");\r
+            }\r
+            if (controllerDescriptor == null) {\r
+                throw new ArgumentNullException("controllerDescriptor");\r
+            }\r
+\r
+            if (validateMethods) {\r
+                string asyncFailedMessage = VerifyActionMethodIsCallable(asyncMethodInfo);\r
+                if (asyncFailedMessage != null) {\r
+                    throw new ArgumentException(asyncFailedMessage, "asyncMethodInfo");\r
+                }\r
+\r
+                string completedFailedMessage = VerifyActionMethodIsCallable(completedMethodInfo);\r
+                if (completedFailedMessage != null) {\r
+                    throw new ArgumentException(completedFailedMessage, "completedMethodInfo");\r
+                }\r
+            }\r
+\r
+            AsyncMethodInfo = asyncMethodInfo;\r
+            CompletedMethodInfo = completedMethodInfo;\r
+            _actionName = actionName;\r
+            _controllerDescriptor = controllerDescriptor;\r
+        }\r
+\r
+        public override string ActionName {\r
+            get {\r
+                return _actionName;\r
+            }\r
+        }\r
+\r
+        public MethodInfo AsyncMethodInfo {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public MethodInfo CompletedMethodInfo {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public override ControllerDescriptor ControllerDescriptor {\r
+            get {\r
+                return _controllerDescriptor;\r
+            }\r
+        }\r
+\r
+        public override IAsyncResult BeginExecute(ControllerContext controllerContext, IDictionary<string, object> parameters, AsyncCallback callback, object state) {\r
+            if (controllerContext == null) {\r
+                throw new ArgumentNullException("controllerContext");\r
+            }\r
+            if (parameters == null) {\r
+                throw new ArgumentNullException("parameters");\r
+            }\r
+\r
+            AsyncManager asyncManager = GetAsyncManager(controllerContext.Controller);\r
+\r
+            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState) {\r
+                // call the XxxAsync() method\r
+                ParameterInfo[] parameterInfos = AsyncMethodInfo.GetParameters();\r
+                var rawParameterValues = from parameterInfo in parameterInfos\r
+                                         select ExtractParameterFromDictionary(parameterInfo, parameters, AsyncMethodInfo);\r
+                object[] parametersArray = rawParameterValues.ToArray();\r
+\r
+                TriggerListener listener = new TriggerListener();\r
+                SimpleAsyncResult asyncResult = new SimpleAsyncResult(asyncState);\r
+\r
+                // hook the Finished event to notify us upon completion\r
+                Trigger finishTrigger = listener.CreateTrigger();\r
+                asyncManager.Finished += delegate { finishTrigger.Fire(); };\r
+                asyncManager.OutstandingOperations.Increment();\r
+\r
+                // to simplify the logic, force the rest of the pipeline to execute in an asynchronous callback\r
+                listener.SetContinuation(() => ThreadPool.QueueUserWorkItem(_ => asyncResult.MarkCompleted(false /* completedSynchronously */, asyncCallback)));\r
+\r
+                // the inner operation might complete synchronously, so all setup work has to be done before this point\r
+                ActionMethodDispatcher dispatcher = DispatcherCache.GetDispatcher(AsyncMethodInfo);\r
+                dispatcher.Execute(controllerContext.Controller, parametersArray); // ignore return value from this method\r
+\r
+                // now that the XxxAsync() method has completed, kick off any pending operations\r
+                asyncManager.OutstandingOperations.Decrement();\r
+                listener.Activate();\r
+                return asyncResult;\r
+            };\r
+\r
+            EndInvokeDelegate<object> endDelegate = delegate(IAsyncResult asyncResult) {\r
+                // call the XxxCompleted() method\r
+                ParameterInfo[] completionParametersInfos = CompletedMethodInfo.GetParameters();\r
+                var rawCompletionParameterValues = from parameterInfo in completionParametersInfos\r
+                                                   select ExtractParameterOrDefaultFromDictionary(parameterInfo, asyncManager.Parameters);\r
+                object[] completionParametersArray = rawCompletionParameterValues.ToArray();\r
+\r
+                ActionMethodDispatcher dispatcher = DispatcherCache.GetDispatcher(CompletedMethodInfo);\r
+                object actionReturnValue = dispatcher.Execute(controllerContext.Controller, completionParametersArray);\r
+                return actionReturnValue;\r
+            };\r
+\r
+            return AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _executeTag, asyncManager.Timeout);\r
+        }\r
+\r
+        public override object EndExecute(IAsyncResult asyncResult) {\r
+            return AsyncResultWrapper.End<object>(asyncResult, _executeTag);\r
+        }\r
+\r
+        public override object[] GetCustomAttributes(bool inherit) {\r
+            return AsyncMethodInfo.GetCustomAttributes(inherit);\r
+        }\r
+\r
+        public override object[] GetCustomAttributes(Type attributeType, bool inherit) {\r
+            return AsyncMethodInfo.GetCustomAttributes(attributeType, inherit);\r
+        }\r
+\r
+        public override FilterInfo GetFilters() {\r
+            // By default, we only look at filters on the XxxAsync() method.\r
+            return GetFilters(AsyncMethodInfo);\r
+        }\r
+\r
+        public override ParameterDescriptor[] GetParameters() {\r
+            ParameterDescriptor[] parameters = LazilyFetchParametersCollection();\r
+\r
+            // need to clone array so that user modifications aren't accidentally stored\r
+            return (ParameterDescriptor[])parameters.Clone();\r
+        }\r
+\r
+        public override ICollection<ActionSelector> GetSelectors() {\r
+            // By default, we only look at filters on the XxxAsync() method.\r
+\r
+            ActionMethodSelectorAttribute[] attrs = (ActionMethodSelectorAttribute[])AsyncMethodInfo.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true /* inherit */);\r
+            ActionSelector[] selectors = Array.ConvertAll(attrs, attr => (ActionSelector)(controllerContext => attr.IsValidForRequest(controllerContext, AsyncMethodInfo)));\r
+            return selectors;\r
+        }\r
+\r
+        public override bool IsDefined(Type attributeType, bool inherit) {\r
+            return AsyncMethodInfo.IsDefined(attributeType, inherit);\r
+        }\r
+\r
+        private ParameterDescriptor[] LazilyFetchParametersCollection() {\r
+            return DescriptorUtil.LazilyFetchOrCreateDescriptors<ParameterInfo, ParameterDescriptor>(\r
+                ref _parametersCache /* cacheLocation */,\r
+                AsyncMethodInfo.GetParameters /* initializer */,\r
+                parameterInfo => new ReflectedParameterDescriptor(parameterInfo, this) /* converter */);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/ReflectedAsyncControllerDescriptor.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/ReflectedAsyncControllerDescriptor.cs
new file mode 100644 (file)
index 0000000..ebbc938
--- /dev/null
@@ -0,0 +1,72 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+\r
+    public class ReflectedAsyncControllerDescriptor : ControllerDescriptor {\r
+\r
+        private static readonly ActionDescriptor[] _emptyCanonicalActions = new ActionDescriptor[0];\r
+\r
+        private readonly Type _controllerType;\r
+        private readonly AsyncActionMethodSelector _selector;\r
+\r
+        public ReflectedAsyncControllerDescriptor(Type controllerType) {\r
+            if (controllerType == null) {\r
+                throw new ArgumentNullException("controllerType");\r
+            }\r
+\r
+            _controllerType = controllerType;\r
+            _selector = new AsyncActionMethodSelector(_controllerType);\r
+        }\r
+\r
+        public sealed override Type ControllerType {\r
+            get {\r
+                return _controllerType;\r
+            }\r
+        }\r
+\r
+        public override ActionDescriptor FindAction(ControllerContext controllerContext, string actionName) {\r
+            if (controllerContext == null) {\r
+                throw new ArgumentNullException("controllerContext");\r
+            }\r
+            if (String.IsNullOrEmpty(actionName)) {\r
+                throw Error.ParameterCannotBeNullOrEmpty("actionName");\r
+            }\r
+\r
+            ActionDescriptorCreator creator = _selector.FindAction(controllerContext, actionName);\r
+            if (creator == null) {\r
+                return null;\r
+            }\r
+\r
+            return creator(actionName, this);\r
+        }\r
+\r
+        public override ActionDescriptor[] GetCanonicalActions() {\r
+            // everything is looked up dymanically, so there are no 'canonical' actions\r
+            return _emptyCanonicalActions;\r
+        }\r
+\r
+        public override object[] GetCustomAttributes(bool inherit) {\r
+            return ControllerType.GetCustomAttributes(inherit);\r
+        }\r
+\r
+        public override object[] GetCustomAttributes(Type attributeType, bool inherit) {\r
+            return ControllerType.GetCustomAttributes(attributeType, inherit);\r
+        }\r
+\r
+        public override bool IsDefined(Type attributeType, bool inherit) {\r
+            return ControllerType.IsDefined(attributeType, inherit);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/SimpleAsyncResult.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/SimpleAsyncResult.cs
new file mode 100644 (file)
index 0000000..74f39b5
--- /dev/null
@@ -0,0 +1,67 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+    using System.Threading;\r
+\r
+    internal sealed class SimpleAsyncResult : IAsyncResult {\r
+\r
+        private readonly object _asyncState;\r
+        private bool _completedSynchronously;\r
+        private volatile bool _isCompleted;\r
+\r
+        public SimpleAsyncResult(object asyncState) {\r
+            _asyncState = asyncState;\r
+        }\r
+\r
+        public object AsyncState {\r
+            get {\r
+                return _asyncState;\r
+            }\r
+        }\r
+\r
+        // ASP.NET IAsyncResult objects should never expose a WaitHandle due to potential deadlocking\r
+        public WaitHandle AsyncWaitHandle {\r
+            get {\r
+                return null;\r
+            }\r
+        }\r
+\r
+        public bool CompletedSynchronously {\r
+            get {\r
+                return _completedSynchronously;\r
+            }\r
+        }\r
+\r
+        public bool IsCompleted {\r
+            get {\r
+                return _isCompleted;\r
+            }\r
+        }\r
+\r
+        // Proper order of execution:\r
+        // 1. Set the CompletedSynchronously property to the correct value\r
+        // 2. Set the IsCompleted flag\r
+        // 3. Execute the callback\r
+        // 4. Signal the WaitHandle (which we don't have)\r
+        public void MarkCompleted(bool completedSynchronously, AsyncCallback callback) {\r
+            _completedSynchronously = completedSynchronously;\r
+            _isCompleted = true;\r
+\r
+            if (callback != null) {\r
+                callback(this);\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/SingleEntryGate.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/SingleEntryGate.cs
new file mode 100644 (file)
index 0000000..c3e63a1
--- /dev/null
@@ -0,0 +1,32 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+    using System.Threading;\r
+\r
+    // used to synchronize access to a single-use consumable resource\r
+    internal sealed class SingleEntryGate {\r
+\r
+        private const int NOT_ENTERED = 0;\r
+        private const int ENTERED = 1;\r
+\r
+        private int _status;\r
+\r
+        // returns true if this is the first call to TryEnter(), false otherwise\r
+        public bool TryEnter() {\r
+            int oldStatus = Interlocked.Exchange(ref _status, ENTERED);\r
+            return (oldStatus == NOT_ENTERED);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/SynchronizationContextUtil.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/SynchronizationContextUtil.cs
new file mode 100644 (file)
index 0000000..5988091
--- /dev/null
@@ -0,0 +1,55 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+    using System.Threading;\r
+\r
+    internal static class SynchronizationContextUtil {\r
+\r
+        public static SynchronizationContext GetSynchronizationContext() {\r
+            // In a runtime environment, SynchronizationContext.Current will be set to an instance\r
+            // of AspNetSynchronizationContext. In a unit test environment, the Current property\r
+            // won't be set and we have to create one on the fly.\r
+            return SynchronizationContext.Current ?? new SynchronizationContext();\r
+        }\r
+\r
+        public static T Sync<T>(this SynchronizationContext syncContext, Func<T> func) {\r
+            T theValue = default(T);\r
+            Exception thrownException = null;\r
+\r
+            syncContext.Send(o => {\r
+                try {\r
+                    theValue = func();\r
+                }\r
+                catch (Exception ex) {\r
+                    // by default, the AspNetSynchronizationContext type will swallow thrown exceptions,\r
+                    // so we need to save and propagate them\r
+                    thrownException = ex;\r
+                }\r
+            }, null);\r
+\r
+            if (thrownException != null) {\r
+                throw Error.SynchronizationContextUtil_ExceptionThrown(thrownException);\r
+            }\r
+            return theValue;\r
+        }\r
+\r
+        public static void Sync(this SynchronizationContext syncContext, Action action) {\r
+            Sync<AsyncVoid>(syncContext, () => {\r
+                action();\r
+                return default(AsyncVoid);\r
+            });\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/SynchronousOperationException.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/SynchronousOperationException.cs
new file mode 100644 (file)
index 0000000..8836e26
--- /dev/null
@@ -0,0 +1,39 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+    using System.Runtime.Serialization;\r
+\r
+    // This exception type is thrown by the SynchronizationContextUtil helper class since the AspNetSynchronizationContext\r
+    // type swallows exceptions. The inner exception contains the data the user cares about.\r
+\r
+    [Serializable]\r
+    public sealed class SynchronousOperationException : HttpException {\r
+\r
+        public SynchronousOperationException() {\r
+        }\r
+\r
+        private SynchronousOperationException(SerializationInfo info, StreamingContext context)\r
+            : base(info, context) {\r
+        }\r
+\r
+        public SynchronousOperationException(string message)\r
+            : base(message) {\r
+        }\r
+\r
+        public SynchronousOperationException(string message, Exception innerException)\r
+            : base(message, innerException) {\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/Trigger.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/Trigger.cs
new file mode 100644 (file)
index 0000000..3ac944c
--- /dev/null
@@ -0,0 +1,33 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+    using System.Runtime.Serialization;\r
+\r
+    // Provides a trigger for the TriggerListener class.\r
+\r
+    internal sealed class Trigger {\r
+\r
+        private readonly Action _fireAction;\r
+\r
+        // Constructor should only be called by TriggerListener.\r
+        internal Trigger(Action fireAction) {\r
+            _fireAction = fireAction;\r
+        }\r
+\r
+        public void Fire() {\r
+            _fireAction();\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/TriggerListener.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Async/TriggerListener.cs
new file mode 100644 (file)
index 0000000..eed5096
--- /dev/null
@@ -0,0 +1,68 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Async {\r
+    using System;\r
+    using System.Threading;\r
+\r
+    // This class is used to wait for triggers and a continuation. When the continuation has been provded\r
+    // and all triggers have been fired, the continuation is called. Similar to WaitHandle.WaitAll().\r
+    // New instances of this type are initially in the inactive state; activation is enabled by a call\r
+    // to Activate().\r
+\r
+    // This class is thread-safe.\r
+\r
+    internal sealed class TriggerListener {\r
+\r
+        private readonly Trigger _activateTrigger;\r
+        private volatile Action _continuation;\r
+        private readonly SingleEntryGate _continuationFiredGate = new SingleEntryGate();\r
+        private int _outstandingTriggers;\r
+        private readonly Trigger _setContinuationTrigger;\r
+\r
+        public TriggerListener() {\r
+            _activateTrigger = CreateTrigger();\r
+            _setContinuationTrigger = CreateTrigger();\r
+        }\r
+\r
+        public void Activate() {\r
+            _activateTrigger.Fire();\r
+        }\r
+\r
+        public Trigger CreateTrigger() {\r
+            Interlocked.Increment(ref _outstandingTriggers);\r
+\r
+            SingleEntryGate triggerFiredGate = new SingleEntryGate();\r
+            return new Trigger(() => {\r
+                if (triggerFiredGate.TryEnter()) {\r
+                    HandleTriggerFired();\r
+                }\r
+            });\r
+        }\r
+\r
+        private void HandleTriggerFired() {\r
+            if (Interlocked.Decrement(ref _outstandingTriggers) == 0) {\r
+                if (_continuationFiredGate.TryEnter()) {\r
+                    _continuation();\r
+                }\r
+            }\r
+        }\r
+\r
+        public void SetContinuation(Action continuation) {\r
+            if (continuation != null) {\r
+                _continuation = continuation;\r
+                _setContinuationTrigger.Fire();\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/AsyncController.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/AsyncController.cs
new file mode 100644 (file)
index 0000000..975ce4f
--- /dev/null
@@ -0,0 +1,111 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Web.Mvc.Async;\r
+    using System.Web.Routing;\r
+\r
+    public abstract class AsyncController : Controller, IAsyncManagerContainer, IAsyncController {\r
+\r
+        private static readonly object _executeTag = new object();\r
+        private static readonly object _executeCoreTag = new object();\r
+\r
+        private readonly AsyncManager _asyncManager = new AsyncManager();\r
+\r
+        public AsyncManager AsyncManager {\r
+            get {\r
+                return _asyncManager;\r
+            }\r
+        }\r
+\r
+        protected virtual IAsyncResult BeginExecute(RequestContext requestContext, AsyncCallback callback, object state) {\r
+            if (requestContext == null) {\r
+                throw new ArgumentNullException("requestContext");\r
+            }\r
+\r
+            VerifyExecuteCalledOnce();\r
+            Initialize(requestContext);\r
+            return AsyncResultWrapper.Begin(callback, state, BeginExecuteCore, EndExecuteCore, _executeTag);\r
+        }\r
+\r
+        protected virtual IAsyncResult BeginExecuteCore(AsyncCallback callback, object state) {\r
+            // If code in this method needs to be updated, please also check the ExecuteCore() method\r
+            // of Controller to see if that code also must be updated.\r
+\r
+            PossiblyLoadTempData();\r
+            try {\r
+                string actionName = RouteData.GetRequiredString("action");\r
+                IActionInvoker invoker = ActionInvoker;\r
+                IAsyncActionInvoker asyncInvoker = invoker as IAsyncActionInvoker;\r
+                if (asyncInvoker != null) {\r
+                    // asynchronous invocation\r
+                    BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState) {\r
+                        return asyncInvoker.BeginInvokeAction(ControllerContext, actionName, asyncCallback, asyncState);\r
+                    };\r
+\r
+                    EndInvokeDelegate endDelegate = delegate(IAsyncResult asyncResult) {\r
+                        if (!asyncInvoker.EndInvokeAction(asyncResult)) {\r
+                            HandleUnknownAction(actionName);\r
+                        }\r
+                    };\r
+\r
+                    return AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _executeCoreTag);\r
+                }\r
+                else {\r
+                    // synchronous invocation\r
+                    Action action = () => {\r
+                        if (!invoker.InvokeAction(ControllerContext, actionName)) {\r
+                            HandleUnknownAction(actionName);\r
+                        }\r
+                    };\r
+                    return AsyncResultWrapper.BeginSynchronous(callback, state, action, _executeCoreTag);\r
+                }\r
+            }\r
+            catch {\r
+                PossiblySaveTempData();\r
+                throw;\r
+            }\r
+        }\r
+\r
+        protected override IActionInvoker CreateActionInvoker() {\r
+            return new AsyncControllerActionInvoker();\r
+        }\r
+\r
+        protected virtual void EndExecute(IAsyncResult asyncResult) {\r
+            AsyncResultWrapper.End(asyncResult, _executeTag);\r
+        }\r
+\r
+        protected virtual void EndExecuteCore(IAsyncResult asyncResult) {\r
+            // If code in this method needs to be updated, please also check the ExecuteCore() method\r
+            // of Controller to see if that code also must be updated.\r
+\r
+            try {\r
+                AsyncResultWrapper.End(asyncResult, _executeCoreTag);\r
+            }\r
+            finally {\r
+                PossiblySaveTempData();\r
+            }\r
+        }\r
+\r
+        #region IAsyncController Members\r
+        IAsyncResult IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, object state) {\r
+            return BeginExecute(requestContext, callback, state);\r
+        }\r
+\r
+        void IAsyncController.EndExecute(IAsyncResult asyncResult) {\r
+            EndExecute(asyncResult);\r
+        }\r
+        #endregion\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/AsyncTimeoutAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/AsyncTimeoutAttribute.cs
new file mode 100644 (file)
index 0000000..9622e25
--- /dev/null
@@ -0,0 +1,53 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Web.Mvc.Async;\r
+\r
+    [SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes",\r
+        Justification = "Unsealed so that subclassed types can set properties in the default constructor.")]\r
+    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\r
+    public class AsyncTimeoutAttribute : ActionFilterAttribute {\r
+\r
+        // duration is specified in milliseconds\r
+        public AsyncTimeoutAttribute(int duration) {\r
+            if (duration < -1) {\r
+                throw Error.AsyncCommon_InvalidTimeout("duration");\r
+            }\r
+\r
+            Duration = duration;\r
+        }\r
+\r
+        public int Duration {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public override void OnActionExecuting(ActionExecutingContext filterContext) {\r
+            if (filterContext == null) {\r
+                throw new ArgumentNullException("filterContext");\r
+            }\r
+\r
+            IAsyncManagerContainer container = filterContext.Controller as IAsyncManagerContainer;\r
+            if (container == null) {\r
+                throw Error.AsyncCommon_ControllerMustImplementIAsyncManagerContainer(filterContext.Controller.GetType());\r
+            }\r
+\r
+            container.AsyncManager.Timeout = Duration;\r
+\r
+            base.OnActionExecuting(filterContext);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/AuthorizationContext.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/AuthorizationContext.cs
new file mode 100644 (file)
index 0000000..8cd6808
--- /dev/null
@@ -0,0 +1,50 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+\r
+    public class AuthorizationContext : ControllerContext {\r
+\r
+        // parameterless constructor used for mocking\r
+        public AuthorizationContext() {\r
+        }\r
+\r
+        [Obsolete("The recommended alternative is the constructor AuthorizationContext(ControllerContext controllerContext, ActionDescriptor actionDescriptor).")]\r
+        public AuthorizationContext(ControllerContext controllerContext)\r
+            : base(controllerContext) {\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors",\r
+            Justification = "The virtual property setters are only to support mocking frameworks, in which case this constructor shouldn't be called anyway.")]\r
+        public AuthorizationContext(ControllerContext controllerContext, ActionDescriptor actionDescriptor)\r
+            : base(controllerContext) {\r
+            if (actionDescriptor == null) {\r
+                throw new ArgumentNullException("actionDescriptor");\r
+            }\r
+\r
+            ActionDescriptor = actionDescriptor;\r
+        }\r
+\r
+        public virtual ActionDescriptor ActionDescriptor {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public ActionResult Result {\r
+            get;\r
+            set;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/AuthorizeAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/AuthorizeAttribute.cs
new file mode 100644 (file)
index 0000000..3b07bca
--- /dev/null
@@ -0,0 +1,135 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Linq;\r
+    using System.Security.Principal;\r
+    using System.Web;\r
+\r
+    [SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes",\r
+        Justification = "Unsealed so that subclassed types can set properties in the default constructor or override our behavior.")]\r
+    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]\r
+    public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter {\r
+\r
+        private readonly object _typeId = new object();\r
+\r
+        private string _roles;\r
+        private string[] _rolesSplit = new string[0];\r
+        private string _users;\r
+        private string[] _usersSplit = new string[0];\r
+\r
+        public string Roles {\r
+            get {\r
+                return _roles ?? String.Empty;\r
+            }\r
+            set {\r
+                _roles = value;\r
+                _rolesSplit = SplitString(value);\r
+            }\r
+        }\r
+\r
+        public override object TypeId {\r
+            get {\r
+                return _typeId;\r
+            }\r
+        }\r
+\r
+        public string Users {\r
+            get {\r
+                return _users ?? String.Empty;\r
+            }\r
+            set {\r
+                _users = value;\r
+                _usersSplit = SplitString(value);\r
+            }\r
+        }\r
+\r
+        // This method must be thread-safe since it is called by the thread-safe OnCacheAuthorization() method.\r
+        protected virtual bool AuthorizeCore(HttpContextBase httpContext) {\r
+            if (httpContext == null) {\r
+                throw new ArgumentNullException("httpContext");\r
+            }\r
+\r
+            IPrincipal user = httpContext.User;\r
+            if (!user.Identity.IsAuthenticated) {\r
+                return false;\r
+            }\r
+\r
+            if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) {\r
+                return false;\r
+            }\r
+\r
+            if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole)) {\r
+                return false;\r
+            }\r
+\r
+            return true;\r
+        }\r
+\r
+        private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus) {\r
+            validationStatus = OnCacheAuthorization(new HttpContextWrapper(context));\r
+        }\r
+\r
+        public virtual void OnAuthorization(AuthorizationContext filterContext) {\r
+            if (filterContext == null) {\r
+                throw new ArgumentNullException("filterContext");\r
+            }\r
+\r
+            if (AuthorizeCore(filterContext.HttpContext)) {\r
+                // ** IMPORTANT **\r
+                // Since we're performing authorization at the action level, the authorization code runs\r
+                // after the output caching module. In the worst case this could allow an authorized user\r
+                // to cause the page to be cached, then an unauthorized user would later be served the\r
+                // cached page. We work around this by telling proxies not to cache the sensitive page,\r
+                // then we hook our custom authorization code into the caching mechanism so that we have\r
+                // the final say on whether a page should be served from the cache.\r
+\r
+                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;\r
+                cachePolicy.SetProxyMaxAge(new TimeSpan(0));\r
+                cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);\r
+            }\r
+            else {\r
+                HandleUnauthorizedRequest(filterContext);\r
+            }\r
+        }\r
+\r
+        protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext) {\r
+            // Returns HTTP 401 - see comment in HttpUnauthorizedResult.cs.\r
+            filterContext.Result = new HttpUnauthorizedResult();\r
+        }\r
+\r
+        // This method must be thread-safe since it is called by the caching module.\r
+        protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext) {\r
+            if (httpContext == null) {\r
+                throw new ArgumentNullException("httpContext");\r
+            }\r
+\r
+            bool isAuthorized = AuthorizeCore(httpContext);\r
+            return (isAuthorized) ? HttpValidationStatus.Valid : HttpValidationStatus.IgnoreThisRequest;\r
+        }\r
+\r
+        internal static string[] SplitString(string original) {\r
+            if (String.IsNullOrEmpty(original)) {\r
+                return new string[0];\r
+            }\r
+\r
+            var split = from piece in original.Split(',')\r
+                        let trimmed = piece.Trim()\r
+                        where !String.IsNullOrEmpty(trimmed)\r
+                        select trimmed;\r
+            return split.ToArray();\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/BindAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/BindAttribute.cs
new file mode 100644 (file)
index 0000000..5f3b1be
--- /dev/null
@@ -0,0 +1,63 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Linq;\r
+\r
+    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]\r
+    public sealed class BindAttribute : Attribute {\r
+\r
+        private string _exclude;\r
+        private string[] _excludeSplit = new string[0];\r
+        private string _include;\r
+        private string[] _includeSplit = new string[0];\r
+\r
+        public string Exclude {\r
+            get {\r
+                return _exclude ?? String.Empty;\r
+            }\r
+            set {\r
+                _exclude = value;\r
+                _excludeSplit = AuthorizeAttribute.SplitString(value);\r
+            }\r
+        }\r
+\r
+        public string Include {\r
+            get {\r
+                return _include ?? String.Empty;\r
+            }\r
+            set {\r
+                _include = value;\r
+                _includeSplit = AuthorizeAttribute.SplitString(value);\r
+            }\r
+        }\r
+\r
+        public string Prefix {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        internal static bool IsPropertyAllowed(string propertyName, string[] includeProperties, string[] excludeProperties) {\r
+            // We allow a property to be bound if its both in the include list AND not in the exclude list.\r
+            // An empty include list implies all properties are allowed.\r
+            // An empty exclude list implies no properties are disallowed.\r
+            bool includeProperty = (includeProperties == null) || (includeProperties.Length == 0) || includeProperties.Contains(propertyName, StringComparer.OrdinalIgnoreCase);\r
+            bool excludeProperty = (excludeProperties != null) && excludeProperties.Contains(propertyName, StringComparer.OrdinalIgnoreCase);\r
+            return includeProperty && !excludeProperty;\r
+        }\r
+\r
+        public bool IsPropertyAllowed(string propertyName) {\r
+            return IsPropertyAllowed(propertyName, _includeSplit, _excludeSplit);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/BuildManagerWrapper.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/BuildManagerWrapper.cs
new file mode 100644 (file)
index 0000000..f8959ec
--- /dev/null
@@ -0,0 +1,43 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Collections;\r
+    using System.IO;\r
+    using System.Web.Compilation;\r
+\r
+    internal sealed class BuildManagerWrapper : IBuildManager {\r
+        private static readonly Func<string, Stream> _readCachedFileDelegate =\r
+            TypeHelpers.CreateDelegate<Func<string, Stream>>(typeof(BuildManager), "ReadCachedFile", null /* thisParameter */);\r
+        private static readonly Func<string, Stream> _createCachedFileDelegate =\r
+            TypeHelpers.CreateDelegate<Func<string, Stream>>(typeof(BuildManager), "CreateCachedFile", null /* thisParameter */);\r
+\r
+        #region IBuildManager Members\r
+        object IBuildManager.CreateInstanceFromVirtualPath(string virtualPath, Type requiredBaseType) {\r
+            return BuildManager.CreateInstanceFromVirtualPath(virtualPath, requiredBaseType);\r
+        }\r
+\r
+        ICollection IBuildManager.GetReferencedAssemblies() {\r
+            return BuildManager.GetReferencedAssemblies();\r
+        }\r
+\r
+        // ASP.NET 4 methods\r
+        Stream IBuildManager.ReadCachedFile(string fileName) {\r
+            return (_readCachedFileDelegate != null) ? _readCachedFileDelegate(fileName) : null;\r
+        }\r
+\r
+        Stream IBuildManager.CreateCachedFile(string fileName) {\r
+            return (_createCachedFileDelegate != null) ? _createCachedFileDelegate(fileName) : null;\r
+        }\r
+        #endregion\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ByteArrayModelBinder.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ByteArrayModelBinder.cs
new file mode 100644 (file)
index 0000000..ad62a13
--- /dev/null
@@ -0,0 +1,43 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    public class ByteArrayModelBinder : IModelBinder {\r
+        public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {\r
+            if (bindingContext == null) {\r
+                throw new ArgumentNullException("bindingContext");\r
+            }\r
+\r
+            ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);\r
+\r
+            // case 1: there was no <input ... /> element containing this data\r
+            if (valueResult == null) {\r
+                return null;\r
+            }\r
+\r
+            string value = valueResult.AttemptedValue;\r
+\r
+            // case 2: there was an <input ... /> element but it was left blank\r
+            if (String.IsNullOrEmpty(value)) {\r
+                return null;\r
+            }\r
+\r
+            // Future proofing. If the byte array is actually an instance of System.Data.Linq.Binary\r
+            // then we need to remove these quotes put in place by the ToString() method.\r
+            string realValue = value.Replace("\"", String.Empty);\r
+            return Convert.FromBase64String(realValue);\r
+        }\r
+    }\r
+\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ChildActionOnlyAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ChildActionOnlyAttribute.cs
new file mode 100644 (file)
index 0000000..398546b
--- /dev/null
@@ -0,0 +1,30 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\r
+    public sealed class ChildActionOnlyAttribute : FilterAttribute, IAuthorizationFilter {\r
+\r
+        public void OnAuthorization(AuthorizationContext filterContext) {\r
+            if (filterContext == null) {\r
+                throw new ArgumentNullException("filterContext");\r
+            }\r
+\r
+            if (!filterContext.IsChildAction) {\r
+                throw Error.ChildActionOnlyAttribute_MustBeInChildRequest(filterContext.ActionDescriptor);\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ClientDataTypeModelValidatorProvider.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ClientDataTypeModelValidatorProvider.cs
new file mode 100644 (file)
index 0000000..54c2519
--- /dev/null
@@ -0,0 +1,79 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public class ClientDataTypeModelValidatorProvider : ModelValidatorProvider {\r
+\r
+        private static readonly HashSet<Type> _numericTypes = new HashSet<Type>(new Type[] {\r
+            typeof(byte), typeof(sbyte),\r
+            typeof(short), typeof(ushort),\r
+            typeof(int), typeof(uint),\r
+            typeof(long), typeof(ulong),\r
+            typeof(float), typeof(double), typeof(decimal)\r
+        });\r
+\r
+        public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context) {\r
+            if (metadata == null) {\r
+                throw new ArgumentNullException("metadata");\r
+            }\r
+            if (context == null) {\r
+                throw new ArgumentNullException("context");\r
+            }\r
+\r
+            return GetValidatorsImpl(metadata, context);\r
+        }\r
+\r
+        private static IEnumerable<ModelValidator> GetValidatorsImpl(ModelMetadata metadata, ControllerContext context) {\r
+            Type type = metadata.ModelType;\r
+            if (IsNumericType(type)) {\r
+                yield return new NumericModelValidator(metadata, context);\r
+            }\r
+        }\r
+\r
+        private static bool IsNumericType(Type type) {\r
+            Type underlyingType = Nullable.GetUnderlyingType(type); // strip off the Nullable<>\r
+            return _numericTypes.Contains(underlyingType ?? type);\r
+        }\r
+\r
+        internal sealed class NumericModelValidator : ModelValidator {\r
+            public NumericModelValidator(ModelMetadata metadata, ControllerContext controllerContext)\r
+                : base(metadata, controllerContext) {\r
+            }\r
+\r
+            public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() {\r
+                ModelClientValidationRule rule = new ModelClientValidationRule() {\r
+                    ValidationType = "number",\r
+                    ErrorMessage = MakeErrorString(Metadata.GetDisplayName())\r
+                };\r
+\r
+                return new ModelClientValidationRule[] { rule };\r
+            }\r
+\r
+            private static string MakeErrorString(string displayName) {\r
+                // use CurrentCulture since this message is intended for the site visitor\r
+                return String.Format(CultureInfo.CurrentCulture, MvcResources.ClientDataTypeModelValidatorProvider_FieldMustBeNumeric, displayName);\r
+            }\r
+\r
+            public override IEnumerable<ModelValidationResult> Validate(object container) {\r
+                // this is not a server-side validator\r
+                return Enumerable.Empty<ModelValidationResult>();\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ContentResult.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ContentResult.cs
new file mode 100644 (file)
index 0000000..37ecb71
--- /dev/null
@@ -0,0 +1,53 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Text;\r
+    using System.Web;\r
+\r
+    public class ContentResult : ActionResult {\r
+\r
+        public string Content {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public Encoding ContentEncoding {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public string ContentType {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public override void ExecuteResult(ControllerContext context) {\r
+            if (context == null) {\r
+                throw new ArgumentNullException("context");\r
+            }\r
+\r
+            HttpResponseBase response = context.HttpContext.Response;\r
+\r
+            if (!String.IsNullOrEmpty(ContentType)) {\r
+                response.ContentType = ContentType;\r
+            }\r
+            if (ContentEncoding != null) {\r
+                response.ContentEncoding = ContentEncoding;\r
+            }\r
+            if (Content != null) {\r
+                response.Write(Content);\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Controller.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Controller.cs
new file mode 100644 (file)
index 0000000..04f4bc4
--- /dev/null
@@ -0,0 +1,599 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.IO;\r
+    using System.Security.Principal;\r
+    using System.Text;\r
+    using System.Web;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.Routing;\r
+\r
+    public abstract class Controller : ControllerBase, IActionFilter, IAuthorizationFilter, IDisposable, IExceptionFilter, IResultFilter {\r
+\r
+        private IActionInvoker _actionInvoker;\r
+        private ModelBinderDictionary _binders;\r
+        private RouteCollection _routeCollection;\r
+        private ITempDataProvider _tempDataProvider;\r
+\r
+        public IActionInvoker ActionInvoker {\r
+            get {\r
+                if (_actionInvoker == null) {\r
+                    _actionInvoker = CreateActionInvoker();\r
+                }\r
+                return _actionInvoker;\r
+            }\r
+            set {\r
+                _actionInvoker = value;\r
+            }\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly",\r
+            Justification = "Property is settable so that the dictionary can be provided for unit testing purposes.")]\r
+        protected internal ModelBinderDictionary Binders {\r
+            get {\r
+                if (_binders == null) {\r
+                    _binders = ModelBinders.Binders;\r
+                }\r
+                return _binders;\r
+            }\r
+            set {\r
+                _binders = value;\r
+            }\r
+        }\r
+\r
+        public HttpContextBase HttpContext {\r
+            get {\r
+                return ControllerContext == null ? null : ControllerContext.HttpContext;\r
+            }\r
+        }\r
+\r
+        public ModelStateDictionary ModelState {\r
+            get {\r
+                return ViewData.ModelState;\r
+            }\r
+        }\r
+\r
+        public HttpRequestBase Request {\r
+            get {\r
+                return HttpContext == null ? null : HttpContext.Request;\r
+            }\r
+        }\r
+\r
+        public HttpResponseBase Response {\r
+            get {\r
+                return HttpContext == null ? null : HttpContext.Response;\r
+            }\r
+        }\r
+\r
+        internal RouteCollection RouteCollection {\r
+            get {\r
+                if (_routeCollection == null) {\r
+                    _routeCollection = RouteTable.Routes;\r
+                }\r
+                return _routeCollection;\r
+            }\r
+            set {\r
+                _routeCollection = value;\r
+            }\r
+        }\r
+\r
+        public RouteData RouteData {\r
+            get {\r
+                return ControllerContext == null ? null : ControllerContext.RouteData;\r
+            }\r
+        }\r
+\r
+        public HttpServerUtilityBase Server {\r
+            get {\r
+                return HttpContext == null ? null : HttpContext.Server;\r
+            }\r
+        }\r
+\r
+        public HttpSessionStateBase Session {\r
+            get {\r
+                return HttpContext == null ? null : HttpContext.Session;\r
+            }\r
+        }\r
+\r
+        public ITempDataProvider TempDataProvider {\r
+            get {\r
+                if (_tempDataProvider == null) {\r
+                    _tempDataProvider = CreateTempDataProvider();\r
+                }\r
+                return _tempDataProvider;\r
+            }\r
+            set {\r
+                _tempDataProvider = value;\r
+            }\r
+        }\r
+\r
+        public UrlHelper Url {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public IPrincipal User {\r
+            get {\r
+                return HttpContext == null ? null : HttpContext.User;\r
+            }\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames", MessageId = "0#",\r
+            Justification = "'Content' refers to ContentResult type; 'content' refers to ContentResult.Content property.")]\r
+        protected internal ContentResult Content(string content) {\r
+            return Content(content, null /* contentType */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames", MessageId = "0#",\r
+            Justification = "'Content' refers to ContentResult type; 'content' refers to ContentResult.Content property.")]\r
+        protected internal ContentResult Content(string content, string contentType) {\r
+            return Content(content, contentType, null /* contentEncoding */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames", MessageId = "0#",\r
+            Justification = "'Content' refers to ContentResult type; 'content' refers to ContentResult.Content property.")]\r
+        protected internal virtual ContentResult Content(string content, string contentType, Encoding contentEncoding) {\r
+            return new ContentResult {\r
+                Content = content,\r
+                ContentType = contentType,\r
+                ContentEncoding = contentEncoding\r
+            };\r
+        }\r
+\r
+        protected virtual IActionInvoker CreateActionInvoker() {\r
+            return new ControllerActionInvoker();\r
+        }\r
+\r
+        protected virtual ITempDataProvider CreateTempDataProvider() {\r
+            return new SessionStateTempDataProvider();\r
+        }\r
+\r
+        // The default invoker will never match methods defined on the Controller type, so\r
+        // the Dispose() method is not web-callable.  However, in general, since implicitly-\r
+        // implemented interface methods are public, they are web-callable unless decorated with\r
+        // [NonAction].\r
+        public void Dispose() {\r
+            Dispose(true /* disposing */);\r
+            GC.SuppressFinalize(this);\r
+        }\r
+\r
+        protected virtual void Dispose(bool disposing) {\r
+        }\r
+\r
+        protected override void ExecuteCore() {\r
+            // If code in this method needs to be updated, please also check the BeginExecuteCore() and\r
+            // EndExecuteCore() methods of AsyncController to see if that code also must be updated.\r
+\r
+            PossiblyLoadTempData();\r
+            try {\r
+                string actionName = RouteData.GetRequiredString("action");\r
+                if (!ActionInvoker.InvokeAction(ControllerContext, actionName)) {\r
+                    HandleUnknownAction(actionName);\r
+                }\r
+            }\r
+            finally {\r
+                PossiblySaveTempData();\r
+            }\r
+        }\r
+\r
+        protected internal FileContentResult File(byte[] fileContents, string contentType) {\r
+            return File(fileContents, contentType, null /* fileDownloadName */);\r
+        }\r
+\r
+        protected internal virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName) {\r
+            return new FileContentResult(fileContents, contentType) { FileDownloadName = fileDownloadName };\r
+        }\r
+\r
+        protected internal FileStreamResult File(Stream fileStream, string contentType) {\r
+            return File(fileStream, contentType, null /* fileDownloadName */);\r
+        }\r
+\r
+        protected internal virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName) {\r
+            return new FileStreamResult(fileStream, contentType) { FileDownloadName = fileDownloadName };\r
+        }\r
+\r
+        protected internal FilePathResult File(string fileName, string contentType) {\r
+            return File(fileName, contentType, null /* fileDownloadName */);\r
+        }\r
+\r
+        protected internal virtual FilePathResult File(string fileName, string contentType, string fileDownloadName) {\r
+            return new FilePathResult(fileName, contentType) { FileDownloadName = fileDownloadName };\r
+        }\r
+\r
+        protected virtual void HandleUnknownAction(string actionName) {\r
+            throw new HttpException(404, String.Format(CultureInfo.CurrentUICulture,\r
+                MvcResources.Controller_UnknownAction, actionName, GetType().FullName));\r
+        }\r
+\r
+        protected internal virtual JavaScriptResult JavaScript(string script) {\r
+            return new JavaScriptResult { Script = script };\r
+        }\r
+\r
+        protected internal JsonResult Json(object data) {\r
+            return Json(data, null /* contentType */, null /* contentEncoding */, JsonRequestBehavior.DenyGet);\r
+        }\r
+\r
+        protected internal JsonResult Json(object data, string contentType) {\r
+            return Json(data, contentType, null /* contentEncoding */, JsonRequestBehavior.DenyGet);\r
+        }\r
+\r
+        protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding) {\r
+            return Json(data, contentType, contentEncoding, JsonRequestBehavior.DenyGet);\r
+        }\r
+\r
+        protected internal JsonResult Json(object data, JsonRequestBehavior behavior) {\r
+            return Json(data, null /* contentType */, null /* contentEncoding */, behavior);\r
+        }\r
+\r
+        protected internal JsonResult Json(object data, string contentType, JsonRequestBehavior behavior) {\r
+            return Json(data, contentType, null /* contentEncoding */, behavior);\r
+        }\r
+\r
+        protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior) {\r
+            return new JsonResult {\r
+                Data = data,\r
+                ContentType = contentType,\r
+                ContentEncoding = contentEncoding,\r
+                JsonRequestBehavior = behavior\r
+            };\r
+        }\r
+\r
+        protected override void Initialize(RequestContext requestContext) {\r
+            base.Initialize(requestContext);\r
+            Url = new UrlHelper(requestContext);\r
+        }\r
+\r
+        protected virtual void OnActionExecuting(ActionExecutingContext filterContext) {\r
+        }\r
+\r
+        protected virtual void OnActionExecuted(ActionExecutedContext filterContext) {\r
+        }\r
+\r
+        protected virtual void OnAuthorization(AuthorizationContext filterContext) {\r
+        }\r
+\r
+        protected virtual void OnException(ExceptionContext filterContext) {\r
+        }\r
+\r
+        protected virtual void OnResultExecuted(ResultExecutedContext filterContext) {\r
+        }\r
+\r
+        protected virtual void OnResultExecuting(ResultExecutingContext filterContext) {\r
+        }\r
+\r
+        protected internal PartialViewResult PartialView() {\r
+            return PartialView(null /* viewName */, null /* model */);\r
+        }\r
+\r
+        protected internal PartialViewResult PartialView(object model) {\r
+            return PartialView(null /* viewName */, model);\r
+        }\r
+\r
+        protected internal PartialViewResult PartialView(string viewName) {\r
+            return PartialView(viewName, null /* model */);\r
+        }\r
+\r
+        protected internal virtual PartialViewResult PartialView(string viewName, object model) {\r
+            if (model != null) {\r
+                ViewData.Model = model;\r
+            }\r
+\r
+            return new PartialViewResult {\r
+                ViewName = viewName,\r
+                ViewData = ViewData,\r
+                TempData = TempData\r
+            };\r
+        }\r
+\r
+        internal void PossiblyLoadTempData() {\r
+            if (!ControllerContext.IsChildAction) {\r
+                TempData.Load(ControllerContext, TempDataProvider);\r
+            }\r
+        }\r
+\r
+        internal void PossiblySaveTempData() {\r
+            if (!ControllerContext.IsChildAction) {\r
+                TempData.Save(ControllerContext, TempDataProvider);\r
+            }\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic",\r
+            Justification = "Instance method for consistency with other helpers.")]\r
+        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#",\r
+            Justification = "Response.Redirect() takes its URI as a string parameter.")]\r
+        protected internal virtual RedirectResult Redirect(string url) {\r
+            if (String.IsNullOrEmpty(url)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "url");\r
+            }\r
+            return new RedirectResult(url);\r
+        }\r
+\r
+        protected internal RedirectToRouteResult RedirectToAction(string actionName) {\r
+            return RedirectToAction(actionName, (RouteValueDictionary)null);\r
+        }\r
+\r
+        protected internal RedirectToRouteResult RedirectToAction(string actionName, object routeValues) {\r
+            return RedirectToAction(actionName, new RouteValueDictionary(routeValues));\r
+        }\r
+\r
+        protected internal RedirectToRouteResult RedirectToAction(string actionName, RouteValueDictionary routeValues) {\r
+            return RedirectToAction(actionName, null /* controllerName */, routeValues);\r
+        }\r
+\r
+        protected internal RedirectToRouteResult RedirectToAction(string actionName, string controllerName) {\r
+            return RedirectToAction(actionName, controllerName, (RouteValueDictionary)null);\r
+        }\r
+\r
+        protected internal RedirectToRouteResult RedirectToAction(string actionName, string controllerName, object routeValues) {\r
+            return RedirectToAction(actionName, controllerName, new RouteValueDictionary(routeValues));\r
+        }\r
+\r
+        protected internal virtual RedirectToRouteResult RedirectToAction(string actionName, string controllerName, RouteValueDictionary routeValues) {\r
+            RouteValueDictionary mergedRouteValues;\r
+\r
+            if (RouteData == null) {\r
+                mergedRouteValues = RouteValuesHelpers.MergeRouteValues(actionName, controllerName, null, routeValues, true /* includeImplicitMvcValues */);\r
+            }\r
+            else {\r
+                mergedRouteValues = RouteValuesHelpers.MergeRouteValues(actionName, controllerName, RouteData.Values, routeValues, true /* includeImplicitMvcValues */);\r
+            }\r
+\r
+            return new RedirectToRouteResult(mergedRouteValues);\r
+        }\r
+\r
+        protected internal RedirectToRouteResult RedirectToRoute(object routeValues) {\r
+            return RedirectToRoute(new RouteValueDictionary(routeValues));\r
+        }\r
+\r
+        protected internal RedirectToRouteResult RedirectToRoute(RouteValueDictionary routeValues) {\r
+            return RedirectToRoute(null /* routeName */, routeValues);\r
+        }\r
+\r
+        protected internal RedirectToRouteResult RedirectToRoute(string routeName) {\r
+            return RedirectToRoute(routeName, (RouteValueDictionary)null);\r
+        }\r
+\r
+        protected internal RedirectToRouteResult RedirectToRoute(string routeName, object routeValues) {\r
+            return RedirectToRoute(routeName, new RouteValueDictionary(routeValues));\r
+        }\r
+\r
+        protected internal virtual RedirectToRouteResult RedirectToRoute(string routeName, RouteValueDictionary routeValues) {\r
+            return new RedirectToRouteResult(routeName, RouteValuesHelpers.GetRouteValues(routeValues));\r
+        }\r
+\r
+        protected internal bool TryUpdateModel<TModel>(TModel model) where TModel : class {\r
+            return TryUpdateModel(model, null, null, null, ValueProvider);\r
+        }\r
+\r
+        protected internal bool TryUpdateModel<TModel>(TModel model, string prefix) where TModel : class {\r
+            return TryUpdateModel(model, prefix, null, null, ValueProvider);\r
+        }\r
+\r
+        protected internal bool TryUpdateModel<TModel>(TModel model, string[] includeProperties) where TModel : class {\r
+            return TryUpdateModel(model, null, includeProperties, null, ValueProvider);\r
+        }\r
+\r
+        protected internal bool TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties) where TModel : class {\r
+            return TryUpdateModel(model, prefix, includeProperties, null, ValueProvider);\r
+        }\r
+\r
+        protected internal bool TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) where TModel : class {\r
+            return TryUpdateModel(model, prefix, includeProperties, excludeProperties, ValueProvider);\r
+        }\r
+\r
+        protected internal bool TryUpdateModel<TModel>(TModel model, IValueProvider valueProvider) where TModel : class {\r
+            return TryUpdateModel(model, null, null, null, valueProvider);\r
+        }\r
+\r
+        protected internal bool TryUpdateModel<TModel>(TModel model, string prefix, IValueProvider valueProvider) where TModel : class {\r
+            return TryUpdateModel(model, prefix, null, null, valueProvider);\r
+        }\r
+\r
+        protected internal bool TryUpdateModel<TModel>(TModel model, string[] includeProperties, IValueProvider valueProvider) where TModel : class {\r
+            return TryUpdateModel(model, null, includeProperties, null, valueProvider);\r
+        }\r
+\r
+        protected internal bool TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, IValueProvider valueProvider) where TModel : class {\r
+            return TryUpdateModel(model, prefix, includeProperties, null, valueProvider);\r
+        }\r
+\r
+        protected internal bool TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties, IValueProvider valueProvider) where TModel : class {\r
+            if (model == null) {\r
+                throw new ArgumentNullException("model");\r
+            }\r
+            if (valueProvider == null) {\r
+                throw new ArgumentNullException("valueProvider");\r
+            }\r
+\r
+            Predicate<string> propertyFilter = propertyName => BindAttribute.IsPropertyAllowed(propertyName, includeProperties, excludeProperties);\r
+            IModelBinder binder = Binders.GetBinder(typeof(TModel));\r
+\r
+            ModelBindingContext bindingContext = new ModelBindingContext() {\r
+                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, typeof(TModel)),\r
+                ModelName = prefix,\r
+                ModelState = ModelState,\r
+                PropertyFilter = propertyFilter,\r
+                ValueProvider = valueProvider\r
+            };\r
+            binder.BindModel(ControllerContext, bindingContext);\r
+            return ModelState.IsValid;\r
+        }\r
+\r
+        protected internal bool TryValidateModel(object model) {\r
+            return TryValidateModel(model, null /* prefix */);\r
+        }\r
+\r
+        protected internal bool TryValidateModel(object model, string prefix) {\r
+            if (model == null) {\r
+                throw new ArgumentNullException("model");\r
+            }\r
+\r
+            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());\r
+\r
+            foreach (ModelValidationResult validationResult in ModelValidator.GetModelValidator(metadata, ControllerContext).Validate(null)) {\r
+                ModelState.AddModelError(DefaultModelBinder.CreateSubPropertyName(prefix, validationResult.MemberName), validationResult.Message);\r
+            }\r
+\r
+            return ModelState.IsValid;\r
+        }\r
+\r
+        protected internal void UpdateModel<TModel>(TModel model) where TModel : class {\r
+            UpdateModel(model, null, null, null, ValueProvider);\r
+        }\r
+\r
+        protected internal void UpdateModel<TModel>(TModel model, string prefix) where TModel : class {\r
+            UpdateModel(model, prefix, null, null, ValueProvider);\r
+        }\r
+\r
+        protected internal void UpdateModel<TModel>(TModel model, string[] includeProperties) where TModel : class {\r
+            UpdateModel(model, null, includeProperties, null, ValueProvider);\r
+        }\r
+\r
+        protected internal void UpdateModel<TModel>(TModel model, string prefix, string[] includeProperties) where TModel : class {\r
+            UpdateModel(model, prefix, includeProperties, null, ValueProvider);\r
+        }\r
+\r
+        protected internal void UpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) where TModel : class {\r
+            UpdateModel(model, prefix, includeProperties, excludeProperties, ValueProvider);\r
+        }\r
+\r
+        protected internal void UpdateModel<TModel>(TModel model, IValueProvider valueProvider) where TModel : class {\r
+            UpdateModel(model, null, null, null, valueProvider);\r
+        }\r
+\r
+        protected internal void UpdateModel<TModel>(TModel model, string prefix, IValueProvider valueProvider) where TModel : class {\r
+            UpdateModel(model, prefix, null, null, valueProvider);\r
+        }\r
+\r
+        protected internal void UpdateModel<TModel>(TModel model, string[] includeProperties, IValueProvider valueProvider) where TModel : class {\r
+            UpdateModel(model, null, includeProperties, null, valueProvider);\r
+        }\r
+\r
+        protected internal void UpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, IValueProvider valueProvider) where TModel : class {\r
+            UpdateModel(model, prefix, includeProperties, null, valueProvider);\r
+        }\r
+\r
+        protected internal void UpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties, IValueProvider valueProvider) where TModel : class {\r
+            bool success = TryUpdateModel(model, prefix, includeProperties, excludeProperties, valueProvider);\r
+            if (!success) {\r
+                string message = String.Format(CultureInfo.CurrentUICulture, MvcResources.Controller_UpdateModel_UpdateUnsuccessful,\r
+                    typeof(TModel).FullName);\r
+                throw new InvalidOperationException(message);\r
+            }\r
+        }\r
+\r
+        protected internal void ValidateModel(object model) {\r
+            ValidateModel(model, null /* prefix */);\r
+        }\r
+\r
+        protected internal void ValidateModel(object model, string prefix) {\r
+            if (!TryValidateModel(model, prefix)) {\r
+                throw new InvalidOperationException(\r
+                    String.Format(\r
+                        CultureInfo.CurrentUICulture,\r
+                        MvcResources.Controller_Validate_ValidationFailed,\r
+                        model.GetType().FullName\r
+                    )\r
+                );\r
+            }\r
+        }\r
+\r
+        protected internal ViewResult View() {\r
+            return View(null /* viewName */, null /* masterName */, null /* model */);\r
+        }\r
+\r
+        protected internal ViewResult View(object model) {\r
+            return View(null /* viewName */, null /* masterName */, model);\r
+        }\r
+\r
+        protected internal ViewResult View(string viewName) {\r
+            return View(viewName, null /* masterName */, null /* model */);\r
+        }\r
+\r
+        protected internal ViewResult View(string viewName, string masterName) {\r
+            return View(viewName, masterName, null /* model */);\r
+        }\r
+\r
+        protected internal ViewResult View(string viewName, object model) {\r
+            return View(viewName, null /* masterName */, model);\r
+        }\r
+\r
+        protected internal virtual ViewResult View(string viewName, string masterName, object model) {\r
+            if (model != null) {\r
+                ViewData.Model = model;\r
+            }\r
+\r
+            return new ViewResult {\r
+                ViewName = viewName,\r
+                MasterName = masterName,\r
+                ViewData = ViewData,\r
+                TempData = TempData\r
+            };\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames", MessageId = "0#",\r
+            Justification = "The method name 'View' is a convenient shorthand for 'CreateViewResult'.")]\r
+        protected internal ViewResult View(IView view) {\r
+            return View(view, null /* model */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames", MessageId = "0#",\r
+            Justification = "The method name 'View' is a convenient shorthand for 'CreateViewResult'.")]\r
+        protected internal virtual ViewResult View(IView view, object model) {\r
+            if (model != null) {\r
+                ViewData.Model = model;\r
+            }\r
+\r
+            return new ViewResult {\r
+                View = view,\r
+                ViewData = ViewData,\r
+                TempData = TempData\r
+            };\r
+        }\r
+\r
+        #region IActionFilter Members\r
+        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext) {\r
+            OnActionExecuting(filterContext);\r
+        }\r
+\r
+        void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext) {\r
+            OnActionExecuted(filterContext);\r
+        }\r
+        #endregion\r
+\r
+        #region IAuthorizationFilter Members\r
+        void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext) {\r
+            OnAuthorization(filterContext);\r
+        }\r
+        #endregion\r
+\r
+        #region IExceptionFilter Members\r
+        void IExceptionFilter.OnException(ExceptionContext filterContext) {\r
+            OnException(filterContext);\r
+        }\r
+        #endregion\r
+\r
+        #region IResultFilter Members\r
+        void IResultFilter.OnResultExecuting(ResultExecutingContext filterContext) {\r
+            OnResultExecuting(filterContext);\r
+        }\r
+\r
+        void IResultFilter.OnResultExecuted(ResultExecutedContext filterContext) {\r
+            OnResultExecuted(filterContext);\r
+        }\r
+        #endregion\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerActionInvoker.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerActionInvoker.cs
new file mode 100644 (file)
index 0000000..aad3e81
--- /dev/null
@@ -0,0 +1,333 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+    using System.Threading;\r
+    using System.Web;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public class ControllerActionInvoker : IActionInvoker {\r
+\r
+        private readonly static ControllerDescriptorCache _staticDescriptorCache = new ControllerDescriptorCache();\r
+\r
+        private ModelBinderDictionary _binders;\r
+        private ControllerDescriptorCache _instanceDescriptorCache;\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly",\r
+            Justification = "Property is settable so that the dictionary can be provided for unit testing purposes.")]\r
+        protected internal ModelBinderDictionary Binders {\r
+            get {\r
+                if (_binders == null) {\r
+                    _binders = ModelBinders.Binders;\r
+                }\r
+                return _binders;\r
+            }\r
+            set {\r
+                _binders = value;\r
+            }\r
+        }\r
+\r
+        internal ControllerDescriptorCache DescriptorCache {\r
+            get {\r
+                if (_instanceDescriptorCache == null) {\r
+                    _instanceDescriptorCache = _staticDescriptorCache;\r
+                }\r
+                return _instanceDescriptorCache;\r
+            }\r
+            set {\r
+                _instanceDescriptorCache = value;\r
+            }\r
+        }\r
+\r
+        private static void AddControllerToFilterList<TFilter>(ControllerBase controller, IList<TFilter> filterList) where TFilter : class {\r
+            TFilter controllerAsFilter = controller as TFilter;\r
+            if (controllerAsFilter != null) {\r
+                filterList.Insert(0, controllerAsFilter);\r
+            }\r
+        }\r
+\r
+        protected virtual ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue) {\r
+            if (actionReturnValue == null) {\r
+                return new EmptyResult();\r
+            }\r
+\r
+            ActionResult actionResult = (actionReturnValue as ActionResult) ??\r
+                new ContentResult { Content = Convert.ToString(actionReturnValue, CultureInfo.InvariantCulture) };\r
+            return actionResult;\r
+        }\r
+\r
+        protected virtual ControllerDescriptor GetControllerDescriptor(ControllerContext controllerContext) {\r
+            Type controllerType = controllerContext.Controller.GetType();\r
+            ControllerDescriptor controllerDescriptor = DescriptorCache.GetDescriptor(controllerType, () => new ReflectedControllerDescriptor(controllerType));\r
+            return controllerDescriptor;\r
+        }\r
+\r
+        protected virtual ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName) {\r
+            ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName);\r
+            return actionDescriptor;\r
+        }\r
+\r
+        protected virtual FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor) {\r
+            FilterInfo filters = actionDescriptor.GetFilters();\r
+\r
+            // if the current controller implements one of the filter interfaces, it should be added to the list at position 0\r
+            ControllerBase controller = controllerContext.Controller;\r
+            AddControllerToFilterList(controller, filters.ActionFilters);\r
+            AddControllerToFilterList(controller, filters.ResultFilters);\r
+            AddControllerToFilterList(controller, filters.AuthorizationFilters);\r
+            AddControllerToFilterList(controller, filters.ExceptionFilters);\r
+\r
+            return filters;\r
+        }\r
+\r
+        private IModelBinder GetModelBinder(ParameterDescriptor parameterDescriptor) {\r
+            // look on the parameter itself, then look in the global table\r
+            return parameterDescriptor.BindingInfo.Binder ?? Binders.GetBinder(parameterDescriptor.ParameterType);\r
+        }\r
+\r
+        protected virtual object GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) {\r
+            // collect all of the necessary binding properties\r
+            Type parameterType = parameterDescriptor.ParameterType;\r
+            IModelBinder binder = GetModelBinder(parameterDescriptor);\r
+            IValueProvider valueProvider = controllerContext.Controller.ValueProvider;\r
+            string parameterName = parameterDescriptor.BindingInfo.Prefix ?? parameterDescriptor.ParameterName;\r
+            Predicate<string> propertyFilter = GetPropertyFilter(parameterDescriptor);\r
+\r
+            // finally, call into the binder\r
+            ModelBindingContext bindingContext = new ModelBindingContext() {\r
+                FallbackToEmptyPrefix = (parameterDescriptor.BindingInfo.Prefix == null), // only fall back if prefix not specified\r
+                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, parameterType),\r
+                ModelName = parameterName,\r
+                ModelState = controllerContext.Controller.ViewData.ModelState,\r
+                PropertyFilter = propertyFilter,\r
+                ValueProvider = valueProvider\r
+            };\r
+\r
+            object result = binder.BindModel(controllerContext, bindingContext);\r
+            return result ?? parameterDescriptor.DefaultValue;\r
+        }\r
+\r
+        protected virtual IDictionary<string, object> GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) {\r
+            Dictionary<string, object> parametersDict = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\r
+            ParameterDescriptor[] parameterDescriptors = actionDescriptor.GetParameters();\r
+\r
+            foreach (ParameterDescriptor parameterDescriptor in parameterDescriptors) {\r
+                parametersDict[parameterDescriptor.ParameterName] = GetParameterValue(controllerContext, parameterDescriptor);\r
+            }\r
+            return parametersDict;\r
+        }\r
+\r
+        private static Predicate<string> GetPropertyFilter(ParameterDescriptor parameterDescriptor) {\r
+            ParameterBindingInfo bindingInfo = parameterDescriptor.BindingInfo;\r
+            return propertyName => BindAttribute.IsPropertyAllowed(propertyName, bindingInfo.Include.ToArray(), bindingInfo.Exclude.ToArray());\r
+        }\r
+\r
+        public virtual bool InvokeAction(ControllerContext controllerContext, string actionName) {\r
+            if (controllerContext == null) {\r
+                throw new ArgumentNullException("controllerContext");\r
+            }\r
+            if (String.IsNullOrEmpty(actionName)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "actionName");\r
+            }\r
+\r
+            ControllerDescriptor controllerDescriptor = GetControllerDescriptor(controllerContext);\r
+            ActionDescriptor actionDescriptor = FindAction(controllerContext, controllerDescriptor, actionName);\r
+            if (actionDescriptor != null) {\r
+                FilterInfo filterInfo = GetFilters(controllerContext, actionDescriptor);\r
+\r
+                try {\r
+                    AuthorizationContext authContext = InvokeAuthorizationFilters(controllerContext, filterInfo.AuthorizationFilters, actionDescriptor);\r
+                    if (authContext.Result != null) {\r
+                        // the auth filter signaled that we should let it short-circuit the request\r
+                        InvokeActionResult(controllerContext, authContext.Result);\r
+                    }\r
+                    else {\r
+                        if (controllerContext.Controller.ValidateRequest) {\r
+                            ValidateRequest(controllerContext);\r
+                        }\r
+\r
+                        IDictionary<string, object> parameters = GetParameterValues(controllerContext, actionDescriptor);\r
+                        ActionExecutedContext postActionContext = InvokeActionMethodWithFilters(controllerContext, filterInfo.ActionFilters, actionDescriptor, parameters);\r
+                        InvokeActionResultWithFilters(controllerContext, filterInfo.ResultFilters, postActionContext.Result);\r
+                    }\r
+                }\r
+                catch (ThreadAbortException) {\r
+                    // This type of exception occurs as a result of Response.Redirect(), but we special-case so that\r
+                    // the filters don't see this as an error.\r
+                    throw;\r
+                }\r
+                catch (Exception ex) {\r
+                    // something blew up, so execute the exception filters\r
+                    ExceptionContext exceptionContext = InvokeExceptionFilters(controllerContext, filterInfo.ExceptionFilters, ex);\r
+                    if (!exceptionContext.ExceptionHandled) {\r
+                        throw;\r
+                    }\r
+                    InvokeActionResult(controllerContext, exceptionContext.Result);\r
+                }\r
+\r
+                return true;\r
+            }\r
+\r
+            // notify controller that no method matched\r
+            return false;\r
+        }\r
+\r
+        protected virtual ActionResult InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters) {\r
+            object returnValue = actionDescriptor.Execute(controllerContext, parameters);\r
+            ActionResult result = CreateActionResult(controllerContext, actionDescriptor, returnValue);\r
+            return result;\r
+        }\r
+\r
+        internal static ActionExecutedContext InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func<ActionExecutedContext> continuation) {\r
+            filter.OnActionExecuting(preContext);\r
+            if (preContext.Result != null) {\r
+                return new ActionExecutedContext(preContext, preContext.ActionDescriptor, true /* canceled */, null /* exception */) {\r
+                    Result = preContext.Result\r
+                };\r
+            }\r
+\r
+            bool wasError = false;\r
+            ActionExecutedContext postContext = null;\r
+            try {\r
+                postContext = continuation();\r
+            }\r
+            catch (ThreadAbortException) {\r
+                // This type of exception occurs as a result of Response.Redirect(), but we special-case so that\r
+                // the filters don't see this as an error.\r
+                postContext = new ActionExecutedContext(preContext, preContext.ActionDescriptor, false /* canceled */, null /* exception */);\r
+                filter.OnActionExecuted(postContext);\r
+                throw;\r
+            }\r
+            catch (Exception ex) {\r
+                wasError = true;\r
+                postContext = new ActionExecutedContext(preContext, preContext.ActionDescriptor, false /* canceled */, ex);\r
+                filter.OnActionExecuted(postContext);\r
+                if (!postContext.ExceptionHandled) {\r
+                    throw;\r
+                }\r
+            }\r
+            if (!wasError) {\r
+                filter.OnActionExecuted(postContext);\r
+            }\r
+            return postContext;\r
+        }\r
+\r
+        protected virtual ActionExecutedContext InvokeActionMethodWithFilters(ControllerContext controllerContext, IList<IActionFilter> filters, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters) {\r
+            ActionExecutingContext preContext = new ActionExecutingContext(controllerContext, actionDescriptor, parameters);\r
+            Func<ActionExecutedContext> continuation = () =>\r
+                new ActionExecutedContext(controllerContext, actionDescriptor, false /* canceled */, null /* exception */) {\r
+                    Result = InvokeActionMethod(controllerContext, actionDescriptor, parameters)\r
+                };\r
+\r
+            // need to reverse the filter list because the continuations are built up backward\r
+            Func<ActionExecutedContext> thunk = filters.Reverse().Aggregate(continuation,\r
+                (next, filter) => () => InvokeActionMethodFilter(filter, preContext, next));\r
+            return thunk();\r
+        }\r
+\r
+        protected virtual void InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) {\r
+            actionResult.ExecuteResult(controllerContext);\r
+        }\r
+\r
+        internal static ResultExecutedContext InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func<ResultExecutedContext> continuation) {\r
+            filter.OnResultExecuting(preContext);\r
+            if (preContext.Cancel) {\r
+                return new ResultExecutedContext(preContext, preContext.Result, true /* canceled */, null /* exception */);\r
+            }\r
+\r
+            bool wasError = false;\r
+            ResultExecutedContext postContext = null;\r
+            try {\r
+                postContext = continuation();\r
+            }\r
+            catch (ThreadAbortException) {\r
+                // This type of exception occurs as a result of Response.Redirect(), but we special-case so that\r
+                // the filters don't see this as an error.\r
+                postContext = new ResultExecutedContext(preContext, preContext.Result, false /* canceled */, null /* exception */);\r
+                filter.OnResultExecuted(postContext);\r
+                throw;\r
+            }\r
+            catch (Exception ex) {\r
+                wasError = true;\r
+                postContext = new ResultExecutedContext(preContext, preContext.Result, false /* canceled */, ex);\r
+                filter.OnResultExecuted(postContext);\r
+                if (!postContext.ExceptionHandled) {\r
+                    throw;\r
+                }\r
+            }\r
+            if (!wasError) {\r
+                filter.OnResultExecuted(postContext);\r
+            }\r
+            return postContext;\r
+        }\r
+\r
+        protected virtual ResultExecutedContext InvokeActionResultWithFilters(ControllerContext controllerContext, IList<IResultFilter> filters, ActionResult actionResult) {\r
+            ResultExecutingContext preContext = new ResultExecutingContext(controllerContext, actionResult);\r
+            Func<ResultExecutedContext> continuation = delegate {\r
+                InvokeActionResult(controllerContext, actionResult);\r
+                return new ResultExecutedContext(controllerContext, actionResult, false /* canceled */, null /* exception */);\r
+            };\r
+\r
+            // need to reverse the filter list because the continuations are built up backward\r
+            Func<ResultExecutedContext> thunk = filters.Reverse().Aggregate(continuation,\r
+                (next, filter) => () => InvokeActionResultFilter(filter, preContext, next));\r
+            return thunk();\r
+        }\r
+\r
+        protected virtual AuthorizationContext InvokeAuthorizationFilters(ControllerContext controllerContext, IList<IAuthorizationFilter> filters, ActionDescriptor actionDescriptor) {\r
+            AuthorizationContext context = new AuthorizationContext(controllerContext, actionDescriptor);\r
+            foreach (IAuthorizationFilter filter in filters) {\r
+                filter.OnAuthorization(context);\r
+                // short-circuit evaluation\r
+                if (context.Result != null) {\r
+                    break;\r
+                }\r
+            }\r
+\r
+            return context;\r
+        }\r
+\r
+        protected virtual ExceptionContext InvokeExceptionFilters(ControllerContext controllerContext, IList<IExceptionFilter> filters, Exception exception) {\r
+            ExceptionContext context = new ExceptionContext(controllerContext, exception);\r
+            foreach (IExceptionFilter filter in filters) {\r
+                filter.OnException(context);\r
+            }\r
+\r
+            return context;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "rawUrl",\r
+            Justification = "We only care about the property getter's side effects, not the returned value.")]\r
+        internal static void ValidateRequest(ControllerContext controllerContext) {\r
+            if (controllerContext.IsChildAction) {\r
+                return;\r
+            }\r
+\r
+            // DevDiv 214040: Enable Request Validation by default for all controller requests\r
+            // \r
+            // Note that we grab the Request's RawUrl to force it to be validated. Calling ValidateInput()\r
+            // doesn't actually validate anything. It just sets flags indicating that on the next usage of\r
+            // certain inputs that they should be validated. We special case RawUrl because the URL has already\r
+            // been consumed by routing and thus might contain dangerous data. By forcing the RawUrl to be\r
+            // re-read we're making sure that it gets validated by ASP.NET.\r
+\r
+            controllerContext.HttpContext.Request.ValidateInput();\r
+            string rawUrl = controllerContext.HttpContext.Request.RawUrl;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerBase.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerBase.cs
new file mode 100644 (file)
index 0000000..b5902bd
--- /dev/null
@@ -0,0 +1,116 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.Web.Mvc.Async;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.Routing;\r
+\r
+    public abstract class ControllerBase : IController {\r
+\r
+        private readonly SingleEntryGate _executeWasCalledGate = new SingleEntryGate();\r
+\r
+        private TempDataDictionary _tempDataDictionary;\r
+        private bool _validateRequest = true;\r
+        private IValueProvider _valueProvider;\r
+        private ViewDataDictionary _viewDataDictionary;\r
+\r
+        public ControllerContext ControllerContext {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly",\r
+            Justification = "This property is settable so that unit tests can provide mock implementations.")]\r
+        public TempDataDictionary TempData {\r
+            get {\r
+                if (ControllerContext != null && ControllerContext.IsChildAction) {\r
+                    return ControllerContext.ParentActionViewContext.TempData;\r
+                }\r
+                if (_tempDataDictionary == null) {\r
+                    _tempDataDictionary = new TempDataDictionary();\r
+                }\r
+                return _tempDataDictionary;\r
+            }\r
+            set {\r
+                _tempDataDictionary = value;\r
+            }\r
+        }\r
+\r
+        public bool ValidateRequest {\r
+            get {\r
+                return _validateRequest;\r
+            }\r
+            set {\r
+                _validateRequest = value;\r
+            }\r
+        }\r
+\r
+        public IValueProvider ValueProvider {\r
+            get {\r
+                if (_valueProvider == null) {\r
+                    _valueProvider = ValueProviderFactories.Factories.GetValueProvider(ControllerContext);\r
+                }\r
+                return _valueProvider;\r
+            }\r
+            set {\r
+                _valueProvider = value;\r
+            }\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly",\r
+            Justification = "This property is settable so that unit tests can provide mock implementations.")]\r
+        public ViewDataDictionary ViewData {\r
+            get {\r
+                if (_viewDataDictionary == null) {\r
+                    _viewDataDictionary = new ViewDataDictionary();\r
+                }\r
+                return _viewDataDictionary;\r
+            }\r
+            set {\r
+                _viewDataDictionary = value;\r
+            }\r
+        }\r
+\r
+        protected virtual void Execute(RequestContext requestContext) {\r
+            if (requestContext == null) {\r
+                throw new ArgumentNullException("requestContext");\r
+            }\r
+\r
+            VerifyExecuteCalledOnce();\r
+            Initialize(requestContext);\r
+            ExecuteCore();\r
+        }\r
+\r
+        protected abstract void ExecuteCore();\r
+\r
+        protected virtual void Initialize(RequestContext requestContext) {\r
+            ControllerContext = new ControllerContext(requestContext, this);\r
+        }\r
+\r
+        internal void VerifyExecuteCalledOnce() {\r
+            if (!_executeWasCalledGate.TryEnter()) {\r
+                string message = String.Format(CultureInfo.CurrentUICulture, MvcResources.ControllerBase_CannotHandleMultipleRequests, GetType());\r
+                throw new InvalidOperationException(message);\r
+            }\r
+        }\r
+\r
+        #region IController Members\r
+        void IController.Execute(RequestContext requestContext) {\r
+            Execute(requestContext);\r
+        }\r
+        #endregion\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerBuilder.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerBuilder.cs
new file mode 100644 (file)
index 0000000..c86f740
--- /dev/null
@@ -0,0 +1,87 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public class ControllerBuilder {\r
+\r
+        private Func<IControllerFactory> _factoryThunk;\r
+        private static ControllerBuilder _instance = new ControllerBuilder();\r
+        private HashSet<string> _namespaces = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\r
+\r
+        public ControllerBuilder() {\r
+            SetControllerFactory(new DefaultControllerFactory() {\r
+                ControllerBuilder = this\r
+            });\r
+        }\r
+\r
+        public static ControllerBuilder Current {\r
+            get {\r
+                return _instance;\r
+            }\r
+        }\r
+\r
+        public HashSet<string> DefaultNamespaces {\r
+            get {\r
+                return _namespaces;\r
+            }\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",\r
+            Justification = "Calling method multiple times might return different objects.")]\r
+        public IControllerFactory GetControllerFactory() {\r
+            IControllerFactory controllerFactoryInstance = _factoryThunk();\r
+            return controllerFactoryInstance;\r
+        }\r
+\r
+        public void SetControllerFactory(IControllerFactory controllerFactory) {\r
+            if (controllerFactory == null) {\r
+                throw new ArgumentNullException("controllerFactory");\r
+            }\r
+\r
+            _factoryThunk = () => controllerFactory;\r
+        }\r
+\r
+        public void SetControllerFactory(Type controllerFactoryType) {\r
+            if (controllerFactoryType == null) {\r
+                throw new ArgumentNullException("controllerFactoryType");\r
+            }\r
+            if (!typeof(IControllerFactory).IsAssignableFrom(controllerFactoryType)) {\r
+                throw new ArgumentException(\r
+                    String.Format(\r
+                        CultureInfo.CurrentUICulture,\r
+                        MvcResources.ControllerBuilder_MissingIControllerFactory,\r
+                        controllerFactoryType),\r
+                    "controllerFactoryType");\r
+            }\r
+\r
+            _factoryThunk = delegate() {\r
+                try {\r
+                    return (IControllerFactory)Activator.CreateInstance(controllerFactoryType);\r
+                }\r
+                catch (Exception ex) {\r
+                    throw new InvalidOperationException(\r
+                        String.Format(\r
+                            CultureInfo.CurrentUICulture,\r
+                            MvcResources.ControllerBuilder_ErrorCreatingControllerFactory,\r
+                            controllerFactoryType),\r
+                        ex);\r
+                }\r
+            };\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerContext.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerContext.cs
new file mode 100644 (file)
index 0000000..2262501
--- /dev/null
@@ -0,0 +1,134 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Web;\r
+    using System.Web.Routing;\r
+    using System.Web.Mvc.Html;\r
+\r
+    // Though many of the properties on ControllerContext and its subclassed types are virtual, there are still sealed\r
+    // properties (like ControllerContext.RequestContext, ActionExecutingContext.Result, etc.). If these properties\r
+    // were virtual, a mocking framework might override them with incorrect behavior (property getters would return\r
+    // null, property setters would be no-ops). By sealing these properties, we are forcing them to have the default\r
+    // "get or store a value" semantics that they were intended to have.\r
+\r
+    public class ControllerContext {\r
+\r
+        private HttpContextBase _httpContext;\r
+        private RequestContext _requestContext;\r
+        private RouteData _routeData;\r
+\r
+        internal const string PARENT_ACTION_VIEWCONTEXT = "ParentActionViewContext";\r
+\r
+        // parameterless constructor used for mocking\r
+        public ControllerContext() {\r
+        }\r
+\r
+        // copy constructor - allows for subclassed types to take an existing ControllerContext as a parameter\r
+        // and we'll automatically set the appropriate properties\r
+        [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors",\r
+            Justification = "The virtual property setters are only to support mocking frameworks, in which case this constructor shouldn't be called anyway.")]\r
+        protected ControllerContext(ControllerContext controllerContext) {\r
+            if (controllerContext == null) {\r
+                throw new ArgumentNullException("controllerContext");\r
+            }\r
+\r
+            Controller = controllerContext.Controller;\r
+            RequestContext = controllerContext.RequestContext;\r
+        }\r
+\r
+        public ControllerContext(HttpContextBase httpContext, RouteData routeData, ControllerBase controller)\r
+            : this(new RequestContext(httpContext, routeData), controller) {\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors",\r
+            Justification = "The virtual property setters are only to support mocking frameworks, in which case this constructor shouldn't be called anyway.")]\r
+        public ControllerContext(RequestContext requestContext, ControllerBase controller) {\r
+            if (requestContext == null) {\r
+                throw new ArgumentNullException("requestContext");\r
+            }\r
+            if (controller == null) {\r
+                throw new ArgumentNullException("controller");\r
+            }\r
+\r
+            RequestContext = requestContext;\r
+            Controller = controller;\r
+        }\r
+\r
+        public virtual ControllerBase Controller {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public virtual HttpContextBase HttpContext {\r
+            get {\r
+                if (_httpContext == null) {\r
+                    _httpContext = (_requestContext != null) ? _requestContext.HttpContext : new EmptyHttpContext();\r
+                }\r
+                return _httpContext;\r
+            }\r
+            set {\r
+                _httpContext = value;\r
+            }\r
+        }\r
+\r
+        public virtual bool IsChildAction {\r
+            get {\r
+                RouteData routeData = RouteData;\r
+                if (routeData == null) {\r
+                    return false;\r
+                }\r
+                return routeData.DataTokens.ContainsKey(PARENT_ACTION_VIEWCONTEXT);\r
+            }\r
+        }\r
+\r
+        public ViewContext ParentActionViewContext {\r
+            get {\r
+                return RouteData.DataTokens[PARENT_ACTION_VIEWCONTEXT] as ViewContext;\r
+            }\r
+        }\r
+\r
+        public RequestContext RequestContext {\r
+            get {\r
+                if (_requestContext == null) {\r
+                    // still need explicit calls to constructors since the property getters are virtual and might return null\r
+                    HttpContextBase httpContext = HttpContext ?? new EmptyHttpContext();\r
+                    RouteData routeData = RouteData ?? new RouteData();\r
+\r
+                    _requestContext = new RequestContext(httpContext, routeData);\r
+                }\r
+                return _requestContext;\r
+            }\r
+            set {\r
+                _requestContext = value;\r
+            }\r
+        }\r
+\r
+        public virtual RouteData RouteData {\r
+            get {\r
+                if (_routeData == null) {\r
+                    _routeData = (_requestContext != null) ? _requestContext.RouteData : new RouteData();\r
+                }\r
+                return _routeData;\r
+            }\r
+            set {\r
+                _routeData = value;\r
+            }\r
+        }\r
+\r
+        private sealed class EmptyHttpContext : HttpContextBase {\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerDescriptor.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerDescriptor.cs
new file mode 100644 (file)
index 0000000..abb7c23
--- /dev/null
@@ -0,0 +1,59 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Reflection;\r
+\r
+    public abstract class ControllerDescriptor : ICustomAttributeProvider {\r
+\r
+        public virtual string ControllerName {\r
+            get {\r
+                string typeName = ControllerType.Name;\r
+                if (typeName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)) {\r
+                    return typeName.Substring(0, typeName.Length - "Controller".Length);\r
+                }\r
+\r
+                return typeName;\r
+            }\r
+        }\r
+\r
+        public abstract Type ControllerType {\r
+            get;\r
+        }\r
+\r
+        public abstract ActionDescriptor FindAction(ControllerContext controllerContext, string actionName);\r
+\r
+        public abstract ActionDescriptor[] GetCanonicalActions();\r
+\r
+        public virtual object[] GetCustomAttributes(bool inherit) {\r
+            return GetCustomAttributes(typeof(object), inherit);\r
+        }\r
+\r
+        public virtual object[] GetCustomAttributes(Type attributeType, bool inherit) {\r
+            if (attributeType == null) {\r
+                throw new ArgumentNullException("attributeType");\r
+            }\r
+\r
+            return (object[])Array.CreateInstance(attributeType, 0);\r
+        }\r
+\r
+        public virtual bool IsDefined(Type attributeType, bool inherit) {\r
+            if (attributeType == null) {\r
+                throw new ArgumentNullException("attributeType");\r
+            }\r
+\r
+            return false;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerDescriptorCache.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerDescriptorCache.cs
new file mode 100644 (file)
index 0000000..43ed25e
--- /dev/null
@@ -0,0 +1,26 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    internal sealed class ControllerDescriptorCache : ReaderWriterCache<Type, ControllerDescriptor> {\r
+\r
+        public ControllerDescriptorCache() {\r
+        }\r
+\r
+        public ControllerDescriptor GetDescriptor(Type controllerType, Func<ControllerDescriptor> creator) {\r
+            return FetchOrCreateItem(controllerType, creator);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerTypeCache.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ControllerTypeCache.cs
new file mode 100644 (file)
index 0000000..bea8005
--- /dev/null
@@ -0,0 +1,127 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections;\r
+    using System.Collections.Generic;\r
+    using System.Linq;\r
+    using System.Reflection;\r
+\r
+    internal sealed class ControllerTypeCache {\r
+\r
+        private const string _typeCacheName = "MVC-ControllerTypeCache.xml";\r
+\r
+        private Dictionary<string, ILookup<string, Type>> _cache;\r
+        private object _lockObj = new object();\r
+\r
+        internal int Count {\r
+            get {\r
+                int count = 0;\r
+                foreach (var lookup in _cache.Values) {\r
+                    foreach (var grouping in lookup) {\r
+                        count += grouping.Count();\r
+                    }\r
+                }\r
+                return count;\r
+            }\r
+        }\r
+\r
+        public void EnsureInitialized(IBuildManager buildManager) {\r
+            if (_cache == null) {\r
+                lock (_lockObj) {\r
+                    if (_cache == null) {\r
+                        List<Type> controllerTypes = TypeCacheUtil.GetFilteredTypesFromAssemblies(_typeCacheName, IsControllerType, buildManager);\r
+                        var groupedByName = controllerTypes.GroupBy(\r
+                            t => t.Name.Substring(0, t.Name.Length - "Controller".Length),\r
+                            StringComparer.OrdinalIgnoreCase);\r
+                        _cache = groupedByName.ToDictionary(\r
+                            g => g.Key,\r
+                            g => g.ToLookup(t => t.Namespace ?? String.Empty, StringComparer.OrdinalIgnoreCase),\r
+                            StringComparer.OrdinalIgnoreCase);\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+        public ICollection<Type> GetControllerTypes(string controllerName, HashSet<string> namespaces) {\r
+            HashSet<Type> matchingTypes = new HashSet<Type>();\r
+\r
+            ILookup<string, Type> nsLookup;\r
+            if (_cache.TryGetValue(controllerName, out nsLookup)) {\r
+                // this friendly name was located in the cache, now cycle through namespaces\r
+                if (namespaces != null) {\r
+                    foreach (string requestedNamespace in namespaces) {\r
+                        foreach (var targetNamespaceGrouping in nsLookup) {\r
+                            if (IsNamespaceMatch(requestedNamespace, targetNamespaceGrouping.Key)) {\r
+                                matchingTypes.UnionWith(targetNamespaceGrouping);\r
+                            }\r
+                        }\r
+                    }\r
+                }\r
+                else {\r
+                    // if the namespaces parameter is null, search *every* namespace\r
+                    foreach (var nsGroup in nsLookup) {\r
+                        matchingTypes.UnionWith(nsGroup);\r
+                    }\r
+                }\r
+            }\r
+\r
+            return matchingTypes;\r
+        }\r
+\r
+        internal static bool IsControllerType(Type t) {\r
+            return\r
+                t != null &&\r
+                t.IsPublic &&\r
+                t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase) &&\r
+                !t.IsAbstract &&\r
+                typeof(IController).IsAssignableFrom(t);\r
+        }\r
+\r
+        internal static bool IsNamespaceMatch(string requestedNamespace, string targetNamespace) {\r
+            // degenerate cases\r
+            if (requestedNamespace == null) {\r
+                return false;\r
+            }\r
+            else if (requestedNamespace.Length == 0) {\r
+                return true;\r
+            }\r
+\r
+            if (!requestedNamespace.EndsWith(".*", StringComparison.OrdinalIgnoreCase)) {\r
+                // looking for exact namespace match\r
+                return String.Equals(requestedNamespace, targetNamespace, StringComparison.OrdinalIgnoreCase);\r
+            }\r
+            else {\r
+                // looking for exact or sub-namespace match\r
+                requestedNamespace = requestedNamespace.Substring(0, requestedNamespace.Length - ".*".Length);\r
+                if (!targetNamespace.StartsWith(requestedNamespace, StringComparison.OrdinalIgnoreCase)) {\r
+                    return false;\r
+                }\r
+\r
+                if (requestedNamespace.Length == targetNamespace.Length) {\r
+                    // exact match\r
+                    return true;\r
+                }\r
+                else if (targetNamespace[requestedNamespace.Length] == '.') {\r
+                    // good prefix match, e.g. requestedNamespace = "Foo.Bar" and targetNamespace = "Foo.Bar.Baz"\r
+                    return true;\r
+                }\r
+                else {\r
+                    // bad prefix match, e.g. requestedNamespace = "Foo.Bar" and targetNamespace = "Foo.Bar2"\r
+                    return false;\r
+                }\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/CustomModelBinderAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/CustomModelBinderAttribute.cs
new file mode 100644 (file)
index 0000000..c086781
--- /dev/null
@@ -0,0 +1,27 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+\r
+    [AttributeUsage(ValidTargets, AllowMultiple = false, Inherited = false)]\r
+    public abstract class CustomModelBinderAttribute : Attribute {\r
+\r
+        internal const AttributeTargets ValidTargets = AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Struct;\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",\r
+            Justification = "This method can potentially perform a non-trivial amount of work.")]\r
+        public abstract IModelBinder GetBinder();\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/DataAnnotationsModelMetadata.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/DataAnnotationsModelMetadata.cs
new file mode 100644 (file)
index 0000000..aba69fa
--- /dev/null
@@ -0,0 +1,63 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.ComponentModel.DataAnnotations;\r
+    using System.Globalization;\r
+    using System.Reflection;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public class DataAnnotationsModelMetadata : ModelMetadata {\r
+        private DisplayColumnAttribute _displayColumnAttribute;\r
+\r
+        public DataAnnotationsModelMetadata(DataAnnotationsModelMetadataProvider provider, Type containerType,\r
+                                            Func<object> modelAccessor, Type modelType, string propertyName,\r
+                                            DisplayColumnAttribute displayColumnAttribute)\r
+            : base(provider, containerType, modelAccessor, modelType, propertyName) {\r
+            _displayColumnAttribute = displayColumnAttribute;\r
+        }\r
+\r
+        protected override string GetSimpleDisplayText() {\r
+            if (Model != null) {\r
+                if (_displayColumnAttribute != null && !String.IsNullOrEmpty(_displayColumnAttribute.DisplayColumn)) {\r
+                    PropertyInfo displayColumnProperty = ModelType.GetProperty(_displayColumnAttribute.DisplayColumn, BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance);\r
+                    ValidateDisplayColumnAttribute(_displayColumnAttribute, displayColumnProperty, ModelType);\r
+\r
+                    object simpleDisplayTextValue = displayColumnProperty.GetValue(Model, new object[0]);\r
+                    if (simpleDisplayTextValue != null) {\r
+                        return simpleDisplayTextValue.ToString();\r
+                    }\r
+                }\r
+            }\r
+\r
+            return base.GetSimpleDisplayText();\r
+        }\r
+\r
+        private static void ValidateDisplayColumnAttribute(DisplayColumnAttribute displayColumnAttribute, PropertyInfo displayColumnProperty, Type modelType) {\r
+            if (displayColumnProperty == null) {\r
+                throw new InvalidOperationException(\r
+                    String.Format(\r
+                        CultureInfo.CurrentCulture,\r
+                        MvcResources.DataAnnotationsModelMetadataProvider_UnknownProperty,\r
+                        modelType.FullName, displayColumnAttribute.DisplayColumn));\r
+            }\r
+            if (displayColumnProperty.GetGetMethod() == null) {\r
+                throw new InvalidOperationException(\r
+                    String.Format(\r
+                        CultureInfo.CurrentCulture,\r
+                        MvcResources.DataAnnotationsModelMetadataProvider_UnreadableProperty,\r
+                        modelType.FullName, displayColumnAttribute.DisplayColumn));\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/DataAnnotationsModelMetadataProvider.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/DataAnnotationsModelMetadataProvider.cs
new file mode 100644 (file)
index 0000000..7dffa9b
--- /dev/null
@@ -0,0 +1,83 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.ComponentModel;\r
+    using System.ComponentModel.DataAnnotations;\r
+    using System.Linq;\r
+\r
+    public class DataAnnotationsModelMetadataProvider : AssociatedMetadataProvider {\r
+        protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName) {\r
+            List<Attribute> attributeList = new List<Attribute>(attributes);\r
+            DisplayColumnAttribute displayColumnAttribute = attributeList.OfType<DisplayColumnAttribute>().FirstOrDefault();\r
+            DataAnnotationsModelMetadata result = new DataAnnotationsModelMetadata(this, containerType, modelAccessor, modelType, propertyName, displayColumnAttribute);\r
+\r
+            // Do [HiddenInput] before [UIHint], so you can override the template hint\r
+            HiddenInputAttribute hiddenInputAttribute = attributeList.OfType<HiddenInputAttribute>().FirstOrDefault();\r
+            if (hiddenInputAttribute != null) {\r
+                result.TemplateHint = "HiddenInput";\r
+                result.HideSurroundingHtml = !hiddenInputAttribute.DisplayValue;\r
+            }\r
+\r
+            // We prefer [UIHint("...", PresentationLayer = "MVC")] but will fall back to [UIHint("...")]\r
+            IEnumerable<UIHintAttribute> uiHintAttributes = attributeList.OfType<UIHintAttribute>();\r
+            UIHintAttribute uiHintAttribute = uiHintAttributes.FirstOrDefault(a => String.Equals(a.PresentationLayer, "MVC", StringComparison.OrdinalIgnoreCase))\r
+                                           ?? uiHintAttributes.FirstOrDefault(a => String.IsNullOrEmpty(a.PresentationLayer));\r
+            if (uiHintAttribute != null) {\r
+                result.TemplateHint = uiHintAttribute.UIHint;\r
+            }\r
+\r
+            DataTypeAttribute dataTypeAttribute = attributeList.OfType<DataTypeAttribute>().FirstOrDefault();\r
+            if (dataTypeAttribute != null) {\r
+                result.DataTypeName = dataTypeAttribute.GetDataTypeName();\r
+            }\r
+\r
+            ReadOnlyAttribute readOnlyAttribute = attributeList.OfType<ReadOnlyAttribute>().FirstOrDefault();\r
+            if (readOnlyAttribute != null) {\r
+                result.IsReadOnly = readOnlyAttribute.IsReadOnly;\r
+            }\r
+\r
+            DisplayFormatAttribute displayFormatAttribute = attributeList.OfType<DisplayFormatAttribute>().FirstOrDefault();\r
+            if (displayFormatAttribute == null && dataTypeAttribute != null) {\r
+                displayFormatAttribute = dataTypeAttribute.DisplayFormat;\r
+            }\r
+            if (displayFormatAttribute != null) {\r
+                result.NullDisplayText = displayFormatAttribute.NullDisplayText;\r
+                result.DisplayFormatString = displayFormatAttribute.DataFormatString;\r
+                result.ConvertEmptyStringToNull = displayFormatAttribute.ConvertEmptyStringToNull;\r
+\r
+                if (displayFormatAttribute.ApplyFormatInEditMode) {\r
+                    result.EditFormatString = displayFormatAttribute.DataFormatString;\r
+                }\r
+            }\r
+\r
+            ScaffoldColumnAttribute scaffoldColumnAttribute = attributeList.OfType<ScaffoldColumnAttribute>().FirstOrDefault();\r
+            if (scaffoldColumnAttribute != null) {\r
+                result.ShowForDisplay = result.ShowForEdit = scaffoldColumnAttribute.Scaffold;\r
+            }\r
+\r
+            DisplayNameAttribute displayNameAttribute = attributeList.OfType<DisplayNameAttribute>().FirstOrDefault();\r
+            if (displayNameAttribute != null) {\r
+                result.DisplayName = displayNameAttribute.DisplayName;\r
+            }\r
+\r
+            RequiredAttribute requiredAttribute = attributeList.OfType<RequiredAttribute>().FirstOrDefault();\r
+            if (requiredAttribute != null) {\r
+                result.IsRequired = true;\r
+            }\r
+\r
+            return result;\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/DataAnnotationsModelValidator.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/DataAnnotationsModelValidator.cs
new file mode 100644 (file)
index 0000000..7b83c66
--- /dev/null
@@ -0,0 +1,55 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.ComponentModel.DataAnnotations;\r
+\r
+    public class DataAnnotationsModelValidator : ModelValidator {\r
+        public DataAnnotationsModelValidator(ModelMetadata metadata, ControllerContext context, ValidationAttribute attribute)\r
+            : base(metadata, context) {\r
+\r
+            if (attribute == null) {\r
+                throw new ArgumentNullException("attribute");\r
+            }\r
+\r
+            Attribute = attribute;\r
+        }\r
+\r
+        protected internal ValidationAttribute Attribute { get; private set; }\r
+\r
+        protected internal string ErrorMessage {\r
+            get {\r
+                return Attribute.FormatErrorMessage(Metadata.GetDisplayName());\r
+            }\r
+        }\r
+\r
+        public override bool IsRequired {\r
+            get {\r
+                return Attribute is RequiredAttribute;\r
+            }\r
+        }\r
+\r
+        internal static ModelValidator Create(ModelMetadata metadata, ControllerContext context, ValidationAttribute attribute) {\r
+            return new DataAnnotationsModelValidator(metadata, context, attribute);\r
+        }\r
+\r
+        public override IEnumerable<ModelValidationResult> Validate(object container) {\r
+            if (!Attribute.IsValid(Metadata.Model)) {\r
+                yield return new ModelValidationResult {\r
+                    Message = ErrorMessage\r
+                };\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/DataAnnotationsModelValidatorProvider.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/DataAnnotationsModelValidatorProvider.cs
new file mode 100644 (file)
index 0000000..3e0c97f
--- /dev/null
@@ -0,0 +1,187 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.ComponentModel.DataAnnotations;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+    using System.Reflection;\r
+    using System.Threading;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public delegate ModelValidator DataAnnotationsModelValidationFactory(ModelMetadata metadata, ControllerContext context, ValidationAttribute attribute);\r
+\r
+    public class DataAnnotationsModelValidatorProvider : AssociatedValidatorProvider {\r
+        private static bool _addImplicitRequiredAttributeForValueTypes = true;\r
+        private static ReaderWriterLockSlim _adaptersLock = new ReaderWriterLockSlim();\r
+\r
+        internal static DataAnnotationsModelValidationFactory DefaultAttributeFactory = DataAnnotationsModelValidator.Create;\r
+        internal static Dictionary<Type, DataAnnotationsModelValidationFactory> AttributeFactories = new Dictionary<Type, DataAnnotationsModelValidationFactory>() {\r
+            {\r
+                typeof(RangeAttribute),\r
+                (metadata, context, attribute) => new RangeAttributeAdapter(metadata, context, (RangeAttribute)attribute)\r
+            },\r
+            {\r
+                typeof(RegularExpressionAttribute),\r
+                (metadata, context, attribute) => new RegularExpressionAttributeAdapter(metadata, context, (RegularExpressionAttribute)attribute)\r
+            },\r
+            {\r
+                typeof(RequiredAttribute),\r
+                (metadata, context, attribute) => new RequiredAttributeAdapter(metadata, context, (RequiredAttribute)attribute)\r
+            },\r
+            {\r
+                typeof(StringLengthAttribute),\r
+                (metadata, context, attribute) => new StringLengthAttributeAdapter(metadata, context, (StringLengthAttribute)attribute)\r
+            },\r
+        };\r
+\r
+        public static bool AddImplicitRequiredAttributeForValueTypes {\r
+            get {\r
+                return _addImplicitRequiredAttributeForValueTypes;\r
+            }\r
+            set {\r
+                _addImplicitRequiredAttributeForValueTypes = value;\r
+            }\r
+        }\r
+\r
+        protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes) {\r
+            _adaptersLock.EnterReadLock();\r
+\r
+            try {\r
+                List<ModelValidator> results = new List<ModelValidator>();\r
+\r
+                if (AddImplicitRequiredAttributeForValueTypes &&\r
+                        metadata.IsRequired &&\r
+                        !attributes.Any(a => a is RequiredAttribute)) {\r
+                    attributes = attributes.Concat(new[] { new RequiredAttribute() });\r
+                }\r
+\r
+                foreach (ValidationAttribute attribute in attributes.OfType<ValidationAttribute>()) {\r
+                    DataAnnotationsModelValidationFactory factory;\r
+                    if (!AttributeFactories.TryGetValue(attribute.GetType(), out factory)) {\r
+                        factory = DefaultAttributeFactory;\r
+                    }\r
+                    results.Add(factory(metadata, context, attribute));\r
+                }\r
+\r
+                return results;\r
+            }\r
+            finally {\r
+                _adaptersLock.ExitReadLock();\r
+            }\r
+        }\r
+\r
+        public static void RegisterAdapter(Type attributeType, Type adapterType) {\r
+            ValidateAttributeType(attributeType);\r
+            ValidateAdapterType(adapterType);\r
+            ConstructorInfo constructor = GetAdapterConstructor(attributeType, adapterType);\r
+\r
+            _adaptersLock.EnterWriteLock();\r
+\r
+            try {\r
+                AttributeFactories[attributeType] = (metadata, context, attribute) => (ModelValidator)constructor.Invoke(new object[] { metadata, context, attribute });\r
+            }\r
+            finally {\r
+                _adaptersLock.ExitWriteLock();\r
+            }\r
+        }\r
+\r
+        public static void RegisterAdapterFactory(Type attributeType, DataAnnotationsModelValidationFactory factory) {\r
+            ValidateAttributeType(attributeType);\r
+            ValidateFactory(factory);\r
+\r
+            _adaptersLock.EnterWriteLock();\r
+\r
+            try {\r
+                AttributeFactories[attributeType] = factory;\r
+            }\r
+            finally {\r
+                _adaptersLock.ExitWriteLock();\r
+            }\r
+        }\r
+\r
+        public static void RegisterDefaultAdapter(Type adapterType) {\r
+            ValidateAdapterType(adapterType);\r
+            ConstructorInfo constructor = GetAdapterConstructor(typeof(ValidationAttribute), adapterType);\r
+\r
+            DefaultAttributeFactory = (metadata, context, attribute) => (ModelValidator)constructor.Invoke(new object[] { metadata, context, attribute });\r
+        }\r
+\r
+        public static void RegisterDefaultAdapterFactory(DataAnnotationsModelValidationFactory factory) {\r
+            ValidateFactory(factory);\r
+\r
+            DefaultAttributeFactory = factory;\r
+        }\r
+\r
+        // Helpers\r
+\r
+        private static ConstructorInfo GetAdapterConstructor(Type attributeType, Type adapterType) {\r
+            ConstructorInfo constructor = adapterType.GetConstructor(new[] { typeof(ModelMetadata), typeof(ControllerContext), attributeType });\r
+            if (constructor == null) {\r
+                throw new ArgumentException(\r
+                    String.Format(\r
+                        CultureInfo.CurrentCulture,\r
+                        MvcResources.DataAnnotationsModelValidatorProvider_ConstructorRequirements,\r
+                        adapterType.FullName,\r
+                        typeof(ModelMetadata).FullName,\r
+                        typeof(ControllerContext).FullName,\r
+                        attributeType.FullName\r
+                    ),\r
+                    "adapterType"\r
+                );\r
+            }\r
+\r
+            return constructor;\r
+        }\r
+\r
+        private static void ValidateAdapterType(Type adapterType) {\r
+            if (adapterType == null) {\r
+                throw new ArgumentNullException("adapterType");\r
+            }\r
+            if (!typeof(ModelValidator).IsAssignableFrom(adapterType)) {\r
+                throw new ArgumentException(\r
+                    String.Format(\r
+                        CultureInfo.CurrentCulture,\r
+                        MvcResources.Common_TypeMustDriveFromType,\r
+                        adapterType.FullName,\r
+                        typeof(ModelValidator).FullName\r
+                    ),\r
+                    "adapterType"\r
+                );\r
+            }\r
+        }\r
+\r
+        private static void ValidateAttributeType(Type attributeType) {\r
+            if (attributeType == null) {\r
+                throw new ArgumentNullException("attributeType");\r
+            }\r
+            if (!typeof(ValidationAttribute).IsAssignableFrom(attributeType)) {\r
+                throw new ArgumentException(\r
+                    String.Format(\r
+                        CultureInfo.CurrentCulture,\r
+                        MvcResources.Common_TypeMustDriveFromType,\r
+                        attributeType.FullName,\r
+                        typeof(ValidationAttribute).FullName\r
+                    ),\r
+                    "attributeType");\r
+            }\r
+        }\r
+\r
+        private static void ValidateFactory(DataAnnotationsModelValidationFactory factory) {\r
+            if (factory == null) {\r
+                throw new ArgumentNullException("factory");\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/DataAnnotationsModelValidator`1.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/DataAnnotationsModelValidator`1.cs
new file mode 100644 (file)
index 0000000..d8d9812
--- /dev/null
@@ -0,0 +1,26 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.ComponentModel.DataAnnotations;\r
+\r
+    public class DataAnnotationsModelValidator<TAttribute> : DataAnnotationsModelValidator where TAttribute : ValidationAttribute {\r
+        public DataAnnotationsModelValidator(ModelMetadata metadata, ControllerContext context, TAttribute attribute)\r
+            : base(metadata, context, attribute) { }\r
+\r
+        protected new TAttribute Attribute {\r
+            get {\r
+                return (TAttribute)base.Attribute;\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/DataErrorInfoModelValidatorProvider.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/DataErrorInfoModelValidatorProvider.cs
new file mode 100644 (file)
index 0000000..eb10e5a
--- /dev/null
@@ -0,0 +1,87 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.ComponentModel;\r
+    using System.Linq;\r
+\r
+    public class DataErrorInfoModelValidatorProvider : ModelValidatorProvider {\r
+\r
+        public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context) {\r
+            if (metadata == null) {\r
+                throw new ArgumentNullException("metadata");\r
+            }\r
+            if (context == null) {\r
+                throw new ArgumentNullException("context");\r
+            }\r
+\r
+            return GetValidatorsImpl(metadata, context);\r
+        }\r
+\r
+        private static IEnumerable<ModelValidator> GetValidatorsImpl(ModelMetadata metadata, ControllerContext context) {\r
+            // If the metadata describes a model that implements IDataErrorInfo, we should call its\r
+            // Error property at the appropriate time.\r
+            if (TypeImplementsIDataErrorInfo(metadata.ModelType)) {\r
+                yield return new DataErrorInfoClassModelValidator(metadata, context);\r
+            }\r
+\r
+            // If the metadata describes a property of a container that implements IDataErrorInfo,\r
+            // we should call its Item indexer at the appropriate time.\r
+            if (TypeImplementsIDataErrorInfo(metadata.ContainerType)) {\r
+                yield return new DataErrorInfoPropertyModelValidator(metadata, context);\r
+            }\r
+        }\r
+\r
+        private static bool TypeImplementsIDataErrorInfo(Type type) {\r
+            return typeof(IDataErrorInfo).IsAssignableFrom(type);\r
+        }\r
+\r
+        internal sealed class DataErrorInfoClassModelValidator : ModelValidator {\r
+            public DataErrorInfoClassModelValidator(ModelMetadata metadata, ControllerContext controllerContext)\r
+                : base(metadata, controllerContext) {\r
+            }\r
+            public override IEnumerable<ModelValidationResult> Validate(object container) {\r
+                IDataErrorInfo castModel = Metadata.Model as IDataErrorInfo;\r
+                if (castModel != null) {\r
+                    string errorMessage = castModel.Error;\r
+                    if (!String.IsNullOrEmpty(errorMessage)) {\r
+                        return new ModelValidationResult[] {\r
+                            new ModelValidationResult() { Message = errorMessage }\r
+                        };\r
+                    }\r
+                }\r
+                return Enumerable.Empty<ModelValidationResult>();\r
+            }\r
+        }\r
+\r
+        internal sealed class DataErrorInfoPropertyModelValidator : ModelValidator {\r
+            public DataErrorInfoPropertyModelValidator(ModelMetadata metadata, ControllerContext controllerContext)\r
+                : base(metadata, controllerContext) {\r
+            }\r
+            public override IEnumerable<ModelValidationResult> Validate(object container) {\r
+                IDataErrorInfo castContainer = container as IDataErrorInfo;\r
+                if (castContainer != null && !String.Equals(Metadata.PropertyName, "error", StringComparison.OrdinalIgnoreCase)) {\r
+                    string errorMessage = castContainer[Metadata.PropertyName];\r
+                    if (!String.IsNullOrEmpty(errorMessage)) {\r
+                        return new ModelValidationResult[] {\r
+                            new ModelValidationResult() { Message = errorMessage }\r
+                        };\r
+                    }\r
+                }\r
+                return Enumerable.Empty<ModelValidationResult>();\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/DefaultControllerFactory.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/DefaultControllerFactory.cs
new file mode 100644 (file)
index 0000000..bb65189
--- /dev/null
@@ -0,0 +1,187 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections;\r
+    using System.Collections.Generic;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+    using System.Text;\r
+    using System.Web;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.Routing;\r
+\r
+    public class DefaultControllerFactory : IControllerFactory {\r
+\r
+        private IBuildManager _buildManager;\r
+        private ControllerBuilder _controllerBuilder;\r
+        private ControllerTypeCache _instanceControllerTypeCache;\r
+        private static ControllerTypeCache _staticControllerTypeCache = new ControllerTypeCache();\r
+\r
+        internal IBuildManager BuildManager {\r
+            get {\r
+                if (_buildManager == null) {\r
+                    _buildManager = new BuildManagerWrapper();\r
+                }\r
+                return _buildManager;\r
+            }\r
+            set {\r
+                _buildManager = value;\r
+            }\r
+        }\r
+\r
+        internal ControllerBuilder ControllerBuilder {\r
+            get {\r
+                return _controllerBuilder ?? ControllerBuilder.Current;\r
+            }\r
+            set {\r
+                _controllerBuilder = value;\r
+            }\r
+        }\r
+\r
+        internal ControllerTypeCache ControllerTypeCache {\r
+            get {\r
+                return _instanceControllerTypeCache ?? _staticControllerTypeCache;\r
+            }\r
+            set {\r
+                _instanceControllerTypeCache = value;\r
+            }\r
+        }\r
+\r
+        internal static InvalidOperationException CreateAmbiguousControllerException(RouteBase route, string controllerName, ICollection<Type> matchingTypes) {\r
+            // we need to generate an exception containing all the controller types\r
+            StringBuilder typeList = new StringBuilder();\r
+            foreach (Type matchedType in matchingTypes) {\r
+                typeList.AppendLine();\r
+                typeList.Append(matchedType.FullName);\r
+            }\r
+\r
+            string errorText;\r
+            Route castRoute = route as Route;\r
+            if (castRoute != null) {\r
+                errorText = String.Format(CultureInfo.CurrentUICulture, MvcResources.DefaultControllerFactory_ControllerNameAmbiguous_WithRouteUrl,\r
+                    controllerName, castRoute.Url, typeList);\r
+            }\r
+            else {\r
+                errorText = String.Format(CultureInfo.CurrentUICulture, MvcResources.DefaultControllerFactory_ControllerNameAmbiguous_WithoutRouteUrl,\r
+                    controllerName, typeList);\r
+            }\r
+\r
+            return new InvalidOperationException(errorText);\r
+        }\r
+\r
+        public virtual IController CreateController(RequestContext requestContext, string controllerName) {\r
+            if (requestContext == null) {\r
+                throw new ArgumentNullException("requestContext");\r
+            }\r
+            if (String.IsNullOrEmpty(controllerName)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "controllerName");\r
+            }\r
+            Type controllerType = GetControllerType(requestContext, controllerName);\r
+            IController controller = GetControllerInstance(requestContext, controllerType);\r
+            return controller;\r
+        }\r
+\r
+        protected internal virtual IController GetControllerInstance(RequestContext requestContext, Type controllerType) {\r
+            if (controllerType == null) {\r
+                throw new HttpException(404,\r
+                    String.Format(\r
+                        CultureInfo.CurrentUICulture,\r
+                        MvcResources.DefaultControllerFactory_NoControllerFound,\r
+                        requestContext.HttpContext.Request.Path));\r
+            }\r
+            if (!typeof(IController).IsAssignableFrom(controllerType)) {\r
+                throw new ArgumentException(\r
+                    String.Format(\r
+                        CultureInfo.CurrentUICulture,\r
+                        MvcResources.DefaultControllerFactory_TypeDoesNotSubclassControllerBase,\r
+                        controllerType),\r
+                    "controllerType");\r
+            }\r
+            try {\r
+                return (IController)Activator.CreateInstance(controllerType);\r
+            }\r
+            catch (Exception ex) {\r
+                throw new InvalidOperationException(\r
+                    String.Format(\r
+                        CultureInfo.CurrentUICulture,\r
+                        MvcResources.DefaultControllerFactory_ErrorCreatingController,\r
+                        controllerType),\r
+                    ex);\r
+            }\r
+        }\r
+\r
+        protected internal virtual Type GetControllerType(RequestContext requestContext, string controllerName) {\r
+            if (String.IsNullOrEmpty(controllerName)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "controllerName");\r
+            }\r
+\r
+            // first search in the current route's namespace collection\r
+            object routeNamespacesObj;\r
+            Type match;\r
+            if (requestContext != null && requestContext.RouteData.DataTokens.TryGetValue("Namespaces", out routeNamespacesObj)) {\r
+                IEnumerable<string> routeNamespaces = routeNamespacesObj as IEnumerable<string>;\r
+                if (routeNamespaces != null && routeNamespaces.Any()) {\r
+                    HashSet<string> nsHash = new HashSet<string>(routeNamespaces, StringComparer.OrdinalIgnoreCase);\r
+                    match = GetControllerTypeWithinNamespaces(requestContext.RouteData.Route, controllerName, nsHash);\r
+\r
+                    // the UseNamespaceFallback key might not exist, in which case its value is implicitly "true"\r
+                    if (match != null || false.Equals(requestContext.RouteData.DataTokens["UseNamespaceFallback"])) {\r
+                        // got a match or the route requested we stop looking\r
+                        return match;\r
+                    }\r
+                }\r
+            }\r
+\r
+            // then search in the application's default namespace collection\r
+            if (ControllerBuilder.DefaultNamespaces.Count > 0) {\r
+                HashSet<string> nsDefaults = new HashSet<string>(ControllerBuilder.DefaultNamespaces, StringComparer.OrdinalIgnoreCase);\r
+                match = GetControllerTypeWithinNamespaces(requestContext.RouteData.Route, controllerName, nsDefaults);\r
+                if (match != null) {\r
+                    return match;\r
+                }\r
+            }\r
+\r
+            // if all else fails, search every namespace\r
+            return GetControllerTypeWithinNamespaces(requestContext.RouteData.Route, controllerName, null /* namespaces */);\r
+        }\r
+\r
+        private Type GetControllerTypeWithinNamespaces(RouteBase route, string controllerName, HashSet<string> namespaces) {\r
+            // Once the master list of controllers has been created we can quickly index into it\r
+            ControllerTypeCache.EnsureInitialized(BuildManager);\r
+\r
+            ICollection<Type> matchingTypes = ControllerTypeCache.GetControllerTypes(controllerName, namespaces);\r
+            switch (matchingTypes.Count) {\r
+                case 0:\r
+                    // no matching types\r
+                    return null;\r
+\r
+                case 1:\r
+                    // single matching type\r
+                    return matchingTypes.First();\r
+\r
+                default:\r
+                    // multiple matching types\r
+                    throw CreateAmbiguousControllerException(route, controllerName, matchingTypes);\r
+            }\r
+        }\r
+\r
+        public virtual void ReleaseController(IController controller) {\r
+            IDisposable disposable = controller as IDisposable;\r
+            if (disposable != null) {\r
+                disposable.Dispose();\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/DefaultModelBinder.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/DefaultModelBinder.cs
new file mode 100644 (file)
index 0000000..02507e6
--- /dev/null
@@ -0,0 +1,709 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections;\r
+    using System.Collections.Generic;\r
+    using System.ComponentModel;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+    using System.Reflection;\r
+    using System.Runtime.CompilerServices;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public class DefaultModelBinder : IModelBinder {\r
+\r
+        private ModelBinderDictionary _binders;\r
+        private static string _resourceClassKey;\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly",\r
+            Justification = "Property is settable so that the dictionary can be provided for unit testing purposes.")]\r
+        protected internal ModelBinderDictionary Binders {\r
+            get {\r
+                if (_binders == null) {\r
+                    _binders = ModelBinders.Binders;\r
+                }\r
+                return _binders;\r
+            }\r
+            set {\r
+                _binders = value;\r
+            }\r
+        }\r
+\r
+        public static string ResourceClassKey {\r
+            get {\r
+                return _resourceClassKey ?? String.Empty;\r
+            }\r
+            set {\r
+                _resourceClassKey = value;\r
+            }\r
+        }\r
+\r
+        private static void AddValueRequiredMessageToModelState(ControllerContext controllerContext, ModelStateDictionary modelState, string modelStateKey, Type elementType, object value) {\r
+            if (value == null && !TypeHelpers.TypeAllowsNullValue(elementType) && modelState.IsValidField(modelStateKey)) {\r
+                modelState.AddModelError(modelStateKey, GetValueRequiredResource(controllerContext));\r
+            }\r
+        }\r
+\r
+        internal void BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, object model) {\r
+            // need to replace the property filter + model object and create an inner binding context\r
+            ModelBindingContext newBindingContext = CreateComplexElementalModelBindingContext(controllerContext, bindingContext, model);\r
+\r
+            // validation\r
+            if (OnModelUpdating(controllerContext, newBindingContext)) {\r
+                BindProperties(controllerContext, newBindingContext);\r
+                OnModelUpdated(controllerContext, newBindingContext);\r
+            }\r
+        }\r
+\r
+        internal object BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {\r
+            object model = bindingContext.Model;\r
+            Type modelType = bindingContext.ModelType;\r
+\r
+            // if we're being asked to create an array, create a list instead, then coerce to an array after the list is created\r
+            if (model == null && modelType.IsArray) {\r
+                Type elementType = modelType.GetElementType();\r
+                Type listType = typeof(List<>).MakeGenericType(elementType);\r
+                object collection = CreateModel(controllerContext, bindingContext, listType);\r
+\r
+                ModelBindingContext arrayBindingContext = new ModelBindingContext() {\r
+                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => collection, listType),\r
+                    ModelName = bindingContext.ModelName,\r
+                    ModelState = bindingContext.ModelState,\r
+                    PropertyFilter = bindingContext.PropertyFilter,\r
+                    ValueProvider = bindingContext.ValueProvider\r
+                };\r
+                IList list = (IList)UpdateCollection(controllerContext, arrayBindingContext, elementType);\r
+\r
+                if (list == null) {\r
+                    return null;\r
+                }\r
+\r
+                Array array = Array.CreateInstance(elementType, list.Count);\r
+                list.CopyTo(array, 0);\r
+                return array;\r
+            }\r
+\r
+            if (model == null) {\r
+                model = CreateModel(controllerContext, bindingContext, modelType);\r
+            }\r
+\r
+            // special-case IDictionary<,> and ICollection<>\r
+            Type dictionaryType = TypeHelpers.ExtractGenericInterface(modelType, typeof(IDictionary<,>));\r
+            if (dictionaryType != null) {\r
+                Type[] genericArguments = dictionaryType.GetGenericArguments();\r
+                Type keyType = genericArguments[0];\r
+                Type valueType = genericArguments[1];\r
+\r
+                ModelBindingContext dictionaryBindingContext = new ModelBindingContext() {\r
+                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, modelType),\r
+                    ModelName = bindingContext.ModelName,\r
+                    ModelState = bindingContext.ModelState,\r
+                    PropertyFilter = bindingContext.PropertyFilter,\r
+                    ValueProvider = bindingContext.ValueProvider\r
+                };\r
+                object dictionary = UpdateDictionary(controllerContext, dictionaryBindingContext, keyType, valueType);\r
+                return dictionary;\r
+            }\r
+\r
+            Type enumerableType = TypeHelpers.ExtractGenericInterface(modelType, typeof(IEnumerable<>));\r
+            if (enumerableType != null) {\r
+                Type elementType = enumerableType.GetGenericArguments()[0];\r
+\r
+                Type collectionType = typeof(ICollection<>).MakeGenericType(elementType);\r
+                if (collectionType.IsInstanceOfType(model)) {\r
+                    ModelBindingContext collectionBindingContext = new ModelBindingContext() {\r
+                        ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, modelType),\r
+                        ModelName = bindingContext.ModelName,\r
+                        ModelState = bindingContext.ModelState,\r
+                        PropertyFilter = bindingContext.PropertyFilter,\r
+                        ValueProvider = bindingContext.ValueProvider\r
+                    };\r
+                    object collection = UpdateCollection(controllerContext, collectionBindingContext, elementType);\r
+                    return collection;\r
+                }\r
+            }\r
+\r
+            // otherwise, just update the properties on the complex type\r
+            BindComplexElementalModel(controllerContext, bindingContext, model);\r
+            return model;\r
+        }\r
+\r
+        public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {\r
+            if (bindingContext == null) {\r
+                throw new ArgumentNullException("bindingContext");\r
+            }\r
+\r
+            bool performedFallback = false;\r
+\r
+            if (!String.IsNullOrEmpty(bindingContext.ModelName) && !bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName)) {\r
+                // We couldn't find any entry that began with the prefix. If this is the top-level element, fall back\r
+                // to the empty prefix.\r
+                if (bindingContext.FallbackToEmptyPrefix) {\r
+                    bindingContext = new ModelBindingContext() {\r
+                        ModelMetadata = bindingContext.ModelMetadata,\r
+                        ModelState = bindingContext.ModelState,\r
+                        PropertyFilter = bindingContext.PropertyFilter,\r
+                        ValueProvider = bindingContext.ValueProvider\r
+                    };\r
+                    performedFallback = true;\r
+                }\r
+                else {\r
+                    return null;\r
+                }\r
+            }\r
+\r
+            // Simple model = int, string, etc.; determined by calling TypeConverter.CanConvertFrom(typeof(string))\r
+            // or by seeing if a value in the request exactly matches the name of the model we're binding.\r
+            // Complex type = everything else.\r
+            if (!performedFallback) {\r
+                ValueProviderResult vpResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);\r
+                if (vpResult != null) {\r
+                    return BindSimpleModel(controllerContext, bindingContext, vpResult);\r
+                }\r
+            }\r
+            if (!bindingContext.ModelMetadata.IsComplexType) {\r
+                return null;\r
+            }\r
+\r
+            return BindComplexModel(controllerContext, bindingContext);\r
+        }\r
+\r
+        private void BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) {\r
+            IEnumerable<PropertyDescriptor> properties = GetFilteredModelProperties(controllerContext, bindingContext);\r
+            foreach (PropertyDescriptor property in properties) {\r
+                BindProperty(controllerContext, bindingContext, property);\r
+            }\r
+        }\r
+\r
+        protected virtual void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) {\r
+            // need to skip properties that aren't part of the request, else we might hit a StackOverflowException\r
+            string fullPropertyKey = CreateSubPropertyName(bindingContext.ModelName, propertyDescriptor.Name);\r
+            if (!bindingContext.ValueProvider.ContainsPrefix(fullPropertyKey)) {\r
+                return;\r
+            }\r
+\r
+            // call into the property's model binder\r
+            IModelBinder propertyBinder = Binders.GetBinder(propertyDescriptor.PropertyType);\r
+            object originalPropertyValue = propertyDescriptor.GetValue(bindingContext.Model);\r
+            ModelMetadata propertyMetadata = bindingContext.PropertyMetadata[propertyDescriptor.Name];\r
+            propertyMetadata.Model = originalPropertyValue;\r
+            ModelBindingContext innerBindingContext = new ModelBindingContext() {\r
+                ModelMetadata = propertyMetadata,\r
+                ModelName = fullPropertyKey,\r
+                ModelState = bindingContext.ModelState,\r
+                ValueProvider = bindingContext.ValueProvider\r
+            };\r
+            object newPropertyValue = GetPropertyValue(controllerContext, innerBindingContext, propertyDescriptor, propertyBinder);\r
+            propertyMetadata.Model = newPropertyValue;\r
+\r
+            // validation\r
+            ModelState modelState = bindingContext.ModelState[fullPropertyKey];\r
+            if (modelState == null || modelState.Errors.Count == 0) {\r
+                if (OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, newPropertyValue)) {\r
+                    SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);\r
+                    OnPropertyValidated(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);\r
+                }\r
+            }\r
+            else {\r
+                SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);\r
+\r
+                // Convert FormatExceptions (type conversion failures) into InvalidValue messages\r
+                foreach (ModelError error in modelState.Errors.Where(err => String.IsNullOrEmpty(err.ErrorMessage) && err.Exception != null).ToList()) {\r
+                    for (Exception exception = error.Exception; exception != null; exception = exception.InnerException) {\r
+                        if (exception is FormatException) {\r
+                            string displayName = propertyMetadata.GetDisplayName();\r
+                            string errorMessageTemplate = GetValueInvalidResource(controllerContext);\r
+                            string errorMessage = String.Format(CultureInfo.CurrentUICulture, errorMessageTemplate, modelState.Value.AttemptedValue, displayName);\r
+                            modelState.Errors.Remove(error);\r
+                            modelState.Errors.Add(errorMessage);\r
+                            break;\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+        internal object BindSimpleModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ValueProviderResult valueProviderResult) {\r
+            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);\r
+\r
+            // if the value provider returns an instance of the requested data type, we can just short-circuit\r
+            // the evaluation and return that instance\r
+            if (bindingContext.ModelType.IsInstanceOfType(valueProviderResult.RawValue)) {\r
+                return valueProviderResult.RawValue;\r
+            }\r
+\r
+            // since a string is an IEnumerable<char>, we want it to skip the two checks immediately following\r
+            if (bindingContext.ModelType != typeof(string)) {\r
+\r
+                // conversion results in 3 cases, as below\r
+                if (bindingContext.ModelType.IsArray) {\r
+                    // case 1: user asked for an array\r
+                    // ValueProviderResult.ConvertTo() understands array types, so pass in the array type directly\r
+                    object modelArray = ConvertProviderResult(bindingContext.ModelState, bindingContext.ModelName, valueProviderResult, bindingContext.ModelType);\r
+                    return modelArray;\r
+                }\r
+\r
+                Type enumerableType = TypeHelpers.ExtractGenericInterface(bindingContext.ModelType, typeof(IEnumerable<>));\r
+                if (enumerableType != null) {\r
+                    // case 2: user asked for a collection rather than an array\r
+                    // need to call ConvertTo() on the array type, then copy the array to the collection\r
+                    object modelCollection = CreateModel(controllerContext, bindingContext, bindingContext.ModelType);\r
+                    Type elementType = enumerableType.GetGenericArguments()[0];\r
+                    Type arrayType = elementType.MakeArrayType();\r
+                    object modelArray = ConvertProviderResult(bindingContext.ModelState, bindingContext.ModelName, valueProviderResult, arrayType);\r
+\r
+                    Type collectionType = typeof(ICollection<>).MakeGenericType(elementType);\r
+                    if (collectionType.IsInstanceOfType(modelCollection)) {\r
+                        CollectionHelpers.ReplaceCollection(elementType, modelCollection, modelArray);\r
+                    }\r
+                    return modelCollection;\r
+                }\r
+            }\r
+\r
+            // case 3: user asked for an individual element\r
+            object model = ConvertProviderResult(bindingContext.ModelState, bindingContext.ModelName, valueProviderResult, bindingContext.ModelType);\r
+            return model;\r
+        }\r
+\r
+        private static bool CanUpdateReadonlyTypedReference(Type type) {\r
+            // value types aren't strictly immutable, but because they have copy-by-value semantics\r
+            // we can't update a value type that is marked readonly\r
+            if (type.IsValueType) {\r
+                return false;\r
+            }\r
+\r
+            // arrays are mutable, but because we can't change their length we shouldn't try\r
+            // to update an array that is referenced readonly\r
+            if (type.IsArray) {\r
+                return false;\r
+            }\r
+\r
+            // special-case known common immutable types\r
+            if (type == typeof(string)) {\r
+                return false;\r
+            }\r
+\r
+            return true;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.Web.Mvc.ValueProviderResult.ConvertTo(System.Type)",\r
+            Justification = "The target object should make the correct culture determination, not this method.")]\r
+        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",\r
+            Justification = "We're recording this exception so that we can act on it later.")]\r
+        private static object ConvertProviderResult(ModelStateDictionary modelState, string modelStateKey, ValueProviderResult valueProviderResult, Type destinationType) {\r
+            try {\r
+                object convertedValue = valueProviderResult.ConvertTo(destinationType);\r
+                return convertedValue;\r
+            }\r
+            catch (Exception ex) {\r
+                modelState.AddModelError(modelStateKey, ex);\r
+                return null;\r
+            }\r
+        }\r
+\r
+        internal ModelBindingContext CreateComplexElementalModelBindingContext(ControllerContext controllerContext, ModelBindingContext bindingContext, object model) {\r
+            BindAttribute bindAttr = (BindAttribute)GetTypeDescriptor(controllerContext, bindingContext).GetAttributes()[typeof(BindAttribute)];\r
+            Predicate<string> newPropertyFilter = (bindAttr != null)\r
+                ? propertyName => bindAttr.IsPropertyAllowed(propertyName) && bindingContext.PropertyFilter(propertyName)\r
+                : bindingContext.PropertyFilter;\r
+\r
+            ModelBindingContext newBindingContext = new ModelBindingContext() {\r
+                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, bindingContext.ModelType),\r
+                ModelName = bindingContext.ModelName,\r
+                ModelState = bindingContext.ModelState,\r
+                PropertyFilter = newPropertyFilter,\r
+                ValueProvider = bindingContext.ValueProvider\r
+            };\r
+\r
+            return newBindingContext;\r
+        }\r
+\r
+        protected virtual object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) {\r
+            Type typeToCreate = modelType;\r
+\r
+            // we can understand some collection interfaces, e.g. IList<>, IDictionary<,>\r
+            if (modelType.IsGenericType) {\r
+                Type genericTypeDefinition = modelType.GetGenericTypeDefinition();\r
+                if (genericTypeDefinition == typeof(IDictionary<,>)) {\r
+                    typeToCreate = typeof(Dictionary<,>).MakeGenericType(modelType.GetGenericArguments());\r
+                }\r
+                else if (genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>) || genericTypeDefinition == typeof(IList<>)) {\r
+                    typeToCreate = typeof(List<>).MakeGenericType(modelType.GetGenericArguments());\r
+                }\r
+            }\r
+\r
+            // fallback to the type's default constructor\r
+            return Activator.CreateInstance(typeToCreate);\r
+        }\r
+\r
+        protected static string CreateSubIndexName(string prefix, int index) {\r
+            return String.Format(CultureInfo.InvariantCulture, "{0}[{1}]", prefix, index);\r
+        }\r
+\r
+        protected static string CreateSubIndexName(string prefix, string index) {\r
+            return String.Format(CultureInfo.InvariantCulture, "{0}[{1}]", prefix, index);\r
+        }\r
+\r
+        protected internal static string CreateSubPropertyName(string prefix, string propertyName) {\r
+            if (String.IsNullOrEmpty(prefix)) {\r
+                return propertyName;\r
+            }\r
+            else if (String.IsNullOrEmpty(propertyName)) {\r
+                return prefix;\r
+            }\r
+            else {\r
+                return prefix + "." + propertyName;\r
+            }\r
+        }\r
+\r
+        protected IEnumerable<PropertyDescriptor> GetFilteredModelProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) {\r
+            PropertyDescriptorCollection properties = GetModelProperties(controllerContext, bindingContext);\r
+            Predicate<string> propertyFilter = bindingContext.PropertyFilter;\r
+\r
+            return from PropertyDescriptor property in properties\r
+                   where ShouldUpdateProperty(property, propertyFilter)\r
+                   select property;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.Web.Mvc.ValueProviderResult.ConvertTo(System.Type)",\r
+            Justification = "ValueProviderResult already handles culture conversion appropriately.")]\r
+        private static void GetIndexes(ModelBindingContext bindingContext, out bool stopOnIndexNotFound, out IEnumerable<string> indexes) {\r
+            string indexKey = CreateSubPropertyName(bindingContext.ModelName, "index");\r
+            ValueProviderResult vpResult = bindingContext.ValueProvider.GetValue(indexKey);\r
+\r
+            if (vpResult != null) {\r
+                string[] indexesArray = vpResult.ConvertTo(typeof(string[])) as string[];\r
+                if (indexesArray != null) {\r
+                    stopOnIndexNotFound = false;\r
+                    indexes = indexesArray;\r
+                    return;\r
+                }\r
+            }\r
+\r
+            // just use a simple zero-based system\r
+            stopOnIndexNotFound = true;\r
+            indexes = GetZeroBasedIndexes();\r
+        }\r
+\r
+        protected virtual PropertyDescriptorCollection GetModelProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) {\r
+            return GetTypeDescriptor(controllerContext, bindingContext).GetProperties();\r
+        }\r
+\r
+        protected virtual object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) {\r
+            object value = propertyBinder.BindModel(controllerContext, bindingContext);\r
+\r
+            if (bindingContext.ModelMetadata.ConvertEmptyStringToNull && Object.Equals(value, String.Empty)) {\r
+                return null;\r
+            }\r
+\r
+            return value;\r
+        }\r
+\r
+        protected virtual ICustomTypeDescriptor GetTypeDescriptor(ControllerContext controllerContext, ModelBindingContext bindingContext) {\r
+            return TypeDescriptorHelper.Get(bindingContext.ModelType);\r
+        }\r
+\r
+        // If the user specified a ResourceClassKey try to load the resource they specified.\r
+        // If the class key is invalid, an exception will be thrown.\r
+        // If the class key is valid but the resource is not found, it returns null, in which\r
+        // case it will fall back to the MVC default error message.\r
+        private static string GetUserResourceString(ControllerContext controllerContext, string resourceName) {\r
+            string result = null;\r
+\r
+            if (!String.IsNullOrEmpty(ResourceClassKey) && (controllerContext != null) && (controllerContext.HttpContext != null)) {\r
+                result = controllerContext.HttpContext.GetGlobalResourceObject(ResourceClassKey, resourceName, CultureInfo.CurrentUICulture) as string;\r
+            }\r
+\r
+            return result;\r
+        }\r
+\r
+        private static string GetValueInvalidResource(ControllerContext controllerContext) {\r
+            return GetUserResourceString(controllerContext, "PropertyValueInvalid") ?? MvcResources.DefaultModelBinder_ValueInvalid;\r
+        }\r
+\r
+        private static string GetValueRequiredResource(ControllerContext controllerContext) {\r
+            return GetUserResourceString(controllerContext, "PropertyValueRequired") ?? MvcResources.DefaultModelBinder_ValueRequired;\r
+        }\r
+\r
+        private static IEnumerable<string> GetZeroBasedIndexes() {\r
+            for (int i = 0; ; i++) {\r
+                yield return i.ToString(CultureInfo.InvariantCulture);\r
+            }\r
+        }\r
+\r
+        protected static bool IsModelValid(ModelBindingContext bindingContext) {\r
+            if (bindingContext == null) {\r
+                throw new ArgumentNullException("bindingContext");\r
+            }\r
+            if (String.IsNullOrEmpty(bindingContext.ModelName)) {\r
+                return bindingContext.ModelState.IsValid;\r
+            }\r
+            return bindingContext.ModelState.IsValidField(bindingContext.ModelName);\r
+        }\r
+\r
+        protected virtual void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) {\r
+            Dictionary<string, bool> startedValid = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);\r
+\r
+            foreach (ModelValidationResult validationResult in ModelValidator.GetModelValidator(bindingContext.ModelMetadata, controllerContext).Validate(null)) {\r
+                string subPropertyName = CreateSubPropertyName(bindingContext.ModelName, validationResult.MemberName);\r
+\r
+                if (!startedValid.ContainsKey(subPropertyName)) {\r
+                    startedValid[subPropertyName] = bindingContext.ModelState.IsValidField(subPropertyName);\r
+                }\r
+\r
+                if (startedValid[subPropertyName]) {\r
+                    bindingContext.ModelState.AddModelError(subPropertyName, validationResult.Message);\r
+                }\r
+            }\r
+        }\r
+\r
+        protected virtual bool OnModelUpdating(ControllerContext controllerContext, ModelBindingContext bindingContext) {\r
+            // default implementation does nothing\r
+            return true;\r
+        }\r
+\r
+        protected virtual void OnPropertyValidated(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value) {\r
+            // default implementation does nothing\r
+        }\r
+\r
+        protected virtual bool OnPropertyValidating(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value) {\r
+            // default implementation does nothing\r
+            return true;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",\r
+            Justification = "We're recording this exception so that we can act on it later.")]\r
+        protected virtual void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value) {\r
+\r
+            ModelMetadata propertyMetadata = bindingContext.PropertyMetadata[propertyDescriptor.Name];\r
+            propertyMetadata.Model = value;\r
+            string modelStateKey = CreateSubPropertyName(bindingContext.ModelName, propertyMetadata.PropertyName);\r
+\r
+            // If the value is null, and the validation system can find a Required validator for\r
+            // us, we'd prefer to run it before we attempt to set the value; otherwise, property\r
+            // setters which throw on null (f.e., Entity Framework properties which are backed by\r
+            // non-nullable strings in the DB) will get their error message in ahead of us.\r
+            //\r
+            // We are effectively using the special validator -- Required -- as a helper to the\r
+            // binding system, which is why this code is here instead of in the Validating/Validated\r
+            // methods, which are really the old-school validation hooks.\r
+            if (value == null && bindingContext.ModelState.IsValidField(modelStateKey)) {\r
+                ModelValidator requiredValidator = ModelValidatorProviders.Providers.GetValidators(propertyMetadata, controllerContext).Where(v => v.IsRequired).FirstOrDefault();\r
+                if (requiredValidator != null) {\r
+                    foreach (ModelValidationResult validationResult in requiredValidator.Validate(bindingContext.Model)) {\r
+                        bindingContext.ModelState.AddModelError(modelStateKey, validationResult.Message);\r
+                    }\r
+                }\r
+            }\r
+\r
+            bool isNullValueOnNonNullableType =\r
+                value == null &&\r
+                !TypeHelpers.TypeAllowsNullValue(propertyDescriptor.PropertyType);\r
+\r
+            // Try to set a value into the property unless we know it will fail (read-only\r
+            // properties and null values with non-nullable types)\r
+            if (!propertyDescriptor.IsReadOnly && !isNullValueOnNonNullableType) {\r
+                try {\r
+                    propertyDescriptor.SetValue(bindingContext.Model, value);\r
+                }\r
+                catch (Exception ex) {\r
+                    // Only add if we're not already invalid\r
+                    if (bindingContext.ModelState.IsValidField(modelStateKey)) {\r
+                        bindingContext.ModelState.AddModelError(modelStateKey, ex);\r
+                    }\r
+                }\r
+            }\r
+\r
+            // Last chance for an error on null values with non-nullable types, we'll use\r
+            // the default "A value is required." message.\r
+            if (isNullValueOnNonNullableType && bindingContext.ModelState.IsValidField(modelStateKey)) {\r
+                bindingContext.ModelState.AddModelError(modelStateKey, GetValueRequiredResource(controllerContext));\r
+            }\r
+        }\r
+\r
+        private static bool ShouldUpdateProperty(PropertyDescriptor property, Predicate<string> propertyFilter) {\r
+            if (property.IsReadOnly && !CanUpdateReadonlyTypedReference(property.PropertyType)) {\r
+                return false;\r
+            }\r
+\r
+            // if this property is rejected by the filter, move on\r
+            if (!propertyFilter(property.Name)) {\r
+                return false;\r
+            }\r
+\r
+            // otherwise, allow\r
+            return true;\r
+        }\r
+\r
+        internal object UpdateCollection(ControllerContext controllerContext, ModelBindingContext bindingContext, Type elementType) {\r
+            bool stopOnIndexNotFound;\r
+            IEnumerable<string> indexes;\r
+            GetIndexes(bindingContext, out stopOnIndexNotFound, out indexes);\r
+            IModelBinder elementBinder = Binders.GetBinder(elementType);\r
+\r
+            // build up a list of items from the request\r
+            List<object> modelList = new List<object>();\r
+            foreach (string currentIndex in indexes) {\r
+                string subIndexKey = CreateSubIndexName(bindingContext.ModelName, currentIndex);\r
+                if (!bindingContext.ValueProvider.ContainsPrefix(subIndexKey)) {\r
+                    if (stopOnIndexNotFound) {\r
+                        // we ran out of elements to pull\r
+                        break;\r
+                    }\r
+                    else {\r
+                        continue;\r
+                    }\r
+                }\r
+\r
+                ModelBindingContext innerContext = new ModelBindingContext() {\r
+                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, elementType),\r
+                    ModelName = subIndexKey,\r
+                    ModelState = bindingContext.ModelState,\r
+                    PropertyFilter = bindingContext.PropertyFilter,\r
+                    ValueProvider = bindingContext.ValueProvider\r
+                };\r
+                object thisElement = elementBinder.BindModel(controllerContext, innerContext);\r
+\r
+                // we need to merge model errors up\r
+                AddValueRequiredMessageToModelState(controllerContext, bindingContext.ModelState, subIndexKey, elementType, thisElement);\r
+                modelList.Add(thisElement);\r
+            }\r
+\r
+            // if there weren't any elements at all in the request, just return\r
+            if (modelList.Count == 0) {\r
+                return null;\r
+            }\r
+\r
+            // replace the original collection\r
+            object collection = bindingContext.Model;\r
+            CollectionHelpers.ReplaceCollection(elementType, collection, modelList);\r
+            return collection;\r
+        }\r
+\r
+        internal object UpdateDictionary(ControllerContext controllerContext, ModelBindingContext bindingContext, Type keyType, Type valueType) {\r
+            bool stopOnIndexNotFound;\r
+            IEnumerable<string> indexes;\r
+            GetIndexes(bindingContext, out stopOnIndexNotFound, out indexes);\r
+\r
+            IModelBinder keyBinder = Binders.GetBinder(keyType);\r
+            IModelBinder valueBinder = Binders.GetBinder(valueType);\r
+\r
+            // build up a list of items from the request\r
+            List<KeyValuePair<object, object>> modelList = new List<KeyValuePair<object, object>>();\r
+            foreach (string currentIndex in indexes) {\r
+                string subIndexKey = CreateSubIndexName(bindingContext.ModelName, currentIndex);\r
+                string keyFieldKey = CreateSubPropertyName(subIndexKey, "key");\r
+                string valueFieldKey = CreateSubPropertyName(subIndexKey, "value");\r
+\r
+                if (!(bindingContext.ValueProvider.ContainsPrefix(keyFieldKey) && bindingContext.ValueProvider.ContainsPrefix(valueFieldKey))) {\r
+                    if (stopOnIndexNotFound) {\r
+                        // we ran out of elements to pull\r
+                        break;\r
+                    }\r
+                    else {\r
+                        continue;\r
+                    }\r
+                }\r
+\r
+                // bind the key\r
+                ModelBindingContext keyBindingContext = new ModelBindingContext() {\r
+                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, keyType),\r
+                    ModelName = keyFieldKey,\r
+                    ModelState = bindingContext.ModelState,\r
+                    ValueProvider = bindingContext.ValueProvider\r
+                };\r
+                object thisKey = keyBinder.BindModel(controllerContext, keyBindingContext);\r
+\r
+                // we need to merge model errors up\r
+                AddValueRequiredMessageToModelState(controllerContext, bindingContext.ModelState, keyFieldKey, keyType, thisKey);\r
+                if (!keyType.IsInstanceOfType(thisKey)) {\r
+                    // we can't add an invalid key, so just move on\r
+                    continue;\r
+                }\r
+\r
+                // bind the value\r
+                ModelBindingContext valueBindingContext = new ModelBindingContext() {\r
+                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, valueType),\r
+                    ModelName = valueFieldKey,\r
+                    ModelState = bindingContext.ModelState,\r
+                    PropertyFilter = bindingContext.PropertyFilter,\r
+                    ValueProvider = bindingContext.ValueProvider\r
+                };\r
+                object thisValue = valueBinder.BindModel(controllerContext, valueBindingContext);\r
+\r
+                // we need to merge model errors up\r
+                AddValueRequiredMessageToModelState(controllerContext, bindingContext.ModelState, valueFieldKey, valueType, thisValue);\r
+                KeyValuePair<object, object> kvp = new KeyValuePair<object, object>(thisKey, thisValue);\r
+                modelList.Add(kvp);\r
+            }\r
+\r
+            // if there weren't any elements at all in the request, just return\r
+            if (modelList.Count == 0) {\r
+                return null;\r
+            }\r
+\r
+            // replace the original collection\r
+            object dictionary = bindingContext.Model;\r
+            CollectionHelpers.ReplaceDictionary(keyType, valueType, dictionary, modelList);\r
+            return dictionary;\r
+        }\r
+\r
+        // This helper type is used because we're working with strongly-typed collections, but we don't know the Ts\r
+        // ahead of time. By using the generic methods below, we can consolidate the collection-specific code in a\r
+        // single helper type rather than having reflection-based calls spread throughout the DefaultModelBinder type.\r
+        // There is a single point of entry to each of the methods below, so they're fairly simple to maintain.\r
+\r
+        private static class CollectionHelpers {\r
+\r
+            private static readonly MethodInfo _replaceCollectionMethod = typeof(CollectionHelpers).GetMethod("ReplaceCollectionImpl", BindingFlags.Static | BindingFlags.NonPublic);\r
+            private static readonly MethodInfo _replaceDictionaryMethod = typeof(CollectionHelpers).GetMethod("ReplaceDictionaryImpl", BindingFlags.Static | BindingFlags.NonPublic);\r
+\r
+            [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]\r
+            public static void ReplaceCollection(Type collectionType, object collection, object newContents) {\r
+                MethodInfo targetMethod = _replaceCollectionMethod.MakeGenericMethod(collectionType);\r
+                targetMethod.Invoke(null, new object[] { collection, newContents });\r
+            }\r
+\r
+            private static void ReplaceCollectionImpl<T>(ICollection<T> collection, IEnumerable newContents) {\r
+                collection.Clear();\r
+                if (newContents != null) {\r
+                    foreach (object item in newContents) {\r
+                        // if the item was not a T, some conversion failed. the error message will be propagated,\r
+                        // but in the meanwhile we need to make a placeholder element in the array.\r
+                        T castItem = (item is T) ? (T)item : default(T);\r
+                        collection.Add(castItem);\r
+                    }\r
+                }\r
+            }\r
+\r
+            [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]\r
+            public static void ReplaceDictionary(Type keyType, Type valueType, object dictionary, object newContents) {\r
+                MethodInfo targetMethod = _replaceDictionaryMethod.MakeGenericMethod(keyType, valueType);\r
+                targetMethod.Invoke(null, new object[] { dictionary, newContents });\r
+            }\r
+\r
+            private static void ReplaceDictionaryImpl<TKey, TValue>(IDictionary<TKey, TValue> dictionary, IEnumerable<KeyValuePair<object, object>> newContents) {\r
+                dictionary.Clear();\r
+                foreach (KeyValuePair<object, object> item in newContents) {\r
+                    // if the item was not a T, some conversion failed. the error message will be propagated,\r
+                    // but in the meanwhile we need to make a placeholder element in the dictionary.\r
+                    TKey castKey = (TKey)item.Key; // this cast shouldn't fail\r
+                    TValue castValue = (item.Value is TValue) ? (TValue)item.Value : default(TValue);\r
+                    dictionary[castKey] = castValue;\r
+                }\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/DefaultViewLocationCache.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/DefaultViewLocationCache.cs
new file mode 100644 (file)
index 0000000..f0479f4
--- /dev/null
@@ -0,0 +1,60 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Web.Caching;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    [SuppressMessage("Microsoft.Security", "CA2112:SecuredTypesShouldNotExposeFields",\r
+        Justification = "The Null field does not have access to secure information")]\r
+    public class DefaultViewLocationCache : IViewLocationCache {\r
+        private static readonly TimeSpan _defaultTimeSpan = new TimeSpan(0, 15, 0);\r
+\r
+        public DefaultViewLocationCache()\r
+            : this(_defaultTimeSpan) {\r
+        }\r
+\r
+        public DefaultViewLocationCache(TimeSpan timeSpan) {\r
+            if (timeSpan.Ticks < 0) {\r
+                throw new InvalidOperationException(MvcResources.DefaultViewLocationCache_NegativeTimeSpan);\r
+            }\r
+            TimeSpan = timeSpan;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes",\r
+            Justification = "The reference type is immutable. ")]\r
+        public static readonly IViewLocationCache Null = new NullViewLocationCache();\r
+\r
+        public TimeSpan TimeSpan {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        #region IViewLocationCache Members\r
+        public string GetViewLocation(HttpContextBase httpContext, string key) {\r
+            if (httpContext == null) {\r
+                throw new ArgumentNullException("httpContext");\r
+            }\r
+            return (string)httpContext.Cache[key];\r
+        }\r
+\r
+        public void InsertViewLocation(HttpContextBase httpContext, string key, string virtualPath) {\r
+            if (httpContext == null) {\r
+                throw new ArgumentNullException("httpContext");\r
+            }\r
+            httpContext.Cache.Insert(key, virtualPath, null /* dependencies */, Cache.NoAbsoluteExpiration, TimeSpan);\r
+        }\r
+        #endregion\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/DescriptorUtil.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/DescriptorUtil.cs
new file mode 100644 (file)
index 0000000..a19c90f
--- /dev/null
@@ -0,0 +1,34 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Linq;\r
+    using System.Threading;\r
+\r
+    internal static class DescriptorUtil {\r
+\r
+        public static TDescriptor[] LazilyFetchOrCreateDescriptors<TReflection, TDescriptor>(ref TDescriptor[] cacheLocation, Func<TReflection[]> initializer, Func<TReflection, TDescriptor> converter) {\r
+            // did we already calculate this once?\r
+            TDescriptor[] existingCache = Interlocked.CompareExchange(ref cacheLocation, null, null);\r
+            if (existingCache != null) {\r
+                return existingCache;\r
+            }\r
+\r
+            TReflection[] memberInfos = initializer();\r
+            TDescriptor[] descriptors = memberInfos.Select(converter).Where(descriptor => descriptor != null).ToArray();\r
+            TDescriptor[] updatedCache = Interlocked.CompareExchange(ref cacheLocation, descriptors, null);\r
+            return updatedCache ?? descriptors;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/DictionaryHelpers.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/DictionaryHelpers.cs
new file mode 100644 (file)
index 0000000..7eb761f
--- /dev/null
@@ -0,0 +1,52 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Linq;\r
+\r
+    internal static class DictionaryHelpers {\r
+\r
+        public static IEnumerable<KeyValuePair<string, TValue>> FindKeysWithPrefix<TValue>(IDictionary<string, TValue> dictionary, string prefix) {\r
+            TValue exactMatchValue;\r
+            if (dictionary.TryGetValue(prefix, out exactMatchValue)) {\r
+                yield return new KeyValuePair<string, TValue>(prefix, exactMatchValue);\r
+            }\r
+\r
+            foreach (var entry in dictionary) {\r
+                string key = entry.Key;\r
+\r
+                if (key.Length <= prefix.Length) {\r
+                    continue;\r
+                }\r
+\r
+                if (!key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) {\r
+                    continue;\r
+                }\r
+\r
+                char charAfterPrefix = key[prefix.Length];\r
+                switch (charAfterPrefix) {\r
+                    case '[':\r
+                    case '.':\r
+                        yield return entry;\r
+                        break;\r
+                }\r
+            }\r
+        }\r
+\r
+        public static bool DoesAnyKeyHavePrefix<TValue>(IDictionary<string, TValue> dictionary, string prefix) {\r
+            return FindKeysWithPrefix(dictionary, prefix).Any();\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/DictionaryValueProvider`1.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/DictionaryValueProvider`1.cs
new file mode 100644 (file)
index 0000000..b1e8845
--- /dev/null
@@ -0,0 +1,64 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Globalization;\r
+\r
+    public class DictionaryValueProvider<TValue> : IValueProvider {\r
+\r
+        private readonly HashSet<string> _prefixes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\r
+        private readonly Dictionary<string, ValueProviderResult> _values = new Dictionary<string, ValueProviderResult>(StringComparer.OrdinalIgnoreCase);\r
+\r
+        public DictionaryValueProvider(IDictionary<string, TValue> dictionary, CultureInfo culture) {\r
+            if (dictionary == null) {\r
+                throw new ArgumentNullException("dictionary");\r
+            }\r
+\r
+            AddValues(dictionary, culture);\r
+        }\r
+\r
+        private void AddValues(IDictionary<string, TValue> dictionary, CultureInfo culture) {\r
+            if (dictionary.Count > 0) {\r
+                _prefixes.Add("");\r
+            }\r
+\r
+            foreach (var entry in dictionary) {\r
+                _prefixes.UnionWith(ValueProviderUtil.GetPrefixes(entry.Key));\r
+\r
+                object rawValue = entry.Value;\r
+                string attemptedValue = Convert.ToString(rawValue, culture);\r
+                _values[entry.Key] = new ValueProviderResult(rawValue, attemptedValue, culture);\r
+            }\r
+        }\r
+\r
+        public virtual bool ContainsPrefix(string prefix) {\r
+            if (prefix == null) {\r
+                throw new ArgumentNullException("prefix");\r
+            }\r
+\r
+            return _prefixes.Contains(prefix);\r
+        }\r
+\r
+        public virtual ValueProviderResult GetValue(string key) {\r
+            if (key == null) {\r
+                throw new ArgumentNullException("key");\r
+            }\r
+\r
+            ValueProviderResult vpResult;\r
+            _values.TryGetValue(key, out vpResult);\r
+            return vpResult;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/DynamicTypeGenerator.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/DynamicTypeGenerator.cs
new file mode 100644 (file)
index 0000000..eefc9f8
--- /dev/null
@@ -0,0 +1,125 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Linq;\r
+    using System.Reflection;\r
+    using System.Reflection.Emit;\r
+    using System.Security;\r
+\r
+    internal static class DynamicTypeGenerator {\r
+\r
+        private static readonly ModuleBuilder _dynamicModule = CreateDynamicModule();\r
+\r
+        private static ModuleBuilder CreateDynamicModule() {\r
+            // DDB 226615 - since MVC is [SecurityTransparent], the dynamic assembly must declare itself likewise\r
+            CustomAttributeBuilder builder = new CustomAttributeBuilder(\r
+                typeof(SecurityTransparentAttribute).GetConstructor(Type.EmptyTypes), new object[0]);\r
+            CustomAttributeBuilder[] assemblyAttributes = new CustomAttributeBuilder[] { builder };\r
+            AssemblyBuilder dynamicAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(\r
+                new AssemblyName("System.Web.Mvc.{Dynamic}"), AssemblyBuilderAccess.Run, assemblyAttributes);\r
+            ModuleBuilder dynamicModule = dynamicAssembly.DefineDynamicModule("System.Web.Mvc.{Dynamic}.dll");\r
+            return dynamicModule;\r
+        }\r
+\r
+        // Creates a new dynamic type that is a subclassed type of baseType and also implements methods of the specified\r
+        // interfaces. The base type must already have method signatures that implicitly implement the given\r
+        // interfaces. The signatures of all public (e.g. not private / internal) constructors from the baseType\r
+        // will be duplicated for the subclassed type and the new constructors made public.\r
+        public static Type GenerateType(string dynamicTypeName, Type baseType, IEnumerable<Type> interfaceTypes) {\r
+            TypeBuilder newType = _dynamicModule.DefineType(\r
+                "System.Web.Mvc.{Dynamic}." + dynamicTypeName,\r
+                TypeAttributes.AutoLayout | TypeAttributes.Public | TypeAttributes.Class,\r
+                baseType);\r
+\r
+            foreach (Type interfaceType in interfaceTypes) {\r
+                newType.AddInterfaceImplementation(interfaceType);\r
+                foreach (MethodInfo interfaceMethod in interfaceType.GetMethods()) {\r
+                    ImplementInterfaceMethod(newType, interfaceMethod);\r
+                }\r
+            }\r
+\r
+            // generate new constructors for each accessible base constructor\r
+            foreach (ConstructorInfo ctor in baseType.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) {\r
+                switch (ctor.Attributes & MethodAttributes.MemberAccessMask) {\r
+                    case MethodAttributes.Family:\r
+                    case MethodAttributes.Public:\r
+                    case MethodAttributes.FamORAssem:\r
+                        ImplementConstructor(newType, ctor);\r
+                        break;\r
+                }\r
+            }\r
+\r
+            Type bakedType = newType.CreateType();\r
+            return bakedType;\r
+        }\r
+\r
+        // generates this constructor:\r
+        // public NewType(param0, param1, ...) : base(param0, param1, ...) { }\r
+        private static void ImplementConstructor(TypeBuilder newType, ConstructorInfo baseCtor) {\r
+            ParameterInfo[] parameters = baseCtor.GetParameters();\r
+            Type[] parameterTypes = (from p in parameters select p.ParameterType).ToArray();\r
+\r
+            ConstructorBuilder newCtor = newType.DefineConstructor(\r
+                (baseCtor.Attributes & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Public /* force public constructor */,\r
+                baseCtor.CallingConvention, parameterTypes);\r
+\r
+            // parameter 0 is 'this', so we start at index 1\r
+            for (int i = 0; i < parameters.Length; i++) {\r
+                newCtor.DefineParameter(i + 1, parameters[i].Attributes, parameters[i].Name);\r
+            }\r
+\r
+            // load all arguments (including 'this') in proper order, then call and return\r
+            ILGenerator ilGen = newCtor.GetILGenerator();\r
+            for (int i = 0; i <= parameterTypes.Length; i++) {\r
+                ilGen.Emit(OpCodes.Ldarg_S, (byte)i);\r
+            }\r
+            ilGen.Emit(OpCodes.Call, baseCtor);\r
+            ilGen.Emit(OpCodes.Ret);\r
+        }\r
+\r
+        // generates this explicit interface method:\r
+        // public new Interface.Method(param0, param1, ...) {\r
+        //   return base.Method(param0, param1, ...);\r
+        // }\r
+        private static void ImplementInterfaceMethod(TypeBuilder newType, MethodInfo interfaceMethod) {\r
+            ParameterInfo[] parameters = interfaceMethod.GetParameters();\r
+            Type[] parameterTypes = (from p in parameters select p.ParameterType).ToArray();\r
+\r
+            // based on http://msdn.microsoft.com/en-us/library/system.reflection.emit.typebuilder.definemethodoverride.aspx\r
+            MethodBuilder newMethod = newType.DefineMethod(interfaceMethod.DeclaringType.Name + "." + interfaceMethod.Name,\r
+                MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final,\r
+                interfaceMethod.ReturnType, parameterTypes);\r
+\r
+            MethodInfo baseMethod = newType.BaseType.GetMethod(interfaceMethod.Name, parameterTypes);\r
+\r
+            // parameter 0 is 'this', so we start at index 1\r
+            for (int i = 0; i < parameters.Length; i++) {\r
+                newMethod.DefineParameter(i + 1, parameters[i].Attributes, parameters[i].Name);\r
+            }\r
+\r
+            // load all arguments (including 'this') in proper order, then call and return\r
+            ILGenerator ilGen = newMethod.GetILGenerator();\r
+            for (int i = 0; i <= parameterTypes.Length; i++) {\r
+                ilGen.Emit(OpCodes.Ldarg_S, (byte)i);\r
+            }\r
+            ilGen.Emit(OpCodes.Call, baseMethod);\r
+            ilGen.Emit(OpCodes.Ret);\r
+\r
+            // finally, hook the new method up to the interface mapping\r
+            newType.DefineMethodOverride(newMethod, interfaceMethod);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/EmptyModelMetadataProvider.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/EmptyModelMetadataProvider.cs
new file mode 100644 (file)
index 0000000..984924b
--- /dev/null
@@ -0,0 +1,23 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Reflection;\r
+\r
+    public class EmptyModelMetadataProvider : AssociatedMetadataProvider {\r
+        protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName) {\r
+            return new ModelMetadata(this, containerType, modelAccessor, modelType, propertyName);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/EmptyModelValidatorProvider.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/EmptyModelValidatorProvider.cs
new file mode 100644 (file)
index 0000000..63fb1a2
--- /dev/null
@@ -0,0 +1,22 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Collections.Generic;\r
+    using System.Linq;\r
+\r
+    public class EmptyModelValidatorProvider : ModelValidatorProvider {\r
+        public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context) {\r
+            return Enumerable.Empty<ModelValidator>();\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/EmptyResult.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/EmptyResult.cs
new file mode 100644 (file)
index 0000000..3fef8ee
--- /dev/null
@@ -0,0 +1,29 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+\r
+    // represents a result that doesn't do anything, like a controller action returning null\r
+    public class EmptyResult : ActionResult {\r
+\r
+        private static readonly EmptyResult _singleton = new EmptyResult();\r
+\r
+        internal static EmptyResult Instance {\r
+            get {\r
+                return _singleton;\r
+            }\r
+        }\r
+\r
+        public override void ExecuteResult(ControllerContext context) {\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Error.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Error.cs
new file mode 100644 (file)
index 0000000..26e86f8
--- /dev/null
@@ -0,0 +1,84 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Globalization;\r
+    using System.Web.Mvc.Async;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    internal static class Error {\r
+\r
+        public static InvalidOperationException AsyncActionMethodSelector_CouldNotFindMethod(string methodName, Type controllerType) {\r
+            string message = String.Format(CultureInfo.CurrentUICulture, MvcResources.AsyncActionMethodSelector_CouldNotFindMethod,\r
+                methodName, controllerType);\r
+            return new InvalidOperationException(message);\r
+        }\r
+\r
+        public static InvalidOperationException AsyncCommon_AsyncResultAlreadyConsumed() {\r
+            return new InvalidOperationException(MvcResources.AsyncCommon_AsyncResultAlreadyConsumed);\r
+        }\r
+\r
+        public static InvalidOperationException AsyncCommon_ControllerMustImplementIAsyncManagerContainer(Type actualControllerType) {\r
+            string message = String.Format(CultureInfo.CurrentUICulture, MvcResources.AsyncCommon_ControllerMustImplementIAsyncManagerContainer,\r
+                actualControllerType);\r
+            return new InvalidOperationException(message);\r
+        }\r
+\r
+        public static ArgumentException AsyncCommon_InvalidAsyncResult(string parameterName) {\r
+            return new ArgumentException(MvcResources.AsyncCommon_InvalidAsyncResult, parameterName);\r
+        }\r
+\r
+        public static ArgumentOutOfRangeException AsyncCommon_InvalidTimeout(string parameterName) {\r
+            return new ArgumentOutOfRangeException(parameterName, MvcResources.AsyncCommon_InvalidTimeout);\r
+        }\r
+\r
+        public static InvalidOperationException ReflectedAsyncActionDescriptor_CannotExecuteSynchronously(string actionName) {\r
+            string message = String.Format(CultureInfo.CurrentUICulture, MvcResources.ReflectedAsyncActionDescriptor_CannotExecuteSynchronously,\r
+                actionName);\r
+            return new InvalidOperationException(message);\r
+        }\r
+\r
+        public static InvalidOperationException ChildActionOnlyAttribute_MustBeInChildRequest(ActionDescriptor actionDescriptor) {\r
+            string message = String.Format(CultureInfo.CurrentUICulture, MvcResources.ChildActionOnlyAttribute_MustBeInChildRequest,\r
+                actionDescriptor.ActionName);\r
+            return new InvalidOperationException(message);\r
+        }\r
+\r
+        public static ArgumentException ParameterCannotBeNullOrEmpty(string parameterName) {\r
+            return new ArgumentException(MvcResources.Common_NullOrEmpty, parameterName);\r
+        }\r
+\r
+        public static InvalidOperationException PropertyCannotBeNullOrEmpty(string propertyName) {\r
+            string message = String.Format(CultureInfo.CurrentUICulture, MvcResources.Common_PropertyCannotBeNullOrEmpty,\r
+                propertyName);\r
+            return new InvalidOperationException(message);\r
+        }\r
+\r
+        public static SynchronousOperationException SynchronizationContextUtil_ExceptionThrown(Exception innerException) {\r
+            return new SynchronousOperationException(MvcResources.SynchronizationContextUtil_ExceptionThrown, innerException);\r
+        }\r
+\r
+        public static InvalidOperationException ViewDataDictionary_WrongTModelType(Type valueType, Type modelType) {\r
+            string message = String.Format(CultureInfo.CurrentUICulture, MvcResources.ViewDataDictionary_WrongTModelType,\r
+                valueType, modelType);\r
+            return new InvalidOperationException(message);\r
+        }\r
+\r
+        public static InvalidOperationException ViewDataDictionary_ModelCannotBeNull(Type modelType) {\r
+            string message = String.Format(CultureInfo.CurrentUICulture, MvcResources.ViewDataDictionary_ModelCannotBeNull,\r
+                modelType);\r
+            return new InvalidOperationException(message);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExceptionContext.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExceptionContext.cs
new file mode 100644 (file)
index 0000000..937dd23
--- /dev/null
@@ -0,0 +1,56 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+\r
+    public class ExceptionContext : ControllerContext {\r
+\r
+        private ActionResult _result;\r
+\r
+        // parameterless constructor used for mocking\r
+        public ExceptionContext() {\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors",\r
+            Justification = "The virtual property setters are only to support mocking frameworks, in which case this constructor shouldn't be called anyway.")]\r
+        public ExceptionContext(ControllerContext controllerContext, Exception exception)\r
+            : base(controllerContext) {\r
+            if (exception == null) {\r
+                throw new ArgumentNullException("exception");\r
+            }\r
+\r
+            Exception = exception;\r
+        }\r
+\r
+        public virtual Exception Exception {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public bool ExceptionHandled {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public ActionResult Result {\r
+            get {\r
+                return _result ?? EmptyResult.Instance;\r
+            }\r
+            set {\r
+                _result = value;\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionHelper.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionHelper.cs
new file mode 100644 (file)
index 0000000..e72d94d
--- /dev/null
@@ -0,0 +1,123 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+    using System.Linq.Expressions;\r
+    using System.Reflection;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public static class ExpressionHelper {\r
+        public static string GetExpressionText(string expression) {\r
+            return\r
+                String.Equals(expression, "model", StringComparison.OrdinalIgnoreCase)\r
+                    ? String.Empty    // If it's exactly "model", then give them an empty string, to replicate the lambda behavior\r
+                    : expression;\r
+        }\r
+\r
+        public static string GetExpressionText(LambdaExpression expression) {\r
+            // Crack the expression string for property/field accessors to create its name\r
+            Stack<string> nameParts = new Stack<string>();\r
+            Expression part = expression.Body;\r
+\r
+            while (part != null) {\r
+                if (part.NodeType == ExpressionType.Call) {\r
+                    MethodCallExpression methodExpression = (MethodCallExpression)part;\r
+\r
+                    if (!IsSingleArgumentIndexer(methodExpression)) {\r
+                        break;\r
+                    }\r
+\r
+                    nameParts.Push(\r
+                        GetIndexerInvocation(\r
+                            methodExpression.Arguments.Single(),\r
+                            expression.Parameters.ToArray()\r
+                        )\r
+                    );\r
+\r
+                    part = methodExpression.Object;\r
+                }\r
+                else if (part.NodeType == ExpressionType.ArrayIndex) {\r
+                    BinaryExpression binaryExpression = (BinaryExpression)part;\r
+\r
+                    nameParts.Push(\r
+                        GetIndexerInvocation(\r
+                            binaryExpression.Right,\r
+                            expression.Parameters.ToArray()\r
+                        )\r
+                    );\r
+\r
+                    part = binaryExpression.Left;\r
+                }\r
+                else if (part.NodeType == ExpressionType.MemberAccess) {\r
+                    MemberExpression memberExpressionPart = (MemberExpression)part;\r
+                    nameParts.Push("." + memberExpressionPart.Member.Name);\r
+                    part = memberExpressionPart.Expression;\r
+                }\r
+                else {\r
+                    break;\r
+                }\r
+            }\r
+\r
+            // If it starts with "model", then strip that away\r
+            if (nameParts.Count > 0 && String.Equals(nameParts.Peek(), ".model", StringComparison.OrdinalIgnoreCase)) {\r
+                nameParts.Pop();\r
+            }\r
+\r
+            if (nameParts.Count > 0) {\r
+                return nameParts.Aggregate((left, right) => left + right).TrimStart('.');\r
+            }\r
+\r
+            return String.Empty;\r
+        }\r
+\r
+        private static string GetIndexerInvocation(Expression expression, ParameterExpression[] parameters) {\r
+            Expression converted = Expression.Convert(expression, typeof(object));\r
+            ParameterExpression fakeParameter = Expression.Parameter(typeof(object), null);\r
+            Expression<Func<object, object>> lambda = Expression.Lambda<Func<object, object>>(converted, fakeParameter);\r
+            Func<object, object> func;\r
+\r
+            try {\r
+                func = ExpressionUtil.CachedExpressionCompiler.Process(lambda);\r
+            }\r
+            catch (InvalidOperationException ex) {\r
+                throw new InvalidOperationException(\r
+                    String.Format(\r
+                        CultureInfo.CurrentUICulture,\r
+                        MvcResources.ExpressionHelper_InvalidIndexerExpression,\r
+                        expression,\r
+                        parameters[0].Name\r
+                    ),\r
+                    ex\r
+                );\r
+            }\r
+\r
+            return "[" + Convert.ToString(func(null), CultureInfo.InvariantCulture) + "]";\r
+        }\r
+\r
+        internal static bool IsSingleArgumentIndexer(Expression expression) {\r
+            MethodCallExpression methodExpression = expression as MethodCallExpression;\r
+            if (methodExpression == null || methodExpression.Arguments.Count != 1) {\r
+                return false;\r
+            }\r
+\r
+            return methodExpression.Method\r
+                                   .DeclaringType\r
+                                   .GetDefaultMembers()\r
+                                   .OfType<PropertyInfo>()\r
+                                   .Any(p => p.GetGetMethod() == methodExpression.Method);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/BinaryExpressionFingerprint.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/BinaryExpressionFingerprint.cs
new file mode 100644 (file)
index 0000000..90e1fd4
--- /dev/null
@@ -0,0 +1,111 @@
+#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\r
+\r
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.ExpressionUtil {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Linq.Expressions;\r
+    using System.Reflection;\r
+\r
+    // BinaryExpression fingerprint class\r
+    // Useful for things like array[index]\r
+    //\r
+    // This particular fingerprint doesn't support the BinaryExpression.Conversion property,\r
+    // which is used in some coalescing operations.\r
+    [SuppressMessage("Microsoft.Usage", "CA2218:OverrideGetHashCodeOnOverridingEquals",\r
+        Justification = "Overrides AddToHashCodeCombiner() instead.")]\r
+    internal sealed class BinaryExpressionFingerprint : ExpressionFingerprint {\r
+\r
+        private BinaryExpressionFingerprint(BinaryExpression expression)\r
+            : base(expression) {\r
+            // don't care about UnaryExpression.IsLifted since it's not necessary to uniquely describe the expression,\r
+            // but IsLiftedToNull *is* required\r
+\r
+            IsLiftedToNull = expression.IsLiftedToNull;\r
+            Method = expression.Method;\r
+        }\r
+\r
+        public bool IsLiftedToNull {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public ExpressionFingerprint Left {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public MethodInfo Method {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public ExpressionFingerprint Right {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        internal override void AddToHashCodeCombiner(HashCodeCombiner combiner) {\r
+            base.AddToHashCodeCombiner(combiner);\r
+\r
+            combiner.AddInt32(IsLiftedToNull.GetHashCode());\r
+            combiner.AddFingerprint(Left);\r
+            combiner.AddObject(Method);\r
+            combiner.AddFingerprint(Right);\r
+        }\r
+\r
+        public static BinaryExpressionFingerprint Create(BinaryExpression expression, ParserContext parserContext) {\r
+            if (expression.Conversion != null) {\r
+                // we don't support the Conversion property\r
+                return null;\r
+            }\r
+\r
+            // if any fingerprinting fails, bail out\r
+            ExpressionFingerprint left = Create(expression.Left, parserContext);\r
+            if (left == null && expression.Left != null) {\r
+                return null;\r
+            }\r
+\r
+            ExpressionFingerprint right = Create(expression.Right, parserContext);\r
+            if (right == null && expression.Right != null) {\r
+                return null;\r
+            }\r
+\r
+            return new BinaryExpressionFingerprint(expression) {\r
+                Left = left,\r
+                Right = right\r
+            };\r
+        }\r
+\r
+        public override bool Equals(object obj) {\r
+            BinaryExpressionFingerprint other = obj as BinaryExpressionFingerprint;\r
+            if (other == null) {\r
+                return false;\r
+            }\r
+\r
+            return (this.IsLiftedToNull == other.IsLiftedToNull\r
+                && Object.Equals(this.Left, other.Left)\r
+                && this.Method == other.Method\r
+                && Object.Equals(this.Right, other.Right)\r
+                && base.Equals(other));\r
+        }\r
+\r
+        public override Expression ToExpression(ParserContext parserContext) {\r
+            Expression leftExpr = ToExpression(Left, parserContext);\r
+            Expression rightExpr = ToExpression(Right, parserContext);\r
+            return Expression.MakeBinary(NodeType, leftExpr, rightExpr, IsLiftedToNull, Method);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/CachedExpressionCompiler.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/CachedExpressionCompiler.cs
new file mode 100644 (file)
index 0000000..29078b6
--- /dev/null
@@ -0,0 +1,86 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.ExpressionUtil {\r
+    using System;\r
+    using System.Linq.Expressions;\r
+\r
+    internal static class CachedExpressionCompiler {\r
+\r
+        // This is the entry point to the cached expression tree compiler. The processor will perform a series of checks\r
+        // and optimizations in order to return a fully-compiled func as quickly as possible to the caller. If the\r
+        // input expression is particularly obscure, the system will fall back to a slow but correct compilation step.\r
+        public static Func<TModel, TValue> Process<TModel, TValue>(Expression<Func<TModel, TValue>> lambdaExpression) {\r
+            return Processor<TModel, TValue>.GetFunc(lambdaExpression);\r
+        }\r
+\r
+        private static class Processor<TModel, TValue> {\r
+\r
+            private static readonly Cache _cache = new Cache();\r
+\r
+            public static Func<TModel, TValue> GetFunc(Expression<Func<TModel, TValue>> lambdaExpression) {\r
+                // look for common patterns that don't need to be fingerprinted\r
+                Func<TModel, TValue> func = GetFuncFastTrack(lambdaExpression);\r
+                if (func != null) {\r
+                    return func;\r
+                }\r
+\r
+                // not a common pattern, so try fingerprinting (slower, but cached)\r
+                func = GetFuncFingerprinted(lambdaExpression);\r
+                if (func != null) {\r
+                    return func;\r
+                }\r
+\r
+                // pattern not recognized by fingerprinting routine, so compile directly (slowest)\r
+                return GetFuncSlow(lambdaExpression);\r
+            }\r
+\r
+            private static Func<TModel, TValue> GetFuncFastTrack(Expression<Func<TModel, TValue>> lambdaExpression) {\r
+                ParameterExpression modelParameter = lambdaExpression.Parameters[0];\r
+                Expression body = lambdaExpression.Body;\r
+\r
+                return FastTrack<TModel, TValue>.GetFunc(modelParameter, body);\r
+            }\r
+\r
+            private static Func<TModel, TValue> GetFuncFingerprinted(Expression<Func<TModel, TValue>> lambdaExpression) {\r
+                ParserContext context = ExpressionParser.Parse(lambdaExpression);\r
+                if (context.Fingerprint == null) {\r
+                    // fingerprinting failed\r
+                    return null;\r
+                }\r
+\r
+                object[] hoistedValues = context.HoistedValues.ToArray();\r
+                var del = _cache.GetDelegate(context);\r
+                return model => del(model, hoistedValues);\r
+            }\r
+\r
+            private static Func<TModel, TValue> GetFuncSlow(Expression<Func<TModel, TValue>> lambdaExpression) {\r
+                Func<TModel, TValue> del = lambdaExpression.Compile();\r
+                return del;\r
+            }\r
+\r
+            private sealed class Cache : ReaderWriterCache<ExpressionFingerprint, CompiledExpressionDelegate<TModel, TValue>> {\r
+                private static CompiledExpressionDelegate<TModel, TValue> CreateDelegate(ParserContext context) {\r
+                    var bodyExpr = context.Fingerprint.ToExpression(context);\r
+                    var lambdaExpr = Expression.Lambda<CompiledExpressionDelegate<TModel, TValue>>(bodyExpr, context.ModelParameter, ParserContext.HoistedValuesParameter);\r
+                    var del = lambdaExpr.Compile();\r
+                    return del;\r
+                }\r
+                public CompiledExpressionDelegate<TModel, TValue> GetDelegate(ParserContext context) {\r
+                    return FetchOrCreateItem(context.Fingerprint, () => CreateDelegate(context));\r
+                }\r
+            }\r
+\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/CompiledExpressionDelegate`2.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/CompiledExpressionDelegate`2.cs
new file mode 100644 (file)
index 0000000..dc95a90
--- /dev/null
@@ -0,0 +1,18 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.ExpressionUtil {\r
+    using System;\r
+\r
+    internal delegate TValue CompiledExpressionDelegate<TModel, TValue>(TModel model, object[] hoistedValues);\r
+\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/ConditionalExpressionFingerprint.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/ConditionalExpressionFingerprint.cs
new file mode 100644 (file)
index 0000000..80e29f0
--- /dev/null
@@ -0,0 +1,97 @@
+#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\r
+\r
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.ExpressionUtil {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Linq.Expressions;\r
+\r
+    // ConditionalExpression fingerprint class\r
+    // Expression of form (test) ? ifTrue : ifFalse\r
+    [SuppressMessage("Microsoft.Usage", "CA2218:OverrideGetHashCodeOnOverridingEquals",\r
+        Justification = "Overrides AddToHashCodeCombiner() instead.")]\r
+    internal sealed class ConditionalExpressionFingerprint : ExpressionFingerprint {\r
+\r
+        private ConditionalExpressionFingerprint(ConditionalExpression expression)\r
+            : base(expression) {\r
+        }\r
+\r
+        public ExpressionFingerprint Test {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public ExpressionFingerprint IfTrue {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public ExpressionFingerprint IfFalse {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        internal override void AddToHashCodeCombiner(HashCodeCombiner combiner) {\r
+            base.AddToHashCodeCombiner(combiner);\r
+\r
+            combiner.AddFingerprint(Test);\r
+            combiner.AddFingerprint(IfTrue);\r
+            combiner.AddFingerprint(IfFalse);\r
+        }\r
+\r
+        public static ConditionalExpressionFingerprint Create(ConditionalExpression expression, ParserContext parserContext) {\r
+            // if any fingerprinting fails, bail out\r
+            ExpressionFingerprint test = Create(expression.Test, parserContext);\r
+            if (test == null && expression.Test != null) {\r
+                return null;\r
+            }\r
+\r
+            ExpressionFingerprint ifTrue = Create(expression.IfTrue, parserContext);\r
+            if (ifTrue == null && expression.IfTrue != null) {\r
+                return null;\r
+            }\r
+\r
+            ExpressionFingerprint ifFalse = Create(expression.IfFalse, parserContext);\r
+            if (ifFalse == null && expression.IfFalse != null) {\r
+                return null;\r
+            }\r
+\r
+            return new ConditionalExpressionFingerprint(expression) {\r
+                Test = test,\r
+                IfTrue = ifTrue,\r
+                IfFalse = ifFalse\r
+            };\r
+        }\r
+\r
+        public override bool Equals(object obj) {\r
+            ConditionalExpressionFingerprint other = obj as ConditionalExpressionFingerprint;\r
+            if (other == null) {\r
+                return false;\r
+            }\r
+\r
+            return (Object.Equals(this.Test, other.Test)\r
+                && Object.Equals(this.IfTrue, other.IfTrue)\r
+                && Object.Equals(this.IfFalse, other.IfFalse)\r
+                && base.Equals(other));\r
+        }\r
+\r
+        public override Expression ToExpression(ParserContext parserContext) {\r
+            Expression testExpr = ToExpression(Test, parserContext);\r
+            Expression ifTrueExpr = ToExpression(IfTrue, parserContext);\r
+            Expression ifFalseExpr = ToExpression(IfFalse, parserContext);\r
+            return Expression.Condition(testExpr, ifTrueExpr, ifFalseExpr);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/ConstantExpressionFingerprint.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/ConstantExpressionFingerprint.cs
new file mode 100644 (file)
index 0000000..96e08bc
--- /dev/null
@@ -0,0 +1,72 @@
+#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\r
+\r
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.ExpressionUtil {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Linq.Expressions;\r
+\r
+    // ConstantExpression fingerprint class\r
+    //\r
+    // A ConstantExpression might represent a captured local variable, so we can't compile\r
+    // the value directly into the cached function. Instead, a placeholder is generated\r
+    // and the value is hoisted into a local variables array. This placeholder can then\r
+    // be compiled and cached, and the array lookup happens at runtime.\r
+    [SuppressMessage("Microsoft.Usage", "CA2218:OverrideGetHashCodeOnOverridingEquals",\r
+        Justification = "Overrides AddToHashCodeCombiner() instead.")]\r
+    internal sealed class ConstantExpressionFingerprint : ExpressionFingerprint {\r
+\r
+        private ConstantExpressionFingerprint(ConstantExpression expression)\r
+            : base(expression) {\r
+        }\r
+\r
+        public int HoistedLocalsIndex {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        internal override void AddToHashCodeCombiner(HashCodeCombiner combiner) {\r
+            base.AddToHashCodeCombiner(combiner);\r
+\r
+            combiner.AddInt32(HoistedLocalsIndex);\r
+        }\r
+\r
+        public static ConstantExpressionFingerprint Create(ConstantExpression expression, ParserContext parserContext) {\r
+            ConstantExpressionFingerprint fingerprint = new ConstantExpressionFingerprint(expression) {\r
+                HoistedLocalsIndex = parserContext.HoistedValues.Count\r
+            };\r
+\r
+            parserContext.HoistedValues.Add(expression.Value);\r
+            return fingerprint;\r
+        }\r
+\r
+        public override bool Equals(object obj) {\r
+            ConstantExpressionFingerprint other = obj as ConstantExpressionFingerprint;\r
+            if (other == null) {\r
+                return false;\r
+            }\r
+\r
+            return (this.HoistedLocalsIndex == other.HoistedLocalsIndex\r
+                && base.Equals(other));\r
+        }\r
+\r
+        public override Expression ToExpression(ParserContext parserContext) {\r
+            // (Type) HoistedValues[HoistedLocalsIndex]\r
+            BinaryExpression arrayIndex = Expression.ArrayIndex(ParserContext.HoistedValuesParameter, Expression.Constant(HoistedLocalsIndex));\r
+            UnaryExpression castExpr = Expression.Convert(arrayIndex, Type);\r
+            return castExpr;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/ExpressionFingerprint.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/ExpressionFingerprint.cs
new file mode 100644 (file)
index 0000000..c942d9b
--- /dev/null
@@ -0,0 +1,174 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.ExpressionUtil {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Collections.ObjectModel;\r
+    using System.Linq;\r
+    using System.Linq.Expressions;\r
+\r
+    // Expression fingerprint class\r
+    // Contains information used for generalizing, comparing, and recreating Expression instances\r
+    //\r
+    // Since Expression objects are immutable and are recreated for every invocation of an expression\r
+    // helper method, they can't be compared directly. Fingerprinting Expression objects allows\r
+    // information about them to be abstracted away, and the fingerprints can be directly compared.\r
+    // Consider the process of fingerprinting that all values (parameters, constants, etc.) are hoisted\r
+    // and replaced with dummies. What remains can be decomposed into a sequence of operations on specific\r
+    // types and specific inputs.\r
+    //\r
+    // Some sample fingerprints:\r
+    //\r
+    // 2 + 4 -> OP_ADD(CONST:int, CONST:int):int\r
+    // 2 + 8 -> OP_ADD(CONST:int, CONST:int):int\r
+    // 2.0 + 4.0 -> OP_ADD(CONST:double, CONST:double):double\r
+    //\r
+    // 2 + 4 and 2 + 8 have the same fingerprint, but 2.0 + 4.0 has a different fingerprint since its\r
+    // underlying types differ.\r
+    //\r
+    // "Hello " + "world" -> OP_ADD(CONST:string, CONST:string):string\r
+    // "Hello " + {model} -> OP_ADD(CONST:string, PARAM:string):string\r
+    //\r
+    // These string concatenations have different fingerprints since the inputs are provided differently:\r
+    // one is a hoisted local, the other is a parameter.\r
+    //\r
+    // ({model} ?? "sample").Length -> MEMBER_ACCESS(String.Length, OP_COALESCE(PARAM:string, CONST:string):string):int\r
+    // ({model} ?? "other sample").Length -> MEMBER_ACCESS(String.Length, OP_COALESCE(PARAM:string, CONST:string):string):int\r
+    //\r
+    // These expressions have the same fingerprint.\r
+    internal abstract class ExpressionFingerprint {\r
+\r
+        protected ExpressionFingerprint(Expression expression) {\r
+            // since the fingerprints are cached potentially forever, don't keep a reference\r
+            // to the original expression\r
+\r
+            NodeType = expression.NodeType;\r
+            Type = expression.Type;\r
+        }\r
+\r
+        // the type of expression node, e.g. OP_ADD, MEMBER_ACCESS, etc.\r
+        public ExpressionType NodeType {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        // the CLR type resulting from this expression, e.g. int, string, etc.\r
+        public Type Type {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        internal virtual void AddToHashCodeCombiner(HashCodeCombiner combiner) {\r
+            combiner.AddObject(NodeType);\r
+            combiner.AddObject(Type);\r
+        }\r
+\r
+        public static ExpressionFingerprint Create(Expression expression, ParserContext parserContext) {\r
+            {\r
+                BinaryExpression binaryExpression = expression as BinaryExpression;\r
+                if (binaryExpression != null) {\r
+                    return BinaryExpressionFingerprint.Create(binaryExpression, parserContext);\r
+                }\r
+            }\r
+\r
+            {\r
+                ConditionalExpression conditionalExpression = expression as ConditionalExpression;\r
+                if (conditionalExpression != null) {\r
+                    return ConditionalExpressionFingerprint.Create(conditionalExpression, parserContext);\r
+                }\r
+            }\r
+\r
+            {\r
+                ConstantExpression constantExpression = expression as ConstantExpression;\r
+                if (constantExpression != null) {\r
+                    return ConstantExpressionFingerprint.Create(constantExpression, parserContext);\r
+                }\r
+            }\r
+\r
+            {\r
+                MemberExpression memberExpression = expression as MemberExpression;\r
+                if (memberExpression != null) {\r
+                    return MemberExpressionFingerprint.Create(memberExpression, parserContext);\r
+                }\r
+            }\r
+\r
+            {\r
+                MethodCallExpression methodCallExpression = expression as MethodCallExpression;\r
+                if (methodCallExpression != null) {\r
+                    return MethodCallExpressionFingerprint.Create(methodCallExpression, parserContext);\r
+                }\r
+            }\r
+\r
+            {\r
+                ParameterExpression parameterExpression = expression as ParameterExpression;\r
+                if (parameterExpression != null) {\r
+                    return ParameterExpressionFingerprint.Create(parameterExpression, parserContext);\r
+                }\r
+            }\r
+\r
+            {\r
+                UnaryExpression unaryExpression = expression as UnaryExpression;\r
+                if (unaryExpression != null) {\r
+                    return UnaryExpressionFingerprint.Create(unaryExpression, parserContext);\r
+                }\r
+            }\r
+\r
+            // unknown expression\r
+            return null;\r
+        }\r
+\r
+        public static ReadOnlyCollection<ExpressionFingerprint> Create(IEnumerable<Expression> expressions, ParserContext parserContext) {\r
+            List<ExpressionFingerprint> fingerprints = new List<ExpressionFingerprint>();\r
+            foreach (Expression expression in expressions) {\r
+                ExpressionFingerprint fingerprint = Create(expression, parserContext);\r
+                if (fingerprint == null && expression != null) {\r
+                    // something couldn't be parsed properly\r
+                    return null;\r
+                }\r
+                else {\r
+                    fingerprints.Add(fingerprint);\r
+                }\r
+            }\r
+            return new ReadOnlyCollection<ExpressionFingerprint>(fingerprints);\r
+        }\r
+\r
+        public override int GetHashCode() {\r
+            HashCodeCombiner combiner = new HashCodeCombiner();\r
+            combiner.AddObject(GetType());\r
+            AddToHashCodeCombiner(combiner);\r
+            return combiner.CombinedHash;\r
+        }\r
+\r
+        public override bool Equals(object obj) {\r
+            ExpressionFingerprint other = obj as ExpressionFingerprint;\r
+            if (other == null) {\r
+                return false;\r
+            }\r
+\r
+            return (this.NodeType == other.NodeType\r
+                && this.Type == other.Type\r
+                && this.GetType() == other.GetType());\r
+        }\r
+\r
+        protected static Expression ToExpression(ExpressionFingerprint fingerprint, ParserContext parserContext) {\r
+            return (fingerprint != null) ? fingerprint.ToExpression(parserContext) : null;\r
+        }\r
+\r
+        protected static IEnumerable<Expression> ToExpression(IEnumerable<ExpressionFingerprint> fingerprints, ParserContext parserContext) {\r
+            return from fingerprint in fingerprints select ToExpression(fingerprint, parserContext);\r
+        }\r
+\r
+        public abstract Expression ToExpression(ParserContext parserContext);\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/ExpressionParser.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/ExpressionParser.cs
new file mode 100644 (file)
index 0000000..f277a9f
--- /dev/null
@@ -0,0 +1,30 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.ExpressionUtil {\r
+    using System;\r
+    using System.Linq.Expressions;\r
+\r
+    internal static class ExpressionParser {\r
+\r
+        public static ParserContext Parse<TModel, TValue>(Expression<Func<TModel, TValue>> expression) {\r
+            ParserContext context = new ParserContext() {\r
+                ModelParameter = expression.Parameters[0]\r
+            };\r
+\r
+            Expression body = expression.Body;\r
+            context.Fingerprint = ExpressionFingerprint.Create(body, context);\r
+            return context;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/FastTrack`2.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/FastTrack`2.cs
new file mode 100644 (file)
index 0000000..ec20c8c
--- /dev/null
@@ -0,0 +1,112 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.ExpressionUtil {\r
+    using System;\r
+    using System.Linq.Expressions;\r
+    using System.Reflection;\r
+\r
+    internal static class FastTrack<TModel, TValue> {\r
+\r
+        private static Func<TModel, TValue> _identityFunc;\r
+\r
+        private static readonly ConstMemberLookupCache _constMemberLookupCache = new ConstMemberLookupCache();\r
+        private static readonly ModelMemberLookupCache _modelMemberLookupCache = new ModelMemberLookupCache();\r
+\r
+        public static Func<TModel, TValue> GetFunc(ParameterExpression modelParameter, Expression body) {\r
+            { // model => model\r
+                if (modelParameter == body) {\r
+                    return GetIdentityFunc();\r
+                }\r
+            }\r
+\r
+            { // model => {const}\r
+                ConstantExpression constantExpression = body as ConstantExpression;\r
+                if (constantExpression != null) {\r
+                    TValue value = (TValue)constantExpression.Value;\r
+                    return _ => value;\r
+                }\r
+            }\r
+\r
+            {\r
+                MemberExpression memberExpression = body as MemberExpression;\r
+                if (memberExpression != null) {\r
+                    if (memberExpression.Expression == null) {\r
+                        // model => {static member}\r
+                        return GetModelMemberLookupFunc(memberExpression.Member, true /* isStatic */);\r
+                    }\r
+                    else if (memberExpression.Expression == modelParameter) {\r
+                        // model => model.Member\r
+                        return GetModelMemberLookupFunc(memberExpression.Member, false /* isStatic */);\r
+                    }\r
+                    else {\r
+                        ConstantExpression constantExpression = memberExpression.Expression as ConstantExpression;\r
+                        if (constantExpression != null) {\r
+                            // model => {const}.Member, e.g. captured local variable in a foreach\r
+                            return GetConstMemberLookupFunc(memberExpression.Member, constantExpression.Value);\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+\r
+            // don't know how to fast-track\r
+            return null;\r
+        }\r
+\r
+        private static Func<TModel, TValue> GetIdentityFunc() {\r
+            // don't need to worry about locking since all identity funcs are the same\r
+            if (_identityFunc == null) {\r
+                ParameterExpression modelParameter = Expression.Parameter(typeof(TModel), "model");\r
+                Expression<Func<TModel, TValue>> identityLambda = Expression.Lambda<Func<TModel, TValue>>(modelParameter, modelParameter);\r
+                _identityFunc = identityLambda.Compile();\r
+            }\r
+\r
+            return _identityFunc;\r
+        }\r
+\r
+        private static Func<TModel, TValue> GetModelMemberLookupFunc(MemberInfo member, bool isStatic) {\r
+            return _modelMemberLookupCache.GetFunc(member, isStatic);\r
+        }\r
+\r
+        private static Func<TModel, TValue> GetConstMemberLookupFunc(MemberInfo member, object constValue) {\r
+            Func<object, TValue> innerFunc = _constMemberLookupCache.GetFunc(member);\r
+            return _ => innerFunc(constValue);\r
+        }\r
+\r
+        private sealed class ConstMemberLookupCache : ReaderWriterCache<MemberInfo, Func<object, TValue>> {\r
+            private static Func<object, TValue> CreateFunc(MemberInfo member) {\r
+                ParameterExpression constParam = Expression.Parameter(typeof(object), "constValue");\r
+                // cast is necessary since the constant value comes in as a standard 'object'\r
+                UnaryExpression castExpr = Expression.Convert(constParam, member.DeclaringType);\r
+                MemberExpression memberExpr = Expression.MakeMemberAccess(castExpr, member);\r
+                Expression<Func<object, TValue>> lambda = Expression.Lambda<Func<object, TValue>>(memberExpr, constParam);\r
+                return lambda.Compile();\r
+            }\r
+            public Func<object, TValue> GetFunc(MemberInfo member) {\r
+                return FetchOrCreateItem(member, () => CreateFunc(member));\r
+            }\r
+        }\r
+\r
+        private sealed class ModelMemberLookupCache : ReaderWriterCache<MemberInfo, Func<TModel, TValue>> {\r
+            private static Func<TModel, TValue> CreateFunc(MemberInfo member, bool isStatic) {\r
+                ParameterExpression modelParam = Expression.Parameter(typeof(TModel), "model");\r
+                MemberExpression memberExpr = Expression.MakeMemberAccess((!isStatic) ? modelParam : null, member);\r
+                Expression<Func<TModel, TValue>> lambda = Expression.Lambda<Func<TModel, TValue>>(memberExpr, modelParam);\r
+                return lambda.Compile();\r
+            }\r
+            public Func<TModel, TValue> GetFunc(MemberInfo member, bool isStatic) {\r
+                return FetchOrCreateItem(member, () => CreateFunc(member, isStatic));\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/HashCodeCombiner.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/HashCodeCombiner.cs
new file mode 100644 (file)
index 0000000..5abdded
--- /dev/null
@@ -0,0 +1,61 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.ExpressionUtil {\r
+    using System;\r
+    using System.Collections;\r
+\r
+    // based on System.Web.Util.HashCodeCombiner\r
+    internal class HashCodeCombiner {\r
+\r
+        private long _combinedHash64 = 0x1505L;\r
+\r
+        public void AddFingerprint(ExpressionFingerprint fingerprint) {\r
+            if (fingerprint != null) {\r
+                fingerprint.AddToHashCodeCombiner(this);\r
+            }\r
+            else {\r
+                AddInt32(0);\r
+            }\r
+        }\r
+\r
+        public void AddEnumerable(IEnumerable e) {\r
+            if (e == null) {\r
+                AddInt32(0);\r
+            }\r
+            else {\r
+                int count = 0;\r
+                foreach (object o in e) {\r
+                    AddObject(o);\r
+                    count++;\r
+                }\r
+                AddInt32(count);\r
+            }\r
+        }\r
+\r
+        public void AddInt32(int i) {\r
+            _combinedHash64 = ((_combinedHash64 << 5) + _combinedHash64) ^ i;\r
+        }\r
+\r
+        public void AddObject(object o) {\r
+            int oHashCode = (o != null) ? o.GetHashCode() : 0;\r
+            AddInt32(oHashCode);\r
+        }\r
+\r
+        public int CombinedHash {\r
+            get {\r
+                return _combinedHash64.GetHashCode();\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/MemberExpressionFingerprint.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/MemberExpressionFingerprint.cs
new file mode 100644 (file)
index 0000000..6a55769
--- /dev/null
@@ -0,0 +1,78 @@
+#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\r
+\r
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.ExpressionUtil {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Linq.Expressions;\r
+    using System.Reflection;\r
+\r
+    // MemberExpression fingerprint class\r
+    // Expression of form xxx.FieldOrProperty\r
+    [SuppressMessage("Microsoft.Usage", "CA2218:OverrideGetHashCodeOnOverridingEquals",\r
+        Justification = "Overrides AddToHashCodeCombiner() instead.")]\r
+    internal sealed class MemberExpressionFingerprint : ExpressionFingerprint {\r
+\r
+        private MemberExpressionFingerprint(MemberExpression expression)\r
+            : base(expression) {\r
+\r
+            Member = expression.Member;\r
+        }\r
+\r
+        public MemberInfo Member {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public ExpressionFingerprint Target {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        internal override void AddToHashCodeCombiner(HashCodeCombiner combiner) {\r
+            base.AddToHashCodeCombiner(combiner);\r
+\r
+            combiner.AddObject(Member);\r
+            combiner.AddFingerprint(Target);\r
+        }\r
+\r
+        public static MemberExpressionFingerprint Create(MemberExpression expression, ParserContext parserContext) {\r
+            ExpressionFingerprint target = Create(expression.Expression, parserContext);\r
+            if (target == null && expression.Expression != null) {\r
+                return null;\r
+            }\r
+\r
+            return new MemberExpressionFingerprint(expression) {\r
+                Target = target\r
+            };\r
+        }\r
+\r
+        public override bool Equals(object obj) {\r
+            MemberExpressionFingerprint other = obj as MemberExpressionFingerprint;\r
+            if (other == null) {\r
+                return false;\r
+            }\r
+\r
+            return (this.Member == other.Member\r
+                && Object.Equals(this.Target, other.Target)\r
+                && base.Equals(other));\r
+        }\r
+\r
+        public override Expression ToExpression(ParserContext parserContext) {\r
+            Expression targetExpr = ToExpression(Target, parserContext);\r
+            return Expression.MakeMemberAccess(targetExpr, Member);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/MethodCallExpressionFingerprint.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/MethodCallExpressionFingerprint.cs
new file mode 100644 (file)
index 0000000..7b8455c
--- /dev/null
@@ -0,0 +1,95 @@
+#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\r
+\r
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.ExpressionUtil {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Collections.ObjectModel;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Linq;\r
+    using System.Linq.Expressions;\r
+    using System.Reflection;\r
+\r
+    // MethodCallExpression fingerprint class\r
+    // Expression of form xxx.Foo(...), xxx[...] (get_Item()), etc.\r
+    [SuppressMessage("Microsoft.Usage", "CA2218:OverrideGetHashCodeOnOverridingEquals",\r
+        Justification = "Overrides AddToHashCodeCombiner() instead.")]\r
+    internal sealed class MethodCallExpressionFingerprint : ExpressionFingerprint {\r
+\r
+        private MethodCallExpressionFingerprint(MethodCallExpression expression)\r
+            : base(expression) {\r
+\r
+            Method = expression.Method;\r
+        }\r
+\r
+        public ReadOnlyCollection<ExpressionFingerprint> Arguments {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public MethodInfo Method {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public ExpressionFingerprint Target {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        internal override void AddToHashCodeCombiner(HashCodeCombiner combiner) {\r
+            base.AddToHashCodeCombiner(combiner);\r
+\r
+            combiner.AddEnumerable(Arguments);\r
+            combiner.AddObject(Method);\r
+            combiner.AddFingerprint(Target);\r
+        }\r
+\r
+        public static MethodCallExpressionFingerprint Create(MethodCallExpression expression, ParserContext parserContext) {\r
+            ReadOnlyCollection<ExpressionFingerprint> arguments = Create(expression.Arguments, parserContext);\r
+            if (arguments == null) {\r
+                return null;\r
+            }\r
+\r
+            ExpressionFingerprint target = Create(expression.Object, parserContext);\r
+            if (target == null && expression.Object != null) {\r
+                return null;\r
+            }\r
+\r
+            return new MethodCallExpressionFingerprint(expression) {\r
+                Arguments = arguments,\r
+                Target = target\r
+            };\r
+        }\r
+\r
+        public override bool Equals(object obj) {\r
+            MethodCallExpressionFingerprint other = obj as MethodCallExpressionFingerprint;\r
+            if (other == null) {\r
+                return false;\r
+            }\r
+\r
+            return (this.Arguments.SequenceEqual(other.Arguments)\r
+                && this.Method == other.Method\r
+                && Object.Equals(this.Target, other.Target)\r
+                && base.Equals(other));\r
+        }\r
+\r
+        public override Expression ToExpression(ParserContext parserContext) {\r
+            Expression targetExpr = ToExpression(Target, parserContext);\r
+            IEnumerable<Expression> argumentsExpr = ToExpression(Arguments, parserContext);\r
+            return Expression.Call(targetExpr, Method, argumentsExpr);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/ParameterExpressionFingerprint.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/ParameterExpressionFingerprint.cs
new file mode 100644 (file)
index 0000000..399f686
--- /dev/null
@@ -0,0 +1,42 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.ExpressionUtil {\r
+    using System;\r
+    using System.Linq.Expressions;\r
+\r
+    // ParameterExpression fingerprint class\r
+    // Specifically, instances of this type represent the model parameter\r
+    internal sealed class ParameterExpressionFingerprint : ExpressionFingerprint {\r
+\r
+        private ParameterExpressionFingerprint(ParameterExpression expression)\r
+            : base(expression) {\r
+        }\r
+\r
+        public static ParameterExpressionFingerprint Create(ParameterExpression expression, ParserContext parserContext) {\r
+            if (expression == parserContext.ModelParameter) {\r
+                return new ParameterExpressionFingerprint(expression);\r
+            }\r
+            else {\r
+                // degenerate case - uncaptured parameter expression passed into the system\r
+                return null;\r
+            }\r
+        }\r
+\r
+        public override Expression ToExpression(ParserContext parserContext) {\r
+            // The only time an instance of this class exists is if it represents the actual model parameter,\r
+            // so just return it directly.\r
+            return parserContext.ModelParameter;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/ParserContext.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/ParserContext.cs
new file mode 100644 (file)
index 0000000..38281c3
--- /dev/null
@@ -0,0 +1,27 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.ExpressionUtil {\r
+    using System;\r
+    using System.Linq.Expressions;\r
+    using System.Collections.Generic;\r
+\r
+    internal class ParserContext {\r
+\r
+        public static readonly ParameterExpression HoistedValuesParameter = Expression.Parameter(typeof(object[]), "hoistedValues");\r
+\r
+        public ExpressionFingerprint Fingerprint;\r
+        public readonly List<object> HoistedValues = new List<object>();\r
+        public ParameterExpression ModelParameter;\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/UnaryExpressionFingerprint.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ExpressionUtil/UnaryExpressionFingerprint.cs
new file mode 100644 (file)
index 0000000..8ba8cfa
--- /dev/null
@@ -0,0 +1,87 @@
+#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\r
+\r
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.ExpressionUtil {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Linq.Expressions;\r
+    using System.Reflection;\r
+\r
+    // UnaryExpression fingerprint class\r
+    // The most common appearance of a UnaryExpression is a cast or other conversion operator\r
+    [SuppressMessage("Microsoft.Usage", "CA2218:OverrideGetHashCodeOnOverridingEquals",\r
+        Justification = "Overrides AddToHashCodeCombiner() instead.")]\r
+    internal sealed class UnaryExpressionFingerprint : ExpressionFingerprint {\r
+\r
+        private UnaryExpressionFingerprint(UnaryExpression expression)\r
+            : base(expression) {\r
+            // don't care about UnaryExpression.IsLifted / IsLiftedToNull since they're not necessary to uniquely describe the expression\r
+\r
+            Method = expression.Method;\r
+        }\r
+\r
+        public MethodInfo Method {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public ExpressionFingerprint Operand {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        internal override void AddToHashCodeCombiner(HashCodeCombiner combiner) {\r
+            base.AddToHashCodeCombiner(combiner);\r
+\r
+            combiner.AddObject(Method);\r
+            combiner.AddFingerprint(Operand);\r
+        }\r
+\r
+        public static UnaryExpressionFingerprint Create(UnaryExpression expression, ParserContext parserContext) {\r
+            ExpressionFingerprint operand = Create(expression.Operand, parserContext);\r
+            if (operand == null && expression.Operand != null) {\r
+                // couldn't convert the operand, so bail\r
+                return null;\r
+            }\r
+\r
+            return new UnaryExpressionFingerprint(expression) {\r
+                Operand = operand\r
+            };\r
+        }\r
+\r
+        public override bool Equals(object obj) {\r
+            UnaryExpressionFingerprint other = obj as UnaryExpressionFingerprint;\r
+            if (other == null) {\r
+                return false;\r
+            }\r
+\r
+            return (this.Method == other.Method\r
+                && Object.Equals(this.Operand, other.Operand)\r
+                && base.Equals(other));\r
+        }\r
+\r
+        public override Expression ToExpression(ParserContext parserContext) {\r
+            Expression operandExpr = ToExpression(Operand, parserContext);\r
+\r
+            // in .NET 3.5 SP1, Expression.MakeUnary() throws if NodeType is UnaryPlus, so special-case\r
+            if (NodeType == ExpressionType.UnaryPlus) {\r
+                return Expression.UnaryPlus(operandExpr, Method);\r
+            }\r
+            else {\r
+                return Expression.MakeUnary(NodeType, operandExpr, Type, Method);\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/FieldValidationMetadata.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/FieldValidationMetadata.cs
new file mode 100644 (file)
index 0000000..5dda044
--- /dev/null
@@ -0,0 +1,49 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Collections.ObjectModel;\r
+\r
+    public class FieldValidationMetadata {\r
+\r
+        private string _fieldName;\r
+        private readonly Collection<ModelClientValidationRule> _validationRules = new Collection<ModelClientValidationRule>();\r
+\r
+        public string FieldName {\r
+            get {\r
+                return _fieldName ?? String.Empty;\r
+            }\r
+            set {\r
+                _fieldName = value;\r
+            }\r
+        }\r
+\r
+        public bool ReplaceValidationMessageContents {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public string ValidationMessageId {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public ICollection<ModelClientValidationRule> ValidationRules {\r
+            get {\r
+                return _validationRules;\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/FileContentResult.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/FileContentResult.cs
new file mode 100644 (file)
index 0000000..8a2fdc0
--- /dev/null
@@ -0,0 +1,41 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Web;\r
+\r
+    public class FileContentResult : FileResult {\r
+\r
+        public FileContentResult(byte[] fileContents, string contentType)\r
+            : base(contentType) {\r
+            if (fileContents == null) {\r
+                throw new ArgumentNullException("fileContents");\r
+            }\r
+\r
+            FileContents = fileContents;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",\r
+            Justification = "There's no reason to tamper-proof this array since it's supplied to the type's constructor.")]\r
+        public byte[] FileContents {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        protected override void WriteFile(HttpResponseBase response) {\r
+            response.OutputStream.Write(FileContents, 0, FileContents.Length);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/FilePathResult.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/FilePathResult.cs
new file mode 100644 (file)
index 0000000..550113f
--- /dev/null
@@ -0,0 +1,39 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Web;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public class FilePathResult : FileResult {\r
+\r
+        public FilePathResult(string fileName, string contentType)\r
+            : base(contentType) {\r
+            if (String.IsNullOrEmpty(fileName)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "fileName");\r
+            }\r
+\r
+            FileName = fileName;\r
+        }\r
+\r
+        public string FileName {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        protected override void WriteFile(HttpResponseBase response) {\r
+            response.TransmitFile(FileName);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/FileResult.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/FileResult.cs
new file mode 100644 (file)
index 0000000..8127e46
--- /dev/null
@@ -0,0 +1,143 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Net.Mime;\r
+    using System.Text;\r
+    using System.Web;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public abstract class FileResult : ActionResult {\r
+\r
+        protected FileResult(string contentType) {\r
+            if (String.IsNullOrEmpty(contentType)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "contentType");\r
+            }\r
+\r
+            ContentType = contentType;\r
+        }\r
+\r
+        private string _fileDownloadName;\r
+\r
+        public string ContentType {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public string FileDownloadName {\r
+            get {\r
+                return _fileDownloadName ?? String.Empty;\r
+            }\r
+            set {\r
+                _fileDownloadName = value;\r
+            }\r
+        }\r
+\r
+        public override void ExecuteResult(ControllerContext context) {\r
+            if (context == null) {\r
+                throw new ArgumentNullException("context");\r
+            }\r
+\r
+            HttpResponseBase response = context.HttpContext.Response;\r
+            response.ContentType = ContentType;\r
+\r
+            if (!String.IsNullOrEmpty(FileDownloadName)) {\r
+                // From RFC 2183, Sec. 2.3:\r
+                // The sender may want to suggest a filename to be used if the entity is\r
+                // detached and stored in a separate file. If the receiving MUA writes\r
+                // the entity to a file, the suggested filename should be used as a\r
+                // basis for the actual filename, where possible.\r
+                string headerValue = ContentDispositionUtil.GetHeaderValue(FileDownloadName);\r
+                context.HttpContext.Response.AddHeader("Content-Disposition", headerValue);\r
+            }\r
+\r
+            WriteFile(response);\r
+        }\r
+\r
+        protected abstract void WriteFile(HttpResponseBase response);\r
+\r
+        private static class ContentDispositionUtil {\r
+            private const string _hexDigits = "0123456789ABCDEF";\r
+\r
+            private static void AddByteToStringBuilder(byte b, StringBuilder builder) {\r
+                builder.Append('%');\r
+\r
+                int i = b;\r
+                AddHexDigitToStringBuilder(i >> 4, builder);\r
+                AddHexDigitToStringBuilder(i % 16, builder);\r
+            }\r
+\r
+            private static void AddHexDigitToStringBuilder(int digit, StringBuilder builder) {\r
+                builder.Append(_hexDigits[digit]);\r
+            }\r
+\r
+            private static string CreateRfc2231HeaderValue(string filename) {\r
+                StringBuilder builder = new StringBuilder("attachment; filename*=UTF-8''");\r
+\r
+                byte[] filenameBytes = Encoding.UTF8.GetBytes(filename);\r
+                foreach (byte b in filenameBytes) {\r
+                    if (IsByteValidHeaderValueCharacter(b)) {\r
+                        builder.Append((char)b);\r
+                    }\r
+                    else {\r
+                        AddByteToStringBuilder(b, builder);\r
+                    }\r
+                }\r
+\r
+                return builder.ToString();\r
+            }\r
+\r
+            public static string GetHeaderValue(string fileName) {\r
+                try {\r
+                    // first, try using the .NET built-in generator\r
+                    ContentDisposition disposition = new ContentDisposition() { FileName = fileName };\r
+                    return disposition.ToString();\r
+                }\r
+                catch (FormatException) {\r
+                    // otherwise, fall back to RFC 2231 extensions generator\r
+                    return CreateRfc2231HeaderValue(fileName);\r
+                }\r
+            }\r
+\r
+            // Application of RFC 2231 Encoding to Hypertext Transfer Protocol (HTTP) Header Fields, sec. 3.2\r
+            // http://greenbytes.de/tech/webdav/draft-reschke-rfc2231-in-http-latest.html\r
+            private static bool IsByteValidHeaderValueCharacter(byte b) {\r
+                if ((byte)'0' <= b && b <= (byte)'9') {\r
+                    return true; // is digit\r
+                }\r
+                if ((byte)'a' <= b && b <= (byte)'z') {\r
+                    return true; // lowercase letter\r
+                }\r
+                if ((byte)'A' <= b && b <= (byte)'Z') {\r
+                    return true; // uppercase letter\r
+                }\r
+\r
+                switch (b) {\r
+                    case (byte)'-':\r
+                    case (byte)'.':\r
+                    case (byte)'_':\r
+                    case (byte)'~':\r
+                    case (byte)':':\r
+                    case (byte)'!':\r
+                    case (byte)'$':\r
+                    case (byte)'&':\r
+                    case (byte)'+':\r
+                        return true;\r
+                }\r
+\r
+                return false;\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/FileStreamResult.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/FileStreamResult.cs
new file mode 100644 (file)
index 0000000..a6e1a6f
--- /dev/null
@@ -0,0 +1,56 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.IO;\r
+    using System.Web;\r
+\r
+    public class FileStreamResult : FileResult {\r
+\r
+        // default buffer size as defined in BufferedStream type\r
+        private const int _bufferSize = 0x1000;\r
+\r
+        public FileStreamResult(Stream fileStream, string contentType)\r
+            : base(contentType) {\r
+            if (fileStream == null) {\r
+                throw new ArgumentNullException("fileStream");\r
+            }\r
+\r
+            FileStream = fileStream;\r
+        }\r
+\r
+        public Stream FileStream {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        protected override void WriteFile(HttpResponseBase response) {\r
+            // grab chunks of data and write to the output stream\r
+            Stream outputStream = response.OutputStream;\r
+            using (FileStream) {\r
+                byte[] buffer = new byte[_bufferSize];\r
+\r
+                while (true) {\r
+                    int bytesRead = FileStream.Read(buffer, 0, _bufferSize);\r
+                    if (bytesRead == 0) {\r
+                        // no more data\r
+                        break;\r
+                    }\r
+\r
+                    outputStream.Write(buffer, 0, bytesRead);\r
+                }\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/FilterAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/FilterAttribute.cs
new file mode 100644 (file)
index 0000000..1cda086
--- /dev/null
@@ -0,0 +1,35 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\r
+    public abstract class FilterAttribute : Attribute {\r
+\r
+        private int _order = -1;\r
+\r
+        public int Order {\r
+            get {\r
+                return _order;\r
+            }\r
+            set {\r
+                if (value < -1) {\r
+                    throw new ArgumentOutOfRangeException("value",\r
+                        MvcResources.FilterAttribute_OrderOutOfRange);\r
+                }\r
+                _order = value;\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/FilterInfo.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/FilterInfo.cs
new file mode 100644 (file)
index 0000000..031ffe3
--- /dev/null
@@ -0,0 +1,48 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Collections.Generic;\r
+\r
+    public class FilterInfo {\r
+\r
+        private List<IActionFilter> _actionFilters = new List<IActionFilter>();\r
+        private List<IAuthorizationFilter> _authorizationFilters = new List<IAuthorizationFilter>();\r
+        private List<IExceptionFilter> _exceptionFilters = new List<IExceptionFilter>();\r
+        private List<IResultFilter> _resultFilters = new List<IResultFilter>();\r
+\r
+        public IList<IActionFilter> ActionFilters {\r
+            get {\r
+                return _actionFilters;\r
+            }\r
+        }\r
+\r
+        public IList<IAuthorizationFilter> AuthorizationFilters {\r
+            get {\r
+                return _authorizationFilters;\r
+            }\r
+        }\r
+\r
+        public IList<IExceptionFilter> ExceptionFilters {\r
+            get {\r
+                return _exceptionFilters;\r
+            }\r
+        }\r
+\r
+        public IList<IResultFilter> ResultFilters {\r
+            get {\r
+                return _resultFilters;\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/FormCollection.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/FormCollection.cs
new file mode 100644 (file)
index 0000000..3736bae
--- /dev/null
@@ -0,0 +1,89 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Specialized;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    [SuppressMessage("Microsoft.Usage", "CA2237:MarkISerializableTypesWithSerializable",\r
+        Justification = "It is not anticipated that users will need to serialize this type.")]\r
+    [SuppressMessage("Microsoft.Design", "CA1035:ICollectionImplementationsHaveStronglyTypedMembers",\r
+        Justification = "It is not anticipated that users will call FormCollection.CopyTo().")]\r
+    [FormCollectionBinder]\r
+    public sealed class FormCollection : NameValueCollection, IValueProvider {\r
+\r
+        public FormCollection() {\r
+        }\r
+\r
+        public FormCollection(NameValueCollection collection) {\r
+            if (collection == null) {\r
+                throw new ArgumentNullException("collection");\r
+            }\r
+\r
+            Add(collection);\r
+        }\r
+\r
+        public ValueProviderResult GetValue(string name) {\r
+            if (name == null) {\r
+                throw new ArgumentNullException("name");\r
+            }\r
+\r
+            string[] rawValue = GetValues(name);\r
+            if (rawValue == null) {\r
+                return null;\r
+            }\r
+\r
+            string attemptedValue = this[name];\r
+            return new ValueProviderResult(rawValue, attemptedValue, CultureInfo.CurrentCulture);\r
+        }\r
+\r
+        public IValueProvider ToValueProvider() {\r
+            return this;\r
+        }\r
+\r
+        #region IValueProvider Members\r
+        bool IValueProvider.ContainsPrefix(string prefix) {\r
+            return ValueProviderUtil.CollectionContainsPrefix(AllKeys, prefix);\r
+        }\r
+\r
+        ValueProviderResult IValueProvider.GetValue(string key) {\r
+            return GetValue(key);\r
+        }\r
+        #endregion\r
+\r
+        private sealed class FormCollectionBinderAttribute : CustomModelBinderAttribute {\r
+\r
+            // since the FormCollectionModelBinder.BindModel() method is thread-safe, we only need to keep\r
+            // a single instance of the binder around\r
+            private static readonly FormCollectionModelBinder _binder = new FormCollectionModelBinder();\r
+\r
+            public override IModelBinder GetBinder() {\r
+                return _binder;\r
+            }\r
+\r
+            // this class is used for generating a FormCollection object\r
+            private sealed class FormCollectionModelBinder : IModelBinder {\r
+                public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {\r
+                    if (controllerContext == null) {\r
+                        throw new ArgumentNullException("controllerContext");\r
+                    }\r
+\r
+                    return new FormCollection(controllerContext.HttpContext.Request.Form);\r
+                }\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/FormContext.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/FormContext.cs
new file mode 100644 (file)
index 0000000..a2c6ec8
--- /dev/null
@@ -0,0 +1,84 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections;\r
+    using System.Collections.Generic;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Web.Script.Serialization;\r
+\r
+    public class FormContext {\r
+\r
+        private readonly Dictionary<string, FieldValidationMetadata> _fieldValidators = new Dictionary<string, FieldValidationMetadata>();\r
+\r
+        public IDictionary<string, FieldValidationMetadata> FieldValidators {\r
+            get {\r
+                return _fieldValidators;\r
+            }\r
+        }\r
+\r
+        public string FormId {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public bool ReplaceValidationSummary {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public string ValidationSummaryId {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",\r
+            Justification = "Performs a potentially time-consuming conversion.")]\r
+        public string GetJsonValidationMetadata() {\r
+            JavaScriptSerializer serializer = new JavaScriptSerializer();\r
+\r
+            SortedDictionary<string, object> dict = new SortedDictionary<string, object>() {\r
+                { "Fields", FieldValidators.Values },\r
+                { "FormId", FormId }\r
+            };\r
+            if (!String.IsNullOrEmpty(ValidationSummaryId)) {\r
+                dict["ValidationSummaryId"] = ValidationSummaryId;\r
+            }\r
+            dict["ReplaceValidationSummary"] = ReplaceValidationSummary;\r
+\r
+            return serializer.Serialize(dict);\r
+        }\r
+\r
+        public FieldValidationMetadata GetValidationMetadataForField(string fieldName) {\r
+            return GetValidationMetadataForField(fieldName, false /* createIfNotFound */);\r
+        }\r
+\r
+        public FieldValidationMetadata GetValidationMetadataForField(string fieldName, bool createIfNotFound) {\r
+            if (String.IsNullOrEmpty(fieldName)) {\r
+                throw Error.ParameterCannotBeNullOrEmpty("fieldName");\r
+            }\r
+\r
+            FieldValidationMetadata metadata;\r
+            if (!FieldValidators.TryGetValue(fieldName, out metadata)) {\r
+                if (createIfNotFound) {\r
+                    metadata = new FieldValidationMetadata() {\r
+                        FieldName = fieldName\r
+                    };\r
+                    FieldValidators[fieldName] = metadata;\r
+                }\r
+            }\r
+            return metadata;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/FormMethod.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/FormMethod.cs
new file mode 100644 (file)
index 0000000..0c9ebc8
--- /dev/null
@@ -0,0 +1,18 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    public enum FormMethod {\r
+        Get,\r
+        Post\r
+    }\r
+}
\ No newline at end of file
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/FormValueProvider.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/FormValueProvider.cs
new file mode 100644 (file)
index 0000000..7349734
--- /dev/null
@@ -0,0 +1,25 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Specialized;\r
+    using System.Globalization;\r
+\r
+    public sealed class FormValueProvider : NameValueCollectionValueProvider {\r
+\r
+        public FormValueProvider(ControllerContext controllerContext)\r
+            : base(controllerContext.HttpContext.Request.Form, CultureInfo.CurrentCulture) {\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/FormValueProviderFactory.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/FormValueProviderFactory.cs
new file mode 100644 (file)
index 0000000..686f3ab
--- /dev/null
@@ -0,0 +1,27 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    public sealed class FormValueProviderFactory : ValueProviderFactory {\r
+\r
+        public override IValueProvider GetValueProvider(ControllerContext controllerContext) {\r
+            if (controllerContext == null) {\r
+                throw new ArgumentNullException("controllerContext");\r
+            }\r
+\r
+            return new FormValueProvider(controllerContext);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/HandleErrorAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/HandleErrorAttribute.cs
new file mode 100644 (file)
index 0000000..99b40cf
--- /dev/null
@@ -0,0 +1,119 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.Web;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    [SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes",\r
+        Justification = "This attribute is AllowMultiple = true and users might want to override behavior.")]\r
+    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]\r
+    public class HandleErrorAttribute : FilterAttribute, IExceptionFilter {\r
+\r
+        private const string _defaultView = "Error";\r
+\r
+        private readonly object _typeId = new object();\r
+\r
+        private Type _exceptionType = typeof(Exception);\r
+        private string _master;\r
+        private string _view;\r
+\r
+        public Type ExceptionType {\r
+            get {\r
+                return _exceptionType;\r
+            }\r
+            set {\r
+                if (value == null) {\r
+                    throw new ArgumentNullException("value");\r
+                }\r
+                if (!typeof(Exception).IsAssignableFrom(value)) {\r
+                    throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture,\r
+                        MvcResources.ExceptionViewAttribute_NonExceptionType, value.FullName));\r
+                }\r
+\r
+                _exceptionType = value;\r
+            }\r
+        }\r
+\r
+        public string Master {\r
+            get {\r
+                return _master ?? String.Empty;\r
+            }\r
+            set {\r
+                _master = value;\r
+            }\r
+        }\r
+\r
+        public override object TypeId {\r
+            get {\r
+                return _typeId;\r
+            }\r
+        }\r
+\r
+        public string View {\r
+            get {\r
+                return (!String.IsNullOrEmpty(_view)) ? _view : _defaultView;\r
+            }\r
+            set {\r
+                _view = value;\r
+            }\r
+        }\r
+\r
+        public virtual void OnException(ExceptionContext filterContext) {\r
+            if (filterContext == null) {\r
+                throw new ArgumentNullException("filterContext");\r
+            }\r
+            if (filterContext.IsChildAction) {\r
+                return;\r
+            }\r
+\r
+            // If custom errors are disabled, we need to let the normal ASP.NET exception handler\r
+            // execute so that the user can see useful debugging information.\r
+            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled) {\r
+                return;\r
+            }\r
+\r
+            Exception exception = filterContext.Exception;\r
+\r
+            // If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method),\r
+            // ignore it.\r
+            if (new HttpException(null, exception).GetHttpCode() != 500) {\r
+                return;\r
+            }\r
+\r
+            if (!ExceptionType.IsInstanceOfType(exception)) {\r
+                return;\r
+            }\r
+\r
+            string controllerName = (string)filterContext.RouteData.Values["controller"];\r
+            string actionName = (string)filterContext.RouteData.Values["action"];\r
+            HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);\r
+            filterContext.Result = new ViewResult {\r
+                ViewName = View,\r
+                MasterName = Master,\r
+                ViewData = new ViewDataDictionary<HandleErrorInfo>(model),\r
+                TempData = filterContext.Controller.TempData\r
+            };\r
+            filterContext.ExceptionHandled = true;\r
+            filterContext.HttpContext.Response.Clear();\r
+            filterContext.HttpContext.Response.StatusCode = 500;\r
+\r
+            // Certain versions of IIS will sometimes use their own error page when\r
+            // they detect a server error. Setting this property indicates that we\r
+            // want it to try to render ASP.NET MVC's error page instead.\r
+            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;\r
+        }\r
+    }\r
+}
\ No newline at end of file
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/HandleErrorInfo.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/HandleErrorInfo.cs
new file mode 100644 (file)
index 0000000..d02f911
--- /dev/null
@@ -0,0 +1,51 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public class HandleErrorInfo {\r
+\r
+        public HandleErrorInfo(Exception exception, string controllerName, string actionName) {\r
+            if (exception == null) {\r
+                throw new ArgumentNullException("exception");\r
+            }\r
+            if (String.IsNullOrEmpty(controllerName)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "controllerName");\r
+            }\r
+            if (string.IsNullOrEmpty(actionName)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "actionName");\r
+            }\r
+\r
+            Exception = exception;\r
+            ControllerName = controllerName;\r
+            ActionName = actionName;\r
+        }\r
+\r
+        public string ActionName {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public string ControllerName {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public Exception Exception {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/HiddenInputAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/HiddenInputAttribute.cs
new file mode 100644 (file)
index 0000000..b1778d4
--- /dev/null
@@ -0,0 +1,24 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]\r
+    public sealed class HiddenInputAttribute : Attribute {\r
+        public HiddenInputAttribute() {\r
+            DisplayValue = true;\r
+        }\r
+\r
+        public bool DisplayValue { get; set; }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/ChildActionExtensions.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/ChildActionExtensions.cs
new file mode 100644 (file)
index 0000000..cd22769
--- /dev/null
@@ -0,0 +1,150 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Html {\r
+    using System.Collections.Generic;\r
+    using System.Globalization;\r
+    using System.IO;\r
+    using System.Linq;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.Routing;\r
+\r
+    public static class ChildActionExtensions {\r
+\r
+        // Action\r
+\r
+        public static MvcHtmlString Action(this HtmlHelper htmlHelper, string actionName) {\r
+            return Action(htmlHelper, actionName, null /* controllerName */, null /* routeValues */);\r
+        }\r
+\r
+        public static MvcHtmlString Action(this HtmlHelper htmlHelper, string actionName, object routeValues) {\r
+            return Action(htmlHelper, actionName, null /* controllerName */, new RouteValueDictionary(routeValues));\r
+        }\r
+\r
+        public static MvcHtmlString Action(this HtmlHelper htmlHelper, string actionName, RouteValueDictionary routeValues) {\r
+            return Action(htmlHelper, actionName, null /* controllerName */, routeValues);\r
+        }\r
+\r
+        public static MvcHtmlString Action(this HtmlHelper htmlHelper, string actionName, string controllerName) {\r
+            return Action(htmlHelper, actionName, controllerName, null /* routeValues */);\r
+        }\r
+\r
+        public static MvcHtmlString Action(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues) {\r
+            return Action(htmlHelper, actionName, controllerName, new RouteValueDictionary(routeValues));\r
+        }\r
+\r
+        public static MvcHtmlString Action(this HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues) {\r
+            StringWriter writer = new StringWriter(CultureInfo.CurrentCulture);\r
+            ActionHelper(htmlHelper, actionName, controllerName, routeValues, writer);\r
+            return MvcHtmlString.Create(writer.ToString());\r
+        }\r
+\r
+        // RenderAction\r
+\r
+        public static void RenderAction(this HtmlHelper htmlHelper, string actionName) {\r
+            RenderAction(htmlHelper, actionName, null /* controllerName */, null /* routeValues */);\r
+        }\r
+\r
+        public static void RenderAction(this HtmlHelper htmlHelper, string actionName, object routeValues) {\r
+            RenderAction(htmlHelper, actionName, null /* controllerName */, new RouteValueDictionary(routeValues));\r
+        }\r
+\r
+        public static void RenderAction(this HtmlHelper htmlHelper, string actionName, RouteValueDictionary routeValues) {\r
+            RenderAction(htmlHelper, actionName, null /* controllerName */, routeValues);\r
+        }\r
+\r
+        public static void RenderAction(this HtmlHelper htmlHelper, string actionName, string controllerName) {\r
+            RenderAction(htmlHelper, actionName, controllerName, null /* routeValues */);\r
+        }\r
+\r
+        public static void RenderAction(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues) {\r
+            RenderAction(htmlHelper, actionName, controllerName, new RouteValueDictionary(routeValues));\r
+        }\r
+\r
+        public static void RenderAction(this HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues) {\r
+            ActionHelper(htmlHelper, actionName, controllerName, routeValues, htmlHelper.ViewContext.Writer);\r
+        }\r
+\r
+        // Helpers\r
+\r
+        internal static void ActionHelper(HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues, TextWriter textWriter) {\r
+            if (htmlHelper == null) {\r
+                throw new ArgumentNullException("htmlHelper");\r
+            }\r
+            if (String.IsNullOrEmpty(actionName)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "actionName");\r
+            }\r
+\r
+            routeValues = MergeDictionaries(routeValues, htmlHelper.ViewContext.RouteData.Values);\r
+            routeValues["action"] = actionName;\r
+            if (!String.IsNullOrEmpty(controllerName)) {\r
+                routeValues["controller"] = controllerName;\r
+            }\r
+\r
+            bool usingAreas;\r
+            VirtualPathData vpd = htmlHelper.RouteCollection.GetVirtualPathForArea(htmlHelper.ViewContext.RequestContext, null /* name */, routeValues, out usingAreas);\r
+            if (vpd == null) {\r
+                throw new InvalidOperationException(MvcResources.Common_NoRouteMatched);\r
+            }\r
+\r
+            if (usingAreas) {\r
+                routeValues.Remove("area");\r
+            }\r
+            RouteData routeData = CreateRouteData(vpd.Route, routeValues, vpd.DataTokens, htmlHelper.ViewContext);\r
+            HttpContextBase httpContext = htmlHelper.ViewContext.HttpContext;\r
+            RequestContext requestContext = new RequestContext(httpContext, routeData);\r
+            ChildActionMvcHandler handler = new ChildActionMvcHandler(requestContext);\r
+            httpContext.Server.Execute(HttpHandlerUtil.WrapForServerExecute(handler), textWriter, true /* preserveForm */);\r
+        }\r
+\r
+        private static RouteData CreateRouteData(RouteBase route, RouteValueDictionary routeValues, RouteValueDictionary dataTokens, ViewContext parentViewContext) {\r
+            RouteData routeData = new RouteData();\r
+\r
+            foreach (KeyValuePair<string, object> kvp in routeValues) {\r
+                routeData.Values.Add(kvp.Key, kvp.Value);\r
+            }\r
+\r
+            foreach (KeyValuePair<string, object> kvp in dataTokens) {\r
+                routeData.DataTokens.Add(kvp.Key, kvp.Value);\r
+            }\r
+\r
+            routeData.Route = route;\r
+            routeData.DataTokens[ControllerContext.PARENT_ACTION_VIEWCONTEXT] = parentViewContext;\r
+            return routeData;\r
+        }\r
+\r
+        private static RouteValueDictionary MergeDictionaries(params RouteValueDictionary[] dictionaries) {\r
+            // Merge existing route values with the user provided values\r
+            var result = new RouteValueDictionary();\r
+\r
+            foreach (RouteValueDictionary dictionary in dictionaries.Where(d => d != null)) {\r
+                foreach (KeyValuePair<string, object> kvp in dictionary) {\r
+                    if (!result.ContainsKey(kvp.Key)) {\r
+                        result.Add(kvp.Key, kvp.Value);\r
+                    }\r
+                }\r
+            }\r
+\r
+            return result;\r
+        }\r
+\r
+        internal class ChildActionMvcHandler : MvcHandler {\r
+            public ChildActionMvcHandler(RequestContext context)\r
+                : base(context) {\r
+            }\r
+\r
+            protected internal override void AddVersionHeader(HttpContextBase httpContext) {\r
+                // No version header for child actions\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/DefaultDisplayTemplates.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/DefaultDisplayTemplates.cs
new file mode 100644 (file)
index 0000000..7edcb3b
--- /dev/null
@@ -0,0 +1,206 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Html {\r
+    using System;\r
+    using System.Collections;\r
+    using System.Collections.Generic;\r
+    using System.Data;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+    using System.Text;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.UI.WebControls;\r
+\r
+    internal static class DefaultDisplayTemplates {\r
+        internal static string BooleanTemplate(HtmlHelper html) {\r
+            bool? value = null;\r
+            if (html.ViewContext.ViewData.Model != null) {\r
+                value = Convert.ToBoolean(html.ViewContext.ViewData.Model, CultureInfo.InvariantCulture);\r
+            }\r
+\r
+            return html.ViewContext.ViewData.ModelMetadata.IsNullableValueType\r
+                        ? BooleanTemplateDropDownList(value)\r
+                        : BooleanTemplateCheckbox(value ?? false);\r
+        }\r
+\r
+        private static string BooleanTemplateCheckbox(bool value) {\r
+            TagBuilder inputTag = new TagBuilder("input");\r
+            inputTag.AddCssClass("check-box");\r
+            inputTag.Attributes["disabled"] = "disabled";\r
+            inputTag.Attributes["type"] = "checkbox";\r
+            if (value) {\r
+                inputTag.Attributes["checked"] = "checked";\r
+            }\r
+\r
+            return inputTag.ToString(TagRenderMode.SelfClosing);\r
+        }\r
+\r
+        private static string BooleanTemplateDropDownList(bool? value) {\r
+            StringBuilder builder = new StringBuilder();\r
+\r
+            TagBuilder selectTag = new TagBuilder("select");\r
+            selectTag.AddCssClass("list-box");\r
+            selectTag.AddCssClass("tri-state");\r
+            selectTag.Attributes["disabled"] = "disabled";\r
+            builder.Append(selectTag.ToString(TagRenderMode.StartTag));\r
+\r
+            foreach (SelectListItem item in DefaultEditorTemplates.TriStateValues(value)) {\r
+                builder.Append(SelectExtensions.ListItemToOption(item));\r
+            }\r
+\r
+            builder.Append(selectTag.ToString(TagRenderMode.EndTag));\r
+            return builder.ToString();\r
+        }\r
+\r
+        internal static string CollectionTemplate(HtmlHelper html) {\r
+            return CollectionTemplate(html, TemplateHelpers.TemplateHelper);\r
+        }\r
+\r
+        internal static string CollectionTemplate(HtmlHelper html, TemplateHelpers.TemplateHelperDelegate templateHelper) {\r
+            object model = html.ViewContext.ViewData.ModelMetadata.Model;\r
+            if (model == null) {\r
+                return String.Empty;\r
+            }\r
+\r
+            IEnumerable collection = model as IEnumerable;\r
+            if (collection == null) {\r
+                throw new InvalidOperationException(\r
+                    String.Format(\r
+                        CultureInfo.CurrentCulture,\r
+                        MvcResources.Templates_TypeMustImplementIEnumerable,\r
+                        model.GetType().FullName\r
+                    )\r
+                );\r
+            }\r
+\r
+            Type typeInCollection = typeof(string);\r
+            Type genericEnumerableType = TypeHelpers.ExtractGenericInterface(collection.GetType(), typeof(IEnumerable<>));\r
+            if (genericEnumerableType != null) {\r
+                typeInCollection = genericEnumerableType.GetGenericArguments()[0];\r
+            }\r
+            bool typeInCollectionIsNullableValueType = TypeHelpers.IsNullableValueType(typeInCollection);\r
+\r
+            string oldPrefix = html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix;\r
+\r
+            try {\r
+                html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = String.Empty;\r
+\r
+                string fieldNameBase = oldPrefix;\r
+                StringBuilder result = new StringBuilder();\r
+                int index = 0;\r
+\r
+                foreach (object item in collection) {\r
+                    Type itemType = typeInCollection;\r
+                    if (item != null && !typeInCollectionIsNullableValueType) {\r
+                        itemType = item.GetType();\r
+                    }\r
+                    ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => item, itemType);\r
+                    string fieldName = String.Format(CultureInfo.InvariantCulture, "{0}[{1}]", fieldNameBase, index++);\r
+                    string output = templateHelper(html, metadata, fieldName, null /* templateName */, DataBoundControlMode.ReadOnly, null /* additionalViewData */);\r
+                    result.Append(output);\r
+                }\r
+\r
+                return result.ToString();\r
+            }\r
+            finally {\r
+                html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = oldPrefix;\r
+            }\r
+        }\r
+\r
+        internal static string DecimalTemplate(HtmlHelper html) {\r
+            if (html.ViewContext.ViewData.TemplateInfo.FormattedModelValue == html.ViewContext.ViewData.ModelMetadata.Model) {\r
+                html.ViewContext.ViewData.TemplateInfo.FormattedModelValue = String.Format(CultureInfo.CurrentCulture, "{0:0.00}", html.ViewContext.ViewData.ModelMetadata.Model);\r
+            }\r
+\r
+            return StringTemplate(html);\r
+        }\r
+\r
+        internal static string EmailAddressTemplate(HtmlHelper html) {\r
+            return String.Format(CultureInfo.InvariantCulture,\r
+                                 "<a href=\"mailto:{0}\">{1}</a>",\r
+                                 html.AttributeEncode(html.ViewContext.ViewData.Model),\r
+                                 html.Encode(html.ViewContext.ViewData.TemplateInfo.FormattedModelValue));\r
+        }\r
+\r
+        internal static string HiddenInputTemplate(HtmlHelper html) {\r
+            if (html.ViewContext.ViewData.ModelMetadata.HideSurroundingHtml) {\r
+                return String.Empty;\r
+            }\r
+            return StringTemplate(html);\r
+        }\r
+\r
+        internal static string HtmlTemplate(HtmlHelper html) {\r
+            return html.ViewContext.ViewData.TemplateInfo.FormattedModelValue.ToString();\r
+        }\r
+\r
+        internal static string ObjectTemplate(HtmlHelper html) {\r
+            return ObjectTemplate(html, TemplateHelpers.TemplateHelper);\r
+        }\r
+\r
+        internal static string ObjectTemplate(HtmlHelper html, TemplateHelpers.TemplateHelperDelegate templateHelper) {\r
+            ViewDataDictionary viewData = html.ViewContext.ViewData;\r
+            TemplateInfo templateInfo = viewData.TemplateInfo;\r
+            ModelMetadata modelMetadata = viewData.ModelMetadata;\r
+            StringBuilder builder = new StringBuilder();\r
+\r
+            if (modelMetadata.Model == null) {    // DDB #225237\r
+                return modelMetadata.NullDisplayText;\r
+            }\r
+\r
+            if (templateInfo.TemplateDepth > 1) {    // DDB #224751\r
+                return modelMetadata.SimpleDisplayText;\r
+            }\r
+\r
+            foreach (ModelMetadata propertyMetadata in modelMetadata.Properties.Where(pm => ShouldShow(pm, templateInfo))) {\r
+                if (!propertyMetadata.HideSurroundingHtml) {\r
+                    string label = propertyMetadata.GetDisplayName();\r
+                    if (!String.IsNullOrEmpty(label)) {\r
+                        builder.AppendFormat(CultureInfo.InvariantCulture, "<div class=\"display-label\">{0}</div>", label);\r
+                        builder.AppendLine();\r
+                    }\r
+\r
+                    builder.Append("<div class=\"display-field\">");\r
+                }\r
+\r
+                builder.Append(templateHelper(html, propertyMetadata, propertyMetadata.PropertyName, null /* templateName */, DataBoundControlMode.ReadOnly, null /* additionalViewData */));\r
+\r
+                if (!propertyMetadata.HideSurroundingHtml) {\r
+                    builder.AppendLine("</div>");\r
+                }\r
+            }\r
+\r
+            return builder.ToString();\r
+        }\r
+\r
+        private static bool ShouldShow(ModelMetadata metadata, TemplateInfo templateInfo) {\r
+            return\r
+                metadata.ShowForDisplay\r
+#if false
+                && metadata.ModelType != typeof(EntityState)\r
+#endif
+                && !metadata.IsComplexType\r
+                && !templateInfo.Visited(metadata);\r
+        }\r
+\r
+        internal static string StringTemplate(HtmlHelper html) {\r
+            return html.Encode(html.ViewContext.ViewData.TemplateInfo.FormattedModelValue);\r
+        }\r
+\r
+        internal static string UrlTemplate(HtmlHelper html) {\r
+            return String.Format(CultureInfo.InvariantCulture,\r
+                                 "<a href=\"{0}\">{1}</a>",\r
+                                 html.AttributeEncode(html.ViewContext.ViewData.Model),\r
+                                 html.Encode(html.ViewContext.ViewData.TemplateInfo.FormattedModelValue));\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/DefaultEditorTemplates.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/DefaultEditorTemplates.cs
new file mode 100644 (file)
index 0000000..a478dbc
--- /dev/null
@@ -0,0 +1,215 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Html {\r
+    using System;\r
+    using System.Collections;\r
+    using System.Collections.Generic;\r
+    using System.Data;\r
+    using System.Data.Linq;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+    using System.Text;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.UI.WebControls;\r
+\r
+    internal static class DefaultEditorTemplates {\r
+        internal static string BooleanTemplate(HtmlHelper html) {\r
+            bool? value = null;\r
+            if (html.ViewContext.ViewData.Model != null) {\r
+                value = Convert.ToBoolean(html.ViewContext.ViewData.Model, CultureInfo.InvariantCulture);\r
+            }\r
+\r
+            return html.ViewContext.ViewData.ModelMetadata.IsNullableValueType\r
+                        ? BooleanTemplateDropDownList(html, value)\r
+                        : BooleanTemplateCheckbox(html, value ?? false);\r
+        }\r
+\r
+        private static string BooleanTemplateCheckbox(HtmlHelper html, bool value) {\r
+            return html.CheckBox(String.Empty, value, CreateHtmlAttributes("check-box")).ToHtmlString();\r
+        }\r
+\r
+        private static string BooleanTemplateDropDownList(HtmlHelper html, bool? value) {\r
+            return html.DropDownList(String.Empty, TriStateValues(value), CreateHtmlAttributes("list-box tri-state")).ToHtmlString();\r
+\r
+        }\r
+\r
+        internal static string CollectionTemplate(HtmlHelper html) {\r
+            return CollectionTemplate(html, TemplateHelpers.TemplateHelper);\r
+        }\r
+\r
+        internal static string CollectionTemplate(HtmlHelper html, TemplateHelpers.TemplateHelperDelegate templateHelper) {\r
+            object model = html.ViewContext.ViewData.ModelMetadata.Model;\r
+            if (model == null) {\r
+                return String.Empty;\r
+            }\r
+\r
+            IEnumerable collection = model as IEnumerable;\r
+            if (collection == null) {\r
+                throw new InvalidOperationException(\r
+                    String.Format(\r
+                        CultureInfo.CurrentCulture,\r
+                        MvcResources.Templates_TypeMustImplementIEnumerable,\r
+                        model.GetType().FullName\r
+                    )\r
+                );\r
+            }\r
+\r
+            Type typeInCollection = typeof(string);\r
+            Type genericEnumerableType = TypeHelpers.ExtractGenericInterface(collection.GetType(), typeof(IEnumerable<>));\r
+            if (genericEnumerableType != null) {\r
+                typeInCollection = genericEnumerableType.GetGenericArguments()[0];\r
+            }\r
+            bool typeInCollectionIsNullableValueType = TypeHelpers.IsNullableValueType(typeInCollection);\r
+\r
+            string oldPrefix = html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix;\r
+\r
+            try {\r
+                html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = String.Empty;\r
+\r
+                string fieldNameBase = oldPrefix;\r
+                StringBuilder result = new StringBuilder();\r
+                int index = 0;\r
+\r
+                foreach (object item in collection) {\r
+                    Type itemType = typeInCollection;\r
+                    if (item != null && !typeInCollectionIsNullableValueType) {\r
+                        itemType = item.GetType();\r
+                    }\r
+                    ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => item, itemType);\r
+                    string fieldName = String.Format(CultureInfo.InvariantCulture, "{0}[{1}]", fieldNameBase, index++);\r
+                    string output = templateHelper(html, metadata, fieldName, null /* templateName */, DataBoundControlMode.Edit, null /* additionalViewData */);\r
+                    result.Append(output);\r
+                }\r
+\r
+                return result.ToString();\r
+            }\r
+            finally {\r
+                html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = oldPrefix;\r
+            }\r
+        }\r
+\r
+        internal static string DecimalTemplate(HtmlHelper html) {\r
+            if (html.ViewContext.ViewData.TemplateInfo.FormattedModelValue == html.ViewContext.ViewData.ModelMetadata.Model) {\r
+                html.ViewContext.ViewData.TemplateInfo.FormattedModelValue = String.Format(CultureInfo.CurrentCulture, "{0:0.00}", html.ViewContext.ViewData.ModelMetadata.Model);\r
+            }\r
+\r
+            return StringTemplate(html);\r
+        }\r
+\r
+        internal static string HiddenInputTemplate(HtmlHelper html) {\r
+            string result;\r
+\r
+            if (html.ViewContext.ViewData.ModelMetadata.HideSurroundingHtml) {\r
+                result = String.Empty;\r
+            }\r
+            else {\r
+                result = DefaultDisplayTemplates.StringTemplate(html);\r
+            }\r
+\r
+            object model = html.ViewContext.ViewData.Model;\r
+\r
+            Binary modelAsBinary = model as Binary;\r
+            if (modelAsBinary != null) {\r
+                model = Convert.ToBase64String(modelAsBinary.ToArray());\r
+            }\r
+            else {\r
+                byte[] modelAsByteArray = model as byte[];\r
+                if (modelAsByteArray != null) {\r
+                    model = Convert.ToBase64String(modelAsByteArray);\r
+                }\r
+            }\r
+\r
+            result += html.Hidden(String.Empty, model).ToHtmlString();\r
+            return result;\r
+        }\r
+\r
+        internal static string MultilineTextTemplate(HtmlHelper html) {\r
+            return html.TextArea(String.Empty,\r
+                                 html.ViewContext.ViewData.TemplateInfo.FormattedModelValue.ToString(),\r
+                                 0 /* rows */, 0 /* columns */,\r
+                                 CreateHtmlAttributes("text-box multi-line")).ToHtmlString();\r
+        }\r
+\r
+        private static IDictionary<string, object> CreateHtmlAttributes(string className) {\r
+            return new Dictionary<string, object>() {\r
+                { "class", className }\r
+            };\r
+        }\r
+\r
+        internal static string ObjectTemplate(HtmlHelper html) {\r
+            return ObjectTemplate(html, TemplateHelpers.TemplateHelper);\r
+        }\r
+\r
+        internal static string ObjectTemplate(HtmlHelper html, TemplateHelpers.TemplateHelperDelegate templateHelper) {\r
+            ViewDataDictionary viewData = html.ViewContext.ViewData;\r
+            TemplateInfo templateInfo = viewData.TemplateInfo;\r
+            ModelMetadata modelMetadata = viewData.ModelMetadata;\r
+            StringBuilder builder = new StringBuilder();\r
+\r
+            if (templateInfo.TemplateDepth > 1) {    // DDB #224751\r
+                return modelMetadata.Model == null ? modelMetadata.NullDisplayText : modelMetadata.SimpleDisplayText;\r
+            }\r
+\r
+            foreach (ModelMetadata propertyMetadata in modelMetadata.Properties.Where(pm => ShouldShow(pm, templateInfo))) {\r
+                if (!propertyMetadata.HideSurroundingHtml) {\r
+                    string label = LabelExtensions.LabelHelper(html, propertyMetadata, propertyMetadata.PropertyName).ToHtmlString();\r
+                    if (!String.IsNullOrEmpty(label)) {\r
+                        builder.AppendFormat(CultureInfo.InvariantCulture, "<div class=\"editor-label\">{0}</div>\r\n", label);\r
+                    }\r
+\r
+                    builder.Append("<div class=\"editor-field\">");\r
+                }\r
+\r
+                builder.Append(templateHelper(html, propertyMetadata, propertyMetadata.PropertyName, null /* templateName */, DataBoundControlMode.Edit, null /* additionalViewData */));\r
+\r
+                if (!propertyMetadata.HideSurroundingHtml) {\r
+                    builder.Append(" ");\r
+                    builder.Append(html.ValidationMessage(propertyMetadata.PropertyName));\r
+                    builder.Append("</div>\r\n");\r
+                }\r
+            }\r
+\r
+            return builder.ToString();\r
+        }\r
+\r
+        internal static string PasswordTemplate(HtmlHelper html) {\r
+            return html.Password(String.Empty,\r
+                                 html.ViewContext.ViewData.TemplateInfo.FormattedModelValue,\r
+                                 CreateHtmlAttributes("text-box single-line password")).ToHtmlString();\r
+        }\r
+\r
+        private static bool ShouldShow(ModelMetadata metadata, TemplateInfo templateInfo) {\r
+            return\r
+                metadata.ShowForEdit\r
+#if false
+                && metadata.ModelType != typeof(EntityState)\r
+#endif
+                && !metadata.IsComplexType\r
+                && !templateInfo.Visited(metadata);\r
+        }\r
+\r
+        internal static string StringTemplate(HtmlHelper html) {\r
+            return html.TextBox(String.Empty,\r
+                                html.ViewContext.ViewData.TemplateInfo.FormattedModelValue,\r
+                                CreateHtmlAttributes("text-box single-line")).ToHtmlString();\r
+        }\r
+\r
+        internal static List<SelectListItem> TriStateValues(bool? value) {\r
+            return new List<SelectListItem> {\r
+                new SelectListItem { Text = MvcResources.Common_TriState_NotSet, Value = String.Empty, Selected = !value.HasValue },\r
+                new SelectListItem { Text = MvcResources.Common_TriState_True, Value = "true", Selected = value.HasValue && value.Value },\r
+                new SelectListItem { Text = MvcResources.Common_TriState_False, Value = "false", Selected = value.HasValue && !value.Value },\r
+            };\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/DisplayExtensions.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/DisplayExtensions.cs
new file mode 100644 (file)
index 0000000..372caf0
--- /dev/null
@@ -0,0 +1,102 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Html {\r
+    using System.Linq.Expressions;\r
+    using System.Web.UI.WebControls;\r
+\r
+    public static class DisplayExtensions {\r
+        public static MvcHtmlString Display(this HtmlHelper html, string expression) {\r
+            return TemplateHelpers.Template(html, expression, null /* templateName */, null /* htmlFieldName */, DataBoundControlMode.ReadOnly, null /* additionalViewData */);\r
+        }\r
+\r
+        public static MvcHtmlString Display(this HtmlHelper html, string expression, object additionalViewData) {\r
+            return TemplateHelpers.Template(html, expression, null /* templateName */, null /* htmlFieldName */, DataBoundControlMode.ReadOnly, additionalViewData);\r
+        }\r
+\r
+        public static MvcHtmlString Display(this HtmlHelper html, string expression, string templateName) {\r
+            return TemplateHelpers.Template(html, expression, templateName, null /* htmlFieldName */, DataBoundControlMode.ReadOnly, null /* additionalViewData */);\r
+        }\r
+\r
+        public static MvcHtmlString Display(this HtmlHelper html, string expression, string templateName, object additionalViewData) {\r
+            return TemplateHelpers.Template(html, expression, templateName, null /* htmlFieldName */, DataBoundControlMode.ReadOnly, additionalViewData);\r
+        }\r
+\r
+        public static MvcHtmlString Display(this HtmlHelper html, string expression, string templateName, string htmlFieldName) {\r
+            return TemplateHelpers.Template(html, expression, templateName, htmlFieldName, DataBoundControlMode.ReadOnly, null /* additionalViewData */);\r
+        }\r
+\r
+        public static MvcHtmlString Display(this HtmlHelper html, string expression, string templateName, string htmlFieldName, object additionalViewData) {\r
+            return TemplateHelpers.Template(html, expression, templateName, htmlFieldName, DataBoundControlMode.ReadOnly, additionalViewData);\r
+        }\r
+\r
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",\r
+            Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString DisplayFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) {\r
+            return TemplateHelpers.TemplateFor(html, expression, null /* templateName */, null /* htmlFieldName */, DataBoundControlMode.ReadOnly, null /* additionalViewData */);\r
+        }\r
+\r
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",\r
+            Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString DisplayFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object additionalViewData) {\r
+            return TemplateHelpers.TemplateFor(html, expression, null /* templateName */, null /* htmlFieldName */, DataBoundControlMode.ReadOnly, additionalViewData);\r
+        }\r
+\r
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",\r
+            Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString DisplayFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName) {\r
+            return TemplateHelpers.TemplateFor(html, expression, templateName, null /* htmlFieldName */, DataBoundControlMode.ReadOnly, null /* additionalViewData */);\r
+        }\r
+\r
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",\r
+            Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString DisplayFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName, object additionalViewData) {\r
+            return TemplateHelpers.TemplateFor(html, expression, templateName, null /* htmlFieldName */, DataBoundControlMode.ReadOnly, additionalViewData);\r
+        }\r
+\r
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",\r
+            Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString DisplayFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName, string htmlFieldName) {\r
+            return TemplateHelpers.TemplateFor(html, expression, templateName, htmlFieldName, DataBoundControlMode.ReadOnly, null /* additionalViewData */);\r
+        }\r
+\r
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",\r
+            Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString DisplayFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName, string htmlFieldName, object additionalViewData) {\r
+            return TemplateHelpers.TemplateFor(html, expression, templateName, htmlFieldName, DataBoundControlMode.ReadOnly, additionalViewData);\r
+        }\r
+\r
+        public static MvcHtmlString DisplayForModel(this HtmlHelper html) {\r
+            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, String.Empty, null /* templateName */, DataBoundControlMode.ReadOnly, null /* additionalViewData */));\r
+        }\r
+\r
+        public static MvcHtmlString DisplayForModel(this HtmlHelper html, object additionalViewData) {\r
+            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, String.Empty, null /* templateName */, DataBoundControlMode.ReadOnly, additionalViewData));\r
+        }\r
+\r
+        public static MvcHtmlString DisplayForModel(this HtmlHelper html, string templateName) {\r
+            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, String.Empty, templateName, DataBoundControlMode.ReadOnly, null /* additionalViewData */));\r
+        }\r
+\r
+        public static MvcHtmlString DisplayForModel(this HtmlHelper html, string templateName, object additionalViewData) {\r
+            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, String.Empty, templateName, DataBoundControlMode.ReadOnly,   additionalViewData ));\r
+        }\r
+\r
+        public static MvcHtmlString DisplayForModel(this HtmlHelper html, string templateName, string htmlFieldName) {\r
+            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, htmlFieldName, templateName, DataBoundControlMode.ReadOnly, null /* additionalViewData */));\r
+        }\r
+\r
+        public static MvcHtmlString DisplayForModel(this HtmlHelper html, string templateName, string htmlFieldName, object additionalViewData) {\r
+            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, htmlFieldName, templateName, DataBoundControlMode.ReadOnly, additionalViewData));\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/DisplayTextExtensions.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/DisplayTextExtensions.cs
new file mode 100644 (file)
index 0000000..272ab0e
--- /dev/null
@@ -0,0 +1,32 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Html {\r
+    using System;\r
+    using System.Linq.Expressions;\r
+\r
+    public static class DisplayTextExtensions {\r
+        public static MvcHtmlString DisplayText(this HtmlHelper html, string name) {\r
+            return DisplayTextHelper(ModelMetadata.FromStringExpression(name, html.ViewContext.ViewData));\r
+        }\r
+\r
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",\r
+            Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString DisplayTextFor<TModel, TResult>(this HtmlHelper<TModel> html, Expression<Func<TModel, TResult>> expression) {\r
+            return DisplayTextHelper(ModelMetadata.FromLambdaExpression(expression, html.ViewData));\r
+        }\r
+\r
+        private static MvcHtmlString DisplayTextHelper(ModelMetadata metadata) {\r
+            return MvcHtmlString.Create(metadata.SimpleDisplayText);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/EditorExtensions.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/EditorExtensions.cs
new file mode 100644 (file)
index 0000000..b022f5c
--- /dev/null
@@ -0,0 +1,103 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Html {\r
+    using System;\r
+    using System.Linq.Expressions;\r
+    using System.Web.UI.WebControls;\r
+\r
+    public static class EditorExtensions {\r
+        public static MvcHtmlString Editor(this HtmlHelper html, string expression) {\r
+            return TemplateHelpers.Template(html, expression, null /* templateName */, null /* htmlFieldName */, DataBoundControlMode.Edit, null /* additionalViewData */);\r
+        }\r
+\r
+        public static MvcHtmlString Editor(this HtmlHelper html, string expression, object additionalViewData) {\r
+            return TemplateHelpers.Template(html, expression, null /* templateName */, null /* htmlFieldName */, DataBoundControlMode.Edit, additionalViewData);\r
+        }\r
+\r
+        public static MvcHtmlString Editor(this HtmlHelper html, string expression, string templateName) {\r
+            return TemplateHelpers.Template(html, expression, templateName, null /* htmlFieldName */, DataBoundControlMode.Edit, null /* additionalViewData */);\r
+        }\r
+\r
+        public static MvcHtmlString Editor(this HtmlHelper html, string expression, string templateName, object additionalViewData) {\r
+            return TemplateHelpers.Template(html, expression, templateName, null /* htmlFieldName */, DataBoundControlMode.Edit, additionalViewData);\r
+        }\r
+\r
+        public static MvcHtmlString Editor(this HtmlHelper html, string expression, string templateName, string htmlFieldName) {\r
+            return TemplateHelpers.Template(html, expression, templateName, htmlFieldName, DataBoundControlMode.Edit, null /* additionalViewData */);\r
+        }\r
+\r
+        public static MvcHtmlString Editor(this HtmlHelper html, string expression, string templateName, string htmlFieldName, object additionalViewData) {\r
+            return TemplateHelpers.Template(html, expression, templateName, htmlFieldName, DataBoundControlMode.Edit, additionalViewData);\r
+        }\r
+\r
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",\r
+            Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString EditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) {\r
+            return TemplateHelpers.TemplateFor(html, expression, null /* templateName */, null /* htmlFieldName */, DataBoundControlMode.Edit, null /* additionalViewData */);\r
+        }\r
+\r
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",\r
+            Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString EditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object additionalViewData) {\r
+            return TemplateHelpers.TemplateFor(html, expression, null /* templateName */, null /* htmlFieldName */, DataBoundControlMode.Edit, additionalViewData);\r
+        }\r
+\r
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",\r
+            Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString EditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName) {\r
+            return TemplateHelpers.TemplateFor(html, expression, templateName, null /* htmlFieldName */, DataBoundControlMode.Edit, null /* additionalViewData */);\r
+        }\r
+\r
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",\r
+            Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString EditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName, object additionalViewData) {\r
+            return TemplateHelpers.TemplateFor(html, expression, templateName, null /* htmlFieldName */, DataBoundControlMode.Edit, additionalViewData);\r
+        }\r
+\r
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",\r
+            Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString EditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName, string htmlFieldName) {\r
+            return TemplateHelpers.TemplateFor(html, expression, templateName, htmlFieldName, DataBoundControlMode.Edit, null /* additionalViewData */);\r
+        }\r
+\r
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",\r
+            Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString EditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName, string htmlFieldName, object additionalViewData) {\r
+            return TemplateHelpers.TemplateFor(html, expression, templateName, htmlFieldName, DataBoundControlMode.Edit, additionalViewData);\r
+        }\r
+\r
+        public static MvcHtmlString EditorForModel(this HtmlHelper html) {\r
+            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, String.Empty, null /* templateName */, DataBoundControlMode.Edit, null /* additionalViewData */));\r
+        }\r
+\r
+        public static MvcHtmlString EditorForModel(this HtmlHelper html, object additionalViewData) {\r
+            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, String.Empty, null /* templateName */, DataBoundControlMode.Edit, additionalViewData));\r
+        }\r
+\r
+        public static MvcHtmlString EditorForModel(this HtmlHelper html, string templateName) {\r
+            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, String.Empty, templateName, DataBoundControlMode.Edit, null /* additionalViewData */));\r
+        }\r
+\r
+        public static MvcHtmlString EditorForModel(this HtmlHelper html, string templateName, object additionalViewData) {\r
+            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, String.Empty, templateName, DataBoundControlMode.Edit, additionalViewData));\r
+        }\r
+\r
+        public static MvcHtmlString EditorForModel(this HtmlHelper html, string templateName, string htmlFieldName) {\r
+            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, htmlFieldName, templateName, DataBoundControlMode.Edit, null /* additionalViewData */));\r
+        }\r
+\r
+        public static MvcHtmlString EditorForModel(this HtmlHelper html, string templateName, string htmlFieldName, object additionalViewData) {\r
+            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, htmlFieldName, templateName, DataBoundControlMode.Edit, additionalViewData));\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/FormExtensions.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/FormExtensions.cs
new file mode 100644 (file)
index 0000000..b5df159
--- /dev/null
@@ -0,0 +1,152 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Html {\r
+    using System.Collections.Generic;\r
+    using System.Web.Routing;\r
+    using System.Globalization;\r
+\r
+    public static class FormExtensions {\r
+        public static MvcForm BeginForm(this HtmlHelper htmlHelper) {\r
+            // generates <form action="{current url}" method="post">...</form>\r
+            string formAction = htmlHelper.ViewContext.HttpContext.Request.RawUrl;\r
+            return FormHelper(htmlHelper, formAction, FormMethod.Post, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcForm BeginForm(this HtmlHelper htmlHelper, object routeValues) {\r
+            return BeginForm(htmlHelper, null, null, new RouteValueDictionary(routeValues), FormMethod.Post, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcForm BeginForm(this HtmlHelper htmlHelper, RouteValueDictionary routeValues) {\r
+            return BeginForm(htmlHelper, null, null, routeValues, FormMethod.Post, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName) {\r
+            return BeginForm(htmlHelper, actionName, controllerName, new RouteValueDictionary(), FormMethod.Post, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues) {\r
+            return BeginForm(htmlHelper, actionName, controllerName, new RouteValueDictionary(routeValues), FormMethod.Post, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues) {\r
+            return BeginForm(htmlHelper, actionName, controllerName, routeValues, FormMethod.Post, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, FormMethod method) {\r
+            return BeginForm(htmlHelper, actionName, controllerName, new RouteValueDictionary(), method, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues, FormMethod method) {\r
+            return BeginForm(htmlHelper, actionName, controllerName, new RouteValueDictionary(routeValues), method, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues, FormMethod method) {\r
+            return BeginForm(htmlHelper, actionName, controllerName, routeValues, method, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, FormMethod method, object htmlAttributes) {\r
+            return BeginForm(htmlHelper, actionName, controllerName, new RouteValueDictionary(), method, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, FormMethod method, IDictionary<string, object> htmlAttributes) {\r
+            return BeginForm(htmlHelper, actionName, controllerName, new RouteValueDictionary(), method, htmlAttributes);\r
+        }\r
+\r
+        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues, FormMethod method, object htmlAttributes) {\r
+            return BeginForm(htmlHelper, actionName, controllerName, new RouteValueDictionary(routeValues), method, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues, FormMethod method, IDictionary<string, object> htmlAttributes) {\r
+            string formAction = UrlHelper.GenerateUrl(null /* routeName */, actionName, controllerName, routeValues, htmlHelper.RouteCollection, htmlHelper.ViewContext.RequestContext, true /* includeImplicitMvcValues */);\r
+            return FormHelper(htmlHelper, formAction, method, htmlAttributes);\r
+        }\r
+\r
+        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, object routeValues) {\r
+            return BeginRouteForm(htmlHelper, null /* routeName */, new RouteValueDictionary(routeValues), FormMethod.Post, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, RouteValueDictionary routeValues) {\r
+            return BeginRouteForm(htmlHelper, null /* routeName */, routeValues, FormMethod.Post, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName) {\r
+            return BeginRouteForm(htmlHelper, routeName, new RouteValueDictionary(), FormMethod.Post, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName, object routeValues) {\r
+            return BeginRouteForm(htmlHelper, routeName, new RouteValueDictionary(routeValues), FormMethod.Post, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName, RouteValueDictionary routeValues) {\r
+            return BeginRouteForm(htmlHelper, routeName, routeValues, FormMethod.Post, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName, FormMethod method) {\r
+            return BeginRouteForm(htmlHelper, routeName, new RouteValueDictionary(), method, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName, object routeValues, FormMethod method) {\r
+            return BeginRouteForm(htmlHelper, routeName, new RouteValueDictionary(routeValues), method, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName, RouteValueDictionary routeValues, FormMethod method) {\r
+            return BeginRouteForm(htmlHelper, routeName, routeValues, method, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName, FormMethod method, object htmlAttributes) {\r
+            return BeginRouteForm(htmlHelper, routeName, new RouteValueDictionary(), method, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName, FormMethod method, IDictionary<string, object> htmlAttributes) {\r
+            return BeginRouteForm(htmlHelper, routeName, new RouteValueDictionary(), method, htmlAttributes);\r
+        }\r
+\r
+        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName, object routeValues, FormMethod method, object htmlAttributes) {\r
+            return BeginRouteForm(htmlHelper, routeName, new RouteValueDictionary(routeValues), method, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName, RouteValueDictionary routeValues, FormMethod method, IDictionary<string, object> htmlAttributes) {\r
+            string formAction = UrlHelper.GenerateUrl(routeName, null, null, routeValues, htmlHelper.RouteCollection, htmlHelper.ViewContext.RequestContext, false /* includeImplicitMvcValues */);\r
+            return FormHelper(htmlHelper, formAction, method, htmlAttributes);\r
+        }\r
+\r
+        public static void EndForm(this HtmlHelper htmlHelper) {\r
+            htmlHelper.ViewContext.Writer.Write("</form>");\r
+            htmlHelper.ViewContext.OutputClientValidation();\r
+        }\r
+\r
+        private static MvcForm FormHelper(this HtmlHelper htmlHelper, string formAction, FormMethod method, IDictionary<string, object> htmlAttributes) {\r
+            TagBuilder tagBuilder = new TagBuilder("form");\r
+            tagBuilder.MergeAttributes(htmlAttributes);\r
+            // action is implicitly generated, so htmlAttributes take precedence.\r
+            tagBuilder.MergeAttribute("action", formAction);\r
+            // method is an explicit parameter, so it takes precedence over the htmlAttributes.\r
+            tagBuilder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true);\r
+\r
+            if (htmlHelper.ViewContext.ClientValidationEnabled) {\r
+                // forms must have an ID for client validation\r
+                tagBuilder.GenerateId(htmlHelper.ViewContext.FormIdGenerator());\r
+            }\r
+\r
+            htmlHelper.ViewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.StartTag));\r
+            MvcForm theForm = new MvcForm(htmlHelper.ViewContext);\r
+\r
+            if (htmlHelper.ViewContext.ClientValidationEnabled) {\r
+                htmlHelper.ViewContext.FormContext.FormId = tagBuilder.Attributes["id"];\r
+            }\r
+\r
+            return theForm;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/InputExtensions.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/InputExtensions.cs
new file mode 100644 (file)
index 0000000..5d56f83
--- /dev/null
@@ -0,0 +1,398 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Html {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Data.Linq;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.Linq.Expressions;\r
+    using System.Text;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.Routing;\r
+\r
+    public static class InputExtensions {\r
+        // CheckBox\r
+\r
+        public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name) {\r
+            return CheckBox(htmlHelper, name, (object)null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, bool isChecked) {\r
+            return CheckBox(htmlHelper, name, isChecked, (object)null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, bool isChecked, object htmlAttributes) {\r
+            return CheckBox(htmlHelper, name, isChecked, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, object htmlAttributes) {\r
+            return CheckBox(htmlHelper, name, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, IDictionary<string, object> htmlAttributes) {\r
+            return CheckBoxHelper(htmlHelper, name, null /* isChecked */, htmlAttributes);\r
+        }\r
+\r
+        public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, bool isChecked, IDictionary<string, object> htmlAttributes) {\r
+            return CheckBoxHelper(htmlHelper, name, isChecked, htmlAttributes);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression) {\r
+            return CheckBoxFor(htmlHelper, expression, null /* htmlAttributes */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression, object htmlAttributes) {\r
+            return CheckBoxFor(htmlHelper, expression, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression, IDictionary<string, object> htmlAttributes) {\r
+            if (expression == null) {\r
+                throw new ArgumentNullException("expression");\r
+            }\r
+\r
+            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);\r
+            bool? isChecked = null;\r
+            if (metadata.Model != null) {\r
+                bool modelChecked;\r
+                if (Boolean.TryParse(metadata.Model.ToString(), out modelChecked)) {\r
+                    isChecked = modelChecked;\r
+                }\r
+            }\r
+\r
+            return CheckBoxHelper(htmlHelper, ExpressionHelper.GetExpressionText(expression), isChecked, htmlAttributes);\r
+        }\r
+\r
+        private static MvcHtmlString CheckBoxHelper(HtmlHelper htmlHelper, string name, bool? isChecked, IDictionary<string, object> htmlAttributes) {\r
+            RouteValueDictionary attributes =\r
+                htmlAttributes == null ? new RouteValueDictionary()\r
+                                       : new RouteValueDictionary(htmlAttributes);\r
+\r
+            bool explicitValue = isChecked.HasValue;\r
+            if (explicitValue) {\r
+                attributes.Remove("checked");    // Explicit value must override dictionary\r
+            }\r
+\r
+            return InputHelper(htmlHelper, InputType.CheckBox, name, "true", !explicitValue /* useViewData */, isChecked ?? false, true /* setId */, false /* isExplicitValue */, attributes);\r
+        }\r
+\r
+        // Hidden\r
+\r
+        public static MvcHtmlString Hidden(this HtmlHelper htmlHelper, string name) {\r
+            return Hidden(htmlHelper, name, null /* value */, null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcHtmlString Hidden(this HtmlHelper htmlHelper, string name, object value) {\r
+            return Hidden(htmlHelper, name, value, null /* hmtlAttributes */);\r
+        }\r
+\r
+        public static MvcHtmlString Hidden(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes) {\r
+            return Hidden(htmlHelper, name, value, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString Hidden(this HtmlHelper htmlHelper, string name, object value, IDictionary<string, object> htmlAttributes) {\r
+            return HiddenHelper(htmlHelper,\r
+                                value,\r
+                                value == null /* useViewData */,\r
+                                name,\r
+                                htmlAttributes);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) {\r
+            return HiddenFor(htmlHelper, expression, (IDictionary<string, object>)null);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes) {\r
+            return HiddenFor(htmlHelper, expression, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes) {\r
+            return HiddenHelper(htmlHelper,\r
+                                ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model,\r
+                                false,\r
+                                ExpressionHelper.GetExpressionText(expression),\r
+                                htmlAttributes);\r
+        }\r
+\r
+        private static MvcHtmlString HiddenHelper(HtmlHelper htmlHelper, object value, bool useViewData, string expression, IDictionary<string, object> htmlAttributes) {\r
+            Binary binaryValue = value as Binary;\r
+            if (binaryValue != null) {\r
+                value = binaryValue.ToArray();\r
+            }\r
+\r
+            byte[] byteArrayValue = value as byte[];\r
+            if (byteArrayValue != null) {\r
+                value = Convert.ToBase64String(byteArrayValue);\r
+            }\r
+\r
+            return InputHelper(htmlHelper, InputType.Hidden, expression, value, useViewData, false /* isChecked */, true /* setId */, true /* isExplicitValue */, htmlAttributes);\r
+        }\r
+\r
+        // Password\r
+\r
+        public static MvcHtmlString Password(this HtmlHelper htmlHelper, string name) {\r
+            return Password(htmlHelper, name, null /* value */);\r
+        }\r
+\r
+        public static MvcHtmlString Password(this HtmlHelper htmlHelper, string name, object value) {\r
+            return Password(htmlHelper, name, value, null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcHtmlString Password(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes) {\r
+            return Password(htmlHelper, name, value, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString Password(this HtmlHelper htmlHelper, string name, object value, IDictionary<string, object> htmlAttributes) {\r
+            return PasswordHelper(htmlHelper, name, value, htmlAttributes);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString PasswordFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) {\r
+            return PasswordFor(htmlHelper, expression, null /* htmlAttributes */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString PasswordFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes) {\r
+            return PasswordFor(htmlHelper, expression, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Users cannot use anonymous methods with the LambdaExpression type")]\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString PasswordFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes) {\r
+            if (expression == null) {\r
+                throw new ArgumentNullException("expression");\r
+            }\r
+\r
+            return PasswordHelper(htmlHelper,\r
+                                  ExpressionHelper.GetExpressionText(expression),\r
+                                  null /* value */,\r
+                                  htmlAttributes);\r
+        }\r
+\r
+        private static MvcHtmlString PasswordHelper(HtmlHelper htmlHelper, string name, object value, IDictionary<string, object> htmlAttributes) {\r
+            return InputHelper(htmlHelper, InputType.Password, name, value, false /* useViewData */, false /* isChecked */, true /* setId */, true /* isExplicitValue */, htmlAttributes);\r
+        }\r
+\r
+        // RadioButton\r
+\r
+        public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, object value) {\r
+            return RadioButton(htmlHelper, name, value, (object)null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes) {\r
+            return RadioButton(htmlHelper, name, value, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, object value, IDictionary<string, object> htmlAttributes) {\r
+            // Determine whether or not to render the checked attribute based on the contents of ViewData.\r
+            string valueString = Convert.ToString(value, CultureInfo.CurrentCulture);\r
+            bool isChecked = (!String.IsNullOrEmpty(name)) && (String.Equals(htmlHelper.EvalString(name), valueString, StringComparison.OrdinalIgnoreCase));\r
+            // checked attributes is implicit, so we need to ensure that the dictionary takes precedence.\r
+            RouteValueDictionary attributes = htmlAttributes == null ? new RouteValueDictionary() : new RouteValueDictionary(htmlAttributes);\r
+            if (attributes.ContainsKey("checked")) {\r
+                return InputHelper(htmlHelper, InputType.Radio, name, value, false, false, true, true /* isExplicitValue */, attributes);\r
+            }\r
+\r
+            return RadioButton(htmlHelper, name, value, isChecked, htmlAttributes);\r
+        }\r
+\r
+        public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, object value, bool isChecked) {\r
+            return RadioButton(htmlHelper, name, value, isChecked, (object)null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, object value, bool isChecked, object htmlAttributes) {\r
+            return RadioButton(htmlHelper, name, value, isChecked, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, object value, bool isChecked, IDictionary<string, object> htmlAttributes) {\r
+            if (value == null) {\r
+                throw new ArgumentNullException("value");\r
+            }\r
+            // checked attribute is an explicit parameter so it takes precedence.\r
+            RouteValueDictionary attributes = htmlAttributes == null ? new RouteValueDictionary() : new RouteValueDictionary(htmlAttributes);\r
+            attributes.Remove("checked");\r
+            return InputHelper(htmlHelper, InputType.Radio, name, value, false, isChecked, true, true /* isExplicitValue */, attributes);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString RadioButtonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value) {\r
+            return RadioButtonFor(htmlHelper, expression, value, null /* htmlAttributes */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString RadioButtonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, object htmlAttributes) {\r
+            return RadioButtonFor(htmlHelper, expression, value, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString RadioButtonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, IDictionary<string, object> htmlAttributes) {\r
+            return RadioButtonHelper(htmlHelper,\r
+                                     ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model,\r
+                                     ExpressionHelper.GetExpressionText(expression),\r
+                                     value,\r
+                                     null /* isChecked */,\r
+                                     htmlAttributes);\r
+        }\r
+\r
+        private static MvcHtmlString RadioButtonHelper(HtmlHelper htmlHelper, object model, string name, object value, bool? isChecked, IDictionary<string, object> htmlAttributes) {\r
+            if (value == null) {\r
+                throw new ArgumentNullException("value");\r
+            }\r
+\r
+            RouteValueDictionary attributes =\r
+                htmlAttributes == null ? new RouteValueDictionary()\r
+                                       : new RouteValueDictionary(htmlAttributes);\r
+\r
+            bool explicitValue = isChecked.HasValue;\r
+            if (explicitValue) {\r
+                attributes.Remove("checked");    // Explicit value must override dictionary\r
+            }\r
+            else {\r
+                string valueString = Convert.ToString(value, CultureInfo.CurrentCulture);\r
+                isChecked = model != null &&\r
+                            !String.IsNullOrEmpty(name) &&\r
+                            String.Equals(model.ToString(), valueString, StringComparison.OrdinalIgnoreCase);\r
+            }\r
+\r
+            return InputHelper(htmlHelper, InputType.Radio, name, value, false /* useViewData */, isChecked ?? false, true /* setId */, true /* isExplicitValue */, attributes);\r
+        }\r
+\r
+        // TextBox\r
+\r
+        public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name) {\r
+            return TextBox(htmlHelper, name, null /* value */);\r
+        }\r
+\r
+        public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name, object value) {\r
+            return TextBox(htmlHelper, name, value, (object)null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes) {\r
+            return TextBox(htmlHelper, name, value, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name, object value, IDictionary<string, object> htmlAttributes) {\r
+            return InputHelper(htmlHelper, InputType.Text, name, value, (value == null) /* useViewData */, false /* isChecked */, true /* setId */, true /* isExplicitValue */, htmlAttributes);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) {\r
+            return htmlHelper.TextBoxFor(expression, (IDictionary<string, object>)null);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes) {\r
+            return htmlHelper.TextBoxFor(expression, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes) {\r
+            return TextBoxHelper(htmlHelper,\r
+                                 ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model,\r
+                                 ExpressionHelper.GetExpressionText(expression),\r
+                                 htmlAttributes);\r
+        }\r
+\r
+        private static MvcHtmlString TextBoxHelper(this HtmlHelper htmlHelper, object model, string expression, IDictionary<string, object> htmlAttributes) {\r
+            return InputHelper(htmlHelper, InputType.Text, expression, model, false /* useViewData */, false /* isChecked */, true /* setId */, true /* isExplicitValue */, htmlAttributes);\r
+        }\r
+\r
+        // Helper methods\r
+\r
+        private static MvcHtmlString InputHelper(HtmlHelper htmlHelper, InputType inputType, string name, object value, bool useViewData, bool isChecked, bool setId, bool isExplicitValue, IDictionary<string, object> htmlAttributes) {\r
+            name = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);\r
+            if (String.IsNullOrEmpty(name)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "name");\r
+            }\r
+\r
+            TagBuilder tagBuilder = new TagBuilder("input");\r
+            tagBuilder.MergeAttributes(htmlAttributes);\r
+            tagBuilder.MergeAttribute("type", HtmlHelper.GetInputTypeString(inputType));\r
+            tagBuilder.MergeAttribute("name", name, true);\r
+\r
+            string valueParameter = Convert.ToString(value, CultureInfo.CurrentCulture);\r
+            bool usedModelState = false;\r
+\r
+            switch (inputType) {\r
+                case InputType.CheckBox:\r
+                    bool? modelStateWasChecked = htmlHelper.GetModelStateValue(name, typeof(bool)) as bool?;\r
+                    if (modelStateWasChecked.HasValue) {\r
+                        isChecked = modelStateWasChecked.Value;\r
+                        usedModelState = true;\r
+                    }\r
+                    goto case InputType.Radio;\r
+                case InputType.Radio:\r
+                    if (!usedModelState) {\r
+                        string modelStateValue = htmlHelper.GetModelStateValue(name, typeof(string)) as string;\r
+                        if (modelStateValue != null) {\r
+                            isChecked = String.Equals(modelStateValue, valueParameter, StringComparison.Ordinal);\r
+                            usedModelState = true;\r
+                        }\r
+                    }\r
+                    if (!usedModelState && useViewData) {\r
+                        isChecked = htmlHelper.EvalBoolean(name);\r
+                    }\r
+                    if (isChecked) {\r
+                        tagBuilder.MergeAttribute("checked", "checked");\r
+                    }\r
+                    tagBuilder.MergeAttribute("value", valueParameter, isExplicitValue);\r
+                    break;\r
+                case InputType.Password:\r
+                    if (value != null) {\r
+                        tagBuilder.MergeAttribute("value", valueParameter, isExplicitValue);\r
+                    }\r
+                    break;\r
+                default:\r
+                    string attemptedValue = (string)htmlHelper.GetModelStateValue(name, typeof(string));\r
+                    tagBuilder.MergeAttribute("value", attemptedValue ?? ((useViewData) ? htmlHelper.EvalString(name) : valueParameter), isExplicitValue);\r
+                    break;\r
+            }\r
+\r
+            if (setId) {\r
+                tagBuilder.GenerateId(name);\r
+            }\r
+\r
+            // If there are any errors for a named field, we add the css attribute.\r
+            ModelState modelState;\r
+            if (htmlHelper.ViewData.ModelState.TryGetValue(name, out modelState)) {\r
+                if (modelState.Errors.Count > 0) {\r
+                    tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);\r
+                }\r
+            }\r
+\r
+            if (inputType == InputType.CheckBox) {\r
+                // Render an additional <input type="hidden".../> for checkboxes. This\r
+                // addresses scenarios where unchecked checkboxes are not sent in the request.\r
+                // Sending a hidden input makes it possible to know that the checkbox was present\r
+                // on the page when the request was submitted.\r
+                StringBuilder inputItemBuilder = new StringBuilder();\r
+                inputItemBuilder.Append(tagBuilder.ToString(TagRenderMode.SelfClosing));\r
+\r
+                TagBuilder hiddenInput = new TagBuilder("input");\r
+                hiddenInput.MergeAttribute("type", HtmlHelper.GetInputTypeString(InputType.Hidden));\r
+                hiddenInput.MergeAttribute("name", name);\r
+                hiddenInput.MergeAttribute("value", "false");\r
+                inputItemBuilder.Append(hiddenInput.ToString(TagRenderMode.SelfClosing));\r
+                return MvcHtmlString.Create(inputItemBuilder.ToString());\r
+            }\r
+\r
+            return tagBuilder.ToMvcHtmlString(TagRenderMode.SelfClosing);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/LabelExtensions.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/LabelExtensions.cs
new file mode 100644 (file)
index 0000000..4af88ea
--- /dev/null
@@ -0,0 +1,49 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Html {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Linq;\r
+    using System.Linq.Expressions;\r
+\r
+    public static class LabelExtensions {\r
+        public static MvcHtmlString Label(this HtmlHelper html, string expression) {\r
+            return LabelHelper(html,\r
+                               ModelMetadata.FromStringExpression(expression, html.ViewData),\r
+                               expression);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) {\r
+            return LabelHelper(html, \r
+                               ModelMetadata.FromLambdaExpression(expression, html.ViewData), \r
+                               ExpressionHelper.GetExpressionText(expression));\r
+        }\r
+\r
+        public static MvcHtmlString LabelForModel(this HtmlHelper html) {\r
+            return LabelHelper(html, html.ViewData.ModelMetadata, String.Empty);\r
+        }\r
+\r
+        internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName) {\r
+            string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();\r
+            if (String.IsNullOrEmpty(labelText)) {\r
+                return MvcHtmlString.Empty;\r
+            }\r
+\r
+            TagBuilder tag = new TagBuilder("label");\r
+            tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));\r
+            tag.SetInnerText(labelText);\r
+            return tag.ToMvcHtmlString(TagRenderMode.Normal);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/LinkExtensions.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/LinkExtensions.cs
new file mode 100644 (file)
index 0000000..8250ff3
--- /dev/null
@@ -0,0 +1,116 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Html {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.Routing;\r
+\r
+    public static class LinkExtensions {\r
+        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName) {\r
+            return ActionLink(htmlHelper, linkText, actionName, null /* controllerName */, new RouteValueDictionary(), new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues) {\r
+            return ActionLink(htmlHelper, linkText, actionName, null /* controllerName */, new RouteValueDictionary(routeValues), new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, object htmlAttributes) {\r
+            return ActionLink(htmlHelper, linkText, actionName, null /* controllerName */, new RouteValueDictionary(routeValues), new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, RouteValueDictionary routeValues) {\r
+            return ActionLink(htmlHelper, linkText, actionName, null /* controllerName */, routeValues, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes) {\r
+            return ActionLink(htmlHelper, linkText, actionName, null /* controllerName */, routeValues, htmlAttributes);\r
+        }\r
+\r
+        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName) {\r
+            return ActionLink(htmlHelper, linkText, actionName, controllerName, new RouteValueDictionary(), new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes) {\r
+            return ActionLink(htmlHelper, linkText, actionName, controllerName, new RouteValueDictionary(routeValues), new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes) {\r
+            if (String.IsNullOrEmpty(linkText)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "linkText");\r
+            }\r
+            return MvcHtmlString.Create(HtmlHelper.GenerateLink(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection, linkText, null/* routeName */, actionName, controllerName, routeValues, htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string protocol, string hostName, string fragment, object routeValues, object htmlAttributes) {\r
+            return ActionLink(htmlHelper, linkText, actionName, controllerName, protocol, hostName, fragment, new RouteValueDictionary(routeValues), new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes) {\r
+            if (String.IsNullOrEmpty(linkText)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "linkText");\r
+            }\r
+            return MvcHtmlString.Create(HtmlHelper.GenerateLink(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection, linkText, null /* routeName */, actionName, controllerName, protocol, hostName, fragment, routeValues, htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, object routeValues) {\r
+            return RouteLink(htmlHelper, linkText, new RouteValueDictionary(routeValues));\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, RouteValueDictionary routeValues) {\r
+            return RouteLink(htmlHelper, linkText, routeValues, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, string routeName) {\r
+            return RouteLink(htmlHelper, linkText, routeName, (object)null /* routeValues */ );\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, string routeName, object routeValues) {\r
+            return RouteLink(htmlHelper, linkText, routeName, new RouteValueDictionary(routeValues));\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, string routeName, RouteValueDictionary routeValues) {\r
+            return RouteLink(htmlHelper, linkText, routeName, routeValues, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, object routeValues, object htmlAttributes) {\r
+            return RouteLink(htmlHelper, linkText, new RouteValueDictionary(routeValues), new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes) {\r
+            return RouteLink(htmlHelper, linkText, null /* routeName */, routeValues, htmlAttributes);\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, string routeName, object routeValues, object htmlAttributes) {\r
+            return RouteLink(htmlHelper, linkText, routeName, new RouteValueDictionary(routeValues), new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, string routeName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes) {\r
+            if (String.IsNullOrEmpty(linkText)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "linkText");\r
+            }\r
+            return MvcHtmlString.Create(HtmlHelper.GenerateRouteLink(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection, linkText, routeName, routeValues, htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, string routeName, string protocol, string hostName, string fragment, object routeValues, object htmlAttributes) {\r
+            return RouteLink(htmlHelper, linkText, routeName, protocol, hostName, fragment, new RouteValueDictionary(routeValues), new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, string routeName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes) {\r
+            if (String.IsNullOrEmpty(linkText)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "linkText");\r
+            }\r
+            return MvcHtmlString.Create(HtmlHelper.GenerateRouteLink(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection, linkText, routeName, protocol, hostName, fragment, routeValues, htmlAttributes));\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/MvcForm.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/MvcForm.cs
new file mode 100644 (file)
index 0000000..6aa1d99
--- /dev/null
@@ -0,0 +1,69 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Html {\r
+    using System;\r
+    using System.IO;\r
+\r
+    public class MvcForm : IDisposable {\r
+\r
+        private bool _disposed;\r
+        private readonly FormContext _originalFormContext;\r
+        private readonly ViewContext _viewContext;\r
+        private readonly TextWriter _writer;\r
+\r
+        [Obsolete("The recommended alternative is the constructor MvcForm(ViewContext viewContext).", true /* error */)]\r
+        public MvcForm(HttpResponseBase httpResponse) {\r
+            if (httpResponse == null) {\r
+                throw new ArgumentNullException("httpResponse");\r
+            }\r
+\r
+            _writer = httpResponse.Output;\r
+        }\r
+\r
+        public MvcForm(ViewContext viewContext) {\r
+            if (viewContext == null) {\r
+                throw new ArgumentNullException("viewContext");\r
+            }\r
+\r
+            _viewContext = viewContext;\r
+            _writer = viewContext.Writer;\r
+\r
+            // push the new FormContext\r
+            _originalFormContext = viewContext.FormContext;\r
+            viewContext.FormContext = new FormContext();\r
+        }\r
+\r
+        public void Dispose() {\r
+            Dispose(true /* disposing */);\r
+            GC.SuppressFinalize(this);\r
+        }\r
+\r
+        protected virtual void Dispose(bool disposing) {\r
+            if (!_disposed) {\r
+                _disposed = true;\r
+                _writer.Write("</form>");\r
+\r
+                // output client validation and restore the original form context\r
+                if (_viewContext != null) {\r
+                    _viewContext.OutputClientValidation();\r
+                    _viewContext.FormContext = _originalFormContext;\r
+                }\r
+            }\r
+        }\r
+\r
+        public void EndForm() {\r
+            Dispose(true);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/PartialExtensions.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/PartialExtensions.cs
new file mode 100644 (file)
index 0000000..8f488c6
--- /dev/null
@@ -0,0 +1,36 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Html {\r
+    using System.Globalization;\r
+    using System.IO;\r
+\r
+    public static class PartialExtensions {\r
+        public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName) {\r
+            return Partial(htmlHelper, partialViewName, null /* model */, htmlHelper.ViewData);\r
+        }\r
+\r
+        public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData) {\r
+            return Partial(htmlHelper, partialViewName, null /* model */, viewData);\r
+        }\r
+\r
+        public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, object model) {\r
+            return Partial(htmlHelper, partialViewName, model, htmlHelper.ViewData);\r
+        }\r
+\r
+        public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData) {\r
+            StringWriter writer = new StringWriter(CultureInfo.CurrentCulture);\r
+            htmlHelper.RenderPartialInternal(partialViewName, viewData, model, writer, ViewEngines.Engines);\r
+            return MvcHtmlString.Create(writer.ToString());\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/RenderPartialExtensions.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/RenderPartialExtensions.cs
new file mode 100644 (file)
index 0000000..3d25070
--- /dev/null
@@ -0,0 +1,35 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Html {\r
+    public static class RenderPartialExtensions {\r
+        // Renders the partial view with the parent's view data and model\r
+        public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName) {\r
+            htmlHelper.RenderPartialInternal(partialViewName, htmlHelper.ViewData, null /* model */, htmlHelper.ViewContext.Writer, ViewEngines.Engines);\r
+        }\r
+\r
+        // Renders the partial view with the given view data and, implicitly, the given view data's model\r
+        public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData) {\r
+            htmlHelper.RenderPartialInternal(partialViewName, viewData, null /* model */, htmlHelper.ViewContext.Writer, ViewEngines.Engines);\r
+        }\r
+\r
+        // Renders the partial view with an empty view data and the given model\r
+        public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, object model) {\r
+            htmlHelper.RenderPartialInternal(partialViewName, htmlHelper.ViewData, model, htmlHelper.ViewContext.Writer, ViewEngines.Engines);\r
+        }\r
+\r
+        // Renders the partial view with a copy of the given view data plus the given model\r
+        public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData) {\r
+            htmlHelper.RenderPartialInternal(partialViewName, viewData, model, htmlHelper.ViewContext.Writer, ViewEngines.Engines);\r
+        }\r
+    }\r
+}
\ No newline at end of file
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/SelectExtensions.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/SelectExtensions.cs
new file mode 100644 (file)
index 0000000..e3cf48b
--- /dev/null
@@ -0,0 +1,256 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Html {\r
+    using System.Collections;\r
+    using System.Collections.Generic;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+    using System.Linq.Expressions;\r
+    using System.Text;\r
+    using System.Web;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.Routing;\r
+\r
+    public static class SelectExtensions {\r
+\r
+        // DropDownList\r
+\r
+        public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name) {\r
+            return DropDownList(htmlHelper, name, null /* selectList */, null /* optionLabel */, null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, string optionLabel) {\r
+            return DropDownList(htmlHelper, name, null /* selectList */, optionLabel, null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList) {\r
+            return DropDownList(htmlHelper, name, selectList, null /* optionLabel */, null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, object htmlAttributes) {\r
+            return DropDownList(htmlHelper, name, selectList, null /* optionLabel */, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes) {\r
+            return DropDownList(htmlHelper, name, selectList, null /* optionLabel */, htmlAttributes);\r
+        }\r
+\r
+        public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, string optionLabel) {\r
+            return DropDownList(htmlHelper, name, selectList, optionLabel, null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes) {\r
+            return DropDownList(htmlHelper, name, selectList, optionLabel, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes) {\r
+            return DropDownListHelper(htmlHelper, name, selectList, optionLabel, htmlAttributes);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList) {\r
+            return DropDownListFor(htmlHelper, expression, selectList, null /* optionLabel */, null /* htmlAttributes */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes) {\r
+            return DropDownListFor(htmlHelper, expression, selectList, null /* optionLabel */, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes) {\r
+            return DropDownListFor(htmlHelper, expression, selectList, null /* optionLabel */, htmlAttributes);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel) {\r
+            return DropDownListFor(htmlHelper, expression, selectList, optionLabel, null /* htmlAttributes */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes) {\r
+            return DropDownListFor(htmlHelper, expression, selectList, optionLabel, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Users cannot use anonymous methods with the LambdaExpression type")]\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes) {\r
+            if (expression == null) {\r
+                throw new ArgumentNullException("expression");\r
+            }\r
+\r
+            return DropDownListHelper(htmlHelper, ExpressionHelper.GetExpressionText(expression), selectList, optionLabel, htmlAttributes);\r
+        }\r
+\r
+        private static MvcHtmlString DropDownListHelper(HtmlHelper htmlHelper, string expression, IEnumerable<SelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes) {\r
+            return SelectInternal(htmlHelper, optionLabel, expression, selectList, false /* allowMultiple */, htmlAttributes);\r
+        }\r
+\r
+        // ListBox\r
+\r
+        public static MvcHtmlString ListBox(this HtmlHelper htmlHelper, string name) {\r
+            return ListBox(htmlHelper, name, null /* selectList */, null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcHtmlString ListBox(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList) {\r
+            return ListBox(htmlHelper, name, selectList, (IDictionary<string, object>)null);\r
+        }\r
+\r
+        public static MvcHtmlString ListBox(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, object htmlAttributes) {\r
+            return ListBox(htmlHelper, name, selectList, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString ListBox(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes) {\r
+            return ListBoxHelper(htmlHelper, name, selectList, htmlAttributes);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString ListBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList) {\r
+            return ListBoxFor(htmlHelper, expression, selectList, null /* htmlAttributes */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString ListBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes) {\r
+            return ListBoxFor(htmlHelper, expression, selectList, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Users cannot use anonymous methods with the LambdaExpression type")]\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString ListBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes) {\r
+            if (expression == null) {\r
+                throw new ArgumentNullException("expression");\r
+            }\r
+\r
+            return ListBoxHelper(htmlHelper,\r
+                                 ExpressionHelper.GetExpressionText(expression),\r
+                                 selectList,\r
+                                 htmlAttributes);\r
+        }\r
+\r
+        private static MvcHtmlString ListBoxHelper(HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes) {\r
+            return SelectInternal(htmlHelper, null /* optionLabel */, name, selectList, true /* allowMultiple */, htmlAttributes);\r
+        }\r
+\r
+        // Helper methods\r
+\r
+        private static IEnumerable<SelectListItem> GetSelectData(this HtmlHelper htmlHelper, string name) {\r
+            object o = null;\r
+            if (htmlHelper.ViewData != null) {\r
+                o = htmlHelper.ViewData.Eval(name);\r
+            }\r
+            if (o == null) {\r
+                throw new InvalidOperationException(\r
+                    String.Format(\r
+                        CultureInfo.CurrentUICulture,\r
+                        MvcResources.HtmlHelper_MissingSelectData,\r
+                        name,\r
+                        "IEnumerable<SelectListItem>"));\r
+            }\r
+            IEnumerable<SelectListItem> selectList = o as IEnumerable<SelectListItem>;\r
+            if (selectList == null) {\r
+                throw new InvalidOperationException(\r
+                    String.Format(\r
+                        CultureInfo.CurrentUICulture,\r
+                        MvcResources.HtmlHelper_WrongSelectDataType,\r
+                        name,\r
+                        o.GetType().FullName,\r
+                        "IEnumerable<SelectListItem>"));\r
+            }\r
+            return selectList;\r
+        }\r
+\r
+        internal static string ListItemToOption(SelectListItem item) {\r
+            TagBuilder builder = new TagBuilder("option") {\r
+                InnerHtml = HttpUtility.HtmlEncode(item.Text)\r
+            };\r
+            if (item.Value != null) {\r
+                builder.Attributes["value"] = item.Value;\r
+            }\r
+            if (item.Selected) {\r
+                builder.Attributes["selected"] = "selected";\r
+            }\r
+            return builder.ToString(TagRenderMode.Normal);\r
+        }\r
+\r
+        private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, string optionLabel, string name, IEnumerable<SelectListItem> selectList, bool allowMultiple, IDictionary<string, object> htmlAttributes) {\r
+            name = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);\r
+            if (String.IsNullOrEmpty(name)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "name");\r
+            }\r
+\r
+            bool usedViewData = false;\r
+\r
+            // If we got a null selectList, try to use ViewData to get the list of items.\r
+            if (selectList == null) {\r
+                selectList = htmlHelper.GetSelectData(name);\r
+                usedViewData = true;\r
+            }\r
+\r
+            object defaultValue = (allowMultiple) ? htmlHelper.GetModelStateValue(name, typeof(string[])) : htmlHelper.GetModelStateValue(name, typeof(string));\r
+\r
+            // If we haven't already used ViewData to get the entire list of items then we need to\r
+            // use the ViewData-supplied value before using the parameter-supplied value.\r
+            if (!usedViewData) {\r
+                if (defaultValue == null) {\r
+                    defaultValue = htmlHelper.ViewData.Eval(name);\r
+                }\r
+            }\r
+\r
+            if (defaultValue != null) {\r
+                IEnumerable defaultValues = (allowMultiple) ? defaultValue as IEnumerable : new[] { defaultValue };\r
+                IEnumerable<string> values = from object value in defaultValues select Convert.ToString(value, CultureInfo.CurrentCulture);\r
+                HashSet<string> selectedValues = new HashSet<string>(values, StringComparer.OrdinalIgnoreCase);\r
+                List<SelectListItem> newSelectList = new List<SelectListItem>();\r
+\r
+                foreach (SelectListItem item in selectList) {\r
+                    item.Selected = (item.Value != null) ? selectedValues.Contains(item.Value) : selectedValues.Contains(item.Text);\r
+                    newSelectList.Add(item);\r
+                }\r
+                selectList = newSelectList;\r
+            }\r
+\r
+            // Convert each ListItem to an <option> tag\r
+            StringBuilder listItemBuilder = new StringBuilder();\r
+\r
+            // Make optionLabel the first item that gets rendered.\r
+            if (optionLabel != null) {\r
+                listItemBuilder.AppendLine(ListItemToOption(new SelectListItem() { Text = optionLabel, Value = String.Empty, Selected = false }));\r
+            }\r
+\r
+            foreach (SelectListItem item in selectList) {\r
+                listItemBuilder.AppendLine(ListItemToOption(item));\r
+            }\r
+\r
+            TagBuilder tagBuilder = new TagBuilder("select") {\r
+                InnerHtml = listItemBuilder.ToString()\r
+            };\r
+            tagBuilder.MergeAttributes(htmlAttributes);\r
+            tagBuilder.MergeAttribute("name", name, true /* replaceExisting */);\r
+            tagBuilder.GenerateId(name);\r
+            if (allowMultiple) {\r
+                tagBuilder.MergeAttribute("multiple", "multiple");\r
+            }\r
+\r
+            // If there are any errors for a named field, we add the css attribute.\r
+            ModelState modelState;\r
+            if (htmlHelper.ViewData.ModelState.TryGetValue(name, out modelState)) {\r
+                if (modelState.Errors.Count > 0) {\r
+                    tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);\r
+                }\r
+            }\r
+\r
+            return tagBuilder.ToMvcHtmlString(TagRenderMode.Normal);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/TemplateHelpers.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/TemplateHelpers.cs
new file mode 100644 (file)
index 0000000..b220233
--- /dev/null
@@ -0,0 +1,277 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Html {\r
+    using System;\r
+    using System.Collections;\r
+    using System.Collections.Generic;\r
+    using System.Globalization;\r
+    using System.IO;\r
+    using System.Linq;\r
+    using System.Linq.Expressions;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.Routing;\r
+    using System.Web.UI.WebControls;\r
+\r
+    internal static class TemplateHelpers {\r
+        static readonly Dictionary<DataBoundControlMode, string> modeViewPaths =\r
+            new Dictionary<DataBoundControlMode, string> {\r
+                { DataBoundControlMode.ReadOnly, "DisplayTemplates" },\r
+                { DataBoundControlMode.Edit,     "EditorTemplates" }\r
+            };\r
+\r
+        static readonly Dictionary<string, Func<HtmlHelper, string>> defaultDisplayActions =\r
+            new Dictionary<string, Func<HtmlHelper, string>>(StringComparer.OrdinalIgnoreCase) {\r
+                { "EmailAddress",       DefaultDisplayTemplates.EmailAddressTemplate },\r
+                { "HiddenInput",        DefaultDisplayTemplates.HiddenInputTemplate },\r
+                { "Html",               DefaultDisplayTemplates.HtmlTemplate },\r
+                { "Text",               DefaultDisplayTemplates.StringTemplate },\r
+                { "Url",                DefaultDisplayTemplates.UrlTemplate },\r
+                { "Collection",         DefaultDisplayTemplates.CollectionTemplate },\r
+                { typeof(bool).Name,    DefaultDisplayTemplates.BooleanTemplate },\r
+                { typeof(decimal).Name, DefaultDisplayTemplates.DecimalTemplate },\r
+                { typeof(string).Name,  DefaultDisplayTemplates.StringTemplate },\r
+                { typeof(object).Name,  DefaultDisplayTemplates.ObjectTemplate },\r
+            };\r
+\r
+        static readonly Dictionary<string, Func<HtmlHelper, string>> defaultEditorActions =\r
+            new Dictionary<string, Func<HtmlHelper, string>>(StringComparer.OrdinalIgnoreCase) {\r
+                { "HiddenInput",        DefaultEditorTemplates.HiddenInputTemplate },\r
+                { "MultilineText",      DefaultEditorTemplates.MultilineTextTemplate },\r
+                { "Password",           DefaultEditorTemplates.PasswordTemplate },\r
+                { "Text",               DefaultEditorTemplates.StringTemplate },\r
+                { "Collection",         DefaultEditorTemplates.CollectionTemplate },\r
+                { typeof(bool).Name,    DefaultEditorTemplates.BooleanTemplate },\r
+                { typeof(decimal).Name, DefaultEditorTemplates.DecimalTemplate },\r
+                { typeof(string).Name,  DefaultEditorTemplates.StringTemplate },\r
+                { typeof(object).Name,  DefaultEditorTemplates.ObjectTemplate },\r
+            };\r
+\r
+        internal static string cacheItemId = Guid.NewGuid().ToString();\r
+\r
+        internal delegate string ExecuteTemplateDelegate(HtmlHelper html, ViewDataDictionary viewData, string templateName, DataBoundControlMode mode, GetViewNamesDelegate getViewNames);\r
+\r
+        internal static string ExecuteTemplate(HtmlHelper html, ViewDataDictionary viewData, string templateName, DataBoundControlMode mode, GetViewNamesDelegate getViewNames) {\r
+            Dictionary<string, ActionCacheItem> actionCache = GetActionCache(html);\r
+            Dictionary<string, Func<HtmlHelper, string>> defaultActions = mode == DataBoundControlMode.ReadOnly ? defaultDisplayActions : defaultEditorActions;\r
+            string modeViewPath = modeViewPaths[mode];\r
+\r
+            foreach (string viewName in getViewNames(viewData.ModelMetadata, templateName, viewData.ModelMetadata.TemplateHint, viewData.ModelMetadata.DataTypeName)) {\r
+                string fullViewName = modeViewPath + "/" + viewName;\r
+                ActionCacheItem cacheItem;\r
+\r
+                if (actionCache.TryGetValue(fullViewName, out cacheItem)) {\r
+                    if (cacheItem != null) {\r
+                        return cacheItem.Execute(html, viewData);\r
+                    }\r
+                }\r
+                else {\r
+                    ViewEngineResult viewEngineResult = ViewEngines.Engines.FindPartialView(html.ViewContext, fullViewName);\r
+                    if (viewEngineResult.View != null) {\r
+                        actionCache[fullViewName] = new ActionCacheViewItem { ViewName = fullViewName };\r
+\r
+                        StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);\r
+                        viewEngineResult.View.Render(new ViewContext(html.ViewContext, viewEngineResult.View, viewData, html.ViewContext.TempData, writer), writer);\r
+                        return writer.ToString();\r
+                    }\r
+\r
+                    Func<HtmlHelper, string> defaultAction;\r
+                    if (defaultActions.TryGetValue(viewName, out defaultAction)) {\r
+                        actionCache[fullViewName] = new ActionCacheCodeItem { Action = defaultAction };\r
+                        return defaultAction(\r
+                            new HtmlHelper(\r
+                                new ViewContext(html.ViewContext, html.ViewContext.View, viewData, html.ViewContext.TempData, html.ViewContext.Writer),\r
+                                html.ViewDataContainer\r
+                            )\r
+                        );\r
+                    }\r
+\r
+                    actionCache[fullViewName] = null;\r
+                }\r
+            }\r
+\r
+            throw new InvalidOperationException(\r
+                String.Format(\r
+                    CultureInfo.CurrentCulture,\r
+                    MvcResources.TemplateHelpers_NoTemplate,\r
+                    viewData.ModelMetadata.RealModelType.FullName\r
+                )\r
+            );\r
+        }\r
+\r
+        internal static Dictionary<string, ActionCacheItem> GetActionCache(HtmlHelper html) {\r
+            HttpContextBase context = html.ViewContext.HttpContext;\r
+            Dictionary<string, ActionCacheItem> result;\r
+\r
+            if (!context.Items.Contains(cacheItemId)) {\r
+                result = new Dictionary<string, ActionCacheItem>();\r
+                context.Items[cacheItemId] = result;\r
+            }\r
+            else {\r
+                result = (Dictionary<string, ActionCacheItem>)context.Items[cacheItemId];\r
+            }\r
+\r
+            return result;\r
+        }\r
+\r
+        internal delegate IEnumerable<string> GetViewNamesDelegate(ModelMetadata metadata, params string[] templateHints);\r
+\r
+        internal static IEnumerable<string> GetViewNames(ModelMetadata metadata, params string[] templateHints) {\r
+            foreach (string templateHint in templateHints.Where(s => !String.IsNullOrEmpty(s))) {\r
+                yield return templateHint;\r
+            }\r
+\r
+            // We don't want to search for Nullable<T>, we want to search for T (which should handle both T and Nullable<T>)\r
+            Type fieldType = Nullable.GetUnderlyingType(metadata.RealModelType) ?? metadata.RealModelType;\r
+\r
+            // TODO: Make better string names for generic types\r
+            yield return fieldType.Name;\r
+\r
+            if (!metadata.IsComplexType) {\r
+                yield return "String";\r
+            }\r
+            else if (fieldType.IsInterface) {\r
+                if (typeof(IEnumerable).IsAssignableFrom(fieldType)) {\r
+                    yield return "Collection";\r
+                }\r
+\r
+                yield return "Object";\r
+            }\r
+            else {\r
+                bool isEnumerable = typeof(IEnumerable).IsAssignableFrom(fieldType);\r
+\r
+                while (true) {\r
+                    fieldType = fieldType.BaseType;\r
+                    if (fieldType == null)\r
+                        break;\r
+\r
+                    if (isEnumerable && fieldType == typeof(Object)) {\r
+                        yield return "Collection";\r
+                    }\r
+\r
+                    yield return fieldType.Name;\r
+                }\r
+            }\r
+        }\r
+\r
+        internal static MvcHtmlString Template(HtmlHelper html, string expression, string templateName, string htmlFieldName, DataBoundControlMode mode, object additionalViewData) {\r
+            return MvcHtmlString.Create(Template(html, expression, templateName, htmlFieldName, mode, additionalViewData, TemplateHelper));\r
+        }\r
+\r
+        // Unit testing version\r
+        internal static string Template(HtmlHelper html, string expression, string templateName, string htmlFieldName,\r
+                                        DataBoundControlMode mode, object additionalViewData, TemplateHelperDelegate templateHelper) {\r
+            return templateHelper(html,\r
+                                  ModelMetadata.FromStringExpression(expression, html.ViewData),\r
+                                  htmlFieldName ?? ExpressionHelper.GetExpressionText(expression),\r
+                                  templateName,\r
+                                  mode,\r
+                                  additionalViewData);\r
+        }\r
+\r
+        internal static MvcHtmlString TemplateFor<TContainer, TValue>(this HtmlHelper<TContainer> html, Expression<Func<TContainer, TValue>> expression,\r
+                                                                      string templateName, string htmlFieldName, DataBoundControlMode mode,\r
+                                                                      object additionalViewData) {\r
+            return MvcHtmlString.Create(TemplateFor(html, expression, templateName, htmlFieldName, mode, additionalViewData, TemplateHelper));\r
+        }\r
+\r
+        // Unit testing version\r
+        internal static string TemplateFor<TContainer, TValue>(this HtmlHelper<TContainer> html, Expression<Func<TContainer, TValue>> expression,\r
+                                                               string templateName, string htmlFieldName, DataBoundControlMode mode,\r
+                                                               object additionalViewData, TemplateHelperDelegate templateHelper) {\r
+            return templateHelper(html,\r
+                                  ModelMetadata.FromLambdaExpression(expression, html.ViewData),\r
+                                  htmlFieldName ?? ExpressionHelper.GetExpressionText(expression),\r
+                                  templateName,\r
+                                  mode,\r
+                                  additionalViewData);\r
+        }\r
+\r
+        internal delegate string TemplateHelperDelegate(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string templateName, DataBoundControlMode mode, object additionalViewData);\r
+\r
+        internal static string TemplateHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string templateName, DataBoundControlMode mode, object additionalViewData) {\r
+            return TemplateHelper(html, metadata, htmlFieldName, templateName, mode, additionalViewData, ExecuteTemplate);\r
+        }\r
+\r
+        internal static string TemplateHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string templateName, DataBoundControlMode mode, object additionalViewData, ExecuteTemplateDelegate executeTemplate) {\r
+            // TODO: Convert Editor into Display if model.IsReadOnly is true? Need to be careful about this because\r
+            // the Model property on the ViewPage/ViewUserControl is get-only, so the type descriptor automatically\r
+            // decorates it with a [ReadOnly] attribute...\r
+\r
+            if (metadata.ConvertEmptyStringToNull && String.Empty.Equals(metadata.Model)) {\r
+                metadata.Model = null;\r
+            }\r
+\r
+            object formattedModelValue = metadata.Model;\r
+            if (metadata.Model == null && mode == DataBoundControlMode.ReadOnly) {\r
+                formattedModelValue = metadata.NullDisplayText;\r
+            }\r
+\r
+            string formatString = mode == DataBoundControlMode.ReadOnly ? metadata.DisplayFormatString : metadata.EditFormatString;\r
+            if (metadata.Model != null && !String.IsNullOrEmpty(formatString)) {\r
+                formattedModelValue = String.Format(CultureInfo.CurrentCulture, formatString, metadata.Model);\r
+            }\r
+\r
+            // Normally this shouldn't happen, unless someone writes their own custom Object templates which\r
+            // don't check to make sure that the object hasn't already been displayed\r
+            object visitedObjectsKey = metadata.Model ?? metadata.RealModelType;\r
+            if (html.ViewDataContainer.ViewData.TemplateInfo.VisitedObjects.Contains(visitedObjectsKey)) {    // DDB #224750\r
+                return String.Empty;\r
+            }\r
+\r
+            ViewDataDictionary viewData = new ViewDataDictionary(html.ViewDataContainer.ViewData) {\r
+                Model = metadata.Model,\r
+                ModelMetadata = metadata,\r
+                TemplateInfo = new TemplateInfo {\r
+                    FormattedModelValue = formattedModelValue,\r
+                    HtmlFieldPrefix = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName),\r
+                    VisitedObjects = new HashSet<object>(html.ViewContext.ViewData.TemplateInfo.VisitedObjects),    // DDB #224750\r
+                }\r
+            };\r
+\r
+            if (additionalViewData != null) {\r
+                foreach (KeyValuePair<string, object> kvp in new RouteValueDictionary(additionalViewData)) {\r
+                    viewData[kvp.Key] = kvp.Value;\r
+                }\r
+            }\r
+\r
+            viewData.TemplateInfo.VisitedObjects.Add(visitedObjectsKey);    // DDB #224750\r
+\r
+            return executeTemplate(html, viewData, templateName, mode, GetViewNames);\r
+        }\r
+\r
+        internal abstract class ActionCacheItem {\r
+            public abstract string Execute(HtmlHelper html, ViewDataDictionary viewData);\r
+        }\r
+\r
+        internal class ActionCacheCodeItem : ActionCacheItem {\r
+            public Func<HtmlHelper, string> Action { get; set; }\r
+\r
+            public override string Execute(HtmlHelper html, ViewDataDictionary viewData) {\r
+                ViewContext newViewContext = new ViewContext(html.ViewContext, html.ViewContext.View, viewData, html.ViewContext.TempData, html.ViewContext.Writer);\r
+                HtmlHelper newHtmlHelper = new HtmlHelper(newViewContext, html.ViewDataContainer);\r
+                return Action(newHtmlHelper);\r
+            }\r
+        }\r
+\r
+        internal class ActionCacheViewItem : ActionCacheItem {\r
+            public string ViewName { get; set; }\r
+\r
+            public override string Execute(HtmlHelper html, ViewDataDictionary viewData) {\r
+                ViewEngineResult viewEngineResult = ViewEngines.Engines.FindPartialView(html.ViewContext, ViewName);\r
+                StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);\r
+                viewEngineResult.View.Render(new ViewContext(html.ViewContext, viewEngineResult.View, viewData, html.ViewContext.TempData, writer), writer);\r
+                return writer.ToString();\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/TextAreaExtensions.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/TextAreaExtensions.cs
new file mode 100644 (file)
index 0000000..4443c43
--- /dev/null
@@ -0,0 +1,172 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Html {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.Linq.Expressions;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.Routing;\r
+\r
+    public static class TextAreaExtensions {\r
+        // These values are similar to the defaults used by WebForms\r
+        // when using <asp:TextBox TextMode="MultiLine"> without specifying\r
+        // the Rows and Columns attributes.\r
+        private const int TextAreaRows = 2;\r
+        private const int TextAreaColumns = 20;\r
+        private static Dictionary<string, object> implicitRowsAndColumns = new Dictionary<string, object> {\r
+            { "rows", TextAreaRows.ToString(CultureInfo.InvariantCulture) },\r
+            { "cols", TextAreaColumns.ToString(CultureInfo.InvariantCulture) },\r
+        };\r
+\r
+        private static Dictionary<string, object> GetRowsAndColumnsDictionary(int rows, int columns) {\r
+            if (rows < 0) {\r
+                throw new ArgumentOutOfRangeException("rows", MvcResources.HtmlHelper_TextAreaParameterOutOfRange);\r
+            }\r
+            if (columns < 0) {\r
+                throw new ArgumentOutOfRangeException("columns", MvcResources.HtmlHelper_TextAreaParameterOutOfRange);\r
+            }\r
+\r
+            Dictionary<string, object> result = new Dictionary<string, object>();\r
+            if (rows > 0) {\r
+                result.Add("rows", rows.ToString(CultureInfo.InvariantCulture));\r
+            }\r
+            if (columns > 0) {\r
+                result.Add("cols", columns.ToString(CultureInfo.InvariantCulture));\r
+            }\r
+\r
+            return result;\r
+        }\r
+\r
+        public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name) {\r
+            return TextArea(htmlHelper, name, null /* value */, null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, object htmlAttributes) {\r
+            return TextArea(htmlHelper, name, null /* value */, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, IDictionary<string, object> htmlAttributes) {\r
+            return TextArea(htmlHelper, name, null /* value */, htmlAttributes);\r
+        }\r
+\r
+        public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, string value) {\r
+            return TextArea(htmlHelper, name, value, null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, string value, object htmlAttributes) {\r
+            return TextArea(htmlHelper, name, value, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, string value, IDictionary<string, object> htmlAttributes) {\r
+            ModelMetadata metadata = ModelMetadata.FromStringExpression(name, htmlHelper.ViewContext.ViewData);\r
+            if (value != null) {\r
+                metadata.Model = value;\r
+            }\r
+\r
+            return TextAreaHelper(htmlHelper, metadata, name, implicitRowsAndColumns, htmlAttributes);\r
+        }\r
+\r
+        public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, string value, int rows, int columns, object htmlAttributes) {\r
+            return TextArea(htmlHelper, name, value, rows, columns, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, string value, int rows, int columns, IDictionary<string, object> htmlAttributes) {\r
+            ModelMetadata metadata = ModelMetadata.FromStringExpression(name, htmlHelper.ViewContext.ViewData);\r
+            if (value != null) {\r
+                metadata.Model = value;\r
+            }\r
+\r
+            return TextAreaHelper(htmlHelper, metadata, name, GetRowsAndColumnsDictionary(rows, columns), htmlAttributes);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString TextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) {\r
+            return TextAreaFor(htmlHelper, expression, (IDictionary<string, object>)null);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString TextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes) {\r
+            return TextAreaFor(htmlHelper, expression, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString TextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes) {\r
+            if (expression == null) {\r
+                throw new ArgumentNullException("expression");\r
+            }\r
+\r
+            return TextAreaHelper(htmlHelper,\r
+                                  ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData),\r
+                                  ExpressionHelper.GetExpressionText(expression),\r
+                                  implicitRowsAndColumns,\r
+                                  htmlAttributes);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString TextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, int rows, int columns, object htmlAttributes) {\r
+            return TextAreaFor(htmlHelper, expression, rows, columns, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString TextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, int rows, int columns, IDictionary<string, object> htmlAttributes) {\r
+            if (expression == null) {\r
+                throw new ArgumentNullException("expression");\r
+            }\r
+\r
+            return TextAreaHelper(htmlHelper,\r
+                                  ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData),\r
+                                  ExpressionHelper.GetExpressionText(expression),\r
+                                  GetRowsAndColumnsDictionary(rows, columns),\r
+                                  htmlAttributes);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "If this fails, it is because the string-based version had an empty 'name' parameter")]\r
+        private static MvcHtmlString TextAreaHelper(HtmlHelper htmlHelper, ModelMetadata modelMetadata, string expression, IDictionary<string, object> rowsAndColumns, IDictionary<string, object> htmlAttributes) {\r
+            string name = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expression);\r
+            if (String.IsNullOrEmpty(name)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "name");\r
+            }\r
+\r
+            TagBuilder tagBuilder = new TagBuilder("textarea");\r
+            tagBuilder.GenerateId(name);\r
+            tagBuilder.MergeAttributes(htmlAttributes, true);\r
+            tagBuilder.MergeAttributes(rowsAndColumns, rowsAndColumns != implicitRowsAndColumns);  // Only force explicit rows/cols\r
+            tagBuilder.MergeAttribute("name", name, true);\r
+\r
+            // If there are any errors for a named field, we add the CSS attribute.\r
+            ModelState modelState;\r
+            if (htmlHelper.ViewData.ModelState.TryGetValue(name, out modelState) && modelState.Errors.Count > 0) {\r
+                tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);\r
+            }\r
+\r
+            string value;\r
+            if (modelState != null && modelState.Value != null) {\r
+                value = modelState.Value.AttemptedValue;\r
+            }\r
+            else if (modelMetadata.Model != null) {\r
+                value = modelMetadata.Model.ToString();\r
+            }\r
+            else {\r
+                value = String.Empty;\r
+            }\r
+\r
+            // The first newline is always trimmed when a TextArea is rendered, so we add an extra one\r
+            // in case the value being rendered is something like "\r\nHello".\r
+            tagBuilder.SetInnerText(Environment.NewLine + value);\r
+\r
+            return tagBuilder.ToMvcHtmlString(TagRenderMode.Normal);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/ValidationExtensions.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Html/ValidationExtensions.cs
new file mode 100644 (file)
index 0000000..1284a49
--- /dev/null
@@ -0,0 +1,304 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc.Html {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+    using System.Linq.Expressions;\r
+    using System.Text;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.Routing;\r
+\r
+    public static class ValidationExtensions {\r
+\r
+        private const string _hiddenListItem = @"<li style=""display:none""></li>";\r
+        private static string _resourceClassKey;\r
+\r
+        public static string ResourceClassKey {\r
+            get {\r
+                return _resourceClassKey ?? String.Empty;\r
+            }\r
+            set {\r
+                _resourceClassKey = value;\r
+            }\r
+        }\r
+\r
+        private static FieldValidationMetadata ApplyFieldValidationMetadata(HtmlHelper htmlHelper, ModelMetadata modelMetadata, string modelName) {\r
+            FormContext formContext = htmlHelper.ViewContext.FormContext;\r
+            FieldValidationMetadata fieldMetadata = formContext.GetValidationMetadataForField(modelName, true /* createIfNotFound */);\r
+\r
+            // write rules to context object\r
+            IEnumerable<ModelValidator> validators = ModelValidatorProviders.Providers.GetValidators(modelMetadata, htmlHelper.ViewContext);\r
+            foreach (ModelClientValidationRule rule in validators.SelectMany(v => v.GetClientValidationRules())) {\r
+                fieldMetadata.ValidationRules.Add(rule);\r
+            }\r
+\r
+            return fieldMetadata;\r
+        }\r
+\r
+        private static string GetInvalidPropertyValueResource(HttpContextBase httpContext) {\r
+            string resourceValue = null;\r
+            if (!String.IsNullOrEmpty(ResourceClassKey) && (httpContext != null)) {\r
+                // If the user specified a ResourceClassKey try to load the resource they specified.\r
+                // If the class key is invalid, an exception will be thrown.\r
+                // If the class key is valid but the resource is not found, it returns null, in which\r
+                // case it will fall back to the MVC default error message.\r
+                resourceValue = httpContext.GetGlobalResourceObject(ResourceClassKey, "InvalidPropertyValue", CultureInfo.CurrentUICulture) as string;\r
+            }\r
+            return resourceValue ?? MvcResources.Common_ValueNotValidForProperty;\r
+        }\r
+\r
+        private static string GetUserErrorMessageOrDefault(HttpContextBase httpContext, ModelError error, ModelState modelState) {\r
+            if (!String.IsNullOrEmpty(error.ErrorMessage)) {\r
+                return error.ErrorMessage;\r
+            }\r
+            if (modelState == null) {\r
+                return null;\r
+            }\r
+\r
+            string attemptedValue = (modelState.Value != null) ? modelState.Value.AttemptedValue : null;\r
+            return String.Format(CultureInfo.CurrentCulture, GetInvalidPropertyValueResource(httpContext), attemptedValue);\r
+        }\r
+\r
+        // Validate\r
+\r
+        public static void Validate(this HtmlHelper htmlHelper, string modelName) {\r
+            if (modelName == null) {\r
+                throw new ArgumentNullException("modelName");\r
+            }\r
+\r
+            ValidateHelper(htmlHelper,\r
+                ModelMetadata.FromStringExpression(modelName, htmlHelper.ViewContext.ViewData),\r
+                modelName);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static void ValidateFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) {\r
+            ValidateHelper(htmlHelper,\r
+                ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData),\r
+                ExpressionHelper.GetExpressionText(expression));\r
+        }\r
+\r
+        private static void ValidateHelper(HtmlHelper htmlHelper, ModelMetadata modelMetadata, string expression) {\r
+            FormContext formContext = htmlHelper.ViewContext.GetFormContextForClientValidation();\r
+            if (formContext == null) {\r
+                return; // nothing to do\r
+            }\r
+\r
+            string modelName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expression);\r
+            ApplyFieldValidationMetadata(htmlHelper, modelMetadata, modelName);\r
+        }\r
+\r
+        // ValidationMessage\r
+\r
+        public static MvcHtmlString ValidationMessage(this HtmlHelper htmlHelper, string modelName) {\r
+            return ValidationMessage(htmlHelper, modelName, null /* validationMessage */, new RouteValueDictionary());\r
+        }\r
+\r
+        public static MvcHtmlString ValidationMessage(this HtmlHelper htmlHelper, string modelName, object htmlAttributes) {\r
+            return ValidationMessage(htmlHelper, modelName, null /* validationMessage */, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames", Justification = "'validationMessage' refers to the message that will be rendered by the ValidationMessage helper.")]\r
+        public static MvcHtmlString ValidationMessage(this HtmlHelper htmlHelper, string modelName, string validationMessage) {\r
+            return ValidationMessage(htmlHelper, modelName, validationMessage, new RouteValueDictionary());\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames", Justification = "'validationMessage' refers to the message that will be rendered by the ValidationMessage helper.")]\r
+        public static MvcHtmlString ValidationMessage(this HtmlHelper htmlHelper, string modelName, string validationMessage, object htmlAttributes) {\r
+            return ValidationMessage(htmlHelper, modelName, validationMessage, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString ValidationMessage(this HtmlHelper htmlHelper, string modelName, IDictionary<string, object> htmlAttributes) {\r
+            return ValidationMessage(htmlHelper, modelName, null /* validationMessage */, htmlAttributes);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames", Justification = "'validationMessage' refers to the message that will be rendered by the ValidationMessage helper.")]\r
+        public static MvcHtmlString ValidationMessage(this HtmlHelper htmlHelper, string modelName, string validationMessage, IDictionary<string, object> htmlAttributes) {\r
+            if (modelName == null) {\r
+                throw new ArgumentNullException("modelName");\r
+            }\r
+\r
+            return ValidationMessageHelper(htmlHelper,\r
+                                           ModelMetadata.FromStringExpression(modelName, htmlHelper.ViewContext.ViewData),\r
+                                           modelName,\r
+                                           validationMessage,\r
+                                           htmlAttributes);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString ValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) {\r
+            return ValidationMessageFor(htmlHelper, expression, null /* validationMessage */, new RouteValueDictionary());\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString ValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string validationMessage) {\r
+            return ValidationMessageFor(htmlHelper, expression, validationMessage, new RouteValueDictionary());\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString ValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string validationMessage, object htmlAttributes) {\r
+            return ValidationMessageFor(htmlHelper, expression, validationMessage, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static MvcHtmlString ValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string validationMessage, IDictionary<string, object> htmlAttributes) {\r
+            return ValidationMessageHelper(htmlHelper,\r
+                                           ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData),\r
+                                           ExpressionHelper.GetExpressionText(expression),\r
+                                           validationMessage,\r
+                                           htmlAttributes);\r
+        }\r
+\r
+        private static MvcHtmlString ValidationMessageHelper(this HtmlHelper htmlHelper, ModelMetadata modelMetadata, string expression, string validationMessage, IDictionary<string, object> htmlAttributes) {\r
+            string modelName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expression);\r
+            FormContext formContext = htmlHelper.ViewContext.GetFormContextForClientValidation();\r
+\r
+            if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName) && formContext == null) {\r
+                return null;\r
+            }\r
+\r
+            ModelState modelState = htmlHelper.ViewData.ModelState[modelName];\r
+            ModelErrorCollection modelErrors = (modelState == null) ? null : modelState.Errors;\r
+            ModelError modelError = ((modelErrors == null) || (modelErrors.Count == 0)) ? null : modelErrors[0];\r
+\r
+            if (modelError == null && formContext == null) {\r
+                return null;\r
+            }\r
+\r
+            TagBuilder builder = new TagBuilder("span");\r
+            builder.MergeAttributes(htmlAttributes);\r
+            builder.AddCssClass((modelError != null) ? HtmlHelper.ValidationMessageCssClassName : HtmlHelper.ValidationMessageValidCssClassName);\r
+\r
+            if (!String.IsNullOrEmpty(validationMessage)) {\r
+                builder.SetInnerText(validationMessage);\r
+            }\r
+            else if (modelError != null) {\r
+                builder.SetInnerText(GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, modelState));\r
+            }\r
+\r
+            if (formContext != null) {\r
+                // client validation always requires an ID\r
+                builder.GenerateId(modelName + ".validationMessage");\r
+\r
+                FieldValidationMetadata fieldMetadata = ApplyFieldValidationMetadata(htmlHelper, modelMetadata, modelName);\r
+                // rules will already have been written to the metadata object\r
+                fieldMetadata.ReplaceValidationMessageContents = (String.IsNullOrEmpty(validationMessage)); // only replace contents if no explicit message was specified\r
+                fieldMetadata.ValidationMessageId = builder.Attributes["id"];\r
+            }\r
+\r
+            return builder.ToMvcHtmlString(TagRenderMode.Normal);\r
+        }\r
+\r
+        // ValidationSummary\r
+\r
+        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper) {\r
+            return ValidationSummary(htmlHelper, false /* excludePropertyErrors */ );\r
+        }\r
+\r
+        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors) {\r
+            return ValidationSummary(htmlHelper, excludePropertyErrors, null /* message */);\r
+        }\r
+\r
+        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, string message) {\r
+            return ValidationSummary(htmlHelper, false /* excludePropertyErrors */, message, (object)null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors, string message) {\r
+            return ValidationSummary(htmlHelper, excludePropertyErrors, message, (object)null /* htmlAttributes */);\r
+        }\r
+\r
+        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, string message, object htmlAttributes) {\r
+            return ValidationSummary(htmlHelper, false /* excludePropertyErrors */, message, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors, string message, object htmlAttributes) {\r
+            return ValidationSummary(htmlHelper, excludePropertyErrors, message, new RouteValueDictionary(htmlAttributes));\r
+        }\r
+\r
+        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, string message, IDictionary<string, object> htmlAttributes) {\r
+            return ValidationSummary(htmlHelper, false /* excludePropertyErrors */, message, htmlAttributes);\r
+        }\r
+\r
+        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors, string message, IDictionary<string, object> htmlAttributes) {\r
+            if (htmlHelper == null) {\r
+                throw new ArgumentNullException("htmlHelper");\r
+            }\r
+\r
+            FormContext formContext = htmlHelper.ViewContext.GetFormContextForClientValidation();\r
+            if (formContext == null && htmlHelper.ViewData.ModelState.IsValid) {\r
+                return null;\r
+            }\r
+\r
+            string messageSpan;\r
+            if (!String.IsNullOrEmpty(message)) {\r
+                TagBuilder spanTag = new TagBuilder("span");\r
+                spanTag.SetInnerText(message);\r
+                messageSpan = spanTag.ToString(TagRenderMode.Normal) + Environment.NewLine;\r
+            }\r
+            else {\r
+                messageSpan = null;\r
+            }\r
+\r
+            StringBuilder htmlSummary = new StringBuilder();\r
+            TagBuilder unorderedList = new TagBuilder("ul");\r
+\r
+            IEnumerable<ModelState> modelStates = null;\r
+            if (excludePropertyErrors) {\r
+                ModelState ms;\r
+                htmlHelper.ViewData.ModelState.TryGetValue(htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix, out ms);\r
+                if (ms != null) {\r
+                    modelStates = new ModelState[] { ms };\r
+                }\r
+            }\r
+            else {\r
+                modelStates = htmlHelper.ViewData.ModelState.Values;\r
+            }\r
+\r
+            if (modelStates != null) {\r
+                foreach (ModelState modelState in modelStates) {\r
+                    foreach (ModelError modelError in modelState.Errors) {\r
+                        string errorText = GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, null /* modelState */);\r
+                        if (!String.IsNullOrEmpty(errorText)) {\r
+                            TagBuilder listItem = new TagBuilder("li");\r
+                            listItem.SetInnerText(errorText);\r
+                            htmlSummary.AppendLine(listItem.ToString(TagRenderMode.Normal));\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+\r
+            if (htmlSummary.Length == 0) {\r
+                htmlSummary.AppendLine(_hiddenListItem);\r
+            }\r
+\r
+            unorderedList.InnerHtml = htmlSummary.ToString();\r
+\r
+            TagBuilder divBuilder = new TagBuilder("div");\r
+            divBuilder.MergeAttributes(htmlAttributes);\r
+            divBuilder.AddCssClass((htmlHelper.ViewData.ModelState.IsValid) ? HtmlHelper.ValidationSummaryValidCssClassName : HtmlHelper.ValidationSummaryCssClassName);\r
+            divBuilder.InnerHtml = messageSpan + unorderedList.ToString(TagRenderMode.Normal);\r
+\r
+            if (formContext != null) {\r
+                // client val summaries need an ID\r
+                divBuilder.GenerateId("validationSummary");\r
+                formContext.ValidationSummaryId = divBuilder.Attributes["id"];\r
+                formContext.ReplaceValidationSummary = !excludePropertyErrors;\r
+            }\r
+            return divBuilder.ToMvcHtmlString(TagRenderMode.Normal);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/HtmlHelper.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/HtmlHelper.cs
new file mode 100644 (file)
index 0000000..ae08fcf
--- /dev/null
@@ -0,0 +1,361 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.IO;\r
+    using System.Text;\r
+    using System.Web;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.Routing;\r
+\r
+    [SuppressMessage("Microsoft.Security", "CA2112:SecuredTypesShouldNotExposeFields",\r
+        Justification = "Public fields for CSS names do not contain secure information.")]\r
+    public class HtmlHelper {\r
+\r
+        private delegate string HtmlEncoder(object value);\r
+        private static readonly HtmlEncoder _htmlEncoder = GetHtmlEncoder();\r
+\r
+        private static string _idAttributeDotReplacement;\r
+\r
+        public static readonly string ValidationInputCssClassName = "input-validation-error";\r
+        public static readonly string ValidationInputValidCssClassName = "input-validation-valid";\r
+        public static readonly string ValidationMessageCssClassName = "field-validation-error";\r
+        public static readonly string ValidationMessageValidCssClassName = "field-validation-valid";\r
+        public static readonly string ValidationSummaryCssClassName = "validation-summary-errors";\r
+        public static readonly string ValidationSummaryValidCssClassName = "validation-summary-valid";\r
+\r
+        private AntiForgeryDataSerializer _serializer;\r
+\r
+        public HtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer)\r
+            : this(viewContext, viewDataContainer, RouteTable.Routes) {\r
+        }\r
+\r
+        public HtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer, RouteCollection routeCollection) {\r
+            if (viewContext == null) {\r
+                throw new ArgumentNullException("viewContext");\r
+            }\r
+            if (viewDataContainer == null) {\r
+                throw new ArgumentNullException("viewDataContainer");\r
+            }\r
+            if (routeCollection == null) {\r
+                throw new ArgumentNullException("routeCollection");\r
+            }\r
+            ViewContext = viewContext;\r
+            ViewDataContainer = viewDataContainer;\r
+            RouteCollection = routeCollection;\r
+        }\r
+\r
+        public static string IdAttributeDotReplacement {\r
+            get {\r
+                if (String.IsNullOrEmpty(_idAttributeDotReplacement)) {\r
+                    _idAttributeDotReplacement = "_";\r
+                }\r
+                return _idAttributeDotReplacement;\r
+            }\r
+            set {\r
+                _idAttributeDotReplacement = value;\r
+            }\r
+        }\r
+\r
+        public RouteCollection RouteCollection {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        internal AntiForgeryDataSerializer Serializer {\r
+            get {\r
+                if (_serializer == null) {\r
+                    _serializer = new AntiForgeryDataSerializer();\r
+                }\r
+                return _serializer;\r
+            }\r
+            set {\r
+                _serializer = value;\r
+            }\r
+        }\r
+\r
+        public ViewContext ViewContext {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public ViewDataDictionary ViewData {\r
+            get {\r
+                return ViewDataContainer.ViewData;\r
+            }\r
+        }\r
+\r
+        public IViewDataContainer ViewDataContainer {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public MvcHtmlString AntiForgeryToken() {\r
+            return AntiForgeryToken(null /* salt */);\r
+        }\r
+\r
+        public MvcHtmlString AntiForgeryToken(string salt) {\r
+            return AntiForgeryToken(salt, null /* domain */, null /* path */);\r
+        }\r
+\r
+        public MvcHtmlString AntiForgeryToken(string salt, string domain, string path) {\r
+            string formValue = GetAntiForgeryTokenAndSetCookie(salt, domain, path);\r
+            string fieldName = AntiForgeryData.GetAntiForgeryTokenName(null);\r
+\r
+            TagBuilder builder = new TagBuilder("input");\r
+            builder.Attributes["type"] = "hidden";\r
+            builder.Attributes["name"] = fieldName;\r
+            builder.Attributes["value"] = formValue;\r
+            return builder.ToMvcHtmlString(TagRenderMode.SelfClosing);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic",\r
+            Justification = "For consistency, all helpers are instance methods.")]\r
+        public string AttributeEncode(string value) {\r
+            return (!String.IsNullOrEmpty(value)) ? HttpUtility.HtmlAttributeEncode(value) : String.Empty;\r
+        }\r
+\r
+        public string AttributeEncode(object value) {\r
+            return AttributeEncode(Convert.ToString(value, CultureInfo.InvariantCulture));\r
+        }\r
+\r
+        public void EnableClientValidation() {\r
+            ViewContext.ClientValidationEnabled = true;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic",\r
+            Justification = "For consistency, all helpers are instance methods.")]\r
+        public string Encode(string value) {\r
+            return (!String.IsNullOrEmpty(value)) ? HttpUtility.HtmlEncode(value) : String.Empty;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic",\r
+            Justification = "For consistency, all helpers are instance methods.")]\r
+        public string Encode(object value) {\r
+            return _htmlEncoder(value);\r
+        }\r
+\r
+        // method used if HttpUtility.HtmlEncode(object) method does not exist\r
+        private static string EncodeLegacy(object value) {\r
+            string stringVal = Convert.ToString(value, CultureInfo.CurrentCulture);\r
+            return (!String.IsNullOrEmpty(stringVal)) ? HttpUtility.HtmlEncode(stringVal) : String.Empty;\r
+        }\r
+\r
+        internal string EvalString(string key) {\r
+            return Convert.ToString(ViewData.Eval(key), CultureInfo.CurrentCulture);\r
+        }\r
+\r
+        internal bool EvalBoolean(string key) {\r
+            return Convert.ToBoolean(ViewData.Eval(key), CultureInfo.InvariantCulture);\r
+        }\r
+\r
+        internal static IView FindPartialView(ViewContext viewContext, string partialViewName, ViewEngineCollection viewEngineCollection) {\r
+            ViewEngineResult result = viewEngineCollection.FindPartialView(viewContext, partialViewName);\r
+            if (result.View != null) {\r
+                return result.View;\r
+            }\r
+\r
+            StringBuilder locationsText = new StringBuilder();\r
+            foreach (string location in result.SearchedLocations) {\r
+                locationsText.AppendLine();\r
+                locationsText.Append(location);\r
+            }\r
+\r
+            throw new InvalidOperationException(String.Format(CultureInfo.CurrentUICulture,\r
+                MvcResources.Common_PartialViewNotFound, partialViewName, locationsText));\r
+        }\r
+\r
+        public static string GenerateIdFromName(string name) {\r
+            return GenerateIdFromName(name, IdAttributeDotReplacement);\r
+        }\r
+\r
+        public static string GenerateIdFromName(string name, string idAttributeDotReplacement) {\r
+            if (name == null) {\r
+                throw new ArgumentNullException("name");\r
+            }\r
+            if (idAttributeDotReplacement == null) {\r
+                throw new ArgumentNullException("idAttributeDotReplacement");\r
+            }\r
+\r
+            return name.Replace(".", idAttributeDotReplacement);\r
+        }\r
+\r
+        public static string GenerateLink(RequestContext requestContext, RouteCollection routeCollection, string linkText, string routeName, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes) {\r
+            return GenerateLink(requestContext, routeCollection, linkText, routeName, actionName, controllerName, null/* protocol */, null/* hostName */, null/* fragment */, routeValues, htmlAttributes);\r
+        }\r
+\r
+        public static string GenerateLink(RequestContext requestContext, RouteCollection routeCollection, string linkText, string routeName, string actionName, string controllerName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes) {\r
+            return GenerateLinkInternal(requestContext, routeCollection, linkText, routeName, actionName, controllerName, protocol, hostName, fragment, routeValues, htmlAttributes, true /* includeImplicitMvcValues */);\r
+        }\r
+\r
+        private static string GenerateLinkInternal(RequestContext requestContext, RouteCollection routeCollection, string linkText, string routeName, string actionName, string controllerName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes, bool includeImplicitMvcValues) {\r
+            string url = UrlHelper.GenerateUrl(routeName, actionName, controllerName, protocol, hostName, fragment, routeValues, routeCollection, requestContext, includeImplicitMvcValues);\r
+            TagBuilder tagBuilder = new TagBuilder("a") {\r
+                InnerHtml = (!String.IsNullOrEmpty(linkText)) ? HttpUtility.HtmlEncode(linkText) : String.Empty\r
+            };\r
+            tagBuilder.MergeAttributes(htmlAttributes);\r
+            tagBuilder.MergeAttribute("href", url);\r
+            return tagBuilder.ToString(TagRenderMode.Normal);\r
+        }\r
+\r
+        public static string GenerateRouteLink(RequestContext requestContext, RouteCollection routeCollection, string linkText, string routeName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes) {\r
+            return GenerateRouteLink(requestContext, routeCollection, linkText, routeName, null/* protocol */, null/* hostName */, null/* fragment */, routeValues, htmlAttributes);\r
+        }\r
+\r
+        public static string GenerateRouteLink(RequestContext requestContext, RouteCollection routeCollection, string linkText, string routeName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes) {\r
+            return GenerateLinkInternal(requestContext, routeCollection, linkText, routeName, null /* actionName */, null /* controllerName */, protocol, hostName, fragment, routeValues, htmlAttributes, false /* includeImplicitMvcValues */);\r
+        }\r
+\r
+        private string GetAntiForgeryTokenAndSetCookie(string salt, string domain, string path) {\r
+            string cookieName = AntiForgeryData.GetAntiForgeryTokenName(ViewContext.HttpContext.Request.ApplicationPath);\r
+\r
+            AntiForgeryData cookieToken;\r
+            HttpCookie cookie = ViewContext.HttpContext.Request.Cookies[cookieName];\r
+            if (cookie != null) {\r
+                cookieToken = Serializer.Deserialize(cookie.Value);\r
+            }\r
+            else {\r
+                cookieToken = AntiForgeryData.NewToken();\r
+                string cookieValue = Serializer.Serialize(cookieToken);\r
+\r
+                HttpCookie newCookie = new HttpCookie(cookieName, cookieValue) { HttpOnly = true, Domain = domain };\r
+                if (!String.IsNullOrEmpty(path)) {\r
+                    newCookie.Path = path;\r
+                }\r
+                ViewContext.HttpContext.Response.Cookies.Set(newCookie);\r
+            }\r
+\r
+            AntiForgeryData formToken = new AntiForgeryData(cookieToken) {\r
+                Salt = salt,\r
+                Username = AntiForgeryData.GetUsername(ViewContext.HttpContext.User)\r
+            };\r
+            string formValue = Serializer.Serialize(formToken);\r
+            return formValue;\r
+        }\r
+\r
+        public static string GetFormMethodString(FormMethod method) {\r
+            switch (method) {\r
+                case FormMethod.Get:\r
+                    return "get";\r
+                case FormMethod.Post:\r
+                    return "post";\r
+                default:\r
+                    return "post";\r
+            }\r
+        }\r
+\r
+        // selects the v3.5 (legacy) or v4 HTML encoder\r
+        private static HtmlEncoder GetHtmlEncoder() {\r
+            return TypeHelpers.CreateDelegate<HtmlEncoder>(TypeHelpers.SystemWebAssembly, "System.Web.HttpUtility", "HtmlEncode", null)\r
+                ?? EncodeLegacy;\r
+        }\r
+\r
+        public static string GetInputTypeString(InputType inputType) {\r
+            switch (inputType) {\r
+                case InputType.CheckBox:\r
+                    return "checkbox";\r
+                case InputType.Hidden:\r
+                    return "hidden";\r
+                case InputType.Password:\r
+                    return "password";\r
+                case InputType.Radio:\r
+                    return "radio";\r
+                case InputType.Text:\r
+                    return "text";\r
+                default:\r
+                    return "text";\r
+            }\r
+        }\r
+\r
+        internal object GetModelStateValue(string key, Type destinationType) {\r
+            ModelState modelState;\r
+            if (ViewData.ModelState.TryGetValue(key, out modelState)) {\r
+                if (modelState.Value != null) {\r
+                    return modelState.Value.ConvertTo(destinationType, null /* culture */);\r
+                }\r
+            }\r
+            return null;\r
+        }\r
+\r
+        public MvcHtmlString HttpMethodOverride(HttpVerbs httpVerb) {\r
+            string httpMethod;\r
+            switch (httpVerb) {\r
+                case HttpVerbs.Delete:\r
+                    httpMethod = "DELETE";\r
+                    break;\r
+                case HttpVerbs.Head:\r
+                    httpMethod = "HEAD";\r
+                    break;\r
+                case HttpVerbs.Put:\r
+                    httpMethod = "PUT";\r
+                    break;\r
+                default:\r
+                    throw new ArgumentException(MvcResources.HtmlHelper_InvalidHttpVerb, "httpVerb");\r
+            }\r
+\r
+            return HttpMethodOverride(httpMethod);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic",\r
+            Justification = "For consistency, all helpers are instance methods.")]\r
+        public MvcHtmlString HttpMethodOverride(string httpMethod) {\r
+            if (String.IsNullOrEmpty(httpMethod)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "httpMethod");\r
+            }\r
+            if (String.Equals(httpMethod, "GET", StringComparison.OrdinalIgnoreCase) ||\r
+                String.Equals(httpMethod, "POST", StringComparison.OrdinalIgnoreCase)) {\r
+                throw new ArgumentException(MvcResources.HtmlHelper_InvalidHttpMethod, "httpMethod");\r
+            }\r
+\r
+            TagBuilder tagBuilder = new TagBuilder("input");\r
+            tagBuilder.Attributes["type"] = "hidden";\r
+            tagBuilder.Attributes["name"] = HttpRequestExtensions.XHttpMethodOverrideKey;\r
+            tagBuilder.Attributes["value"] = httpMethod;\r
+\r
+            return tagBuilder.ToMvcHtmlString(TagRenderMode.SelfClosing);\r
+        }\r
+\r
+        internal virtual void RenderPartialInternal(string partialViewName, ViewDataDictionary viewData, object model, TextWriter writer, ViewEngineCollection viewEngineCollection) {\r
+            if (String.IsNullOrEmpty(partialViewName)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "partialViewName");\r
+            }\r
+\r
+            ViewDataDictionary newViewData = null;\r
+\r
+            if (model == null) {\r
+                if (viewData == null) {\r
+                    newViewData = new ViewDataDictionary(ViewData);\r
+                }\r
+                else {\r
+                    newViewData = new ViewDataDictionary(viewData);\r
+                }\r
+            }\r
+            else {\r
+                if (viewData == null) {\r
+                    newViewData = new ViewDataDictionary(model);\r
+                }\r
+                else {\r
+                    newViewData = new ViewDataDictionary(viewData) { Model = model };\r
+                }\r
+            }\r
+\r
+            ViewContext newViewContext = new ViewContext(ViewContext, ViewContext.View, newViewData, ViewContext.TempData, writer);\r
+            IView view = FindPartialView(newViewContext, partialViewName, viewEngineCollection);\r
+            view.Render(newViewContext, writer);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/HtmlHelper`1.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/HtmlHelper`1.cs
new file mode 100644 (file)
index 0000000..243f7f6
--- /dev/null
@@ -0,0 +1,35 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Web.Routing;\r
+\r
+    public class HtmlHelper<TModel> : HtmlHelper {\r
+        private ViewDataDictionary<TModel> _viewData;\r
+\r
+        public HtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer)\r
+            : this(viewContext, viewDataContainer, RouteTable.Routes) {\r
+        }\r
+\r
+        public HtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer, RouteCollection routeCollection)\r
+            : base(viewContext, viewDataContainer, routeCollection) {\r
+\r
+            _viewData = new ViewDataDictionary<TModel>(viewDataContainer.ViewData);\r
+        }\r
+\r
+        public new ViewDataDictionary<TModel> ViewData {\r
+            get {\r
+                return _viewData;\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpAntiForgeryException.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpAntiForgeryException.cs
new file mode 100644 (file)
index 0000000..8a8cf34
--- /dev/null
@@ -0,0 +1,37 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Runtime.Serialization;\r
+    using System.Web;\r
+\r
+    [Serializable]\r
+    public sealed class HttpAntiForgeryException : HttpException {\r
+\r
+        public HttpAntiForgeryException() {\r
+        }\r
+\r
+        private HttpAntiForgeryException(SerializationInfo info, StreamingContext context)\r
+            : base(info, context) {\r
+        }\r
+\r
+        public HttpAntiForgeryException(string message)\r
+            : base(message) {\r
+        }\r
+\r
+        public HttpAntiForgeryException(string message, Exception innerException)\r
+            : base(message, innerException) {\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpDeleteAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpDeleteAttribute.cs
new file mode 100644 (file)
index 0000000..1314f05
--- /dev/null
@@ -0,0 +1,27 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Reflection;\r
+    using System.Web;\r
+\r
+    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\r
+    public sealed class HttpDeleteAttribute : ActionMethodSelectorAttribute {\r
+\r
+        private static readonly AcceptVerbsAttribute _innerAttribute = new AcceptVerbsAttribute(HttpVerbs.Delete);\r
+\r
+        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) {\r
+            return _innerAttribute.IsValidForRequest(controllerContext, methodInfo);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpFileCollectionValueProvider.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpFileCollectionValueProvider.cs
new file mode 100644 (file)
index 0000000..d67ec5e
--- /dev/null
@@ -0,0 +1,52 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+\r
+    public sealed class HttpFileCollectionValueProvider : DictionaryValueProvider<HttpPostedFileBase[]> {\r
+\r
+        private static readonly Dictionary<string, HttpPostedFileBase[]> _emptyDictionary = new Dictionary<string, HttpPostedFileBase[]>();\r
+\r
+        public HttpFileCollectionValueProvider(ControllerContext controllerContext)\r
+            : base(GetHttpPostedFileDictionary(controllerContext), CultureInfo.InvariantCulture) {\r
+        }\r
+\r
+        private static Dictionary<string, HttpPostedFileBase[]> GetHttpPostedFileDictionary(ControllerContext controllerContext) {\r
+            HttpFileCollectionBase files = controllerContext.HttpContext.Request.Files;\r
+\r
+            // fast-track common case of no files\r
+            if (files.Count == 0) {\r
+                return _emptyDictionary;\r
+            }\r
+\r
+            // build up the 1:many file mapping\r
+            List<KeyValuePair<string, HttpPostedFileBase>> mapping = new List<KeyValuePair<string, HttpPostedFileBase>>();\r
+            string[] allKeys = files.AllKeys;\r
+            for (int i = 0; i < files.Count; i++) {\r
+                string key = allKeys[i];\r
+                if (key != null) {\r
+                    HttpPostedFileBase file = HttpPostedFileBaseModelBinder.ChooseFileOrNull(files[i]);\r
+                    mapping.Add(new KeyValuePair<string, HttpPostedFileBase>(key, file));\r
+                }\r
+            }\r
+\r
+            // turn the mapping into a 1:many dictionary\r
+            var grouped = mapping.GroupBy(el => el.Key, el => el.Value, StringComparer.OrdinalIgnoreCase);\r
+            return grouped.ToDictionary(g => g.Key, g => g.ToArray(), StringComparer.OrdinalIgnoreCase);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpFileCollectionValueProviderFactory.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpFileCollectionValueProviderFactory.cs
new file mode 100644 (file)
index 0000000..6eec3ce
--- /dev/null
@@ -0,0 +1,27 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    public sealed class HttpFileCollectionValueProviderFactory : ValueProviderFactory {\r
+\r
+        public override IValueProvider GetValueProvider(ControllerContext controllerContext) {\r
+            if (controllerContext == null) {\r
+                throw new ArgumentNullException("controllerContext");\r
+            }\r
+\r
+            return new HttpFileCollectionValueProvider(controllerContext);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpGetAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpGetAttribute.cs
new file mode 100644 (file)
index 0000000..d2f2e9e
--- /dev/null
@@ -0,0 +1,27 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Reflection;\r
+    using System.Web;\r
+\r
+    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\r
+    public sealed class HttpGetAttribute : ActionMethodSelectorAttribute {\r
+\r
+        private static readonly AcceptVerbsAttribute _innerAttribute = new AcceptVerbsAttribute(HttpVerbs.Get);\r
+\r
+        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) {\r
+            return _innerAttribute.IsValidForRequest(controllerContext, methodInfo);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpHandlerUtil.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpHandlerUtil.cs
new file mode 100644 (file)
index 0000000..a9b1f8d
--- /dev/null
@@ -0,0 +1,87 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Web;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.UI;\r
+\r
+    internal static class HttpHandlerUtil {\r
+\r
+        // Since Server.Execute() doesn't propagate HttpExceptions where the status code is\r
+        // anything other than 500, we need to wrap these exceptions ourselves.\r
+        public static IHttpHandler WrapForServerExecute(IHttpHandler httpHandler) {\r
+            IHttpAsyncHandler asyncHandler = httpHandler as IHttpAsyncHandler;\r
+            return (asyncHandler != null) ? new ServerExecuteHttpHandlerAsyncWrapper(asyncHandler) : new ServerExecuteHttpHandlerWrapper(httpHandler);\r
+        }\r
+\r
+        // Server.Execute() requires that the provided IHttpHandler subclass Page.\r
+        internal class ServerExecuteHttpHandlerWrapper : Page {\r
+            private readonly IHttpHandler _httpHandler;\r
+\r
+            public ServerExecuteHttpHandlerWrapper(IHttpHandler httpHandler) {\r
+                _httpHandler = httpHandler;\r
+            }\r
+\r
+            internal IHttpHandler InnerHandler {\r
+                get {\r
+                    return _httpHandler;\r
+                }\r
+            }\r
+\r
+            public override void ProcessRequest(HttpContext context) {\r
+                Wrap(() => _httpHandler.ProcessRequest(context));\r
+            }\r
+\r
+            protected static void Wrap(Action action) {\r
+                Wrap(delegate {\r
+                    action();\r
+                    return (object)null;\r
+                });\r
+            }\r
+\r
+            protected static TResult Wrap<TResult>(Func<TResult> func) {\r
+                try {\r
+                    return func();\r
+                }\r
+                catch (HttpException he) {\r
+                    if (he.GetHttpCode() == 500) {\r
+                        throw; // doesn't need to be wrapped\r
+                    }\r
+                    else {\r
+                        HttpException newHe = new HttpException(500, MvcResources.ViewPageHttpHandlerWrapper_ExceptionOccurred, he);\r
+                        throw newHe;\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+        private sealed class ServerExecuteHttpHandlerAsyncWrapper : ServerExecuteHttpHandlerWrapper, IHttpAsyncHandler {\r
+            private readonly IHttpAsyncHandler _httpHandler;\r
+\r
+            public ServerExecuteHttpHandlerAsyncWrapper(IHttpAsyncHandler httpHandler)\r
+                : base(httpHandler) {\r
+                _httpHandler = httpHandler;\r
+            }\r
+\r
+            public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) {\r
+                return Wrap(() => _httpHandler.BeginProcessRequest(context, cb, extraData));\r
+            }\r
+\r
+            public void EndProcessRequest(IAsyncResult result) {\r
+                Wrap(() => _httpHandler.EndProcessRequest(result));\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpPostAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpPostAttribute.cs
new file mode 100644 (file)
index 0000000..8a07d95
--- /dev/null
@@ -0,0 +1,27 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Reflection;\r
+    using System.Web;\r
+\r
+    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\r
+    public sealed class HttpPostAttribute : ActionMethodSelectorAttribute {\r
+\r
+        private static readonly AcceptVerbsAttribute _innerAttribute = new AcceptVerbsAttribute(HttpVerbs.Post);\r
+\r
+        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) {\r
+            return _innerAttribute.IsValidForRequest(controllerContext, methodInfo);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpPostedFileBaseModelBinder.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpPostedFileBaseModelBinder.cs
new file mode 100644 (file)
index 0000000..4adb369
--- /dev/null
@@ -0,0 +1,48 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Web;\r
+\r
+    public class HttpPostedFileBaseModelBinder : IModelBinder {\r
+\r
+        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {\r
+            if (controllerContext == null) {\r
+                throw new ArgumentNullException("controllerContext");\r
+            }\r
+            if (bindingContext == null) {\r
+                throw new ArgumentNullException("bindingContext");\r
+            }\r
+\r
+            HttpPostedFileBase theFile = controllerContext.HttpContext.Request.Files[bindingContext.ModelName];\r
+            return ChooseFileOrNull(theFile);\r
+        }\r
+\r
+        // helper that returns the original file if there was content uploaded, null if empty\r
+        internal static HttpPostedFileBase ChooseFileOrNull(HttpPostedFileBase rawFile) {\r
+            // case 1: there was no <input type="file" ... /> element in the post\r
+            if (rawFile == null) {\r
+                return null;\r
+            }\r
+\r
+            // case 2: there was an <input type="file" ... /> element in the post, but it was left blank\r
+            if (rawFile.ContentLength == 0 && String.IsNullOrEmpty(rawFile.FileName)) {\r
+                return null;\r
+            }\r
+\r
+            // case 3: the file was posted\r
+            return rawFile;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpPutAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpPutAttribute.cs
new file mode 100644 (file)
index 0000000..d438f3d
--- /dev/null
@@ -0,0 +1,27 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Reflection;\r
+    using System.Web;\r
+\r
+    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\r
+    public sealed class HttpPutAttribute : ActionMethodSelectorAttribute {\r
+\r
+        private static readonly AcceptVerbsAttribute _innerAttribute = new AcceptVerbsAttribute(HttpVerbs.Put);\r
+\r
+        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) {\r
+            return _innerAttribute.IsValidForRequest(controllerContext, methodInfo);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpRequestExtensions.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpRequestExtensions.cs
new file mode 100644 (file)
index 0000000..07a76e1
--- /dev/null
@@ -0,0 +1,56 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    public static class HttpRequestExtensions {\r
+        internal const string XHttpMethodOverrideKey = "X-HTTP-Method-Override";\r
+\r
+        public static string GetHttpMethodOverride(this HttpRequestBase request) {\r
+            if (request == null) {\r
+                throw new ArgumentNullException("request");\r
+            }\r
+\r
+            string incomingVerb = request.HttpMethod;\r
+\r
+            if (!String.Equals(incomingVerb, "POST", StringComparison.OrdinalIgnoreCase)) {\r
+                return incomingVerb;\r
+            }\r
+\r
+            string verbOverride = null;\r
+            string headerOverrideValue = request.Headers[XHttpMethodOverrideKey];\r
+            if (!String.IsNullOrEmpty(headerOverrideValue)) {\r
+                verbOverride = headerOverrideValue;\r
+            }\r
+            else {\r
+                string formOverrideValue = request.Form[XHttpMethodOverrideKey];\r
+                if (!String.IsNullOrEmpty(formOverrideValue)) {\r
+                    verbOverride = formOverrideValue;\r
+                }\r
+                else {\r
+                    string queryStringOverrideValue = request.QueryString[XHttpMethodOverrideKey];\r
+                    if (!String.IsNullOrEmpty(queryStringOverrideValue)) {\r
+                        verbOverride = queryStringOverrideValue;\r
+                    }\r
+                }\r
+            }\r
+            if (verbOverride != null) {\r
+                if (!String.Equals(verbOverride, "GET", StringComparison.OrdinalIgnoreCase) &&\r
+                    !String.Equals(verbOverride, "POST", StringComparison.OrdinalIgnoreCase)) {\r
+                    incomingVerb = verbOverride;\r
+                }\r
+            }\r
+            return incomingVerb;\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpUnauthorizedResult.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpUnauthorizedResult.cs
new file mode 100644 (file)
index 0000000..cae9d1d
--- /dev/null
@@ -0,0 +1,30 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    public class HttpUnauthorizedResult : ActionResult {\r
+\r
+        public override void ExecuteResult(ControllerContext context) {\r
+            if (context == null) {\r
+                throw new ArgumentNullException("context");\r
+            }\r
+\r
+            // HTTP 401 is the status code for unauthorized access. Other code might\r
+            // intercept this and perform some special logic. For example, the\r
+            // FormsAuthenticationModule looks for 401 responses and instead redirects\r
+            // the user to the login page.\r
+            context.HttpContext.Response.StatusCode = 401;\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpVerbs.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/HttpVerbs.cs
new file mode 100644 (file)
index 0000000..b9506c1
--- /dev/null
@@ -0,0 +1,24 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    [Flags]\r
+    public enum HttpVerbs {\r
+        Get = 1 << 0,\r
+        Post = 1 << 1,\r
+        Put = 1 << 2,\r
+        Delete = 1 << 3,\r
+        Head = 1 << 4\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/IActionFilter.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/IActionFilter.cs
new file mode 100644 (file)
index 0000000..2cc7f3e
--- /dev/null
@@ -0,0 +1,19 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+\r
+    public interface IActionFilter {\r
+        void OnActionExecuting(ActionExecutingContext filterContext);\r
+        void OnActionExecuted(ActionExecutedContext filterContext);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/IActionInvoker.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/IActionInvoker.cs
new file mode 100644 (file)
index 0000000..9ab878d
--- /dev/null
@@ -0,0 +1,18 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+\r
+    public interface IActionInvoker {\r
+        bool InvokeAction(ControllerContext controllerContext, string actionName);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/IAuthorizationFilter.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/IAuthorizationFilter.cs
new file mode 100644 (file)
index 0000000..93ab7b3
--- /dev/null
@@ -0,0 +1,18 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+\r
+    public interface IAuthorizationFilter {\r
+        void OnAuthorization(AuthorizationContext filterContext);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/IBuildManager.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/IBuildManager.cs
new file mode 100644 (file)
index 0000000..34eea42
--- /dev/null
@@ -0,0 +1,26 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Collections;\r
+    using System.IO;\r
+\r
+    // REVIEW: Should we make this public?\r
+    internal interface IBuildManager {\r
+        object CreateInstanceFromVirtualPath(string virtualPath, Type requiredBaseType);\r
+        ICollection GetReferencedAssemblies();\r
+\r
+        // ASP.NET 4 methods\r
+        Stream ReadCachedFile(string fileName);\r
+        Stream CreateCachedFile(string fileName);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/IController.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/IController.cs
new file mode 100644 (file)
index 0000000..d5bb4ca
--- /dev/null
@@ -0,0 +1,19 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Web.Routing;\r
+\r
+    public interface IController {\r
+        void Execute(RequestContext requestContext);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/IControllerFactory.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/IControllerFactory.cs
new file mode 100644 (file)
index 0000000..316774f
--- /dev/null
@@ -0,0 +1,20 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Web.Routing;\r
+\r
+    public interface IControllerFactory {\r
+        IController CreateController(RequestContext requestContext, string controllerName);\r
+        void ReleaseController(IController controller);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/IExceptionFilter.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/IExceptionFilter.cs
new file mode 100644 (file)
index 0000000..ede6fd3
--- /dev/null
@@ -0,0 +1,18 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+\r
+    public interface IExceptionFilter {\r
+        void OnException(ExceptionContext filterContext);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/IModelBinder.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/IModelBinder.cs
new file mode 100644 (file)
index 0000000..d6ce039
--- /dev/null
@@ -0,0 +1,18 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+\r
+    public interface IModelBinder {\r
+        object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/IResultFilter.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/IResultFilter.cs
new file mode 100644 (file)
index 0000000..c00395f
--- /dev/null
@@ -0,0 +1,19 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+\r
+    public interface IResultFilter {\r
+        void OnResultExecuting(ResultExecutingContext filterContext);\r
+        void OnResultExecuted(ResultExecutedContext filterContext);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/IRouteWithArea.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/IRouteWithArea.cs
new file mode 100644 (file)
index 0000000..23eab10
--- /dev/null
@@ -0,0 +1,21 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    public interface IRouteWithArea {\r
+\r
+        string Area { get; }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ITempDataProvider.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ITempDataProvider.cs
new file mode 100644 (file)
index 0000000..3361130
--- /dev/null
@@ -0,0 +1,20 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Collections.Generic;\r
+\r
+    public interface ITempDataProvider {\r
+        IDictionary<string, object> LoadTempData(ControllerContext controllerContext);\r
+        void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/IValueProvider.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/IValueProvider.cs
new file mode 100644 (file)
index 0000000..95c7e16
--- /dev/null
@@ -0,0 +1,20 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    public interface IValueProvider {\r
+        bool ContainsPrefix(string prefix);\r
+        ValueProviderResult GetValue(string key);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/IView.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/IView.cs
new file mode 100644 (file)
index 0000000..97d044c
--- /dev/null
@@ -0,0 +1,19 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.IO;\r
+\r
+    public interface IView {\r
+        void Render(ViewContext viewContext, TextWriter writer);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/IViewDataContainer.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/IViewDataContainer.cs
new file mode 100644 (file)
index 0000000..c1bfacb
--- /dev/null
@@ -0,0 +1,21 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Diagnostics.CodeAnalysis;\r
+\r
+    public interface IViewDataContainer {\r
+        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly",\r
+            Justification = "This is the mechanism by which the ViewPage / ViewUserControl get their ViewDataDictionary objects.")]\r
+        ViewDataDictionary ViewData { get; set; }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/IViewEngine.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/IViewEngine.cs
new file mode 100644 (file)
index 0000000..9950ce7
--- /dev/null
@@ -0,0 +1,20 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+\r
+    public interface IViewEngine {\r
+        ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache);\r
+        ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache);\r
+        void ReleaseView(ControllerContext controllerContext, IView view);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/IViewLocationCache.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/IViewLocationCache.cs
new file mode 100644 (file)
index 0000000..824950b
--- /dev/null
@@ -0,0 +1,20 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Web;\r
+\r
+    public interface IViewLocationCache {\r
+        string GetViewLocation(HttpContextBase httpContext, string key);\r
+        void InsertViewLocation(HttpContextBase httpContext, string key, string virtualPath);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/InputType.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/InputType.cs
new file mode 100644 (file)
index 0000000..a4a39d8
--- /dev/null
@@ -0,0 +1,21 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    public enum InputType {\r
+        CheckBox,\r
+        Hidden,\r
+        Password,\r
+        Radio,\r
+        Text\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/JavaScriptResult.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/JavaScriptResult.cs
new file mode 100644 (file)
index 0000000..4ee833e
--- /dev/null
@@ -0,0 +1,36 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    public class JavaScriptResult : ActionResult {\r
+\r
+        public string Script {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public override void ExecuteResult(ControllerContext context) {\r
+            if (context == null) {\r
+                throw new ArgumentNullException("context");\r
+            }\r
+\r
+            HttpResponseBase response = context.HttpContext.Response;\r
+            response.ContentType = "application/x-javascript";\r
+\r
+            if (Script != null) {\r
+                response.Write(Script);\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/JsonRequestBehavior.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/JsonRequestBehavior.cs
new file mode 100644 (file)
index 0000000..da9ee8f
--- /dev/null
@@ -0,0 +1,18 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    public enum JsonRequestBehavior {\r
+        AllowGet,\r
+        DenyGet,\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/JsonResult.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/JsonResult.cs
new file mode 100644 (file)
index 0000000..3950b09
--- /dev/null
@@ -0,0 +1,72 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Text;\r
+    using System.Web;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.Script.Serialization;\r
+\r
+    public class JsonResult : ActionResult {\r
+\r
+        public JsonResult() {\r
+            JsonRequestBehavior = JsonRequestBehavior.DenyGet;\r
+        }\r
+\r
+        public Encoding ContentEncoding {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public string ContentType {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public object Data {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public JsonRequestBehavior JsonRequestBehavior {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public override void ExecuteResult(ControllerContext context) {\r
+            if (context == null) {\r
+                throw new ArgumentNullException("context");\r
+            }\r
+            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&\r
+                String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) {\r
+                throw new InvalidOperationException(MvcResources.JsonRequest_GetNotAllowed);\r
+            }\r
+\r
+            HttpResponseBase response = context.HttpContext.Response;\r
+\r
+            if (!String.IsNullOrEmpty(ContentType)) {\r
+                response.ContentType = ContentType;\r
+            }\r
+            else {\r
+                response.ContentType = "application/json";\r
+            }\r
+            if (ContentEncoding != null) {\r
+                response.ContentEncoding = ContentEncoding;\r
+            }\r
+            if (Data != null) {\r
+                JavaScriptSerializer serializer = new JavaScriptSerializer();\r
+                response.Write(serializer.Serialize(Data));\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/LinqBinaryModelBinder.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/LinqBinaryModelBinder.cs
new file mode 100644 (file)
index 0000000..4d5edcc
--- /dev/null
@@ -0,0 +1,26 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Data.Linq;\r
+\r
+    public class LinqBinaryModelBinder : ByteArrayModelBinder {\r
+        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {\r
+            byte[] byteValue = (byte[])base.BindModel(controllerContext, bindingContext);\r
+            if (byteValue == null) {\r
+                return null;\r
+            }\r
+\r
+            return new Binary(byteValue);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelBinderAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelBinderAttribute.cs
new file mode 100644 (file)
index 0000000..b057c73
--- /dev/null
@@ -0,0 +1,54 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Globalization;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    [AttributeUsage(ValidTargets, AllowMultiple = false, Inherited = false)]\r
+    public sealed class ModelBinderAttribute : CustomModelBinderAttribute {\r
+\r
+        public ModelBinderAttribute(Type binderType) {\r
+            if (binderType == null) {\r
+                throw new ArgumentNullException("binderType");\r
+            }\r
+            if (!typeof(IModelBinder).IsAssignableFrom(binderType)) {\r
+                string message = String.Format(CultureInfo.CurrentUICulture,\r
+                    MvcResources.ModelBinderAttribute_TypeNotIModelBinder, binderType.FullName);\r
+                throw new ArgumentException(message, "binderType");\r
+            }\r
+\r
+            BinderType = binderType;\r
+        }\r
+\r
+        public Type BinderType {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public override IModelBinder GetBinder() {\r
+            try {\r
+                return (IModelBinder)Activator.CreateInstance(BinderType);\r
+            }\r
+            catch (Exception ex) {\r
+                throw new InvalidOperationException(\r
+                    String.Format(\r
+                        CultureInfo.CurrentUICulture,\r
+                        MvcResources.ModelBinderAttribute_ErrorCreatingModelBinder,\r
+                        BinderType.FullName),\r
+                    ex);\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelBinderDictionary.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelBinderDictionary.cs
new file mode 100644 (file)
index 0000000..964db46
--- /dev/null
@@ -0,0 +1,148 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections;\r
+    using System.Collections.Generic;\r
+    using System.Globalization;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public class ModelBinderDictionary : IDictionary<Type, IModelBinder> {\r
+\r
+        private IModelBinder _defaultBinder;\r
+        private readonly Dictionary<Type, IModelBinder> _innerDictionary = new Dictionary<Type, IModelBinder>();\r
+\r
+        public int Count {\r
+            get {\r
+                return _innerDictionary.Count;\r
+            }\r
+        }\r
+\r
+        public IModelBinder DefaultBinder {\r
+            get {\r
+                if (_defaultBinder == null) {\r
+                    _defaultBinder = new DefaultModelBinder();\r
+                }\r
+                return _defaultBinder;\r
+            }\r
+            set {\r
+                _defaultBinder = value;\r
+            }\r
+        }\r
+\r
+        public bool IsReadOnly {\r
+            get {\r
+                return ((IDictionary<Type, IModelBinder>)_innerDictionary).IsReadOnly;\r
+            }\r
+        }\r
+\r
+        public ICollection<Type> Keys {\r
+            get {\r
+                return _innerDictionary.Keys;\r
+            }\r
+        }\r
+\r
+        public IModelBinder this[Type key] {\r
+            get {\r
+                IModelBinder binder;\r
+                _innerDictionary.TryGetValue(key, out binder);\r
+                return binder;\r
+            }\r
+            set {\r
+                _innerDictionary[key] = value;\r
+            }\r
+        }\r
+\r
+        public ICollection<IModelBinder> Values {\r
+            get {\r
+                return _innerDictionary.Values;\r
+            }\r
+        }\r
+\r
+        public void Add(KeyValuePair<Type, IModelBinder> item) {\r
+            ((IDictionary<Type, IModelBinder>)_innerDictionary).Add(item);\r
+        }\r
+\r
+        public void Add(Type key, IModelBinder value) {\r
+            _innerDictionary.Add(key, value);\r
+        }\r
+\r
+        public void Clear() {\r
+            _innerDictionary.Clear();\r
+        }\r
+\r
+        public bool Contains(KeyValuePair<Type, IModelBinder> item) {\r
+            return ((IDictionary<Type, IModelBinder>)_innerDictionary).Contains(item);\r
+        }\r
+\r
+        public bool ContainsKey(Type key) {\r
+            return _innerDictionary.ContainsKey(key);\r
+        }\r
+\r
+        public void CopyTo(KeyValuePair<Type, IModelBinder>[] array, int arrayIndex) {\r
+            ((IDictionary<Type, IModelBinder>)_innerDictionary).CopyTo(array, arrayIndex);\r
+        }\r
+\r
+        public IModelBinder GetBinder(Type modelType) {\r
+            return GetBinder(modelType, true /* fallbackToDefault */);\r
+        }\r
+\r
+        public virtual IModelBinder GetBinder(Type modelType, bool fallbackToDefault) {\r
+            if (modelType == null) {\r
+                throw new ArgumentNullException("modelType");\r
+            }\r
+\r
+            return GetBinder(modelType, (fallbackToDefault) ? DefaultBinder : null);\r
+        }\r
+\r
+        private IModelBinder GetBinder(Type modelType, IModelBinder fallbackBinder) {\r
+            // Try to look up a binder for this type. We use this order of precedence:\r
+            // 1. Binder registered in the global table\r
+            // 2. Binder attribute defined on the type\r
+            // 3. Supplied fallback binder\r
+\r
+            IModelBinder binder;\r
+            if (_innerDictionary.TryGetValue(modelType, out binder)) {\r
+                return binder;\r
+            }\r
+\r
+            binder = ModelBinders.GetBinderFromAttributes(modelType,\r
+                () => String.Format(CultureInfo.CurrentUICulture, MvcResources.ModelBinderDictionary_MultipleAttributes, modelType.FullName));\r
+\r
+            return binder ?? fallbackBinder;\r
+        }\r
+\r
+        public IEnumerator<KeyValuePair<Type, IModelBinder>> GetEnumerator() {\r
+            return _innerDictionary.GetEnumerator();\r
+        }\r
+\r
+        public bool Remove(KeyValuePair<Type, IModelBinder> item) {\r
+            return ((IDictionary<Type, IModelBinder>)_innerDictionary).Remove(item);\r
+        }\r
+\r
+        public bool Remove(Type key) {\r
+            return _innerDictionary.Remove(key);\r
+        }\r
+\r
+        public bool TryGetValue(Type key, out IModelBinder value) {\r
+            return _innerDictionary.TryGetValue(key, out value);\r
+        }\r
+\r
+        #region IEnumerable Members\r
+        IEnumerator IEnumerable.GetEnumerator() {\r
+            return ((IEnumerable)_innerDictionary).GetEnumerator();\r
+        }\r
+        #endregion\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelBinders.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelBinders.cs
new file mode 100644 (file)
index 0000000..f354b9d
--- /dev/null
@@ -0,0 +1,77 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.ComponentModel;\r
+    using System.Data.Linq;\r
+    using System.Linq;\r
+    using System.Reflection;\r
+    using System.Web;\r
+\r
+    public static class ModelBinders {\r
+\r
+        private static readonly ModelBinderDictionary _binders = CreateDefaultBinderDictionary();\r
+\r
+        public static ModelBinderDictionary Binders {\r
+            get {\r
+                return _binders;\r
+            }\r
+        }\r
+\r
+        internal static IModelBinder GetBinderFromAttributes(Type type, Func<string> errorMessageAccessor) {\r
+            AttributeCollection allAttrs = TypeDescriptorHelper.Get(type).GetAttributes();\r
+            CustomModelBinderAttribute[] filteredAttrs = allAttrs.OfType<CustomModelBinderAttribute>().ToArray();\r
+            return GetBinderFromAttributesImpl(filteredAttrs, errorMessageAccessor);\r
+        }\r
+\r
+        internal static IModelBinder GetBinderFromAttributes(ICustomAttributeProvider element, Func<string> errorMessageAccessor) {\r
+            CustomModelBinderAttribute[] attrs = (CustomModelBinderAttribute[])element.GetCustomAttributes(typeof(CustomModelBinderAttribute), true /* inherit */);\r
+            return GetBinderFromAttributesImpl(attrs, errorMessageAccessor);\r
+        }\r
+\r
+        private static IModelBinder GetBinderFromAttributesImpl(CustomModelBinderAttribute[] attrs, Func<string> errorMessageAccessor) {\r
+            // this method is used to get a custom binder based on the attributes of the element passed to it.\r
+            // it will return null if a binder cannot be detected based on the attributes alone.\r
+\r
+            if (attrs == null) {\r
+                return null;\r
+            }\r
+\r
+            switch (attrs.Length) {\r
+                case 0:\r
+                    return null;\r
+\r
+                case 1:\r
+                    IModelBinder binder = attrs[0].GetBinder();\r
+                    return binder;\r
+\r
+                default:\r
+                    string errorMessage = errorMessageAccessor();\r
+                    throw new InvalidOperationException(errorMessage);\r
+            }\r
+        }\r
+\r
+        private static ModelBinderDictionary CreateDefaultBinderDictionary() {\r
+            // We can't add a binder to the HttpPostedFileBase type as an attribute, so we'll just\r
+            // prepopulate the dictionary as a convenience to users.\r
+\r
+            ModelBinderDictionary binders = new ModelBinderDictionary() {\r
+                { typeof(HttpPostedFileBase), new HttpPostedFileBaseModelBinder() },\r
+                { typeof(byte[]), new ByteArrayModelBinder() },\r
+                { typeof(Binary), new LinqBinaryModelBinder() }\r
+            };\r
+            return binders;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelBindingContext.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelBindingContext.cs
new file mode 100644 (file)
index 0000000..c3f8fbd
--- /dev/null
@@ -0,0 +1,125 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Linq;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public class ModelBindingContext {\r
+\r
+        private static readonly Predicate<string> _defaultPropertyFilter = _ => true;\r
+\r
+        private string _modelName;\r
+        private ModelStateDictionary _modelState;\r
+        private Predicate<string> _propertyFilter;\r
+        private Dictionary<string, ModelMetadata> _propertyMetadata;\r
+\r
+        public ModelBindingContext()\r
+            : this(null) {\r
+        }\r
+\r
+        // copies certain values that won't change between parent and child objects,\r
+        // e.g. ValueProvider, ModelState\r
+        public ModelBindingContext(ModelBindingContext bindingContext) {\r
+            if (bindingContext != null) {\r
+                ModelState = bindingContext.ModelState;\r
+                ValueProvider = bindingContext.ValueProvider;\r
+            }\r
+        }\r
+\r
+        public bool FallbackToEmptyPrefix {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value", Justification = "Cannot remove setter as that's a breaking change")]\r
+        public object Model {\r
+            get {\r
+                return ModelMetadata.Model;\r
+            }\r
+            set {\r
+                throw new InvalidOperationException(MvcResources.ModelMetadata_PropertyNotSettable);\r
+            }\r
+        }\r
+\r
+        public ModelMetadata ModelMetadata {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public string ModelName {\r
+            get {\r
+                if (_modelName == null) {\r
+                    _modelName = String.Empty;\r
+                }\r
+                return _modelName;\r
+            }\r
+            set {\r
+                _modelName = value;\r
+            }\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "The containing type is mutable.")]\r
+        public ModelStateDictionary ModelState {\r
+            get {\r
+                if (_modelState == null) {\r
+                    _modelState = new ModelStateDictionary();\r
+                }\r
+                return _modelState;\r
+            }\r
+            set {\r
+                _modelState = value;\r
+            }\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value", Justification = "Cannot remove setter as that's a breaking change")]\r
+        public Type ModelType {\r
+            get {\r
+                return ModelMetadata.ModelType;\r
+            }\r
+            set {\r
+                throw new InvalidOperationException(MvcResources.ModelMetadata_PropertyNotSettable);\r
+            }\r
+        }\r
+\r
+        public Predicate<string> PropertyFilter {\r
+            get {\r
+                if (_propertyFilter == null) {\r
+                    _propertyFilter = _defaultPropertyFilter;\r
+                }\r
+                return _propertyFilter;\r
+            }\r
+            set {\r
+                _propertyFilter = value;\r
+            }\r
+        }\r
+\r
+        public IDictionary<string, ModelMetadata> PropertyMetadata {\r
+            get {\r
+                if (_propertyMetadata == null) {\r
+                    _propertyMetadata = ModelMetadata.Properties.ToDictionary(m => m.PropertyName, StringComparer.OrdinalIgnoreCase);\r
+                }\r
+\r
+                return _propertyMetadata;\r
+            }\r
+        }\r
+\r
+        public IValueProvider ValueProvider {\r
+            get;\r
+            set;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelClientValidationRangeRule.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelClientValidationRangeRule.cs
new file mode 100644 (file)
index 0000000..0d12858
--- /dev/null
@@ -0,0 +1,22 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    public class ModelClientValidationRangeRule : ModelClientValidationRule {\r
+        public ModelClientValidationRangeRule(string errorMessage, object minValue, object maxValue) {\r
+            ErrorMessage = errorMessage;\r
+            ValidationType = "range";\r
+            ValidationParameters["minimum"] = minValue;\r
+            ValidationParameters["maximum"] = maxValue;\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelClientValidationRegexRule.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelClientValidationRegexRule.cs
new file mode 100644 (file)
index 0000000..a012da6
--- /dev/null
@@ -0,0 +1,21 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    public class ModelClientValidationRegexRule : ModelClientValidationRule {\r
+        public ModelClientValidationRegexRule(string errorMessage, string pattern) {\r
+            ErrorMessage = errorMessage;\r
+            ValidationType = "regularExpression";\r
+            ValidationParameters.Add("pattern", pattern);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelClientValidationRequiredRule.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelClientValidationRequiredRule.cs
new file mode 100644 (file)
index 0000000..6ae6dc9
--- /dev/null
@@ -0,0 +1,20 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    public class ModelClientValidationRequiredRule : ModelClientValidationRule {\r
+        public ModelClientValidationRequiredRule(string errorMessage) {\r
+            ErrorMessage = errorMessage;\r
+            ValidationType = "required";\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelClientValidationRule.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelClientValidationRule.cs
new file mode 100644 (file)
index 0000000..99ed578
--- /dev/null
@@ -0,0 +1,43 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+\r
+    public class ModelClientValidationRule {\r
+\r
+        private readonly Dictionary<string, object> _validationParameters = new Dictionary<string, object>();\r
+        private string _validationType;\r
+\r
+        public string ErrorMessage {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public IDictionary<string, object> ValidationParameters {\r
+            get {\r
+                return _validationParameters;\r
+            }\r
+        }\r
+\r
+        public string ValidationType {\r
+            get {\r
+                return _validationType ?? String.Empty;\r
+            }\r
+            set {\r
+                _validationType = value;\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelClientValidationStringLengthRule.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelClientValidationStringLengthRule.cs
new file mode 100644 (file)
index 0000000..92999ee
--- /dev/null
@@ -0,0 +1,22 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    public class ModelClientValidationStringLengthRule : ModelClientValidationRule {\r
+        public ModelClientValidationStringLengthRule(string errorMessage, int minimumLength, int maximumLength) {\r
+            ErrorMessage = errorMessage;\r
+            ValidationType = "stringLength";\r
+            ValidationParameters["minimumLength"] = minimumLength;\r
+            ValidationParameters["maximumLength"] = maximumLength;\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelError.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelError.cs
new file mode 100644 (file)
index 0000000..a6fb177
--- /dev/null
@@ -0,0 +1,46 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    [Serializable]\r
+    public class ModelError {\r
+\r
+        public ModelError(Exception exception)\r
+            : this(exception, null /* errorMessage */) {\r
+        }\r
+\r
+        public ModelError(Exception exception, string errorMessage)\r
+            : this(errorMessage) {\r
+            if (exception == null) {\r
+                throw new ArgumentNullException("exception");\r
+            }\r
+\r
+            Exception = exception;\r
+        }\r
+\r
+        public ModelError(string errorMessage) {\r
+            ErrorMessage = errorMessage ?? String.Empty;\r
+        }\r
+\r
+        public Exception Exception {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public string ErrorMessage {\r
+            get;\r
+            private set;\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelErrorCollection.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelErrorCollection.cs
new file mode 100644 (file)
index 0000000..61898dd
--- /dev/null
@@ -0,0 +1,28 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.ObjectModel;\r
+\r
+    [Serializable]\r
+    public class ModelErrorCollection : Collection<ModelError> {\r
+\r
+        public void Add(Exception exception) {\r
+            Add(new ModelError(exception));\r
+        }\r
+\r
+        public void Add(string errorMessage) {\r
+            Add(new ModelError(errorMessage));\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelMetadata.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelMetadata.cs
new file mode 100644 (file)
index 0000000..54a56d6
--- /dev/null
@@ -0,0 +1,388 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.ComponentModel;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+    using System.Linq.Expressions;\r
+    using System.Reflection;\r
+    using System.Web.Mvc.ExpressionUtil;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public class ModelMetadata {\r
+        // Explicit backing store for the things we want initialized by default, so don't have to call\r
+        // the protected virtual setters of an auto-generated property\r
+        private Dictionary<string, object> _additionalValues = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\r
+        private readonly Type _containerType;\r
+        private bool _convertEmptyStringToNull = true;\r
+        private bool _isRequired;\r
+        private object _model;\r
+        private Func<object> _modelAccessor;\r
+        private readonly Type _modelType;\r
+        private IEnumerable<ModelMetadata> _properties;\r
+        private readonly string _propertyName;\r
+        private Type _realModelType;\r
+        private bool _showForDisplay = true;\r
+        private bool _showForEdit = true;\r
+        private string _simpleDisplayText;\r
+\r
+        public ModelMetadata(ModelMetadataProvider provider, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName) {\r
+            if (provider == null) {\r
+                throw new ArgumentNullException("provider");\r
+            }\r
+            if (modelType == null) {\r
+                throw new ArgumentNullException("modelType");\r
+            }\r
+\r
+            Provider = provider;\r
+\r
+            _containerType = containerType;\r
+            _isRequired = !TypeHelpers.TypeAllowsNullValue(modelType);\r
+            _modelAccessor = modelAccessor;\r
+            _modelType = modelType;\r
+            _propertyName = propertyName;\r
+        }\r
+\r
+        public virtual Dictionary<string, object> AdditionalValues {\r
+            get {\r
+                return _additionalValues;\r
+            }\r
+        }\r
+\r
+        public Type ContainerType {\r
+            get {\r
+                return _containerType;\r
+            }\r
+        }\r
+\r
+        public virtual bool ConvertEmptyStringToNull {\r
+            get {\r
+                return _convertEmptyStringToNull;\r
+            }\r
+            set {\r
+                _convertEmptyStringToNull = value;\r
+            }\r
+        }\r
+\r
+        public virtual string DataTypeName {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public virtual string Description {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public virtual string DisplayFormatString {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods", Justification = "The method is a delegating helper to choose among multiple property values")]\r
+        public virtual string DisplayName {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public virtual string EditFormatString {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public virtual bool HideSurroundingHtml {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public virtual bool IsComplexType {\r
+            get {\r
+                return !(TypeDescriptor.GetConverter(ModelType).CanConvertFrom(typeof(string)));\r
+            }\r
+        }\r
+\r
+        public bool IsNullableValueType {\r
+            get {\r
+                return TypeHelpers.IsNullableValueType(ModelType);\r
+            }\r
+        }\r
+\r
+        public virtual bool IsReadOnly {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public virtual bool IsRequired {\r
+            get {\r
+                return _isRequired;\r
+            }\r
+            set {\r
+                _isRequired = value;\r
+            }\r
+        }\r
+\r
+        public object Model {\r
+            get {\r
+                if (_modelAccessor != null) {\r
+                    _model = _modelAccessor();\r
+                    _modelAccessor = null;\r
+                }\r
+                return _model;\r
+            }\r
+            set {\r
+                _model = value;\r
+                _modelAccessor = null;\r
+            }\r
+        }\r
+\r
+        public Type ModelType {\r
+            get {\r
+                return _modelType;\r
+            }\r
+        }\r
+\r
+        public virtual string NullDisplayText { get; set; }\r
+\r
+        public virtual IEnumerable<ModelMetadata> Properties {\r
+            get {\r
+                if (_properties == null) {\r
+                    _properties = Provider.GetMetadataForProperties(Model, RealModelType);\r
+                }\r
+                return _properties;\r
+            }\r
+        }\r
+\r
+        public string PropertyName {\r
+            get {\r
+                return _propertyName;\r
+            }\r
+        }\r
+\r
+        protected ModelMetadataProvider Provider {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        internal Type RealModelType {\r
+            get {\r
+                if (_realModelType == null) {\r
+                    _realModelType = ModelType;\r
+\r
+                    // Don't call GetType() if the model is Nullable<T>, because it will\r
+                    // turn Nullable<T> into T for non-null values\r
+                    if (Model != null && !TypeHelpers.IsNullableValueType(ModelType)) {\r
+                        _realModelType = Model.GetType();\r
+                    }\r
+                }\r
+\r
+                return _realModelType;\r
+            }\r
+        }\r
+\r
+        public virtual string ShortDisplayName {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public virtual bool ShowForDisplay {\r
+            get {\r
+                return _showForDisplay;\r
+            }\r
+            set {\r
+                _showForDisplay = value;\r
+            }\r
+        }\r
+\r
+        public virtual bool ShowForEdit {\r
+            get {\r
+                return _showForEdit;\r
+            }\r
+            set {\r
+                _showForEdit = value;\r
+            }\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods", Justification = "This property delegates to the method when the user has not yet set a simple display text value.")]\r
+        public virtual string SimpleDisplayText {\r
+            get {\r
+                if (_simpleDisplayText == null) {\r
+                    _simpleDisplayText = GetSimpleDisplayText();\r
+                }\r
+                return _simpleDisplayText;\r
+            }\r
+            set {\r
+                _simpleDisplayText = value;\r
+            }\r
+        }\r
+\r
+        public virtual string TemplateHint {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public virtual string Watermark {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]\r
+        public static ModelMetadata FromLambdaExpression<TParameter, TValue>(Expression<Func<TParameter, TValue>> expression,\r
+                                                                             ViewDataDictionary<TParameter> viewData) {\r
+            if (expression == null) {\r
+                throw new ArgumentNullException("expression");\r
+            }\r
+            if (viewData == null) {\r
+                throw new ArgumentNullException("viewData");\r
+            }\r
+\r
+            string propertyName = null;\r
+            Type containerType = null;\r
+            bool legalExpression = false;\r
+\r
+            // Need to verify the expression is valid; it needs to at least end in something\r
+            // that we can convert to a meaningful string for model binding purposes\r
+\r
+            switch (expression.Body.NodeType) {\r
+                // ArrayIndex always means a single-dimensional indexer; multi-dimensional indexer is a method call to Get()\r
+                case ExpressionType.ArrayIndex:\r
+                    legalExpression = true;\r
+                    break;\r
+\r
+                // Only legal method call is a single argument indexer/DefaultMember call\r
+                case ExpressionType.Call:\r
+                    legalExpression = ExpressionHelper.IsSingleArgumentIndexer(expression.Body);\r
+                    break;\r
+\r
+                // Property/field access is always legal\r
+                case ExpressionType.MemberAccess:\r
+                    MemberExpression memberExpression = (MemberExpression)expression.Body;\r
+                    propertyName = memberExpression.Member is PropertyInfo ? memberExpression.Member.Name : null;\r
+                    containerType = memberExpression.Member.DeclaringType;\r
+                    legalExpression = true;\r
+                    break;\r
+\r
+                // Parameter expression means "model => model", so we delegate to FromModel\r
+                case ExpressionType.Parameter:\r
+                    return FromModel(viewData);\r
+            }\r
+\r
+            if (!legalExpression) {\r
+                throw new InvalidOperationException(MvcResources.TemplateHelpers_TemplateLimitations);\r
+            }\r
+\r
+            TParameter container = viewData.Model;\r
+            Func<object> modelAccessor = () =>\r
+            {\r
+                try {\r
+                    return CachedExpressionCompiler.Process(expression)(container);\r
+                }\r
+                catch (NullReferenceException) {\r
+                    return null;\r
+                }\r
+            };\r
+\r
+            return GetMetadataFromProvider(modelAccessor, typeof(TValue), propertyName, containerType);\r
+        }\r
+\r
+        private static ModelMetadata FromModel(ViewDataDictionary viewData) {\r
+            return viewData.ModelMetadata ?? GetMetadataFromProvider(null, typeof(string), null, null);\r
+        }\r
+\r
+        public static ModelMetadata FromStringExpression(string expression, ViewDataDictionary viewData) {\r
+            if (expression == null) {\r
+                throw new ArgumentNullException("expression");\r
+            }\r
+            if (viewData == null) {\r
+                throw new ArgumentNullException("viewData");\r
+            }\r
+            if (expression.Length == 0) {    // Empty string really means "model metadata for the current model"\r
+                return FromModel(viewData);\r
+            }\r
+\r
+            ViewDataInfo vdi = viewData.GetViewDataInfo(expression);\r
+            Type containerType = null;\r
+            Type modelType = null;\r
+            Func<object> modelAccessor = null;\r
+            string propertyName = null;\r
+\r
+            if (vdi != null) {\r
+                if (vdi.Container != null) {\r
+                    containerType = vdi.Container.GetType();\r
+                }\r
+\r
+                modelAccessor = () => vdi.Value;\r
+\r
+                if (vdi.PropertyDescriptor != null) {\r
+                    propertyName = vdi.PropertyDescriptor.Name;\r
+                    modelType = vdi.PropertyDescriptor.PropertyType;\r
+                }\r
+                else if (vdi.Value != null) {  // We only need to delay accessing properties (for LINQ to SQL)\r
+                    modelType = vdi.Value.GetType();\r
+                }\r
+            }\r
+            //  Try getting a property from ModelMetadata if we couldn't find an answer in ViewData\r
+            else if (viewData.ModelMetadata != null) {\r
+                ModelMetadata propertyMetadata = viewData.ModelMetadata.Properties.Where(p => p.PropertyName == expression).FirstOrDefault();\r
+                if (propertyMetadata != null) {\r
+                    return propertyMetadata;\r
+                }\r
+            }\r
+\r
+\r
+            return GetMetadataFromProvider(modelAccessor, modelType ?? typeof(string), propertyName, containerType);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "The method is a delegating helper to choose among multiple property values")]\r
+        public string GetDisplayName() {\r
+            return DisplayName ?? PropertyName ?? ModelType.Name;\r
+        }\r
+\r
+        private static ModelMetadata GetMetadataFromProvider(Func<object> modelAccessor, Type modelType, string propertyName, Type containerType) {\r
+            if (containerType != null && !String.IsNullOrEmpty(propertyName)) {\r
+                return ModelMetadataProviders.Current.GetMetadataForProperty(modelAccessor, containerType, propertyName);\r
+            }\r
+            return ModelMetadataProviders.Current.GetMetadataForType(modelAccessor, modelType);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "This method is used to resolve the simple display text when it was not explicitly set through other means.")]\r
+        protected virtual string GetSimpleDisplayText() {\r
+            if (Model == null) {\r
+                return NullDisplayText;\r
+            }\r
+\r
+            string toStringResult = Convert.ToString(Model, CultureInfo.CurrentCulture);\r
+            if (!toStringResult.Equals(Model.GetType().FullName, StringComparison.Ordinal)) {\r
+                return toStringResult;\r
+            }\r
+\r
+            ModelMetadata firstProperty = Properties.FirstOrDefault();\r
+            if (firstProperty == null) {\r
+                return String.Empty;\r
+            }\r
+\r
+            if (firstProperty.Model == null) {\r
+                return firstProperty.NullDisplayText;\r
+            }\r
+\r
+            return Convert.ToString(firstProperty.Model, CultureInfo.CurrentCulture);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "This method may perform non-trivial work.")]\r
+        public virtual IEnumerable<ModelValidator> GetValidators(ControllerContext context) {\r
+            return ModelValidatorProviders.Providers.GetValidators(this, context);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelMetadataProvider.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelMetadataProvider.cs
new file mode 100644 (file)
index 0000000..6e92367
--- /dev/null
@@ -0,0 +1,23 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Collections.Generic;\r
+\r
+    public abstract class ModelMetadataProvider {\r
+        public abstract IEnumerable<ModelMetadata> GetMetadataForProperties(object container, Type containerType);\r
+\r
+        public abstract ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, string propertyName);\r
+\r
+        public abstract ModelMetadata GetMetadataForType(Func<object> modelAccessor, Type modelType);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelMetadataProviders.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelMetadataProviders.cs
new file mode 100644 (file)
index 0000000..de948d1
--- /dev/null
@@ -0,0 +1,26 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    public static class ModelMetadataProviders {\r
+        private static ModelMetadataProvider _current = new DataAnnotationsModelMetadataProvider();\r
+\r
+        public static ModelMetadataProvider Current {\r
+            get {\r
+                return _current;\r
+            }\r
+            set {\r
+                _current = value ?? new EmptyModelMetadataProvider();\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelState.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelState.cs
new file mode 100644 (file)
index 0000000..38c5860
--- /dev/null
@@ -0,0 +1,31 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+\r
+    [Serializable]\r
+    public class ModelState {\r
+\r
+        private ModelErrorCollection _errors = new ModelErrorCollection();\r
+\r
+        public ValueProviderResult Value {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public ModelErrorCollection Errors {\r
+            get {\r
+                return _errors;\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelStateDictionary.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelStateDictionary.cs
new file mode 100644 (file)
index 0000000..2510505
--- /dev/null
@@ -0,0 +1,170 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections;\r
+    using System.Collections.Generic;\r
+    using System.Linq;\r
+\r
+    [Serializable]\r
+    public class ModelStateDictionary : IDictionary<string, ModelState> {\r
+\r
+        private readonly Dictionary<string, ModelState> _innerDictionary = new Dictionary<string, ModelState>(StringComparer.OrdinalIgnoreCase);\r
+\r
+        public ModelStateDictionary() {\r
+        }\r
+\r
+        public ModelStateDictionary(ModelStateDictionary dictionary) {\r
+            if (dictionary == null) {\r
+                throw new ArgumentNullException("dictionary");\r
+            }\r
+\r
+            foreach (var entry in dictionary) {\r
+                _innerDictionary.Add(entry.Key, entry.Value);\r
+            }\r
+        }\r
+\r
+        public int Count {\r
+            get {\r
+                return _innerDictionary.Count;\r
+            }\r
+        }\r
+\r
+        public bool IsReadOnly {\r
+            get {\r
+                return ((IDictionary<string, ModelState>)_innerDictionary).IsReadOnly;\r
+            }\r
+        }\r
+\r
+        public bool IsValid {\r
+            get {\r
+                return Values.All(modelState => modelState.Errors.Count == 0);\r
+            }\r
+        }\r
+\r
+        public ICollection<string> Keys {\r
+            get {\r
+                return _innerDictionary.Keys;\r
+            }\r
+        }\r
+\r
+        public ModelState this[string key] {\r
+            get {\r
+                ModelState value;\r
+                _innerDictionary.TryGetValue(key, out value);\r
+                return value;\r
+            }\r
+            set {\r
+                _innerDictionary[key] = value;\r
+            }\r
+        }\r
+\r
+        public ICollection<ModelState> Values {\r
+            get {\r
+                return _innerDictionary.Values;\r
+            }\r
+        }\r
+\r
+        public void Add(KeyValuePair<string, ModelState> item) {\r
+            ((IDictionary<string, ModelState>)_innerDictionary).Add(item);\r
+        }\r
+\r
+        public void Add(string key, ModelState value) {\r
+            _innerDictionary.Add(key, value);\r
+        }\r
+\r
+        public void AddModelError(string key, Exception exception) {\r
+            GetModelStateForKey(key).Errors.Add(exception);\r
+        }\r
+\r
+        public void AddModelError(string key, string errorMessage) {\r
+            GetModelStateForKey(key).Errors.Add(errorMessage);\r
+        }\r
+\r
+        public void Clear() {\r
+            _innerDictionary.Clear();\r
+        }\r
+\r
+        public bool Contains(KeyValuePair<string, ModelState> item) {\r
+            return ((IDictionary<string, ModelState>)_innerDictionary).Contains(item);\r
+        }\r
+\r
+        public bool ContainsKey(string key) {\r
+            return _innerDictionary.ContainsKey(key);\r
+        }\r
+\r
+        public void CopyTo(KeyValuePair<string, ModelState>[] array, int arrayIndex) {\r
+            ((IDictionary<string, ModelState>)_innerDictionary).CopyTo(array, arrayIndex);\r
+        }\r
+\r
+        public IEnumerator<KeyValuePair<string, ModelState>> GetEnumerator() {\r
+            return _innerDictionary.GetEnumerator();\r
+        }\r
+\r
+        private ModelState GetModelStateForKey(string key) {\r
+            if (key == null) {\r
+                throw new ArgumentNullException("key");\r
+            }\r
+\r
+            ModelState modelState;\r
+            if (!TryGetValue(key, out modelState)) {\r
+                modelState = new ModelState();\r
+                this[key] = modelState;\r
+            }\r
+\r
+            return modelState;\r
+        }\r
+\r
+        public bool IsValidField(string key) {\r
+            if (key == null) {\r
+                throw new ArgumentNullException("key");\r
+            }\r
+\r
+            // if the key is not found in the dictionary, we just say that it's valid (since there are no errors)\r
+            return DictionaryHelpers.FindKeysWithPrefix(this, key).All(entry => entry.Value.Errors.Count == 0);\r
+        }\r
+\r
+        public void Merge(ModelStateDictionary dictionary) {\r
+            if (dictionary == null) {\r
+                return;\r
+            }\r
+\r
+            foreach (var entry in dictionary) {\r
+                this[entry.Key] = entry.Value;\r
+            }\r
+        }\r
+\r
+        public bool Remove(KeyValuePair<string, ModelState> item) {\r
+            return ((IDictionary<string, ModelState>)_innerDictionary).Remove(item);\r
+        }\r
+\r
+        public bool Remove(string key) {\r
+            return _innerDictionary.Remove(key);\r
+        }\r
+\r
+        public void SetModelValue(string key, ValueProviderResult value) {\r
+            GetModelStateForKey(key).Value = value;\r
+        }\r
+\r
+        public bool TryGetValue(string key, out ModelState value) {\r
+            return _innerDictionary.TryGetValue(key, out value);\r
+        }\r
+\r
+        #region IEnumerable Members\r
+        IEnumerator IEnumerable.GetEnumerator() {\r
+            return ((IEnumerable)_innerDictionary).GetEnumerator();\r
+        }\r
+        #endregion\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelValidationResult.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelValidationResult.cs
new file mode 100644 (file)
index 0000000..dcb262e
--- /dev/null
@@ -0,0 +1,40 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    public class ModelValidationResult {\r
+\r
+        private string _memberName;\r
+        private string _message;\r
+\r
+        public string MemberName {\r
+            get {\r
+                return _memberName ?? String.Empty;\r
+            }\r
+            set {\r
+                _memberName = value;\r
+            }\r
+        }\r
+\r
+        public string Message {\r
+            get {\r
+                return _message ?? String.Empty;\r
+            }\r
+            set {\r
+                _message = value;\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelValidator.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelValidator.cs
new file mode 100644 (file)
index 0000000..0570bff
--- /dev/null
@@ -0,0 +1,83 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Linq;\r
+\r
+    public abstract class ModelValidator {\r
+        protected ModelValidator(ModelMetadata metadata, ControllerContext controllerContext) {\r
+            if (metadata == null) {\r
+                throw new ArgumentNullException("metadata");\r
+            }\r
+            if (controllerContext == null) {\r
+                throw new ArgumentNullException("controllerContext");\r
+            }\r
+\r
+            Metadata = metadata;\r
+            ControllerContext = controllerContext;\r
+        }\r
+\r
+        protected internal ControllerContext ControllerContext { get; private set; }\r
+\r
+        public virtual bool IsRequired {\r
+            get {\r
+                return false;\r
+            }\r
+        }\r
+\r
+        protected internal ModelMetadata Metadata { get; private set; }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "This method may perform non-trivial work.")]\r
+        public virtual IEnumerable<ModelClientValidationRule> GetClientValidationRules() {\r
+            return Enumerable.Empty<ModelClientValidationRule>();\r
+        }\r
+\r
+        public static ModelValidator GetModelValidator(ModelMetadata metadata, ControllerContext context) {\r
+            return new CompositeModelValidator(metadata, context);\r
+        }\r
+\r
+        public abstract IEnumerable<ModelValidationResult> Validate(object container);\r
+\r
+        private class CompositeModelValidator : ModelValidator {\r
+            public CompositeModelValidator(ModelMetadata metadata, ControllerContext controllerContext)\r
+                : base(metadata, controllerContext) {\r
+            }\r
+\r
+            public override IEnumerable<ModelValidationResult> Validate(object container) {\r
+                bool propertiesValid = true;\r
+\r
+                foreach (ModelMetadata propertyMetadata in Metadata.Properties) {\r
+                    foreach (ModelValidator propertyValidator in propertyMetadata.GetValidators(ControllerContext)) {\r
+                        foreach (ModelValidationResult propertyResult in propertyValidator.Validate(Metadata.Model)) {\r
+                            propertiesValid = false;\r
+                            yield return new ModelValidationResult {\r
+                                MemberName = DefaultModelBinder.CreateSubPropertyName(propertyMetadata.PropertyName, propertyResult.MemberName),\r
+                                Message = propertyResult.Message\r
+                            };\r
+                        }\r
+                    }\r
+                }\r
+\r
+                if (propertiesValid) {\r
+                    foreach (ModelValidator typeValidator in Metadata.GetValidators(ControllerContext)) {\r
+                        foreach (ModelValidationResult typeResult in typeValidator.Validate(container)) {\r
+                            yield return typeResult;\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelValidatorProvider.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelValidatorProvider.cs
new file mode 100644 (file)
index 0000000..88dc223
--- /dev/null
@@ -0,0 +1,19 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Collections.Generic;\r
+\r
+    public abstract class ModelValidatorProvider {\r
+        public abstract IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelValidatorProviderCollection.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelValidatorProviderCollection.cs
new file mode 100644 (file)
index 0000000..ffc845b
--- /dev/null
@@ -0,0 +1,47 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Collections.ObjectModel;\r
+    using System.Linq;\r
+\r
+    public class ModelValidatorProviderCollection : Collection<ModelValidatorProvider> {\r
+\r
+        public ModelValidatorProviderCollection() {\r
+        }\r
+\r
+        public ModelValidatorProviderCollection(IList<ModelValidatorProvider> list)\r
+            : base(list) {\r
+        }\r
+\r
+        protected override void InsertItem(int index, ModelValidatorProvider item) {\r
+            if (item == null) {\r
+                throw new ArgumentNullException("item");\r
+            }\r
+            base.InsertItem(index, item);\r
+        }\r
+\r
+        protected override void SetItem(int index, ModelValidatorProvider item) {\r
+            if (item == null) {\r
+                throw new ArgumentNullException("item");\r
+            }\r
+            base.SetItem(index, item);\r
+        }\r
+\r
+        public IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context) {\r
+            return this.SelectMany(provider => provider.GetValidators(metadata, context));\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelValidatorProviders.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ModelValidatorProviders.cs
new file mode 100644 (file)
index 0000000..563d495
--- /dev/null
@@ -0,0 +1,29 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    public static class ModelValidatorProviders {\r
+\r
+        private static readonly ModelValidatorProviderCollection _providers = new ModelValidatorProviderCollection() {\r
+            new DataAnnotationsModelValidatorProvider(),\r
+            new DataErrorInfoModelValidatorProvider(),\r
+            new ClientDataTypeModelValidatorProvider()\r
+        };\r
+\r
+        public static ModelValidatorProviderCollection Providers {\r
+            get {\r
+                return _providers;\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/MultiSelectList.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/MultiSelectList.cs
new file mode 100644 (file)
index 0000000..2f1776f
--- /dev/null
@@ -0,0 +1,126 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections;\r
+    using System.Collections.Generic;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+    using System.Web.UI;\r
+\r
+    [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]\r
+    [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Multi",\r
+        Justification = "Common shorthand for 'multiple'.")]\r
+    public class MultiSelectList : IEnumerable<SelectListItem> {\r
+\r
+        public MultiSelectList(IEnumerable items)\r
+            : this(items, null /* selectedValues */) {\r
+        }\r
+\r
+        public MultiSelectList(IEnumerable items, IEnumerable selectedValues)\r
+            : this(items, null /* dataValuefield */, null /* dataTextField */, selectedValues) {\r
+        }\r
+\r
+        public MultiSelectList(IEnumerable items, string dataValueField, string dataTextField)\r
+            : this(items, dataValueField, dataTextField, null /* selectedValues */) {\r
+        }\r
+\r
+        public MultiSelectList(IEnumerable items, string dataValueField, string dataTextField, IEnumerable selectedValues) {\r
+            if (items == null) {\r
+                throw new ArgumentNullException("items");\r
+            }\r
+\r
+            Items = items;\r
+            DataValueField = dataValueField;\r
+            DataTextField = dataTextField;\r
+            SelectedValues = selectedValues;\r
+        }\r
+\r
+        public string DataTextField {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public string DataValueField {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public IEnumerable Items {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public IEnumerable SelectedValues {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public virtual IEnumerator<SelectListItem> GetEnumerator() {\r
+            return GetListItems().GetEnumerator();\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",\r
+            Justification = "Operation performs conversions and returns a unique instance on each call.")]\r
+        internal IList<SelectListItem> GetListItems() {\r
+            return (!String.IsNullOrEmpty(DataValueField)) ?\r
+                GetListItemsWithValueField() :\r
+                GetListItemsWithoutValueField();\r
+        }\r
+\r
+        private IList<SelectListItem> GetListItemsWithValueField() {\r
+            HashSet<string> selectedValues = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\r
+            if (SelectedValues != null) {\r
+                selectedValues.UnionWith(from object value in SelectedValues select Convert.ToString(value, CultureInfo.CurrentCulture));\r
+            }\r
+\r
+            var listItems = from object item in Items\r
+                            let value = Eval(item, DataValueField)\r
+                            select new SelectListItem {\r
+                                Value = value,\r
+                                Text = Eval(item, DataTextField),\r
+                                Selected = selectedValues.Contains(value)\r
+                            };\r
+            return listItems.ToList();\r
+        }\r
+\r
+        private IList<SelectListItem> GetListItemsWithoutValueField() {\r
+            HashSet<object> selectedValues = new HashSet<object>();\r
+            if (SelectedValues != null) {\r
+                selectedValues.UnionWith(SelectedValues.Cast<object>());\r
+            }\r
+\r
+            var listItems = from object item in Items\r
+                            select new SelectListItem {\r
+                                Text = Eval(item, DataTextField),\r
+                                Selected = selectedValues.Contains(item)\r
+                            };\r
+            return listItems.ToList();\r
+        }\r
+\r
+        private static string Eval(object container, string expression) {\r
+            object value = container;\r
+            if (!String.IsNullOrEmpty(expression)) {\r
+                value = DataBinder.Eval(container, expression);\r
+            }\r
+            return Convert.ToString(value, CultureInfo.CurrentCulture);\r
+        }\r
+\r
+        #region IEnumerable Members\r
+        IEnumerator IEnumerable.GetEnumerator() {\r
+            return GetEnumerator();\r
+        }\r
+        #endregion\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/MvcHandler.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/MvcHandler.cs
new file mode 100644 (file)
index 0000000..1f15ae7
--- /dev/null
@@ -0,0 +1,212 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+    using System.Reflection;\r
+    using System.Threading;\r
+    using System.Web;\r
+    using System.Web.Mvc.Async;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.Routing;\r
+    using System.Web.SessionState;\r
+\r
+    [SuppressMessage("Microsoft.Security", "CA2112:SecuredTypesShouldNotExposeFields", Justification = "There's nothing secret about the value of this field.")]\r
+    public class MvcHandler : IHttpAsyncHandler, IHttpHandler, IRequiresSessionState {\r
+        private static readonly object _processRequestTag = new object();\r
+        private ControllerBuilder _controllerBuilder;\r
+\r
+        internal static readonly string MvcVersion = GetMvcVersionString();\r
+        public static readonly string MvcVersionHeaderName = "X-AspNetMvc-Version";\r
+\r
+        public MvcHandler(RequestContext requestContext) {\r
+            if (requestContext == null) {\r
+                throw new ArgumentNullException("requestContext");\r
+            }\r
+\r
+            RequestContext = requestContext;\r
+        }\r
+\r
+        internal ControllerBuilder ControllerBuilder {\r
+            get {\r
+                if (_controllerBuilder == null) {\r
+                    _controllerBuilder = ControllerBuilder.Current;\r
+                }\r
+                return _controllerBuilder;\r
+            }\r
+            set {\r
+                _controllerBuilder = value;\r
+            }\r
+        }\r
+\r
+        public static bool DisableMvcResponseHeader {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        protected virtual bool IsReusable {\r
+            get {\r
+                return false;\r
+            }\r
+        }\r
+\r
+        public RequestContext RequestContext {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        protected internal virtual void AddVersionHeader(HttpContextBase httpContext) {\r
+            if (!DisableMvcResponseHeader) {\r
+                httpContext.Response.AppendHeader(MvcVersionHeaderName, MvcVersion);\r
+            }\r
+        }\r
+\r
+        protected virtual IAsyncResult BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, object state) {\r
+            HttpContextBase iHttpContext = new HttpContextWrapper(httpContext);\r
+            return BeginProcessRequest(iHttpContext, callback, state);\r
+        }\r
+\r
+        protected internal virtual IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, object state) {\r
+            IController controller;\r
+            IControllerFactory factory;\r
+            ProcessRequestInit(httpContext, out controller, out factory);\r
+\r
+            IAsyncController asyncController = controller as IAsyncController;\r
+            if (asyncController != null) {\r
+                // asynchronous controller\r
+                BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState) {\r
+                    try {\r
+                        return asyncController.BeginExecute(RequestContext, asyncCallback, asyncState);\r
+                    }\r
+                    catch {\r
+                        factory.ReleaseController(asyncController);\r
+                        throw;\r
+                    }\r
+                };\r
+\r
+                EndInvokeDelegate endDelegate = delegate(IAsyncResult asyncResult) {\r
+                    try {\r
+                        asyncController.EndExecute(asyncResult);\r
+                    }\r
+                    finally {\r
+                        factory.ReleaseController(asyncController);\r
+                    }\r
+                };\r
+\r
+                SynchronizationContext syncContext = SynchronizationContextUtil.GetSynchronizationContext();\r
+                AsyncCallback newCallback = AsyncUtil.WrapCallbackForSynchronizedExecution(callback, syncContext);\r
+                return AsyncResultWrapper.Begin(newCallback, state, beginDelegate, endDelegate, _processRequestTag);\r
+            }\r
+            else {\r
+                // synchronous controller\r
+                Action action = delegate {\r
+                    try {\r
+                        controller.Execute(RequestContext);\r
+                    }\r
+                    finally {\r
+                        factory.ReleaseController(controller);\r
+                    }\r
+                };\r
+\r
+                return AsyncResultWrapper.BeginSynchronous(callback, state, action, _processRequestTag);\r
+            }\r
+        }\r
+\r
+        protected internal virtual void EndProcessRequest(IAsyncResult asyncResult) {\r
+            AsyncResultWrapper.End(asyncResult, _processRequestTag);\r
+        }\r
+\r
+        private static string GetMvcVersionString() {\r
+            // DevDiv 216459:\r
+            // This code originally used Assembly.GetName(), but that requires FileIOPermission, which isn't granted in\r
+            // medium trust. However, Assembly.FullName *is* accessible in medium trust.\r
+            return new AssemblyName(typeof(MvcHandler).Assembly.FullName).Version.ToString(2);\r
+        }\r
+\r
+        protected virtual void ProcessRequest(HttpContext httpContext) {\r
+            HttpContextBase iHttpContext = new HttpContextWrapper(httpContext);\r
+            ProcessRequest(iHttpContext);\r
+        }\r
+\r
+        protected internal virtual void ProcessRequest(HttpContextBase httpContext) {\r
+            IController controller;\r
+            IControllerFactory factory;\r
+            ProcessRequestInit(httpContext, out controller, out factory);\r
+\r
+            try {\r
+                controller.Execute(RequestContext);\r
+            }\r
+            finally {\r
+                factory.ReleaseController(controller);\r
+            }\r
+        }\r
+\r
+        private void ProcessRequestInit(HttpContextBase httpContext, out IController controller, out IControllerFactory factory) {\r
+            AddVersionHeader(httpContext);\r
+            RemoveOptionalRoutingParameters();\r
+\r
+            // Get the controller type\r
+            string controllerName = RequestContext.RouteData.GetRequiredString("controller");\r
+\r
+            // Instantiate the controller and call Execute\r
+            factory = ControllerBuilder.GetControllerFactory();\r
+            controller = factory.CreateController(RequestContext, controllerName);\r
+            if (controller == null) {\r
+                throw new InvalidOperationException(\r
+                    String.Format(\r
+                        CultureInfo.CurrentUICulture,\r
+                        MvcResources.ControllerBuilder_FactoryReturnedNull,\r
+                        factory.GetType(),\r
+                        controllerName));\r
+            }\r
+        }\r
+\r
+        private void RemoveOptionalRoutingParameters() {\r
+            RouteValueDictionary rvd = RequestContext.RouteData.Values;\r
+\r
+            // Get all keys for which the corresponding value is 'Optional'.\r
+            // ToArray() necessary so that we don't manipulate the dictionary while enumerating.\r
+            string[] matchingKeys = (from entry in rvd\r
+                                     where entry.Value == UrlParameter.Optional\r
+                                     select entry.Key).ToArray();\r
+\r
+            foreach (string key in matchingKeys) {\r
+                rvd.Remove(key);\r
+            }\r
+        }\r
+\r
+        #region IHttpHandler Members\r
+        bool IHttpHandler.IsReusable {\r
+            get {\r
+                return IsReusable;\r
+            }\r
+        }\r
+\r
+        void IHttpHandler.ProcessRequest(HttpContext httpContext) {\r
+            ProcessRequest(httpContext);\r
+        }\r
+        #endregion\r
+\r
+        #region IHttpAsyncHandler Members\r
+        IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) {\r
+            return BeginProcessRequest(context, cb, extraData);\r
+        }\r
+\r
+        void IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) {\r
+            EndProcessRequest(result);\r
+        }\r
+        #endregion\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/MvcHtmlString.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/MvcHtmlString.cs
new file mode 100644 (file)
index 0000000..a6674bf
--- /dev/null
@@ -0,0 +1,101 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.ComponentModel;\r
+    using System.Linq.Expressions;\r
+    using System.Web;\r
+\r
+    // In ASP.NET 4, a new syntax <%: %> is being introduced in WebForms pages, where <%: expression %> is equivalent to\r
+    // <%= HttpUtility.HtmlEncode(expression) %>. The intent of this is to reduce common causes of XSS vulnerabilities\r
+    // in WebForms pages (WebForms views in the case of MVC). This involves the addition of an interface\r
+    // System.Web.IHtmlString and a static method overload System.Web.HttpUtility::HtmlEncode(object).  The interface\r
+    // definition is roughly:\r
+    //   public interface IHtmlString {\r
+    //     string ToHtmlString();\r
+    //   }\r
+    // And the HtmlEncode(object) logic is roughly:\r
+    //   - If the input argument is an IHtmlString, return argument.ToHtmlString(),\r
+    //   - Otherwise, return HtmlEncode(Convert.ToString(argument)).\r
+    //\r
+    // Unfortunately this has the effect that calling <%: Html.SomeHelper() %> in an MVC application running on .NET 4\r
+    // will end up encoding output that is already HTML-safe. As a result, we're changing out HTML helpers to return\r
+    // MvcHtmlString where appropriate. <%= Html.SomeHelper() %> will continue to work in both .NET 3.5 and .NET 4, but\r
+    // changing the return types to MvcHtmlString has the added benefit that <%: Html.SomeHelper() %> will also work\r
+    // properly in .NET 4 rather than resulting in a double-encoded output. MVC developers in .NET 4 will then be able\r
+    // to use the <%: %> syntax almost everywhere instead of having to remember where to use <%= %> and where to use\r
+    // <%: %>. This should help developers craft more secure web applications by default.\r
+    //\r
+    // To create an MvcHtmlString, use the static Create() method instead of calling the protected constructor.\r
+\r
+    public class MvcHtmlString {\r
+\r
+        private delegate MvcHtmlString MvcHtmlStringCreator(string value);\r
+        private static readonly MvcHtmlStringCreator _creator = GetCreator();\r
+\r
+        // imporant: this declaration must occur after the _creator declaration\r
+        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes",\r
+            Justification = "MvcHtmlString is immutable")]\r
+        public static readonly MvcHtmlString Empty = Create(String.Empty);\r
+\r
+        private readonly string _value;\r
+\r
+        // This constructor is only protected so that we can subclass it in a dynamic module. In practice,\r
+        // nobody should ever call this constructor, and it is likely to be removed in a future version\r
+        // of the framework. Use the static Create() method instead.\r
+        [EditorBrowsable(EditorBrowsableState.Never)]\r
+        [Obsolete("The recommended alternative is the static MvcHtmlString.Create(String value) method.")]\r
+        protected MvcHtmlString(string value) {\r
+            _value = value ?? String.Empty;\r
+        }\r
+\r
+        public static MvcHtmlString Create(string value) {\r
+            return _creator(value);\r
+        }\r
+\r
+        // in .NET 4, we dynamically create a type that subclasses MvcHtmlString and implements IHtmlString\r
+        private static MvcHtmlStringCreator GetCreator() {\r
+            Type iHtmlStringType = typeof(HttpContext).Assembly.GetType("System.Web.IHtmlString");\r
+            if (iHtmlStringType != null) {\r
+                // first, create the dynamic type\r
+                Type dynamicType = DynamicTypeGenerator.GenerateType("DynamicMvcHtmlString", typeof(MvcHtmlString), new Type[] { iHtmlStringType });\r
+\r
+                // then, create the delegate to instantiate the dynamic type\r
+                ParameterExpression valueParamExpr = Expression.Parameter(typeof(string), "value");\r
+                NewExpression newObjExpr = Expression.New(dynamicType.GetConstructor(new Type[] { typeof(string) }), valueParamExpr);\r
+                Expression<MvcHtmlStringCreator> lambdaExpr = Expression.Lambda<MvcHtmlStringCreator>(newObjExpr, valueParamExpr);\r
+                return lambdaExpr.Compile();\r
+            }\r
+            else {\r
+                // disabling 0618 allows us to call the MvcHtmlString() constructor\r
+#pragma warning disable 0618\r
+                return value => new MvcHtmlString(value);\r
+#pragma warning restore 0618\r
+            }\r
+        }\r
+\r
+        public static bool IsNullOrEmpty(MvcHtmlString value) {\r
+            return (value == null || value._value.Length == 0);\r
+        }\r
+\r
+        // IHtmlString.ToHtmlString()\r
+        public string ToHtmlString() {\r
+            return _value;\r
+        }\r
+\r
+        public override string ToString() {\r
+            return _value;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/MvcHttpHandler.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/MvcHttpHandler.cs
new file mode 100644 (file)
index 0000000..c9773d7
--- /dev/null
@@ -0,0 +1,101 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Web;\r
+    using System.Web.Mvc.Async;\r
+    using System.Web.Routing;\r
+    using System.Web.SessionState;\r
+\r
+    public class MvcHttpHandler : UrlRoutingHandler, IHttpAsyncHandler, IRequiresSessionState {\r
+\r
+        private static readonly object _processRequestTag = new object();\r
+\r
+        protected virtual IAsyncResult BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, object state) {\r
+            HttpContextBase iHttpContext = new HttpContextWrapper(httpContext);\r
+            return BeginProcessRequest(iHttpContext, callback, state);\r
+        }\r
+\r
+        protected internal virtual IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, object state) {\r
+            IHttpHandler httpHandler = GetHttpHandler(httpContext);\r
+            IHttpAsyncHandler httpAsyncHandler = httpHandler as IHttpAsyncHandler;\r
+\r
+            if (httpAsyncHandler != null) {\r
+                // asynchronous handler\r
+                BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState) {\r
+                    return httpAsyncHandler.BeginProcessRequest(HttpContext.Current, asyncCallback, asyncState);\r
+                };\r
+                EndInvokeDelegate endDelegate = delegate(IAsyncResult asyncResult) {\r
+                    httpAsyncHandler.EndProcessRequest(asyncResult);\r
+                };\r
+                return AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _processRequestTag);\r
+            }\r
+            else {\r
+                // synchronous handler\r
+                Action action = delegate {\r
+                    httpHandler.ProcessRequest(HttpContext.Current);\r
+                };\r
+                return AsyncResultWrapper.BeginSynchronous(callback, state, action, _processRequestTag);\r
+            }\r
+        }\r
+\r
+        protected internal virtual void EndProcessRequest(IAsyncResult asyncResult) {\r
+            AsyncResultWrapper.End(asyncResult, _processRequestTag);\r
+        }\r
+\r
+        private static IHttpHandler GetHttpHandler(HttpContextBase httpContext) {\r
+            DummyHttpHandler dummyHandler = new DummyHttpHandler();\r
+            dummyHandler.PublicProcessRequest(httpContext);\r
+            return dummyHandler.HttpHandler;\r
+        }\r
+\r
+        // synchronous code\r
+        protected override void VerifyAndProcessRequest(IHttpHandler httpHandler, HttpContextBase httpContext) {\r
+            if (httpHandler == null) {\r
+                throw new ArgumentNullException("httpHandler");\r
+            }\r
+\r
+            httpHandler.ProcessRequest(HttpContext.Current);\r
+        }\r
+\r
+        #region IHttpAsyncHandler Members\r
+        IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) {\r
+            return BeginProcessRequest(context, cb, extraData);\r
+        }\r
+\r
+        void IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) {\r
+            EndProcessRequest(result);\r
+        }\r
+        #endregion\r
+\r
+        // Since UrlRoutingHandler.ProcessRequest() does the heavy lifting of looking at the RouteCollection for\r
+        // a matching route, we need to call into it. However, that method is also responsible for kicking off\r
+        // the synchronous request, and we can't allow it to do that. The purpose of this dummy class is to run\r
+        // only the lookup portion of UrlRoutingHandler.ProcessRequest(), then intercept the handler it returns\r
+        // and execute it asynchronously.\r
+\r
+        private sealed class DummyHttpHandler : UrlRoutingHandler {\r
+            public IHttpHandler HttpHandler;\r
+\r
+            public void PublicProcessRequest(HttpContextBase httpContext) {\r
+                ProcessRequest(httpContext);\r
+            }\r
+\r
+            protected override void VerifyAndProcessRequest(IHttpHandler httpHandler, HttpContextBase httpContext) {\r
+                // don't process the request, just store a reference to it\r
+                HttpHandler = httpHandler;\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/MvcRouteHandler.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/MvcRouteHandler.cs
new file mode 100644 (file)
index 0000000..5d2bbaa
--- /dev/null
@@ -0,0 +1,27 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Web.Routing;\r
+\r
+    public class MvcRouteHandler : IRouteHandler {\r
+        protected virtual IHttpHandler GetHttpHandler(RequestContext requestContext) {\r
+            return new MvcHandler(requestContext);\r
+        }\r
+\r
+        #region IRouteHandler Members\r
+        IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) {\r
+            return GetHttpHandler(requestContext);\r
+        }\r
+        #endregion\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/NameValueCollectionExtensions.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/NameValueCollectionExtensions.cs
new file mode 100644 (file)
index 0000000..7faf9f0
--- /dev/null
@@ -0,0 +1,39 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Collections.Specialized;\r
+\r
+    public static class NameValueCollectionExtensions {\r
+\r
+        public static void CopyTo(this NameValueCollection collection, IDictionary<string, object> destination) {\r
+            CopyTo(collection, destination, false /* replaceEntries */);\r
+        }\r
+\r
+        public static void CopyTo(this NameValueCollection collection, IDictionary<string, object> destination, bool replaceEntries) {\r
+            if (collection == null) {\r
+                throw new ArgumentNullException("collection");\r
+            }\r
+            if (destination == null) {\r
+                throw new ArgumentNullException("destination");\r
+            }\r
+\r
+            foreach (string key in collection.Keys) {\r
+                if (replaceEntries || !destination.ContainsKey(key)) {\r
+                    destination[key] = collection[key];\r
+                }\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/NameValueCollectionValueProvider.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/NameValueCollectionValueProvider.cs
new file mode 100644 (file)
index 0000000..9bc990b
--- /dev/null
@@ -0,0 +1,68 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Collections.Specialized;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+\r
+    public class NameValueCollectionValueProvider : IValueProvider {\r
+\r
+        private readonly HashSet<string> _prefixes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\r
+        private readonly Dictionary<string, ValueProviderResult> _values = new Dictionary<string, ValueProviderResult>(StringComparer.OrdinalIgnoreCase);\r
+\r
+        public NameValueCollectionValueProvider(NameValueCollection collection, CultureInfo culture) {\r
+            if (collection == null) {\r
+                throw new ArgumentNullException("collection");\r
+            }\r
+\r
+            AddValues(collection, culture);\r
+        }\r
+\r
+        private void AddValues(NameValueCollection collection, CultureInfo culture) {\r
+            if (collection.Count > 0) {\r
+                _prefixes.Add("");\r
+            }\r
+\r
+            foreach (string key in collection) {\r
+                if (key != null) {\r
+                    _prefixes.UnionWith(ValueProviderUtil.GetPrefixes(key));\r
+\r
+                    string[] rawValue = collection.GetValues(key);\r
+                    string attemptedValue = collection[key];\r
+                    _values[key] = new ValueProviderResult(rawValue, attemptedValue, culture);\r
+                }\r
+            }\r
+        }\r
+\r
+        public virtual bool ContainsPrefix(string prefix) {\r
+            if (prefix == null) {\r
+                throw new ArgumentNullException("prefix");\r
+            }\r
+\r
+            return _prefixes.Contains(prefix);\r
+        }\r
+\r
+        public virtual ValueProviderResult GetValue(string key) {\r
+            if (key == null) {\r
+                throw new ArgumentNullException("key");\r
+            }\r
+\r
+            ValueProviderResult vpResult;\r
+            _values.TryGetValue(key, out vpResult);\r
+            return vpResult;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/NoAsyncTimeoutAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/NoAsyncTimeoutAttribute.cs
new file mode 100644 (file)
index 0000000..b482dc8
--- /dev/null
@@ -0,0 +1,24 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Threading;\r
+\r
+    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\r
+    public sealed class NoAsyncTimeoutAttribute : AsyncTimeoutAttribute {\r
+\r
+        public NoAsyncTimeoutAttribute()\r
+            : base(Timeout.Infinite) {\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/NonActionAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/NonActionAttribute.cs
new file mode 100644 (file)
index 0000000..c50ef63
--- /dev/null
@@ -0,0 +1,22 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Reflection;\r
+\r
+    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\r
+    public sealed class NonActionAttribute : ActionMethodSelectorAttribute {\r
+        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) {\r
+            return false;\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/NullViewLocationCache.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/NullViewLocationCache.cs
new file mode 100644 (file)
index 0000000..dbfc9ae
--- /dev/null
@@ -0,0 +1,30 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Linq;\r
+    using System.Text;\r
+\r
+    internal sealed class NullViewLocationCache : IViewLocationCache {\r
+\r
+        #region IViewLocationCache Members\r
+        public string GetViewLocation(HttpContextBase httpContext, string key) {\r
+            return null;\r
+        }\r
+\r
+        public void InsertViewLocation(HttpContextBase httpContext, string key, string virtualPath) {\r
+        }\r
+        #endregion\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/OutputCacheAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/OutputCacheAttribute.cs
new file mode 100644 (file)
index 0000000..a83a82b
--- /dev/null
@@ -0,0 +1,146 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Web;\r
+    using System.Web.UI;\r
+\r
+    [SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes",\r
+        Justification = "Unsealed so that subclassed types can set properties in the default constructor.")]\r
+    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\r
+    public class OutputCacheAttribute : ActionFilterAttribute {\r
+\r
+        private OutputCacheParameters _cacheSettings = new OutputCacheParameters();\r
+\r
+        public string CacheProfile {\r
+            get {\r
+                return _cacheSettings.CacheProfile ?? String.Empty;\r
+            }\r
+            set {\r
+                _cacheSettings.CacheProfile = value;\r
+            }\r
+        }\r
+\r
+        internal OutputCacheParameters CacheSettings {\r
+            get {\r
+                return _cacheSettings;\r
+            }\r
+        }\r
+\r
+        public int Duration {\r
+            get {\r
+                return _cacheSettings.Duration;\r
+            }\r
+            set {\r
+                _cacheSettings.Duration = value;\r
+            }\r
+        }\r
+\r
+        public OutputCacheLocation Location {\r
+            get {\r
+                return _cacheSettings.Location;\r
+            }\r
+            set {\r
+                _cacheSettings.Location = value;\r
+            }\r
+        }\r
+\r
+        public bool NoStore {\r
+            get {\r
+                return _cacheSettings.NoStore;\r
+            }\r
+            set {\r
+                _cacheSettings.NoStore = value;\r
+            }\r
+        }\r
+\r
+        public string SqlDependency {\r
+            get {\r
+                return _cacheSettings.SqlDependency ?? String.Empty;\r
+            }\r
+            set {\r
+                _cacheSettings.SqlDependency = value;\r
+            }\r
+        }\r
+\r
+        public string VaryByContentEncoding {\r
+            get {\r
+                return _cacheSettings.VaryByContentEncoding ?? String.Empty;\r
+            }\r
+            set {\r
+                _cacheSettings.VaryByContentEncoding = value;\r
+            }\r
+        }\r
+\r
+        public string VaryByCustom {\r
+            get {\r
+                return _cacheSettings.VaryByCustom ?? String.Empty;\r
+            }\r
+            set {\r
+                _cacheSettings.VaryByCustom = value;\r
+            }\r
+        }\r
+\r
+        public string VaryByHeader {\r
+            get {\r
+                return _cacheSettings.VaryByHeader ?? String.Empty;\r
+            }\r
+            set {\r
+                _cacheSettings.VaryByHeader = value;\r
+            }\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Param",\r
+            Justification = "Matches the @ OutputCache page directive.")]\r
+        public string VaryByParam {\r
+            get {\r
+                return _cacheSettings.VaryByParam ?? String.Empty;\r
+            }\r
+            set {\r
+                _cacheSettings.VaryByParam = value;\r
+            }\r
+        }\r
+\r
+        public override void OnResultExecuting(ResultExecutingContext filterContext) {\r
+            if (filterContext == null) {\r
+                throw new ArgumentNullException("filterContext");\r
+            }\r
+\r
+            if (filterContext.IsChildAction) {\r
+                return;\r
+            }\r
+\r
+            // we need to call ProcessRequest() since there's no other way to set the Page.Response intrinsic\r
+            OutputCachedPage page = new OutputCachedPage(_cacheSettings);\r
+            page.ProcessRequest(HttpContext.Current);\r
+        }\r
+\r
+        private sealed class OutputCachedPage : Page {\r
+            private OutputCacheParameters _cacheSettings;\r
+\r
+            public OutputCachedPage(OutputCacheParameters cacheSettings) {\r
+                // Tracing requires Page IDs to be unique.\r
+                ID = Guid.NewGuid().ToString();\r
+                _cacheSettings = cacheSettings;\r
+            }\r
+\r
+            protected override void FrameworkInitialize() {\r
+                // when you put the <%@ OutputCache %> directive on a page, the generated code calls InitOutputCache() from here\r
+                base.FrameworkInitialize();\r
+                InitOutputCache(_cacheSettings);\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ParameterBindingInfo.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ParameterBindingInfo.cs
new file mode 100644 (file)
index 0000000..09334b8
--- /dev/null
@@ -0,0 +1,43 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Collections.Generic;\r
+\r
+    public abstract class ParameterBindingInfo {\r
+\r
+        public virtual IModelBinder Binder {\r
+            get {\r
+                return null;\r
+            }\r
+        }\r
+\r
+        public virtual ICollection<string> Exclude {\r
+            get {\r
+                return new string[0];\r
+            }\r
+        }\r
+\r
+        public virtual ICollection<string> Include {\r
+            get {\r
+                return new string[0];\r
+            }\r
+        }\r
+\r
+        public virtual string Prefix {\r
+            get {\r
+                return null;\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ParameterDescriptor.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ParameterDescriptor.cs
new file mode 100644 (file)
index 0000000..92ddce4
--- /dev/null
@@ -0,0 +1,69 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Reflection;\r
+\r
+    public abstract class ParameterDescriptor : ICustomAttributeProvider {\r
+\r
+        private static readonly EmptyParameterBindingInfo _emptyBindingInfo = new EmptyParameterBindingInfo();\r
+\r
+        public abstract ActionDescriptor ActionDescriptor {\r
+            get;\r
+        }\r
+\r
+        public virtual ParameterBindingInfo BindingInfo {\r
+            get {\r
+                return _emptyBindingInfo;\r
+            }\r
+        }\r
+\r
+        public virtual object DefaultValue {\r
+            get {\r
+                return null;\r
+            }\r
+        }\r
+\r
+        public abstract string ParameterName {\r
+            get;\r
+        }\r
+\r
+        public abstract Type ParameterType {\r
+            get;\r
+        }\r
+\r
+        public virtual object[] GetCustomAttributes(bool inherit) {\r
+            return GetCustomAttributes(typeof(object), inherit);\r
+        }\r
+\r
+        public virtual object[] GetCustomAttributes(Type attributeType, bool inherit) {\r
+            if (attributeType == null) {\r
+                throw new ArgumentNullException("attributeType");\r
+            }\r
+\r
+            return (object[])Array.CreateInstance(attributeType, 0);\r
+        }\r
+\r
+        public virtual bool IsDefined(Type attributeType, bool inherit) {\r
+            if (attributeType == null) {\r
+                throw new ArgumentNullException("attributeType");\r
+            }\r
+\r
+            return false;\r
+        }\r
+\r
+        private sealed class EmptyParameterBindingInfo : ParameterBindingInfo {\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ParameterInfoUtil.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ParameterInfoUtil.cs
new file mode 100644 (file)
index 0000000..c538e14
--- /dev/null
@@ -0,0 +1,42 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.ComponentModel;\r
+    using System.Reflection;\r
+\r
+    internal static class ParameterInfoUtil {\r
+\r
+        public static bool TryGetDefaultValue(ParameterInfo parameterInfo, out object value) {\r
+            // this will get the default value as seen by the VB / C# compilers\r
+            // if no value was baked in, RawDefaultValue returns DBNull.Value\r
+            object rawDefaultValue = parameterInfo.RawDefaultValue;\r
+            if (rawDefaultValue != DBNull.Value) {\r
+                value = rawDefaultValue;\r
+                return true;\r
+            }\r
+\r
+            // if the compiler did not bake in a default value, check the [DefaultValue] attribute\r
+            DefaultValueAttribute[] attrs = (DefaultValueAttribute[])parameterInfo.GetCustomAttributes(typeof(DefaultValueAttribute), false);\r
+            if (attrs == null || attrs.Length == 0) {\r
+                value = default(object);\r
+                return false;\r
+            }\r
+            else {\r
+                value = attrs[0].Value;\r
+                return true;\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/PartialViewResult.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/PartialViewResult.cs
new file mode 100644 (file)
index 0000000..86f9fb1
--- /dev/null
@@ -0,0 +1,37 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Globalization;\r
+    using System.Text;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public class PartialViewResult : ViewResultBase {\r
+\r
+        protected override ViewEngineResult FindView(ControllerContext context) {\r
+            ViewEngineResult result = ViewEngineCollection.FindPartialView(context, ViewName);\r
+            if (result.View != null) {\r
+                return result;\r
+            }\r
+\r
+            // we need to generate an exception containing all the locations we searched\r
+            StringBuilder locationsText = new StringBuilder();\r
+            foreach (string location in result.SearchedLocations) {\r
+                locationsText.AppendLine();\r
+                locationsText.Append(location);\r
+            }\r
+            throw new InvalidOperationException(String.Format(CultureInfo.CurrentUICulture,\r
+                MvcResources.Common_PartialViewNotFound, ViewName, locationsText));\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/PathHelpers.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/PathHelpers.cs
new file mode 100644 (file)
index 0000000..cb5be74
--- /dev/null
@@ -0,0 +1,97 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Specialized;\r
+    using System.Web;\r
+\r
+    internal static class PathHelpers {\r
+\r
+        private const string _urlRewriterServerVar = "HTTP_X_ORIGINAL_URL";\r
+\r
+        // this method can accept an app-relative path or an absolute path for contentPath\r
+        public static string GenerateClientUrl(HttpContextBase httpContext, string contentPath) {\r
+            if (String.IsNullOrEmpty(contentPath)) {\r
+                return contentPath;\r
+            }\r
+\r
+            // many of the methods we call internally can't handle query strings properly, so just strip it out for\r
+            // the time being\r
+            string query;\r
+            contentPath = StripQuery(contentPath, out query);\r
+\r
+            return GenerateClientUrlInternal(httpContext, contentPath) + query;\r
+        }\r
+\r
+        private static string GenerateClientUrlInternal(HttpContextBase httpContext, string contentPath) {\r
+            if (String.IsNullOrEmpty(contentPath)) {\r
+                return contentPath;\r
+            }\r
+\r
+            // can't call VirtualPathUtility.IsAppRelative since it throws on some inputs\r
+            bool isAppRelative = contentPath[0] == '~';\r
+            if (isAppRelative) {\r
+                string absoluteContentPath = VirtualPathUtility.ToAbsolute(contentPath, httpContext.Request.ApplicationPath);\r
+                string modifiedAbsoluteContentPath = httpContext.Response.ApplyAppPathModifier(absoluteContentPath);\r
+                return GenerateClientUrlInternal(httpContext, modifiedAbsoluteContentPath);\r
+            }\r
+\r
+            // we only want to manipulate the path if URL rewriting is active, else we risk breaking the generated URL\r
+            NameValueCollection serverVars = httpContext.Request.ServerVariables;\r
+            bool urlRewriterIsEnabled = (serverVars != null && serverVars[_urlRewriterServerVar] != null);\r
+            if (!urlRewriterIsEnabled) {\r
+                return contentPath;\r
+            }\r
+\r
+            // Since the rawUrl represents what the user sees in his browser, it is what we want to use as the base\r
+            // of our absolute paths. For example, consider mysite.example.com/foo, which is internally\r
+            // rewritten to content.example.com/mysite/foo. When we want to generate a link to ~/bar, we want to\r
+            // base it from / instead of /foo, otherwise the user ends up seeing mysite.example.com/foo/bar,\r
+            // which is incorrect.\r
+            string relativeUrlToDestination = MakeRelative(httpContext.Request.Path, contentPath);\r
+            string absoluteUrlToDestination = MakeAbsolute(httpContext.Request.RawUrl, relativeUrlToDestination);\r
+            return absoluteUrlToDestination;\r
+        }\r
+\r
+        public static string MakeAbsolute(string basePath, string relativePath) {\r
+            // The Combine() method can't handle query strings on the base path, so we trim it off.\r
+            string query;\r
+            basePath = StripQuery(basePath, out query);\r
+            return VirtualPathUtility.Combine(basePath, relativePath);\r
+        }\r
+\r
+        public static string MakeRelative(string fromPath, string toPath) {\r
+            string relativeUrl = VirtualPathUtility.MakeRelative(fromPath, toPath);\r
+            if (String.IsNullOrEmpty(relativeUrl) || relativeUrl[0] == '?') {\r
+                // Sometimes VirtualPathUtility.MakeRelative() will return an empty string when it meant to return '.',\r
+                // but links to {empty string} are browser dependent. We replace it with an explicit path to force\r
+                // consistency across browsers.\r
+                relativeUrl = "./" + relativeUrl;\r
+            }\r
+            return relativeUrl;\r
+        }\r
+\r
+        private static string StripQuery(string path, out string query) {\r
+            int queryIndex = path.IndexOf('?');\r
+            if (queryIndex >= 0) {\r
+                query = path.Substring(queryIndex);\r
+                return path.Substring(0, queryIndex);\r
+            }\r
+            else {\r
+                query = null;\r
+                return path;\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/QueryStringValueProvider.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/QueryStringValueProvider.cs
new file mode 100644 (file)
index 0000000..19f4c6e
--- /dev/null
@@ -0,0 +1,27 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Specialized;\r
+    using System.Globalization;\r
+\r
+    public sealed class QueryStringValueProvider : NameValueCollectionValueProvider {\r
+\r
+        // QueryString should use the invariant culture since it's part of the URL, and the URL should be\r
+        // interpreted in a uniform fashion regardless of the origin of a particular request.\r
+        public QueryStringValueProvider(ControllerContext controllerContext)\r
+            : base(controllerContext.HttpContext.Request.QueryString, CultureInfo.InvariantCulture) {\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/QueryStringValueProviderFactory.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/QueryStringValueProviderFactory.cs
new file mode 100644 (file)
index 0000000..c12bb3b
--- /dev/null
@@ -0,0 +1,27 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    public sealed class QueryStringValueProviderFactory : ValueProviderFactory {\r
+\r
+        public override IValueProvider GetValueProvider(ControllerContext controllerContext) {\r
+            if (controllerContext == null) {\r
+                throw new ArgumentNullException("controllerContext");\r
+            }\r
+\r
+            return new QueryStringValueProvider(controllerContext);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/RangeAttributeAdapter.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/RangeAttributeAdapter.cs
new file mode 100644 (file)
index 0000000..d789d98
--- /dev/null
@@ -0,0 +1,26 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Collections.Generic;\r
+    using System.ComponentModel.DataAnnotations;\r
+\r
+    public class RangeAttributeAdapter : DataAnnotationsModelValidator<RangeAttribute> {\r
+        public RangeAttributeAdapter(ModelMetadata metadata, ControllerContext context, RangeAttribute attribute)\r
+            : base(metadata, context, attribute) {\r
+        }\r
+\r
+        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() {\r
+            return new[] { new ModelClientValidationRangeRule(ErrorMessage, Attribute.Minimum, Attribute.Maximum) };\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ReaderWriterCache`2.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ReaderWriterCache`2.cs
new file mode 100644 (file)
index 0000000..63e2fd4
--- /dev/null
@@ -0,0 +1,72 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Threading;\r
+\r
+    [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",\r
+        Justification = "Instances of this type are meant to be singletons.")]\r
+    internal abstract class ReaderWriterCache<TKey, TValue> {\r
+\r
+        private readonly Dictionary<TKey, TValue> _cache;\r
+        private readonly ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim();\r
+\r
+        protected ReaderWriterCache()\r
+            : this(null) {\r
+        }\r
+\r
+        protected ReaderWriterCache(IEqualityComparer<TKey> comparer) {\r
+            _cache = new Dictionary<TKey, TValue>(comparer);\r
+        }\r
+\r
+        protected Dictionary<TKey, TValue> Cache {\r
+            get {\r
+                return _cache;\r
+            }\r
+        }\r
+\r
+        protected TValue FetchOrCreateItem(TKey key, Func<TValue> creator) {\r
+            // first, see if the item already exists in the cache\r
+            _rwLock.EnterReadLock();\r
+            try {\r
+                TValue existingEntry;\r
+                if (_cache.TryGetValue(key, out existingEntry)) {\r
+                    return existingEntry;\r
+                }\r
+            }\r
+            finally {\r
+                _rwLock.ExitReadLock();\r
+            }\r
+\r
+            // insert the new item into the cache\r
+            TValue newEntry = creator();\r
+            _rwLock.EnterWriteLock();\r
+            try {\r
+                TValue existingEntry;\r
+                if (_cache.TryGetValue(key, out existingEntry)) {\r
+                    // another thread already inserted an item, so use that one\r
+                    return existingEntry;\r
+                }\r
+\r
+                _cache[key] = newEntry;\r
+                return newEntry;\r
+            }\r
+            finally {\r
+                _rwLock.ExitWriteLock();\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/RedirectResult.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/RedirectResult.cs
new file mode 100644 (file)
index 0000000..10abf15
--- /dev/null
@@ -0,0 +1,52 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    // represents a result that performs a redirection given some URI\r
+    public class RedirectResult : ActionResult {\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#",\r
+            Justification = "Response.Redirect() takes its URI as a string parameter.")]\r
+        public RedirectResult(string url) {\r
+            if (String.IsNullOrEmpty(url)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "url");\r
+            }\r
+\r
+            Url = url;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings",\r
+            Justification = "Response.Redirect() takes its URI as a string parameter.")]\r
+        public string Url {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public override void ExecuteResult(ControllerContext context) {\r
+            if (context == null) {\r
+                throw new ArgumentNullException("context");\r
+            }\r
+            if (context.IsChildAction) {\r
+                throw new InvalidOperationException(MvcResources.RedirectAction_CannotRedirectInChildAction);\r
+            }\r
+\r
+            string destinationUrl = UrlHelper.GenerateContentUrl(Url, context.HttpContext);\r
+            context.Controller.TempData.Keep();\r
+            context.HttpContext.Response.Redirect(destinationUrl, false /* endResponse */);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/RedirectToRouteResult.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/RedirectToRouteResult.cs
new file mode 100644 (file)
index 0000000..74b5ce5
--- /dev/null
@@ -0,0 +1,71 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.Routing;\r
+\r
+    // represents a result that performs a redirection given some values dictionary\r
+    public class RedirectToRouteResult : ActionResult {\r
+\r
+        private RouteCollection _routes;\r
+\r
+        public RedirectToRouteResult(RouteValueDictionary routeValues) :\r
+            this(null, routeValues) {\r
+        }\r
+\r
+        public RedirectToRouteResult(string routeName, RouteValueDictionary routeValues) {\r
+            RouteName = routeName ?? String.Empty;\r
+            RouteValues = routeValues ?? new RouteValueDictionary();\r
+        }\r
+\r
+        public string RouteName {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public RouteValueDictionary RouteValues {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        internal RouteCollection Routes {\r
+            get {\r
+                if (_routes == null) {\r
+                    _routes = RouteTable.Routes;\r
+                }\r
+                return _routes;\r
+            }\r
+            set {\r
+                _routes = value;\r
+            }\r
+        }\r
+\r
+        public override void ExecuteResult(ControllerContext context) {\r
+            if (context == null) {\r
+                throw new ArgumentNullException("context");\r
+            }\r
+            if (context.IsChildAction) {\r
+                throw new InvalidOperationException(MvcResources.RedirectAction_CannotRedirectInChildAction);\r
+            }\r
+\r
+            string destinationUrl = UrlHelper.GenerateUrl(RouteName, null /* actionName */, null /* controllerName */, RouteValues, Routes, context.RequestContext, false /* includeImplicitMvcValues */);\r
+            if (String.IsNullOrEmpty(destinationUrl)) {\r
+                throw new InvalidOperationException(MvcResources.Common_NoRouteMatched);\r
+            }\r
+\r
+            context.Controller.TempData.Keep();\r
+            context.HttpContext.Response.Redirect(destinationUrl, false /* endResponse */);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ReflectedActionDescriptor.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ReflectedActionDescriptor.cs
new file mode 100644 (file)
index 0000000..c8ff6ba
--- /dev/null
@@ -0,0 +1,131 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Linq;\r
+    using System.Reflection;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public class ReflectedActionDescriptor : ActionDescriptor {\r
+\r
+        private readonly string _actionName;\r
+        private readonly ControllerDescriptor _controllerDescriptor;\r
+        private ParameterDescriptor[] _parametersCache;\r
+\r
+        public ReflectedActionDescriptor(MethodInfo methodInfo, string actionName, ControllerDescriptor controllerDescriptor)\r
+            : this(methodInfo, actionName, controllerDescriptor, true /* validateMethod */) {\r
+        }\r
+\r
+        internal ReflectedActionDescriptor(MethodInfo methodInfo, string actionName, ControllerDescriptor controllerDescriptor, bool validateMethod) {\r
+            if (methodInfo == null) {\r
+                throw new ArgumentNullException("methodInfo");\r
+            }\r
+            if (String.IsNullOrEmpty(actionName)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "actionName");\r
+            }\r
+            if (controllerDescriptor == null) {\r
+                throw new ArgumentNullException("controllerDescriptor");\r
+            }\r
+\r
+            if (validateMethod) {\r
+                string failedMessage = VerifyActionMethodIsCallable(methodInfo);\r
+                if (failedMessage != null) {\r
+                    throw new ArgumentException(failedMessage, "methodInfo");\r
+                }\r
+            }\r
+\r
+            MethodInfo = methodInfo;\r
+            _actionName = actionName;\r
+            _controllerDescriptor = controllerDescriptor;\r
+        }\r
+\r
+        public override string ActionName {\r
+            get {\r
+                return _actionName;\r
+            }\r
+        }\r
+\r
+        public override ControllerDescriptor ControllerDescriptor {\r
+            get {\r
+                return _controllerDescriptor;\r
+            }\r
+        }\r
+\r
+        public MethodInfo MethodInfo {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public override object Execute(ControllerContext controllerContext, IDictionary<string, object> parameters) {\r
+            if (controllerContext == null) {\r
+                throw new ArgumentNullException("controllerContext");\r
+            }\r
+            if (parameters == null) {\r
+                throw new ArgumentNullException("parameters");\r
+            }\r
+\r
+            ParameterInfo[] parameterInfos = MethodInfo.GetParameters();\r
+            var rawParameterValues = from parameterInfo in parameterInfos\r
+                                     select ExtractParameterFromDictionary(parameterInfo, parameters, MethodInfo);\r
+            object[] parametersArray = rawParameterValues.ToArray();\r
+\r
+            ActionMethodDispatcher dispatcher = DispatcherCache.GetDispatcher(MethodInfo);\r
+            object actionReturnValue = dispatcher.Execute(controllerContext.Controller, parametersArray);\r
+            return actionReturnValue;\r
+        }\r
+\r
+        public override object[] GetCustomAttributes(bool inherit) {\r
+            return MethodInfo.GetCustomAttributes(inherit);\r
+        }\r
+\r
+        public override object[] GetCustomAttributes(Type attributeType, bool inherit) {\r
+            return MethodInfo.GetCustomAttributes(attributeType, inherit);\r
+        }\r
+\r
+        public override FilterInfo GetFilters() {\r
+            return GetFilters(MethodInfo);\r
+        }\r
+\r
+        public override ParameterDescriptor[] GetParameters() {\r
+            ParameterDescriptor[] parameters = LazilyFetchParametersCollection();\r
+\r
+            // need to clone array so that user modifications aren't accidentally stored\r
+            return (ParameterDescriptor[])parameters.Clone();\r
+        }\r
+\r
+        public override ICollection<ActionSelector> GetSelectors() {\r
+            ActionMethodSelectorAttribute[] attrs = (ActionMethodSelectorAttribute[])MethodInfo.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true /* inherit */);\r
+            ActionSelector[] selectors = Array.ConvertAll(attrs, attr => (ActionSelector)(controllerContext => attr.IsValidForRequest(controllerContext, MethodInfo)));\r
+            return selectors;\r
+        }\r
+\r
+        public override bool IsDefined(Type attributeType, bool inherit) {\r
+            return MethodInfo.IsDefined(attributeType, inherit);\r
+        }\r
+\r
+        private ParameterDescriptor[] LazilyFetchParametersCollection() {\r
+            return DescriptorUtil.LazilyFetchOrCreateDescriptors<ParameterInfo, ParameterDescriptor>(\r
+                ref _parametersCache /* cacheLocation */,\r
+                MethodInfo.GetParameters /* initializer */,\r
+                parameterInfo => new ReflectedParameterDescriptor(parameterInfo, this) /* converter */);\r
+        }\r
+\r
+        internal static ReflectedActionDescriptor TryCreateDescriptor(MethodInfo methodInfo, string name, ControllerDescriptor controllerDescriptor) {\r
+            ReflectedActionDescriptor descriptor = new ReflectedActionDescriptor(methodInfo, name, controllerDescriptor, false /* validateMethod */);\r
+            string failedMessage = VerifyActionMethodIsCallable(methodInfo);\r
+            return (failedMessage == null) ? descriptor : null;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ReflectedControllerDescriptor.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ReflectedControllerDescriptor.cs
new file mode 100644 (file)
index 0000000..990f136
--- /dev/null
@@ -0,0 +1,91 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Linq;\r
+    using System.Reflection;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public class ReflectedControllerDescriptor : ControllerDescriptor {\r
+\r
+        private ActionDescriptor[] _canonicalActionsCache;\r
+        private readonly Type _controllerType;\r
+        private readonly ActionMethodSelector _selector;\r
+\r
+        public ReflectedControllerDescriptor(Type controllerType) {\r
+            if (controllerType == null) {\r
+                throw new ArgumentNullException("controllerType");\r
+            }\r
+\r
+            _controllerType = controllerType;\r
+            _selector = new ActionMethodSelector(_controllerType);\r
+        }\r
+\r
+        public sealed override Type ControllerType {\r
+            get {\r
+                return _controllerType;\r
+            }\r
+        }\r
+\r
+        public override ActionDescriptor FindAction(ControllerContext controllerContext, string actionName) {\r
+            if (controllerContext == null) {\r
+                throw new ArgumentNullException("controllerContext");\r
+            }\r
+            if (String.IsNullOrEmpty(actionName)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "actionName");\r
+            }\r
+\r
+            MethodInfo matched = _selector.FindActionMethod(controllerContext, actionName);\r
+            if (matched == null) {\r
+                return null;\r
+            }\r
+\r
+            return new ReflectedActionDescriptor(matched, actionName, this);\r
+        }\r
+\r
+        private MethodInfo[] GetAllActionMethodsFromSelector() {\r
+            List<MethodInfo> allValidMethods = new List<MethodInfo>();\r
+            allValidMethods.AddRange(_selector.AliasedMethods);\r
+            allValidMethods.AddRange(_selector.NonAliasedMethods.SelectMany(g => g));\r
+            return allValidMethods.ToArray();\r
+        }\r
+\r
+        public override ActionDescriptor[] GetCanonicalActions() {\r
+            ActionDescriptor[] actions = LazilyFetchCanonicalActionsCollection();\r
+\r
+            // need to clone array so that user modifications aren't accidentally stored\r
+            return (ActionDescriptor[])actions.Clone();\r
+        }\r
+\r
+        public override object[] GetCustomAttributes(bool inherit) {\r
+            return ControllerType.GetCustomAttributes(inherit);\r
+        }\r
+\r
+        public override object[] GetCustomAttributes(Type attributeType, bool inherit) {\r
+            return ControllerType.GetCustomAttributes(attributeType, inherit);\r
+        }\r
+\r
+        public override bool IsDefined(Type attributeType, bool inherit) {\r
+            return ControllerType.IsDefined(attributeType, inherit);\r
+        }\r
+\r
+        private ActionDescriptor[] LazilyFetchCanonicalActionsCollection() {\r
+            return DescriptorUtil.LazilyFetchOrCreateDescriptors<MethodInfo, ActionDescriptor>(\r
+                ref _canonicalActionsCache /* cacheLocation */,\r
+                GetAllActionMethodsFromSelector /* initializer */,\r
+                methodInfo => ReflectedActionDescriptor.TryCreateDescriptor(methodInfo, methodInfo.Name, this) /* converter */);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ReflectedParameterBindingInfo.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ReflectedParameterBindingInfo.cs
new file mode 100644 (file)
index 0000000..0281765
--- /dev/null
@@ -0,0 +1,73 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Collections.ObjectModel;\r
+    using System.Globalization;\r
+    using System.Reflection;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    internal class ReflectedParameterBindingInfo : ParameterBindingInfo {\r
+\r
+        private ICollection<string> _exclude = new string[0];\r
+        private ICollection<string> _include = new string[0];\r
+        private readonly ParameterInfo _parameterInfo;\r
+        private string _prefix;\r
+\r
+        public ReflectedParameterBindingInfo(ParameterInfo parameterInfo) {\r
+            _parameterInfo = parameterInfo;\r
+            ReadSettingsFromBindAttribute();\r
+        }\r
+\r
+        public override IModelBinder Binder {\r
+            get {\r
+                IModelBinder binder = ModelBinders.GetBinderFromAttributes(_parameterInfo,\r
+                    () => String.Format(CultureInfo.CurrentUICulture, MvcResources.ReflectedParameterBindingInfo_MultipleConverterAttributes,\r
+                        _parameterInfo.Name, _parameterInfo.Member));\r
+\r
+                return binder;\r
+            }\r
+        }\r
+\r
+        public override ICollection<string> Exclude {\r
+            get {\r
+                return _exclude;\r
+            }\r
+        }\r
+\r
+        public override ICollection<string> Include {\r
+            get {\r
+                return _include;\r
+            }\r
+        }\r
+\r
+        public override string Prefix {\r
+            get {\r
+                return _prefix;\r
+            }\r
+        }\r
+\r
+        private void ReadSettingsFromBindAttribute() {\r
+            BindAttribute attr = (BindAttribute)Attribute.GetCustomAttribute(_parameterInfo, typeof(BindAttribute));\r
+            if (attr == null) {\r
+                return;\r
+            }\r
+\r
+            _exclude = new ReadOnlyCollection<string>(AuthorizeAttribute.SplitString(attr.Exclude));\r
+            _include = new ReadOnlyCollection<string>(AuthorizeAttribute.SplitString(attr.Include));\r
+            _prefix = attr.Prefix;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ReflectedParameterDescriptor.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ReflectedParameterDescriptor.cs
new file mode 100644 (file)
index 0000000..357f45e
--- /dev/null
@@ -0,0 +1,90 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.ComponentModel;\r
+    using System.Reflection;\r
+\r
+    public class ReflectedParameterDescriptor : ParameterDescriptor {\r
+\r
+        private readonly ActionDescriptor _actionDescriptor;\r
+        private readonly ReflectedParameterBindingInfo _bindingInfo;\r
+\r
+        public ReflectedParameterDescriptor(ParameterInfo parameterInfo, ActionDescriptor actionDescriptor) {\r
+            if (parameterInfo == null) {\r
+                throw new ArgumentNullException("parameterInfo");\r
+            }\r
+            if (actionDescriptor == null) {\r
+                throw new ArgumentNullException("actionDescriptor");\r
+            }\r
+\r
+            ParameterInfo = parameterInfo;\r
+            _actionDescriptor = actionDescriptor;\r
+            _bindingInfo = new ReflectedParameterBindingInfo(parameterInfo);\r
+        }\r
+\r
+        public override ActionDescriptor ActionDescriptor {\r
+            get {\r
+                return _actionDescriptor;\r
+            }\r
+        }\r
+\r
+        public override ParameterBindingInfo BindingInfo {\r
+            get {\r
+                return _bindingInfo;\r
+            }\r
+        }\r
+\r
+        public override object DefaultValue {\r
+            get {\r
+                object value;\r
+                if (ParameterInfoUtil.TryGetDefaultValue(ParameterInfo, out value)) {\r
+                    return value;\r
+                }\r
+                else {\r
+                    return base.DefaultValue;\r
+                }\r
+            }\r
+        }\r
+\r
+        public ParameterInfo ParameterInfo {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public override string ParameterName {\r
+            get {\r
+                return ParameterInfo.Name;\r
+            }\r
+        }\r
+\r
+        public override Type ParameterType {\r
+            get {\r
+                return ParameterInfo.ParameterType;\r
+            }\r
+        }\r
+\r
+        public override object[] GetCustomAttributes(bool inherit) {\r
+            return ParameterInfo.GetCustomAttributes(inherit);\r
+        }\r
+\r
+        public override object[] GetCustomAttributes(Type attributeType, bool inherit) {\r
+            return ParameterInfo.GetCustomAttributes(attributeType, inherit);\r
+        }\r
+\r
+        public override bool IsDefined(Type attributeType, bool inherit) {\r
+            return ParameterInfo.IsDefined(attributeType, inherit);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/RegularExpressionAttributeAdapter.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/RegularExpressionAttributeAdapter.cs
new file mode 100644 (file)
index 0000000..f175502
--- /dev/null
@@ -0,0 +1,26 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Collections.Generic;\r
+    using System.ComponentModel.DataAnnotations;\r
+\r
+    public class RegularExpressionAttributeAdapter : DataAnnotationsModelValidator<RegularExpressionAttribute> {\r
+        public RegularExpressionAttributeAdapter(ModelMetadata metadata, ControllerContext context, RegularExpressionAttribute attribute)\r
+            : base(metadata, context, attribute) {\r
+        }\r
+\r
+        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() {\r
+            return new[] { new ModelClientValidationRegexRule(ErrorMessage, Attribute.Pattern) };\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/RequireHttpsAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/RequireHttpsAttribute.cs
new file mode 100644 (file)
index 0000000..dff4c92
--- /dev/null
@@ -0,0 +1,47 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    [SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes",\r
+        Justification = "Unsealed because type contains virtual extensibility points.")]\r
+    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\r
+    public class RequireHttpsAttribute : FilterAttribute, IAuthorizationFilter {\r
+\r
+        public virtual void OnAuthorization(AuthorizationContext filterContext) {\r
+            if (filterContext == null) {\r
+                throw new ArgumentNullException("filterContext");\r
+            }\r
+\r
+            if (!filterContext.HttpContext.Request.IsSecureConnection) {\r
+                HandleNonHttpsRequest(filterContext);\r
+            }\r
+        }\r
+\r
+        protected virtual void HandleNonHttpsRequest(AuthorizationContext filterContext) {\r
+            // only redirect for GET requests, otherwise the browser might not propagate the verb and request\r
+            // body correctly.\r
+\r
+            if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) {\r
+                throw new InvalidOperationException(MvcResources.RequireHttpsAttribute_MustUseSsl);\r
+            }\r
+\r
+            // redirect to HTTPS version of page\r
+            string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;\r
+            filterContext.Result = new RedirectResult(url);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/RequiredAttributeAdapter.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/RequiredAttributeAdapter.cs
new file mode 100644 (file)
index 0000000..edb7dc3
--- /dev/null
@@ -0,0 +1,26 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Collections.Generic;\r
+    using System.ComponentModel.DataAnnotations;\r
+\r
+    public class RequiredAttributeAdapter : DataAnnotationsModelValidator<RequiredAttribute> {\r
+        public RequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)\r
+            : base(metadata, context, attribute) {\r
+        }\r
+\r
+        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() {\r
+            return new[] { new ModelClientValidationRequiredRule(ErrorMessage) };\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Resources/MvcResources.Designer.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Resources/MvcResources.Designer.cs
new file mode 100644 (file)
index 0000000..4be3e6b
--- /dev/null
@@ -0,0 +1,797 @@
+//------------------------------------------------------------------------------\r
+// <auto-generated>\r
+//     This code was generated by a tool.\r
+//     Runtime Version:2.0.50727.4200\r
+//\r
+//     Changes to this file may cause incorrect behavior and will be lost if\r
+//     the code is regenerated.\r
+// </auto-generated>\r
+//------------------------------------------------------------------------------\r
+\r
+namespace System.Web.Mvc.Resources {\r
+    using System;\r
+    \r
+    \r
+    /// <summary>\r
+    ///   A strongly-typed resource class, for looking up localized strings, etc.\r
+    /// </summary>\r
+    // This class was auto-generated by the StronglyTypedResourceBuilder\r
+    // class via a tool like ResGen or Visual Studio.\r
+    // To add or remove a member, edit your .ResX file then rerun ResGen\r
+    // with the /str option, or rebuild your VS project.\r
+    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]\r
+    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\r
+    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\r
+    internal class MvcResources {\r
+        \r
+        private static global::System.Resources.ResourceManager resourceMan;\r
+        \r
+        private static global::System.Globalization.CultureInfo resourceCulture;\r
+        \r
+        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]\r
+        internal MvcResources() {\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Returns the cached ResourceManager instance used by this class.\r
+        /// </summary>\r
+        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\r
+        internal static global::System.Resources.ResourceManager ResourceManager {\r
+            get {\r
+                if (object.ReferenceEquals(resourceMan, null)) {\r
+                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("System.Web.Mvc.Resources.MvcResources", typeof(MvcResources).Assembly);\r
+                    resourceMan = temp;\r
+                }\r
+                return resourceMan;\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Overrides the current thread's CurrentUICulture property for all\r
+        ///   resource lookups using this strongly typed resource class.\r
+        /// </summary>\r
+        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\r
+        internal static global::System.Globalization.CultureInfo Culture {\r
+            get {\r
+                return resourceCulture;\r
+            }\r
+            set {\r
+                resourceCulture = value;\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The current request for action &apos;{0}&apos; on controller type &apos;{1}&apos; is ambiguous between the following action methods:{2}.\r
+        /// </summary>\r
+        internal static string ActionMethodSelector_AmbiguousMatch {\r
+            get {\r
+                return ResourceManager.GetString("ActionMethodSelector_AmbiguousMatch", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to {0} on type {1}.\r
+        /// </summary>\r
+        internal static string ActionMethodSelector_AmbiguousMatchType {\r
+            get {\r
+                return ResourceManager.GetString("ActionMethodSelector_AmbiguousMatchType", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to A required anti-forgery token was not supplied or was invalid..\r
+        /// </summary>\r
+        internal static string AntiForgeryToken_ValidationFailed {\r
+            get {\r
+                return ResourceManager.GetString("AntiForgeryToken_ValidationFailed", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to Lookup for method &apos;{0}&apos; on controller type &apos;{1}&apos; failed because of an ambiguity between the following methods:{2}.\r
+        /// </summary>\r
+        internal static string AsyncActionMethodSelector_AmbiguousMethodMatch {\r
+            get {\r
+                return ResourceManager.GetString("AsyncActionMethodSelector_AmbiguousMethodMatch", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to Could not locate a method named &apos;{0}&apos; on controller type {1}..\r
+        /// </summary>\r
+        internal static string AsyncActionMethodSelector_CouldNotFindMethod {\r
+            get {\r
+                return ResourceManager.GetString("AsyncActionMethodSelector_CouldNotFindMethod", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The provided IAsyncResult has already been consumed..\r
+        /// </summary>\r
+        internal static string AsyncCommon_AsyncResultAlreadyConsumed {\r
+            get {\r
+                return ResourceManager.GetString("AsyncCommon_AsyncResultAlreadyConsumed", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The controller of type &apos;{0}&apos; must subclass AsyncController or implement the IAsyncManagerContainer interface..\r
+        /// </summary>\r
+        internal static string AsyncCommon_ControllerMustImplementIAsyncManagerContainer {\r
+            get {\r
+                return ResourceManager.GetString("AsyncCommon_ControllerMustImplementIAsyncManagerContainer", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The provided IAsyncResult is not valid for this method..\r
+        /// </summary>\r
+        internal static string AsyncCommon_InvalidAsyncResult {\r
+            get {\r
+                return ResourceManager.GetString("AsyncCommon_InvalidAsyncResult", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The timeout value must be non-negative or Timeout.Infinite..\r
+        /// </summary>\r
+        internal static string AsyncCommon_InvalidTimeout {\r
+            get {\r
+                return ResourceManager.GetString("AsyncCommon_InvalidTimeout", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The action &apos;{0}&apos; is accessible only by a child request..\r
+        /// </summary>\r
+        internal static string ChildActionOnlyAttribute_MustBeInChildRequest {\r
+            get {\r
+                return ResourceManager.GetString("ChildActionOnlyAttribute_MustBeInChildRequest", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The field {0} must be a number..\r
+        /// </summary>\r
+        internal static string ClientDataTypeModelValidatorProvider_FieldMustBeNumeric {\r
+            get {\r
+                return ResourceManager.GetString("ClientDataTypeModelValidatorProvider_FieldMustBeNumeric", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to No route in the route table matches the supplied values..\r
+        /// </summary>\r
+        internal static string Common_NoRouteMatched {\r
+            get {\r
+                return ResourceManager.GetString("Common_NoRouteMatched", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to Value cannot be null or empty..\r
+        /// </summary>\r
+        internal static string Common_NullOrEmpty {\r
+            get {\r
+                return ResourceManager.GetString("Common_NullOrEmpty", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The partial view &apos;{0}&apos; was not found. The following locations were searched:{1}.\r
+        /// </summary>\r
+        internal static string Common_PartialViewNotFound {\r
+            get {\r
+                return ResourceManager.GetString("Common_PartialViewNotFound", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The property &apos;{0}&apos; cannot be null or empty..\r
+        /// </summary>\r
+        internal static string Common_PropertyCannotBeNullOrEmpty {\r
+            get {\r
+                return ResourceManager.GetString("Common_PropertyCannotBeNullOrEmpty", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The property {0}.{1} could not be found..\r
+        /// </summary>\r
+        internal static string Common_PropertyNotFound {\r
+            get {\r
+                return ResourceManager.GetString("Common_PropertyNotFound", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to False.\r
+        /// </summary>\r
+        internal static string Common_TriState_False {\r
+            get {\r
+                return ResourceManager.GetString("Common_TriState_False", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to Not Set.\r
+        /// </summary>\r
+        internal static string Common_TriState_NotSet {\r
+            get {\r
+                return ResourceManager.GetString("Common_TriState_NotSet", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to True.\r
+        /// </summary>\r
+        internal static string Common_TriState_True {\r
+            get {\r
+                return ResourceManager.GetString("Common_TriState_True", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The type {0} must derive from {1}.\r
+        /// </summary>\r
+        internal static string Common_TypeMustDriveFromType {\r
+            get {\r
+                return ResourceManager.GetString("Common_TypeMustDriveFromType", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The value &apos;{0}&apos; is invalid..\r
+        /// </summary>\r
+        internal static string Common_ValueNotValidForProperty {\r
+            get {\r
+                return ResourceManager.GetString("Common_ValueNotValidForProperty", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The view &apos;{0}&apos; or its master was not found. The following locations were searched:{1}.\r
+        /// </summary>\r
+        internal static string Common_ViewNotFound {\r
+            get {\r
+                return ResourceManager.GetString("Common_ViewNotFound", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to A public action method &apos;{0}&apos; was not found on controller &apos;{1}&apos;..\r
+        /// </summary>\r
+        internal static string Controller_UnknownAction {\r
+            get {\r
+                return ResourceManager.GetString("Controller_UnknownAction", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The model of type &apos;{0}&apos; could not be updated..\r
+        /// </summary>\r
+        internal static string Controller_UpdateModel_UpdateUnsuccessful {\r
+            get {\r
+                return ResourceManager.GetString("Controller_UpdateModel_UpdateUnsuccessful", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The model of type &apos;{0}&apos; is not valid..\r
+        /// </summary>\r
+        internal static string Controller_Validate_ValidationFailed {\r
+            get {\r
+                return ResourceManager.GetString("Controller_Validate_ValidationFailed", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to A single instance of controller &apos;{0}&apos; cannot be used to handle multiple requests. If a custom controller factory is in use, make sure that it creates a new instance of the controller for each request..\r
+        /// </summary>\r
+        internal static string ControllerBase_CannotHandleMultipleRequests {\r
+            get {\r
+                return ResourceManager.GetString("ControllerBase_CannotHandleMultipleRequests", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to An error occurred when trying to create the IControllerFactory &apos;{0}&apos;. Make sure that the controller factory has a public parameterless constructor..\r
+        /// </summary>\r
+        internal static string ControllerBuilder_ErrorCreatingControllerFactory {\r
+            get {\r
+                return ResourceManager.GetString("ControllerBuilder_ErrorCreatingControllerFactory", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The IControllerFactory &apos;{0}&apos; did not return a controller for the name &apos;{1}&apos;..\r
+        /// </summary>\r
+        internal static string ControllerBuilder_FactoryReturnedNull {\r
+            get {\r
+                return ResourceManager.GetString("ControllerBuilder_FactoryReturnedNull", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The controller factory type &apos;{0}&apos; must implement the IControllerFactory interface..\r
+        /// </summary>\r
+        internal static string ControllerBuilder_MissingIControllerFactory {\r
+            get {\r
+                return ResourceManager.GetString("ControllerBuilder_MissingIControllerFactory", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to {0} has a DisplayColumn attribute for {1}, but property {1} does not exist..\r
+        /// </summary>\r
+        internal static string DataAnnotationsModelMetadataProvider_UnknownProperty {\r
+            get {\r
+                return ResourceManager.GetString("DataAnnotationsModelMetadataProvider_UnknownProperty", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to {0} has a DisplayColumn attribute for {1}, but property {1} does not have a public getter..\r
+        /// </summary>\r
+        internal static string DataAnnotationsModelMetadataProvider_UnreadableProperty {\r
+            get {\r
+                return ResourceManager.GetString("DataAnnotationsModelMetadataProvider_UnreadableProperty", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The type {0} must have a public constructor which accepts three parameters of types {1}, {2}, and {3}.\r
+        /// </summary>\r
+        internal static string DataAnnotationsModelValidatorProvider_ConstructorRequirements {\r
+            get {\r
+                return ResourceManager.GetString("DataAnnotationsModelValidatorProvider_ConstructorRequirements", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to Multiple types were found that match the controller named &apos;{0}&apos;. This can happen if the route that services this request does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the &apos;MapRoute&apos; method that takes a &apos;namespaces&apos; parameter.\r
+        ///\r
+        ///The request for &apos;{0}&apos; has found the following matching controllers:{1}.\r
+        /// </summary>\r
+        internal static string DefaultControllerFactory_ControllerNameAmbiguous_WithoutRouteUrl {\r
+            get {\r
+                return ResourceManager.GetString("DefaultControllerFactory_ControllerNameAmbiguous_WithoutRouteUrl", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to Multiple types were found that match the controller named &apos;{0}&apos;. This can happen if the route that services this request (&apos;{1}&apos;) does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the &apos;MapRoute&apos; method that takes a &apos;namespaces&apos; parameter.\r
+        ///\r
+        ///The request for &apos;{0}&apos; has found the following matching controllers:{2}.\r
+        /// </summary>\r
+        internal static string DefaultControllerFactory_ControllerNameAmbiguous_WithRouteUrl {\r
+            get {\r
+                return ResourceManager.GetString("DefaultControllerFactory_ControllerNameAmbiguous_WithRouteUrl", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to An error occurred when trying to create a controller of type &apos;{0}&apos;. Make sure that the controller has a parameterless public constructor..\r
+        /// </summary>\r
+        internal static string DefaultControllerFactory_ErrorCreatingController {\r
+            get {\r
+                return ResourceManager.GetString("DefaultControllerFactory_ErrorCreatingController", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The controller for path &apos;{0}&apos; was not found or does not implement IController..\r
+        /// </summary>\r
+        internal static string DefaultControllerFactory_NoControllerFound {\r
+            get {\r
+                return ResourceManager.GetString("DefaultControllerFactory_NoControllerFound", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The controller type &apos;{0}&apos; must implement IController..\r
+        /// </summary>\r
+        internal static string DefaultControllerFactory_TypeDoesNotSubclassControllerBase {\r
+            get {\r
+                return ResourceManager.GetString("DefaultControllerFactory_TypeDoesNotSubclassControllerBase", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The value &apos;{0}&apos; is not valid for {1}..\r
+        /// </summary>\r
+        internal static string DefaultModelBinder_ValueInvalid {\r
+            get {\r
+                return ResourceManager.GetString("DefaultModelBinder_ValueInvalid", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to A value is required..\r
+        /// </summary>\r
+        internal static string DefaultModelBinder_ValueRequired {\r
+            get {\r
+                return ResourceManager.GetString("DefaultModelBinder_ValueRequired", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The number of ticks for the TimeSpan value must be greater than or equal to 0..\r
+        /// </summary>\r
+        internal static string DefaultViewLocationCache_NegativeTimeSpan {\r
+            get {\r
+                return ResourceManager.GetString("DefaultViewLocationCache_NegativeTimeSpan", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The type &apos;{0}&apos; does not inherit from Exception..\r
+        /// </summary>\r
+        internal static string ExceptionViewAttribute_NonExceptionType {\r
+            get {\r
+                return ResourceManager.GetString("ExceptionViewAttribute_NonExceptionType", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The expression compiler was unable to evaluate the indexer expression &apos;{0}&apos; because it references the model parameter &apos;{1}&apos; which is unavailable..\r
+        /// </summary>\r
+        internal static string ExpressionHelper_InvalidIndexerExpression {\r
+            get {\r
+                return ResourceManager.GetString("ExpressionHelper_InvalidIndexerExpression", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to Order must be greater than or equal to -1..\r
+        /// </summary>\r
+        internal static string FilterAttribute_OrderOutOfRange {\r
+            get {\r
+                return ResourceManager.GetString("FilterAttribute_OrderOutOfRange", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The GET and POST HTTP methods are not supported..\r
+        /// </summary>\r
+        internal static string HtmlHelper_InvalidHttpMethod {\r
+            get {\r
+                return ResourceManager.GetString("HtmlHelper_InvalidHttpMethod", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The specified HttpVerbs value is not supported. The supported values are Delete, Head, and Put..\r
+        /// </summary>\r
+        internal static string HtmlHelper_InvalidHttpVerb {\r
+            get {\r
+                return ResourceManager.GetString("HtmlHelper_InvalidHttpVerb", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to There is no ViewData item of type &apos;{1}&apos; that has the key &apos;{0}&apos;..\r
+        /// </summary>\r
+        internal static string HtmlHelper_MissingSelectData {\r
+            get {\r
+                return ResourceManager.GetString("HtmlHelper_MissingSelectData", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The value must be greater than or equal to zero..\r
+        /// </summary>\r
+        internal static string HtmlHelper_TextAreaParameterOutOfRange {\r
+            get {\r
+                return ResourceManager.GetString("HtmlHelper_TextAreaParameterOutOfRange", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The ViewData item that has the key &apos;{0}&apos; is of type &apos;{1}&apos; but must be of type &apos;{2}&apos;..\r
+        /// </summary>\r
+        internal static string HtmlHelper_WrongSelectDataType {\r
+            get {\r
+                return ResourceManager.GetString("HtmlHelper_WrongSelectDataType", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet..\r
+        /// </summary>\r
+        internal static string JsonRequest_GetNotAllowed {\r
+            get {\r
+                return ResourceManager.GetString("JsonRequest_GetNotAllowed", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to An error occurred when trying to create the IModelBinder &apos;{0}&apos;. Make sure that the binder has a public parameterless constructor..\r
+        /// </summary>\r
+        internal static string ModelBinderAttribute_ErrorCreatingModelBinder {\r
+            get {\r
+                return ResourceManager.GetString("ModelBinderAttribute_ErrorCreatingModelBinder", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The type &apos;{0}&apos; does not implement the IModelBinder interface..\r
+        /// </summary>\r
+        internal static string ModelBinderAttribute_TypeNotIModelBinder {\r
+            get {\r
+                return ResourceManager.GetString("ModelBinderAttribute_TypeNotIModelBinder", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The type &apos;{0}&apos; contains multiple attributes that inherit from CustomModelBinderAttribute..\r
+        /// </summary>\r
+        internal static string ModelBinderDictionary_MultipleAttributes {\r
+            get {\r
+                return ResourceManager.GetString("ModelBinderDictionary_MultipleAttributes", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to This property setter is obsolete, because its value is derived from ModelMetadata.Model now..\r
+        /// </summary>\r
+        internal static string ModelMetadata_PropertyNotSettable {\r
+            get {\r
+                return ResourceManager.GetString("ModelMetadata_PropertyNotSettable", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The associated metadata type for type &apos;{0}&apos; contains the following unknown properties or fields: {1}. Please make sure that the names of these members match the names of the properties on the main type..\r
+        /// </summary>\r
+        internal static string PrivateAssociatedMetadataTypeTypeDescriptor_MetadataTypeContainsUnknownProperties {\r
+            get {\r
+                return ResourceManager.GetString("PrivateAssociatedMetadataTypeTypeDescriptor_MetadataTypeContainsUnknownProperties" +\r
+                        "", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to Child actions are not allowed to perform redirect actions..\r
+        /// </summary>\r
+        internal static string RedirectAction_CannotRedirectInChildAction {\r
+            get {\r
+                return ResourceManager.GetString("RedirectAction_CannotRedirectInChildAction", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to Cannot create a descriptor for instance method &apos;{0}&apos; on type &apos;{1}&apos; because the type does not derive from ControllerBase..\r
+        /// </summary>\r
+        internal static string ReflectedActionDescriptor_CannotCallInstanceMethodOnNonControllerType {\r
+            get {\r
+                return ResourceManager.GetString("ReflectedActionDescriptor_CannotCallInstanceMethodOnNonControllerType", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to Cannot call action method &apos;{0}&apos; on controller &apos;{1}&apos; because the parameter &apos;{2}&apos; is passed by reference..\r
+        /// </summary>\r
+        internal static string ReflectedActionDescriptor_CannotCallMethodsWithOutOrRefParameters {\r
+            get {\r
+                return ResourceManager.GetString("ReflectedActionDescriptor_CannotCallMethodsWithOutOrRefParameters", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to Cannot call action method &apos;{0}&apos; on controller &apos;{1}&apos; because the action method is a generic method..\r
+        /// </summary>\r
+        internal static string ReflectedActionDescriptor_CannotCallOpenGenericMethods {\r
+            get {\r
+                return ResourceManager.GetString("ReflectedActionDescriptor_CannotCallOpenGenericMethods", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The parameters dictionary contains a null entry for parameter &apos;{0}&apos; of non-nullable type &apos;{1}&apos; for method &apos;{2}&apos; in &apos;{3}&apos;. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter..\r
+        /// </summary>\r
+        internal static string ReflectedActionDescriptor_ParameterCannotBeNull {\r
+            get {\r
+                return ResourceManager.GetString("ReflectedActionDescriptor_ParameterCannotBeNull", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The parameters dictionary does not contain an entry for parameter &apos;{0}&apos; of type &apos;{1}&apos; for method &apos;{2}&apos; in &apos;{3}&apos;. The dictionary must contain an entry for each parameter, including parameters that have null values..\r
+        /// </summary>\r
+        internal static string ReflectedActionDescriptor_ParameterNotInDictionary {\r
+            get {\r
+                return ResourceManager.GetString("ReflectedActionDescriptor_ParameterNotInDictionary", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The parameters dictionary contains an invalid entry for parameter &apos;{0}&apos; for method &apos;{1}&apos; in &apos;{2}&apos;. The dictionary contains a value of type &apos;{3}&apos;, but the parameter requires a value of type &apos;{4}&apos;..\r
+        /// </summary>\r
+        internal static string ReflectedActionDescriptor_ParameterValueHasWrongType {\r
+            get {\r
+                return ResourceManager.GetString("ReflectedActionDescriptor_ParameterValueHasWrongType", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The asynchronous action method &apos;{0}&apos; cannot be executed synchronously..\r
+        /// </summary>\r
+        internal static string ReflectedAsyncActionDescriptor_CannotExecuteSynchronously {\r
+            get {\r
+                return ResourceManager.GetString("ReflectedAsyncActionDescriptor_CannotExecuteSynchronously", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The parameter &apos;{0}&apos; on method &apos;{1}&apos; contains multiple attributes that inherit from CustomModelBinderAttribute..\r
+        /// </summary>\r
+        internal static string ReflectedParameterBindingInfo_MultipleConverterAttributes {\r
+            get {\r
+                return ResourceManager.GetString("ReflectedParameterBindingInfo_MultipleConverterAttributes", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The requested resource can only be accessed via SSL..\r
+        /// </summary>\r
+        internal static string RequireHttpsAttribute_MustUseSsl {\r
+            get {\r
+                return ResourceManager.GetString("RequireHttpsAttribute_MustUseSsl", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The SessionStateTempDataProvider class requires session state to be enabled..\r
+        /// </summary>\r
+        internal static string SessionStateTempDataProvider_SessionStateDisabled {\r
+            get {\r
+                return ResourceManager.GetString("SessionStateTempDataProvider_SessionStateDisabled", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to An operation that crossed a synchronization context failed. See the inner exception for more information..\r
+        /// </summary>\r
+        internal static string SynchronizationContextUtil_ExceptionThrown {\r
+            get {\r
+                return ResourceManager.GetString("SynchronizationContextUtil_ExceptionThrown", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to Unable to locate an appropriate template for type {0}..\r
+        /// </summary>\r
+        internal static string TemplateHelpers_NoTemplate {\r
+            get {\r
+                return ResourceManager.GetString("TemplateHelpers_NoTemplate", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions..\r
+        /// </summary>\r
+        internal static string TemplateHelpers_TemplateLimitations {\r
+            get {\r
+                return ResourceManager.GetString("TemplateHelpers_TemplateLimitations", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The Collection template was used with an object of type &apos;{0}&apos;, which does not implement System.IEnumerable..\r
+        /// </summary>\r
+        internal static string Templates_TypeMustImplementIEnumerable {\r
+            get {\r
+                return ResourceManager.GetString("Templates_TypeMustImplementIEnumerable", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to This file is automatically generated. Please do not modify the contents of this file..\r
+        /// </summary>\r
+        internal static string TypeCache_DoNotModify {\r
+            get {\r
+                return ResourceManager.GetString("TypeCache_DoNotModify", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The parameter conversion from type &apos;{0}&apos; to type &apos;{1}&apos; failed. See the inner exception for more information..\r
+        /// </summary>\r
+        internal static string ValueProviderResult_ConversionThrew {\r
+            get {\r
+                return ResourceManager.GetString("ValueProviderResult_ConversionThrew", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The parameter conversion from type &apos;{0}&apos; to type &apos;{1}&apos; failed because no type converter can convert between these types..\r
+        /// </summary>\r
+        internal static string ValueProviderResult_NoConverterExists {\r
+            get {\r
+                return ResourceManager.GetString("ValueProviderResult_NoConverterExists", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type &apos;{0}&apos;..\r
+        /// </summary>\r
+        internal static string ViewDataDictionary_ModelCannotBeNull {\r
+            get {\r
+                return ResourceManager.GetString("ViewDataDictionary_ModelCannotBeNull", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The model item passed into the dictionary is of type &apos;{0}&apos;, but this dictionary requires a model item of type &apos;{1}&apos;..\r
+        /// </summary>\r
+        internal static string ViewDataDictionary_WrongTModelType {\r
+            get {\r
+                return ResourceManager.GetString("ViewDataDictionary_WrongTModelType", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to A ViewMasterPage can be used only with content pages that derive from ViewPage or ViewPage&lt;TViewItem&gt;..\r
+        /// </summary>\r
+        internal static string ViewMasterPage_RequiresViewPage {\r
+            get {\r
+                return ResourceManager.GetString("ViewMasterPage_RequiresViewPage", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to Execution of the child request failed. Please examine the InnerException for more information..\r
+        /// </summary>\r
+        internal static string ViewPageHttpHandlerWrapper_ExceptionOccurred {\r
+            get {\r
+                return ResourceManager.GetString("ViewPageHttpHandlerWrapper_ExceptionOccurred", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The ViewUserControl &apos;{0}&apos; cannot find an IViewDataContainer object. The ViewUserControl must be inside a ViewPage, a ViewMasterPage, or another ViewUserControl..\r
+        /// </summary>\r
+        internal static string ViewUserControl_RequiresViewDataProvider {\r
+            get {\r
+                return ResourceManager.GetString("ViewUserControl_RequiresViewDataProvider", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to A ViewUserControl can be used only in pages that derive from ViewPage or ViewPage&lt;TViewItem&gt;..\r
+        /// </summary>\r
+        internal static string ViewUserControl_RequiresViewPage {\r
+            get {\r
+                return ResourceManager.GetString("ViewUserControl_RequiresViewPage", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to A master name cannot be specified when the view is a ViewUserControl..\r
+        /// </summary>\r
+        internal static string WebFormViewEngine_UserControlCannotHaveMaster {\r
+            get {\r
+                return ResourceManager.GetString("WebFormViewEngine_UserControlCannotHaveMaster", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The view found at &apos;{0}&apos; was not created..\r
+        /// </summary>\r
+        internal static string WebFormViewEngine_ViewCouldNotBeCreated {\r
+            get {\r
+                return ResourceManager.GetString("WebFormViewEngine_ViewCouldNotBeCreated", resourceCulture);\r
+            }\r
+        }\r
+        \r
+        /// <summary>\r
+        ///   Looks up a localized string similar to The view at &apos;{0}&apos; must derive from ViewPage, ViewPage&lt;TViewData&gt;, ViewUserControl, or ViewUserControl&lt;TViewData&gt;..\r
+        /// </summary>\r
+        internal static string WebFormViewEngine_WrongViewBase {\r
+            get {\r
+                return ResourceManager.GetString("WebFormViewEngine_WrongViewBase", resourceCulture);\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/Resources/MvcResources.resx b/mcs/class/System.Web.Mvc2/System.Web.Mvc/Resources/MvcResources.resx
new file mode 100644 (file)
index 0000000..6e29c4d
--- /dev/null
@@ -0,0 +1,367 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<root>\r
+  <!-- \r
+    Microsoft ResX Schema \r
+    \r
+    Version 2.0\r
+    \r
+    The primary goals of this format is to allow a simple XML format \r
+    that is mostly human readable. The generation and parsing of the \r
+    various data types are done through the TypeConverter classes \r
+    associated with the data types.\r
+    \r
+    Example:\r
+    \r
+    ... ado.net/XML headers & schema ...\r
+    <resheader name="resmimetype">text/microsoft-resx</resheader>\r
+    <resheader name="version">2.0</resheader>\r
+    <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\r
+    <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\r
+    <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>\r
+    <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>\r
+    <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">\r
+        <value>[base64 mime encoded serialized .NET Framework object]</value>\r
+    </data>\r
+    <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">\r
+        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\r
+        <comment>This is a comment</comment>\r
+    </data>\r
+                \r
+    There are any number of "resheader" rows that contain simple \r
+    name/value pairs.\r
+    \r
+    Each data row contains a name, and value. The row also contains a \r
+    type or mimetype. Type corresponds to a .NET class that support \r
+    text/value conversion through the TypeConverter architecture. \r
+    Classes that don't support this are serialized and stored with the \r
+    mimetype set.\r
+    \r
+    The mimetype is used for serialized objects, and tells the \r
+    ResXResourceReader how to depersist the object. This is currently not \r
+    extensible. For a given mimetype the value must be set accordingly:\r
+    \r
+    Note - application/x-microsoft.net.object.binary.base64 is the format \r
+    that the ResXResourceWriter will generate, however the reader can \r
+    read any of the formats listed below.\r
+    \r
+    mimetype: application/x-microsoft.net.object.binary.base64\r
+    value   : The object must be serialized with \r
+            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\r
+            : and then encoded with base64 encoding.\r
+    \r
+    mimetype: application/x-microsoft.net.object.soap.base64\r
+    value   : The object must be serialized with \r
+            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\r
+            : and then encoded with base64 encoding.\r
+\r
+    mimetype: application/x-microsoft.net.object.bytearray.base64\r
+    value   : The object must be serialized into a byte array \r
+            : using a System.ComponentModel.TypeConverter\r
+            : and then encoded with base64 encoding.\r
+    -->\r
+  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">\r
+    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />\r
+    <xsd:element name="root" msdata:IsDataSet="true">\r
+      <xsd:complexType>\r
+        <xsd:choice maxOccurs="unbounded">\r
+          <xsd:element name="metadata">\r
+            <xsd:complexType>\r
+              <xsd:sequence>\r
+                <xsd:element name="value" type="xsd:string" minOccurs="0" />\r
+              </xsd:sequence>\r
+              <xsd:attribute name="name" use="required" type="xsd:string" />\r
+              <xsd:attribute name="type" type="xsd:string" />\r
+              <xsd:attribute name="mimetype" type="xsd:string" />\r
+              <xsd:attribute ref="xml:space" />\r
+            </xsd:complexType>\r
+          </xsd:element>\r
+          <xsd:element name="assembly">\r
+            <xsd:complexType>\r
+              <xsd:attribute name="alias" type="xsd:string" />\r
+              <xsd:attribute name="name" type="xsd:string" />\r
+            </xsd:complexType>\r
+          </xsd:element>\r
+          <xsd:element name="data">\r
+            <xsd:complexType>\r
+              <xsd:sequence>\r
+                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />\r
+                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />\r
+              </xsd:sequence>\r
+              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />\r
+              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />\r
+              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />\r
+              <xsd:attribute ref="xml:space" />\r
+            </xsd:complexType>\r
+          </xsd:element>\r
+          <xsd:element name="resheader">\r
+            <xsd:complexType>\r
+              <xsd:sequence>\r
+                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />\r
+              </xsd:sequence>\r
+              <xsd:attribute name="name" type="xsd:string" use="required" />\r
+            </xsd:complexType>\r
+          </xsd:element>\r
+        </xsd:choice>\r
+      </xsd:complexType>\r
+    </xsd:element>\r
+  </xsd:schema>\r
+  <resheader name="resmimetype">\r
+    <value>text/microsoft-resx</value>\r
+  </resheader>\r
+  <resheader name="version">\r
+    <value>2.0</value>\r
+  </resheader>\r
+  <resheader name="reader">\r
+    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r
+  </resheader>\r
+  <resheader name="writer">\r
+    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\r
+  </resheader>\r
+  <data name="ActionMethodSelector_AmbiguousMatch" xml:space="preserve">\r
+    <value>The current request for action '{0}' on controller type '{1}' is ambiguous between the following action methods:{2}</value>\r
+  </data>\r
+  <data name="Common_NoRouteMatched" xml:space="preserve">\r
+    <value>No route in the route table matches the supplied values.</value>\r
+  </data>\r
+  <data name="Common_NullOrEmpty" xml:space="preserve">\r
+    <value>Value cannot be null or empty.</value>\r
+  </data>\r
+  <data name="Common_PartialViewNotFound" xml:space="preserve">\r
+    <value>The partial view '{0}' was not found. The following locations were searched:{1}</value>\r
+  </data>\r
+  <data name="Common_PropertyCannotBeNullOrEmpty" xml:space="preserve">\r
+    <value>The property '{0}' cannot be null or empty.</value>\r
+  </data>\r
+  <data name="Common_ViewNotFound" xml:space="preserve">\r
+    <value>The view '{0}' or its master was not found. The following locations were searched:{1}</value>\r
+  </data>\r
+  <data name="ControllerBuilder_ErrorCreatingControllerFactory" xml:space="preserve">\r
+    <value>An error occurred when trying to create the IControllerFactory '{0}'. Make sure that the controller factory has a public parameterless constructor.</value>\r
+  </data>\r
+  <data name="ControllerBuilder_FactoryReturnedNull" xml:space="preserve">\r
+    <value>The IControllerFactory '{0}' did not return a controller for the name '{1}'.</value>\r
+  </data>\r
+  <data name="ControllerBuilder_MissingIControllerFactory" xml:space="preserve">\r
+    <value>The controller factory type '{0}' must implement the IControllerFactory interface.</value>\r
+  </data>\r
+  <data name="Controller_UnknownAction" xml:space="preserve">\r
+    <value>A public action method '{0}' was not found on controller '{1}'.</value>\r
+  </data>\r
+  <data name="DefaultControllerFactory_ErrorCreatingController" xml:space="preserve">\r
+    <value>An error occurred when trying to create a controller of type '{0}'. Make sure that the controller has a parameterless public constructor.</value>\r
+  </data>\r
+  <data name="DefaultControllerFactory_NoControllerFound" xml:space="preserve">\r
+    <value>The controller for path '{0}' was not found or does not implement IController.</value>\r
+  </data>\r
+  <data name="DefaultControllerFactory_TypeDoesNotSubclassControllerBase" xml:space="preserve">\r
+    <value>The controller type '{0}' must implement IController.</value>\r
+  </data>\r
+  <data name="ValueProviderResult_ConversionThrew" xml:space="preserve">\r
+    <value>The parameter conversion from type '{0}' to type '{1}' failed. See the inner exception for more information.</value>\r
+  </data>\r
+  <data name="ValueProviderResult_NoConverterExists" xml:space="preserve">\r
+    <value>The parameter conversion from type '{0}' to type '{1}' failed because no type converter can convert between these types.</value>\r
+  </data>\r
+  <data name="ExceptionViewAttribute_NonExceptionType" xml:space="preserve">\r
+    <value>The type '{0}' does not inherit from Exception.</value>\r
+  </data>\r
+  <data name="FilterAttribute_OrderOutOfRange" xml:space="preserve">\r
+    <value>Order must be greater than or equal to -1.</value>\r
+  </data>\r
+  <data name="HtmlHelper_MissingSelectData" xml:space="preserve">\r
+    <value>There is no ViewData item of type '{1}' that has the key '{0}'.</value>\r
+  </data>\r
+  <data name="HtmlHelper_TextAreaParameterOutOfRange" xml:space="preserve">\r
+    <value>The value must be greater than or equal to zero.</value>\r
+  </data>\r
+  <data name="HtmlHelper_WrongSelectDataType" xml:space="preserve">\r
+    <value>The ViewData item that has the key '{0}' is of type '{1}' but must be of type '{2}'.</value>\r
+  </data>\r
+  <data name="ModelBinderAttribute_ErrorCreatingModelBinder" xml:space="preserve">\r
+    <value>An error occurred when trying to create the IModelBinder '{0}'. Make sure that the binder has a public parameterless constructor.</value>\r
+  </data>\r
+  <data name="ModelBinderAttribute_TypeNotIModelBinder" xml:space="preserve">\r
+    <value>The type '{0}' does not implement the IModelBinder interface.</value>\r
+  </data>\r
+  <data name="ModelBinderDictionary_MultipleAttributes" xml:space="preserve">\r
+    <value>The type '{0}' contains multiple attributes that inherit from CustomModelBinderAttribute.</value>\r
+  </data>\r
+  <data name="SessionStateTempDataProvider_SessionStateDisabled" xml:space="preserve">\r
+    <value>The SessionStateTempDataProvider class requires session state to be enabled.</value>\r
+  </data>\r
+  <data name="ViewDataDictionary_WrongTModelType" xml:space="preserve">\r
+    <value>The model item passed into the dictionary is of type '{0}', but this dictionary requires a model item of type '{1}'.</value>\r
+  </data>\r
+  <data name="ViewMasterPage_RequiresViewPage" xml:space="preserve">\r
+    <value>A ViewMasterPage can be used only with content pages that derive from ViewPage or ViewPage&lt;TViewItem&gt;.</value>\r
+  </data>\r
+  <data name="ViewUserControl_RequiresViewDataProvider" xml:space="preserve">\r
+    <value>The ViewUserControl '{0}' cannot find an IViewDataContainer object. The ViewUserControl must be inside a ViewPage, a ViewMasterPage, or another ViewUserControl.</value>\r
+  </data>\r
+  <data name="ViewUserControl_RequiresViewPage" xml:space="preserve">\r
+    <value>A ViewUserControl can be used only in pages that derive from ViewPage or ViewPage&lt;TViewItem&gt;.</value>\r
+  </data>\r
+  <data name="WebFormViewEngine_UserControlCannotHaveMaster" xml:space="preserve">\r
+    <value>A master name cannot be specified when the view is a ViewUserControl.</value>\r
+  </data>\r
+  <data name="WebFormViewEngine_ViewCouldNotBeCreated" xml:space="preserve">\r
+    <value>The view found at '{0}' was not created.</value>\r
+  </data>\r
+  <data name="WebFormViewEngine_WrongViewBase" xml:space="preserve">\r
+    <value>The view at '{0}' must derive from ViewPage, ViewPage&lt;TViewData&gt;, ViewUserControl, or ViewUserControl&lt;TViewData&gt;.</value>\r
+  </data>\r
+  <data name="Common_ValueNotValidForProperty" xml:space="preserve">\r
+    <value>The value '{0}' is invalid.</value>\r
+  </data>\r
+  <data name="ActionMethodSelector_AmbiguousMatchType" xml:space="preserve">\r
+    <value>{0} on type {1}</value>\r
+  </data>\r
+  <data name="Controller_UpdateModel_UpdateUnsuccessful" xml:space="preserve">\r
+    <value>The model of type '{0}' could not be updated.</value>\r
+  </data>\r
+  <data name="DefaultModelBinder_ValueRequired" xml:space="preserve">\r
+    <value>A value is required.</value>\r
+  </data>\r
+  <data name="ReflectedActionDescriptor_ParameterCannotBeNull" xml:space="preserve">\r
+    <value>The parameters dictionary contains a null entry for parameter '{0}' of non-nullable type '{1}' for method '{2}' in '{3}'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.</value>\r
+  </data>\r
+  <data name="ReflectedActionDescriptor_ParameterNotInDictionary" xml:space="preserve">\r
+    <value>The parameters dictionary does not contain an entry for parameter '{0}' of type '{1}' for method '{2}' in '{3}'. The dictionary must contain an entry for each parameter, including parameters that have null values.</value>\r
+  </data>\r
+  <data name="ReflectedActionDescriptor_ParameterValueHasWrongType" xml:space="preserve">\r
+    <value>The parameters dictionary contains an invalid entry for parameter '{0}' for method '{1}' in '{2}'. The dictionary contains a value of type '{3}', but the parameter requires a value of type '{4}'.</value>\r
+  </data>\r
+  <data name="ReflectedParameterBindingInfo_MultipleConverterAttributes" xml:space="preserve">\r
+    <value>The parameter '{0}' on method '{1}' contains multiple attributes that inherit from CustomModelBinderAttribute.</value>\r
+  </data>\r
+  <data name="ReflectedActionDescriptor_CannotCallInstanceMethodOnNonControllerType" xml:space="preserve">\r
+    <value>Cannot create a descriptor for instance method '{0}' on type '{1}' because the type does not derive from ControllerBase.</value>\r
+  </data>\r
+  <data name="ReflectedActionDescriptor_CannotCallMethodsWithOutOrRefParameters" xml:space="preserve">\r
+    <value>Cannot call action method '{0}' on controller '{1}' because the parameter '{2}' is passed by reference.</value>\r
+  </data>\r
+  <data name="ReflectedActionDescriptor_CannotCallOpenGenericMethods" xml:space="preserve">\r
+    <value>Cannot call action method '{0}' on controller '{1}' because the action method is a generic method.</value>\r
+  </data>\r
+  <data name="DefaultViewLocationCache_NegativeTimeSpan" xml:space="preserve">\r
+    <value>The number of ticks for the TimeSpan value must be greater than or equal to 0.</value>\r
+  </data>\r
+  <data name="AntiForgeryToken_ValidationFailed" xml:space="preserve">\r
+    <value>A required anti-forgery token was not supplied or was invalid.</value>\r
+  </data>\r
+  <data name="DefaultModelBinder_ValueInvalid" xml:space="preserve">\r
+    <value>The value '{0}' is not valid for {1}.</value>\r
+  </data>\r
+  <data name="TemplateHelpers_TemplateLimitations" xml:space="preserve">\r
+    <value>Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.</value>\r
+  </data>\r
+  <data name="Common_TriState_False" xml:space="preserve">\r
+    <value>False</value>\r
+  </data>\r
+  <data name="Common_TriState_NotSet" xml:space="preserve">\r
+    <value>Not Set</value>\r
+  </data>\r
+  <data name="Common_TriState_True" xml:space="preserve">\r
+    <value>True</value>\r
+  </data>\r
+  <data name="ControllerBase_CannotHandleMultipleRequests" xml:space="preserve">\r
+    <value>A single instance of controller '{0}' cannot be used to handle multiple requests. If a custom controller factory is in use, make sure that it creates a new instance of the controller for each request.</value>\r
+  </data>\r
+  <data name="Common_PropertyNotFound" xml:space="preserve">\r
+    <value>The property {0}.{1} could not be found.</value>\r
+  </data>\r
+  <data name="DataAnnotationsModelMetadataProvider_UnknownProperty" xml:space="preserve">\r
+    <value>{0} has a DisplayColumn attribute for {1}, but property {1} does not exist.</value>\r
+  </data>\r
+  <data name="DataAnnotationsModelMetadataProvider_UnreadableProperty" xml:space="preserve">\r
+    <value>{0} has a DisplayColumn attribute for {1}, but property {1} does not have a public getter.</value>\r
+  </data>\r
+  <data name="TemplateHelpers_NoTemplate" xml:space="preserve">\r
+    <value>Unable to locate an appropriate template for type {0}.</value>\r
+  </data>\r
+  <data name="RequireHttpsAttribute_MustUseSsl" xml:space="preserve">\r
+    <value>The requested resource can only be accessed via SSL.</value>\r
+  </data>\r
+  <data name="HtmlHelper_InvalidHttpVerb" xml:space="preserve">\r
+    <value>The specified HttpVerbs value is not supported. The supported values are Delete, Head, and Put.</value>\r
+  </data>\r
+  <data name="HtmlHelper_InvalidHttpMethod" xml:space="preserve">\r
+    <value>The GET and POST HTTP methods are not supported.</value>\r
+  </data>\r
+  <data name="JsonRequest_GetNotAllowed" xml:space="preserve">\r
+    <value>This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.</value>\r
+  </data>\r
+  <data name="ModelMetadata_PropertyNotSettable" xml:space="preserve">\r
+    <value>This property setter is obsolete, because its value is derived from ModelMetadata.Model now.</value>\r
+  </data>\r
+  <data name="ViewDataDictionary_ModelCannotBeNull" xml:space="preserve">\r
+    <value>The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type '{0}'.</value>\r
+  </data>\r
+  <data name="Common_TypeMustDriveFromType" xml:space="preserve">\r
+    <value>The type {0} must derive from {1}</value>\r
+  </data>\r
+  <data name="DataAnnotationsModelValidatorProvider_ConstructorRequirements" xml:space="preserve">\r
+    <value>The type {0} must have a public constructor which accepts three parameters of types {1}, {2}, and {3}</value>\r
+  </data>\r
+  <data name="ViewPageHttpHandlerWrapper_ExceptionOccurred" xml:space="preserve">\r
+    <value>Execution of the child request failed. Please examine the InnerException for more information.</value>\r
+  </data>\r
+  <data name="RedirectAction_CannotRedirectInChildAction" xml:space="preserve">\r
+    <value>Child actions are not allowed to perform redirect actions.</value>\r
+  </data>\r
+  <data name="AsyncCommon_AsyncResultAlreadyConsumed" xml:space="preserve">\r
+    <value>The provided IAsyncResult has already been consumed.</value>\r
+  </data>\r
+  <data name="AsyncCommon_InvalidAsyncResult" xml:space="preserve">\r
+    <value>The provided IAsyncResult is not valid for this method.</value>\r
+  </data>\r
+  <data name="SynchronizationContextUtil_ExceptionThrown" xml:space="preserve">\r
+    <value>An operation that crossed a synchronization context failed. See the inner exception for more information.</value>\r
+  </data>\r
+  <data name="ReflectedAsyncActionDescriptor_CannotExecuteSynchronously" xml:space="preserve">\r
+    <value>The asynchronous action method '{0}' cannot be executed synchronously.</value>\r
+  </data>\r
+  <data name="AsyncCommon_ControllerMustImplementIAsyncManagerContainer" xml:space="preserve">\r
+    <value>The controller of type '{0}' must subclass AsyncController or implement the IAsyncManagerContainer interface.</value>\r
+  </data>\r
+  <data name="AsyncCommon_InvalidTimeout" xml:space="preserve">\r
+    <value>The timeout value must be non-negative or Timeout.Infinite.</value>\r
+  </data>\r
+  <data name="AsyncActionMethodSelector_AmbiguousMethodMatch" xml:space="preserve">\r
+    <value>Lookup for method '{0}' on controller type '{1}' failed because of an ambiguity between the following methods:{2}</value>\r
+  </data>\r
+  <data name="AsyncActionMethodSelector_CouldNotFindMethod" xml:space="preserve">\r
+    <value>Could not locate a method named '{0}' on controller type {1}.</value>\r
+  </data>\r
+  <data name="ChildActionOnlyAttribute_MustBeInChildRequest" xml:space="preserve">\r
+    <value>The action '{0}' is accessible only by a child request.</value>\r
+  </data>\r
+  <data name="Templates_TypeMustImplementIEnumerable" xml:space="preserve">\r
+    <value>The Collection template was used with an object of type '{0}', which does not implement System.IEnumerable.</value>\r
+  </data>\r
+  <data name="TypeCache_DoNotModify" xml:space="preserve">\r
+    <value>This file is automatically generated. Please do not modify the contents of this file.</value>\r
+  </data>\r
+  <data name="PrivateAssociatedMetadataTypeTypeDescriptor_MetadataTypeContainsUnknownProperties" xml:space="preserve">\r
+    <value>The associated metadata type for type '{0}' contains the following unknown properties or fields: {1}. Please make sure that the names of these members match the names of the properties on the main type.</value>\r
+  </data>\r
+  <data name="ClientDataTypeModelValidatorProvider_FieldMustBeNumeric" xml:space="preserve">\r
+    <value>The field {0} must be a number.</value>\r
+  </data>\r
+  <data name="ExpressionHelper_InvalidIndexerExpression" xml:space="preserve">\r
+    <value>The expression compiler was unable to evaluate the indexer expression '{0}' because it references the model parameter '{1}' which is unavailable.</value>\r
+  </data>\r
+  <data name="Controller_Validate_ValidationFailed" xml:space="preserve">\r
+    <value>The model of type '{0}' is not valid.</value>\r
+  </data>\r
+  <data name="DefaultControllerFactory_ControllerNameAmbiguous_WithoutRouteUrl" xml:space="preserve">\r
+    <value>Multiple types were found that match the controller named '{0}'. This can happen if the route that services this request does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.\r
+\r
+The request for '{0}' has found the following matching controllers:{1}</value>\r
+  </data>\r
+  <data name="DefaultControllerFactory_ControllerNameAmbiguous_WithRouteUrl" xml:space="preserve">\r
+    <value>Multiple types were found that match the controller named '{0}'. This can happen if the route that services this request ('{1}') does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.\r
+\r
+The request for '{0}' has found the following matching controllers:{2}</value>\r
+  </data>\r
+</root>
\ No newline at end of file
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ResultExecutedContext.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ResultExecutedContext.cs
new file mode 100644 (file)
index 0000000..aec1a1f
--- /dev/null
@@ -0,0 +1,57 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+\r
+    public class ResultExecutedContext : ControllerContext {\r
+\r
+        // parameterless constructor used for mocking\r
+        public ResultExecutedContext() {\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors",\r
+            Justification = "The virtual property setters are only to support mocking frameworks, in which case this constructor shouldn't be called anyway.")]\r
+        public ResultExecutedContext(ControllerContext controllerContext, ActionResult result, bool canceled, Exception exception)\r
+            : base(controllerContext) {\r
+            if (result == null) {\r
+                throw new ArgumentNullException("result");\r
+            }\r
+\r
+            Result = result;\r
+            Canceled = canceled;\r
+            Exception = exception;\r
+        }\r
+\r
+        public virtual bool Canceled {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public virtual Exception Exception {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public bool ExceptionHandled {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public virtual ActionResult Result {\r
+            get;\r
+            set;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ResultExecutingContext.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ResultExecutingContext.cs
new file mode 100644 (file)
index 0000000..893bfd0
--- /dev/null
@@ -0,0 +1,45 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+\r
+    public class ResultExecutingContext : ControllerContext {\r
+\r
+        // parameterless constructor used for mocking\r
+        public ResultExecutingContext() {\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors",\r
+            Justification = "The virtual property setters are only to support mocking frameworks, in which case this constructor shouldn't be called anyway.")]\r
+        public ResultExecutingContext(ControllerContext controllerContext, ActionResult result)\r
+            : base(controllerContext) {\r
+            if (result == null) {\r
+                throw new ArgumentNullException("result");\r
+            }\r
+\r
+            Result = result;\r
+        }\r
+\r
+        public bool Cancel {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public virtual ActionResult Result {\r
+            get;\r
+            set;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/RouteCollectionExtensions.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/RouteCollectionExtensions.cs
new file mode 100644 (file)
index 0000000..a42b6f6
--- /dev/null
@@ -0,0 +1,181 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Web.Routing;\r
+\r
+    public static class RouteCollectionExtensions {\r
+\r
+        // This method returns a new RouteCollection containing only routes that matched a particular area.\r
+        // The Boolean out parameter is just a flag specifying whether any registered routes were area-aware.\r
+        private static RouteCollection FilterRouteCollectionByArea(RouteCollection routes, string areaName, out bool usingAreas) {\r
+            if (areaName == null) {\r
+                areaName = String.Empty;\r
+            }\r
+\r
+            usingAreas = false;\r
+            RouteCollection filteredRoutes = new RouteCollection();\r
+\r
+            using (routes.GetReadLock()) {\r
+                foreach (RouteBase route in routes) {\r
+                    string thisAreaName = AreaHelpers.GetAreaName(route) ?? String.Empty;\r
+                    usingAreas |= (thisAreaName.Length > 0);\r
+                    if (String.Equals(thisAreaName, areaName, StringComparison.OrdinalIgnoreCase)) {\r
+                        filteredRoutes.Add(route);\r
+                    }\r
+                }\r
+            }\r
+\r
+            // if areas are not in use, the filtered route collection might be incorrect\r
+            return (usingAreas) ? filteredRoutes : routes;\r
+        }\r
+\r
+        public static VirtualPathData GetVirtualPathForArea(this RouteCollection routes, RequestContext requestContext, RouteValueDictionary values) {\r
+            return GetVirtualPathForArea(routes, requestContext, null /* name */, values);\r
+        }\r
+\r
+        public static VirtualPathData GetVirtualPathForArea(this RouteCollection routes, RequestContext requestContext, string name, RouteValueDictionary values) {\r
+            bool usingAreas; // don't care about this value\r
+            return GetVirtualPathForArea(routes, requestContext, name, values, out usingAreas);\r
+        }\r
+\r
+        internal static VirtualPathData GetVirtualPathForArea(this RouteCollection routes, RequestContext requestContext, string name, RouteValueDictionary values, out bool usingAreas) {\r
+            if (routes == null) {\r
+                throw new ArgumentNullException("routes");\r
+            }\r
+\r
+            if (!String.IsNullOrEmpty(name)) {\r
+                // the route name is a stronger qualifier than the area name, so just pipe it through\r
+                usingAreas = false;\r
+                return routes.GetVirtualPath(requestContext, name, values);\r
+            }\r
+\r
+            string targetArea = null;\r
+            if (values != null) {\r
+                object targetAreaRawValue;\r
+                if (values.TryGetValue("area", out targetAreaRawValue)) {\r
+                    targetArea = targetAreaRawValue as string;\r
+                }\r
+                else {\r
+                    // set target area to current area\r
+                    if (requestContext != null) {\r
+                        targetArea = AreaHelpers.GetAreaName(requestContext.RouteData);\r
+                    }\r
+                }\r
+            }\r
+\r
+            // need to apply a correction to the RVD if areas are in use\r
+            RouteValueDictionary correctedValues = values;\r
+            RouteCollection filteredRoutes = FilterRouteCollectionByArea(routes, targetArea, out usingAreas);\r
+            if (usingAreas) {\r
+                correctedValues = new RouteValueDictionary(values);\r
+                correctedValues.Remove("area");\r
+            }\r
+\r
+            VirtualPathData vpd = filteredRoutes.GetVirtualPath(requestContext, correctedValues);\r
+            return vpd;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#",\r
+            Justification = "This is not a regular URL as it may contain special routing characters.")]\r
+        public static void IgnoreRoute(this RouteCollection routes, string url) {\r
+            IgnoreRoute(routes, url, null /* constraints */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#",\r
+            Justification = "This is not a regular URL as it may contain special routing characters.")]\r
+        public static void IgnoreRoute(this RouteCollection routes, string url, object constraints) {\r
+            if (routes == null) {\r
+                throw new ArgumentNullException("routes");\r
+            }\r
+            if (url == null) {\r
+                throw new ArgumentNullException("url");\r
+            }\r
+\r
+            IgnoreRouteInternal route = new IgnoreRouteInternal(url) {\r
+                Constraints = new RouteValueDictionary(constraints)\r
+            };\r
+\r
+            routes.Add(route);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",\r
+            Justification = "This is not a regular URL as it may contain special routing characters.")]\r
+        public static Route MapRoute(this RouteCollection routes, string name, string url) {\r
+            return MapRoute(routes, name, url, null /* defaults */, (object)null /* constraints */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",\r
+            Justification = "This is not a regular URL as it may contain special routing characters.")]\r
+        public static Route MapRoute(this RouteCollection routes, string name, string url, object defaults) {\r
+            return MapRoute(routes, name, url, defaults, (object)null /* constraints */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",\r
+            Justification = "This is not a regular URL as it may contain special routing characters.")]\r
+        public static Route MapRoute(this RouteCollection routes, string name, string url, object defaults, object constraints) {\r
+            return MapRoute(routes, name, url, defaults, constraints, null /* namespaces */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",\r
+            Justification = "This is not a regular URL as it may contain special routing characters.")]\r
+        public static Route MapRoute(this RouteCollection routes, string name, string url, string[] namespaces) {\r
+            return MapRoute(routes, name, url, null /* defaults */, null /* constraints */, namespaces);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",\r
+            Justification = "This is not a regular URL as it may contain special routing characters.")]\r
+        public static Route MapRoute(this RouteCollection routes, string name, string url, object defaults, string[] namespaces) {\r
+            return MapRoute(routes, name, url, defaults, null /* constraints */, namespaces);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#",\r
+            Justification = "This is not a regular URL as it may contain special routing characters.")]\r
+        public static Route MapRoute(this RouteCollection routes, string name, string url, object defaults, object constraints, string[] namespaces) {\r
+            if (routes == null) {\r
+                throw new ArgumentNullException("routes");\r
+            }\r
+            if (url == null) {\r
+                throw new ArgumentNullException("url");\r
+            }\r
+\r
+            Route route = new Route(url, new MvcRouteHandler()) {\r
+                Defaults = new RouteValueDictionary(defaults),\r
+                Constraints = new RouteValueDictionary(constraints),\r
+                DataTokens = new RouteValueDictionary()\r
+            };\r
+\r
+            if ((namespaces != null) && (namespaces.Length > 0)) {\r
+                route.DataTokens["Namespaces"] = namespaces;\r
+            }\r
+\r
+            routes.Add(name, route);\r
+\r
+            return route;\r
+        }\r
+\r
+        private sealed class IgnoreRouteInternal : Route {\r
+            public IgnoreRouteInternal(string url)\r
+                : base(url, new StopRoutingHandler()) {\r
+            }\r
+\r
+            public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary routeValues) {\r
+                // Never match during route generation. This avoids the scenario where an IgnoreRoute with\r
+                // fairly relaxed constraints ends up eagerly matching all generated URLs.\r
+                return null;\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/RouteDataValueProvider.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/RouteDataValueProvider.cs
new file mode 100644 (file)
index 0000000..5ae1ee7
--- /dev/null
@@ -0,0 +1,26 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Globalization;\r
+\r
+    public sealed class RouteDataValueProvider : DictionaryValueProvider<object> {\r
+\r
+        // RouteData should use the invariant culture since it's part of the URL, and the URL should be\r
+        // interpreted in a uniform fashion regardless of the origin of a particular request.\r
+        public RouteDataValueProvider(ControllerContext controllerContext)\r
+            : base(controllerContext.RouteData.Values, CultureInfo.InvariantCulture) {\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/RouteDataValueProviderFactory.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/RouteDataValueProviderFactory.cs
new file mode 100644 (file)
index 0000000..4efadbf
--- /dev/null
@@ -0,0 +1,27 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    public sealed class RouteDataValueProviderFactory : ValueProviderFactory {\r
+\r
+        public override IValueProvider GetValueProvider(ControllerContext controllerContext) {\r
+            if (controllerContext == null) {\r
+                throw new ArgumentNullException("controllerContext");\r
+            }\r
+\r
+            return new RouteDataValueProvider(controllerContext);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/RouteValuesHelpers.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/RouteValuesHelpers.cs
new file mode 100644 (file)
index 0000000..d227cb4
--- /dev/null
@@ -0,0 +1,61 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Collections.Generic;\r
+    using System.Web.Routing;\r
+\r
+    internal static class RouteValuesHelpers {\r
+        public static RouteValueDictionary GetRouteValues(RouteValueDictionary routeValues) {\r
+            return (routeValues != null) ? new RouteValueDictionary(routeValues) : new RouteValueDictionary();\r
+        }\r
+\r
+        public static RouteValueDictionary MergeRouteValues(string actionName, string controllerName, RouteValueDictionary implicitRouteValues, RouteValueDictionary routeValues, bool includeImplicitMvcValues) {\r
+            // Create a new dictionary containing implicit and auto-generated values\r
+            RouteValueDictionary mergedRouteValues = new RouteValueDictionary();\r
+\r
+            if (includeImplicitMvcValues) {\r
+                // We only include MVC-specific values like 'controller' and 'action' if we are generating an action link.\r
+                // If we are generating a route link [as to MapRoute("Foo", "any/url", new { controller = ... })], including\r
+                // the current controller name will cause the route match to fail if the current controller is not the same\r
+                // as the destination controller.\r
+\r
+                object implicitValue;\r
+                if (implicitRouteValues != null && implicitRouteValues.TryGetValue("action", out implicitValue)) {\r
+                    mergedRouteValues["action"] = implicitValue;\r
+                }\r
+\r
+                if (implicitRouteValues != null && implicitRouteValues.TryGetValue("controller", out implicitValue)) {\r
+                    mergedRouteValues["controller"] = implicitValue;\r
+                }\r
+            }\r
+\r
+            // Merge values from the user's dictionary/object\r
+            if (routeValues != null) {\r
+                foreach (KeyValuePair<string, object> routeElement in GetRouteValues(routeValues)) {\r
+                    mergedRouteValues[routeElement.Key] = routeElement.Value;\r
+                }\r
+            }\r
+\r
+            // Merge explicit parameters when not null\r
+            if (actionName != null) {\r
+                mergedRouteValues["action"] = actionName;\r
+            }\r
+\r
+            if (controllerName != null) {\r
+                mergedRouteValues["controller"] = controllerName;\r
+            }\r
+\r
+            return mergedRouteValues;\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/SelectList.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/SelectList.cs
new file mode 100644 (file)
index 0000000..9c85624
--- /dev/null
@@ -0,0 +1,46 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Collections;\r
+    using System.Diagnostics.CodeAnalysis;    \r
+\r
+    [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]\r
+    public class SelectList : MultiSelectList {\r
+\r
+        public SelectList(IEnumerable items)\r
+            : this(items, null /* selectedValue */) {\r
+        }\r
+\r
+        public SelectList(IEnumerable items, object selectedValue)\r
+            : this(items, null /* dataValuefield */, null /* dataTextField */, selectedValue) {\r
+        }\r
+\r
+        public SelectList(IEnumerable items, string dataValueField, string dataTextField)\r
+            : this(items, dataValueField, dataTextField, null /* selectedValue */) {\r
+        }\r
+\r
+        public SelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue)\r
+            : base(items, dataValueField, dataTextField, ToEnumerable(selectedValue)) {\r
+            SelectedValue = selectedValue;\r
+        }\r
+\r
+        public object SelectedValue {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        private static IEnumerable ToEnumerable(object selectedValue) {\r
+            return (selectedValue != null) ? new object[] { selectedValue } : null;\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/SelectListItem.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/SelectListItem.cs
new file mode 100644 (file)
index 0000000..962bf36
--- /dev/null
@@ -0,0 +1,32 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+\r
+    public class SelectListItem {\r
+\r
+        public bool Selected {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public string Text {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public string Value {\r
+            get;\r
+            set;\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/SessionStateTempDataProvider.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/SessionStateTempDataProvider.cs
new file mode 100644 (file)
index 0000000..1da67bd
--- /dev/null
@@ -0,0 +1,65 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public class SessionStateTempDataProvider : ITempDataProvider {\r
+        internal const string TempDataSessionStateKey = "__ControllerTempData";\r
+\r
+        public virtual IDictionary<string, object> LoadTempData(ControllerContext controllerContext) {\r
+            HttpSessionStateBase session = controllerContext.HttpContext.Session;\r
+\r
+            if (session != null) {\r
+                Dictionary<string, object> tempDataDictionary = session[TempDataSessionStateKey] as Dictionary<string, object>;\r
+\r
+                if (tempDataDictionary != null) {\r
+                    // If we got it from Session, remove it so that no other request gets it\r
+                    session.Remove(TempDataSessionStateKey);\r
+                    return tempDataDictionary;\r
+                }\r
+            }\r
+\r
+            return new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\r
+        }\r
+\r
+        public virtual void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values) {\r
+            if (controllerContext == null) {\r
+                throw new ArgumentNullException("controllerContext");\r
+            }\r
+\r
+            HttpSessionStateBase session = controllerContext.HttpContext.Session;\r
+            bool isDirty = (values != null && values.Count > 0);\r
+\r
+            if (session == null) {\r
+                if (isDirty) {\r
+                    throw new InvalidOperationException(MvcResources.SessionStateTempDataProvider_SessionStateDisabled);\r
+                }\r
+            }\r
+            else {\r
+                if (isDirty) {\r
+                    session[TempDataSessionStateKey] = values;\r
+                }\r
+                else {\r
+                    // Since the default implementation of Remove() (from SessionStateItemCollection) dirties the\r
+                    // collection, we shouldn't call it unless we really do need to remove the existing key.\r
+                    if (session[TempDataSessionStateKey] != null) {\r
+                        session.Remove(TempDataSessionStateKey);\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/StringLengthAttributeAdapter.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/StringLengthAttributeAdapter.cs
new file mode 100644 (file)
index 0000000..6e96be4
--- /dev/null
@@ -0,0 +1,26 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Collections.Generic;\r
+    using System.ComponentModel.DataAnnotations;\r
+\r
+    public class StringLengthAttributeAdapter : DataAnnotationsModelValidator<StringLengthAttribute> {\r
+        public StringLengthAttributeAdapter(ModelMetadata metadata, ControllerContext context, StringLengthAttribute attribute)\r
+            : base(metadata, context, attribute) {\r
+        }\r
+\r
+        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() {\r
+            return new[] { new ModelClientValidationStringLengthRule(ErrorMessage, 0, Attribute.MaximumLength) };\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/TagBuilder.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/TagBuilder.cs
new file mode 100644 (file)
index 0000000..d093204
--- /dev/null
@@ -0,0 +1,214 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Globalization;\r
+    using System.Text;\r
+    using System.Web;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public class TagBuilder {\r
+        private string _idAttributeDotReplacement;\r
+\r
+        private const string _attributeFormat = @" {0}=""{1}""";\r
+        private const string _elementFormatEndTag = "</{0}>";\r
+        private const string _elementFormatNormal = "<{0}{1}>{2}</{0}>";\r
+        private const string _elementFormatSelfClosing = "<{0}{1} />";\r
+        private const string _elementFormatStartTag = "<{0}{1}>";\r
+\r
+        private string _innerHtml;\r
+\r
+        public TagBuilder(string tagName) {\r
+            if (String.IsNullOrEmpty(tagName)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "tagName");\r
+            }\r
+\r
+            TagName = tagName;\r
+            Attributes = new SortedDictionary<string, string>(StringComparer.Ordinal);\r
+        }\r
+\r
+        public IDictionary<string, string> Attributes {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public string IdAttributeDotReplacement {\r
+            get {\r
+                if (String.IsNullOrEmpty(_idAttributeDotReplacement)) {\r
+                    _idAttributeDotReplacement = HtmlHelper.IdAttributeDotReplacement;\r
+                }\r
+                return _idAttributeDotReplacement;\r
+            }\r
+            set {\r
+                _idAttributeDotReplacement = value;\r
+            }\r
+        }\r
+\r
+        public string InnerHtml {\r
+            get {\r
+                return _innerHtml ?? String.Empty;\r
+            }\r
+            set {\r
+                _innerHtml = value;\r
+            }\r
+        }\r
+\r
+        public string TagName {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public void AddCssClass(string value) {\r
+            string currentValue;\r
+\r
+            if (Attributes.TryGetValue("class", out currentValue)) {\r
+                Attributes["class"] = value + " " + currentValue;\r
+            }\r
+            else {\r
+                Attributes["class"] = value;\r
+            }\r
+        }\r
+\r
+        internal static string CreateSanitizedId(string originalId, string dotReplacement) {\r
+            if (String.IsNullOrEmpty(originalId)) {\r
+                return null;\r
+            }\r
+\r
+            char firstChar = originalId[0];\r
+            if (!Html401IdUtil.IsLetter(firstChar)) {\r
+                // the first character must be a letter\r
+                return null;\r
+            }\r
+\r
+            StringBuilder sb = new StringBuilder(originalId.Length);\r
+            sb.Append(firstChar);\r
+\r
+            for (int i = 1; i < originalId.Length; i++) {\r
+                char thisChar = originalId[i];\r
+                if (Html401IdUtil.IsValidIdCharacter(thisChar)) {\r
+                    sb.Append(thisChar);\r
+                }\r
+                else {\r
+                    sb.Append(dotReplacement);\r
+                }\r
+            }\r
+\r
+            return sb.ToString();\r
+        }\r
+\r
+        public void GenerateId(string name) {\r
+            if (!Attributes.ContainsKey("id")) {\r
+                string sanitizedId = CreateSanitizedId(name, IdAttributeDotReplacement);\r
+                if (!String.IsNullOrEmpty(sanitizedId)) {\r
+                    Attributes["id"] = sanitizedId;\r
+                }\r
+            }\r
+        }\r
+\r
+        private string GetAttributesString() {\r
+            StringBuilder sb = new StringBuilder();\r
+            foreach (var attribute in Attributes) {\r
+                string key = attribute.Key;\r
+                if (String.Equals(key, "id", StringComparison.Ordinal /* case-sensitive */) && String.IsNullOrEmpty(attribute.Value)) {\r
+                    continue; // DevDiv Bugs #227595: don't output empty IDs\r
+                }\r
+                string value = HttpUtility.HtmlAttributeEncode(attribute.Value);\r
+                sb.AppendFormat(CultureInfo.InvariantCulture, _attributeFormat, key, value);\r
+            }\r
+            return sb.ToString();\r
+        }\r
+\r
+        public void MergeAttribute(string key, string value) {\r
+            MergeAttribute(key, value, false /* replaceExisting */);\r
+        }\r
+\r
+        public void MergeAttribute(string key, string value, bool replaceExisting) {\r
+            if (String.IsNullOrEmpty(key)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "key");\r
+            }\r
+\r
+            if (replaceExisting || !Attributes.ContainsKey(key)) {\r
+                Attributes[key] = value;\r
+            }\r
+        }\r
+\r
+        public void MergeAttributes<TKey, TValue>(IDictionary<TKey, TValue> attributes) {\r
+            MergeAttributes(attributes, false /* replaceExisting */);\r
+        }\r
+\r
+        public void MergeAttributes<TKey, TValue>(IDictionary<TKey, TValue> attributes, bool replaceExisting) {\r
+            if (attributes != null) {\r
+                foreach (var entry in attributes) {\r
+                    string key = Convert.ToString(entry.Key, CultureInfo.InvariantCulture);\r
+                    string value = Convert.ToString(entry.Value, CultureInfo.InvariantCulture);\r
+                    MergeAttribute(key, value, replaceExisting);\r
+                }\r
+            }\r
+        }\r
+\r
+        public void SetInnerText(string innerText) {\r
+            InnerHtml = HttpUtility.HtmlEncode(innerText);\r
+        }\r
+\r
+        internal MvcHtmlString ToMvcHtmlString(TagRenderMode renderMode) {\r
+            return MvcHtmlString.Create(ToString(renderMode));\r
+        }\r
+\r
+        public override string ToString() {\r
+            return ToString(TagRenderMode.Normal);\r
+        }\r
+\r
+        public string ToString(TagRenderMode renderMode) {\r
+            switch (renderMode) {\r
+                case TagRenderMode.StartTag:\r
+                    return String.Format(CultureInfo.InvariantCulture, _elementFormatStartTag, TagName, GetAttributesString());\r
+                case TagRenderMode.EndTag:\r
+                    return String.Format(CultureInfo.InvariantCulture, _elementFormatEndTag, TagName);\r
+                case TagRenderMode.SelfClosing:\r
+                    return String.Format(CultureInfo.InvariantCulture, _elementFormatSelfClosing, TagName, GetAttributesString());\r
+                default:\r
+                    return String.Format(CultureInfo.InvariantCulture, _elementFormatNormal, TagName, GetAttributesString(), InnerHtml);\r
+            }\r
+        }\r
+\r
+        // Valid IDs are defined in http://www.w3.org/TR/html401/types.html#type-id\r
+        private static class Html401IdUtil {\r
+            private static bool IsAllowableSpecialCharacter(char c) {\r
+                switch (c) {\r
+                    case '-':\r
+                    case '_':\r
+                    case ':':\r
+                        // note that we're specifically excluding the '.' character\r
+                        return true;\r
+\r
+                    default:\r
+                        return false;\r
+                }\r
+            }\r
+\r
+            private static bool IsDigit(char c) {\r
+                return ('0' <= c && c <= '9');\r
+            }\r
+\r
+            public static bool IsLetter(char c) {\r
+                return (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'));\r
+            }\r
+\r
+            public static bool IsValidIdCharacter(char c) {\r
+                return (IsLetter(c) || IsDigit(c) || IsAllowableSpecialCharacter(c));\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/TagRenderMode.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/TagRenderMode.cs
new file mode 100644 (file)
index 0000000..8f889e7
--- /dev/null
@@ -0,0 +1,20 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    public enum TagRenderMode {\r
+        Normal,\r
+        StartTag,\r
+        EndTag,\r
+        SelfClosing\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/TempDataDictionary.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/TempDataDictionary.cs
new file mode 100644 (file)
index 0000000..b2aa489
--- /dev/null
@@ -0,0 +1,219 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections;\r
+    using System.Collections.Generic;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Linq;\r
+    using System.Runtime.Serialization;\r
+\r
+    [Serializable]\r
+    public class TempDataDictionary : IDictionary<string, object>, ISerializable {\r
+        internal const string _tempDataSerializationKey = "__tempData";\r
+\r
+        private Dictionary<string, object> _data;\r
+        private HashSet<string> _initialKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\r
+        private HashSet<string> _retainedKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\r
+\r
+        public TempDataDictionary() {\r
+            _data = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\r
+        }\r
+\r
+        protected TempDataDictionary(SerializationInfo info, StreamingContext context) {\r
+            _data = info.GetValue(_tempDataSerializationKey, typeof(Dictionary<string, object>)) as Dictionary<string, object>;\r
+        }\r
+\r
+        public int Count {\r
+            get {\r
+                return _data.Count;\r
+            }\r
+        }\r
+\r
+        public ICollection<string> Keys {\r
+            get {\r
+                return _data.Keys;\r
+            }\r
+        }\r
+\r
+        public void Keep() {\r
+            _retainedKeys.Clear();\r
+            _retainedKeys.UnionWith(_data.Keys);\r
+        }\r
+\r
+        public void Keep(string key) {\r
+            _retainedKeys.Add(key);\r
+        }\r
+\r
+        public void Load(ControllerContext controllerContext, ITempDataProvider tempDataProvider) {\r
+            IDictionary<string, object> providerDictionary = tempDataProvider.LoadTempData(controllerContext);\r
+            _data = (providerDictionary != null) ? new Dictionary<string, object>(providerDictionary, StringComparer.OrdinalIgnoreCase) :\r
+                new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\r
+            _initialKeys = new HashSet<string>(_data.Keys, StringComparer.OrdinalIgnoreCase);\r
+            _retainedKeys.Clear();\r
+        }\r
+\r
+        public object Peek(string key) {\r
+            object value;\r
+            _data.TryGetValue(key, out value);\r
+            return value;\r
+        }\r
+\r
+        public void Save(ControllerContext controllerContext, ITempDataProvider tempDataProvider) {\r
+            string[] keysToKeep = _initialKeys.Union(_retainedKeys, StringComparer.OrdinalIgnoreCase).ToArray();\r
+            string[] keysToRemove = _data.Keys.Except(keysToKeep, StringComparer.OrdinalIgnoreCase).ToArray();\r
+            foreach (string key in keysToRemove) {\r
+                _data.Remove(key);\r
+            }\r
+            tempDataProvider.SaveTempData(controllerContext, _data);\r
+        }\r
+\r
+        public ICollection<object> Values {\r
+            get {\r
+                return _data.Values;\r
+            }\r
+        }\r
+\r
+        public object this[string key] {\r
+            get {\r
+                object value;\r
+                if (TryGetValue(key, out value)) {\r
+                    _initialKeys.Remove(key);\r
+                    return value;\r
+                }\r
+                return null;\r
+            }\r
+            set {\r
+                _data[key] = value;\r
+                _initialKeys.Add(key);\r
+            }\r
+        }\r
+\r
+        public void Add(string key, object value) {\r
+            _data.Add(key, value);\r
+            _initialKeys.Add(key);\r
+        }\r
+\r
+        public void Clear() {\r
+            _data.Clear();\r
+            _retainedKeys.Clear();\r
+            _initialKeys.Clear();\r
+        }\r
+\r
+        public bool ContainsKey(string key) {\r
+            return _data.ContainsKey(key);\r
+        }\r
+\r
+        public bool ContainsValue(object value) {\r
+            return _data.ContainsValue(value);\r
+        }\r
+\r
+        public IEnumerator<KeyValuePair<string, object>> GetEnumerator() {\r
+            return new TempDataDictionaryEnumerator(this);\r
+        }\r
+\r
+        protected virtual void GetObjectData(SerializationInfo info, StreamingContext context) {\r
+            info.AddValue(_tempDataSerializationKey, _data);\r
+        }\r
+\r
+        public bool Remove(string key) {\r
+            _retainedKeys.Remove(key);\r
+            _initialKeys.Remove(key);\r
+            return _data.Remove(key);\r
+        }\r
+\r
+        public bool TryGetValue(string key, out object value) {\r
+            _initialKeys.Remove(key);\r
+            return _data.TryGetValue(key, out value);\r
+        }\r
+\r
+        #region ICollection<KeyValuePair<string, object>> Implementation\r
+        bool ICollection<KeyValuePair<string, object>>.IsReadOnly {\r
+            get {\r
+                return ((ICollection<KeyValuePair<string, object>>)_data).IsReadOnly;\r
+            }\r
+        }\r
+\r
+        void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int index) {\r
+            ((ICollection<KeyValuePair<string, object>>)_data).CopyTo(array, index);\r
+        }\r
+\r
+        void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> keyValuePair) {\r
+            _initialKeys.Add(keyValuePair.Key);\r
+            ((ICollection<KeyValuePair<string, object>>)_data).Add(keyValuePair);\r
+        }\r
+\r
+        bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> keyValuePair) {\r
+            return ((ICollection<KeyValuePair<string, object>>)_data).Contains(keyValuePair);\r
+        }\r
+\r
+        bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> keyValuePair) {\r
+            _initialKeys.Remove(keyValuePair.Key);\r
+            return ((ICollection<KeyValuePair<string, object>>)_data).Remove(keyValuePair);\r
+        }\r
+        #endregion\r
+\r
+        #region IEnumerable Implementation\r
+        IEnumerator IEnumerable.GetEnumerator() {\r
+            return (IEnumerator)(new TempDataDictionaryEnumerator(this));\r
+        }\r
+        #endregion\r
+\r
+        #region ISerializable Members\r
+        [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]\r
+        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {\r
+            GetObjectData(info, context);\r
+        }\r
+        #endregion\r
+\r
+        private sealed class TempDataDictionaryEnumerator : IEnumerator<KeyValuePair<string, object>> {\r
+            private IEnumerator<KeyValuePair<string, object>> _enumerator;\r
+            private TempDataDictionary _tempData;\r
+\r
+            public TempDataDictionaryEnumerator(TempDataDictionary tempData) {\r
+                _tempData = tempData;\r
+                _enumerator = _tempData._data.GetEnumerator();\r
+            }\r
+\r
+            public KeyValuePair<string, object> Current {\r
+                get {\r
+                    KeyValuePair<string, object> kvp = _enumerator.Current;\r
+                    _tempData._initialKeys.Remove(kvp.Key);\r
+                    return kvp;\r
+                }\r
+            }\r
+\r
+            public bool MoveNext() {\r
+                return _enumerator.MoveNext();\r
+            }\r
+\r
+            public void Reset() {\r
+                _enumerator.Reset();\r
+            }\r
+\r
+            #region IEnumerator Implementation\r
+            object IEnumerator.Current {\r
+                get {\r
+                    return Current;\r
+                }\r
+            }\r
+            #endregion\r
+\r
+            #region IDisposable Implementation\r
+            void IDisposable.Dispose() {\r
+                _enumerator.Dispose();\r
+            }\r
+            #endregion\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/TemplateInfo.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/TemplateInfo.cs
new file mode 100644 (file)
index 0000000..5ca8280
--- /dev/null
@@ -0,0 +1,71 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Collections.Generic;\r
+\r
+    public class TemplateInfo {\r
+        private string _htmlFieldPrefix;\r
+        private object _formattedModelValue;\r
+        private HashSet<object> _visitedObjects;\r
+\r
+        public object FormattedModelValue {\r
+            get {\r
+                return _formattedModelValue ?? String.Empty;\r
+            }\r
+            set {\r
+                _formattedModelValue = value;\r
+            }\r
+        }\r
+\r
+        public string HtmlFieldPrefix {\r
+            get {\r
+                return _htmlFieldPrefix ?? String.Empty;\r
+            }\r
+            set {\r
+                _htmlFieldPrefix = value;\r
+            }\r
+        }\r
+\r
+        public int TemplateDepth {\r
+            get {\r
+                return VisitedObjects.Count;\r
+            }\r
+        }\r
+\r
+        // DDB #224750 - Keep a collection of visited objects to prevent infinite recursion\r
+        internal HashSet<object> VisitedObjects {\r
+            get {\r
+                if (_visitedObjects == null) {\r
+                    _visitedObjects = new HashSet<object>();\r
+                }\r
+                return _visitedObjects;\r
+            }\r
+            set {\r
+                _visitedObjects = value;\r
+            }\r
+        }\r
+\r
+        public string GetFullHtmlFieldId(string partialFieldName) {\r
+            return HtmlHelper.GenerateIdFromName(GetFullHtmlFieldName(partialFieldName));\r
+        }\r
+\r
+        public string GetFullHtmlFieldName(string partialFieldName) {\r
+            // This uses "combine and trim" because either or both of these values might be empty\r
+            return (HtmlFieldPrefix + "." + (partialFieldName ?? String.Empty)).Trim('.');\r
+        }\r
+\r
+        public bool Visited(ModelMetadata metadata) {\r
+            return VisitedObjects.Contains(metadata.Model ?? metadata.ModelType);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/TryGetValueDelegate.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/TryGetValueDelegate.cs
new file mode 100644 (file)
index 0000000..66a1966
--- /dev/null
@@ -0,0 +1,17 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    internal delegate bool TryGetValueDelegate(object dictionary, string key, out object value);\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/TypeCacheSerializer.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/TypeCacheSerializer.cs
new file mode 100644 (file)
index 0000000..bec4f0b
--- /dev/null
@@ -0,0 +1,128 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.IO;\r
+    using System.Linq;\r
+    using System.Reflection;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Xml;\r
+\r
+    // Processes files with this format:\r
+    //\r
+    // <typeCache lastModified=... mvcVersionId=...>\r
+    //   <assembly name=...>\r
+    //     <module versionId=...>\r
+    //       <type>...</type>\r
+    //     </module>\r
+    //   </assembly>\r
+    // </typeCache>\r
+    //\r
+    // This is used to store caches of files between AppDomain resets, leading to improved cold boot time\r
+    // and more efficient use of memory.\r
+\r
+    internal sealed class TypeCacheSerializer {\r
+\r
+        private static readonly Guid _mvcVersionId = typeof(TypeCacheSerializer).Module.ModuleVersionId;\r
+\r
+        // used for unit testing\r
+\r
+        private DateTime CurrentDate {\r
+            get {\r
+                return CurrentDateOverride ?? DateTime.Now;\r
+            }\r
+        }\r
+\r
+        internal DateTime? CurrentDateOverride {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic",\r
+            Justification = "This is an instance method for consistency with the SerializeTypes() method.")]\r
+        public List<Type> DeserializeTypes(TextReader input) {\r
+            XmlDocument doc = new XmlDocument();\r
+            doc.Load(input);\r
+            XmlElement rootElement = doc.DocumentElement;\r
+\r
+            Guid readMvcVersionId = new Guid(rootElement.Attributes["mvcVersionId"].Value);\r
+            if (readMvcVersionId != _mvcVersionId) {\r
+                // The cache is outdated because the cache file was produced by a different version\r
+                // of MVC.\r
+                return null;\r
+            }\r
+\r
+            List<Type> deserializedTypes = new List<Type>();\r
+            foreach (XmlNode assemblyNode in rootElement.ChildNodes) {\r
+                string assemblyName = assemblyNode.Attributes["name"].Value;\r
+                Assembly assembly = Assembly.Load(assemblyName);\r
+\r
+                foreach (XmlNode moduleNode in assemblyNode.ChildNodes) {\r
+                    Guid moduleVersionId = new Guid(moduleNode.Attributes["versionId"].Value);\r
+\r
+                    foreach (XmlNode typeNode in moduleNode.ChildNodes) {\r
+                        string typeName = typeNode.InnerText;\r
+                        Type type = assembly.GetType(typeName);\r
+                        if (type == null || type.Module.ModuleVersionId != moduleVersionId) {\r
+                            // The cache is outdated because we couldn't find a previously recorded\r
+                            // type or the type's containing module was modified.\r
+                            return null;\r
+                        }\r
+                        else {\r
+                            deserializedTypes.Add(type);\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+\r
+            return deserializedTypes;\r
+        }\r
+\r
+        public void SerializeTypes(IEnumerable<Type> types, TextWriter output) {\r
+            var groupedByAssembly = from type in types\r
+                                    group type by type.Module into groupedByModule\r
+                                    group groupedByModule by groupedByModule.Key.Assembly;\r
+\r
+            XmlDocument doc = new XmlDocument();\r
+            doc.AppendChild(doc.CreateComment(MvcResources.TypeCache_DoNotModify));\r
+\r
+            XmlElement typeCacheElement = doc.CreateElement("typeCache");\r
+            doc.AppendChild(typeCacheElement);\r
+            typeCacheElement.SetAttribute("lastModified", CurrentDate.ToString());\r
+            typeCacheElement.SetAttribute("mvcVersionId", _mvcVersionId.ToString());\r
+\r
+            foreach (var assemblyGroup in groupedByAssembly) {\r
+                XmlElement assemblyElement = doc.CreateElement("assembly");\r
+                typeCacheElement.AppendChild(assemblyElement);\r
+                assemblyElement.SetAttribute("name", assemblyGroup.Key.FullName);\r
+\r
+                foreach (var moduleGroup in assemblyGroup) {\r
+                    XmlElement moduleElement = doc.CreateElement("module");\r
+                    assemblyElement.AppendChild(moduleElement);\r
+                    moduleElement.SetAttribute("versionId", moduleGroup.Key.ModuleVersionId.ToString());\r
+\r
+                    foreach (Type type in moduleGroup) {\r
+                        XmlElement typeElement = doc.CreateElement("type");\r
+                        moduleElement.AppendChild(typeElement);\r
+                        typeElement.AppendChild(doc.CreateTextNode(type.FullName));\r
+                    }\r
+                }\r
+            }\r
+\r
+            doc.Save(output);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/TypeCacheUtil.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/TypeCacheUtil.cs
new file mode 100644 (file)
index 0000000..b3366d1
--- /dev/null
@@ -0,0 +1,103 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections;\r
+    using System.Collections.Generic;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.IO;\r
+    using System.Linq;\r
+    using System.Reflection;\r
+\r
+    internal static class TypeCacheUtil {\r
+\r
+        private static IEnumerable<Type> FilterTypesInAssemblies(IBuildManager buildManager, Predicate<Type> predicate) {\r
+            // Go through all assemblies referenced by the application and search for types matching a predicate\r
+            IEnumerable<Type> typesSoFar = Type.EmptyTypes;\r
+\r
+            ICollection assemblies = buildManager.GetReferencedAssemblies();\r
+            foreach (Assembly assembly in assemblies) {\r
+                Type[] typesInAsm;\r
+                try {\r
+                    typesInAsm = assembly.GetTypes();\r
+                }\r
+                catch (ReflectionTypeLoadException ex) {\r
+                    typesInAsm = ex.Types;\r
+                }\r
+                typesSoFar = typesSoFar.Concat(typesInAsm);\r
+            }\r
+            return typesSoFar.Where(type => TypeIsPublicClass(type) && predicate(type));\r
+        }\r
+\r
+        public static List<Type> GetFilteredTypesFromAssemblies(string cacheName, Predicate<Type> predicate, IBuildManager buildManager) {\r
+            TypeCacheSerializer serializer = new TypeCacheSerializer();\r
+\r
+            // first, try reading from the cache on disk\r
+            List<Type> matchingTypes = ReadTypesFromCache(cacheName, predicate, buildManager, serializer);\r
+            if (matchingTypes != null) {\r
+                return matchingTypes;\r
+            }\r
+\r
+            // if reading from the cache failed, enumerate over every assembly looking for a matching type\r
+            matchingTypes = FilterTypesInAssemblies(buildManager, predicate).ToList();\r
+\r
+            // finally, save the cache back to disk\r
+            SaveTypesToCache(cacheName, matchingTypes, buildManager, serializer);\r
+\r
+            return matchingTypes;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",\r
+            Justification = "Cache failures are not fatal, and the code should continue executing normally.")]\r
+        internal static List<Type> ReadTypesFromCache(string cacheName, Predicate<Type> predicate, IBuildManager buildManager, TypeCacheSerializer serializer) {\r
+            try {\r
+                using (Stream stream = buildManager.ReadCachedFile(cacheName)) {\r
+                    if (stream != null) {\r
+                        using (StreamReader reader = new StreamReader(stream)) {\r
+                            List<Type> deserializedTypes = serializer.DeserializeTypes(reader);\r
+                            if (deserializedTypes != null && deserializedTypes.All(type => TypeIsPublicClass(type) && predicate(type))) {\r
+                                // If all read types still match the predicate, success!\r
+                                return deserializedTypes;\r
+                            }\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+            catch {\r
+            }\r
+\r
+            return null;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",\r
+            Justification = "Cache failures are not fatal, and the code should continue executing normally.")]\r
+        internal static void SaveTypesToCache(string cacheName, IList<Type> matchingTypes, IBuildManager buildManager, TypeCacheSerializer serializer) {\r
+            try {\r
+                using (Stream stream = buildManager.CreateCachedFile(cacheName)) {\r
+                    if (stream != null) {\r
+                        using (StreamWriter writer = new StreamWriter(stream)) {\r
+                            serializer.SerializeTypes(matchingTypes, writer);\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+            catch {\r
+            }\r
+        }\r
+\r
+        private static bool TypeIsPublicClass(Type type) {\r
+            return (type != null && type.IsPublic && type.IsClass && !type.IsAbstract);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/TypeDescriptorHelper.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/TypeDescriptorHelper.cs
new file mode 100644 (file)
index 0000000..48ccb8e
--- /dev/null
@@ -0,0 +1,282 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.ComponentModel;\r
+    using System.ComponentModel.DataAnnotations;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+    using System.Reflection;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    // TODO: Remove this class in MVC 3\r
+    //\r
+    // We brought in a private copy of the AssociatedMetadataTypeTypeDescriptionProvider\r
+    // from .NET 4, because it provides several bug fixes and perf improvements. If we're\r
+    // running on .NET < 4, we'll use our private copy.\r
+\r
+    internal static class TypeDescriptorHelper {\r
+\r
+        private static Func<Type, ICustomTypeDescriptor> _typeDescriptorFactory = GetTypeDescriptorFactory();\r
+\r
+        private static Func<Type, ICustomTypeDescriptor> GetTypeDescriptorFactory() {\r
+            if (Environment.Version.Major < 4) {\r
+                return type => new _AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type);\r
+            }\r
+\r
+            return type => new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type);\r
+        }\r
+\r
+        public static ICustomTypeDescriptor Get(Type type) {\r
+            return _typeDescriptorFactory(type);\r
+        }\r
+\r
+        // Private copies of the .NET 4 AssociatedMetadataType classes\r
+\r
+        private class _AssociatedMetadataTypeTypeDescriptionProvider : TypeDescriptionProvider {\r
+            public _AssociatedMetadataTypeTypeDescriptionProvider(Type type)\r
+                : base(TypeDescriptor.GetProvider(type)) {\r
+            }\r
+\r
+            public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance) {\r
+                ICustomTypeDescriptor baseDescriptor = base.GetTypeDescriptor(objectType, instance);\r
+                return new _AssociatedMetadataTypeTypeDescriptor(baseDescriptor, objectType);\r
+            }\r
+        }\r
+\r
+        private class _AssociatedMetadataTypeTypeDescriptor : CustomTypeDescriptor {\r
+            private Type AssociatedMetadataType {\r
+                get;\r
+                set;\r
+            }\r
+\r
+            public _AssociatedMetadataTypeTypeDescriptor(ICustomTypeDescriptor parent, Type type)\r
+                : base(parent) {\r
+                AssociatedMetadataType = TypeDescriptorCache.GetAssociatedMetadataType(type);\r
+                if (AssociatedMetadataType != null) {\r
+                    TypeDescriptorCache.ValidateMetadataType(type, AssociatedMetadataType);\r
+                }\r
+            }\r
+\r
+            public override PropertyDescriptorCollection GetProperties(Attribute[] attributes) {\r
+                return GetPropertiesWithMetadata(base.GetProperties(attributes));\r
+            }\r
+\r
+            public override PropertyDescriptorCollection GetProperties() {\r
+                return GetPropertiesWithMetadata(base.GetProperties());\r
+            }\r
+\r
+            private PropertyDescriptorCollection GetPropertiesWithMetadata(PropertyDescriptorCollection originalCollection) {\r
+                if (AssociatedMetadataType == null) {\r
+                    return originalCollection;\r
+                }\r
+\r
+                bool customDescriptorsCreated = false;\r
+                List<PropertyDescriptor> tempPropertyDescriptors = new List<PropertyDescriptor>();\r
+                foreach (PropertyDescriptor propDescriptor in originalCollection) {\r
+                    Attribute[] newMetadata = TypeDescriptorCache.GetAssociatedMetadata(AssociatedMetadataType, propDescriptor.Name);\r
+                    PropertyDescriptor descriptor = propDescriptor;\r
+                    if (newMetadata.Length > 0) {\r
+                        // Create a metadata descriptor that wraps the property descriptor\r
+                        descriptor = new _MetadataPropertyDescriptorWrapper(propDescriptor, newMetadata);\r
+                        customDescriptorsCreated = true;\r
+                    }\r
+\r
+                    tempPropertyDescriptors.Add(descriptor);\r
+                }\r
+\r
+                if (customDescriptorsCreated) {\r
+                    return new PropertyDescriptorCollection(tempPropertyDescriptors.ToArray(), true);\r
+                }\r
+                return originalCollection;\r
+            }\r
+\r
+            public override AttributeCollection GetAttributes() {\r
+                // Since normal TD behavior is to return cached attribute instances on subsequent\r
+                // calls to GetAttributes, we must be sure below to use the TD APIs to get both\r
+                // the base and associated attributes\r
+                AttributeCollection attributes = base.GetAttributes();\r
+                if (AssociatedMetadataType != null) {\r
+                    // Note that the use of TypeDescriptor.GetAttributes here opens up the possibility of\r
+                    // infinite recursion, in the corner case of two Types referencing each other as\r
+                    // metadata types (or a longer cycle)\r
+                    Attribute[] newAttributes = TypeDescriptor.GetAttributes(AssociatedMetadataType).OfType<Attribute>().ToArray();\r
+                    attributes = AttributeCollection.FromExisting(attributes, newAttributes);\r
+                }\r
+                return attributes;\r
+            }\r
+\r
+            private static class TypeDescriptorCache {\r
+                private static readonly Attribute[] emptyAttributes = new Attribute[0];\r
+\r
+                // Stores the associated metadata type for a type\r
+                private static readonly Dictionary<Type, Type> _metadataTypeCache = new Dictionary<Type, Type>();\r
+\r
+                // For a type and a property name stores the attributes for that property name.\r
+                private static readonly Dictionary<Tuple<Type, string>, Attribute[]> _typeMemberCache = new Dictionary<Tuple<Type, string>, Attribute[]>();\r
+\r
+                // Stores whether or not a type and associated metadata type has been checked for validity\r
+                private static readonly Dictionary<Tuple<Type, Type>, bool> _validatedMetadataTypeCache = new Dictionary<Tuple<Type, Type>, bool>();\r
+\r
+                public static void ValidateMetadataType(Type type, Type associatedType) {\r
+                    Tuple<Type, Type> typeTuple = new Tuple<Type, Type>(type, associatedType);\r
+\r
+                    lock (_validatedMetadataTypeCache) {\r
+                        if (!_validatedMetadataTypeCache.ContainsKey(typeTuple)) {\r
+                            CheckAssociatedMetadataType(type, associatedType);\r
+                            _validatedMetadataTypeCache.Add(typeTuple, true);\r
+                        }\r
+                    }\r
+                }\r
+\r
+                public static Type GetAssociatedMetadataType(Type type) {\r
+                    Type associatedMetadataType = null;\r
+                    lock (_metadataTypeCache) {\r
+                        if (_metadataTypeCache.TryGetValue(type, out associatedMetadataType)) {\r
+                            return associatedMetadataType;\r
+                        }\r
+                    }\r
+\r
+                    // Try association attribute\r
+                    MetadataTypeAttribute attribute = (MetadataTypeAttribute)Attribute.GetCustomAttribute(type, typeof(MetadataTypeAttribute));\r
+                    if (attribute != null) {\r
+                        associatedMetadataType = attribute.MetadataClassType;\r
+                    }\r
+\r
+                    lock (_metadataTypeCache) {\r
+                        _metadataTypeCache[type] = associatedMetadataType; \r
+                    }\r
+\r
+                    return associatedMetadataType;\r
+                }\r
+\r
+                private static void CheckAssociatedMetadataType(Type mainType, Type associatedMetadataType) {\r
+                    // Only properties from main type\r
+                    HashSet<string> mainTypeMemberNames = new HashSet<string>(mainType.GetProperties().Select(p => p.Name));\r
+\r
+                    // Properties and fields from buddy type\r
+                    var buddyFields = associatedMetadataType.GetFields().Select(f => f.Name);\r
+                    var buddyProperties = associatedMetadataType.GetProperties().Select(p => p.Name);\r
+                    HashSet<string> buddyTypeMembers = new HashSet<string>(buddyFields.Concat(buddyProperties), StringComparer.Ordinal);\r
+\r
+                    // Buddy members should be a subset of the main type's members\r
+                    if (!buddyTypeMembers.IsSubsetOf(mainTypeMemberNames)) {\r
+                        // Reduce the buddy members to the set not contained in the main members\r
+                        buddyTypeMembers.ExceptWith(mainTypeMemberNames);\r
+\r
+                        throw new InvalidOperationException(String.Format(\r
+                            CultureInfo.CurrentCulture,\r
+                            MvcResources.PrivateAssociatedMetadataTypeTypeDescriptor_MetadataTypeContainsUnknownProperties,\r
+                            mainType.FullName,\r
+                            String.Join(", ", buddyTypeMembers.ToArray())));\r
+                    }\r
+                }\r
+\r
+                public static Attribute[] GetAssociatedMetadata(Type type, string memberName) {\r
+                    var memberTuple = new Tuple<Type, string>(type, memberName);\r
+                    Attribute[] attributes;\r
+                    lock (_typeMemberCache) {\r
+                        if (_typeMemberCache.TryGetValue(memberTuple, out attributes)) {\r
+                            return attributes;\r
+                        }\r
+                    }\r
+\r
+                    // Allow fields and properties\r
+                    MemberTypes allowedMemberTypes = MemberTypes.Property | MemberTypes.Field;\r
+                    // Only public static/instance members\r
+                    BindingFlags searchFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;\r
+                    // Try to find a matching member on type\r
+                    MemberInfo matchingMember = type.GetMember(memberName, allowedMemberTypes, searchFlags).FirstOrDefault();\r
+                    if (matchingMember != null) {\r
+                        attributes = Attribute.GetCustomAttributes(matchingMember, true /* inherit */);\r
+                    }\r
+                    else {\r
+                        attributes = emptyAttributes;\r
+                    }\r
+\r
+                    lock (_typeMemberCache) {\r
+                        _typeMemberCache[memberTuple] = attributes;\r
+                    }\r
+                    return attributes;\r
+                }\r
+\r
+                private class Tuple<T1, T2> {\r
+                    public T1 Item1 { get; set; }\r
+                    public T2 Item2 { get; set; }\r
+\r
+                    public Tuple(T1 item1, T2 item2) {\r
+                        Item1 = item1;\r
+                        Item2 = item2;\r
+                    }\r
+\r
+                    public override int GetHashCode() {\r
+                        int h1 = Item1.GetHashCode();\r
+                        int h2 = Item2.GetHashCode();\r
+                        return ((h1 << 5) + h1) ^ h2;\r
+                    }\r
+\r
+                    public override bool Equals(object obj) {\r
+                        var other = obj as Tuple<T1, T2>;\r
+                        if (other != null) {\r
+                            return other.Item1.Equals(Item1) && other.Item2.Equals(Item2);\r
+                        }\r
+                        return false;\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+        private class _MetadataPropertyDescriptorWrapper : PropertyDescriptor {\r
+            private PropertyDescriptor _descriptor;\r
+            private bool _isReadOnly;\r
+\r
+            public _MetadataPropertyDescriptorWrapper(PropertyDescriptor descriptor, Attribute[] newAttributes)\r
+                : base(descriptor, newAttributes) {\r
+                _descriptor = descriptor;\r
+                var readOnlyAttribute = newAttributes.OfType<ReadOnlyAttribute>().FirstOrDefault();\r
+                _isReadOnly = (readOnlyAttribute != null ? readOnlyAttribute.IsReadOnly : false);\r
+            }\r
+\r
+            public override void AddValueChanged(object component, EventHandler handler) { _descriptor.AddValueChanged(component, handler); }\r
+\r
+            public override bool CanResetValue(object component) { return _descriptor.CanResetValue(component); }\r
+\r
+            public override Type ComponentType { get { return _descriptor.ComponentType; } }\r
+\r
+            public override object GetValue(object component) { return _descriptor.GetValue(component); }\r
+\r
+            public override bool IsReadOnly {\r
+                get {\r
+                    // Dev10 Bug 594083\r
+                    // It's not enough to call the wrapped _descriptor because it does not know anything about\r
+                    // new attributes passed into the constructor of this class.\r
+                    return _isReadOnly || _descriptor.IsReadOnly;\r
+                }\r
+            }\r
+\r
+            public override Type PropertyType { get { return _descriptor.PropertyType; } }\r
+\r
+            public override void RemoveValueChanged(object component, EventHandler handler) { _descriptor.RemoveValueChanged(component, handler); }\r
+\r
+            public override void ResetValue(object component) { _descriptor.ResetValue(component); }\r
+\r
+            public override void SetValue(object component, object value) { _descriptor.SetValue(component, value); }\r
+\r
+            public override bool ShouldSerializeValue(object component) { return _descriptor.ShouldSerializeValue(component); }\r
+\r
+            public override bool SupportsChangeEvents { get { return _descriptor.SupportsChangeEvents; } }\r
+        }\r
+    \r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/TypeHelpers.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/TypeHelpers.cs
new file mode 100644 (file)
index 0000000..6a024bb
--- /dev/null
@@ -0,0 +1,138 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections;\r
+    using System.Collections.Generic;\r
+    using System.Linq;\r
+    using System.Reflection;\r
+    using System.Threading;\r
+\r
+    internal static class TypeHelpers {\r
+\r
+        private static readonly Dictionary<Type, TryGetValueDelegate> _tryGetValueDelegateCache = new Dictionary<Type, TryGetValueDelegate>();\r
+        private static readonly ReaderWriterLockSlim _tryGetValueDelegateCacheLock = new ReaderWriterLockSlim();\r
+\r
+        private static readonly MethodInfo _strongTryGetValueImplInfo = typeof(TypeHelpers).GetMethod("StrongTryGetValueImpl", BindingFlags.NonPublic | BindingFlags.Static);\r
+\r
+        public static readonly Assembly MsCorLibAssembly = typeof(string).Assembly;\r
+        public static readonly Assembly MvcAssembly = typeof(Controller).Assembly;\r
+        public static readonly Assembly SystemWebAssembly = typeof(HttpContext).Assembly;\r
+\r
+        // method is used primarily for lighting up new .NET Framework features even if MVC targets the previous version\r
+        // thisParameter is the 'this' parameter if target method is instance method, should be null for static method\r
+        public static TDelegate CreateDelegate<TDelegate>(Assembly assembly, string typeName, string methodName, object thisParameter) where TDelegate : class {\r
+            // ensure target type exists\r
+            Type targetType = assembly.GetType(typeName, false /* throwOnError */);\r
+            if (targetType == null) {\r
+                return null;\r
+            }\r
+\r
+            return CreateDelegate<TDelegate>(targetType, methodName, thisParameter);\r
+        }\r
+\r
+        public static TDelegate CreateDelegate<TDelegate>(Type targetType, string methodName, object thisParameter) where TDelegate : class {\r
+            // ensure target method exists\r
+            ParameterInfo[] delegateParameters = typeof(TDelegate).GetMethod("Invoke").GetParameters();\r
+            Type[] argumentTypes = Array.ConvertAll(delegateParameters, pInfo => pInfo.ParameterType);\r
+            MethodInfo targetMethod = targetType.GetMethod(methodName, argumentTypes);\r
+            if (targetMethod == null) {\r
+                return null;\r
+            }\r
+\r
+            TDelegate d = Delegate.CreateDelegate(typeof(TDelegate), thisParameter, targetMethod, false /* throwOnBindFailure */) as TDelegate;\r
+            return d;\r
+        }\r
+\r
+        public static TryGetValueDelegate CreateTryGetValueDelegate(Type targetType) {\r
+            TryGetValueDelegate result;\r
+\r
+            _tryGetValueDelegateCacheLock.EnterReadLock();\r
+            try {\r
+                if (_tryGetValueDelegateCache.TryGetValue(targetType, out result)) {\r
+                    return result;\r
+                }\r
+            }\r
+            finally {\r
+                _tryGetValueDelegateCacheLock.ExitReadLock();\r
+            }\r
+\r
+            Type dictionaryType = ExtractGenericInterface(targetType, typeof(IDictionary<,>));\r
+\r
+            // just wrap a call to the underlying IDictionary<TKey, TValue>.TryGetValue() where string can be cast to TKey\r
+            if (dictionaryType != null) {\r
+                Type[] typeArguments = dictionaryType.GetGenericArguments();\r
+                Type keyType = typeArguments[0];\r
+                Type returnType = typeArguments[1];\r
+\r
+                if (keyType.IsAssignableFrom(typeof(string))) {\r
+                    MethodInfo strongImplInfo = _strongTryGetValueImplInfo.MakeGenericMethod(keyType, returnType);\r
+                    result = (TryGetValueDelegate)Delegate.CreateDelegate(typeof(TryGetValueDelegate), strongImplInfo);\r
+                }\r
+            }\r
+\r
+            // wrap a call to the underlying IDictionary.Item()\r
+            if (result == null && typeof(IDictionary).IsAssignableFrom(targetType)) {\r
+                result = TryGetValueFromNonGenericDictionary;\r
+            }\r
+\r
+            _tryGetValueDelegateCacheLock.EnterWriteLock();\r
+            try {\r
+                _tryGetValueDelegateCache[targetType] = result;\r
+            }\r
+            finally {\r
+                _tryGetValueDelegateCacheLock.ExitWriteLock();\r
+            }\r
+\r
+            return result;\r
+        }\r
+\r
+        public static Type ExtractGenericInterface(Type queryType, Type interfaceType) {\r
+            Func<Type, bool> matchesInterface = t => t.IsGenericType && t.GetGenericTypeDefinition() == interfaceType;\r
+            return (matchesInterface(queryType)) ? queryType : queryType.GetInterfaces().FirstOrDefault(matchesInterface);\r
+        }\r
+\r
+        public static object GetDefaultValue(Type type) {\r
+            return (TypeAllowsNullValue(type)) ? null : Activator.CreateInstance(type);\r
+        }\r
+\r
+        public static bool IsCompatibleObject<T>(object value) {\r
+            return (value is T || (value == null && TypeAllowsNullValue(typeof(T))));\r
+        }\r
+\r
+        public static bool IsNullableValueType(Type type) {\r
+            return Nullable.GetUnderlyingType(type) != null;\r
+        }\r
+\r
+        private static bool StrongTryGetValueImpl<TKey, TValue>(object dictionary, string key, out object value) {\r
+            IDictionary<TKey, TValue> strongDict = (IDictionary<TKey, TValue>)dictionary;\r
+\r
+            TValue strongValue;\r
+            bool retVal = strongDict.TryGetValue((TKey)(object)key, out strongValue);\r
+            value = strongValue;\r
+            return retVal;\r
+        }\r
+\r
+        private static bool TryGetValueFromNonGenericDictionary(object dictionary, string key, out object value) {\r
+            IDictionary weakDict = (IDictionary)dictionary;\r
+\r
+            bool containsKey = weakDict.Contains(key);\r
+            value = (containsKey) ? weakDict[key] : null;\r
+            return containsKey;\r
+        }\r
+\r
+        public static bool TypeAllowsNullValue(Type type) {\r
+            return (!type.IsValueType || IsNullableValueType(type));\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/UrlHelper.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/UrlHelper.cs
new file mode 100644 (file)
index 0000000..6b310c8
--- /dev/null
@@ -0,0 +1,209 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.Routing;\r
+\r
+    public class UrlHelper {\r
+        public UrlHelper(RequestContext requestContext)\r
+            : this(requestContext, RouteTable.Routes) {\r
+        }\r
+\r
+        public UrlHelper(RequestContext requestContext, RouteCollection routeCollection) {\r
+            if (requestContext == null) {\r
+                throw new ArgumentNullException("requestContext");\r
+            }\r
+            if (routeCollection == null) {\r
+                throw new ArgumentNullException("routeCollection");\r
+            }\r
+            RequestContext = requestContext;\r
+            RouteCollection = routeCollection;\r
+        }\r
+\r
+        public RequestContext RequestContext {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public RouteCollection RouteCollection {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public string Action(string actionName) {\r
+            return GenerateUrl(null /* routeName */, actionName, null, (RouteValueDictionary)null /* routeValues */);\r
+        }\r
+\r
+        public string Action(string actionName, object routeValues) {\r
+            return GenerateUrl(null /* routeName */, actionName, null /* controllerName */, new RouteValueDictionary(routeValues));\r
+        }\r
+\r
+        public string Action(string actionName, RouteValueDictionary routeValues) {\r
+            return GenerateUrl(null /* routeName */, actionName, null /* controllerName */, routeValues);\r
+        }\r
+\r
+        public string Action(string actionName, string controllerName) {\r
+            return GenerateUrl(null /* routeName */, actionName, controllerName, (RouteValueDictionary)null /* routeValues */);\r
+        }\r
+\r
+        public string Action(string actionName, string controllerName, object routeValues) {\r
+            return GenerateUrl(null /* routeName */, actionName, controllerName, new RouteValueDictionary(routeValues));\r
+        }\r
+\r
+        public string Action(string actionName, string controllerName, RouteValueDictionary routeValues) {\r
+            return GenerateUrl(null /* routeName */, actionName, controllerName, routeValues);\r
+        }\r
+\r
+        public string Action(string actionName, string controllerName, object routeValues, string protocol) {\r
+            return GenerateUrl(null /* routeName */, actionName, controllerName, protocol, null /* hostName */, null /* fragment */, new RouteValueDictionary(routeValues), RouteCollection, RequestContext, true /* includeImplicitMvcValues */);\r
+        }\r
+\r
+        public string Action(string actionName, string controllerName, RouteValueDictionary routeValues, string protocol, string hostName) {\r
+            return GenerateUrl(null /* routeName */, actionName, controllerName, protocol, hostName, null /* fragment */, routeValues, RouteCollection, RequestContext, true /* includeImplicitMvcValues */);\r
+        }\r
+\r
+        public string Content(string contentPath) {\r
+            return GenerateContentUrl(contentPath, RequestContext.HttpContext);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings",\r
+            Justification = "As the return value will used only for rendering, string return value is more appropriate.")]\r
+        public static string GenerateContentUrl(string contentPath, HttpContextBase httpContext) {\r
+            if (String.IsNullOrEmpty(contentPath)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "contentPath");\r
+            }\r
+\r
+            if (httpContext == null) {\r
+                throw new ArgumentNullException("httpContext");\r
+            }\r
+\r
+            if (contentPath[0] == '~') {\r
+                return PathHelpers.GenerateClientUrl(httpContext, contentPath);\r
+            }\r
+            else {\r
+                return contentPath;\r
+            }\r
+        }\r
+\r
+        //REVIEW: Should we have an overload that takes Uri?\r
+        [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings",\r
+            Justification = "As the return value will used only for rendering, string return value is more appropriate.")]\r
+        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",\r
+            Justification = "Needs to take same parameters as HttpUtility.UrlEncode()")]\r
+        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic",\r
+            Justification = "For consistency, all helpers are instance methods.")]\r
+        public string Encode(string url) {\r
+            return HttpUtility.UrlEncode(url);\r
+        }\r
+\r
+        private string GenerateUrl(string routeName, string actionName, string controllerName, RouteValueDictionary routeValues) {\r
+            return GenerateUrl(routeName, actionName, controllerName, routeValues, RouteCollection, RequestContext, true /* includeImplicitMvcValues */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings",\r
+            Justification = "As the return value will used only for rendering, string return value is more appropriate.")]\r
+        public static string GenerateUrl(string routeName, string actionName, string controllerName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, bool includeImplicitMvcValues) {\r
+            string url = GenerateUrl(routeName, actionName, controllerName, routeValues, routeCollection, requestContext, includeImplicitMvcValues);\r
+\r
+            if (url != null) {\r
+                if (!String.IsNullOrEmpty(fragment)) {\r
+                    url = url + "#" + fragment;\r
+                }\r
+\r
+                if (!String.IsNullOrEmpty(protocol) || !String.IsNullOrEmpty(hostName)) {\r
+                    Uri requestUrl = requestContext.HttpContext.Request.Url;\r
+                    protocol = (!String.IsNullOrEmpty(protocol)) ? protocol : Uri.UriSchemeHttp;\r
+                    hostName = (!String.IsNullOrEmpty(hostName)) ? hostName : requestUrl.Host;\r
+\r
+                    string port = String.Empty;\r
+                    string requestProtocol = requestUrl.Scheme;\r
+\r
+                    if (String.Equals(protocol, requestProtocol, StringComparison.OrdinalIgnoreCase)) {\r
+                        port = requestUrl.IsDefaultPort ? String.Empty : (":" + Convert.ToString(requestUrl.Port, CultureInfo.InvariantCulture));\r
+                    }\r
+\r
+                    url = protocol + Uri.SchemeDelimiter + hostName + port + url;\r
+                }\r
+            }\r
+\r
+            return url;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings",\r
+            Justification = "As the return value will used only for rendering, string return value is more appropriate.")]\r
+        public static string GenerateUrl(string routeName, string actionName, string controllerName, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, bool includeImplicitMvcValues) {\r
+            if (routeCollection == null) {\r
+                throw new ArgumentNullException("routeCollection");\r
+            }\r
+\r
+            if (requestContext == null) {\r
+                throw new ArgumentNullException("requestContext");\r
+            }\r
+\r
+            RouteValueDictionary mergedRouteValues = RouteValuesHelpers.MergeRouteValues(actionName, controllerName, requestContext.RouteData.Values, routeValues, includeImplicitMvcValues);\r
+\r
+            VirtualPathData vpd = routeCollection.GetVirtualPathForArea(requestContext, routeName, mergedRouteValues);\r
+            if (vpd == null) {\r
+                return null;\r
+            }\r
+\r
+            string modifiedUrl = PathHelpers.GenerateClientUrl(requestContext.HttpContext, vpd.VirtualPath);\r
+            return modifiedUrl;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings",\r
+            Justification = "As the return value will used only for rendering, string return value is more appropriate.")]\r
+        public string RouteUrl(object routeValues) {\r
+            return RouteUrl(null /* routeName */, routeValues);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings",\r
+            Justification = "As the return value will used only for rendering, string return value is more appropriate.")]\r
+        public string RouteUrl(RouteValueDictionary routeValues) {\r
+            return RouteUrl(null /* routeName */, routeValues);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings",\r
+            Justification = "As the return value will used only for rendering, string return value is more appropriate.")]\r
+        public string RouteUrl(string routeName) {\r
+            return RouteUrl(routeName, (object)null /* routeValues */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings",\r
+            Justification = "As the return value will used only for rendering, string return value is more appropriate.")]\r
+        public string RouteUrl(string routeName, object routeValues) {\r
+            return RouteUrl(routeName, routeValues, null /* protocol */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings",\r
+            Justification = "As the return value will used only for rendering, string return value is more appropriate.")]\r
+        public string RouteUrl(string routeName, RouteValueDictionary routeValues) {\r
+            return RouteUrl(routeName, routeValues, null /* protocol */, null /* hostName */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings",\r
+            Justification = "As the return value will used only for rendering, string return value is more appropriate.")]\r
+        public string RouteUrl(string routeName, object routeValues, string protocol) {\r
+            return GenerateUrl(routeName, null /* actionName */, null /* controllerName */, protocol, null /* hostName */, null /* fragment */, new RouteValueDictionary(routeValues), RouteCollection, RequestContext, false /* includeImplicitMvcValues */);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings",\r
+            Justification = "As the return value will used only for rendering, string return value is more appropriate.")]\r
+        public string RouteUrl(string routeName, RouteValueDictionary routeValues, string protocol, string hostName) {\r
+            return GenerateUrl(routeName, null /* actionName */, null /* controllerName */, protocol, hostName, null /* fragment */, routeValues, RouteCollection, RequestContext, false /* includeImplicitMvcValues */);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/UrlParameter.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/UrlParameter.cs
new file mode 100644 (file)
index 0000000..3d39c1e
--- /dev/null
@@ -0,0 +1,27 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+\r
+    public sealed class UrlParameter {\r
+\r
+        [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes",\r
+            Justification = "This type is immutable.")]\r
+        public static readonly UrlParameter Optional = new UrlParameter();\r
+\r
+        // singleton constructor\r
+        private UrlParameter() { }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ValidateAntiForgeryTokenAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ValidateAntiForgeryTokenAttribute.cs
new file mode 100644 (file)
index 0000000..0eedc81
--- /dev/null
@@ -0,0 +1,94 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Web;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\r
+    public sealed class ValidateAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter {\r
+\r
+        private string _salt;\r
+        private AntiForgeryDataSerializer _serializer;\r
+\r
+        public string Salt {\r
+            get {\r
+                return _salt ?? String.Empty;\r
+            }\r
+            set {\r
+                _salt = value;\r
+            }\r
+        }\r
+\r
+        internal AntiForgeryDataSerializer Serializer {\r
+            get {\r
+                if (_serializer == null) {\r
+                    _serializer = new AntiForgeryDataSerializer();\r
+                }\r
+                return _serializer;\r
+            }\r
+            set {\r
+                _serializer = value;\r
+            }\r
+        }\r
+\r
+        private bool ValidateFormToken(AntiForgeryData token) {\r
+            return (String.Equals(Salt, token.Salt, StringComparison.Ordinal));\r
+        }\r
+\r
+        private static HttpAntiForgeryException CreateValidationException() {\r
+            return new HttpAntiForgeryException(MvcResources.AntiForgeryToken_ValidationFailed);\r
+        }\r
+\r
+        public void OnAuthorization(AuthorizationContext filterContext) {\r
+            if (filterContext == null) {\r
+                throw new ArgumentNullException("filterContext");\r
+            }\r
+\r
+            string fieldName = AntiForgeryData.GetAntiForgeryTokenName(null);\r
+            string cookieName = AntiForgeryData.GetAntiForgeryTokenName(filterContext.HttpContext.Request.ApplicationPath);\r
+\r
+            HttpCookie cookie = filterContext.HttpContext.Request.Cookies[cookieName];\r
+            if (cookie == null || String.IsNullOrEmpty(cookie.Value)) {\r
+                // error: cookie token is missing\r
+                throw CreateValidationException();\r
+            }\r
+            AntiForgeryData cookieToken = Serializer.Deserialize(cookie.Value);\r
+\r
+            string formValue = filterContext.HttpContext.Request.Form[fieldName];\r
+            if (String.IsNullOrEmpty(formValue)) {\r
+                // error: form token is missing\r
+                throw CreateValidationException();\r
+            }\r
+            AntiForgeryData formToken = Serializer.Deserialize(formValue);\r
+\r
+            if (!String.Equals(cookieToken.Value, formToken.Value, StringComparison.Ordinal)) {\r
+                // error: form token does not match cookie token\r
+                throw CreateValidationException();\r
+            }\r
+\r
+            string currentUsername = AntiForgeryData.GetUsername(filterContext.HttpContext.User);\r
+            if (!String.Equals(formToken.Username, currentUsername, StringComparison.OrdinalIgnoreCase)) {\r
+                // error: form token is not valid for this user\r
+                // (don't care about cookie token)\r
+                throw CreateValidationException();\r
+            }\r
+\r
+            if (!ValidateFormToken(formToken)) {\r
+                // error: custom validation failed\r
+                throw CreateValidationException();\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ValidateInputAttribute.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ValidateInputAttribute.cs
new file mode 100644 (file)
index 0000000..7e07f99
--- /dev/null
@@ -0,0 +1,40 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+\r
+    [SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes",\r
+        Justification = "No compelling performance reason to seal this type.")]\r
+    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\r
+    public class ValidateInputAttribute : FilterAttribute, IAuthorizationFilter {\r
+\r
+        public ValidateInputAttribute(bool enableValidation) {\r
+            EnableValidation = enableValidation;\r
+        }\r
+\r
+        public bool EnableValidation {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public virtual void OnAuthorization(AuthorizationContext filterContext) {\r
+            if (filterContext == null) {\r
+                throw new ArgumentNullException("filterContext");\r
+            }\r
+\r
+            filterContext.Controller.ValidateRequest = EnableValidation;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderCollection.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderCollection.cs
new file mode 100644 (file)
index 0000000..46ec5ae
--- /dev/null
@@ -0,0 +1,54 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Collections.ObjectModel;\r
+    using System.Linq;\r
+\r
+    public class ValueProviderCollection : Collection<IValueProvider>, IValueProvider {\r
+\r
+        public ValueProviderCollection() {\r
+        }\r
+\r
+        public ValueProviderCollection(IList<IValueProvider> list)\r
+            : base(list) {\r
+        }\r
+\r
+        public virtual bool ContainsPrefix(string prefix) {\r
+            return this.Any(vp => vp.ContainsPrefix(prefix));\r
+        }\r
+\r
+        public virtual ValueProviderResult GetValue(string key) {\r
+            return (from provider in this\r
+                    let result = provider.GetValue(key)\r
+                    where result != null\r
+                    select result).FirstOrDefault();\r
+        }\r
+\r
+        protected override void InsertItem(int index, IValueProvider item) {\r
+            if (item == null) {\r
+                throw new ArgumentNullException("item");\r
+            }\r
+            base.InsertItem(index, item);\r
+        }\r
+\r
+        protected override void SetItem(int index, IValueProvider item) {\r
+            if (item == null) {\r
+                throw new ArgumentNullException("item");\r
+            }\r
+            base.SetItem(index, item);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderDictionary.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderDictionary.cs
new file mode 100644 (file)
index 0000000..a5ea7f0
--- /dev/null
@@ -0,0 +1,208 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections;\r
+    using System.Collections.Generic;\r
+    using System.Collections.Specialized;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.Web.Routing;\r
+\r
+    [Obsolete("The recommended alternative is to use one of the specific ValueProvider types, such as FormValueProvider.")]\r
+    public class ValueProviderDictionary : IDictionary<string, ValueProviderResult>, IValueProvider {\r
+\r
+        private readonly Dictionary<string, ValueProviderResult> _dictionary = new Dictionary<string, ValueProviderResult>(StringComparer.OrdinalIgnoreCase);\r
+\r
+        public ValueProviderDictionary(ControllerContext controllerContext) {\r
+            ControllerContext = controllerContext;\r
+            if (controllerContext != null) {\r
+                PopulateDictionary();\r
+            }\r
+        }\r
+\r
+        public ControllerContext ControllerContext {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public int Count {\r
+            get {\r
+                return ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).Count;\r
+            }\r
+        }\r
+\r
+        internal Dictionary<string, ValueProviderResult> Dictionary {\r
+            get {\r
+                return _dictionary;\r
+            }\r
+        }\r
+\r
+        public bool IsReadOnly {\r
+            get {\r
+                return ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).IsReadOnly;\r
+            }\r
+        }\r
+\r
+        public ICollection<string> Keys {\r
+            get {\r
+                return Dictionary.Keys;\r
+            }\r
+        }\r
+\r
+        public ValueProviderResult this[string key] {\r
+            get {\r
+                ValueProviderResult result;\r
+                Dictionary.TryGetValue(key, out result);\r
+                return result;\r
+            }\r
+            set {\r
+                Dictionary[key] = value;\r
+            }\r
+        }\r
+\r
+        public ICollection<ValueProviderResult> Values {\r
+            get {\r
+                return Dictionary.Values;\r
+            }\r
+        }\r
+\r
+        public void Add(KeyValuePair<string, ValueProviderResult> item) {\r
+            ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).Add(item);\r
+        }\r
+\r
+        public void Add(string key, object value) {\r
+            string attemptedValue = Convert.ToString(value, CultureInfo.InvariantCulture);\r
+            ValueProviderResult vpResult = new ValueProviderResult(value, attemptedValue, CultureInfo.InvariantCulture);\r
+            Add(key, vpResult);\r
+        }\r
+\r
+        public void Add(string key, ValueProviderResult value) {\r
+            Dictionary.Add(key, value);\r
+        }\r
+\r
+        private void AddToDictionaryIfNotPresent(string key, ValueProviderResult result) {\r
+            if (!String.IsNullOrEmpty(key)) {\r
+                if (!Dictionary.ContainsKey(key)) {\r
+                    Dictionary.Add(key, result);\r
+                }\r
+            }\r
+        }\r
+\r
+        public void Clear() {\r
+            ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).Clear();\r
+        }\r
+\r
+        public bool Contains(KeyValuePair<string, ValueProviderResult> item) {\r
+            return ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).Contains(item);\r
+        }\r
+\r
+        public bool ContainsKey(string key) {\r
+            return Dictionary.ContainsKey(key);\r
+        }\r
+\r
+        public void CopyTo(KeyValuePair<string, ValueProviderResult>[] array, int arrayIndex) {\r
+            ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).CopyTo(array, arrayIndex);\r
+        }\r
+\r
+        public IEnumerator<KeyValuePair<string, ValueProviderResult>> GetEnumerator() {\r
+            return ((IEnumerable<KeyValuePair<string, ValueProviderResult>>)Dictionary).GetEnumerator();\r
+        }\r
+\r
+        private void PopulateDictionary() {\r
+            CultureInfo currentCulture = CultureInfo.CurrentCulture;\r
+            CultureInfo invariantCulture = CultureInfo.InvariantCulture;\r
+\r
+            // We use this order of precedence to populate the dictionary:\r
+            // 1. Request form submission (should be culture-aware)\r
+            // 2. Values from the RouteData (could be from the typed-in URL or from the route's default values)\r
+            // 3. URI query string\r
+\r
+            NameValueCollection form = ControllerContext.HttpContext.Request.Form;\r
+            if (form != null) {\r
+                string[] keys = form.AllKeys;\r
+                foreach (string key in keys) {\r
+                    string[] rawValue = form.GetValues(key);\r
+                    string attemptedValue = form[key];\r
+                    ValueProviderResult result = new ValueProviderResult(rawValue, attemptedValue, currentCulture);\r
+                    AddToDictionaryIfNotPresent(key, result);\r
+                }\r
+            }\r
+\r
+            RouteValueDictionary routeValues = ControllerContext.RouteData.Values;\r
+            if (routeValues != null) {\r
+                foreach (var kvp in routeValues) {\r
+                    string key = kvp.Key;\r
+                    object rawValue = kvp.Value;\r
+                    string attemptedValue = Convert.ToString(rawValue, invariantCulture);\r
+                    ValueProviderResult result = new ValueProviderResult(rawValue, attemptedValue, invariantCulture);\r
+                    AddToDictionaryIfNotPresent(key, result);\r
+                }\r
+            }\r
+\r
+            NameValueCollection queryString = ControllerContext.HttpContext.Request.QueryString;\r
+            if (queryString != null) {\r
+                string[] keys = queryString.AllKeys;\r
+                foreach (string key in keys) {\r
+                    string[] rawValue = queryString.GetValues(key);\r
+                    string attemptedValue = queryString[key];\r
+                    ValueProviderResult result = new ValueProviderResult(rawValue, attemptedValue, invariantCulture);\r
+                    AddToDictionaryIfNotPresent(key, result);\r
+                }\r
+            }\r
+        }\r
+\r
+        public bool Remove(KeyValuePair<string, ValueProviderResult> item) {\r
+            return ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).Remove(item);\r
+        }\r
+\r
+        public bool Remove(string key) {\r
+            return Dictionary.Remove(key);\r
+        }\r
+\r
+        public bool TryGetValue(string key, out ValueProviderResult value) {\r
+            return Dictionary.TryGetValue(key, out value);\r
+        }\r
+\r
+        #region IEnumerable Members\r
+        IEnumerator IEnumerable.GetEnumerator() {\r
+            return ((IEnumerable)Dictionary).GetEnumerator();\r
+        }\r
+        #endregion\r
+\r
+        #region IValueProvider Members\r
+        [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes",\r
+            Justification = "The declaring type is obsolete, so there is little benefit to exposing this as a virtual method.")]\r
+        bool IValueProvider.ContainsPrefix(string prefix) {\r
+            if (prefix == null) {\r
+                throw new ArgumentNullException("prefix");\r
+            }\r
+\r
+            return ValueProviderUtil.CollectionContainsPrefix(Keys, prefix);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes",\r
+            Justification = "The declaring type is obsolete, so there is little benefit to exposing this as a virtual method.")]\r
+        ValueProviderResult IValueProvider.GetValue(string key) {\r
+            if (key == null) {\r
+                throw new ArgumentNullException("key");\r
+            }\r
+\r
+            ValueProviderResult vpResult;\r
+            TryGetValue(key, out vpResult);\r
+            return vpResult;\r
+        }\r
+        #endregion\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderFactories.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderFactories.cs
new file mode 100644 (file)
index 0000000..f926e58
--- /dev/null
@@ -0,0 +1,32 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    public static class ValueProviderFactories {\r
+\r
+        private static readonly ValueProviderFactoryCollection _factories = new ValueProviderFactoryCollection() {\r
+            new FormValueProviderFactory(),\r
+            new RouteDataValueProviderFactory(),\r
+            new QueryStringValueProviderFactory(),\r
+            new HttpFileCollectionValueProviderFactory()\r
+        };\r
+\r
+        public static ValueProviderFactoryCollection Factories {\r
+            get {\r
+                return _factories;\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderFactory.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderFactory.cs
new file mode 100644 (file)
index 0000000..3d2e42a
--- /dev/null
@@ -0,0 +1,19 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    public abstract class ValueProviderFactory {\r
+        public abstract IValueProvider GetValueProvider(ControllerContext controllerContext);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderFactoryCollection.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderFactoryCollection.cs
new file mode 100644 (file)
index 0000000..2d797e2
--- /dev/null
@@ -0,0 +1,53 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Collections.ObjectModel;\r
+    using System.Linq;\r
+\r
+    public class ValueProviderFactoryCollection : Collection<ValueProviderFactory> {\r
+\r
+        public ValueProviderFactoryCollection() {\r
+        }\r
+\r
+        public ValueProviderFactoryCollection(IList<ValueProviderFactory> list)\r
+            : base(list) {\r
+        }\r
+\r
+        public IValueProvider GetValueProvider(ControllerContext controllerContext) {\r
+            var valueProviders = from factory in this\r
+                                 let valueProvider = factory.GetValueProvider(controllerContext)\r
+                                 where valueProvider != null\r
+                                 select valueProvider;\r
+\r
+            return new ValueProviderCollection(valueProviders.ToList());\r
+        }\r
+\r
+\r
+        protected override void InsertItem(int index, ValueProviderFactory item) {\r
+            if (item == null) {\r
+                throw new ArgumentNullException("item");\r
+            }\r
+            base.InsertItem(index, item);\r
+        }\r
+\r
+        protected override void SetItem(int index, ValueProviderFactory item) {\r
+            if (item == null) {\r
+                throw new ArgumentNullException("item");\r
+            }\r
+            base.SetItem(index, item);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderResult.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderResult.cs
new file mode 100644 (file)
index 0000000..790a04a
--- /dev/null
@@ -0,0 +1,147 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections;\r
+    using System.ComponentModel;\r
+    using System.Globalization;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    [Serializable]\r
+    public class ValueProviderResult {\r
+\r
+        private static readonly CultureInfo _staticCulture = CultureInfo.InvariantCulture;\r
+        private CultureInfo _instanceCulture;\r
+\r
+        // default constructor so that subclassed types can set the properties themselves\r
+        protected ValueProviderResult() {\r
+        }\r
+\r
+        public ValueProviderResult(object rawValue, string attemptedValue, CultureInfo culture) {\r
+            RawValue = rawValue;\r
+            AttemptedValue = attemptedValue;\r
+            Culture = culture;\r
+        }\r
+\r
+        public string AttemptedValue {\r
+            get;\r
+            protected set;\r
+        }\r
+\r
+        public CultureInfo Culture {\r
+            get {\r
+                if (_instanceCulture == null) {\r
+                    _instanceCulture = _staticCulture;\r
+                }\r
+                return _instanceCulture;\r
+            }\r
+            protected set {\r
+                _instanceCulture = value;\r
+            }\r
+        }\r
+\r
+        public object RawValue {\r
+            get;\r
+            protected set;\r
+        }\r
+\r
+        private static object ConvertSimpleType(CultureInfo culture, object value, Type destinationType) {\r
+            if (value == null || destinationType.IsInstanceOfType(value)) {\r
+                return value;\r
+            }\r
+\r
+            // if this is a user-input value but the user didn't type anything, return no value\r
+            string valueAsString = value as string;\r
+            if (valueAsString != null && valueAsString.Trim().Length == 0) {\r
+                return null;\r
+            }\r
+\r
+            TypeConverter converter = TypeDescriptor.GetConverter(destinationType);\r
+            bool canConvertFrom = converter.CanConvertFrom(value.GetType());\r
+            if (!canConvertFrom) {\r
+                converter = TypeDescriptor.GetConverter(value.GetType());\r
+            }\r
+            if (!(canConvertFrom || converter.CanConvertTo(destinationType))) {\r
+                string message = String.Format(CultureInfo.CurrentUICulture, MvcResources.ValueProviderResult_NoConverterExists,\r
+                    value.GetType().FullName, destinationType.FullName);\r
+                throw new InvalidOperationException(message);\r
+            }\r
+\r
+            try {\r
+                object convertedValue = (canConvertFrom) ?\r
+                     converter.ConvertFrom(null /* context */, culture, value) :\r
+                     converter.ConvertTo(null /* context */, culture, value, destinationType);\r
+                return convertedValue;\r
+            }\r
+            catch (Exception ex) {\r
+                string message = String.Format(CultureInfo.CurrentUICulture, MvcResources.ValueProviderResult_ConversionThrew,\r
+                    value.GetType().FullName, destinationType.FullName);\r
+                throw new InvalidOperationException(message, ex);\r
+            }\r
+        }\r
+\r
+        public object ConvertTo(Type type) {\r
+            return ConvertTo(type, null /* culture */);\r
+        }\r
+\r
+        public virtual object ConvertTo(Type type, CultureInfo culture) {\r
+            if (type == null) {\r
+                throw new ArgumentNullException("type");\r
+            }\r
+\r
+            CultureInfo cultureToUse = culture ?? Culture;\r
+            return UnwrapPossibleArrayType(cultureToUse, RawValue, type);\r
+        }\r
+\r
+        private static object UnwrapPossibleArrayType(CultureInfo culture, object value, Type destinationType) {\r
+            if (value == null || destinationType.IsInstanceOfType(value)) {\r
+                return value;\r
+            }\r
+\r
+            // array conversion results in four cases, as below\r
+            Array valueAsArray = value as Array;\r
+            if (destinationType.IsArray) {\r
+                Type destinationElementType = destinationType.GetElementType();\r
+                if (valueAsArray != null) {\r
+                    // case 1: both destination + source type are arrays, so convert each element\r
+                    IList converted = Array.CreateInstance(destinationElementType, valueAsArray.Length);\r
+                    for (int i = 0; i < valueAsArray.Length; i++) {\r
+                        converted[i] = ConvertSimpleType(culture, valueAsArray.GetValue(i), destinationElementType);\r
+                    }\r
+                    return converted;\r
+                }\r
+                else {\r
+                    // case 2: destination type is array but source is single element, so wrap element in array + convert\r
+                    object element = ConvertSimpleType(culture, value, destinationElementType);\r
+                    IList converted = Array.CreateInstance(destinationElementType, 1);\r
+                    converted[0] = element;\r
+                    return converted;\r
+                }\r
+            }\r
+            else if (valueAsArray != null) {\r
+                // case 3: destination type is single element but source is array, so extract first element + convert\r
+                if (valueAsArray.Length > 0) {\r
+                    value = valueAsArray.GetValue(0);\r
+                    return ConvertSimpleType(culture, value, destinationType);\r
+                }\r
+                else {\r
+                    // case 3(a): source is empty array, so can't perform conversion\r
+                    return null;\r
+                }\r
+            }\r
+            // case 4: both destination + source type are single elements, so convert\r
+            return ConvertSimpleType(culture, value, destinationType);\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderUtil.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ValueProviderUtil.cs
new file mode 100644 (file)
index 0000000..4bbad40
--- /dev/null
@@ -0,0 +1,63 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Linq;\r
+\r
+    internal static class ValueProviderUtil {\r
+\r
+        // Given "foo.bar[baz].quux", this method will return:\r
+        // - "foo.bar[baz].quux"\r
+        // - "foo.bar[baz]"\r
+        // - "foo.bar"\r
+        // - "foo"\r
+        public static IEnumerable<string> GetPrefixes(string key) {\r
+            yield return key;\r
+            for (int i = key.Length - 1; i >= 0; i--) {\r
+                switch (key[i]) {\r
+                    case '.':\r
+                    case '[':\r
+                        yield return key.Substring(0, i);\r
+                        break;\r
+                }\r
+            }\r
+        }\r
+\r
+        public static bool CollectionContainsPrefix(IEnumerable<string> collection, string prefix) {\r
+            foreach (string key in collection) {\r
+                if (key != null) {\r
+                    if (prefix.Length == 0) {\r
+                        return true; // shortcut - non-null key matches empty prefix\r
+                    }\r
+\r
+                    if (key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) {\r
+                        if (key.Length == prefix.Length) {\r
+                            return true; // exact match\r
+                        }\r
+                        else {\r
+                            switch (key[prefix.Length]) {\r
+                                case '.': // known separator characters\r
+                                case '[':\r
+                                    return true;\r
+                            }\r
+                        }\r
+                    }\r
+                }\r
+            }\r
+\r
+            return false; // nothing found\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewContext.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewContext.cs
new file mode 100644 (file)
index 0000000..882c6df
--- /dev/null
@@ -0,0 +1,153 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.IO;\r
+    using System.Web.Script.Serialization;\r
+\r
+    public class ViewContext : ControllerContext {\r
+\r
+        private const string _clientValidationScript = @"<script type=""text/javascript"">\r
+//<![CDATA[\r
+if (!window.mvcClientValidationMetadata) {{ window.mvcClientValidationMetadata = []; }}\r
+window.mvcClientValidationMetadata.push({0});\r
+//]]>\r
+</script>";\r
+\r
+        // Some values have to be stored in HttpContext.Items in order to be propagated between calls\r
+        // to RenderPartial(), RenderAction(), etc.\r
+        private static readonly object _clientValidationEnabledKey = new object();\r
+        private static readonly object _formContextKey = new object();\r
+        private static readonly object _lastFormNumKey = new object();\r
+\r
+        private Func<string> _formIdGenerator;\r
+\r
+        // parameterless constructor used for mocking\r
+        public ViewContext() {\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors",\r
+            Justification = "The virtual property setters are only to support mocking frameworks, in which case this constructor shouldn't be called anyway.")]\r
+        public ViewContext(ControllerContext controllerContext, IView view, ViewDataDictionary viewData, TempDataDictionary tempData, TextWriter writer)\r
+            : base(controllerContext) {\r
+            if (controllerContext == null) {\r
+                throw new ArgumentNullException("controllerContext");\r
+            }\r
+            if (view == null) {\r
+                throw new ArgumentNullException("view");\r
+            }\r
+            if (viewData == null) {\r
+                throw new ArgumentNullException("viewData");\r
+            }\r
+            if (tempData == null) {\r
+                throw new ArgumentNullException("tempData");\r
+            }\r
+            if (writer == null) {\r
+                throw new ArgumentNullException("writer");\r
+            }\r
+\r
+            View = view;\r
+            ViewData = viewData;\r
+            Writer = writer;\r
+            TempData = tempData;\r
+        }\r
+\r
+        public virtual bool ClientValidationEnabled {\r
+            get {\r
+                return (HttpContext.Items[_clientValidationEnabledKey] as bool?).GetValueOrDefault();\r
+            }\r
+            set {\r
+                HttpContext.Items[_clientValidationEnabledKey] = value;\r
+            }\r
+        }\r
+\r
+        public virtual FormContext FormContext {\r
+            get {\r
+                return HttpContext.Items[_formContextKey] as FormContext;\r
+            }\r
+            set {\r
+                HttpContext.Items[_formContextKey] = value;\r
+            }\r
+        }\r
+\r
+        internal Func<string> FormIdGenerator {\r
+            get {\r
+                if (_formIdGenerator == null) {\r
+                    _formIdGenerator = DefaultFormIdGenerator;\r
+                }\r
+                return _formIdGenerator;\r
+            }\r
+            set {\r
+                _formIdGenerator = value;\r
+            }\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly",\r
+            Justification = "The property setter is only here to support mocking this type and should not be called at runtime.")]\r
+        public virtual TempDataDictionary TempData {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public virtual IView View {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly",\r
+            Justification = "The property setter is only here to support mocking this type and should not be called at runtime.")]\r
+        public virtual ViewDataDictionary ViewData {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public virtual TextWriter Writer {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        private string DefaultFormIdGenerator() {\r
+            int formNum = IncrementFormCount(HttpContext.Items);\r
+            return String.Format(CultureInfo.InvariantCulture, "form{0}", formNum);\r
+        }\r
+\r
+        internal FormContext GetFormContextForClientValidation() {\r
+            return (ClientValidationEnabled) ? FormContext : null;\r
+        }\r
+\r
+        private static int IncrementFormCount(IDictionary items) {\r
+            object lastFormNum = items[_lastFormNumKey];\r
+            int newFormNum = (lastFormNum != null) ? ((int)lastFormNum) + 1 : 0;\r
+            items[_lastFormNumKey] = newFormNum;\r
+            return newFormNum;\r
+        }\r
+\r
+        public void OutputClientValidation() {\r
+            FormContext formContext = GetFormContextForClientValidation();\r
+            if (formContext == null) {\r
+                return; // do nothing\r
+            }\r
+                        \r
+            string scriptWithCorrectNewLines = _clientValidationScript.Replace("\r\n", Environment.NewLine);\r
+            string validationJson = formContext.GetJsonValidationMetadata();\r
+            string formatted = String.Format(CultureInfo.InvariantCulture, scriptWithCorrectNewLines, validationJson);\r
+\r
+            Writer.Write(formatted);\r
+            FormContext = null;\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewDataDictionary.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewDataDictionary.cs
new file mode 100644 (file)
index 0000000..28b25dd
--- /dev/null
@@ -0,0 +1,356 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections;\r
+    using System.Collections.Generic;\r
+    using System.ComponentModel;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.Reflection;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    // TODO: Unit test ModelState interaction with VDD\r
+\r
+    public class ViewDataDictionary : IDictionary<string, object> {\r
+\r
+        private readonly Dictionary<string, object> _innerDictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\r
+        private object _model;\r
+        private ModelMetadata _modelMetadata;\r
+        private readonly ModelStateDictionary _modelState = new ModelStateDictionary();\r
+        private TemplateInfo _templateMetadata;\r
+\r
+        public ViewDataDictionary()\r
+            : this((object)null) {\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors",\r
+            Justification = "See note on SetModel() method.")]\r
+        public ViewDataDictionary(object model) {\r
+            Model = model;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors",\r
+            Justification = "See note on SetModel() method.")]\r
+        public ViewDataDictionary(ViewDataDictionary dictionary) {\r
+            if (dictionary == null) {\r
+                throw new ArgumentNullException("dictionary");\r
+            }\r
+\r
+            foreach (var entry in dictionary) {\r
+                _innerDictionary.Add(entry.Key, entry.Value);\r
+            }\r
+            foreach (var entry in dictionary.ModelState) {\r
+                ModelState.Add(entry.Key, entry.Value);\r
+            }\r
+\r
+            Model = dictionary.Model;\r
+            TemplateInfo = dictionary.TemplateInfo;\r
+\r
+            // PERF: Don't unnecessarily instantiate the model metadata\r
+            _modelMetadata = dictionary._modelMetadata;\r
+        }\r
+\r
+        public int Count {\r
+            get {\r
+                return _innerDictionary.Count;\r
+            }\r
+        }\r
+\r
+        public bool IsReadOnly {\r
+            get {\r
+                return ((IDictionary<string, object>)_innerDictionary).IsReadOnly;\r
+            }\r
+        }\r
+\r
+        public ICollection<string> Keys {\r
+            get {\r
+                return _innerDictionary.Keys;\r
+            }\r
+        }\r
+\r
+        public object Model {\r
+            get {\r
+                return _model;\r
+            }\r
+            set {\r
+                _modelMetadata = null;\r
+                SetModel(value);\r
+            }\r
+        }\r
+\r
+        public virtual ModelMetadata ModelMetadata {\r
+            get {\r
+                if (_modelMetadata == null && _model != null) {\r
+                    _modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => _model, _model.GetType());\r
+                }\r
+                return _modelMetadata;\r
+            }\r
+            set {\r
+                _modelMetadata = value;\r
+            }\r
+        }\r
+\r
+        public ModelStateDictionary ModelState {\r
+            get {\r
+                return _modelState;\r
+            }\r
+        }\r
+\r
+        public object this[string key] {\r
+            get {\r
+                object value;\r
+                _innerDictionary.TryGetValue(key, out value);\r
+                return value;\r
+            }\r
+            set {\r
+                _innerDictionary[key] = value;\r
+            }\r
+        }\r
+\r
+        public TemplateInfo TemplateInfo {\r
+            get {\r
+                if (_templateMetadata == null) {\r
+                    _templateMetadata = new TemplateInfo();\r
+                }\r
+                return _templateMetadata;\r
+            }\r
+            set {\r
+                _templateMetadata = value;\r
+            }\r
+        }\r
+\r
+        public ICollection<object> Values {\r
+            get {\r
+                return _innerDictionary.Values;\r
+            }\r
+        }\r
+\r
+        public void Add(KeyValuePair<string, object> item) {\r
+            ((IDictionary<string, object>)_innerDictionary).Add(item);\r
+        }\r
+\r
+        public void Add(string key, object value) {\r
+            _innerDictionary.Add(key, value);\r
+        }\r
+\r
+        public void Clear() {\r
+            _innerDictionary.Clear();\r
+        }\r
+\r
+        public bool Contains(KeyValuePair<string, object> item) {\r
+            return ((IDictionary<string, object>)_innerDictionary).Contains(item);\r
+        }\r
+\r
+        public bool ContainsKey(string key) {\r
+            return _innerDictionary.ContainsKey(key);\r
+        }\r
+\r
+        public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex) {\r
+            ((IDictionary<string, object>)_innerDictionary).CopyTo(array, arrayIndex);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Eval",\r
+            Justification = "Commonly used shorthand for Evaluate.")]\r
+        public object Eval(string expression) {\r
+            ViewDataInfo info = GetViewDataInfo(expression);\r
+            return (info != null) ? info.Value : null;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Eval",\r
+            Justification = "Commonly used shorthand for Evaluate.")]\r
+        public string Eval(string expression, string format) {\r
+            object value = Eval(expression);\r
+\r
+            if (value == null) {\r
+                return String.Empty;\r
+            }\r
+\r
+            if (String.IsNullOrEmpty(format)) {\r
+                return Convert.ToString(value, CultureInfo.CurrentCulture);\r
+            }\r
+            else {\r
+                return String.Format(CultureInfo.CurrentCulture, format, value);\r
+            }\r
+        }\r
+\r
+        public IEnumerator<KeyValuePair<string, object>> GetEnumerator() {\r
+            return _innerDictionary.GetEnumerator();\r
+        }\r
+\r
+        public ViewDataInfo GetViewDataInfo(string expression) {\r
+            if (String.IsNullOrEmpty(expression)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "expression");\r
+            }\r
+\r
+            return ViewDataEvaluator.Eval(this, expression);\r
+        }\r
+\r
+        public bool Remove(KeyValuePair<string, object> item) {\r
+            return ((IDictionary<string, object>)_innerDictionary).Remove(item);\r
+        }\r
+\r
+        public bool Remove(string key) {\r
+            return _innerDictionary.Remove(key);\r
+        }\r
+\r
+        // This method will execute before the derived type's instance constructor executes. Derived types must\r
+        // be aware of this and should plan accordingly. For example, the logic in SetModel() should be simple\r
+        // enough so as not to depend on the "this" pointer referencing a fully constructed object.\r
+        protected virtual void SetModel(object value) {\r
+            _model = value;\r
+        }\r
+\r
+        public bool TryGetValue(string key, out object value) {\r
+            return _innerDictionary.TryGetValue(key, out value);\r
+        }\r
+\r
+        internal static class ViewDataEvaluator {\r
+\r
+            public static ViewDataInfo Eval(ViewDataDictionary vdd, string expression) {\r
+                //Given an expression "foo.bar.baz" we look up the following (pseudocode):\r
+                //  this["foo.bar.baz.quux"]\r
+                //  this["foo.bar.baz"]["quux"]\r
+                //  this["foo.bar"]["baz.quux]\r
+                //  this["foo.bar"]["baz"]["quux"]\r
+                //  this["foo"]["bar.baz.quux"]\r
+                //  this["foo"]["bar.baz"]["quux"]\r
+                //  this["foo"]["bar"]["baz.quux"]\r
+                //  this["foo"]["bar"]["baz"]["quux"]\r
+\r
+                ViewDataInfo evaluated = EvalComplexExpression(vdd, expression);\r
+                return evaluated;\r
+            }\r
+\r
+            private static ViewDataInfo EvalComplexExpression(object indexableObject, string expression) {\r
+                foreach (ExpressionPair expressionPair in GetRightToLeftExpressions(expression)) {\r
+                    string subExpression = expressionPair.Left;\r
+                    string postExpression = expressionPair.Right;\r
+\r
+                    ViewDataInfo subTargetInfo = GetPropertyValue(indexableObject, subExpression);\r
+                    if (subTargetInfo != null) {\r
+                        if (String.IsNullOrEmpty(postExpression)) {\r
+                            return subTargetInfo;\r
+                        }\r
+\r
+                        if (subTargetInfo.Value != null) {\r
+                            ViewDataInfo potential = EvalComplexExpression(subTargetInfo.Value, postExpression);\r
+                            if (potential != null) {\r
+                                return potential;\r
+                            }\r
+                        }\r
+                    }\r
+                }\r
+                return null;\r
+            }\r
+\r
+            private static IEnumerable<ExpressionPair> GetRightToLeftExpressions(string expression) {\r
+                // Produces an enumeration of all the combinations of complex property names\r
+                // given a complex expression. See the list above for an example of the result\r
+                // of the enumeration.\r
+\r
+                yield return new ExpressionPair(expression, String.Empty);\r
+\r
+                int lastDot = expression.LastIndexOf('.');\r
+\r
+                string subExpression = expression;\r
+                string postExpression = string.Empty;\r
+\r
+                while (lastDot > -1) {\r
+                    subExpression = expression.Substring(0, lastDot);\r
+                    postExpression = expression.Substring(lastDot + 1);\r
+                    yield return new ExpressionPair(subExpression, postExpression);\r
+\r
+                    lastDot = subExpression.LastIndexOf('.');\r
+                }\r
+            }\r
+\r
+            private static ViewDataInfo GetIndexedPropertyValue(object indexableObject, string key) {\r
+                IDictionary<string, object> dict = indexableObject as IDictionary<string, object>;\r
+                object value = null;\r
+                bool success = false;\r
+                \r
+                if (dict != null) {\r
+                    success = dict.TryGetValue(key, out value);\r
+                }\r
+                else {\r
+                    TryGetValueDelegate tgvDel = TypeHelpers.CreateTryGetValueDelegate(indexableObject.GetType());\r
+                    if (tgvDel != null) {\r
+                        success = tgvDel(indexableObject, key, out value);\r
+                    }\r
+                }\r
+                \r
+                if (success) {\r
+                    return new ViewDataInfo() {\r
+                        Container = indexableObject,\r
+                        Value = value\r
+                    };\r
+                }\r
+\r
+                return null;\r
+            }\r
+\r
+            private static ViewDataInfo GetPropertyValue(object container, string propertyName) {\r
+                // This method handles one "segment" of a complex property expression\r
+\r
+                // First, we try to evaluate the property based on its indexer\r
+                ViewDataInfo value = GetIndexedPropertyValue(container, propertyName);\r
+                if (value != null) {\r
+                    return value;\r
+                }\r
+\r
+                // If the indexer didn't return anything useful, continue...\r
+\r
+                // If the container is a ViewDataDictionary then treat its Model property\r
+                // as the container instead of the ViewDataDictionary itself.\r
+                ViewDataDictionary vdd = container as ViewDataDictionary;\r
+                if (vdd != null) {\r
+                    container = vdd.Model;\r
+                }\r
+\r
+                // If the container is null, we're out of options\r
+                if (container == null) {\r
+                    return null;\r
+                }\r
+\r
+                // Second, we try to use PropertyDescriptors and treat the expression as a property name\r
+                PropertyDescriptor descriptor = TypeDescriptor.GetProperties(container).Find(propertyName, true);\r
+                if (descriptor == null) {\r
+                    return null;\r
+                }\r
+\r
+                return new ViewDataInfo(() => descriptor.GetValue(container)) {\r
+                    Container = container,\r
+                    PropertyDescriptor = descriptor\r
+                };\r
+            }\r
+\r
+            private struct ExpressionPair {\r
+                public readonly string Left;\r
+                public readonly string Right;\r
+\r
+                public ExpressionPair(string left, string right) {\r
+                    Left = left;\r
+                    Right = right;\r
+                }\r
+            }\r
+        }\r
+\r
+        #region IEnumerable Members\r
+        IEnumerator IEnumerable.GetEnumerator() {\r
+            return ((IEnumerable)_innerDictionary).GetEnumerator();\r
+        }\r
+        #endregion\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewDataDictionary`1.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewDataDictionary`1.cs
new file mode 100644 (file)
index 0000000..a0d09f2
--- /dev/null
@@ -0,0 +1,66 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+\r
+    public class ViewDataDictionary<TModel> : ViewDataDictionary {\r
+        public ViewDataDictionary() :\r
+            base(default(TModel)) {\r
+        }\r
+\r
+        public ViewDataDictionary(TModel model) :\r
+            base(model) {\r
+        }\r
+\r
+        public ViewDataDictionary(ViewDataDictionary viewDataDictionary) :\r
+            base(viewDataDictionary) {\r
+        }\r
+\r
+        public new TModel Model {\r
+            get {\r
+                return (TModel)base.Model;\r
+            }\r
+            set {\r
+                SetModel(value);\r
+            }\r
+        }\r
+\r
+        public override ModelMetadata ModelMetadata {\r
+            get {\r
+                ModelMetadata result = base.ModelMetadata;\r
+                if (result == null) {\r
+                    result = base.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TModel));\r
+                }\r
+                return result;\r
+            }\r
+            set {\r
+                base.ModelMetadata = value;\r
+            }\r
+        }\r
+\r
+        protected override void SetModel(object value) {\r
+            bool castWillSucceed = TypeHelpers.IsCompatibleObject<TModel>(value);\r
+\r
+            if (castWillSucceed) {\r
+                base.SetModel((TModel)value);\r
+            }\r
+            else {\r
+                InvalidOperationException exception = (value != null)\r
+                    ? Error.ViewDataDictionary_WrongTModelType(value.GetType(), typeof(TModel))\r
+                    : Error.ViewDataDictionary_ModelCannotBeNull(typeof(TModel));\r
+                throw exception;\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewDataInfo.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewDataInfo.cs
new file mode 100644 (file)
index 0000000..8cc480b
--- /dev/null
@@ -0,0 +1,55 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.ComponentModel;\r
+\r
+    public class ViewDataInfo {\r
+\r
+        private object _value;\r
+        private Func<object> _valueAccessor;\r
+\r
+        public ViewDataInfo() {\r
+        }\r
+\r
+        public ViewDataInfo(Func<object> valueAccessor) {\r
+            _valueAccessor = valueAccessor;\r
+        }\r
+\r
+        public object Container {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public PropertyDescriptor PropertyDescriptor {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public object Value {\r
+            get {\r
+                if (_valueAccessor != null) {\r
+                    _value = _valueAccessor();\r
+                    _valueAccessor = null;\r
+                }\r
+\r
+                return _value;\r
+            }\r
+            set {\r
+                _value = value;\r
+                _valueAccessor = null;\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewEngineCollection.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewEngineCollection.cs
new file mode 100644 (file)
index 0000000..1fce965
--- /dev/null
@@ -0,0 +1,95 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Collections.Generic;\r
+    using System.Collections.ObjectModel;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public class ViewEngineCollection : Collection<IViewEngine> {\r
+\r
+        public ViewEngineCollection() {\r
+        }\r
+\r
+        public ViewEngineCollection(IList<IViewEngine> list)\r
+            : base(list) {\r
+        }\r
+\r
+        protected override void InsertItem(int index, IViewEngine item) {\r
+            if (item == null) {\r
+                throw new ArgumentNullException("item");\r
+            }\r
+            base.InsertItem(index, item);\r
+        }\r
+\r
+        protected override void SetItem(int index, IViewEngine item) {\r
+            if (item == null) {\r
+                throw new ArgumentNullException("item");\r
+            }\r
+            base.SetItem(index, item);\r
+        }\r
+\r
+        private ViewEngineResult Find(Func<IViewEngine, ViewEngineResult> cacheLocator, Func<IViewEngine, ViewEngineResult> locator) {\r
+            ViewEngineResult result;\r
+\r
+            foreach (IViewEngine engine in Items) {\r
+                if (engine != null) {\r
+                    result = cacheLocator(engine);\r
+\r
+                    if (result.View != null) {\r
+                        return result;\r
+                    }\r
+                }\r
+            }\r
+\r
+            List<string> searched = new List<string>();\r
+\r
+            foreach (IViewEngine engine in Items) {\r
+                if (engine != null) {\r
+                    result = locator(engine);\r
+\r
+                    if (result.View != null) {\r
+                        return result;\r
+                    }\r
+\r
+                    searched.AddRange(result.SearchedLocations);\r
+                }\r
+            }\r
+\r
+            return new ViewEngineResult(searched);\r
+        }\r
+\r
+        public virtual ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName) {\r
+            if (controllerContext == null) {\r
+                throw new ArgumentNullException("controllerContext");\r
+            }\r
+            if (string.IsNullOrEmpty(partialViewName)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "partialViewName");\r
+            }\r
+            Func<IViewEngine, ViewEngineResult> cacheLocator = e => e.FindPartialView(controllerContext, partialViewName, true);\r
+            Func<IViewEngine, ViewEngineResult> locator = e => e.FindPartialView(controllerContext, partialViewName, false);\r
+            return Find(cacheLocator, locator);\r
+        }\r
+\r
+        public virtual ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName) {\r
+            if (controllerContext == null) {\r
+                throw new ArgumentNullException("controllerContext");\r
+            }\r
+            if (string.IsNullOrEmpty(viewName)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "viewName");\r
+            }\r
+            Func<IViewEngine, ViewEngineResult> cacheLocator = e => e.FindView(controllerContext, viewName, masterName, true);\r
+            Func<IViewEngine, ViewEngineResult> locator = e => e.FindView(controllerContext, viewName, masterName, false);\r
+            return Find(cacheLocator, locator);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewEngineResult.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewEngineResult.cs
new file mode 100644 (file)
index 0000000..97a1b31
--- /dev/null
@@ -0,0 +1,54 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+\r
+    public class ViewEngineResult {\r
+\r
+        public ViewEngineResult(IEnumerable<string> searchedLocations) {\r
+            if (searchedLocations == null) {\r
+                throw new ArgumentNullException("searchedLocations");\r
+            }\r
+\r
+            SearchedLocations = searchedLocations;\r
+        }\r
+\r
+        public ViewEngineResult(IView view, IViewEngine viewEngine) {\r
+            if (view == null) {\r
+                throw new ArgumentNullException("view");\r
+            }\r
+            if (viewEngine == null) {\r
+                throw new ArgumentNullException("viewEngine");\r
+            }\r
+\r
+            View = view;\r
+            ViewEngine = viewEngine;\r
+        }\r
+\r
+        public IEnumerable<string> SearchedLocations {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public IView View {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public IViewEngine ViewEngine {\r
+            get;\r
+            private set;\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewEngines.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewEngines.cs
new file mode 100644 (file)
index 0000000..af4c016
--- /dev/null
@@ -0,0 +1,27 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+\r
+    public static class ViewEngines {\r
+\r
+        private readonly static ViewEngineCollection _engines = new ViewEngineCollection {\r
+            new WebFormViewEngine() \r
+        };\r
+\r
+        public static ViewEngineCollection Engines {\r
+            get {\r
+                return _engines;\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewMasterPage.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewMasterPage.cs
new file mode 100644 (file)
index 0000000..837dabf
--- /dev/null
@@ -0,0 +1,77 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Globalization;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.UI;\r
+\r
+    public class ViewMasterPage : MasterPage {\r
+        public AjaxHelper<object> Ajax {\r
+            get {\r
+                return ViewPage.Ajax;\r
+            }\r
+        }\r
+\r
+        public HtmlHelper<object> Html {\r
+            get {\r
+                return ViewPage.Html;\r
+            }\r
+        }\r
+\r
+        public object Model {\r
+            get {\r
+                return ViewData.Model;\r
+            }\r
+        }\r
+\r
+        public TempDataDictionary TempData {\r
+            get {\r
+                return ViewPage.TempData;\r
+            }\r
+        }\r
+\r
+        public UrlHelper Url {\r
+            get {\r
+                return ViewPage.Url;\r
+            }\r
+        }\r
+\r
+        public ViewContext ViewContext {\r
+            get {\r
+                return ViewPage.ViewContext;\r
+            }\r
+        }\r
+\r
+        public ViewDataDictionary ViewData {\r
+            get {\r
+                return ViewPage.ViewData;\r
+            }\r
+        }\r
+\r
+        internal ViewPage ViewPage {\r
+            get {\r
+                ViewPage viewPage = Page as ViewPage;\r
+                if (viewPage == null) {\r
+                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentUICulture, MvcResources.ViewMasterPage_RequiresViewPage));\r
+                }\r
+                return viewPage;\r
+            }\r
+        }\r
+\r
+        public HtmlTextWriter Writer {\r
+            get {\r
+                return ViewPage.Writer;\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewMasterPage`1.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewMasterPage`1.cs
new file mode 100644 (file)
index 0000000..c3c95d1
--- /dev/null
@@ -0,0 +1,53 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+\r
+    public class ViewMasterPage<TModel> : ViewMasterPage {\r
+        private AjaxHelper<TModel> _ajaxHelper;\r
+        private HtmlHelper<TModel> _htmlHelper;\r
+        private ViewDataDictionary<TModel> _viewData;\r
+\r
+        public new AjaxHelper<TModel> Ajax {\r
+            get {\r
+                if (_ajaxHelper == null) {\r
+                    _ajaxHelper = new AjaxHelper<TModel>(ViewContext, ViewPage);\r
+                }\r
+                return _ajaxHelper;\r
+            }\r
+        }\r
+\r
+        public new HtmlHelper<TModel> Html {\r
+            get {\r
+                if (_htmlHelper == null) {\r
+                    _htmlHelper = new HtmlHelper<TModel>(ViewContext, ViewPage);\r
+                }\r
+                return _htmlHelper;\r
+            }\r
+        }\r
+\r
+        public new TModel Model {\r
+            get {\r
+                return ViewData.Model;\r
+            }\r
+        }\r
+\r
+        public new ViewDataDictionary<TModel> ViewData {\r
+            get {\r
+                if (_viewData == null) {\r
+                    _viewData = new ViewDataDictionary<TModel>(ViewPage.ViewData);\r
+                }\r
+                return _viewData;\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewPage.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewPage.cs
new file mode 100644 (file)
index 0000000..6e1891c
--- /dev/null
@@ -0,0 +1,378 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.IO;\r
+    using System.Text;\r
+    using System.Web;\r
+    using System.Web.UI;\r
+\r
+    [FileLevelControlBuilder(typeof(ViewPageControlBuilder))]\r
+    public class ViewPage : Page, IViewDataContainer {\r
+\r
+        private string _masterLocation;\r
+        [ThreadStatic]\r
+        private static int _nextId;\r
+        private ViewDataDictionary _viewData;\r
+\r
+        public AjaxHelper<object> Ajax {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public HtmlHelper<object> Html {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public string MasterLocation {\r
+            get {\r
+                return _masterLocation ?? String.Empty;\r
+            }\r
+            set {\r
+                _masterLocation = value;\r
+            }\r
+        }\r
+\r
+        public object Model {\r
+            get {\r
+                return ViewData.Model;\r
+            }\r
+        }\r
+\r
+        public TempDataDictionary TempData {\r
+            get {\r
+                return ViewContext.TempData;\r
+            }\r
+        }\r
+\r
+        public UrlHelper Url {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public ViewContext ViewContext {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly",\r
+            Justification = "This is the mechanism by which the ViewPage gets its ViewDataDictionary object.")]\r
+        public ViewDataDictionary ViewData {\r
+            get {\r
+                if (_viewData == null) {\r
+                    SetViewData(new ViewDataDictionary());\r
+                }\r
+                return _viewData;\r
+            }\r
+            set {\r
+                SetViewData(value);\r
+            }\r
+        }\r
+\r
+        public HtmlTextWriter Writer {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public virtual void InitHelpers() {\r
+            Ajax = new AjaxHelper<object>(ViewContext, this);\r
+            Html = new HtmlHelper<object>(ViewContext, this);\r
+            Url = new UrlHelper(ViewContext.RequestContext);\r
+        }\r
+\r
+        internal static string NextId() {\r
+            return (++_nextId).ToString(CultureInfo.InvariantCulture);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")]\r
+        protected override void OnPreInit(EventArgs e) {\r
+            base.OnPreInit(e);\r
+\r
+            if (!String.IsNullOrEmpty(MasterLocation)) {\r
+                MasterPageFile = MasterLocation;\r
+            }\r
+        }\r
+\r
+        public override void ProcessRequest(HttpContext context) {\r
+            // Tracing requires IDs to be unique.\r
+            ID = NextId();\r
+\r
+            base.ProcessRequest(context);\r
+        }\r
+\r
+        protected override void Render(HtmlTextWriter writer) {\r
+            Writer = writer;\r
+            try {\r
+                base.Render(writer);\r
+            }\r
+            finally {\r
+                Writer = null;\r
+            }\r
+        }\r
+\r
+        public virtual void RenderView(ViewContext viewContext) {\r
+            ViewContext = viewContext;\r
+            InitHelpers();\r
+\r
+            bool needServerExecute = false;\r
+\r
+            SwitchWriter switchWriter = viewContext.HttpContext.Response.Output as SwitchWriter;\r
+            if (switchWriter == null) {\r
+                switchWriter = new SwitchWriter();\r
+                needServerExecute = true;\r
+            }\r
+\r
+            using (switchWriter.Scope(viewContext.Writer)) {\r
+                if (needServerExecute) {\r
+                    // It's safe to reset the _nextId within a Server.Execute() since it pushes a new TraceContext onto\r
+                    // the stack, so there won't be an ID conflict.\r
+                    int originalNextId = _nextId;\r
+                    try {\r
+                        _nextId = 0;\r
+                        viewContext.HttpContext.Server.Execute(HttpHandlerUtil.WrapForServerExecute(this), switchWriter, true /* preserveForm */);\r
+                    }\r
+                    finally {\r
+                        // Restore the original _nextId in case this isn't actually the outermost view, since resetting\r
+                        // the _nextId may now cause trace ID conflicts in the outer view.\r
+                        _nextId = originalNextId;\r
+                    }\r
+                }\r
+                else {\r
+                    ProcessRequest(HttpContext.Current);\r
+                }\r
+            }\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "textWriter",\r
+            Justification = "This method existed in MVC 1.0 and has been deprecated.")]\r
+        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic",\r
+            Justification = "This method existed in MVC 1.0 and has been deprecated.")]\r
+        [Obsolete("The TextWriter is now provided by the ViewContext object passed to the RenderView method.", true /* error */)]\r
+        public void SetTextWriter(TextWriter textWriter) {\r
+            // this is now a no-op\r
+        }\r
+\r
+        protected virtual void SetViewData(ViewDataDictionary viewData) {\r
+            _viewData = viewData;\r
+        }\r
+\r
+        internal class SwitchWriter : TextWriter {\r
+            public SwitchWriter()\r
+                : base(CultureInfo.CurrentCulture) {\r
+            }\r
+\r
+            public override Encoding Encoding {\r
+                get {\r
+                    return InnerWriter.Encoding;\r
+                }\r
+            }\r
+\r
+            public override IFormatProvider FormatProvider {\r
+                get {\r
+                    return InnerWriter.FormatProvider;\r
+                }\r
+            }\r
+\r
+            internal TextWriter InnerWriter {\r
+                get;\r
+                set;\r
+            }\r
+\r
+            public override string NewLine {\r
+                get {\r
+                    return InnerWriter.NewLine;\r
+                }\r
+                set {\r
+                    InnerWriter.NewLine = value;\r
+                }\r
+            }\r
+\r
+            public override void Close() {\r
+                InnerWriter.Close();\r
+            }\r
+\r
+            public override void Flush() {\r
+                InnerWriter.Flush();\r
+            }\r
+\r
+            public IDisposable Scope(TextWriter writer) {\r
+                WriterScope scope = new WriterScope(this, InnerWriter);\r
+\r
+                if (writer != this) {\r
+                    InnerWriter = writer;\r
+                }\r
+\r
+                return scope;\r
+            }\r
+\r
+            public override void Write(bool value) {\r
+                InnerWriter.Write(value);\r
+            }\r
+\r
+            public override void Write(char value) {\r
+                InnerWriter.Write(value);\r
+            }\r
+\r
+            public override void Write(char[] buffer) {\r
+                InnerWriter.Write(buffer);\r
+            }\r
+\r
+            public override void Write(char[] buffer, int index, int count) {\r
+                InnerWriter.Write(buffer, index, count);\r
+            }\r
+\r
+            public override void Write(decimal value) {\r
+                InnerWriter.Write(value);\r
+            }\r
+\r
+            public override void Write(double value) {\r
+                InnerWriter.Write(value);\r
+            }\r
+\r
+            public override void Write(float value) {\r
+                InnerWriter.Write(value);\r
+            }\r
+\r
+            public override void Write(int value) {\r
+                InnerWriter.Write(value);\r
+            }\r
+\r
+            public override void Write(long value) {\r
+                InnerWriter.Write(value);\r
+            }\r
+\r
+            public override void Write(object value) {\r
+                InnerWriter.Write(value);\r
+            }\r
+\r
+            public override void Write(string format, object arg0) {\r
+                InnerWriter.Write(format, arg0);\r
+            }\r
+\r
+            public override void Write(string format, object arg0, object arg1) {\r
+                InnerWriter.Write(format, arg0, arg1);\r
+            }\r
+\r
+            public override void Write(string format, object arg0, object arg1, object arg2) {\r
+                InnerWriter.Write(format, arg0, arg1, arg2);\r
+            }\r
+\r
+            public override void Write(string format, params object[] arg) {\r
+                InnerWriter.Write(format, arg);\r
+            }\r
+\r
+            public override void Write(string value) {\r
+                InnerWriter.Write(value);\r
+            }\r
+\r
+            public override void Write(uint value) {\r
+                InnerWriter.Write(value);\r
+            }\r
+\r
+            public override void Write(ulong value) {\r
+                InnerWriter.Write(value);\r
+            }\r
+\r
+            public override void WriteLine() {\r
+                InnerWriter.WriteLine();\r
+            }\r
+\r
+            public override void WriteLine(bool value) {\r
+                InnerWriter.WriteLine(value);\r
+            }\r
+\r
+            public override void WriteLine(char value) {\r
+                InnerWriter.WriteLine(value);\r
+            }\r
+\r
+            public override void WriteLine(char[] buffer) {\r
+                InnerWriter.WriteLine(buffer);\r
+            }\r
+\r
+            public override void WriteLine(char[] buffer, int index, int count) {\r
+                InnerWriter.WriteLine(buffer, index, count);\r
+            }\r
+\r
+            public override void WriteLine(decimal value) {\r
+                InnerWriter.WriteLine(value);\r
+            }\r
+\r
+            public override void WriteLine(double value) {\r
+                InnerWriter.WriteLine(value);\r
+            }\r
+\r
+            public override void WriteLine(float value) {\r
+                InnerWriter.WriteLine(value);\r
+            }\r
+\r
+            public override void WriteLine(int value) {\r
+                InnerWriter.WriteLine(value);\r
+            }\r
+\r
+            public override void WriteLine(long value) {\r
+                InnerWriter.WriteLine(value);\r
+            }\r
+\r
+            public override void WriteLine(object value) {\r
+                InnerWriter.WriteLine(value);\r
+            }\r
+\r
+            public override void WriteLine(string format, object arg0) {\r
+                InnerWriter.WriteLine(format, arg0);\r
+            }\r
+\r
+            public override void WriteLine(string format, object arg0, object arg1) {\r
+                InnerWriter.WriteLine(format, arg0, arg1);\r
+            }\r
+\r
+            public override void WriteLine(string format, object arg0, object arg1, object arg2) {\r
+                InnerWriter.WriteLine(format, arg0, arg1, arg2);\r
+            }\r
+\r
+            public override void WriteLine(string format, params object[] arg) {\r
+                InnerWriter.WriteLine(format, arg);\r
+            }\r
+\r
+            public override void WriteLine(string value) {\r
+                InnerWriter.WriteLine(value);\r
+            }\r
+\r
+            public override void WriteLine(uint value) {\r
+                InnerWriter.WriteLine(value);\r
+            }\r
+\r
+            public override void WriteLine(ulong value) {\r
+                InnerWriter.WriteLine(value);\r
+            }\r
+\r
+            private sealed class WriterScope : IDisposable {\r
+                private SwitchWriter _switchWriter;\r
+                private TextWriter _writerToRestore;\r
+\r
+                public WriterScope(SwitchWriter switchWriter, TextWriter writerToRestore) {\r
+                    _switchWriter = switchWriter;\r
+                    _writerToRestore = writerToRestore;\r
+                }\r
+\r
+                public void Dispose() {\r
+                    _switchWriter.InnerWriter = _writerToRestore;\r
+                }\r
+            }\r
+\r
+        }\r
+\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewPageControlBuilder.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewPageControlBuilder.cs
new file mode 100644 (file)
index 0000000..cf494c2
--- /dev/null
@@ -0,0 +1,36 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.CodeDom;\r
+    using System.Web.UI;\r
+\r
+    internal sealed class ViewPageControlBuilder : FileLevelPageControlBuilder {\r
+        public string PageBaseType {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public override void ProcessGeneratedCode(\r
+            CodeCompileUnit codeCompileUnit,\r
+            CodeTypeDeclaration baseType,\r
+            CodeTypeDeclaration derivedType,\r
+            CodeMemberMethod buildMethod,\r
+            CodeMemberMethod dataBindingMethod) {\r
+\r
+            // If we find got a base class string, use it\r
+            if (PageBaseType != null) {\r
+                derivedType.BaseTypes[0] = new CodeTypeReference(PageBaseType);\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewPage`1.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewPage`1.cs
new file mode 100644 (file)
index 0000000..3f55539
--- /dev/null
@@ -0,0 +1,62 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Diagnostics.CodeAnalysis;\r
+\r
+    public class ViewPage<TModel> : ViewPage {\r
+\r
+        private ViewDataDictionary<TModel> _viewData;\r
+\r
+        public new AjaxHelper<TModel> Ajax {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public new HtmlHelper<TModel> Html {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public new TModel Model {\r
+            get {\r
+                return ViewData.Model;\r
+            }\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]\r
+        public new ViewDataDictionary<TModel> ViewData {\r
+            get {\r
+                if (_viewData == null) {\r
+                    SetViewData(new ViewDataDictionary<TModel>());\r
+                }\r
+                return _viewData;\r
+            }\r
+            set {\r
+                SetViewData(value);\r
+            }\r
+        }\r
+\r
+        public override void InitHelpers() {\r
+            base.InitHelpers();\r
+\r
+            Ajax = new AjaxHelper<TModel>(ViewContext, this);\r
+            Html = new HtmlHelper<TModel>(ViewContext, this);\r
+        }\r
+\r
+        protected override void SetViewData(ViewDataDictionary viewData) {\r
+            _viewData = new ViewDataDictionary<TModel>(viewData);\r
+\r
+            base.SetViewData(_viewData);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewResult.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewResult.cs
new file mode 100644 (file)
index 0000000..49b8a85
--- /dev/null
@@ -0,0 +1,47 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Globalization;\r
+    using System.Text;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public class ViewResult : ViewResultBase {\r
+        private string _masterName;\r
+\r
+        public string MasterName {\r
+            get {\r
+                return _masterName ?? String.Empty;\r
+            }\r
+            set {\r
+                _masterName = value;\r
+            }\r
+        }\r
+\r
+        protected override ViewEngineResult FindView(ControllerContext context) {\r
+            ViewEngineResult result = ViewEngineCollection.FindView(context, ViewName, MasterName);\r
+            if (result.View != null) {\r
+                return result;\r
+            }\r
+\r
+            // we need to generate an exception containing all the locations we searched\r
+            StringBuilder locationsText = new StringBuilder();\r
+            foreach (string location in result.SearchedLocations) {\r
+                locationsText.AppendLine();\r
+                locationsText.Append(location);\r
+            }\r
+            throw new InvalidOperationException(String.Format(CultureInfo.CurrentUICulture,\r
+                MvcResources.Common_ViewNotFound, ViewName, locationsText));\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewResultBase.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewResultBase.cs
new file mode 100644 (file)
index 0000000..c4fc2cc
--- /dev/null
@@ -0,0 +1,103 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.IO;\r
+\r
+    public abstract class ViewResultBase : ActionResult {\r
+        private TempDataDictionary _tempData;\r
+        private ViewDataDictionary _viewData;\r
+        private ViewEngineCollection _viewEngineCollection;\r
+        private string _viewName;\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly",\r
+            Justification = "This entire type is meant to be mutable.")]\r
+        public TempDataDictionary TempData {\r
+            get {\r
+                if (_tempData == null) {\r
+                    _tempData = new TempDataDictionary();\r
+                }\r
+                return _tempData;\r
+            }\r
+            set {\r
+                _tempData = value;\r
+            }\r
+        }\r
+\r
+        public IView View {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly",\r
+            Justification = "This entire type is meant to be mutable.")]\r
+        public ViewDataDictionary ViewData {\r
+            get {\r
+                if (_viewData == null) {\r
+                    _viewData = new ViewDataDictionary();\r
+                }\r
+                return _viewData;\r
+            }\r
+            set {\r
+                _viewData = value;\r
+            }\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly",\r
+            Justification = "This entire type is meant to be mutable.")]\r
+        public ViewEngineCollection ViewEngineCollection {\r
+            get {\r
+                return _viewEngineCollection ?? ViewEngines.Engines;\r
+            }\r
+            set {\r
+                _viewEngineCollection = value;\r
+            }\r
+        }\r
+\r
+        public string ViewName {\r
+            get {\r
+                return _viewName ?? String.Empty;\r
+            }\r
+            set {\r
+                _viewName = value;\r
+            }\r
+        }\r
+\r
+        public override void ExecuteResult(ControllerContext context) {\r
+            if (context == null) {\r
+                throw new ArgumentNullException("context");\r
+            }\r
+            if (String.IsNullOrEmpty(ViewName)) {\r
+                ViewName = context.RouteData.GetRequiredString("action");\r
+            }\r
+\r
+            ViewEngineResult result = null;\r
+\r
+            if (View == null) {\r
+                result = FindView(context);\r
+                View = result.View;\r
+            }\r
+\r
+            TextWriter writer = context.HttpContext.Response.Output;\r
+            ViewContext viewContext = new ViewContext(context, View, ViewData, TempData, writer);\r
+            View.Render(viewContext, writer);\r
+\r
+            if (result != null) {\r
+                result.ViewEngine.ReleaseView(context, View);\r
+            }\r
+        }\r
+\r
+        protected abstract ViewEngineResult FindView(ControllerContext context);\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewTemplateUserControl.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewTemplateUserControl.cs
new file mode 100644 (file)
index 0000000..3ccc4fb
--- /dev/null
@@ -0,0 +1,15 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    public class ViewTemplateUserControl : ViewTemplateUserControl<object> { }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewTemplateUserControl`1.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewTemplateUserControl`1.cs
new file mode 100644 (file)
index 0000000..f2ae5db
--- /dev/null
@@ -0,0 +1,19 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    public class ViewTemplateUserControl<TModel> : ViewUserControl<TModel> {\r
+        protected string FormattedModelValue {\r
+            get { return ViewData.TemplateInfo.FormattedModelValue.ToString(); }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewType.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewType.cs
new file mode 100644 (file)
index 0000000..39afcc9
--- /dev/null
@@ -0,0 +1,32 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.ComponentModel;\r
+    using System.Web.UI;\r
+\r
+    [ControlBuilder(typeof(ViewTypeControlBuilder))]\r
+    [NonVisualControl]\r
+    public class ViewType : Control {\r
+        private string _typeName;\r
+\r
+        [DefaultValue("")]\r
+        public string TypeName {\r
+            get {\r
+                return _typeName ?? String.Empty;\r
+            }\r
+            set {\r
+                _typeName = value;\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewTypeControlBuilder.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewTypeControlBuilder.cs
new file mode 100644 (file)
index 0000000..0a30653
--- /dev/null
@@ -0,0 +1,39 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.CodeDom;\r
+    using System.Collections;\r
+    using System.Web.UI;\r
+\r
+    internal sealed class ViewTypeControlBuilder : ControlBuilder {\r
+        private string _typeName;\r
+\r
+        public override void Init(TemplateParser parser, ControlBuilder parentBuilder, Type type, string tagName, string id, IDictionary attribs) {\r
+            base.Init(parser, parentBuilder, type, tagName, id, attribs);\r
+\r
+            _typeName = (string)attribs["typename"];\r
+        }\r
+\r
+        public override void ProcessGeneratedCode(\r
+            CodeCompileUnit codeCompileUnit,\r
+            CodeTypeDeclaration baseType,\r
+            CodeTypeDeclaration derivedType,\r
+            CodeMemberMethod buildMethod,\r
+            CodeMemberMethod dataBindingMethod) {\r
+\r
+            // Override the view's base type with the explicit base type\r
+            derivedType.BaseTypes[0] = new CodeTypeReference(_typeName);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewTypeParserFilter.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewTypeParserFilter.cs
new file mode 100644 (file)
index 0000000..4fb159a
--- /dev/null
@@ -0,0 +1,156 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections;\r
+    using System.Web.UI;\r
+\r
+    internal class ViewTypeParserFilter : PageParserFilter {\r
+\r
+        private string _viewBaseType;\r
+        private DirectiveType _directiveType = DirectiveType.Unknown;\r
+        private bool _viewTypeControlAdded;\r
+\r
+        public override void PreprocessDirective(string directiveName, IDictionary attributes) {\r
+            base.PreprocessDirective(directiveName, attributes);\r
+\r
+            string defaultBaseType = null;\r
+\r
+            // If we recognize the directive, keep track of what it was. If we don't recognize\r
+            // the directive then just stop.\r
+            switch (directiveName) {\r
+                case "page":\r
+                    _directiveType = DirectiveType.Page;\r
+                    defaultBaseType = typeof(ViewPage).FullName;\r
+                    break;\r
+                case "control":\r
+                    _directiveType = DirectiveType.UserControl;\r
+                    defaultBaseType = typeof(ViewUserControl).FullName;\r
+                    break;\r
+                case "master":\r
+                    _directiveType = DirectiveType.Master;\r
+                    defaultBaseType = typeof(ViewMasterPage).FullName;\r
+                    break;\r
+            }\r
+\r
+            if (_directiveType == DirectiveType.Unknown) {\r
+                // If we're processing an unknown directive (e.g. a register directive), stop processing\r
+                return;\r
+            }\r
+\r
+            // Look for an inherit attribute\r
+            string inherits = (string)attributes["inherits"];\r
+            if (!String.IsNullOrEmpty(inherits)) {\r
+                // If it doesn't look like a generic type, don't do anything special,\r
+                // and let the parser do its normal processing\r
+                if (IsGenericTypeString(inherits)) {\r
+                    // Remove the inherits attribute so the parser doesn't blow up\r
+                    attributes["inherits"] = defaultBaseType;\r
+\r
+                    // Remember the full type string so we can later give it to the ControlBuilder\r
+                    _viewBaseType = inherits;\r
+                }\r
+            }\r
+        }\r
+\r
+        private static bool IsGenericTypeString(string typeName) {\r
+            // Detect C# and VB generic syntax\r
+            // REVIEW: what about other languages?\r
+            return typeName.IndexOfAny(new char[] { '<', '(' }) >= 0;\r
+        }\r
+\r
+        public override void ParseComplete(ControlBuilder rootBuilder) {\r
+            base.ParseComplete(rootBuilder);\r
+\r
+            // If it's our page ControlBuilder, give it the base type string\r
+            ViewPageControlBuilder pageBuilder = rootBuilder as ViewPageControlBuilder;\r
+            if (pageBuilder != null) {\r
+                pageBuilder.PageBaseType = _viewBaseType;\r
+            }\r
+            ViewUserControlControlBuilder userControlBuilder = rootBuilder as ViewUserControlControlBuilder;\r
+            if (userControlBuilder != null) {\r
+                userControlBuilder.UserControlBaseType = _viewBaseType;\r
+            }\r
+        }\r
+\r
+        public override bool ProcessCodeConstruct(CodeConstructType codeType, string code) {\r
+            if (!_viewTypeControlAdded &&\r
+                _viewBaseType != null &&\r
+                _directiveType == DirectiveType.Master) {\r
+\r
+                // If we're dealing with a master page that needs to have its base type set, do it here.\r
+                // It's done by adding the ViewType control, which has a builder that sets the base type.\r
+\r
+                // The code currently assumes that the file in question contains a code snippet, since\r
+                // that's the item we key off of in order to know when to add the ViewType control.\r
+\r
+                Hashtable attribs = new Hashtable();\r
+                attribs["typename"] = _viewBaseType;\r
+                AddControl(typeof(ViewType), attribs);\r
+                _viewTypeControlAdded = true;\r
+            }\r
+\r
+            return base.ProcessCodeConstruct(codeType, code);\r
+        }\r
+\r
+        // Everything else in this class is unrelated to our 'inherits' handling.\r
+        // Since PageParserFilter blocks everything by default, we need to unblock it\r
+\r
+        public override bool AllowCode {\r
+            get {\r
+                return true;\r
+            }\r
+        }\r
+\r
+        public override bool AllowBaseType(Type baseType) {\r
+            return true;\r
+        }\r
+\r
+        public override bool AllowControl(Type controlType, ControlBuilder builder) {\r
+            return true;\r
+        }\r
+\r
+        public override bool AllowVirtualReference(string referenceVirtualPath, VirtualReferenceType referenceType) {\r
+            return true;\r
+        }\r
+\r
+        public override bool AllowServerSideInclude(string includeVirtualPath) {\r
+            return true;\r
+        }\r
+\r
+        public override int NumberOfControlsAllowed {\r
+            get {\r
+                return -1;\r
+            }\r
+        }\r
+\r
+        public override int NumberOfDirectDependenciesAllowed {\r
+            get {\r
+                return -1;\r
+            }\r
+        }\r
+\r
+        public override int TotalNumberOfDependenciesAllowed {\r
+            get {\r
+                return -1;\r
+            }\r
+        }\r
+\r
+        private enum DirectiveType {\r
+            Unknown,\r
+            Page,\r
+            UserControl,\r
+            Master,\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewUserControl.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewUserControl.cs
new file mode 100644 (file)
index 0000000..d1ec1e1
--- /dev/null
@@ -0,0 +1,200 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.ComponentModel;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.IO;\r
+    using System.Web.Mvc.Resources;\r
+    using System.Web.UI;\r
+\r
+    [FileLevelControlBuilder(typeof(ViewUserControlControlBuilder))]\r
+    public class ViewUserControl : UserControl, IViewDataContainer {\r
+        private AjaxHelper<object> _ajaxHelper;\r
+        private HtmlHelper<object> _htmlHelper;\r
+        private ViewContext _viewContext;\r
+        private ViewDataDictionary _viewData;\r
+        private string _viewDataKey;\r
+\r
+        public AjaxHelper<object> Ajax {\r
+            get {\r
+                if (_ajaxHelper == null) {\r
+                    _ajaxHelper = new AjaxHelper<object>(ViewContext, this);\r
+                }\r
+                return _ajaxHelper;\r
+            }\r
+        }\r
+\r
+        public HtmlHelper<object> Html {\r
+            get {\r
+                if (_htmlHelper == null) {\r
+                    _htmlHelper = new HtmlHelper<object>(ViewContext, this);\r
+                }\r
+                return _htmlHelper;\r
+            }\r
+        }\r
+\r
+        public object Model {\r
+            get {\r
+                return ViewData.Model;\r
+            }\r
+        }\r
+\r
+        public TempDataDictionary TempData {\r
+            get {\r
+                return ViewPage.TempData;\r
+            }\r
+        }\r
+\r
+        public UrlHelper Url {\r
+            get {\r
+                return ViewPage.Url;\r
+            }\r
+        }\r
+\r
+        [Browsable(false)]\r
+        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\r
+        public ViewContext ViewContext {\r
+            get {\r
+                return _viewContext ?? ViewPage.ViewContext;\r
+            }\r
+            set {\r
+                _viewContext = value;\r
+            }\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly",\r
+            Justification = "This is the mechanism by which the ViewUserControl gets its ViewDataDictionary object.")]\r
+        [Browsable(false)]\r
+        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\r
+        public ViewDataDictionary ViewData {\r
+            get {\r
+                EnsureViewData();\r
+                return _viewData;\r
+            }\r
+            set {\r
+                SetViewData(value);\r
+            }\r
+        }\r
+\r
+        [DefaultValue("")]\r
+        public string ViewDataKey {\r
+            get {\r
+                return _viewDataKey ?? String.Empty;\r
+            }\r
+            set {\r
+                _viewDataKey = value;\r
+            }\r
+        }\r
+\r
+        internal ViewPage ViewPage {\r
+            get {\r
+                ViewPage viewPage = Page as ViewPage;\r
+                if (viewPage == null) {\r
+                    throw new InvalidOperationException(MvcResources.ViewUserControl_RequiresViewPage);\r
+                }\r
+                return viewPage;\r
+            }\r
+        }\r
+\r
+        public HtmlTextWriter Writer {\r
+            get {\r
+                return ViewPage.Writer;\r
+            }\r
+        }\r
+\r
+        protected virtual void SetViewData(ViewDataDictionary viewData) {\r
+            _viewData = viewData;\r
+        }\r
+\r
+        protected void EnsureViewData() {\r
+            if (_viewData != null) {\r
+                return;\r
+            }\r
+\r
+            // Get the ViewData for this ViewUserControl, optionally using the specified ViewDataKey\r
+            IViewDataContainer vdc = GetViewDataContainer(this);\r
+            if (vdc == null) {\r
+                throw new InvalidOperationException(\r
+                    String.Format(\r
+                        CultureInfo.CurrentUICulture,\r
+                        MvcResources.ViewUserControl_RequiresViewDataProvider,\r
+                        AppRelativeVirtualPath));\r
+            }\r
+\r
+            ViewDataDictionary myViewData = vdc.ViewData;\r
+\r
+            // If we have a ViewDataKey, try to extract the ViewData from the dictionary, otherwise\r
+            // return the container's ViewData.\r
+            if (!String.IsNullOrEmpty(ViewDataKey)) {\r
+                object target = myViewData.Eval(ViewDataKey);\r
+                myViewData = target as ViewDataDictionary ?? new ViewDataDictionary(myViewData) { Model = target };\r
+            }\r
+\r
+            SetViewData(myViewData);\r
+        }\r
+\r
+        private static IViewDataContainer GetViewDataContainer(Control control) {\r
+            // Walk up the control hierarchy until we find someone that implements IViewDataContainer\r
+            while (control != null) {\r
+                control = control.Parent;\r
+                IViewDataContainer vdc = control as IViewDataContainer;\r
+                if (vdc != null) {\r
+                    return vdc;\r
+                }\r
+            }\r
+            return null;\r
+        }\r
+\r
+        public virtual void RenderView(ViewContext viewContext) {\r
+            ViewUserControlContainerPage containerPage = new ViewUserControlContainerPage(this);\r
+\r
+            RenderViewAndRestoreContentType(containerPage, viewContext);\r
+        }\r
+\r
+        internal static void RenderViewAndRestoreContentType(ViewPage containerPage, ViewContext viewContext) {\r
+            // We need to restore the Content-Type since Page.SetIntrinsics() will reset it. It's not possible\r
+            // to work around the call to SetIntrinsics() since the control's render method requires the\r
+            // containing page's Response property to be non-null, and SetIntrinsics() is the only way to set\r
+            // this.\r
+            string savedContentType = viewContext.HttpContext.Response.ContentType;\r
+            containerPage.RenderView(viewContext);\r
+            viewContext.HttpContext.Response.ContentType = savedContentType;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "textWriter",\r
+            Justification = "This method existed in MVC 1.0 and has been deprecated.")]\r
+        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic",\r
+            Justification = "This method existed in MVC 1.0 and has been deprecated.")]\r
+        [Obsolete("The TextWriter is now provided by the ViewContext object passed to the RenderView method.", true /* error */)]\r
+        public void SetTextWriter(TextWriter textWriter) {\r
+            // this is now a no-op\r
+        }\r
+\r
+        private sealed class ViewUserControlContainerPage : ViewPage {\r
+            private readonly ViewUserControl _userControl;\r
+\r
+            public ViewUserControlContainerPage(ViewUserControl userControl) {\r
+                _userControl = userControl;\r
+            }\r
+\r
+            public override void ProcessRequest(HttpContext context) {\r
+                _userControl.ID = ViewPage.NextId();\r
+                Controls.Add(_userControl);\r
+\r
+                base.ProcessRequest(context);\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewUserControlControlBuilder.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewUserControlControlBuilder.cs
new file mode 100644 (file)
index 0000000..8bd473a
--- /dev/null
@@ -0,0 +1,36 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.CodeDom;\r
+    using System.Web.UI;\r
+\r
+    internal sealed class ViewUserControlControlBuilder : FileLevelUserControlBuilder {\r
+        internal string UserControlBaseType {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public override void ProcessGeneratedCode(\r
+            CodeCompileUnit codeCompileUnit,\r
+            CodeTypeDeclaration baseType,\r
+            CodeTypeDeclaration derivedType,\r
+            CodeMemberMethod buildMethod,\r
+            CodeMemberMethod dataBindingMethod) {\r
+\r
+            // If we find got a base class string, use it\r
+            if (UserControlBaseType != null) {\r
+                derivedType.BaseTypes[0] = new CodeTypeReference(UserControlBaseType);\r
+            }\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewUserControl`1.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/ViewUserControl`1.cs
new file mode 100644 (file)
index 0000000..1a36f68
--- /dev/null
@@ -0,0 +1,62 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Diagnostics.CodeAnalysis;\r
+\r
+    public class ViewUserControl<TModel> : ViewUserControl {\r
+        private AjaxHelper<TModel> _ajaxHelper;\r
+        private HtmlHelper<TModel> _htmlHelper;\r
+        private ViewDataDictionary<TModel> _viewData;\r
+\r
+        public new AjaxHelper<TModel> Ajax {\r
+            get {\r
+                if (_ajaxHelper == null) {\r
+                    _ajaxHelper = new AjaxHelper<TModel>(ViewContext, this);\r
+                }\r
+                return _ajaxHelper;\r
+            }\r
+        }\r
+\r
+        public new HtmlHelper<TModel> Html {\r
+            get {\r
+                if (_htmlHelper == null) {\r
+                    _htmlHelper = new HtmlHelper<TModel>(ViewContext, this);\r
+                }\r
+                return _htmlHelper;\r
+            }\r
+        }\r
+\r
+        public new TModel Model {\r
+            get {\r
+                return ViewData.Model;\r
+            }            \r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]\r
+        public new ViewDataDictionary<TModel> ViewData {\r
+            get {\r
+                EnsureViewData();\r
+                return _viewData;\r
+            }\r
+            set {\r
+                SetViewData(value);\r
+            }\r
+        }\r
+\r
+        protected override void SetViewData(ViewDataDictionary viewData) {\r
+            _viewData = new ViewDataDictionary<TModel>(viewData);\r
+\r
+            base.SetViewData(_viewData);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/VirtualPathProviderViewEngine.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/VirtualPathProviderViewEngine.cs
new file mode 100644 (file)
index 0000000..5dd74ba
--- /dev/null
@@ -0,0 +1,266 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Collections.Generic;\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Globalization;\r
+    using System.Linq;\r
+    using System.Web;\r
+    using System.Web.Hosting;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public abstract class VirtualPathProviderViewEngine : IViewEngine {\r
+        // format is ":ViewCacheEntry:{cacheType}:{prefix}:{name}:{controllerName}:{areaName}:"\r
+        private const string _cacheKeyFormat = ":ViewCacheEntry:{0}:{1}:{2}:{3}:{4}:";\r
+        private const string _cacheKeyPrefix_Master = "Master";\r
+        private const string _cacheKeyPrefix_Partial = "Partial";\r
+        private const string _cacheKeyPrefix_View = "View";\r
+        private static readonly string[] _emptyLocations = new string[0];\r
+\r
+        private VirtualPathProvider _vpp;\r
+\r
+        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]\r
+        public string[] AreaMasterLocationFormats {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]\r
+        public string[] AreaPartialViewLocationFormats {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]\r
+        public string[] AreaViewLocationFormats {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]\r
+        public string[] MasterLocationFormats {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]\r
+        public string[] PartialViewLocationFormats {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        public IViewLocationCache ViewLocationCache {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]\r
+        public string[] ViewLocationFormats {\r
+            get;\r
+            set;\r
+        }\r
+\r
+        protected VirtualPathProvider VirtualPathProvider {\r
+            get {\r
+                if (_vpp == null) {\r
+                    _vpp = HostingEnvironment.VirtualPathProvider;\r
+                }\r
+                return _vpp;\r
+            }\r
+            set {\r
+                _vpp = value;\r
+            }\r
+        }\r
+\r
+        protected VirtualPathProviderViewEngine() {\r
+            if (HttpContext.Current == null || HttpContext.Current.IsDebuggingEnabled) {\r
+                ViewLocationCache = DefaultViewLocationCache.Null;\r
+            }\r
+            else {\r
+                ViewLocationCache = new DefaultViewLocationCache();\r
+            }\r
+        }\r
+\r
+        private string CreateCacheKey(string prefix, string name, string controllerName, string areaName) {\r
+            return String.Format(CultureInfo.InvariantCulture, _cacheKeyFormat,\r
+                GetType().AssemblyQualifiedName, prefix, name, controllerName, areaName);\r
+        }\r
+\r
+        protected abstract IView CreatePartialView(ControllerContext controllerContext, string partialPath);\r
+\r
+        protected abstract IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath);\r
+\r
+        protected virtual bool FileExists(ControllerContext controllerContext, string virtualPath) {\r
+            return VirtualPathProvider.FileExists(virtualPath);\r
+        }\r
+\r
+        public virtual ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache) {\r
+            if (controllerContext == null) {\r
+                throw new ArgumentNullException("controllerContext");\r
+            }\r
+            if (String.IsNullOrEmpty(partialViewName)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "partialViewName");\r
+            }\r
+\r
+            string[] searched;\r
+            string controllerName = controllerContext.RouteData.GetRequiredString("controller");\r
+            string partialPath = GetPath(controllerContext, PartialViewLocationFormats, AreaPartialViewLocationFormats, "PartialViewLocationFormats", partialViewName, controllerName, _cacheKeyPrefix_Partial, useCache, out searched);\r
+\r
+            if (String.IsNullOrEmpty(partialPath)) {\r
+                return new ViewEngineResult(searched);\r
+            }\r
+\r
+            return new ViewEngineResult(CreatePartialView(controllerContext, partialPath), this);\r
+        }\r
+\r
+        public virtual ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache) {\r
+            if (controllerContext == null) {\r
+                throw new ArgumentNullException("controllerContext");\r
+            }\r
+            if (String.IsNullOrEmpty(viewName)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "viewName");\r
+            }\r
+\r
+            string[] viewLocationsSearched;\r
+            string[] masterLocationsSearched;\r
+\r
+            string controllerName = controllerContext.RouteData.GetRequiredString("controller");\r
+            string viewPath = GetPath(controllerContext, ViewLocationFormats, AreaViewLocationFormats, "ViewLocationFormats", viewName, controllerName, _cacheKeyPrefix_View, useCache, out viewLocationsSearched);\r
+            string masterPath = GetPath(controllerContext, MasterLocationFormats, AreaMasterLocationFormats, "MasterLocationFormats", masterName, controllerName, _cacheKeyPrefix_Master, useCache, out masterLocationsSearched);\r
+\r
+            if (String.IsNullOrEmpty(viewPath) || (String.IsNullOrEmpty(masterPath) && !String.IsNullOrEmpty(masterName))) {\r
+                return new ViewEngineResult(viewLocationsSearched.Union(masterLocationsSearched));\r
+            }\r
+\r
+            return new ViewEngineResult(CreateView(controllerContext, viewPath, masterPath), this);\r
+        }\r
+\r
+        private string GetPath(ControllerContext controllerContext, string[] locations, string[] areaLocations, string locationsPropertyName, string name, string controllerName, string cacheKeyPrefix, bool useCache, out string[] searchedLocations) {\r
+            searchedLocations = _emptyLocations;\r
+\r
+            if (String.IsNullOrEmpty(name)) {\r
+                return String.Empty;\r
+            }\r
+\r
+            string areaName = AreaHelpers.GetAreaName(controllerContext.RouteData);\r
+            bool usingAreas = !String.IsNullOrEmpty(areaName);\r
+            List<ViewLocation> viewLocations = GetViewLocations(locations, (usingAreas) ? areaLocations : null);\r
+\r
+            if (viewLocations.Count == 0) {\r
+                throw new InvalidOperationException(String.Format(CultureInfo.CurrentUICulture,\r
+                    MvcResources.Common_PropertyCannotBeNullOrEmpty, locationsPropertyName));\r
+            }\r
+\r
+            bool nameRepresentsPath = IsSpecificPath(name);\r
+            string cacheKey = CreateCacheKey(cacheKeyPrefix, name, (nameRepresentsPath) ? String.Empty : controllerName, areaName);\r
+\r
+            if (useCache) {\r
+                return ViewLocationCache.GetViewLocation(controllerContext.HttpContext, cacheKey);\r
+            }\r
+\r
+            return (nameRepresentsPath) ?\r
+                GetPathFromSpecificName(controllerContext, name, cacheKey, ref searchedLocations) :\r
+                GetPathFromGeneralName(controllerContext, viewLocations, name, controllerName, areaName, cacheKey, ref searchedLocations);\r
+        }\r
+\r
+        private string GetPathFromGeneralName(ControllerContext controllerContext, List<ViewLocation> locations, string name, string controllerName, string areaName, string cacheKey, ref string[] searchedLocations) {\r
+            string result = String.Empty;\r
+            searchedLocations = new string[locations.Count];\r
+\r
+            for (int i = 0; i < locations.Count; i++) {\r
+                ViewLocation location = locations[i];\r
+                string virtualPath = location.Format(name, controllerName, areaName);\r
+\r
+                if (FileExists(controllerContext, virtualPath)) {\r
+                    searchedLocations = _emptyLocations;\r
+                    result = virtualPath;\r
+                    ViewLocationCache.InsertViewLocation(controllerContext.HttpContext, cacheKey, result);\r
+                    break;\r
+                }\r
+\r
+                searchedLocations[i] = virtualPath;\r
+            }\r
+\r
+            return result;\r
+        }\r
+\r
+        private string GetPathFromSpecificName(ControllerContext controllerContext, string name, string cacheKey, ref string[] searchedLocations) {\r
+            string result = name;\r
+\r
+            if (!FileExists(controllerContext, name)) {\r
+                result = String.Empty;\r
+                searchedLocations = new[] { name };\r
+            }\r
+\r
+            ViewLocationCache.InsertViewLocation(controllerContext.HttpContext, cacheKey, result);\r
+            return result;\r
+        }\r
+\r
+        private static List<ViewLocation> GetViewLocations(string[] viewLocationFormats, string[] areaViewLocationFormats) {\r
+            List<ViewLocation> allLocations = new List<ViewLocation>();\r
+\r
+            if (areaViewLocationFormats != null) {\r
+                foreach (string areaViewLocationFormat in areaViewLocationFormats) {\r
+                    allLocations.Add(new AreaAwareViewLocation(areaViewLocationFormat));\r
+                }\r
+            }\r
+\r
+            if (viewLocationFormats != null) {\r
+                foreach (string viewLocationFormat in viewLocationFormats) {\r
+                    allLocations.Add(new ViewLocation(viewLocationFormat));\r
+                }\r
+            }\r
+\r
+            return allLocations;\r
+        }\r
+\r
+        private static bool IsSpecificPath(string name) {\r
+            char c = name[0];\r
+            return (c == '~' || c == '/');\r
+        }\r
+\r
+        public virtual void ReleaseView(ControllerContext controllerContext, IView view) {\r
+            IDisposable disposable = view as IDisposable;\r
+            if (disposable != null) {\r
+                disposable.Dispose();\r
+            }\r
+        }\r
+\r
+        private class ViewLocation {\r
+\r
+            protected string _virtualPathFormatString;\r
+\r
+            public ViewLocation(string virtualPathFormatString) {\r
+                _virtualPathFormatString = virtualPathFormatString;\r
+            }\r
+\r
+            public virtual string Format(string viewName, string controllerName, string areaName) {\r
+                return String.Format(CultureInfo.InvariantCulture, _virtualPathFormatString, viewName, controllerName);\r
+            }\r
+\r
+        }\r
+\r
+        private class AreaAwareViewLocation : ViewLocation {\r
+\r
+            public AreaAwareViewLocation(string virtualPathFormatString)\r
+                : base(virtualPathFormatString) {\r
+            }\r
+\r
+            public override string Format(string viewName, string controllerName, string areaName) {\r
+                return String.Format(CultureInfo.InvariantCulture, _virtualPathFormatString, viewName, controllerName, areaName);\r
+            }\r
+\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/WebFormView.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/WebFormView.cs
new file mode 100644 (file)
index 0000000..7167d8c
--- /dev/null
@@ -0,0 +1,109 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System;\r
+    using System.Globalization;\r
+    using System.IO;\r
+    using System.Web.Mvc.Resources;\r
+\r
+    public class WebFormView : IView {\r
+\r
+        private IBuildManager _buildManager;\r
+\r
+        public WebFormView(string viewPath)\r
+            : this(viewPath, null) {\r
+        }\r
+\r
+        public WebFormView(string viewPath, string masterPath) {\r
+            if (String.IsNullOrEmpty(viewPath)) {\r
+                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "viewPath");\r
+            }\r
+\r
+            ViewPath = viewPath;\r
+            MasterPath = masterPath ?? String.Empty;\r
+        }\r
+\r
+        internal IBuildManager BuildManager {\r
+            get {\r
+                if (_buildManager == null) {\r
+                    _buildManager = new BuildManagerWrapper();\r
+                }\r
+                return _buildManager;\r
+            }\r
+            set {\r
+                _buildManager = value;\r
+            }\r
+        }\r
+\r
+        public string MasterPath {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public string ViewPath {\r
+            get;\r
+            private set;\r
+        }\r
+\r
+        public virtual void Render(ViewContext viewContext, TextWriter writer) {\r
+            if (viewContext == null) {\r
+                throw new ArgumentNullException("viewContext");\r
+            }\r
+\r
+            object viewInstance = BuildManager.CreateInstanceFromVirtualPath(ViewPath, typeof(object));\r
+            if (viewInstance == null) {\r
+                throw new InvalidOperationException(\r
+                    String.Format(\r
+                        CultureInfo.CurrentUICulture,\r
+                        MvcResources.WebFormViewEngine_ViewCouldNotBeCreated,\r
+                        ViewPath));\r
+            }\r
+\r
+            ViewPage viewPage = viewInstance as ViewPage;\r
+            if (viewPage != null) {\r
+                RenderViewPage(viewContext, viewPage);\r
+                return;\r
+            }\r
+\r
+            ViewUserControl viewUserControl = viewInstance as ViewUserControl;\r
+            if (viewUserControl != null) {\r
+                RenderViewUserControl(viewContext, viewUserControl);\r
+                return;\r
+            }\r
+\r
+            throw new InvalidOperationException(\r
+                String.Format(\r
+                    CultureInfo.CurrentUICulture,\r
+                    MvcResources.WebFormViewEngine_WrongViewBase,\r
+                    ViewPath));\r
+        }\r
+\r
+        private void RenderViewPage(ViewContext context, ViewPage page) {\r
+            if (!String.IsNullOrEmpty(MasterPath)) {\r
+                page.MasterLocation = MasterPath;\r
+            }\r
+\r
+            page.ViewData = context.ViewData;\r
+            page.RenderView(context);\r
+        }\r
+\r
+        private void RenderViewUserControl(ViewContext context, ViewUserControl control) {\r
+            if (!String.IsNullOrEmpty(MasterPath)) {\r
+                throw new InvalidOperationException(MvcResources.WebFormViewEngine_UserControlCannotHaveMaster);\r
+            }\r
+\r
+            control.ViewData = context.ViewData;\r
+            control.RenderView(context);\r
+        }\r
+    }\r
+}\r
diff --git a/mcs/class/System.Web.Mvc2/System.Web.Mvc/WebFormViewEngine.cs b/mcs/class/System.Web.Mvc2/System.Web.Mvc/WebFormViewEngine.cs
new file mode 100644 (file)
index 0000000..9f2d080
--- /dev/null
@@ -0,0 +1,98 @@
+/* ****************************************************************************\r
+ *\r
+ * Copyright (c) Microsoft Corporation. All rights reserved.\r
+ *\r
+ * This software is subject to the Microsoft Public License (Ms-PL). \r
+ * A copy of the license can be found in the license.htm file included \r
+ * in this distribution.\r
+ *\r
+ * You must not remove this notice, or any other, from this software.\r
+ *\r
+ * ***************************************************************************/\r
+\r
+namespace System.Web.Mvc {\r
+    using System.Diagnostics.CodeAnalysis;\r
+    using System.Net;\r
+    using System.Web;\r
+\r
+    public class WebFormViewEngine : VirtualPathProviderViewEngine {\r
+\r
+        private IBuildManager _buildManager;\r
+\r
+        public WebFormViewEngine() {\r
+            MasterLocationFormats = new[] {\r
+                "~/Views/{1}/{0}.master",\r
+                "~/Views/Shared/{0}.master"\r
+            };\r
+\r
+            AreaMasterLocationFormats = new[] {\r
+                "~/Areas/{2}/Views/{1}/{0}.master",\r
+                "~/Areas/{2}/Views/Shared/{0}.master",\r
+            };\r
+\r
+            ViewLocationFormats = new[] {\r
+                "~/Views/{1}/{0}.aspx",\r
+                "~/Views/{1}/{0}.ascx",\r
+                "~/Views/Shared/{0}.aspx",\r
+                "~/Views/Shared/{0}.ascx"\r
+            };\r
+\r
+            AreaViewLocationFormats = new[] {\r
+                "~/Areas/{2}/Views/{1}/{0}.aspx",\r
+                "~/Areas/{2}/Views/{1}/{0}.ascx",\r
+                "~/Areas/{2}/Views/Shared/{0}.aspx",\r
+                "~/Areas/{2}/Views/Shared/{0}.ascx",\r
+            };\r
+\r
+            PartialViewLocationFormats = ViewLocationFormats;\r
+            AreaPartialViewLocationFormats = AreaViewLocationFormats;\r
+        }\r
+\r
+        internal IBuildManager BuildManager {\r
+            get {\r
+                if (_buildManager == null) {\r
+                    _buildManager = new BuildManagerWrapper();\r
+                }\r
+                return _buildManager;\r
+            }\r
+            set {\r
+                _buildManager = value;\r
+            }\r
+        }\r
+\r
+        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) {\r
+            return new WebFormView(partialPath, null);\r
+        }\r
+\r
+        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) {\r
+            return new WebFormView(viewPath, masterPath);\r
+        }\r
+\r
+        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",\r
+            Justification = "Exceptions are interpreted as indicating that the file does not exist.")]\r
+        protected override bool FileExists(ControllerContext controllerContext, string virtualPath) {\r
+            try {\r
+                object viewInstance = BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(object));\r
+                return viewInstance != null;\r
+            }\r
+            catch (HttpException he) {\r
+                if (he is HttpParseException) {\r
+                    // The build manager found something, but instantiation failed due to a runtime lookup failure\r
+                    throw;\r
+                }\r
+\r
+                if (he.GetHttpCode() == (int)HttpStatusCode.NotFound) {\r
+                    // If BuildManager returns a 404 (Not Found) that means that a file did not exist.\r
+                    // If the view itself doesn't exist, then this method should report that rather than throw an exception.\r
+                    if (!base.FileExists(controllerContext, virtualPath)) {\r
+                        return false;\r
+                    }\r
+                }\r
+\r
+                // All other error codes imply other errors such as compilation or parsing errors\r
+                throw;\r
+            }\r
+        }\r
+\r
+    }\r
+}\r
index 44a1a6b4a0f81e8948c353b3e24e4d49f97f7aa7..a3f6b8668c688c1230c6565d09efd11164332079 100644 (file)
@@ -1,3 +1,12 @@
+2010-04-07  Marek Habersack  <mhabersack@novell.com>
+
+       * Makefile: moved App_* test resources to separate variables -
+       whatever is contained in those variables is preprocessed before
+       embedding as resource to include appropriate resource name prefix
+       (App_Code/, App_GlobalResources/ for now). This is used in WebTest
+       to automatically populate the relevant directories when running
+       the test suite.
+
 2010-02-18  Marek Habersack  <mhabersack@novell.com>
 
        * Makefile (TEST_RESOURCE_FILES): added
index 9cd3b8efc8a732204a90ee43ddd57254ac23c606..f4a69906008d8bcc3dc5642bfd610d69c6ea04da 100644 (file)
@@ -74,6 +74,16 @@ RESOURCE_FILES_2 = \
        System.Web.UI.WebControls/Menu.js
 
 OTHER_RES = $(RESOURCE_FILES_1)
+TEST_APP_CODE_FILES = \
+       Test/mainsoft/NunitWebResources/App_Code/EnumConverterControl.cs \
+       Test/mainsoft/NunitWebResources/App_Code/MyContainer.cs \
+       Test/mainsoft/NunitWebResources/App_Code/CustomCheckBoxColumn.cs
+
+TEST_APP_GLOBALRESOURCES_FILES = \
+       Test/mainsoft/NunitWebResources/App_GlobalResources/Common.resx \
+       Test/mainsoft/NunitWebResources/App_GlobalResources/Common.fr-FR.resx \
+       Test/mainsoft/NunitWebResources/App_GlobalResources/Resource1.resx
+
 TEST_RESOURCE_FILES = \
        Test/mainsoft/NunitWeb/NunitWeb/Resources/Global.asax \
        Test/mainsoft/NunitWeb/NunitWeb/Resources/My.ashx \
@@ -93,10 +103,6 @@ TEST_RESOURCE_FILES = \
        Test/mainsoft/NunitWeb/NunitWeb/Resources/test_map_07.sitemap \
        Test/mainsoft/NunitWeb/NunitWeb/Resources/test_map_08.sitemap \
        Test/mainsoft/NunitWeb/NunitWeb/Resources/test_map_09.sitemap \
-       Test/mainsoft/NunitWebResources/App_GlobalResources/Common.resx \
-       Test/mainsoft/NunitWebResources/App_GlobalResources/Common.fr-FR.resx \
-       Test/mainsoft/NunitWebResources/App_GlobalResources/Resource1.resx \
-       Test/mainsoft/NunitWebResources/App_Code/EnumConverterControl.cs \
        Test/mainsoft/NunitWebResources/menuclass.aspx \
        Test/mainsoft/NunitWebResources/FormView.aspx \
        Test/mainsoft/NunitWebResources/PostBackMenuTest.aspx \
@@ -207,7 +213,17 @@ TEST_RESOURCE_FILES = \
        Test/mainsoft/NunitWebResources/CheckBoxList_Bug578770.aspx \
        Test/mainsoft/NunitWebResources/EnumConverter_Bug578586.aspx \
        Test/mainsoft/NunitWebResources/ButtonColor_Bug325489.aspx \
-       Test/mainsoft/NunitWebResources/SqlDataSource_OnInit_Bug572781.aspx
+       Test/mainsoft/NunitWebResources/SqlDataSource_OnInit_Bug572781.aspx \
+       Test/mainsoft/NunitWebResources/FormViewPagerVisibility.aspx \
+       Test/mainsoft/NunitWebResources/OverridenControlsPropertyAndPostBack_Bug594238.aspx \
+       Test/mainsoft/NunitWebResources/GlobalizationEncodingName.aspx \
+       Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_0.aspx \
+       Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_1.aspx \
+       Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_2.aspx \
+       Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_5.aspx \
+       Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_6.aspx \
+       Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_7.aspx \
+       Test/mainsoft/NunitWebResources/GridView_Bug595567.aspx
 
 RESX_DIST =  resources/TranslationResources.resx
 ifneq (1, $(FRAMEWORK_VERSION_MAJOR))
@@ -215,6 +231,9 @@ RESX_RES = $(RESX_DIST:.resx=.resources)
 endif
 
 NUNIT_RESOURCE_FILES = $(TEST_RESOURCE_FILES)
+NUNIT_APP_CODE_FILES = $(TEST_APP_CODE_FILES)
+NUNIT_APP_GLOBALRESOURCES_FILES = $(TEST_APP_GLOBALRESOURCES_FILES)
+
 ifneq (1, $(FRAMEWORK_VERSION_MAJOR))
 OTHER_RES += $(RESOURCE_FILES_2)
 OTHER_LIB_MCS_FLAGS = -d:INSIDE_SYSTEM_WEB -nowarn:618 -r:System.Configuration.dll -r:Mono.Data.Sqlite.dll
@@ -252,7 +271,11 @@ echo-warning-systemcore:
 endif
 endif
 
-TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) -doc:$(test_lib:.dll=.xml) -nowarn:219,169,1591 $(NUNIT_RESOURCE_FILES:%=/resource:%) -r:SystemWebTestShim.dll
+TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) -doc:$(test_lib:.dll=.xml) -nowarn:219,169,1591 -r:SystemWebTestShim.dll \
+       $(NUNIT_RESOURCE_FILES:%=/resource:%) \
+       $(foreach file,$(NUNIT_APP_CODE_FILES),$(shell echo $(file) | sed -e 's;\(.*\)/\(.*\);/resource:\1/\2,App_Code/\2 ;g')) \
+       $(foreach file,$(NUNIT_APP_GLOBALRESOURCES_FILES),$(shell echo $(file) | sed -e 's;\(.*\)/\(.*\);/resource:\1/\2,App_GlobalResources/\2 ;g'))
+
 ifeq (net_2_0, $(PROFILE))
 TEST_MCS_FLAGS += -r:System.Web.Extensions.dll
 endif
@@ -261,6 +284,8 @@ EXTRA_DISTFILES = \
        $(RESOURCE_FILES_2) \
        $(RESOURCE_FILES_1) \
        $(TEST_RESOURCE_FILES) \
+       $(TEST_APP_CODE_FILES) \
+       $(TEST_APP_GLOBALRESOURCES_FILES) \
        UplevelHelperDefinitions.xml \
        $(RESX_DIST) \
        SQLiteProviders_DatabaseSchema.sql \
index 12433d7341e5eaeaed4ac334c1fc13cd1966890e..372b03b8a29ac83f4218b0dd2983833c3a099cea 100644 (file)
@@ -884,9 +884,14 @@ namespace System.Web.Compilation
                        if (tparser != null)
                                tparser.Location = location;
 
-                       if (text.Length != 0)
-                               FlushText (lastTag == TagType.CodeRender);
-
+                       if (text.Length != 0) {
+                               bool ignoreEmptyString = lastTag == TagType.CodeRender;
+#if NET_4_0
+                               ignoreEmptyString |= lastTag == TagType.CodeRenderEncode;
+#endif
+                               FlushText (ignoreEmptyString);
+                       }
+                       
                        if (0 == String.Compare (tagid, "script", true, Helpers.InvariantCulture)) {
                                bool in_script = (inScript || ignore_text);
                                if (in_script) {
@@ -941,10 +946,11 @@ namespace System.Web.Compilation
                                }
                                break;
                        case TagType.DataBinding:
-                               goto case TagType.CodeRender;
                        case TagType.CodeRenderExpression:
-                               goto case TagType.CodeRender;
                        case TagType.CodeRender:
+#if NET_4_0
+                       case TagType.CodeRenderEncode:
+#endif
                                if (isApplication)
                                        throw new ParseException (location, "Invalid content for application file.");
                        
@@ -1442,6 +1448,9 @@ namespace System.Web.Compilation
                                        return CodeConstructType.ExpressionSnippet;
 
                                case TagType.CodeRender:
+#if NET_4_0
+                               case TagType.CodeRenderEncode:
+#endif
                                        return CodeConstructType.CodeSnippet;
 
                                case TagType.DataBinding:
@@ -1474,6 +1483,10 @@ namespace System.Web.Compilation
                                b = new CodeRenderBuilder (code, true, location);
                        else if (tagtype == TagType.DataBinding)
                                b = new DataBindingBuilder (code, location);
+#if NET_4_0
+                       else if (tagtype == TagType.CodeRenderEncode)
+                               b = new CodeRenderBuilder (code, true, location, true);
+#endif
                        else
                                throw new HttpException ("Should never happen");
 
@@ -1578,7 +1591,11 @@ namespace System.Web.Compilation
                                        case TagType.CodeRenderExpression:
                                                builder.AppendSubBuilder (new CodeRenderBuilder (tagid, true, location));
                                                break;
-                                               
+#if NET_4_0
+                                       case TagType.CodeRenderEncode:
+                                               builder.AppendSubBuilder (new CodeRenderBuilder (tagid, true, location, true));
+                                               break;
+#endif
                                        case TagType.DataBinding:
                                                builder.AppendSubBuilder (new DataBindingBuilder (tagid, location));
                                                break;
index d0e08f8fcb962dad5b18719f7e73de213d7678ff..af8cc7b9b65e0460b827f3e5e775540d9bca0283 100644 (file)
@@ -597,8 +597,14 @@ namespace System.Web.Compilation
                        tokenizer.ExpectAttrValue = old;
                        bool varname;
                        bool databinding;
+#if NET_4_0
+                       bool codeRenderEncode;
+#endif
                        varname = Eat ('=');
                        databinding = !varname && Eat ('#');
+#if NET_4_0
+                       codeRenderEncode = !databinding && !varname && Eat (':');
+#endif
                        string odds = tokenizer.Odds;
                        
                        tokenizer.Verbatim = true;
@@ -614,8 +620,16 @@ namespace System.Web.Compilation
                        tokenizer.Verbatim = false;
                        id = inside_tags;
                        attributes = null;
-                       tagtype = (databinding ? TagType.DataBinding :
-                                 (varname ? TagType.CodeRenderExpression : TagType.CodeRender));
+                       if (databinding)
+                               tagtype = TagType.DataBinding;
+                       else if (varname)
+                               tagtype = TagType.CodeRenderExpression;
+#if NET_4_0
+                       else if (codeRenderEncode)
+                               tagtype = TagType.CodeRenderEncode;
+#endif
+                       else
+                               tagtype = TagType.CodeRender;
                }
 
                public override string ToString ()
index d9d49b1bd9ba03cef91860563b25083626f271d0..76bcb3a5e231e88b1fce2e777aba3fb626ee03c3 100644 (file)
@@ -1,3 +1,12 @@
+2010-04-12  Marek Habersack  <mhabersack@novell.com>
+
+       * PageCompiler.cs: if EnableViewStateMac is set in the page
+       source, generate relevant code.
+
+2010-03-17  Marek Habersack  <mhabersack@novell.com>
+
+       * AspGenerator.cs, AspParser.cs, TemplateControlCompiler.cs, TagType.cs, CodeRenderBuilder.cs: implemented the new <%: %> 4.0 html-encoded code render expression.
+
 2010-03-06  Marek Habersack  <mhabersack@novell.com>
 
        * TemplateControlCompiler.cs: AssignPropertyForResources localizes
index 3c0bfea23255448ebf8d13a7ebc9bbec3b1450b5..81d691e34a28159150e64dea655ebaf17a3d30fd 100644 (file)
@@ -292,6 +292,9 @@ namespace System.Web.Compilation
                        ILocation directiveLocation = pageParser.DirectiveLocation;
 
                        CodeArgumentReferenceExpression ctrlVar = new CodeArgumentReferenceExpression("__ctrl");
+                       if (pageParser.EnableViewStateMacSet)
+                               method.Statements.Add (AddLinePragma (CreatePropertyAssign (ctrlVar, "EnableViewStateMac", pageParser.EnableViewStateMacSet), directiveLocation));
+                       
                        if (pageParser.Title != null)
                                method.Statements.Add (AddLinePragma (CreatePropertyAssign (ctrlVar, "Title", pageParser.Title), directiveLocation));
 
index af38a4124b34e04091977b4f378f825b99de9470..9d3b879599bab250d2e6ac917e654a2ebd294e9b 100644 (file)
@@ -40,7 +40,10 @@ namespace System.Web.Compilation
                DataBinding,
                CodeRender,
                CodeRenderExpression,
-               Include
+               Include,
+#if NET_4_0
+               CodeRenderEncode
+#endif
        }
 }
 
index 1d2a5365524ed863b96760df774ab129ccbac14a..4b01ccd67853f2ae263f23f390a1cc351188cde5 100644 (file)
@@ -1262,9 +1262,21 @@ namespace System.Web.Compilation
                                                        new CodeArgumentReferenceExpression ("__output"),
                                                        "Write");
 
-                       expr.Parameters.Add (new CodeSnippetExpression (cr.Code));
+                       expr.Parameters.Add (GetWrappedCodeExpression (cr));
                        parent.RenderMethod.Statements.Add (AddLinePragma (expr, cr));
                }
+
+               CodeExpression GetWrappedCodeExpression (CodeRenderBuilder cr)
+               {
+                       var ret = new CodeSnippetExpression (cr.Code);
+#if NET_4_0
+                       if (cr.HtmlEncode) {
+                               var encodeRef = new CodeMethodReferenceExpression (new CodeTypeReferenceExpression (typeof (HttpUtility)), "HtmlEncode");
+                               return new CodeMethodInvokeExpression (encodeRef, new CodeExpression[] { ret });
+                       } else
+#endif
+                               return ret;
+               }
                
                static Type GetContainerType (ControlBuilder builder)
                {
index fa7591926b533a387de8a01eee69f15b8afa53a5..09b93df7dd679db539cbf27fe664e2e20b1e96ff 100644 (file)
@@ -1,3 +1,13 @@
+2010-04-09  Marek Habersack  <mhabersack@novell.com>
+
+       * WebConfigurationManager.cs: GetSection properly processes paths
+       of form '~'. Fixes bug #595140. Patch from Adriaan van Kekem
+       <avkekem@hotmail.com>, thanks!
+
+2010-04-08 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * GlobalizationSection.cs: use WebName instead of EncodingName.
+
 2010-03-06  Marek Habersack  <mhabersack@novell.com>
 
        * WebConfigurationManager.cs: do not use Request.Path - it may
index 3025cf5d3717858e0cd72ddfcaf154532b88ec68..0e8367cd118ca6350c0061bf52e4c23c6e665b4d 100644 (file)
@@ -135,13 +135,13 @@ namespace System.Web.Configuration {
                [ConfigurationProperty ("fileEncoding")]
                public Encoding FileEncoding {
                        get { return GetEncoding (fileEncodingProp, ref cached_fileencoding); }
-                       set { base[fileEncodingProp] = value.EncodingName; }
+                       set { base[fileEncodingProp] = value.WebName; }
                }
 
                [ConfigurationProperty ("requestEncoding", DefaultValue = "utf-8")]
                public Encoding RequestEncoding {
                        get { return GetEncoding (requestEncodingProp, ref cached_requestencoding); }
-                       set { base[requestEncodingProp] = value.EncodingName; }
+                       set { base[requestEncodingProp] = value.WebName; }
                }
 
                [ConfigurationProperty ("resourceProviderFactoryType", DefaultValue = "")]
@@ -153,13 +153,13 @@ namespace System.Web.Configuration {
                [ConfigurationProperty ("responseEncoding", DefaultValue = "utf-8")]
                public Encoding ResponseEncoding {
                        get { return GetEncoding (responseEncodingProp, ref cached_responseencoding); }
-                       set { base[responseEncodingProp] = value.EncodingName; }
+                       set { base[responseEncodingProp] = value.WebName; }
                }
 
                [ConfigurationProperty ("responseHeaderEncoding", DefaultValue = "utf-8")]
                public Encoding ResponseHeaderEncoding {
                        get { return GetEncoding (responseHeaderEncodingProp, ref cached_responseheaderencoding); }
-                       set { base[responseHeaderEncodingProp] = value.EncodingName; }
+                       set { base[responseHeaderEncodingProp] = value.WebName; }
                }
 
                [ConfigurationProperty ("uiCulture", DefaultValue = "")]
@@ -257,7 +257,7 @@ namespace System.Web.Configuration {
                                cached_encoding_name = ((enc == null) ? "utf-8" : enc);
 
                        Encoding encoding = (Encoding)encodingHash [prop];
-                       if (encoding == null || encoding.EncodingName != cached_encoding_name) {
+                       if (encoding == null || encoding.WebName != cached_encoding_name) {
                                try {
                                        switch (cached_encoding_name.ToLower (Helpers.InvariantCulture)) {
                                        case "utf-16le":
@@ -289,7 +289,7 @@ namespace System.Web.Configuration {
                        }
 
                        encodingHash[prop] = encoding;
-                       cached_encoding_name = encoding.EncodingName;
+                       cached_encoding_name = encoding.WebName;
 
                        return encoding;
                }
index 860df8df8e18fd144ea66dbab996b20c2aff7529..cc4d8d6a0f444ded164037c9ad891ce14d70d0da 100644 (file)
@@ -466,7 +466,7 @@ namespace System.Web.Configuration {
                                
                                if (VirtualPathUtility.IsRooted (path)) {
                                        if (path [0] == '~')
-                                               relPath = path.Substring (2);
+                                               relPath = path.Length > 1 ? path.Substring (2) : String.Empty;
                                        else if (path [0] == '/')
                                                relPath = path.Substring (1);
                                        else
index bc22af6bee934048dece7f1347bff432df0f71ca..ea0aa13b97df70875b3c7d3ffc115140804e2548 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Dick Porter  <dick@ximian.com>
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -26,7 +26,6 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_0
 using System.Web;
 using System.Web.UI;
 using System.ComponentModel;
@@ -177,4 +176,4 @@ namespace System.Web.UI.Adapters
                }
        }
 }
-#endif
+
index c23f9a7b8c4cf206b20a5fe5c2a86e28d294ab6c..a86a98f71be152bb9696bbfb9439e7195a5fcdf2 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Dick Porter  <dick@ximian.com>
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -26,7 +26,6 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_0
 using System.Web.UI;
 using System.Web.UI.WebControls;
 using System.Collections;
@@ -176,4 +175,4 @@ namespace System.Web.UI.Adapters
                ListDictionary radio_button_group;
        }
 }
-#endif
+
index 0956c0134005b26a37f9d32e890b1652b0200e3b..c1cb48028b047ac7edd21fed508fbf15d743adf9 100644 (file)
@@ -4,7 +4,7 @@
 // Authors:
 //     Sanjay Gupta (gsanjay@novell.com)
 //
-// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2004-2010 Novell, Inc (http://www.novell.com)
 //
 //
 // Permission is hereby granted, free of charge, to any person obtaining
@@ -27,7 +27,6 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_0
 namespace System.Web.UI.Adapters {
        public enum WmlPostFieldType {
                Normal = 0,
@@ -36,5 +35,5 @@ namespace System.Web.UI.Adapters {
                Raw = 3
        } 
 }
-#endif
+
 
index 234f4d55ed0bb9b804e10d18f59d39f9b369d5c0..edc7e4a204cd6bbcbd922039bff745f8653235d0 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Sebastien Pouliot  <sebastien@ximian.com>
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -36,9 +36,7 @@ namespace System.Web.UI.HtmlControls {
        [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        // attributes
        [DefaultEvent ("ServerClick")]
-#if NET_2_0
        [SupportsEventValidation]
-#endif
        public class HtmlAnchor : HtmlContainerControl, IPostBackEventHandler 
        {
                static readonly object serverClickEvent = new object ();
@@ -52,9 +50,7 @@ namespace System.Web.UI.HtmlControls {
                [WebSysDescription("")]
                [WebCategory("Action")]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
-#if NET_2_0
                [UrlProperty]
-#endif
                public string HRef {
                        get {
                                string s = Attributes ["href"];
@@ -107,9 +103,7 @@ namespace System.Web.UI.HtmlControls {
                [WebSysDescription("")]
                [WebCategory("Appearance")]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
-#if NET_2_0
                [Localizable (true)]
-#endif
                public string Title {
                        get {
                                string s = Attributes ["title"];
@@ -123,7 +117,6 @@ namespace System.Web.UI.HtmlControls {
                        }
                }
 
-#if NET_2_0
                [DefaultValue (true)]
                public virtual bool CausesValidation {
                        get {
@@ -143,14 +136,8 @@ namespace System.Web.UI.HtmlControls {
                                ViewState ["ValidationGroup"] = value;
                        }
                }
-#endif
 
-#if NET_2_0
-               protected internal
-#else
-               protected
-#endif         
-               override void OnPreRender (EventArgs e)
+               protected internal override void OnPreRender (EventArgs e)
                {
                        base.OnPreRender (e);
                }
@@ -168,17 +155,12 @@ namespace System.Web.UI.HtmlControls {
                        EventHandler serverClick = (EventHandler) Events [serverClickEvent];
                        if (serverClick != null) {
                                ClientScriptManager csm;
-#if NET_2_0
+
                                // a script
                                PostBackOptions options = GetPostBackOptions ();
                                csm = Page.ClientScript;
                                csm.RegisterForEventValidation (options);
                                Attributes ["href"] = csm.GetPostBackEventReference (options, true);
-#else
-                               // a script
-                               csm = new ClientScriptManager (Page);
-                               Attributes ["href"] = csm.GetPostBackClientHyperlink (this, String.Empty);
-#endif
                        } else {
                                string hr = HRef;
                                if (hr != string.Empty)
@@ -197,7 +179,6 @@ namespace System.Web.UI.HtmlControls {
                        Attributes.Remove ("href");
                }
 
-#if NET_2_0
                protected virtual void RaisePostBackEvent (string eventArgument)
                {
                        ValidateEvent (UniqueID, eventArgument);
@@ -209,27 +190,23 @@ namespace System.Web.UI.HtmlControls {
        
                PostBackOptions GetPostBackOptions ()
                {
+                       Page page = Page;
                        PostBackOptions options = new PostBackOptions (this);
                        options.ValidationGroup = null;
                        options.ActionUrl = null;
                        options.Argument = String.Empty;
                        options.RequiresJavaScriptProtocol = true;
                        options.ClientSubmit = true;
-                       options.PerformValidation = CausesValidation && Page != null && Page.AreValidatorsUplevel (ValidationGroup);
+                       options.PerformValidation = CausesValidation && page != null && page.AreValidatorsUplevel (ValidationGroup);
                        if (options.PerformValidation)
                                options.ValidationGroup = ValidationGroup;
 
                        return options;
                }
-#endif
 
                void IPostBackEventHandler.RaisePostBackEvent (string eventArgument)
                {
-#if NET_2_0
                        RaisePostBackEvent (eventArgument);
-#else
-                       OnServerClick (EventArgs.Empty);
-#endif
                }
 
                [WebSysDescription("")]
index 4e00d373631711a11240997c47a4d261f701bcbc..e61a051b446cd9ce13570e3ea9643fa23655e30c 100644 (file)
@@ -24,7 +24,7 @@
 // Authors:
 //     Jackson Harper (jackson@ximian.com)
 //
-// (C) 2005 Novell, Inc.
+// (C) 2005-2010 Novell, Inc.
 
 
 using System.ComponentModel;
@@ -37,9 +37,7 @@ namespace System.Web.UI.HtmlControls {
        [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        // attributes
        [DefaultEvent("ServerClick")]
-#if NET_2_0
        [SupportsEventValidation]
-#endif
        public class HtmlButton : HtmlContainerControl, IPostBackEventHandler {
 
                static readonly object ServerClickEvent = new object();
@@ -51,12 +49,7 @@ namespace System.Web.UI.HtmlControls {
                [DefaultValue(true)]
                [WebSysDescription("")]
                [WebCategory("Behavior")]
-#if NET_2_0
-               public virtual
-#else          
-               public
-#endif         
-               bool CausesValidation {
+               public virtual bool CausesValidation {
                        get {
                                return ViewState.GetBool ("CausesValidation", true);
                        }
@@ -65,7 +58,6 @@ namespace System.Web.UI.HtmlControls {
                        }
                }
 
-#if NET_2_0
                [DefaultValue ("")]
                public virtual string ValidationGroup 
                {
@@ -76,37 +68,20 @@ namespace System.Web.UI.HtmlControls {
                                ViewState ["ValidationGroup"] = value;
                        }
                }
-#endif         
-
-#if NET_2_0
                void IPostBackEventHandler.RaisePostBackEvent (string eventArgument)
                {
                        RaisePostBackEvent (eventArgument);
                }
 
                protected virtual void RaisePostBackEvent (string eventArgument)
-#else
-               void IPostBackEventHandler.RaisePostBackEvent (string eventArgument)
-#endif
                {
-#if NET_2_0
                        ValidateEvent (UniqueID, eventArgument);
-#endif
                        if (CausesValidation)
-#if NET_2_0
                                Page.Validate (ValidationGroup);
-#else
-                               Page.Validate ();
-#endif
                        OnServerClick (EventArgs.Empty);
                }
                
-#if NET_2_0
-               protected internal
-#else          
-               protected
-#endif
-               override void OnPreRender (EventArgs e)
+               protected internal override void OnPreRender (EventArgs e)
                {
                        base.OnPreRender (e);
                }
@@ -120,56 +95,31 @@ namespace System.Web.UI.HtmlControls {
 
                protected override void RenderAttributes (HtmlTextWriter writer)
                {
-#if NET_2_0
-                       if (Page != null && Events [ServerClickEvent] != null) {
+                       Page page = Page;
+                       if (page != null && Events [ServerClickEvent] != null) {
                                PostBackOptions options = GetPostBackOptions ();
-                               Attributes ["onclick"] += Page.ClientScript.GetPostBackEventReference (options, true);
-                               writer.WriteAttribute ("language", "javascript");
-                       }
-#else          
-                       ClientScriptManager csm = new ClientScriptManager (Page);
-                       bool postback = false;
-
-                       if (Page != null && Events [ServerClickEvent] != null)
-                               postback = true;
-
-                       if (CausesValidation && Page != null && Page.AreValidatorsUplevel ()) {
-                               if (postback)
-                                       writer.WriteAttribute ("onclick",
-                                                              String.Concat ("javascript:{if (typeof(Page_ClientValidate) != 'function' ||  Page_ClientValidate()) ",
-                                                                             csm.GetPostBackEventReference (this, String.Empty), "}"));
-                               else
-                                       writer.WriteAttribute ("onclick",
-                                                              "if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate();");
-
+                               Attributes ["onclick"] += page.ClientScript.GetPostBackEventReference (options, true);
                                writer.WriteAttribute ("language", "javascript");
                        }
-                       else if (postback) {
-                               writer.WriteAttribute ("onclick",
-                                                      Page.ClientScript.GetPostBackClientHyperlink (this, ""));
-
-                               writer.WriteAttribute ("language", "javascript");
-                       }
-#endif
 
                        base.RenderAttributes (writer);
                }
 
-#if NET_2_0
-               PostBackOptions GetPostBackOptions () {
+               PostBackOptions GetPostBackOptions ()
+               {
+                       Page page = Page;
                        PostBackOptions options = new PostBackOptions (this);
                        options.ValidationGroup = null;
                        options.ActionUrl = null;
                        options.Argument = String.Empty;
                        options.RequiresJavaScriptProtocol = false;
                        options.ClientSubmit = true;
-                       options.PerformValidation = CausesValidation && Page != null && Page.AreValidatorsUplevel (ValidationGroup);
+                       options.PerformValidation = CausesValidation && page != null && page.AreValidatorsUplevel (ValidationGroup);
                        if (options.PerformValidation)
                                options.ValidationGroup = ValidationGroup;
 
                        return options;
                }
-#endif
 
                [WebSysDescription("")]
                [WebCategory("Action")]
@@ -178,6 +128,5 @@ namespace System.Web.UI.HtmlControls {
                        remove { Events.RemoveHandler (ServerClickEvent, value); }
                }
        }
-
 }
 
index f8e45bef2eed8c3299cab141a7e6291d268277eb..66d1881d64104da93c1c90871c6d34618689e9fb 100644 (file)
@@ -7,7 +7,7 @@
 //
 // (C) Bob Smith
 // (c) 2002 Ximian, Inc. (http://www.ximian.com)
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -55,16 +55,13 @@ namespace System.Web.UI.HtmlControls
        // CAS
        [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
-       public abstract class HtmlContainerControl : HtmlControl {
-
-#if NET_2_0
-               protected
-#else
-               public
-#endif
-               HtmlContainerControl () : this ("span") {}
+       public abstract class HtmlContainerControl : HtmlControl
+       {
+               protected HtmlContainerControl () : this ("span")
+               {}
                
-               public HtmlContainerControl (string tag) : base(tag) {}
+               public HtmlContainerControl (string tag) : base(tag)
+               {}
 
                [HtmlControlPersistable (false)]
                [BrowsableAttribute(false)]
@@ -113,12 +110,7 @@ namespace System.Web.UI.HtmlControls
                        }
                }
                
-#if NET_2_0
-               protected internal
-#else
-               protected
-#endif         
-               override void Render (HtmlTextWriter writer)
+               protected internal override void Render (HtmlTextWriter writer)
                {
                        RenderBeginTag (writer);
                        RenderChildren (writer);
index f708b2ea3d47f335f249bcaa58d17d7f076a9453..a77b7dbb16922882490a7673260f0dce17d3b524 100644 (file)
@@ -6,7 +6,7 @@
 //
 //
 // (C) Bob Smith
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -47,20 +47,9 @@ namespace System.Web.UI.HtmlControls{
                internal string _tagName;
                AttributeCollection _attributes;
 
+               protected HtmlControl() : this ("span") {}
                
-#if NET_2_0
-               protected
-#else
-               public
-#endif
-               HtmlControl() : this ("span") {}
-               
-#if NET_2_0
-               protected
-#else
-               public
-#endif
-               HtmlControl(string tag)
+               protected HtmlControl(string tag)
                {
                        _tagName = tag;
                }
@@ -96,7 +85,6 @@ namespace System.Web.UI.HtmlControls{
                        }
                }
 
-#if NET_2_0
                /* keep these two methods in sync with the
                 * IAttributeAccessor iface methods below */
                protected virtual string GetAttribute (string name)
@@ -108,7 +96,6 @@ namespace System.Web.UI.HtmlControls{
                {
                        Attributes[name] = value;
                }
-#endif         
                
                string System.Web.UI.IAttributeAccessor.GetAttribute(string name){
                        return Attributes[name];
@@ -125,12 +112,7 @@ namespace System.Web.UI.HtmlControls{
                        writer.Write ('>');
                }
 
-#if NET_2_0
-               protected internal
-#else
-               protected
-#endif
-               override void Render (HtmlTextWriter writer)
+               protected internal override void Render (HtmlTextWriter writer)
                {
                        RenderBeginTag (writer);
                }
@@ -144,8 +126,7 @@ namespace System.Web.UI.HtmlControls{
                
                [Browsable(false)]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
-               public AttributeCollection Attributes
-               {
+               public AttributeCollection Attributes {
                        get { 
                                if (_attributes == null)
                                        _attributes = new AttributeCollection (ViewState);
@@ -157,11 +138,8 @@ namespace System.Web.UI.HtmlControls{
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                [WebSysDescription("")]
                [WebCategory("Behavior")]
-#if NET_2_0
                [TypeConverter (typeof(MinimizableAttributeTypeConverter))]
-#endif
-               public bool Disabled
-               {
+               public bool Disabled {
                        get {
                                string disableAttr = Attributes["disabled"] as string;
                                return (disableAttr != null);
@@ -176,8 +154,7 @@ namespace System.Web.UI.HtmlControls{
 
                [Browsable(false)]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
-               public CssStyleCollection Style
-               {
+               public CssStyleCollection Style {
                        get { return Attributes.CssStyle; }
                }
 
@@ -185,13 +162,11 @@ namespace System.Web.UI.HtmlControls{
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                [WebSysDescription("")]
                [WebCategory("Appearance")]
-               public virtual string TagName
-               {
+               public virtual string TagName {
                        get { return _tagName; }
                }
 
-               protected override bool ViewStateIgnoresCase 
-               {
+               protected override bool ViewStateIgnoresCase {
                        get {
                                return true;
                        }
index 48c72a0b49bdfc7d5d6bd75ed2314fbe6690d08f..5e5725d4e7f4dfd2bce644718bd346c052c8295c 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Sebastien Pouliot  <sebastien@ximian.com>
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -26,8 +26,6 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_0
-
 using System.Security.Permissions;
 
 namespace System.Web.UI.HtmlControls {
@@ -35,8 +33,8 @@ namespace System.Web.UI.HtmlControls {
        // CAS
        [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
-       public sealed class HtmlEmptyTagControlBuilder : ControlBuilder {
-
+       public sealed class HtmlEmptyTagControlBuilder : ControlBuilder
+       {
                public HtmlEmptyTagControlBuilder ()
                {
                }
@@ -49,4 +47,3 @@ namespace System.Web.UI.HtmlControls {
        }
 }
 
-#endif
index 0cfe963259375232766483559500cf85c397d9fc..419f7a99390935dec5ceb81202107dd9b5601e1f 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Dick Porter  <dick@ximian.com>
 //
-// Copyright (C) 2005-2009 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -42,12 +42,15 @@ namespace System.Web.UI.HtmlControls
        public class HtmlForm : HtmlContainerControl 
        {
                bool inited;
-
+               string _defaultfocus;
+               string _defaultbutton;
+               bool submitdisabledcontrols = false;
+               bool? isUplevel;
+               
                public HtmlForm () : base ("form")
                {
                }
 
-#if NET_2_0
                // LAMESPEC: This is undocumented on MSDN, but apparently it does exist on MS.NET.
                // See https://bugzilla.novell.com/show_bug.cgi?id=442104
                public string Action {
@@ -65,12 +68,10 @@ namespace System.Web.UI.HtmlControls
                                else
                                        Attributes ["action"] = value;
                        }
-               }
-               
-               string _defaultbutton;
+               }               
+
                [DefaultValue ("")]
-               public string DefaultButton
-               {
+               public string DefaultButton {
                        get {
                                return _defaultbutton ?? String.Empty;
                        }
@@ -79,10 +80,8 @@ namespace System.Web.UI.HtmlControls
                        }
                }
 
-               string _defaultfocus;
                [DefaultValue ("")]
-               public string DefaultFocus
-               {
+               public string DefaultFocus {
                        get {
                                return _defaultfocus ?? String.Empty;
                        }
@@ -90,12 +89,10 @@ namespace System.Web.UI.HtmlControls
                                _defaultfocus = value;
                        }
                }
-#endif         
 
                [DefaultValue ("")]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
-               public string Enctype 
-               {
+               public string Enctype {
                        get {
                                string enc = Attributes["enctype"];
 
@@ -116,8 +113,7 @@ namespace System.Web.UI.HtmlControls
                
                [DefaultValue ("")]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
-               public string Method 
-               {
+               public string Method {
                        get {
                                string method = Attributes["method"];
 
@@ -138,8 +134,7 @@ namespace System.Web.UI.HtmlControls
 
                [DefaultValue ("")]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
-               public virtual string Name 
-               {
+               public virtual string Name {
                        get {
                                return UniqueID;
                        }
@@ -148,11 +143,8 @@ namespace System.Web.UI.HtmlControls
                        }
                }
 
-#if NET_2_0
-               bool submitdisabledcontrols = false;
                [DefaultValue (false)]
-               public virtual bool SubmitDisabledControls 
-               {
+               public virtual bool SubmitDisabledControls {
                        get {
                                return submitdisabledcontrols;
                        }
@@ -160,12 +152,10 @@ namespace System.Web.UI.HtmlControls
                                submitdisabledcontrols = value;
                        }
                }
-#endif
                        
                [DefaultValue ("")]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
-               public string Target 
-               {
+               public string Target {
                        get {
                                string target = Attributes["target"];
 
@@ -190,33 +180,24 @@ namespace System.Web.UI.HtmlControls
                        }
                }
 
-#if NET_2_0            
                [MonoTODO ("why override?")]
                protected override ControlCollection CreateControlCollection ()
                {
                        return base.CreateControlCollection ();
                }
-#endif         
-
-#if NET_2_0
-               protected internal
-#else          
-               protected
-#endif         
-               override void OnInit (EventArgs e)
+
+               protected internal override void OnInit (EventArgs e)
                {
                        inited = true;
-                       Page.RegisterViewStateHandler ();
-
-#if NET_2_0
-                       Page.RegisterForm (this);
-#endif
-
+                       Page page = Page;
+                       if (page != null) {
+                               page.RegisterViewStateHandler ();
+                               page.RegisterForm (this);
+                       }
+                       
                        base.OnInit (e);
                }
 
-#if NET_2_0
-               bool? isUplevel;
                internal bool DetermineRenderUplevel ()
                {
 #if TARGET_J2EE
@@ -250,7 +231,6 @@ namespace System.Web.UI.HtmlControls
                {
                        base.OnPreRender(e);
                }
-#endif         
 
                protected override void RenderAttributes (HtmlTextWriter w)
                {
@@ -262,17 +242,13 @@ namespace System.Web.UI.HtmlControls
                        */
                        
                        string action;
-#if NET_2_0
                        string customAction = Attributes ["action"];
-#endif
-                       Page p = Page;
-                       HttpRequest req = p != null ? p.Request : null;
+                       Page page = Page;
+                       HttpRequest req = page != null ? page.Request : null;
                        if (req == null)
                                throw new HttpException ("No current request, cannot continue rendering.");
 #if !TARGET_J2EE
-#if NET_2_0
                        if (String.IsNullOrEmpty (customAction)) {
-#endif
                                string file_path = req.ClientFilePath;
                                string current_path = req.CurrentExecutionFilePath;
                                if (file_path == current_path) {
@@ -282,14 +258,8 @@ namespace System.Web.UI.HtmlControls
                                        // Fun. We need to make cookieless sessions work, so no
                                        // absolute paths here.
                                        bool cookieless;
-
-#if NET_2_0
                                        SessionStateSection sec = WebConfigurationManager.GetSection ("system.web/sessionState") as SessionStateSection;
                                        cookieless = sec != null ? sec.Cookieless == HttpCookieMode.UseUri: false;
-#else
-                                       SessionConfig sec = HttpContext.GetAppConfig ("system.web/sessionState") as SessionConfig;
-                                       cookieless = sec != null ? sec.CookieLess : false;
-#endif
                                        string appVPath = HttpRuntime.AppDomainAppVirtualPath;
                                        int appVPathLen = appVPath.Length;
                                                
@@ -308,10 +278,8 @@ namespace System.Web.UI.HtmlControls
                                        } else
                                                action = current_path;
                                }
-#if NET_2_0
                        } else
                                action = customAction;
-#endif
                        action += req.QueryStringRaw;
 #else
                        // Allow the page to transform action to a portlet action url
@@ -325,18 +293,14 @@ namespace System.Web.UI.HtmlControls
 
 #endif
 
-#if NET_2_0
                        XhtmlConformanceSection xhtml = WebConfigurationManager.GetSection ("system.web/xhtmlConformance") as
                                XhtmlConformanceSection;
                        
                        if (xhtml != null && xhtml.Mode == XhtmlConformanceMode.Legacy)
-#endif
                                w.WriteAttribute ("name", Name);
 
                        w.WriteAttribute ("method", Method);
-#if NET_2_0
                        if (String.IsNullOrEmpty (customAction))
-#endif
                                w.WriteAttribute ("action", action, true);
 
                        /*
@@ -353,8 +317,8 @@ namespace System.Web.UI.HtmlControls
 #pragma warning restore 219
                        }
                        
-                       string submit = Page.GetSubmitStatements ();
-                       if (submit != null && submit != "") {
+                       string submit = page != null ? page.GetSubmitStatements () : null;
+                       if (!String.IsNullOrEmpty (submit)) {
                                Attributes.Remove ("onsubmit");
                                w.WriteAttribute ("onsubmit", submit);
                        }
@@ -363,16 +327,13 @@ namespace System.Web.UI.HtmlControls
                         * they are empty
                         */
                        string enctype = Enctype;
-                       if (enctype != null && enctype != "") {
+                       if (!String.IsNullOrEmpty (enctype))
                                w.WriteAttribute ("enctype", enctype);
-                       }
 
                        string target = Target;
-                       if (target != null && target != "") {
+                       if (!String.IsNullOrEmpty (target))
                                w.WriteAttribute ("target", target);
-                       }
 
-#if NET_2_0
                        string defaultbutton = DefaultButton;
                        if (!String.IsNullOrEmpty (defaultbutton)) {
                                Control c = FindControl (defaultbutton);
@@ -381,13 +342,12 @@ namespace System.Web.UI.HtmlControls
                                        throw new InvalidOperationException(String.Format ("The DefaultButton of '{0}' must be the ID of a control of type IButtonControl.",
                                                                                           ID));
 
-                               if (DetermineRenderUplevel ()) {
+                               if (page != null && DetermineRenderUplevel ()) {
                                        w.WriteAttribute (
                                                "onkeypress",
-                                               "javascript:return " + Page.WebFormScriptReference + ".WebForm_FireDefaultButton(event, '" + c.ClientID + "')");
+                                               "javascript:return " + page.WebFormScriptReference + ".WebForm_FireDefaultButton(event, '" + c.ClientID + "')");
                                }
                        }
-#endif
 
                        /* Now remove them from the hash so the base
                         * RenderAttributes can do all the rest
@@ -399,20 +359,13 @@ namespace System.Web.UI.HtmlControls
                        base.RenderAttributes (w);
                }
 
-#if NET_2_0
-               protected internal
-#else          
-               protected
-#endif         
-               override void RenderChildren (HtmlTextWriter w)
+               protected internal override void RenderChildren (HtmlTextWriter w)
                {
                        Page page = Page;
                        
                        if (!inited && page != null) {
                                page.RegisterViewStateHandler ();
-#if NET_2_0
                                page.RegisterForm (this);
-#endif
                        }
                        if (page != null)
                                page.OnFormRender (w, ClientID);
@@ -421,25 +374,16 @@ namespace System.Web.UI.HtmlControls
                                page.OnFormPostRender (w, ClientID);
                }
 
-#if NET_2_0
                /* According to corcompare */
                [MonoTODO ("why override?")]
                public override void RenderControl (HtmlTextWriter w)
                {
                        base.RenderControl (w);
                }
-#endif         
-
-#if NET_2_0
-               protected internal
-#else          
-               protected
-#endif         
-               override void Render (HtmlTextWriter w)
+
+               protected internal override void Render (HtmlTextWriter w)
                {
                        base.Render (w);
                }
        }
 }
-
-       
index 59ccb938fd0ccaa95542e197cbad32d5a0cfb1d7..6f80e8a23aa8cccfeed0796d0963ee797fb845e0 100644 (file)
@@ -4,7 +4,7 @@
 // Authors:
 //     Lluis Sanchez Gual (lluis@novell.com)
 //
-// Copyright (C) 2004-2009 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2004-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -26,8 +26,6 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_0
-
 using System.ComponentModel;
 using System.Collections;
 using System.Security.Permissions;
@@ -255,4 +253,3 @@ namespace System.Web.UI.HtmlControls
        }
 }
 
-#endif
index 302bcd348a85330fcb984e959920abdc653159bd..ab52926462b6a382d2595f4d4f03389fbf80321c 100644 (file)
@@ -4,7 +4,7 @@
 // Authors:
 //     Lluis Sanchez Gual (lluis@novell.com)
 //
-// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2004-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -26,7 +26,6 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_0
 using System.Collections;
 using System.Globalization;
 using System.Security.Permissions;
@@ -55,4 +54,4 @@ namespace System.Web.UI.HtmlControls
                }
        }
 }
-#endif
+
index eb91a5baa5824d6a2359b8e954468489a50c0367..871e22e6ad9dbf83aa0f635b5c98eb995473abc1 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Dick Porter  <dick@ximian.com>
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -37,11 +37,7 @@ namespace System.Web.UI.HtmlControls
        [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        // attributes
-#if NET_2_0
        [ControlBuilder (typeof (HtmlEmptyTagControlBuilder))]
-#else
-       [ControlBuilder (typeof (HtmlControlBuilder))]
-#endif
        public class HtmlImage : HtmlControl 
        {
                public HtmlImage () : base ("img")
@@ -52,8 +48,7 @@ namespace System.Web.UI.HtmlControls
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                [WebSysDescription("")]
                [WebCategory("Layout")]
-               public string Align 
-               {
+               public string Align {
                        get {
                                string align = Attributes["align"];
 
@@ -76,11 +71,8 @@ namespace System.Web.UI.HtmlControls
                [WebSysDescription("")]
                [WebCategory("Appearance")]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
-#if NET_2_0
                [Localizable (true)]
-#endif
-               public string Alt 
-               {
+               public string Alt {
                        get {
                                string alt = Attributes["alt"];
 
@@ -103,8 +95,7 @@ namespace System.Web.UI.HtmlControls
                [WebSysDescription("")]
                [WebCategory("Appearance")]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
-               public int Border 
-               {
+               public int Border {
                        get {
                                string border = Attributes["border"];
                                
@@ -127,8 +118,7 @@ namespace System.Web.UI.HtmlControls
                [WebSysDescription("")]
                [WebCategory("Layout")]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
-               public int Height
-               {
+               public int Height {
                        get {
                                string height = Attributes["height"];
                                
@@ -151,11 +141,8 @@ namespace System.Web.UI.HtmlControls
                [WebSysDescription("")]
                [WebCategory("Behavior")]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
-#if NET_2_0
                [UrlProperty]
-#endif
-               public string Src 
-               {
+               public string Src {
                        get {
                                string src = Attributes["src"];
 
@@ -178,8 +165,7 @@ namespace System.Web.UI.HtmlControls
                [WebSysDescription("")]
                [WebCategory("Layout")]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
-               public int Width 
-               {
+               public int Width {
                        get {
                                string width = Attributes["width"];
 
@@ -221,5 +207,3 @@ namespace System.Web.UI.HtmlControls
                }
        }
 }
-
-       
index 513a93939df4ee60f9de7d4bf342372cd0a412d6..c674ec1922584023e3da5c110f359af21ed04909 100644 (file)
@@ -4,7 +4,7 @@
 // Authors:
 //     Jackson Harper (jackson@ximian.com)
 //
-// (C) 2005 Novell, Inc.
+// (C) 2005-2010 Novell, Inc.
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -39,9 +39,7 @@ namespace System.Web.UI.HtmlControls {
        [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        // attributes
        [DefaultEventAttribute ("ServerClick")]
-#if NET_2_0
        [SupportsEventValidation]
-#endif
        public class HtmlInputButton : HtmlInputControl, IPostBackEventHandler 
        {
                static readonly object ServerClickEvent = new object();
@@ -57,12 +55,7 @@ namespace System.Web.UI.HtmlControls {
                [DefaultValue(true)]
                [WebSysDescription("")]
                [WebCategory("Behavior")]
-#if NET_2_0
-               public virtual
-#else          
-               public
-#endif         
-               bool CausesValidation {
+               public virtual bool CausesValidation {
                        get {
                                string flag = Attributes["CausesValidation"];
 
@@ -76,7 +69,6 @@ namespace System.Web.UI.HtmlControls {
                        }
                }
 
-#if NET_2_0
                [DefaultValue ("")]
                public virtual string ValidationGroup
                {
@@ -95,20 +87,12 @@ namespace System.Web.UI.HtmlControls {
                                        Attributes["ValidationGroup"] = value;
                        }
                }
-#endif
 
                void RaisePostBackEventInternal (string eventArgument)
                {
-#if NET_2_0
                        ValidateEvent (UniqueID, eventArgument);
-#endif
-                       if (CausesValidation) {
-#if NET_2_0
+                       if (CausesValidation)
                                Page.Validate (ValidationGroup);
-#else
-                               Page.Validate ();
-#endif
-                       }
                        
                        if (String.Compare (Type, "reset", true, Helpers.InvariantCulture) != 0)
                                OnServerClick (EventArgs.Empty);
@@ -118,22 +102,11 @@ namespace System.Web.UI.HtmlControls {
 
                HtmlForm FindForm ()
                {
-#if NET_2_0
-                       return Page.Form;
-#else
-                       HtmlForm ret = null;
-                       Control p = Parent;
-                       while (p != null) {
-                               ret = p as HtmlForm;
-                               if (ret == null) {
-                                       p = p.Parent;
-                                       continue;
-                               }
-                               return ret;
-                       }
+                       Page p = Page;
+                       if (p != null)
+                               return p.Form;
 
                        return null;
-#endif
                }
                
                void ResetForm (HtmlForm form)
@@ -214,28 +187,18 @@ namespace System.Web.UI.HtmlControls {
                                // ignore
                        }
                }
-#if NET_2_0
+
                protected virtual void RaisePostBackEvent (string eventArgument)
                {
                        RaisePostBackEventInternal (eventArgument);
                }
-#endif
                
                void IPostBackEventHandler.RaisePostBackEvent (string eventArgument)
                {
-#if NET_2_0
                        RaisePostBackEvent (eventArgument);
-#else
-                       RaisePostBackEventInternal (eventArgument);
-#endif
                }
 
-#if NET_2_0
-               protected internal
-#else          
-               protected
-#endif         
-               override void OnPreRender (EventArgs e)
+               protected internal override void OnPreRender (EventArgs e)
                {
                        base.OnPreRender (e);
                        if (Events [ServerClickEvent] != null)
@@ -249,29 +212,8 @@ namespace System.Web.UI.HtmlControls {
                                server_click (this, e);
                }
 
-#if !NET_2_0
-               bool RenderOnClick ()
-               {
-                       if (Page == null || !CausesValidation)
-                               return false;
-
-                       CultureInfo inv = Helpers.InvariantCulture;
-                       string input_type = Type;
-                       if (0 == String.Compare (input_type, "submit", true, inv) &&
-                               Page.Validators.Count > 0)
-                               return true;
-
-                       if (0 == String.Compare (input_type, "button", true, inv) &&
-                               Events [ServerClickEvent] != null)
-                               return true;
-
-                       return false;
-               }
-#endif
-
                protected override void RenderAttributes (HtmlTextWriter writer)
                {
-#if NET_2_0
                        CultureInfo inv = Helpers.InvariantCulture;
                        string input_type = Type;
                        if (0 != String.Compare (input_type, "reset", true, inv) &&
@@ -283,9 +225,11 @@ namespace System.Web.UI.HtmlControls {
                                        onclick = ClientScriptManager.EnsureEndsWithSemicolon (Attributes ["onclick"] + onclick);
                                        Attributes.Remove ("onclick");
                                }
-                               if (Page != null) {
+
+                               Page page = Page;
+                               if (page != null) {
                                        PostBackOptions options = GetPostBackOptions ();
-                                       onclick += Page.ClientScript.GetPostBackEventReference (options, true);
+                                       onclick += page.ClientScript.GetPostBackEventReference (options, true);
                                }
 
                                if (onclick.Length > 0) {
@@ -293,49 +237,31 @@ namespace System.Web.UI.HtmlControls {
                                        writer.WriteAttribute ("language", "javascript");
                                }
                        }
-#else
-                       if (RenderOnClick ()) {
-                               string oc = null;
-                               ClientScriptManager csm = new ClientScriptManager (Page);
-                               if (Page.AreValidatorsUplevel ()) {
-                                       oc = csm.GetClientValidationEvent ();
-                               } else if (Events [ServerClickEvent] != null) {
-                                       oc = Attributes ["onclick"] + " " + csm.GetPostBackEventReference (this, "");
-                               }
-                               
-                               if (oc != null) {
-                                       writer.WriteAttribute ("language", "javascript");
-                                       writer.WriteAttribute ("onclick", oc, true);
-                               }
-                       }
-#endif
 
                        Attributes.Remove ("CausesValidation");
-#if NET_2_0
                        // LAMESPEC: MS doesn't actually remove this
                        //attribute.  it shows up in the rendered
                        //output.
 
                        // Attributes.Remove("ValidationGroup");
-#endif
                        base.RenderAttributes (writer);
                }
 
-#if NET_2_0
-               PostBackOptions GetPostBackOptions () {
+               PostBackOptions GetPostBackOptions ()
+               {
+                       Page page = Page;
                        PostBackOptions options = new PostBackOptions (this);
                        options.ValidationGroup = null;
                        options.ActionUrl = null;
                        options.Argument = String.Empty;
                        options.RequiresJavaScriptProtocol = false;
                        options.ClientSubmit = (0 != String.Compare (Type, "submit", true, Helpers.InvariantCulture));
-                       options.PerformValidation = CausesValidation && Page != null && Page.Validators.Count > 0;
+                       options.PerformValidation = CausesValidation && page != null && page.Validators.Count > 0;
                        if (options.PerformValidation)
                                options.ValidationGroup = ValidationGroup;
 
                        return options;
                }
-#endif
 
                [WebSysDescription("")]
                [WebCategory("Action")]
@@ -343,7 +269,6 @@ namespace System.Web.UI.HtmlControls {
                        add { Events.AddHandler (ServerClickEvent, value); }
                        remove { Events.RemoveHandler (ServerClickEvent, value); }
                }
-       }
-       
+       }       
 }
 
index 2b8f7568fc1f6d27b4bdbda4452d51646d6cc6b0..59eefc7a12f291657a069821fdf8480f86b5ed32 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Dick Porter  <dick@ximian.com>
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -37,11 +37,11 @@ namespace System.Web.UI.HtmlControls
        [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        // attributes
        [DefaultEvent ("ServerChange")]
-#if NET_2_0
        [SupportsEventValidation]
-#endif
        public class HtmlInputCheckBox : HtmlInputControl, IPostBackDataHandler
        {
+               static readonly object EventServerChange = new object ();
+               
                public HtmlInputCheckBox () : base ("checkbox")
                {
                }
@@ -50,11 +50,8 @@ namespace System.Web.UI.HtmlControls
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                [WebSysDescription("")]
                [WebCategory("Misc")]
-#if NET_2_0
                [TypeConverter (typeof(MinimizableAttributeTypeConverter))]
-#endif
-               public bool Checked
-               {
+               public bool Checked {
                        get {
                                string check = Attributes["checked"];
 
@@ -72,13 +69,10 @@ namespace System.Web.UI.HtmlControls
                                }
                        }
                }
-               
-               static readonly object EventServerChange = new object ();
 
                [WebSysDescription("")]
                [WebCategory("Action")]
-               public event EventHandler ServerChange
-               {
+               public event EventHandler ServerChange {
                        add {
                                Events.AddHandler (EventServerChange, value);
                        }
@@ -87,29 +81,22 @@ namespace System.Web.UI.HtmlControls
                        }
                }
 
-#if NET_2_0
                protected override void RenderAttributes (HtmlTextWriter writer)
                {
-                       if (Page != null)
-                               Page.ClientScript.RegisterForEventValidation (UniqueID);
+                       Page page = Page;
+                       if (page != null)
+                               page.ClientScript.RegisterForEventValidation (UniqueID);
                        base.RenderAttributes (writer);
                }
-#endif
-
-#if NET_2_0
-               protected internal
-#else
-               protected
-#endif
-               override void OnPreRender (EventArgs e)
+
+               protected internal override void OnPreRender (EventArgs e)
                {
                        base.OnPreRender (e);
 
-                       if (Page != null && !Disabled) {
-                               Page.RegisterRequiresPostBack (this);
-#if NET_2_0
-                               Page.RegisterEnabledControl (this);
-#endif
+                       Page page = Page;
+                       if (page != null && !Disabled) {
+                               page.RegisterRequiresPostBack (this);
+                               page.RegisterEnabledControl (this);
                        }
                }
 
@@ -117,9 +104,8 @@ namespace System.Web.UI.HtmlControls
                {
                        EventHandler handler = (EventHandler)Events[EventServerChange];
 
-                       if (handler != null) {
+                       if (handler != null)
                                handler (this, e);
-                       }
                }
 
                bool LoadPostDataInternal (string postDataKey, NameValueCollection postCollection)
@@ -141,7 +127,6 @@ namespace System.Web.UI.HtmlControls
                        OnServerChange (EventArgs.Empty);
                }
 
-#if NET_2_0
                protected virtual bool LoadPostData (string postDataKey, NameValueCollection postCollection)
                {
                        return LoadPostDataInternal (postDataKey, postCollection);
@@ -152,24 +137,15 @@ namespace System.Web.UI.HtmlControls
                        ValidateEvent (UniqueID, String.Empty);
                        RaisePostDataChangedEventInternal ();
                }
-#endif
                
                bool IPostBackDataHandler.LoadPostData (string postDataKey, NameValueCollection postCollection)
                {
-#if NET_2_0
                        return LoadPostData (postDataKey, postCollection);
-#else
-                       return LoadPostDataInternal (postDataKey, postCollection);
-#endif
                }
 
                void IPostBackDataHandler.RaisePostDataChangedEvent ()
                {
-#if NET_2_0
                        RaisePostDataChangedEvent();
-#else
-                       RaisePostDataChangedEventInternal ();
-#endif
                }
        }
 }
index aa1370ed01f052a12bed30bd35d5886a25b6fb0a..3dd53826e820f8abae401bbb16440b0151a4bde0 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Sebastien Pouliot  <sebastien@ximian.com>
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
 using System.ComponentModel;
 using System.Security.Permissions;
 
-namespace System.Web.UI.HtmlControls {
-
+namespace System.Web.UI.HtmlControls
+{
        // CAS
        [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        // attributes
-#if NET_2_0
        [ControlBuilder (typeof (HtmlEmptyTagControlBuilder))]
-#else
-       [ControlBuilder (typeof (HtmlControlBuilder))]
-#endif
-       public abstract class HtmlInputControl : HtmlControl {
-
+       public abstract class HtmlInputControl : HtmlControl
+       {
                protected HtmlInputControl (string type)
                        : base ("input")
                {
index f1d76bdecb6729cec1d33bcafe8942d37b3cf402..38fe556e5cd2c2516cf3d35f8ba83f8a15364379 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Dick Porter  <dick@ximian.com>
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -39,6 +39,8 @@ namespace System.Web.UI.HtmlControls
        [ValidationProperty ("Value")]
        public class HtmlInputFile : HtmlInputControl , IPostBackDataHandler
        {
+               HttpPostedFile posted_file;
+
                public HtmlInputFile () : base ("file")
                {
                }
@@ -46,8 +48,7 @@ namespace System.Web.UI.HtmlControls
                [DefaultValue ("")]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                [WebSysDescription("")]
-               public string Accept 
-               {
+               public string Accept {
                        get {
                                string acc = Attributes["accept"];
 
@@ -69,8 +70,7 @@ namespace System.Web.UI.HtmlControls
                [DefaultValue ("")]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                [WebSysDescription("")]
-               public int MaxLength 
-               {
+               public int MaxLength {
                        get {
                                string maxlen = Attributes["maxlength"];
                                
@@ -88,30 +88,22 @@ namespace System.Web.UI.HtmlControls
                                }
                        }
                }
-
-               HttpPostedFile posted_file;
                
                [DefaultValue ("")]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                [WebSysDescription("")]
                [WebCategory("Misc")]
-               public HttpPostedFile PostedFile 
-               {
+               public HttpPostedFile PostedFile {
                        get {
                                return (posted_file);
                        }
                }
                
-#if NET_2_0
                [DefaultValue ("-1")]
-#else
-               [DefaultValue ("")]
-#endif
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                [WebSysDescription("")]
                [WebCategory("Appearance")]
-               public int Size 
-               {
+               public int Size {
                        get {
                                string size = Attributes["size"];
                                
@@ -131,8 +123,7 @@ namespace System.Web.UI.HtmlControls
                }
                
                [Browsable (false)]
-               public override string Value 
-               {
+               public override string Value {
                        get {
                                HttpPostedFile file = PostedFile;
                                if (file == null)
@@ -145,24 +136,18 @@ namespace System.Web.UI.HtmlControls
                        }
                }
 
-#if NET_2_0
-               protected internal
-#else
-               protected
-#endif         
-               override void OnPreRender (EventArgs e)
+               protected internal override void OnPreRender (EventArgs e)
                {
                        base.OnPreRender (e);
 
-                       if (Page != null && !Disabled) {
-                               Page.RegisterRequiresPostBack (this);
-#if NET_2_0
-                               Page.RegisterEnabledControl (this);
-#endif
+                       Page page = Page;
+                       if (page != null && !Disabled) {
+                               page.RegisterRequiresPostBack (this);
+                               page.RegisterEnabledControl (this);
                        }
                        
                        HtmlForm form = (HtmlForm) SearchParentByType (typeof (HtmlForm));
-                       if (form != null && form.Enctype == "")
+                       if (form != null && form.Enctype == String.Empty)
                                form.Enctype = "multipart/form-data";
                }
 
@@ -181,7 +166,9 @@ namespace System.Web.UI.HtmlControls
 
                bool LoadPostDataInternal (string postDataKey, NameValueCollection postCollection)
                {
-                       posted_file = Page.Request.Files [postDataKey];
+                       Page page = Page;
+                       if (page != null)
+                               posted_file = page.Request.Files [postDataKey];
                        
                        return (false);
                }
@@ -191,7 +178,6 @@ namespace System.Web.UI.HtmlControls
                        /* No events to raise */
                }
 
-#if NET_2_0
                protected virtual bool LoadPostData (string postDataKey, NameValueCollection postCollection)
                {
                        return LoadPostDataInternal (postDataKey, postCollection);
@@ -201,24 +187,15 @@ namespace System.Web.UI.HtmlControls
                {
                        RaisePostDataChangedEventInternal ();
                }
-#endif         
                
                bool IPostBackDataHandler.LoadPostData (string postDataKey, NameValueCollection postCollection)
                {
-#if NET_2_0
                        return LoadPostData (postDataKey, postCollection);
-#else
-                       return LoadPostDataInternal (postDataKey, postCollection);
-#endif
                }
 
                void IPostBackDataHandler.RaisePostDataChangedEvent ()
                {
-#if NET_2_0
                        RaisePostDataChangedEvent ();
-#else
-                       RaisePostDataChangedEventInternal ();
-#endif
                }
        }
 }
index 755ce95b9bcc2969e0bbe1b223012adc0618c5f5..cf6b48eadfc2a69b876d715ebf7fd2a2e7cbf872 100644 (file)
@@ -24,7 +24,7 @@
 // Authors:
 //     Jackson Harper (jackson@ximian.com)
 //
-// (C) 2005 Novell, Inc.
+// (C) 2005-2010 Novell, Inc.
 
 using System.ComponentModel;
 using System.Collections.Specialized;
@@ -37,9 +37,7 @@ namespace System.Web.UI.HtmlControls {
        [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        // attributes
        [DefaultEvent ("ServerChange")]
-#if NET_2_0
        [SupportsEventValidation]
-#endif
        public class HtmlInputHidden : HtmlInputControl, IPostBackDataHandler {
 
                static readonly object ServerChangeEvent = new object ();
@@ -52,9 +50,7 @@ namespace System.Web.UI.HtmlControls {
                {
                        string data = postCollection [postDataKey];
                        if (data != null && data != Value) {
-#if NET_2_0
                                ValidateEvent (postDataKey, String.Empty);
-#endif
                                Value = data;
                                return true;
                        }
@@ -66,7 +62,6 @@ namespace System.Web.UI.HtmlControls {
                        OnServerChange (EventArgs.Empty);
                }
 
-#if NET_2_0
                protected virtual bool LoadPostData (string postDataKey, NameValueCollection postCollection)
                {
                        return LoadPostDataInternal (postDataKey, postCollection);
@@ -76,28 +71,18 @@ namespace System.Web.UI.HtmlControls {
                {
                        RaisePostDataChangedEventInternal ();
                }
-#endif         
                
                bool IPostBackDataHandler.LoadPostData (string postDataKey,
                                                        NameValueCollection postCollection)
                {
-#if NET_2_0
                        return LoadPostData (postDataKey, postCollection);
-#else
-                       return LoadPostDataInternal (postDataKey, postCollection);
-#endif
                }
 
                void IPostBackDataHandler.RaisePostDataChangedEvent ()
                {
-#if NET_2_0
                        RaisePostDataChangedEvent ();
-#else
-                       RaisePostDataChangedEventInternal ();
-#endif
                }
 
-#if NET_2_0
                protected override void RenderAttributes (HtmlTextWriter writer)
                {
                        Page page = Page;
@@ -106,19 +91,14 @@ namespace System.Web.UI.HtmlControls {
                        base.RenderAttributes (writer);
                }               
 
-               protected internal
-#else
-               protected
-#endif         
-               override void OnPreRender (EventArgs e)
+               protected internal override void OnPreRender (EventArgs e)
                {
                        base.OnPreRender (e);
 
-                       if (Page != null && !Disabled) {
-                               Page.RegisterRequiresPostBack (this);
-#if NET_2_0
-                               Page.RegisterEnabledControl (this);
-#endif
+                       Page page = Page;
+                       if (page != null && !Disabled) {
+                               page.RegisterRequiresPostBack (this);
+                               page.RegisterEnabledControl (this);
                        }
                }
 
index 3821c02eeaf65f078b9148f7c27784048f0c7250..d73f34fb05c23553aa6a675c99129f747960a8d0 100644 (file)
@@ -24,7 +24,7 @@
 // Authors:
 //     Jackson Harper (jackson@ximian.com)
 //
-// (C) 2005 Novell, Inc.
+// (C) 2005-2010 Novell, Inc.
 
 
 //
@@ -37,16 +37,14 @@ using System.ComponentModel;
 using System.Security.Permissions;
 using System.Web.Util;
 
-namespace System.Web.UI.HtmlControls {
-
+namespace System.Web.UI.HtmlControls
+{
        // CAS
        [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        // attributes
        [DefaultEvent("ServerClick")]
-#if NET_2_0
        [SupportsEventValidation]
-#endif
        public class HtmlInputImage : HtmlInputControl, IPostBackDataHandler, IPostBackEventHandler 
        {
                static readonly object ServerClickEvent = new object ();
@@ -61,12 +59,7 @@ namespace System.Web.UI.HtmlControls {
                [DefaultValue(true)]
                [WebSysDescription("")]
                [WebCategory("Behavior")]
-#if NET_2_0
-               public virtual
-#else
-               public
-#endif         
-               bool CausesValidation {
+               public virtual bool CausesValidation {
                        get {
                                return ViewState.GetBool ("CausesValidation", true);
                        }
@@ -86,9 +79,7 @@ namespace System.Web.UI.HtmlControls {
 
                [DefaultValue("")]
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
-#if NET_2_0
                [Localizable (true)]
-#endif         
                [WebSysDescription("")]
                [WebCategory("Appearance")]
                public string Alt {
@@ -100,19 +91,13 @@ namespace System.Web.UI.HtmlControls {
                [WebSysDescription("")]
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                [WebCategory("Appearance")]
-#if NET_2_0
                [UrlProperty]
-#endif
                public string Src {
                        get { return GetAtt ("src"); }
                        set { SetAtt ("src", value); }
                }
 
-#if NET_2_0
                [DefaultValue("-1")]
-#else          
-               [DefaultValue("")]
-#endif         
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                [WebSysDescription("")]
                [WebCategory("Appearance")]
@@ -152,11 +137,8 @@ namespace System.Web.UI.HtmlControls {
                void RaisePostBackEventInternal (string eventArgument)
                {
                        if (CausesValidation)
-#if NET_2_0
                                Page.Validate (ValidationGroup);
-#else
-                               Page.Validate ();
-#endif
+
                        OnServerClick (new ImageClickEventArgs (clicked_x, clicked_y));
                }
 
@@ -165,7 +147,6 @@ namespace System.Web.UI.HtmlControls {
                        /* no events to raise */
                }
 
-#if NET_2_0
                [DefaultValue ("")]
                public virtual string ValidationGroup
                {
@@ -192,51 +173,30 @@ namespace System.Web.UI.HtmlControls {
                        ValidateEvent (UniqueID, String.Empty);
                        RaisePostDataChangedEventInternal ();
                }
-#endif         
 
-               bool IPostBackDataHandler.LoadPostData (string postDataKey,
-                               NameValueCollection postCollection)
+               bool IPostBackDataHandler.LoadPostData (string postDataKey, NameValueCollection postCollection)
                {
-#if NET_2_0
                        return LoadPostData (postDataKey, postCollection);
-#else
-                       return LoadPostDataInternal (postDataKey, postCollection);
-#endif
                }
-
                
                void IPostBackDataHandler.RaisePostDataChangedEvent ()
                {
-#if NET_2_0
                        RaisePostDataChangedEvent();
-#else
-                       RaisePostDataChangedEventInternal ();
-#endif
                }
                                
                void IPostBackEventHandler.RaisePostBackEvent (string eventArgument)
                {
-#if NET_2_0
                        RaisePostBackEvent (eventArgument);
-#else
-                       RaisePostBackEventInternal (eventArgument);
-#endif
                }
 
-#if NET_2_0
-               protected internal
-#else          
-               protected
-#endif         
-               override void OnPreRender (EventArgs e)
+               protected internal override void OnPreRender (EventArgs e)
                {
                        base.OnPreRender (e);
-                       
-                       if (Page != null && !Disabled) {
-                               Page.RegisterRequiresPostBack (this);
-#if NET_2_0
-                               Page.RegisterEnabledControl (this);
-#endif
+
+                       Page page = Page;
+                       if (page != null && !Disabled) {
+                               page.RegisterRequiresPostBack (this);
+                               page.RegisterEnabledControl (this);
                        }
                }
 
@@ -249,20 +209,14 @@ namespace System.Web.UI.HtmlControls {
 
                protected override void RenderAttributes (HtmlTextWriter writer)
                {
-#if NET_2_0
-                       if (Page != null)
-                               Page.ClientScript.RegisterForEventValidation (UniqueID);
+                       Page page = Page;
+                       if (page != null)
+                               page.ClientScript.RegisterForEventValidation (UniqueID);
                        
-                       if (CausesValidation && Page != null && Page.AreValidatorsUplevel (ValidationGroup)) {
-                               ClientScriptManager csm = Page.ClientScript;
+                       if (CausesValidation && page != null && page.AreValidatorsUplevel (ValidationGroup)) {
+                               ClientScriptManager csm = page.ClientScript;
                                Attributes ["onclick"] += csm.GetClientValidationEvent (ValidationGroup);
                        }
-#else          
-                       if (CausesValidation && Page != null && Page.AreValidatorsUplevel ()) {
-                               ClientScriptManager csm = new ClientScriptManager (Page);
-                               writer.WriteAttribute ("onclick", csm.GetClientValidationEvent ());
-                       }
-#endif         
 
                        PreProcessRelativeReference (writer,"src");
                        base.RenderAttributes (writer);
@@ -292,4 +246,3 @@ namespace System.Web.UI.HtmlControls {
                }
        }
 }
-
index 1639215b534408a947281b702329f955c29cd558..a91d78abf85af33ae30069f95b39e1568a1fb87e 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Chris Toshok  <toshok@ximian.com>
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_0
-
 using System.ComponentModel;
 using System.Collections.Specialized;
 using System.Security.Permissions;
 
-namespace System.Web.UI.HtmlControls {
-
+namespace System.Web.UI.HtmlControls
+{
        // CAS
        [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
@@ -75,4 +73,4 @@ namespace System.Web.UI.HtmlControls {
        }
 
 }
-#endif
+
index 15589da533f65ea9b6927d1734bd74876395f3f8..bcccf968bcc535cd3944341863b0c7771fbef3e6 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Sebastien Pouliot  <sebastien@ximian.com>
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -30,16 +30,14 @@ using System.ComponentModel;
 using System.Collections.Specialized;
 using System.Security.Permissions;
 
-namespace System.Web.UI.HtmlControls {
-
+namespace System.Web.UI.HtmlControls
+{
        // CAS
        [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        // attributes
        [DefaultEvent ("ServerChange")]
-#if NET_2_0
        [SupportsEventValidation]
-#endif
        public class HtmlInputRadioButton : HtmlInputControl, IPostBackDataHandler 
        {
                static readonly object serverChangeEvent = new object ();
@@ -94,20 +92,14 @@ namespace System.Web.UI.HtmlControls {
                        }
                }
 
-#if NET_2_0
-               protected internal
-#else
-               protected
-#endif         
-               override void OnPreRender (EventArgs e)
+               protected internal override void OnPreRender (EventArgs e)
                {
                        base.OnPreRender (e);
 
-                       if (Page != null && !Disabled) {
-                               Page.RegisterRequiresPostBack (this);
-#if NET_2_0
-                               Page.RegisterEnabledControl (this);
-#endif
+                       Page page = Page;
+                       if (page != null && !Disabled) {
+                               page.RegisterRequiresPostBack (this);
+                               page.RegisterEnabledControl (this);
                        }
                }
 
@@ -120,34 +112,26 @@ namespace System.Web.UI.HtmlControls {
 
                protected override void RenderAttributes (HtmlTextWriter writer)
                {
-#if NET_2_0
-                       if (Page != null)
-                               Page.ClientScript.RegisterForEventValidation (this.UniqueID, Value);
-#endif
+                       Page page = Page;
+                       if (page != null)
+                               page.ClientScript.RegisterForEventValidation (this.UniqueID, Value);
                        writer.WriteAttribute ("value", Value, true);
                        Attributes.Remove ("value");
                        base.RenderAttributes (writer);
                }
-#if NET_2_0
-               protected virtual 
-#endif
-               bool LoadPostData (string postDataKey, NameValueCollection postCollection)
+               
+               protected virtual bool LoadPostData (string postDataKey, NameValueCollection postCollection)
                {
                        bool checkedOnClient = postCollection [Name] == Value;
                        if (Checked == checkedOnClient)
                                return false;
 
-#if NET_2_0
                        ValidateEvent (UniqueID, Value);
-#endif
                        Checked = checkedOnClient;
                        return checkedOnClient;
                }
 
-#if NET_2_0
-               protected virtual 
-#endif
-               void RaisePostDataChangedEvent ()
+               protected virtual void RaisePostDataChangedEvent ()
                {
                        OnServerChange (EventArgs.Empty);
                }
index 32551d3cb07c1a6edd3af35a8001bf5db10ed2d4..9c9314daadacb6e0ac51f90da54b00bd25fc6468 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Chris Toshok  <toshok@ximian.com>
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_0
-
 using System.ComponentModel;
 using System.Security.Permissions;
 
-namespace System.Web.UI.HtmlControls {
-
+namespace System.Web.UI.HtmlControls
+{
        // CAS
        [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
@@ -85,4 +83,4 @@ namespace System.Web.UI.HtmlControls {
 
        }
 }
-#endif
+
index 1fa8621810288e85115f97fadfaced858d605eab..9f75a74fae16bd3f464163adf05f41e844466d81 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Chris Toshok  <toshok@ximian.com>
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_0
-
 using System.ComponentModel;
 using System.Security.Permissions;
 
-namespace System.Web.UI.HtmlControls {
-
+namespace System.Web.UI.HtmlControls
+{
        // CAS
        [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
@@ -57,4 +55,4 @@ namespace System.Web.UI.HtmlControls {
                }
        }
 }
-#endif
+
index 2540a4288b63ea49fa1b30f890a9ff9835311157..cace1b4ef8c2fd932116a2415d17efa30e7e733f 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Sebastien Pouliot  <sebastien@ximian.com>
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -32,17 +32,15 @@ using System.Globalization;
 using System.Security.Permissions;
 using System.Web.Util;
 
-namespace System.Web.UI.HtmlControls {
-
+namespace System.Web.UI.HtmlControls
+{
        // CAS
        [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        // attributes
        [DefaultEvent ("ServerChange")]
        [ValidationProperty ("Value")]
-#if NET_2_0
        [SupportsEventValidation]
-#endif
        public class HtmlInputText : HtmlInputControl, IPostBackDataHandler 
        {
                static readonly object serverChangeEvent = new object ();
@@ -74,11 +72,7 @@ namespace System.Web.UI.HtmlControls {
                        }
                }
 
-#if NET_2_0
                [DefaultValue (-1)]
-#else
-               [DefaultValue ("")]
-#endif
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                [WebSysDescription("")]
                [WebCategory("Appearance")]
@@ -108,8 +102,6 @@ namespace System.Web.UI.HtmlControls {
                        }
                }
 
-
-#if NET_2_0
                protected internal override void Render (HtmlTextWriter writer)
                {
                        Page page = Page;
@@ -117,21 +109,15 @@ namespace System.Web.UI.HtmlControls {
                                page.ClientScript.RegisterForEventValidation (UniqueID);
                        base.Render (writer);
                }
-#endif
 
-#if NET_2_0
-               protected internal
-#else          
-               protected
-#endif         
-               override void OnPreRender (EventArgs e)
+               protected internal override void OnPreRender (EventArgs e)
                {
                        base.OnPreRender (e);
-                       if (Page != null && !Disabled) {
-                               Page.RegisterRequiresPostBack (this);
-#if NET_2_0
-                               Page.RegisterEnabledControl (this);
-#endif
+
+                       Page page = Page;
+                       if (page != null && !Disabled) {
+                               page.RegisterRequiresPostBack (this);
+                               page.RegisterEnabledControl (this);
                        }
                }
 
@@ -167,7 +153,6 @@ namespace System.Web.UI.HtmlControls {
                        OnServerChange (EventArgs.Empty);
                }
 
-#if NET_2_0
                protected virtual bool LoadPostData (string postDataKey, NameValueCollection postCollection)
                {
                        return LoadPostDataInternal (postDataKey, postCollection);
@@ -178,27 +163,17 @@ namespace System.Web.UI.HtmlControls {
                        ValidateEvent (UniqueID, String.Empty);
                        RaisePostDataChangedEventInternal ();
                }
-#endif
 
                bool IPostBackDataHandler.LoadPostData (string postDataKey, NameValueCollection postCollection)
                {
-#if NET_2_0
                        return LoadPostData (postDataKey, postCollection);
-#else
-                       return LoadPostDataInternal (postDataKey, postCollection);
-#endif
                }
 
                void IPostBackDataHandler.RaisePostDataChangedEvent ()
                {
-#if NET_2_0
                        RaisePostDataChangedEvent ();
-#else
-                       RaisePostDataChangedEventInternal ();
-#endif
                }
 
-
                [WebSysDescription("")]
                [WebCategory("Action")]
                public event EventHandler ServerChange {
index c92d55db39d68db287138991e9c3de5eece73013..2c068e368b13caaf2914b334f6e138e7a7c8af95 100644 (file)
@@ -4,7 +4,7 @@
 // Authors:
 //     Chris Toshok (toshok@ximian.com)
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -26,8 +26,6 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_0
-
 using System.ComponentModel;
 using System.Collections;
 using System.Security.Permissions;
@@ -77,4 +75,3 @@ namespace System.Web.UI.HtmlControls
        }
 }
 
-#endif
index dfd71c56bffacb27470093ce39d36774a4094d7a..6cb40f441a68b3943025111a07903235c838abe2 100644 (file)
@@ -4,7 +4,7 @@
 // Authors:
 //     Chris Toshok (toshok@ximian.com)
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -26,8 +26,6 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_0
-
 using System.ComponentModel;
 using System.Collections;
 using System.Security.Permissions;
@@ -49,7 +47,7 @@ namespace System.Web.UI.HtmlControls
                        get {
                                string s = Attributes["content"];
                                if (s == null)
-                                       return "";
+                                       return String.Empty;
                                return s;
                        }
                        set {
@@ -66,7 +64,7 @@ namespace System.Web.UI.HtmlControls
                        get {
                                string s = Attributes["http-equiv"];
                                if (s == null)
-                                       return "";
+                                       return String.Empty;
                                return s;
                        }
                        set {
@@ -83,7 +81,7 @@ namespace System.Web.UI.HtmlControls
                        get {
                                string s = Attributes["name"];
                                if (s == null)
-                                       return "";
+                                       return String.Empty;
                                return s;
                        }
                        set {
@@ -100,7 +98,7 @@ namespace System.Web.UI.HtmlControls
                        get {
                                string s = Attributes["scheme"];
                                if (s == null)
-                                       return "";
+                                       return String.Empty;
                                return s;
                        }
                        set {
@@ -126,4 +124,3 @@ namespace System.Web.UI.HtmlControls
        }
 }
 
-#endif
index 6a9c5a8891190fd21f326bf3dc12115ca58997ab..5df90808b7907b3371eb92b4928cf641d0e0098f 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Dick Porter  <dick@ximian.com>
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -43,16 +43,17 @@ namespace System.Web.UI.HtmlControls
        [DefaultEvent ("ServerChange")]
        [ValidationProperty ("Value")]
        [ControlBuilder (typeof (HtmlSelectBuilder))]
-#if NET_2_0
        [SupportsEventValidation]
-       public class HtmlSelect : HtmlContainerControl, IPostBackDataHandler, IParserAccessor {
+       public class HtmlSelect : HtmlContainerControl, IPostBackDataHandler, IParserAccessor
+       {
+               static readonly object EventServerChange = new object ();
 
                DataSourceView _boundDataSourceView;
                bool requiresDataBinding;
                bool _initialized;
-#else
-       public class HtmlSelect : HtmlContainerControl, IPostBackDataHandler {
-#endif
+               object datasource;
+               ListItemCollection items;
+
                public HtmlSelect () : base ("select")
                {
                }
@@ -61,8 +62,7 @@ namespace System.Web.UI.HtmlControls
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                [WebSysDescription("")]
                [WebCategory("Data")]
-               public virtual string DataMember 
-               {
+               public virtual string DataMember {
                        get {
                                string member = Attributes["datamember"];
 
@@ -80,15 +80,12 @@ namespace System.Web.UI.HtmlControls
                                }
                        }
                }
-
-               object datasource;
                
                [DefaultValue (null)]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                [WebSysDescription("")]
                [WebCategory("Data")]
-               public virtual object DataSource 
-               {
+               public virtual object DataSource {
                        get {
                                return (datasource);
                        }
@@ -103,10 +100,8 @@ namespace System.Web.UI.HtmlControls
                        }
                }
 
-#if NET_2_0
                [DefaultValue ("")]
-               public virtual string DataSourceID
-               {
+               public virtual string DataSourceID {
                        get {
                                return ViewState.GetString ("DataSourceID", "");
                        }
@@ -120,14 +115,11 @@ namespace System.Web.UI.HtmlControls
                                OnDataPropertyChanged ();
                        }
                }
-#endif
-                               
 
                [DefaultValue ("")]
                [WebSysDescription("")]
                [WebCategory("Data")]
-               public virtual string DataTextField 
-               {
+               public virtual string DataTextField {
                        get {
                                string text = Attributes["datatextfield"];
 
@@ -149,8 +141,7 @@ namespace System.Web.UI.HtmlControls
                [DefaultValue ("")]
                [WebSysDescription("")]
                [WebCategory("Data")]
-               public virtual string DataValueField 
-               {
+               public virtual string DataValueField {
                        get {
                                string value = Attributes["datavaluefield"];
 
@@ -169,8 +160,7 @@ namespace System.Web.UI.HtmlControls
                        }
                }
 
-               public override string InnerHtml 
-               {
+               public override string InnerHtml {
                        get {
                                throw new NotSupportedException ();
                        }
@@ -179,8 +169,7 @@ namespace System.Web.UI.HtmlControls
                        }
                }
 
-               public override string InnerText
-               {
+               public override string InnerText {
                        get {
                                throw new NotSupportedException ();
                        }
@@ -189,21 +178,15 @@ namespace System.Web.UI.HtmlControls
                        }
                }
 
-#if NET_2_0
-               protected bool IsBoundUsingDataSourceID 
-               {
+               protected bool IsBoundUsingDataSourceID {
                        get {
                                return (DataSourceID.Length != 0);
                        }
                }
-#endif         
-
-               ListItemCollection items;
                
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                [Browsable (false)]
-               public ListItemCollection Items 
-               {
+               public ListItemCollection Items {
                        get {
                                if (items == null) {
                                        items = new ListItemCollection ();
@@ -219,8 +202,7 @@ namespace System.Web.UI.HtmlControls
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                [WebSysDescription("")]
                [WebCategory("Behavior")]
-               public bool Multiple 
-               {
+               public bool Multiple {
                        get {
                                string multi = Attributes["multiple"];
 
@@ -243,8 +225,7 @@ namespace System.Web.UI.HtmlControls
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                [WebSysDescription("")]
                [WebCategory("Behavior")]
-               public string Name 
-               {
+               public string Name {
                        get {
                                return (UniqueID);
                        }
@@ -253,18 +234,14 @@ namespace System.Web.UI.HtmlControls
                        }
                }
 
-#if NET_2_0
-               protected bool RequiresDataBinding 
-               {
+               protected bool RequiresDataBinding {
                        get { return requiresDataBinding; }
                        set { requiresDataBinding = value; }
                }
-#endif
 
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                [Browsable (false)]
-               public virtual int SelectedIndex 
-               {
+               public virtual int SelectedIndex {
                        get {
                                /* Make sure Items has been initialised */
                                ListItemCollection listitems = Items;
@@ -313,8 +290,7 @@ namespace System.Web.UI.HtmlControls
                /* "internal infrastructure" according to the docs,
                 * but has some documentation in 2.0
                 */
-               protected virtual int[] SelectedIndices
-               {
+               protected virtual int[] SelectedIndices {
                        get {
                                ArrayList selected = new ArrayList ();
 
@@ -332,8 +308,7 @@ namespace System.Web.UI.HtmlControls
                
 
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
-               public int Size 
-               {
+               public int Size {
                        get {
                                string size = Attributes["size"];
 
@@ -353,8 +328,7 @@ namespace System.Web.UI.HtmlControls
                }
 
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
-               public string Value 
-               {
+               public string Value {
                        get {
                                int sel = SelectedIndex;
 
@@ -373,12 +347,9 @@ namespace System.Web.UI.HtmlControls
                        }
                }
 
-               static readonly object EventServerChange = new object ();
-               
                [WebSysDescription("")]
                [WebCategory("Action")]
-               public event EventHandler ServerChange
-               {
+               public event EventHandler ServerChange {
                        add {
                                Events.AddHandler (EventServerChange, value);
                        }
@@ -418,7 +389,6 @@ namespace System.Web.UI.HtmlControls
                        return (base.CreateControlCollection ());
                }
 
-#if NET_2_0
                protected void EnsureDataBound ()
                {
                        if (IsBoundUsingDataSourceID && RequiresDataBinding)
@@ -443,7 +413,6 @@ namespace System.Web.UI.HtmlControls
 
                        return result;
                }
-#endif         
 
                protected override void LoadViewState (object savedState)
                {
@@ -473,17 +442,9 @@ namespace System.Web.UI.HtmlControls
 
                        listitems.Clear ();
                        
-                       IEnumerable list;
-
-#if NET_2_0
-                               list = GetData ();
-#else
-                               list = DataSourceResolver.ResolveDataSource (DataSource, DataMember);
-#endif
-
-                       if (list == null) {
+                       IEnumerable list = GetData ();
+                       if (list == null)
                                return;
-                       }
                        
                        foreach (object container in list) {
                                string text = null;
@@ -520,13 +481,10 @@ namespace System.Web.UI.HtmlControls
                                ListItem item = new ListItem (text, value);
                                listitems.Add (item);
                        }
-#if NET_2_0
                        RequiresDataBinding = false;
                        IsDataBound = true;
-#endif
                }
 
-#if NET_2_0
                protected virtual void OnDataPropertyChanged ()
                {
                        if (_initialized)
@@ -546,7 +504,8 @@ namespace System.Web.UI.HtmlControls
                        Page.PreLoad += new EventHandler (OnPagePreLoad);
                }
 
-               protected virtual void OnPagePreLoad (object sender, EventArgs e) {
+               protected virtual void OnPagePreLoad (object sender, EventArgs e)
+               {
                        Initialize ();
                }
 
@@ -558,7 +517,8 @@ namespace System.Web.UI.HtmlControls
                        base.OnLoad (e);
                }
 
-               void Initialize () {
+               void Initialize ()
+               {
                        _initialized = true;
 
                        if (!IsDataBound)
@@ -568,7 +528,7 @@ namespace System.Web.UI.HtmlControls
                                ConnectToDataSource ();
                }
 
-               bool IsDataBound {
+               bool IsDataBound{
                        get {
                                return ViewState.GetBool ("_DataBound", false);
                        }
@@ -584,8 +544,9 @@ namespace System.Web.UI.HtmlControls
 
                        /* verify that the data source exists and is an IDataSource */
                        object ctrl = null;
-                       if (Page != null)
-                               ctrl = Page.FindControl (DataSourceID);
+                       Page page = Page;
+                       if (page != null)
+                               ctrl = page.FindControl (DataSourceID);
 
                        if (ctrl == null || !(ctrl is IDataSource)) {
                                string format;
@@ -602,26 +563,16 @@ namespace System.Web.UI.HtmlControls
                        _boundDataSourceView.DataSourceViewChanged += OnDataSourceViewChanged;
                        return _boundDataSourceView;
                }
-#endif
 
-#if NET_2_0
-               protected internal
-#else          
-               protected
-#endif         
-               override void OnPreRender (EventArgs e)
+               protected internal override void OnPreRender (EventArgs e)
                {
-#if NET_2_0
                        EnsureDataBound ();
-#endif
-
                        base.OnPreRender (e);
 
-                       if (Page != null && !Disabled) {
-                               Page.RegisterRequiresPostBack (this);
-#if NET_2_0
-                               Page.RegisterEnabledControl (this);
-#endif
+                       Page page = Page;
+                       if (page != null && !Disabled) {
+                               page.RegisterRequiresPostBack (this);
+                               page.RegisterEnabledControl (this);
                        }
                }
 
@@ -636,10 +587,10 @@ namespace System.Web.UI.HtmlControls
                
                protected override void RenderAttributes (HtmlTextWriter w)
                {
-#if NET_2_0
-                       if (Page != null)
-                               Page.ClientScript.RegisterForEventValidation (UniqueID);
-#endif
+                       Page page = Page;
+                       if (page != null)
+                               page.ClientScript.RegisterForEventValidation (UniqueID);
+
                        /* If there is no "name" attribute,
                         * LoadPostData doesn't work...
                         */
@@ -654,18 +605,12 @@ namespace System.Web.UI.HtmlControls
                        base.RenderAttributes (w);
                }
                
-#if NET_2_0
-               protected internal
-#else
-               protected
-#endif         
-               override void RenderChildren (HtmlTextWriter w)
+               protected internal override void RenderChildren (HtmlTextWriter w)
                {
                        base.RenderChildren (w);
 
-                       if (items == null) {
+                       if (items == null)
                                return;
-                       }
                        
                        w.WriteLine ();
 
@@ -751,18 +696,12 @@ namespace System.Web.UI.HtmlControls
                        }
                }
 
-#if NET_2_0
-               protected virtual
-#endif
-               void RaisePostDataChangedEvent ()
+               protected virtual void RaisePostDataChangedEvent ()
                {
                        OnServerChange (EventArgs.Empty);
                }
 
-#if NET_2_0
-               protected virtual
-#endif
-               bool LoadPostData (string postDataKey, NameValueCollection postCollection)
+               protected virtual bool LoadPostData (string postDataKey, NameValueCollection postCollection)
                {
                        /* postCollection contains the values that are
                         * selected
@@ -806,10 +745,8 @@ namespace System.Web.UI.HtmlControls
                                }
                        }
 
-#if NET_2_0
                        if (changed)
                                ValidateEvent (postDataKey, String.Empty);
-#endif
                        return (changed);
                }
 
index 806f42c766d72e05eba726f01261197dbaba7d7b..b4c8e726e07f85eb40913c74c18955d985f2fa3b 100644 (file)
@@ -5,7 +5,7 @@
 //     Gonzalo Paniagua Javier (gonzalo@ximian.com)
 //
 // (C) 2003 Ximian, Inc (http://www.ximian.com)
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -38,10 +38,7 @@ namespace System.Web.UI.HtmlControls
        // CAS
        [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
-#if NET_2_0
-       public
-#endif
-       class HtmlSelectBuilder : ControlBuilder
+       public class HtmlSelectBuilder : ControlBuilder
        {
                public override bool AllowWhitespaceLiterals () 
                {
index ca9015275224bf9fc59f65a7879bbba38e866a11..7ae378a0bc9bbbac34e1c3f1b062638fa66b86fc 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Sebastien Pouliot  <sebastien@ximian.com>
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -31,15 +31,15 @@ using System.Globalization;
 using System.Security.Permissions;
 using System.Web.Util;
 
-namespace System.Web.UI.HtmlControls {
-
+namespace System.Web.UI.HtmlControls
+{
        // CAS
        [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        // attributes
        [ParseChildren (true, "Rows")]  
-       public class HtmlTable : HtmlContainerControl {
-
+       public class HtmlTable : HtmlContainerControl
+       {
                HtmlTableRowCollection _rows;
 
                public HtmlTable ()
@@ -209,12 +209,7 @@ namespace System.Web.UI.HtmlControls {
                        return new HtmlTableRowControlCollection (this);
                }
 
-#if NET_2_0
-               protected internal
-#else          
-               protected
-#endif         
-               override void RenderChildren (HtmlTextWriter writer)
+               protected internal override void RenderChildren (HtmlTextWriter writer)
                {
                        if (HasControls ()) {
                                writer.Indent++;
index 9873c45e6086278e98d202ac25b5af80f22459ca..6ee00e536ddd2a2215d2a0337fb68405da589e2f 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Sebastien Pouliot  <sebastien@ximian.com>
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -31,15 +31,15 @@ using System.Globalization;
 using System.Security.Permissions;
 using System.Web.Util;
 
-namespace System.Web.UI.HtmlControls {
-
+namespace System.Web.UI.HtmlControls
+{
        // CAS
        [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        // attributes
        [ConstructorNeedsTag (true)]
-       public class HtmlTableCell : HtmlContainerControl {
-
+       public class HtmlTableCell : HtmlContainerControl
+       {
                public HtmlTableCell ()
                        : base ("td")
                {
@@ -138,9 +138,7 @@ namespace System.Web.UI.HtmlControls {
 
                [DefaultValue ("")]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
-#if NET_2_0
                [TypeConverter (typeof (MinimizableAttributeTypeConverter))]
-#endif
                [WebSysDescription("")]
                [WebCategory("Behavior")]
                public bool NoWrap {
index b58ce168181c1346aee37bba4b397e64a9905729..c54b3570acbff82bdeb57468f2a0c852bd10a2d9 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Sebastien Pouliot  <sebastien@ximian.com>
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
 using System.ComponentModel;
 using System.Security.Permissions;
 
-namespace System.Web.UI.HtmlControls {
-
+namespace System.Web.UI.HtmlControls
+{
        // CAS
        [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        // attributes
        [ParseChildren (true, "Cells")] 
-       public class HtmlTableRow : HtmlContainerControl {
-
+       public class HtmlTableRow : HtmlContainerControl
+       {
                HtmlTableCellCollection _cells;
 
-
                public HtmlTableRow ()
                        : base ("tr")
                {
                }
 
-
                [DefaultValue ("")]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                [WebSysDescription("")]
@@ -162,12 +160,7 @@ namespace System.Web.UI.HtmlControls {
                        return new HtmlTableCellControlCollection (this);
                }
 
-#if NET_2_0
-               protected internal
-#else          
-               protected
-#endif         
-               override void RenderChildren (HtmlTextWriter writer)
+               protected internal override void RenderChildren (HtmlTextWriter writer)
                {
                        if (HasControls ()) {
                                writer.Indent++;
index 6afdb8bbe65cc546e3d98a640055d9565dbc7447..ba4057b17a0170744c30516a44c2c137b800460f 100644 (file)
@@ -4,7 +4,7 @@
 // Author:
 //     Sebastien Pouliot  <sebastien@ximian.com>
 //
-// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -32,17 +32,15 @@ using System.Globalization;
 using System.Security.Permissions;
 using System.Web.Util;
 
-namespace System.Web.UI.HtmlControls {
-
+namespace System.Web.UI.HtmlControls
+{
        // CAS
        [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        // attributes
        [DefaultEvent ("ServerChange")]
        [ValidationProperty ("Value")]
-#if NET_2_0
        [SupportsEventValidation]
-#endif
        public class HtmlTextArea : HtmlContainerControl, IPostBackDataHandler 
        {
                static readonly object serverChangeEvent = new object ();
@@ -52,7 +50,6 @@ namespace System.Web.UI.HtmlControls {
                {
                }
 
-
                [DefaultValue ("")]
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                [WebSysDescription("")]
@@ -114,20 +111,14 @@ namespace System.Web.UI.HtmlControls {
                        base.AddParsedSubObject (obj);
                }
 
-#if NET_2_0
-               protected internal
-#else          
-               protected
-#endif         
-               override void OnPreRender (EventArgs e)
+               protected internal override void OnPreRender (EventArgs e)
                {
                        base.OnPreRender (e);
 
-                       if (Page != null && !Disabled) {
-                               Page.RegisterRequiresPostBack (this);
-#if NET_2_0
-                               Page.RegisterEnabledControl (this);
-#endif
+                       Page page = Page;
+                       if (page != null && !Disabled) {
+                               page.RegisterRequiresPostBack (this);
+                               page.RegisterEnabledControl (this);
                        }
                }
 
@@ -140,17 +131,15 @@ namespace System.Web.UI.HtmlControls {
 
                protected override void RenderAttributes (HtmlTextWriter writer)
                {
-#if NET_2_0
-                       if (Page != null)
-                               Page.ClientScript.RegisterForEventValidation (UniqueID);
-#endif
-                       if (Attributes ["name"] == null) {
+                       Page page = Page;
+                       if (page != null)
+                               page.ClientScript.RegisterForEventValidation (UniqueID);
+                       
+                       if (Attributes ["name"] == null)
                                writer.WriteAttribute ("name", Name);
-                       }
                        base.RenderAttributes (writer);
                }
 
-#if NET_2_0
                protected virtual bool LoadPostData (string postDataKey, NameValueCollection postCollection)
                {
                        return DefaultLoadPostData (postDataKey, postCollection);
@@ -161,7 +150,6 @@ namespace System.Web.UI.HtmlControls {
                        ValidateEvent (UniqueID, String.Empty);
                        OnServerChange (EventArgs.Empty);
                }
-#endif
 
                internal bool DefaultLoadPostData (string postDataKey, NameValueCollection postCollection)
                {
@@ -175,23 +163,14 @@ namespace System.Web.UI.HtmlControls {
 
                bool IPostBackDataHandler.LoadPostData (string postDataKey, NameValueCollection postCollection)
                {
-#if NET_2_0
                        return LoadPostData (postDataKey, postCollection);
-#else
-                       return DefaultLoadPostData (postDataKey, postCollection);
-#endif
                }
 
                void IPostBackDataHandler.RaisePostDataChangedEvent ()
                {
-#if NET_2_0
                        RaisePostDataChangedEvent ();
-#else
-                       OnServerChange (EventArgs.Empty);
-#endif
                }
 
-
                [WebSysDescription("")]
                [WebCategory("Action")]
                public event EventHandler ServerChange {
index b75921b23b3073cb2b2535286b2c87c676d5f029..a26215484cd3c1c0a33e2a8937b5b295bf26fbb6 100644 (file)
@@ -4,7 +4,7 @@
 // Authors:
 //     Lluis Sanchez Gual (lluis@novell.com)
 //
-// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2004-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -26,8 +26,6 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_0
-
 using System.ComponentModel;
 using System.Security.Permissions;
 
@@ -43,8 +41,10 @@ namespace System.Web.UI.HtmlControls
                protected override void AddParsedSubObject(object obj)
                {
                        LiteralControl lit = obj as LiteralControl;
-                       if (lit != null) text = lit.Text;
-                       else base.AddParsedSubObject (obj);
+                       if (lit != null)
+                               text = lit.Text;
+                       else
+                               base.AddParsedSubObject (obj);
                }
 
                protected override ControlCollection CreateControlCollection ()
@@ -73,4 +73,3 @@ namespace System.Web.UI.HtmlControls
        }
 }
 
-#endif
index 3721ff584b8418135aad2922f9aebf252098502c..a7814351913e8d7d34e63160000f5c4ca466e305 100644 (file)
@@ -1,3 +1,32 @@
+2010-04-13  Marek Habersack  <mhabersack@novell.com>
+
+       * GridView.cs: make sure Header and Footer visibility are set when
+       binding the data. Fixes bug #595567
+
+       * ImageField.cs, CheckBoxField.cs: OnDataBindField must expect
+       sender to be something else than DataControlFieldCell. Fixes bug
+       #595568
+
+2010-04-07  Marek Habersack  <mhabersack@novell.com>
+
+       * FormParameter.cs, CookieParameter.cs, ProfileParameter.cs,
+       QueryStringParameter.cs, SessionParameter.cs: implemented
+       constructor overloads which take DbType as one of the arguments.
+
+2010-04-01  Marek Habersack  <mhabersack@novell.com>
+
+       * FormView.cs: do not show the pager if PagerSettings.Visible is
+       false. Fixes bug #578863
+
+2010-03-29  Marek Habersack  <mhabersack@novell.com>
+
+       * GridView.cs: main table must be created and added to the
+       controls collection before any OnRowCreated event is fired.
+
+2010-03-19 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * TreeView.cs: use enums instead of strings for attributes.
+
 2010-03-06  Marek Habersack  <mhabersack@novell.com>
 
        * XmlDataSource.cs: reload document when one of Data, DataFile,
index 696728bd174dd0824e0b643bfcb65335f2df400c..b7faf08a560480d0a56e047d319396e8265120d1 100644 (file)
@@ -121,9 +121,24 @@ namespace System.Web.UI.WebControls {
                protected override void OnDataBindField (object sender, EventArgs e)
                {
                        try {
-                               DataControlFieldCell cell = (DataControlFieldCell) sender;
-                               CheckBox box = (CheckBox) cell.Controls [0];
-                               object val = GetValue (cell.BindingContainer);
+                               Control container = (Control) sender;
+                               object val = GetValue (container.NamingContainer);
+                               CheckBox box = sender as CheckBox;
+                               if (box == null) {
+                                       DataControlFieldCell cell = sender as DataControlFieldCell;
+                                       if (cell != null) {
+                                               ControlCollection controls = cell.Controls;
+                                               int ccount = controls != null ? controls.Count : 0;
+                                               if (ccount == 1)
+                                                       box = controls [0] as CheckBox;
+                                               if (box == null)
+                                                       return;
+                                       }
+                               }
+                               
+                               if (box == null)
+                                       throw new HttpException ("CheckBox field '" + DataField + "' contains a control that isn't a CheckBox.  Override OnDataBindField to inherit from CheckBoxField and add different controls.");
+                               
                                if (val != null && val != DBNull.Value)
                                        box.Checked = (bool) val;
                                else
@@ -134,11 +149,9 @@ namespace System.Web.UI.WebControls {
 
                                if (!box.Visible)
                                        box.Visible = true;
-                       }
-                       catch (HttpException) {
+                       } catch (HttpException) {
                                throw;
-                       }
-                       catch (Exception ex) {
+                       } catch (Exception ex) {
                                throw new HttpException (ex.Message, ex);
                        }
                }
index 0d3c459a57e601e7c0cb6a8993453112ea2f9c25..257ddc4b3a946eeab8763ec5f786af50448b2da4 100644 (file)
@@ -31,6 +31,7 @@
 #if NET_2_0
 using System.Collections;
 using System.Collections.Specialized;
+using System.Data;
 using System.Text;
 using System.ComponentModel;
 
@@ -57,6 +58,11 @@ namespace System.Web.UI.WebControls {
                {
                        CookieName = cookieName;
                }
+
+               public CookieParameter (string name, DbType dbType, string cookieName) : base (name, dbType)
+               {
+                       CookieName = cookieName;
+               }
                
                protected override Parameter Clone()
                {
index 5602e002080237a179367d482cfcaaf4768abd51..cb9b9c4a35c3666244d508b88dca6307763362a7 100644 (file)
@@ -31,6 +31,7 @@
 #if NET_2_0
 using System.Collections;
 using System.Collections.Specialized;
+using System.Data;
 using System.Text;
 using System.ComponentModel;
 
@@ -57,6 +58,11 @@ namespace System.Web.UI.WebControls {
                {
                        FormField = formField;
                }
+
+               public FormParameter (string name, DbType dbType, string formField) : base (name, dbType)
+               {
+                       FormField = formField;
+               }
                
                protected override Parameter Clone ()
                {
index 7fdb4b9d2617ac9be9e26a6f6016aeffb90f53be..099ceb54126870937b3078e7a62e0b4d90078923 100644 (file)
@@ -898,7 +898,8 @@ namespace System.Web.UI.WebControls
                                }
                        }
 
-                       bool showPager = AllowPaging && (dataSource.PageCount > 1);
+                       PagerSettings pagerSettings = PagerSettings;
+                       bool showPager = AllowPaging && pagerSettings.Visible && (dataSource.PageCount > 1);
                        
                        Controls.Clear ();
                        table = CreateTable ();
@@ -947,8 +948,8 @@ namespace System.Web.UI.WebControls
                                InitializeRow (headerRow);
                                table.Rows.Add (headerRow);
                        }
-                       
-                       if (showPager && PagerSettings.Position == PagerPosition.Top || PagerSettings.Position == PagerPosition.TopAndBottom) {
+
+                       if (showPager && pagerSettings.Position == PagerPosition.Top || pagerSettings.Position == PagerPosition.TopAndBottom) {
                                topPagerRow = CreateRow (-1, DataControlRowType.Pager, DataControlRowState.Normal);
                                InitializePager (topPagerRow, dataSource);
                                table.Rows.Add (topPagerRow);
@@ -981,7 +982,7 @@ namespace System.Web.UI.WebControls
                                table.Rows.Add (footerRow);
                        }
                        
-                       if (showPager && PagerSettings.Position == PagerPosition.Bottom || PagerSettings.Position == PagerPosition.TopAndBottom) {
+                       if (showPager && pagerSettings.Position == PagerPosition.Bottom || pagerSettings.Position == PagerPosition.TopAndBottom) {
                                bottomPagerRow = CreateRow (0, DataControlRowType.Pager, DataControlRowState.Normal);
                                InitializePager (bottomPagerRow, dataSource);
                                table.Rows.Add (bottomPagerRow);
index eac5c285e924b1e251f59b73edba373e8fd1e40e..26ace72c5ce04e6ab91bba0de75cd5e2295ab890 100644 (file)
@@ -1321,6 +1321,7 @@ namespace System.Web.UI.WebControls
                        }
 
                        // Main table creation
+                       Table mainTable = ContainedTable;
                        while (skip_first || enumerator.MoveNext ()) {
                                skip_first = false;
                                object obj = enumerator.Current;
@@ -1329,7 +1330,7 @@ namespace System.Web.UI.WebControls
                                        if (createPager && (PagerSettings.Position == PagerPosition.Top || PagerSettings.Position == PagerPosition.TopAndBottom)) {
                                                topPagerRow = CreatePagerRow (fieldCount, dataSource);
                                                OnRowCreated (new GridViewRowEventArgs (topPagerRow));
-                                               ContainedTable.Rows.Add (topPagerRow);
+                                               mainTable.Rows.Add (topPagerRow);
                                                if (dataBinding) {
                                                        topPagerRow.DataBind ();
                                                        OnRowDataBound (new GridViewRowEventArgs (topPagerRow));
@@ -1341,7 +1342,7 @@ namespace System.Web.UI.WebControls
                                        GridViewRow headerRow = CreateRow (-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
                                        InitializeRow (headerRow, fields);
                                        OnRowCreated (new GridViewRowEventArgs (headerRow));
-                                       ContainedTable.Rows.Add (headerRow);
+                                       mainTable.Rows.Add (headerRow);
                                        if (dataBinding) {
                                                headerRow.DataBind ();
                                                OnRowDataBound (new GridViewRowEventArgs (headerRow));
@@ -1354,7 +1355,7 @@ namespace System.Web.UI.WebControls
                                list.Add (row);
                                InitializeRow (row, fields);
                                OnRowCreated (new GridViewRowEventArgs (row));
-                               ContainedTable.Rows.Add (row);
+                               mainTable.Rows.Add (row);
                                if (dataBinding) {
                                        row.DataBind ();                                        
                                        if (EditIndex == row.RowIndex)
@@ -1368,7 +1369,7 @@ namespace System.Web.UI.WebControls
                                GridViewRow emptyRow = CreateEmptyrRow (fieldCount);
                                if (emptyRow != null) {
                                        OnRowCreated (new GridViewRowEventArgs (emptyRow));
-                                       ContainedTable.Rows.Add (emptyRow);
+                                       mainTable.Rows.Add (emptyRow);
                                        if (dataBinding) {
                                                emptyRow.DataBind ();
                                                OnRowDataBound (new GridViewRowEventArgs (emptyRow));
@@ -1380,7 +1381,7 @@ namespace System.Web.UI.WebControls
                                GridViewRow footerRow = CreateRow (-1, -1, DataControlRowType.Footer, DataControlRowState.Normal);
                                InitializeRow (footerRow, fields);
                                OnRowCreated (new GridViewRowEventArgs (footerRow));
-                               ContainedTable.Rows.Add (footerRow);
+                               mainTable.Rows.Add (footerRow);
                                if (dataBinding) {
                                        footerRow.DataBind ();
                                        OnRowDataBound (new GridViewRowEventArgs (footerRow));
@@ -1389,7 +1390,7 @@ namespace System.Web.UI.WebControls
                                if (createPager && (PagerSettings.Position == PagerPosition.Bottom || PagerSettings.Position == PagerPosition.TopAndBottom)) {
                                        bottomPagerRow = CreatePagerRow (fieldCount, dataSource);
                                        OnRowCreated (new GridViewRowEventArgs (bottomPagerRow));
-                                       ContainedTable.Rows.Add (bottomPagerRow);
+                                       mainTable.Rows.Add (bottomPagerRow);
                                        if (dataBinding) {
                                                bottomPagerRow.DataBind ();
                                                OnRowDataBound (new GridViewRowEventArgs (bottomPagerRow));
@@ -1567,6 +1568,14 @@ namespace System.Web.UI.WebControls
                        base.DataBind ();
 
                        keys = new DataKeyArray (DataKeyArrayList);
+                       
+                       GridViewRow row = HeaderRow;
+                       if (row != null)
+                               row.Visible = ShowHeader;
+
+                       row = FooterRow;
+                       if (row != null)
+                               row.Visible = ShowFooter;
                }
                
                protected internal override void PerformDataBinding (IEnumerable data)
@@ -1578,7 +1587,7 @@ namespace System.Web.UI.WebControls
                {
                        if (table == null)
                                return;
-                       
+
                        table.Caption = Caption;
                        table.CaptionAlign = CaptionAlign;
                        table.CopyBaseAttributes (this);
@@ -2200,7 +2209,6 @@ namespace System.Web.UI.WebControls
                protected internal override void Render (HtmlTextWriter writer)
                {
                        PrepareControlHierarchy ();
-
                        if (EnableSortingAndPagingCallbacks)
                                writer.AddAttribute (HtmlTextWriterAttribute.Id, ClientID + "_div");
                        writer.RenderBeginTag (HtmlTextWriterTag.Div);
index 1a53061ca94f526bd2f14df3ef814bb3d1fc1690..7513feafd010053c2f3561b6c8a27b672765ecab 100644 (file)
@@ -285,10 +285,15 @@ namespace System.Web.UI.WebControls {
                
                PropertyDescriptor GetProperty (Control controlContainer, string fieldName)
                {
+                       if (fieldName == ThisExpression)
+                               return null;
+                       
                        IDataItemContainer dic = (IDataItemContainer) controlContainer;
-                       PropertyDescriptor prop = TypeDescriptor.GetProperties (dic.DataItem) [fieldName];
+                       PropertyDescriptorCollection properties = TypeDescriptor.GetProperties (dic.DataItem);
+                       PropertyDescriptor prop = properties != null ? properties [fieldName] : null;
                        if (prop == null)
                                throw new InvalidOperationException ("Property '" + fieldName + "' not found in object of type " + dic.DataItem.GetType());
+                       
                        return prop;
                }
                
@@ -299,34 +304,41 @@ namespace System.Web.UI.WebControls {
                
                protected virtual void OnDataBindField (object sender, EventArgs e)
                {
-                       DataControlFieldCell cell = (DataControlFieldCell) sender;
-
-                       if (cell.Controls.Count == 0)
+                       Control control = (Control) sender;
+                       ControlCollection controls = control != null ? control.Controls : null;
+                       Control namingContainer = control.NamingContainer;
+                       Control c;
+                       if (sender is DataControlFieldCell) {
+                               if (controls.Count == 0)
+                                       return;
+                               c = controls [0];
+                       } else if (sender is Image || sender is TextBox)
+                               c = control;
+                       else
                                return;
-                       
+
                        if (imageProperty == null)
-                               imageProperty = GetProperty (cell.BindingContainer, DataImageUrlField);
+                               imageProperty = GetProperty (namingContainer, DataImageUrlField);
                        
-                       Control c = cell.Controls [0];
                        if (c is TextBox) {
-                               object val = GetValue (cell.BindingContainer, DataImageUrlField, ref imageProperty);
-                               ((TextBox)c).Text = val != null ? val.ToString() : "";
+                               object val = GetValue (namingContainer, DataImageUrlField, ref imageProperty);
+                               ((TextBox)c).Text = val != null ? val.ToString() : String.Empty;
                        }
                        else if (c is Image) {
                                Image img = (Image)c;
-                               string value =  FormatImageUrlValue (GetValue (cell.BindingContainer, DataImageUrlField, ref imageProperty));
+                               string value =  FormatImageUrlValue (GetValue (namingContainer, DataImageUrlField, ref imageProperty));
                                if (value == null || (ConvertEmptyStringToNull && value.Length == 0)) {
                                        if (NullImageUrl == null || NullImageUrl.Length == 0) {
                                                c.Visible = false;
                                                Label label = new Label ();
                                                label.Text = NullDisplayText;
-                                               cell.Controls.Add (label);
+                                               controls.Add (label);
                                        }
                                        else
                                                value = NullImageUrl;
                                }
                                img.ImageUrl = value;
-                               img.AlternateText = GetFormattedAlternateText (cell.BindingContainer);
+                               img.AlternateText = GetFormattedAlternateText (namingContainer);
                        }
                }
                
index 1f2997b154af760ed4622b8504bf88e70fc54d42..fcaa635ce78a4a396915cf85bef7db915b412fa3 100644 (file)
@@ -28,6 +28,7 @@
 
 using System;
 using System.Collections.Generic;
+using System.Data;
 using System.Text;
 
 namespace System.Web.UI.WebControls
@@ -57,6 +58,12 @@ namespace System.Web.UI.WebControls
                        this.PropertyName = propertyName;
                }
 
+               public ProfileParameter (string name, DbType dbType, string propertyName)
+                       : base (name, dbType)
+               {
+                       this.PropertyName = propertyName;
+               }
+               
                protected override Parameter Clone ()
                {
                        return new ProfileParameter (this);
index d37ccfd82489cf369eac5315d9d06ca7f2b19ade..bc51e81f7ee3856d1ea24865cfd0374671c8e3cc 100644 (file)
@@ -31,6 +31,7 @@
 #if NET_2_0
 using System.Collections;
 using System.Collections.Specialized;
+using System.Data;
 using System.Text;
 using System.ComponentModel;
 
@@ -58,6 +59,11 @@ namespace System.Web.UI.WebControls {
                {
                        QueryStringField = queryStringField;
                }
+
+               public QueryStringParameter (string name, DbType dbType, string queryStringField) : base (name, dbType)
+               {
+                       QueryStringField = queryStringField;
+               }
                
                protected override Parameter Clone ()
                {
index ca35b71ed4d3df3c906f31818301eb89e865fcd5..c4ea93feddd6a76f1ef4c0a8fbdf52b2e95cd58e 100644 (file)
@@ -31,6 +31,7 @@
 #if NET_2_0
 using System.Collections;
 using System.Collections.Specialized;
+using System.Data;
 using System.Text;
 using System.ComponentModel;
 
@@ -57,6 +58,11 @@ namespace System.Web.UI.WebControls {
                {
                        SessionField = sessionField;
                }
+
+               public SessionParameter (string name, DbType dbType, string sessionField) : base (name, dbType)
+               {
+                       SessionField = sessionField;
+               }
                
                protected override Parameter Clone ()
                {
index b3c005d0c8f4782cc64eb4d29e87fc8b69d2de1b..1716ee8709def23989c4045eda8fd6bcb8e18599 100644 (file)
@@ -1375,9 +1375,9 @@ namespace System.Web.UI.WebControls
                        else
                                hasChildNodes = (node.PopulateOnDemand && !node.Populated) || node.ChildNodes.Count > 0;
                                
-                       writer.AddAttribute ("cellpadding", "0", false);
-                       writer.AddAttribute ("cellspacing", "0", false);
-                       writer.AddStyleAttribute ("border-width", "0");
+                       writer.AddAttribute (HtmlTextWriterAttribute.Cellpadding, "0", false);
+                       writer.AddAttribute (HtmlTextWriterAttribute.Cellspacing, "0", false);
+                       writer.AddStyleAttribute (HtmlTextWriterStyle.BorderWidth, "0");
                        writer.RenderBeginTag (HtmlTextWriterTag.Table);
 
                        Unit nodeSpacing = GetNodeSpacing (node);
@@ -1392,11 +1392,11 @@ namespace System.Web.UI.WebControls
                        nodeImage = GetNodeImageUrl ("i", imageStyle);
                        for (int n=0; n<level; n++) {
                                writer.RenderBeginTag (HtmlTextWriterTag.Td);
-                               writer.AddStyleAttribute ("width", NodeIndent + "px");
-                               writer.AddStyleAttribute ("height", "1px");
+                               writer.AddStyleAttribute (HtmlTextWriterStyle.Width, NodeIndent + "px");
+                               writer.AddStyleAttribute (HtmlTextWriterStyle.Height, "1px");
                                writer.RenderBeginTag (HtmlTextWriterTag.Div);
                                if (ShowLines && levelLines [n] != null) {
-                                       writer.AddAttribute ("src", nodeImage);
+                                       writer.AddAttribute (HtmlTextWriterAttribute.Src, nodeImage);
                                        writer.AddAttribute (HtmlTextWriterAttribute.Alt, String.Empty, false);
                                        writer.RenderBeginTag (HtmlTextWriterTag.Img);
                                        writer.RenderEndTag ();
@@ -1442,18 +1442,18 @@ namespace System.Web.UI.WebControls
                                        
                                        if (buttonImage) {
                                                if (!clientExpand || (!PopulateNodesFromClient && node.PopulateOnDemand && !node.Populated))
-                                                       writer.AddAttribute ("href", GetClientEvent (node, "ec"));
+                                                       writer.AddAttribute (HtmlTextWriterAttribute.Href, GetClientEvent (node, "ec"));
                                                else
-                                                       writer.AddAttribute ("href", GetClientExpandEvent(node));
+                                                       writer.AddAttribute (HtmlTextWriterAttribute.Href, GetClientExpandEvent(node));
                                                writer.RenderBeginTag (HtmlTextWriterTag.A);    // Anchor
                                        }
 
                                        // tooltip is 'HtmlAttributeEncoded'
-                                       writer.AddAttribute ("alt", tooltip);
+                                       writer.AddAttribute (HtmlTextWriterAttribute.Alt, tooltip);
 
                                        if (buttonImage && clientExpand)
-                                               writer.AddAttribute ("id", GetNodeClientId (node, "img"));
-                                       writer.AddAttribute ("src", nodeImage);
+                                               writer.AddAttribute (HtmlTextWriterAttribute.Id, GetNodeClientId (node, "img"));
+                                       writer.AddAttribute (HtmlTextWriterAttribute.Src, nodeImage);
                                        if (buttonImage)
                                                writer.AddStyleAttribute (HtmlTextWriterStyle.BorderWidth, "0");
                                        writer.RenderBeginTag (HtmlTextWriterTag.Img);
@@ -1484,9 +1484,9 @@ namespace System.Web.UI.WebControls
                        if (!String.IsNullOrEmpty (imageUrl)) {
                                writer.RenderBeginTag (HtmlTextWriterTag.Td);   // TD
                                BeginNodeTag (writer, node, clientExpand);
-                               writer.AddAttribute ("src", imageUrl);
+                               writer.AddAttribute (HtmlTextWriterAttribute.Src, imageUrl);
                                writer.AddStyleAttribute (HtmlTextWriterStyle.BorderWidth, "0");
-                               writer.AddAttribute ("alt", node.ImageToolTip);
+                               writer.AddAttribute (HtmlTextWriterAttribute.Alt, node.ImageToolTip);
                                writer.RenderBeginTag (HtmlTextWriterTag.Img);
                                writer.RenderEndTag (); // IMG
                                writer.RenderEndTag (); // style tag
@@ -1494,7 +1494,7 @@ namespace System.Web.UI.WebControls
                        }
 
                        if (!NodeWrap)
-                               writer.AddStyleAttribute ("white-space", "nowrap");
+                               writer.AddStyleAttribute (HtmlTextWriterStyle.WhiteSpace, "nowrap");
 
                        bool nodeIsSelected = node == SelectedNode && selectedNodeStyle != null;
                        if (!nodeIsSelected && selectedNodeStyle != null) {
@@ -1512,10 +1512,10 @@ namespace System.Web.UI.WebControls
                        // Checkbox
                        
                        if (node.ShowCheckBoxInternal) {
-                               writer.AddAttribute ("name", ClientID + "_cs_" + node.Path);
-                               writer.AddAttribute ("type", "checkbox", false);
-                               writer.AddAttribute ("title", node.Text);
-                               if (node.Checked) writer.AddAttribute ("checked", "checked", false);
+                               writer.AddAttribute (HtmlTextWriterAttribute.Name, ClientID + "_cs_" + node.Path);
+                               writer.AddAttribute (HtmlTextWriterAttribute.Type, "checkbox", false);
+                               writer.AddAttribute (HtmlTextWriterAttribute.Title, node.Text);
+                               if (node.Checked) writer.AddAttribute (HtmlTextWriterAttribute.Checked, "checked", false);
                                writer.RenderBeginTag (HtmlTextWriterTag.Input);        // INPUT
                                writer.RenderEndTag (); // INPUT
                        }
@@ -1525,7 +1525,7 @@ namespace System.Web.UI.WebControls
                        node.BeginRenderText (writer);
                        
                        if (clientExpand)
-                               writer.AddAttribute ("id", GetNodeClientId (node, "txt"));
+                               writer.AddAttribute (HtmlTextWriterAttribute.Id, GetNodeClientId (node, "txt"));
                        AddNodeLinkStyle (writer, node, level, nodeIsSelected);
                        BeginNodeTag (writer, node, clientExpand);
                        writer.Write (node.Text);
@@ -1559,10 +1559,10 @@ namespace System.Web.UI.WebControls
                                
                                if (clientExpand) {
                                        if (!(node.Expanded.HasValue && node.Expanded.Value))
-                                               writer.AddStyleAttribute ("display", "none");
+                                               writer.AddStyleAttribute (HtmlTextWriterStyle.Display, "none");
                                        else
-                                               writer.AddStyleAttribute ("display", "block");
-                                       writer.AddAttribute ("id", GetNodeClientId (node, null));
+                                               writer.AddStyleAttribute (HtmlTextWriterStyle.Display, "block");
+                                       writer.AddAttribute (HtmlTextWriterAttribute.Id, GetNodeClientId (node, null));
                                        writer.RenderBeginTag (HtmlTextWriterTag.Span);
                                        
                                        if (renderChildNodes) {
@@ -1600,7 +1600,7 @@ namespace System.Web.UI.WebControls
                                return;
 
                        writer.RenderBeginTag (HtmlTextWriterTag.Table);
-                       writer.AddAttribute ("height", ((int) value).ToString (), false);
+                       writer.AddAttribute (HtmlTextWriterAttribute.Height, ((int) value).ToString (), false);
                        writer.RenderBeginTag (HtmlTextWriterTag.Tr);
                        writer.RenderBeginTag (HtmlTextWriterTag.Td);
                        writer.RenderEndTag (); // td
@@ -1610,7 +1610,7 @@ namespace System.Web.UI.WebControls
                
                void RenderMenuItemSpacing (HtmlTextWriter writer, Unit itemSpacing)
                {
-                       writer.AddStyleAttribute ("height", itemSpacing.ToString ());
+                       writer.AddStyleAttribute (HtmlTextWriterStyle.Height, itemSpacing.ToString ());
                        writer.RenderBeginTag (HtmlTextWriterTag.Tr);
                        writer.RenderBeginTag (HtmlTextWriterTag.Td);
                        writer.RenderEndTag ();
@@ -1774,7 +1774,7 @@ namespace System.Web.UI.WebControls
                void BeginNodeTag (HtmlTextWriter writer, TreeNode node, bool clientExpand)
                {
                        if(node.ToolTip.Length>0)
-                               writer.AddAttribute ("title", node.ToolTip);
+                               writer.AddAttribute (HtmlTextWriterAttribute.Title, node.ToolTip);
 
                        string navigateUrl = node.NavigateUrl;
                        if (!String.IsNullOrEmpty (navigateUrl)) {
@@ -1784,15 +1784,15 @@ namespace System.Web.UI.WebControls
 #else
                                string navUrl = ResolveClientUrl (navigateUrl);
 #endif
-                               writer.AddAttribute ("href", navUrl);
+                               writer.AddAttribute (HtmlTextWriterAttribute.Href, navUrl);
                                if (target.Length > 0)
-                                       writer.AddAttribute ("target", target);
+                                       writer.AddAttribute (HtmlTextWriterAttribute.Target, target);
                                writer.RenderBeginTag (HtmlTextWriterTag.A);
                        } else if (node.SelectAction != TreeNodeSelectAction.None) {
                                if (node.SelectAction == TreeNodeSelectAction.Expand && clientExpand)
-                                       writer.AddAttribute ("href", GetClientExpandEvent (node));
+                                       writer.AddAttribute (HtmlTextWriterAttribute.Href, GetClientExpandEvent (node));
                                else
-                                       writer.AddAttribute ("href", GetClientEvent (node, "sel"));
+                                       writer.AddAttribute (HtmlTextWriterAttribute.Href, GetClientEvent (node, "sel"));
                                writer.RenderBeginTag (HtmlTextWriterTag.A);
                        } else
                                writer.RenderBeginTag (HtmlTextWriterTag.Span);
index cb8821b2d9baff0356cc641a7a409b068eb9ad3a..e7a2942c9ce91b39d9c94da2695f292936d9f11b 100644 (file)
@@ -1,3 +1,22 @@
+2010-04-12  Marek Habersack  <mhabersack@novell.com>
+
+       * PageParser.cs: if EnableViewStateMac option is present in the
+       directive, remember it for later use by the compiler.
+
+       * Page.cs: initialize EnableViewStateMac with the default read
+       from the config.
+
+2010-04-07  Marek Habersack  <mhabersack@novell.com>
+
+       * Control.cs: control cache must be filled using the local
+       _controls collection instead of the virtual Controls
+       property. Fixes bug #594238
+       Check if _controls isn't null before using it.
+
+2010-04-06  Marek Safar  <marek.safar@gmail.com>
+
+       * FileLevelControlBuilderAttribute.cs: Use reference comparison.
+
 2010-01-20  Marek Habersack  <mhabersack@novell.com>
 
        * ObjectStateFormatter.cs: implemented support for IndexedString
index 5997bc55a144d7d927579b6090d0239d732a9db1..c3b23b4a6bd0f8a7ef82558c43bb747d0661c40d 100644 (file)
@@ -34,6 +34,18 @@ namespace System.Web.UI
 {
        sealed class CodeRenderBuilder : CodeBuilder
        {
+#if NET_4_0
+               public bool HtmlEncode {
+                       get; private set;
+               }
+
+               public CodeRenderBuilder (string code, bool isAssign, ILocation location, bool doHtmlEncode)
+                       : base (code, isAssign, location)
+               {
+                       this.HtmlEncode = doHtmlEncode;
+               }
+#endif
+               
                public CodeRenderBuilder (string code, bool isAssign, ILocation location)
                        : base (code, isAssign, location)
                {
index ff8e9075332e14b642d9e8f754e4ff69541c7278..59c13c3127e485822c8d608abe8f761ab9a21383 100644 (file)
@@ -452,8 +452,9 @@ namespace System.Web.UI
                        get { return ((stateMask & CHILD_CONTROLS_CREATED) != 0); }
                        set {
                                if (value == false && (stateMask & CHILD_CONTROLS_CREATED) != 0) {
-                                       if (_controls != null)
-                                               _controls.Clear ();
+                                       ControlCollection cc = Controls;
+                                       if (cc != null)
+                                               cc.Clear ();
                                }
 
                                SetMask (CHILD_CONTROLS_CREATED, value);
@@ -765,12 +766,15 @@ namespace System.Web.UI
                                return;
 
                        InitControlsCache ();
-                       FillControlCache (Controls);
 
+                       FillControlCache (_controls);
                }
 
                void FillControlCache (ControlCollection controls)
                {
+                       if (controls == null || controls.Count == 0)
+                               return;
+                       
                        foreach (Control c in controls) {
                                try {
                                        if (c._userId != null)
@@ -789,7 +793,7 @@ namespace System.Web.UI
 
                protected bool IsLiteralContent ()
                {
-                       if (HasControls () && _controls.Count == 1 && (_controls [0] is LiteralControl))
+                       if (_controls != null && _controls.Count == 1 && _controls [0] is LiteralControl)
                                return true;
 
                        return false;
@@ -1044,19 +1048,23 @@ namespace System.Web.UI
                {
                        if (_renderMethodDelegate != null) {
                                _renderMethodDelegate (writer, this);
-                       } else if (_controls != null) {
-                               int len = _controls.Count;
-                               Control c;
-                               for (int i = 0; i < len; i++) {
-                                       c = _controls [i];
-                                       if (c == null)
-                                               continue;
-                                       ControlAdapter tmp = c.Adapter;
-                                       if (tmp != null)
-                                               c.RenderControl (writer, tmp);
-                                       else
-                                               c.RenderControl (writer);
-                               }
+                               return;
+                       }
+
+                       if (_controls == null)
+                               return;
+
+                       int len = _controls.Count;
+                       Control c;
+                       for (int i = 0; i < len; i++) {
+                               c = _controls [i];
+                               if (c == null)
+                                       continue;
+                               ControlAdapter tmp = c.Adapter;
+                               if (tmp != null)
+                                       c.RenderControl (writer, tmp);
+                               else
+                                       c.RenderControl (writer);
                        }
                }
 
@@ -1178,7 +1186,7 @@ namespace System.Web.UI
                        if (!HasControls ())
                                return;
 
-                       int len = _controls.Count;
+                       int len = _controls != null ? _controls.Count : 0;
                        for (int i = 0; i < len; i++) {
                                Control c = _controls [i];
                                c.DataBind ();
@@ -1189,7 +1197,7 @@ namespace System.Web.UI
                {
                        return (_controls != null && _controls.Count > 0);
                }
-
+               
                public virtual void RenderControl (HtmlTextWriter writer)
                {
                        if (this.adapter != null) {
@@ -1341,12 +1349,10 @@ namespace System.Web.UI
                                Adapter.OnLoad (EventArgs.Empty);
                        else
                                OnLoad (EventArgs.Empty);
-                       if (HasControls ()) {
-                               int len = _controls.Count;
-                               for (int i = 0; i < len; i++) {
-                                       Control c = _controls [i];
-                                       c.LoadRecursive ();
-                               }
+                       int ccount = _controls != null ? _controls.Count : 0;
+                       for (int i = 0; i < ccount; i++) {
+                               Control c = _controls [i];
+                               c.LoadRecursive ();
                        }
 
 #if MONO_TRACE
@@ -1366,12 +1372,10 @@ namespace System.Web.UI
                                trace.Write ("control", String.Concat ("UnloadRecursive ", _userId, " ", type_name));
                        }
 #endif
-                       if (HasControls ()) {
-                               int len = _controls.Count;
-                               for (int i = 0; i < len; i++) {
-                                       Control c = _controls [i];
-                                       c.UnloadRecursive (dispose);
-                               }
+                       int ccount = _controls != null ? _controls.Count : 0;
+                       for (int i = 0; i < ccount; i++) {
+                               Control c = _controls [i];
+                               c.UnloadRecursive (dispose);
                        }
 
 #if MONO_TRACE
@@ -1410,7 +1414,7 @@ namespace System.Web.UI
                                if (!HasControls ())
                                        return;
 
-                               int len = _controls.Count;
+                               int len = _controls != null ? _controls.Count : 0;
                                for (int i = 0; i < len; i++) {
                                        Control c = _controls [i];
                                        c.PreRenderRecursiveInternal ();
@@ -1441,7 +1445,7 @@ namespace System.Web.UI
                                if ((stateMask & IS_NAMING_CONTAINER) != 0)
                                        namingContainer = this;
 
-                               int len = _controls.Count;
+                               int len = _controls != null ? _controls.Count : 0;
                                for (int i = 0; i < len; i++) {
                                        Control c = _controls [i];
                                        c.InitRecursive (namingContainer);
@@ -1481,7 +1485,7 @@ namespace System.Web.UI
                        ArrayList controlStates = null;
                        bool byId = LoadViewStateByID;
                        if (HasControls ()) {
-                               int len = _controls.Count;
+                               int len = _controls != null ? _controls.Count : 0;
                                for (int i = 0; i < len; i++) {
                                        Control ctrl = _controls [i];
                                        object ctrlState = ctrl.SaveViewStateRecursive ();
index 20857aa89169627e07aa91e8a1cf532b8d033917..16f6fba8533490a8b0bfa97948a0f2a16314a3a1 100644 (file)
@@ -77,7 +77,7 @@ namespace System.Web.UI
                
                public override bool IsDefaultAttribute ()
                {
-                       return Equals (Default);
+                       return this == Default;
                }
        }
 }
index c3f86937072259630c275fe395a03f8cb376dbad..49ebf1a8256b6b407f44c6f6270f9b7b98ecf47e 100644 (file)
@@ -167,6 +167,7 @@ public partial class Page : TemplateControl, IHttpHandler
                        asyncTimeout = ps.AsyncTimeout;
                        viewStateEncryptionMode = ps.ViewStateEncryptionMode;
                        _viewState = ps.EnableViewState;
+                       _viewStateMac = ps.EnableViewStateMac;
                } else {
                        asyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
                        viewStateEncryptionMode = ViewStateEncryptionMode.Auto;
index bcbab1d6a8ecd194a3a949498701bfb79fe39c18..54eeae730d32df224021f5f9a5adc7e22a3a2521 100644 (file)
@@ -45,7 +45,8 @@ namespace System.Web.UI
        public sealed class PageParser : TemplateControlParser
        {
                PagesEnableSessionState enableSessionState = PagesEnableSessionState.True;
-               bool enableViewStateMac = true;
+               bool enableViewStateMac;
+               bool enableViewStateMacSet;
                bool smartNavigation;
                bool haveTrace;
                bool trace;
@@ -335,8 +336,12 @@ namespace System.Web.UI
                        enable_event_validation = GetBool (atts, "EnableEventValidation", enable_event_validation);
                        maintainScrollPositionOnPostBack = GetBool (atts, "MaintainScrollPositionOnPostBack", maintainScrollPositionOnPostBack);
 
+                       if (atts.ContainsKey ("EnableViewState")) {
+                               enableViewStateMac = GetBool (atts, "EnableViewStateMac", enableViewStateMac);
+                               enableViewStateMacSet = true;
+                       }
+                       
                        // Ignored by now
-                       GetString (atts, "EnableViewStateMac", null);
                        GetString (atts, "SmartNavigation", null);
 
                        base.ProcessMainAttributes (atts);
@@ -420,6 +425,10 @@ namespace System.Web.UI
                internal bool EnableViewStateMac {
                        get { return enableViewStateMac; }
                }
+
+               internal bool EnableViewStateMacSet {
+                       get { return enableViewStateMacSet; }
+               }
                
                internal bool SmartNavigation {
                        get { return smartNavigation; }
index d7f305d0cc460ae33fa3b1fc4950675edb862d04..8cc7339ca81a81f79a71aaf191524080568b7fd0 100644 (file)
@@ -1,3 +1,38 @@
+2010-04-27  Marek Habersack  <mhabersack@novell.com>
+
+       * HttpException.cs: implemented 4.0 property WebEventCode, also
+       made it available in the 2.0 profile as internal.
+       Added a method with several overloads, NewWithCode, which creates
+       an instance of HttpException and sets the web error code.
+
+       * HttpApplication.cs, HttpRequest.cs, HttpRuntime.cs: use HttpException.NewWithCode for some
+       exceptions.
+
+2010-04-21  Marek Habersack  <mhabersack@novell.com>
+
+       * HttpApplication.cs: update to fix for bug #572469 - ProcessError
+       clears the error after handler return only if stop_processing is
+       true. Also, stop_processing is never set before calling ProcessError
+
+2010-04-02  Marek Habersack  <mhabersack@novell.com>
+
+       * HttpException.cs: handle situations when current exception is an
+       instance of a class derived from HttpException and there's no
+       InnerException.
+
+       * HttpApplication.cs: ProcessError must call ClearError on the
+       current context after the handler returns without error. Fixes bug
+       #572469
+
+2010-03-30 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * HttpResponseStream.cs: speed up short writes.
+
+2010-03-20  Marek Habersack  <mhabersack@novell.com>
+
+       * SiteMapNode.cs: avoid calling ChildNodes twice in HasChildNodes.
+       Cache child nodes in the ChildNodes property.
+
 2010-03-06  Marek Habersack  <mhabersack@novell.com>
 
        * HttpRequest.cs: cache RawUrl value.
index 81d666683d5be366f4c492b41f10cdd723012eab..d9972ceddec874d60ed40d8dafba25186e78fad8 100644 (file)
@@ -75,6 +75,7 @@ using System.Threading;
 using System.Web.Caching;
 using System.Web.Compilation;
 using System.Web.Configuration;
+using System.Web.Management;
 using System.Web.SessionState;
 using System.Web.UI;
 using System.Web.Util;
@@ -277,10 +278,10 @@ namespace System.Web
                public HttpRequest Request {
                        get {
                                if (context == null)
-                                       throw new HttpException (Locale.GetText ("No context is available."));
+                                       throw HttpException.NewWithCode (Locale.GetText ("No context is available."), WebEventCodes.RuntimeErrorRequestAbort);
 
                                if (false == HttpApplicationFactory.ContextAvailable)
-                                       throw new HttpException (Locale.GetText ("Request is not available in this context."));
+                                       throw HttpException.NewWithCode (Locale.GetText ("Request is not available in this context."), WebEventCodes.RuntimeErrorRequestAbort);
 
                                return context.Request;
                        }
@@ -291,10 +292,10 @@ namespace System.Web
                public HttpResponse Response {
                        get {
                                if (context == null)
-                                       throw new HttpException (Locale.GetText ("No context is available."));
+                                       throw HttpException.NewWithCode (Locale.GetText ("No context is available."), WebEventCodes.RuntimeErrorRequestAbort);
 
                                if (false == HttpApplicationFactory.ContextAvailable)
-                                       throw new HttpException (Locale.GetText ("Response is not available in this context."));
+                                       throw HttpException.NewWithCode (Locale.GetText ("Response is not available in this context."), WebEventCodes.RuntimeErrorRequestAbort);
 
                                return context.Response;
                        }
@@ -324,11 +325,11 @@ namespace System.Web
                                        return session;
 
                                if (context == null)
-                                       throw new HttpException (Locale.GetText ("No context is available."));
+                                       throw HttpException.NewWithCode (Locale.GetText ("No context is available."), WebEventCodes.RuntimeErrorRequestAbort);
 
                                HttpSessionState ret = context.Session;
                                if (ret == null)
-                                       throw new HttpException (Locale.GetText ("Session state is not available in the context."));
+                                       throw HttpException.NewWithCode (Locale.GetText ("Session state is not available in the context."), WebEventCodes.RuntimeErrorRequestAbort);
                                
                                return ret;
                        }
@@ -850,6 +851,14 @@ namespace System.Web
                        return null;
                }
 
+               bool ShouldHandleException (Exception e)
+               {
+                       if (e is ParseException)
+                               return false;
+
+                       return true;
+               }
+               
                //
                // If we catch an error, queue this error
                //
@@ -857,11 +866,13 @@ namespace System.Web
                {
                        bool first = context.Error == null;
                        context.AddError (e);
-                       if (first) {
+                       if (first && ShouldHandleException (e)) {
                                EventHandler eh = nonApplicationEvents [errorEvent] as EventHandler;
                                if (eh != null){
                                        try {
                                                eh (this, EventArgs.Empty);
+                                               if (stop_processing)
+                                                       context.ClearError ();
                                        } catch (ThreadAbortException taex){
                                                context.ClearError ();
                                                if (FlagEnd.Value == taex.ExceptionState || HttpRuntime.DomainUnloading)
@@ -922,19 +933,19 @@ namespace System.Web
                        } catch (ThreadAbortException taex) {
                                object obj = taex.ExceptionState;
                                Thread.ResetAbort ();
-                               stop_processing = true;
                                if (obj is StepTimeout)
-                                       ProcessError (new HttpException ("The request timed out."));
+                                       ProcessError (HttpException.NewWithCode ("The request timed out.", WebEventCodes.RequestTransactionAbort));
                                else {
                                        context.ClearError ();
                                        if (FlagEnd.Value != obj && !HttpRuntime.DomainUnloading)
                                                context.AddError (taex);
                                }
-
+                               
+                               stop_processing = true;
                                PipelineDone ();
                        } catch (Exception e) {
-                               stop_processing = true;
                                ProcessError (e);
+                               stop_processing = true;
                                PipelineDone ();
                        }
                }
@@ -1053,7 +1064,7 @@ namespace System.Web
                                        if (error is HttpException){
                                                response.StatusCode = ((HttpException)error).GetHttpCode ();
                                        } else {
-                                               error = new HttpException ("", error);
+                                               error = HttpException.NewWithCode (String.Empty, error, WebEventCodes.WebErrorOtherError);
                                                response.StatusCode = 500;
                                        }
                                        HttpException httpEx = (HttpException) error;
@@ -1063,7 +1074,7 @@ namespace System.Web
                                                response.Flush (true);
                                } else {
                                        if (!(error is HttpException))
-                                               error = new HttpException ("", error);
+                                               error = HttpException.NewWithCode (String.Empty, error, WebEventCodes.WebErrorOtherError);
                                        FinalErrorWrite (response, ((HttpException) error).GetHtmlErrorMessage ());
                                }
                        }
@@ -1172,8 +1183,9 @@ namespace System.Web
                                        string path = req.PathNoValidation;
                                        int idx = path != null ? path.IndexOfAny (invalidChars) : -1;
                                        if (idx != -1)
-                                               throw new HttpException (
-                                                       String.Format ("A potentially dangerous Request.Path value was detected from the client ({0}).", path [idx])
+                                               throw HttpException.NewWithCode (
+                                                       String.Format ("A potentially dangerous Request.Path value was detected from the client ({0}).", path [idx]),
+                                                       WebEventCodes.RuntimeErrorValidationFailure
                                                );
                                }
                        }
@@ -1257,13 +1269,20 @@ namespace System.Web
                                Console.WriteLine (fnf.ToString ());
 #endif
                                if (context.Request.IsLocal)
-                                       ProcessError (new HttpException (404, String.Format ("File not found {0}", fnf.FileName), fnf, context.Request.FilePath));
+                                       ProcessError (HttpException.NewWithCode (404,
+                                                                                String.Format ("File not found {0}", fnf.FileName),
+                                                                                fnf,
+                                                                                context.Request.FilePath,
+                                                                                WebEventCodes.RuntimeErrorRequestAbort));
                                else
-                                       ProcessError (new HttpException (404, "File not found: " + Path.GetFileName (fnf.FileName), context.Request.FilePath));
+                                       ProcessError (HttpException.NewWithCode (404,
+                                                                                "File not found: " + Path.GetFileName (fnf.FileName),
+                                                                                context.Request.FilePath,
+                                                                                WebEventCodes.RuntimeErrorRequestAbort));
                        } catch (DirectoryNotFoundException dnf){
                                if (!context.Request.IsLocal)
                                        dnf = null; // Do not "leak" real path information
-                               ProcessError (new HttpException (404, "Directory not found", dnf));
+                               ProcessError (HttpException.NewWithCode (404, "Directory not found", dnf, WebEventCodes.RuntimeErrorRequestAbort));
                        } catch (Exception e) {
                                ProcessError (e);
                        }
@@ -1524,7 +1543,7 @@ namespace System.Web
                                InitOnce (true);
                        } catch (Exception e) {
                                initialization_exception = e;
-                               FinalErrorWrite (context.Response, new HttpException ("", e).GetHtmlErrorMessage ());
+                               FinalErrorWrite (context.Response, HttpException.NewWithCode (String.Empty, e, WebEventCodes.RuntimeErrorRequestAbort).GetHtmlErrorMessage ());
                                PipelineDone ();
                                return;
                        }
@@ -1715,7 +1734,7 @@ namespace System.Web
                        return RedirectErrorPage (redirect);
                        }
                        catch (Exception ex) {
-                               httpEx = new HttpException (500, "", ex);
+                               httpEx = HttpException.NewWithCode (500, String.Empty, ex, WebEventCodes.WebErrorOtherError);
                                return false;
                        }
                }
index 7d4c541179c466ff76125f30a871906efc22648b..006da9ed8320b33e8b84c2a83c7b9d06366bc775 100644 (file)
@@ -36,6 +36,7 @@ using System.Security.Permissions;
 using System.Text;
 using System.Web.Util;
 using System.Web.Compilation;
+using System.Web.Management;
 using System.Collections.Specialized;
 
 namespace System.Web
@@ -48,12 +49,23 @@ namespace System.Web
        {
                const string DEFAULT_DESCRIPTION_TEXT = "Error processing request.";
                const string ERROR_404_DESCRIPTION = "The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.";
-               
+
+               int webEventCode = WebEventCodes.UndefinedEventCode;
                int http_code = 500;
                string resource_name;
                string description;
                
                const string errorStyleFonts = "\"Verdana\",\"DejaVu Sans\",sans-serif";
+
+#if NET_4_0
+               public
+#else
+               internal
+#endif
+               int WebEventCode 
+               {
+                       get { return webEventCode; }
+               }
                
                public HttpException ()
                {
@@ -88,6 +100,7 @@ namespace System.Web
                        : base (info, context)
                {
                        http_code = info.GetInt32 ("_httpCode");
+                       webEventCode = info.GetInt32 ("_webEventCode");
                }
 
                [SecurityPermission (SecurityAction.Demand, SerializationFormatter = true)]
@@ -95,6 +108,7 @@ namespace System.Web
                {
                        base.GetObjectData (info, context);
                        info.AddValue ("_httpCode", http_code);
+                       info.AddValue ("_webEventCode", webEventCode);
                }
 
                public HttpException (int httpCode, string message, int hr) 
@@ -128,13 +142,18 @@ namespace System.Web
                                        if (http_code != 404 && http_code != 403)
                                                return GetCustomErrorDefaultMessage ();
                                        else
-                                               return GetDefaultErrorMessage (false);
+                                               return GetDefaultErrorMessage (false, null);
                                }
                                
-                               if (!(this.InnerException is HtmlizedException))
-                                       return GetDefaultErrorMessage (true);
+                               Exception ex = GetBaseException ();
+                               if (ex == null)
+                                       ex = this;
                                
-                               return GetHtmlizedErrorMessage ();
+                               HtmlizedException htmlException = ex  as HtmlizedException;
+                               if (htmlException == null)
+                                       return GetDefaultErrorMessage (true, ex);
+                               
+                               return GetHtmlizedErrorMessage (htmlException);
                        } catch (Exception ex) {
                                Console.WriteLine (ex);
                                
@@ -161,6 +180,59 @@ namespace System.Web
                        }
                }
 
+               internal static HttpException NewWithCode (string message, int webEventCode)
+               {
+                       var ret = new HttpException (message);
+                       ret.SetWebEventCode (webEventCode);
+
+                       return ret;
+               }
+
+               internal static HttpException NewWithCode (string message, Exception innerException, int webEventCode)
+               {
+                       var ret = new HttpException (message, innerException);
+                       ret.SetWebEventCode (webEventCode);
+
+                       return ret;
+               }
+
+               internal static HttpException NewWithCode (int httpCode, string message, int webEventCode)
+               {
+                       var ret = new HttpException (httpCode, message);
+                       ret.SetWebEventCode (webEventCode);
+
+                       return ret;
+               }
+               
+               internal static HttpException NewWithCode (int httpCode, string message, Exception innerException, string resourceName, int webEventCode)
+               {
+                       var ret = new HttpException (httpCode, message, innerException, resourceName);
+                       ret.SetWebEventCode (webEventCode);
+
+                       return ret;
+               }
+
+               internal static HttpException NewWithCode (int httpCode, string message, string resourceName, int webEventCode)
+               {
+                       var ret = new HttpException (httpCode, message, resourceName);
+                       ret.SetWebEventCode (webEventCode);
+
+                       return ret;
+               }
+
+               internal static HttpException NewWithCode (int httpCode, string message, Exception innerException, int webEventCode)
+               {
+                       var ret = new HttpException (httpCode, message, innerException);
+                       ret.SetWebEventCode (webEventCode);
+
+                       return ret;
+               }
+               
+               internal void SetWebEventCode (int webEventCode)
+               {
+                       this.webEventCode = webEventCode;
+               }
+               
                void WriteFileTop (StringBuilder builder, string title)
                {
 #if TARGET_J2EE
@@ -290,10 +362,10 @@ table.sampleCode {{width: 100%; background-color: #ffffcc; }}
                        return builder.ToString ();
                }
                
-               string GetDefaultErrorMessage (bool showTrace)
+               string GetDefaultErrorMessage (bool showTrace, Exception baseEx)
                {
-                       Exception ex, baseEx;
-                       ex = baseEx = GetBaseException ();
+                       Exception ex;
+                       ex = baseEx;
                        if (ex == null)
                                ex = this;
 
@@ -345,10 +417,9 @@ table.sampleCode {{width: 100%; background-color: #ffffcc; }}
                        return filename;
                }
                
-               string GetHtmlizedErrorMessage ()
+               string GetHtmlizedErrorMessage (HtmlizedException exc)
                {
                        StringBuilder builder = new StringBuilder ();
-                       HtmlizedException exc = (HtmlizedException) this.InnerException;
 #if TARGET_J2EE
                        bool isParseException = false;
                        bool isCompileException = false;
index 7405ae20f4b8d79a7054c6cefdab365e00780c8b..ded9e9e8e55859d08ccec241f9af83043fb435f7 100644 (file)
@@ -39,6 +39,7 @@ using System.Security;
 using System.Security.Permissions;
 using System.Security.Principal;
 using System.Web.Configuration;
+using System.Web.Management;
 using System.Web.UI;
 using System.Web.Util;
 using System.Globalization;
@@ -335,7 +336,7 @@ namespace System.Web
                        get {
                                if (encoding == null){
                                        if (worker_request == null)
-                                               throw new HttpException ("No HttpWorkerRequest");
+                                               throw HttpException.NewWithCode ("No HttpWorkerRequest", WebEventCodes.RuntimeErrorRequestAbort);
                                        
                                        string content_type = ContentType;
                                        string parameter = GetParameter (content_type, "; charset=");
@@ -786,7 +787,7 @@ namespace System.Web
                        int content_length_kb = content_length / 1024;
                        HttpRuntimeSection config = (HttpRuntimeSection) WebConfigurationManager.GetWebApplicationSection ("system.web/httpRuntime");
                        if (content_length_kb > config.MaxRequestLength)
-                               throw new HttpException (400, "Upload size exceeds httpRuntime limit.");
+                               throw HttpException.NewWithCode (400, "Upload size exceeds httpRuntime limit.", WebEventCodes.RuntimeErrorPostTooLarge);
 
                        int total = 0;
                        byte [] buffer;
@@ -833,8 +834,9 @@ namespace System.Web
                                total = Math.Min (content_length, total);
                                IntPtr content = Marshal.AllocHGlobal (content_length);
                                if (content == (IntPtr) 0)
-                                       throw new HttpException (String.Format ("Not enough memory to allocate {0} bytes.",
-                                                                       content_length));
+                                       throw HttpException.NewWithCode (
+                                               String.Format ("Not enough memory to allocate {0} bytes.", content_length),
+                                               WebEventCodes.WebErrorOtherError);
 
                                if (total > 0)
                                        Marshal.Copy (buffer, 0, content, total);
@@ -870,7 +872,7 @@ namespace System.Web
                                                break;
                                        total += n;
                                        if (total < 0 || total > maxlength)
-                                               throw new HttpException (400, "Upload size exceeds httpRuntime limit.");
+                                               throw HttpException.NewWithCode (400, "Upload size exceeds httpRuntime limit.", WebEventCodes.RuntimeErrorPostTooLarge);
 
                                        if (ms != null && total > disk_th) {
                                                // Swith to on-disk file.
@@ -892,7 +894,7 @@ namespace System.Web
                        DoFilter (buffer);
 
                        if (total < content_length)
-                               throw new HttpException (411, "The request body is incomplete.");
+                               throw HttpException.NewWithCode (411, "The request body is incomplete.", WebEventCodes.WebErrorOtherError);
                }
 #endif
 
@@ -1290,7 +1292,7 @@ namespace System.Web
                public string MapPath (string virtualPath, string baseVirtualDir, bool allowCrossAppMapping)
                {
                        if (worker_request == null)
-                               throw new HttpException ("No HttpWorkerRequest");
+                               throw HttpException.NewWithCode ("No HttpWorkerRequest", WebEventCodes.RuntimeErrorRequestAbort);
 
                        if (virtualPath == null)
                                virtualPath = "~";
@@ -1301,7 +1303,7 @@ namespace System.Web
                        }
 
                        if (!VirtualPathUtility.IsValidVirtualPath (virtualPath))
-                               throw new HttpException (String.Format ("'{0}' is not a valid virtual path.", virtualPath));
+                               throw HttpException.NewWithCode (String.Format ("'{0}' is not a valid virtual path.", virtualPath), WebEventCodes.RuntimeErrorRequestAbort);
 
                        string appVirtualPath = HttpRuntime.AppDomainAppVirtualPath;
 
@@ -1314,9 +1316,9 @@ namespace System.Web
                        
                        if (!allowCrossAppMapping){
                                if (!StrUtils.StartsWith (virtualPath, appVirtualPath, true))
-                                       throw new HttpException ("MapPath: Mapping across applications not allowed");
+                                       throw HttpException.NewWithCode ("MapPath: Mapping across applications not allowed", WebEventCodes.RuntimeErrorRequestAbort);
                                if (appVirtualPath.Length > 1 && virtualPath.Length > 1 && virtualPath [0] != '/')
-                                       throw new HttpException ("MapPath: Mapping across applications not allowed");
+                                       throw HttpException.NewWithCode ("MapPath: Mapping across applications not allowed", WebEventCodes.RuntimeErrorRequestAbort);
                        }
 #if TARGET_JVM
                        return worker_request.MapPath (virtualPath);
index c1d8d6e7fcd2b024d46547b44664ba6f7cd4afbc..a7ec533a0e7296600b879bd59cbfceb46ddca2df 100644 (file)
@@ -189,7 +189,13 @@ namespace System.Web
                                
                                EnsureCapacity (position + count);
                                byte *src = (byte *) ptr.ToPointer ();
-                               memcpy (data + position, src, count);
+                               if (count < 32) {
+                                       byte *dest = (data + position);
+                                       for (int i = 0; i < count; i++)
+                                               *dest++ = *src++;
+                               } else {
+                                       memcpy (data + position, src, count);
+                               }
                                position += count;
                        }
 
index d2bd1447f7bd533d9b2111c36d94d7f64b6f1731..0ca52c6e21552a0481c4c8764edfe2a7c760ae4b 100644 (file)
@@ -40,6 +40,7 @@ using System.Security;
 using System.Security.Permissions;
 using System.Web.Caching;
 using System.Web.Configuration;
+using System.Web.Management;
 using System.Web.UI;
 using System.Web.Util;
 #if MONOWEB_DEP
@@ -453,7 +454,7 @@ namespace System.Web
                                SetupOfflineWatch ();
                                firstRun = false;
                                if (initialException != null) {
-                                       FinishWithException (req, new HttpException ("Initial exception", initialException));
+                                       FinishWithException (req, HttpException.NewWithCode ("Initial exception", initialException, WebEventCodes.RuntimeErrorRequestAbort));
                                        error = true;
                                }
                        }
@@ -470,7 +471,7 @@ namespace System.Web
                                try {
                                        app = HttpApplicationFactory.GetApplication (context);
                                } catch (Exception e) {
-                                       FinishWithException (req, new HttpException ("", e));
+                                       FinishWithException (req, HttpException.NewWithCode (String.Empty, e, WebEventCodes.RuntimeErrorRequestAbort));
                                        error = true;
                                }
                        }
index ec30ded240ad5495cf4ae2549867a08a03d9939e..e1fb52011f9f6017f96a3eb4f6ee86fbda1e9d2f 100644 (file)
@@ -91,7 +91,10 @@ namespace System.Web {
                }
 
                public virtual bool HasChildNodes {
-                       get { return ChildNodes != null && ChildNodes.Count != 0; }
+                       get {
+                               SiteMapNodeCollection childNodes = ChildNodes;
+                               return childNodes != null && childNodes.Count > 0;
+                       }
                }
 
                public SiteMapNodeCollection GetAllNodes ()
@@ -172,18 +175,11 @@ namespace System.Web {
                        }
                }
 
-               internal SiteMapNodeCollection ChildNodesInternal {
+               public virtual SiteMapNodeCollection ChildNodes {
                        get {
                                if (childNodes == null)
-                                       childNodes = new SiteMapNodeCollection ();
+                                       childNodes = provider.GetChildNodes (this);
                                return childNodes;
-                       }
-               }
-
-               public virtual SiteMapNodeCollection ChildNodes {
-                       get {
-                               if (childNodes != null) return childNodes;
-                               return provider.GetChildNodes (this);
                        } 
                        set {
                                CheckWritable ();
index 6de1e36317618375a3fe365137582e804fa50114..eb98c1af4d16a525a38525253b072ede28a71161 100644 (file)
@@ -4,3 +4,4 @@ Test/standalone-tests/OutputCacheProvider.cs
 Test/standalone-tests/RequestValidator.cs
 Test/standalone-tests/RequestValidatorTestGenerated.cs
 Test/standalone-tests/SiteMapDuplicateEntries_Bug570194.cs
+Test/standalone-tests/Unhandled_Exception_Global_Asax.cs
index d271519838c5b4c064f94112f1612f8cccf01b55..714e98645a8720c3fb8067e38d279f4505fc4c4d 100644 (file)
@@ -319,6 +319,7 @@ System.Web/HttpContextCas.cs
 System.Web/HttpCookieCas.cs
 System.Web/HttpCookieCollectionCas.cs
 System.Web/HttpExceptionCas.cs
+System.Web/HttpExceptionTest.cs
 System.Web/HttpFileCollectionCas.cs
 System.Web/HttpModuleCollectionCas.cs
 System.Web/HttpParseExceptionCas.cs
index be63b6822d79e192126c4b7ae13f46bf975cab6a..ec5560dfd07f509176543974c22f4d63748349d4 100644 (file)
@@ -222,11 +222,11 @@ namespace MonoTests.System.Web.Compilation {
                }
 
                [Test (Description="Bug #524358")]
-               [ExpectedException ("System.Web.Compilation.ParseException")]
                public void DuplicateControlsInClientComment ()
                {
                        // Just test if it throws an exception
-                       new WebTest ("DuplicateControlsInClientComment.aspx").Run ();
+                       string pageHtml = new WebTest ("DuplicateControlsInClientComment.aspx").Run ();
+                       Assert.IsTrue (pageHtml.IndexOf ("[System.Web.Compilation.ParseException]:") != -1, "#A1");
                }
 
                [Test (Description="Bug #367723")]
index 27817463966a1949bb88cb75563817c176bc91dd..2c8f4f1277e047b4e66ac881ade8e86eacb48790 100644 (file)
@@ -41,11 +41,20 @@ using System.Web.Configuration;
 using System.Web;
 using System.Web.Security;
 
+using MonoTests.SystemWeb.Framework;
+using MonoTests.stand_alone.WebHarness;
+
 namespace MonoTests.System.Web.Configuration {
 
        [TestFixture]
        public class GlobalizationSectionTest  {
 
+               [TestFixtureSetUp]
+               public void SetUp ()
+               {
+                       WebTest.CopyResource (GetType (), "GlobalizationEncodingName.aspx", "GlobalizationEncodingName.aspx");
+               }
+               
                [Test]
                public void Defaults ()
                {
@@ -161,6 +170,15 @@ namespace MonoTests.System.Web.Configuration {
                        mi.Invoke (s, parms);
                }
 
+               [Test]
+               public void GlobalizationEncodingName ()
+               {
+                       string pageHtml = new WebTest ("GlobalizationEncodingName.aspx").Run ();
+                       string renderedHtml = HtmlDiff.GetControlFromPageHtml (pageHtml);
+                       string originalHtml = "GOOD";
+                       Assert.AreEqual (originalHtml, renderedHtml, "#A1");
+               }
+               
        }
 }
 
index 31618d1dae7630e0eb439c33ecb0152bca00e70d..6b297869791979fe35f6f60b74591c60835e3a17 100644 (file)
@@ -1,3 +1,11 @@
+2010-04-13  Marek Habersack  <mhabersack@novell.com>
+
+       * CheckBoxFieldTest.cs: added test for bug #595568
+
+2010-04-01  Marek Habersack  <mhabersack@novell.com>
+
+       * FormViewTest.cs: added test for bug #578863
+
 2010-02-19  Marek Habersack  <mhabersack@novell.com>
 
        * SqlDataSourceTest.cs: added test for bug #572781
index 2ab402da6ba95a713ab38650abf9ddde2d22f7ec..955a3665b96bb6a5381dc9cd53cc16d012195e47 100644 (file)
@@ -43,8 +43,8 @@ using System.Collections.Specialized;
 using NUnit.Framework;
 using System.Data;
 
-
-
+using MonoTests.SystemWeb.Framework;
+using MonoTests.stand_alone.WebHarness;
 
 namespace MonoTests.System.Web.UI.WebControls
 {
@@ -114,6 +114,183 @@ namespace MonoTests.System.Web.UI.WebControls
                public const string WRONGFIELD = "str";
                public static int databound;
 
+               [TestFixtureSetUp]
+               public void SetUp ()
+               {
+                       WebTest.CopyResource (GetType (), "CheckBoxField_Bug595568_0.aspx", "CheckBoxField_Bug595568_0.aspx");
+                       WebTest.CopyResource (GetType (), "CheckBoxField_Bug595568_1.aspx", "CheckBoxField_Bug595568_1.aspx");
+                       WebTest.CopyResource (GetType (), "CheckBoxField_Bug595568_2.aspx", "CheckBoxField_Bug595568_2.aspx");
+                       WebTest.CopyResource (GetType (), "CheckBoxField_Bug595568_5.aspx", "CheckBoxField_Bug595568_5.aspx");
+                       WebTest.CopyResource (GetType (), "CheckBoxField_Bug595568_6.aspx", "CheckBoxField_Bug595568_6.aspx");
+                       WebTest.CopyResource (GetType (), "CheckBoxField_Bug595568_7.aspx", "CheckBoxField_Bug595568_7.aspx");
+               }
+
+               [Test (Description="Bug 595568 #0")]
+               public void CheckBoxField_Bug595568_0 ()
+               {
+                       string originalHtml = @"<div> 
+       <table id=""gridView"" cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;""> 
+                       <tr> 
+                               <th scope=""col"">&nbsp;</th> 
+                       </tr><tr> 
+                               <td><span title=""Dummy""><input id=""gridView_ctl02_ctl00"" type=""checkbox"" name=""gridView$ctl02$ctl00"" checked=""checked"" /></span></td> 
+                       </tr><tr> 
+                               <td><span title=""Dummy""><input id=""gridView_ctl03_ctl00"" type=""checkbox"" name=""gridView$ctl03$ctl00"" /></span></td> 
+                       </tr><tr> 
+                               <td><span title=""Dummy""><input id=""gridView_ctl04_ctl00"" type=""checkbox"" name=""gridView$ctl04$ctl00"" /></span></td> 
+                       </tr> 
+               </table>
+       </div>";
+                       WebTest t = new WebTest ("CheckBoxField_Bug595568_0.aspx");
+                       string pageHtml = t.Run ();
+                       string renderedHtml = HtmlDiff.GetControlFromPageHtml (pageHtml);
+
+                       HtmlDiff.AssertAreEqual (originalHtml, renderedHtml, "#A1");
+               }
+
+               [Test (Description="Bug 595568 #1")]
+               public void CheckBoxField_Bug595568_1 ()
+               {
+                       string originalHtml = @"<div> 
+       <table id=""gridView"" cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;""> 
+                       <tr> 
+                               <th scope=""col"">&nbsp;</th> 
+                       </tr><tr> 
+                               <td><select size=""4""> 
+                               </select><span title=""Dummy""><input id=""gridView_ctl02_ctl01"" type=""checkbox"" name=""gridView$ctl02$ctl01"" checked=""checked"" /></span></td> 
+                       </tr><tr> 
+                               <td><select size=""4""> 
+                               </select><span title=""Dummy""><input id=""gridView_ctl03_ctl01"" type=""checkbox"" name=""gridView$ctl03$ctl01"" /></span></td> 
+                       </tr><tr> 
+                               <td><select size=""4""> 
+                               </select><span title=""Dummy""><input id=""gridView_ctl04_ctl01"" type=""checkbox"" name=""gridView$ctl04$ctl01"" /></span></td> 
+                       </tr> 
+               </table> 
+       </div>";
+                       WebTest t = new WebTest ("CheckBoxField_Bug595568_1.aspx");
+                       string pageHtml = t.Run ();
+                       string renderedHtml = HtmlDiff.GetControlFromPageHtml (pageHtml);
+
+                       HtmlDiff.AssertAreEqual (originalHtml, renderedHtml, "#A1");
+               }
+
+               [Test (Description="Bug 595568 #2")]
+               public void CheckBoxField_Bug595568_2 ()
+               {
+                       string originalHtml = @"<div> 
+       <table id=""gridView"" cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;""> 
+                       <tr> 
+                               <th scope=""col"">&nbsp;</th> 
+                       </tr><tr> 
+                               <td><input id=""gridView_ctl02_ctl00"" type=""checkbox"" name=""gridView$ctl02$ctl00"" /><span title=""Dummy""><input id=""gridView_ctl02_ctl01"" type=""checkbox"" name=""gridView$ctl02$ctl01"" checked=""checked"" /></span><input id=""gridView_ctl02_ctl02"" type=""checkbox"" name=""gridView$ctl02$ctl02"" /></td> 
+                       </tr><tr> 
+                               <td><input id=""gridView_ctl03_ctl00"" type=""checkbox"" name=""gridView$ctl03$ctl00"" /><span title=""Dummy""><input id=""gridView_ctl03_ctl01"" type=""checkbox"" name=""gridView$ctl03$ctl01"" /></span><input id=""gridView_ctl03_ctl02"" type=""checkbox"" name=""gridView$ctl03$ctl02"" /></td> 
+                       </tr><tr> 
+                               <td><input id=""gridView_ctl04_ctl00"" type=""checkbox"" name=""gridView$ctl04$ctl00"" /><span title=""Dummy""><input id=""gridView_ctl04_ctl01"" type=""checkbox"" name=""gridView$ctl04$ctl01"" /></span><input id=""gridView_ctl04_ctl02"" type=""checkbox"" name=""gridView$ctl04$ctl02"" /></td> 
+                       </tr> 
+               </table> 
+       </div>";
+                       
+                       WebTest t = new WebTest ("CheckBoxField_Bug595568_2.aspx");
+                       string pageHtml = t.Run ();
+                       string renderedHtml = HtmlDiff.GetControlFromPageHtml (pageHtml);
+
+                       HtmlDiff.AssertAreEqual (originalHtml, renderedHtml, "#A1");
+               }
+
+               [Test (Description="Bug 595568 #5")]
+               public void CheckBoxField_Bug595568_5 ()
+               {
+                       string originalHtml = @"<div> 
+       <table id=""gridView"" cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;""> 
+                       <tr> 
+                               <th scope=""col"">&nbsp;</th> 
+                       </tr><tr> 
+                               <td><select size=""4""> 
+                               </select></td> 
+                       </tr><tr> 
+                               <td><select size=""4""> 
+                               </select></td> 
+                       </tr><tr> 
+                               <td><select size=""4""> 
+                               </select></td> 
+                       </tr> 
+               </table> 
+       </div>";
+
+                       WebTest t = new WebTest ("CheckBoxField_Bug595568_5.aspx");
+                       string pageHtml = t.Run ();
+                       string renderedHtml = HtmlDiff.GetControlFromPageHtml (pageHtml);
+
+                       HtmlDiff.AssertAreEqual (originalHtml, renderedHtml, "#A1");
+               }
+               
+               [Test (Description="Bug 595568 #6")]
+               public void CheckBoxField_Bug595568_6 ()
+               {       
+                       string originalHtml = @"<div> 
+       <table id=""gridView"" cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;""> 
+                       <tr> 
+                               <th scope=""col"">&nbsp;</th> 
+                       </tr><tr> 
+                               <td><select size=""4""> 
+                               </select><input id=""gridView_ctl02_ctl01"" type=""checkbox"" name=""gridView$ctl02$ctl01"" /></td> 
+                       </tr><tr> 
+                               <td><select size=""4""> 
+                               </select><input id=""gridView_ctl03_ctl01"" type=""checkbox"" name=""gridView$ctl03$ctl01"" /></td> 
+                       </tr><tr> 
+                               <td><select size=""4""> 
+                               </select><input id=""gridView_ctl04_ctl01"" type=""checkbox"" name=""gridView$ctl04$ctl01"" /></td> 
+                       </tr> 
+               </table> 
+       </div>";
+
+                       WebTest t = new WebTest ("CheckBoxField_Bug595568_6.aspx");
+                       string pageHtml = t.Run ();
+                       string renderedHtml = HtmlDiff.GetControlFromPageHtml (pageHtml);
+
+                       HtmlDiff.AssertAreEqual (originalHtml, renderedHtml, "#A1");
+               }
+
+               [Test (Description="Bug 595568 #7")]
+               public void CheckBoxField_Bug595568_7 ()
+               {
+                       string originalHtml = @"<div> 
+       <table id=""gridView"" cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;""> 
+                       <tr> 
+                               <th scope=""col"">&nbsp;</th> 
+                       </tr><tr> 
+                               <td><input id=""gridView_ctl02_ctl00"" type=""checkbox"" name=""gridView$ctl02$ctl00"" /><select size=""4""> 
+                               </select></td> 
+                       </tr><tr> 
+                               <td><input id=""gridView_ctl03_ctl00"" type=""checkbox"" name=""gridView$ctl03$ctl00"" /><select size=""4""> 
+                               </select></td> 
+                       </tr><tr> 
+                               <td><input id=""gridView_ctl04_ctl00"" type=""checkbox"" name=""gridView$ctl04$ctl00"" /><select size=""4""> 
+                               </select></td> 
+                       </tr> 
+               </table> 
+       </div>";
+
+                       WebTest t = new WebTest ("CheckBoxField_Bug595568_7.aspx");             
+                       string pageHtml = t.Run ();
+                       string renderedHtml = HtmlDiff.GetControlFromPageHtml (pageHtml);
+
+                       HtmlDiff.AssertAreEqual (originalHtml, renderedHtml, "#A1");
+               }
+               
                [Test]
                public void CheckBoxField_DefaultProperty ()
                {
index 134c69037a18b6a98c4ee360deb9893befaf58f9..fcec2e1ad3096f6ea544877e8826fcb043a7ec45 100644 (file)
@@ -385,6 +385,7 @@ namespace MonoTests.System.Web.UI.WebControls
                         WebTest.CopyResource (GetType (), "FormView.aspx", "FormView.aspx");
                         WebTest.CopyResource (GetType (), "FormViewTest1.aspx", "FormViewTest1.aspx");
                         WebTest.CopyResource (GetType (), "FormViewInsertEditDelete.aspx", "FormViewInsertEditDelete.aspx");
+                       WebTest.CopyResource (GetType (), "FormViewPagerVisibility.aspx", "FormViewPagerVisibility.aspx");
                }
                
 
@@ -1822,6 +1823,24 @@ CommandEventArgs cargs = new CommandEventArgs ("Page", "Prev");
                        
                }
 
+               [Test (Description="Bug #578863")]
+               public void FormView_PagerSettings_Visibility ()
+               {
+                       string origHtml = @"<table id=""FormView1"" cellpadding=""3"" cellspacing=""2"" rules=""all"" border=""1"" style=""background-color:#DEBA84;border-color:#DEBA84;border-width:1px;border-style:None;""> 
+               <tr style=""background-color:#FFF7E7;color:#8C4510;""> 
+                       <td colspan=""2""> 
+          <span id=""FormView1_Label1"">1</span> 
+       </td> 
+               </tr> 
+       </table>";
+                       
+                       WebTest t = new WebTest ("FormViewPagerVisibility.aspx");
+                       string pageHtml = t.Run ();
+                       string renderedHtml = HtmlDiff.GetControlFromPageHtml (pageHtml);
+
+                       HtmlDiff.AssertAreEqual (origHtml, renderedHtml, "#A1");
+               }
+               
                [Test]
                [Category ("NunitWeb")]
                public void FormView_FireEvent_1 ()
index 905f3d89d80b64e2f9348b969d220b76230c6663..57730c4bbd996b521a7b15966276dd6266c2a4e8 100644 (file)
@@ -440,8 +440,32 @@ namespace MonoTests.System.Web.UI.WebControls
                        WebTest.CopyResource (GetType (), "NoEventValidation.aspx", "NoEventValidation.aspx");
                        WebTest.CopyResource (GetType (), "TableSections_Bug551666.aspx", "TableSections_Bug551666.aspx");
                        WebTest.CopyResource (GetType (), "TableSections_Bug551666.aspx.cs", "TableSections_Bug551666.aspx.cs");
-               }
+                       WebTest.CopyResource (GetType (), "GridView_Bug595567.aspx", "GridView_Bug595567.aspx");
+               }
+
+               [Test (Description="Bug 595567")]
+               public void HeaderFooterVisibility_Bug595567 ()
+               {
+                       WebTest t = new WebTest ("GridView_Bug595567.aspx");
+                       string originalHtml = @"<div> 
+       <table id=""gridView"" cellspacing=""0"" rules=""all"" border=""1"" style=""border-collapse:collapse;""> 
+                       <tr> 
+                               <th scope=""col"">Item</th> 
+                       </tr><tr> 
+                               <td>0</td> 
+                       </tr><tr> 
+                               <td>0</td> 
+                       </tr><tr> 
+                               <td>0</td> 
+                       </tr> 
+               </table> 
+       </div>";
+                       string pageHtml = t.Run ();
+                       string renderedHtml = HtmlDiff.GetControlFromPageHtml (pageHtml);
 
+                       HtmlDiff.AssertAreEqual (originalHtml, renderedHtml, "#A1");
+               }
+               
                [Test]
                public void GridView_DefaultProperties ()
                {
index 1e6a577df86bd991e66b51c11dd994ffa88e1e52..2c4b89c477d2a8c7736b8597511f4c02ace5de01 100644 (file)
@@ -1,3 +1,7 @@
+2010-04-07  Marek Habersack  <mhabersack@novell.com>
+
+       * ControlTest.cs: added test for bug #594238
+
 2009-12-18  Marek Habersack  <mhabersack@novell.com>
 
        * ObjectStateFormatterTest.cs: added.
index e52699b5137f39b97ef0255784910e39902d0c1e..9da9eaed5c0e95e8f5d22469a86c77017c05d9e0 100644 (file)
@@ -39,6 +39,7 @@ using System.Web;
 using System.Web.UI;
 using System.Web.UI.WebControls;
 using MonoTests.SystemWeb.Framework;
+using MonoTests.stand_alone.WebHarness;
 
 #if NET_2_0
 using System.Web.UI.Adapters;
@@ -978,6 +979,26 @@ namespace MonoTests.System.Web.UI
                }
 
 #if NET_2_0
+               [Test (Description="Bug #594238")]
+               public void OverridenControlsPropertyAndPostBack_Bug594238 ()
+               {
+                       WebTest t = new WebTest ("OverridenControlsPropertyAndPostBack_Bug594238.aspx");
+                       t.Run ();
+
+                       FormRequest fr = new FormRequest (t.Response, "form1");
+                       fr.Controls.Add ("__EVENTTARGET");
+                       fr.Controls.Add ("__EVENTARGUMENT");
+                       fr.Controls ["__EVENTTARGET"].Value = "container$children$lb";
+                       fr.Controls ["__EVENTARGUMENT"].Value = String.Empty;
+                       t.Request = fr;
+
+                       string originalHtml = @"<span id=""container""><a href=""javascript:__doPostBack('container$children$lb','')"" id=""container_children_lb"">Woot! I got clicked!</a></span><hr/>";
+                       string pageHtml = t.Run ();
+                       string renderedHtml = HtmlDiff.GetControlFromPageHtml (pageHtml);
+
+                       HtmlDiff.AssertAreEqual (originalHtml, renderedHtml, "#A1");
+               }
+               
                [TestFixtureTearDown]
                public void Tear_down ()
                {
@@ -989,6 +1010,7 @@ namespace MonoTests.System.Web.UI
                {
                        WebTest.CopyResource (GetType (), "ResolveUrl.aspx", "ResolveUrl.aspx");
                        WebTest.CopyResource (GetType (), "ResolveUrl.ascx", "Folder/ResolveUrl.ascx");
+                       WebTest.CopyResource (GetType (), "OverridenControlsPropertyAndPostBack_Bug594238.aspx", "OverridenControlsPropertyAndPostBack_Bug594238.aspx");
                }
 
 #endif
index 8f94f587a422c26f71dd6e5c816eefd4ba3a45a6..50825f57a169bb1ee474297dca99bcc6857a20fb 100644 (file)
@@ -44,10 +44,10 @@ namespace MonoTests.System.Web.UI
                }
                
                [Test]
-               [ExpectedException ("System.Web.Compilation.ParseException")]
                public void MissingMasterFile ()
                {
-                       new WebTest ("MissingMasterFile.aspx").Run ();
+                       string pageHtml = new WebTest ("MissingMasterFile.aspx").Run ();
+                       Assert.IsTrue (pageHtml.IndexOf ("[System.Web.Compilation.ParseException]:") != -1, "#A1");
                }
        }
 }
index 2f640577a411e9e31ceac5eae41d5fab17700a30..d2dcf223779108a6263d88b30600d8c37f7eb864 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-20  Marek Habersack  <mhabersack@novell.com>
+
+       * XmlSiteMapProviderTest.cs: AreEqual should have expected result first
+       and actual next - swapped parameters in RootNode_2_OnLoad
+
 2009-11-16  Marek Habersack  <mhabersack@novell.com>
 
        * HttpContext.cs: added some tests for RewritePath
diff --git a/mcs/class/System.Web/Test/System.Web/HttpExceptionTest.cs b/mcs/class/System.Web/Test/System.Web/HttpExceptionTest.cs
new file mode 100644 (file)
index 0000000..69a21a3
--- /dev/null
@@ -0,0 +1,23 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Web;
+using System.Web.Management;
+
+using NUnit.Framework;
+
+namespace MonoTests.System.Web
+{
+       [TestFixture]
+       public class HttpExceptionTest
+       {
+#if NET_4_0
+               [Test]
+               public void WebEventCode ()
+               {
+                       var ex = new HttpException ();
+                       Assert.AreEqual (WebEventCodes.UndefinedEventCode, ex.WebEventCode);
+               }
+#endif
+       }
+}
index 60f384a4824c2902c28ae1f6ae960f4d538db86e..0eae9bc5a9ab725ecc90605ca3eac7faa7a35ae5 100644 (file)
@@ -249,8 +249,8 @@ namespace MonoTests.System.Web
                        Assert.AreEqual (provider.RootNode.Provider, provider, "#A2");
                        Assert.IsNotNull (provider.CallTrace, "#A3");
                        Assert.Greater (provider.CallTrace.Length, 1, "#A3-1");
-                       Assert.AreEqual (provider.CallTrace[0].Name, "BuildSiteMap", "#A3-2");
-                       Assert.AreEqual (provider.CallTrace[1].Name, "get_RootNode", "#A3-3");
+                       Assert.AreEqual ("BuildSiteMap", provider.CallTrace[0].Name, "#A3-2");
+                       Assert.AreEqual ("get_RootNode", provider.CallTrace[1].Name, "#A3-3");
                }
 
                [Test]
index 125a21bbc9f56847b37ee585ebd8b3d19841767a..e1f8ed657cea743edbaa1789cc20f54bd61b7547 100644 (file)
@@ -1,3 +1,11 @@
+2010-04-07  Marek Habersack  <mhabersack@novell.com>
+
+       * WebTest.cs: introduced concept of prefixed resources and added
+       an API which handles them - CopyPrefixedResources. All the
+       manifest resource names are checked for match with the given
+       prefix, and all the matching ones are copied to the specified
+       subdirectory of the test directory.
+
 2010-02-11  Marek Habersack  <mhabersack@novell.com>
 
        * WebTest.cs: test environment setup enhancements. Contributed by
index 223f21ccded2b396a5b86779add7fce9ee692022..152b15fe79043ebfe3a38aa711446a6382f331be 100644 (file)
@@ -302,6 +302,8 @@ namespace MonoTests.SystemWeb.Framework
                /// <example><code>CopyResource (GetType (), "Default.skin", "App_Themes/Black/Default.skin");</code></example>
                public static void CopyResource (Type type, string resourceName, string targetUrl)
                {
+                       if (type == null)
+                               throw new ArgumentNullException ("type");
 #if !TARGET_JVM
                        using (Stream source = type.Assembly.GetManifestResourceStream (resourceName)) {
                                if (source == null)
@@ -313,6 +315,26 @@ namespace MonoTests.SystemWeb.Framework
 #endif
                }
 
+               public static void CopyPrefixedResources (Type type, string namePrefix, string targetDir)
+               {
+                       if (type == null)
+                               throw new ArgumentNullException ("type");
+                       
+                       string[] manifestResources = type.Assembly.GetManifestResourceNames ();
+                       if (manifestResources == null || manifestResources.Length == 0)
+                               return;
+
+                       foreach (string resource in manifestResources) {
+                               if (resource == null || resource.Length == 0)
+                                       continue;
+                               
+                               if (!resource.StartsWith (namePrefix))
+                                       continue;
+                               
+                               CopyResource (type, resource, Path.Combine (targetDir, resource.Substring (namePrefix.Length)));
+                       }
+               }
+               
                /// <summary>
                /// Copy a chunk of data as a file into the web application.
                /// </summary>
@@ -570,23 +592,23 @@ namespace MonoTests.SystemWeb.Framework
 
                public static void CopyResources ()
                {
-                       CopyResource (typeof (WebTest), "My.ashx", "My.ashx");
-                       CopyResource (typeof (WebTest), "Global.asax", "Global.asax");
+                       Type myself = typeof (WebTest);
+                       
+                       CopyResource (myself, "My.ashx", "My.ashx");
+                       CopyResource (myself, "Global.asax", "Global.asax");
 #if NET_2_0
 #if INSIDE_SYSTEM_WEB
-                       CopyResource (typeof (WebTest), "Common.resx", "App_GlobalResources/Common.resx");
-                       CopyResource (typeof (WebTest), "Common.fr-FR.resx", "App_GlobalResources/Common.fr-FR.resx");
-                       CopyResource (typeof (WebTest), "Resource1.resx", "App_GlobalResources/Resource1.resx");
-                       CopyResource (typeof (WebTest), "EnumConverterControl.cs", "App_Code/EnumConverterControl.cs");
+                       CopyPrefixedResources (myself, "App_GlobalResources/", "App_GlobalResources");
+                       CopyPrefixedResources (myself, "App_Code/", "App_Code");
 #endif
-                       CopyResource (typeof (WebTest), "Web.mono.config", "Web.config");
+                       CopyResource (myself, "Web.mono.config", "Web.config");
 #else
-                       CopyResource (typeof (WebTest), "Web.mono.config.1.1", "Web.config");
+                       CopyResource (myself, "Web.mono.config.1.1", "Web.config");
 #endif
-                       CopyResource (typeof (WebTest), "MyPage.aspx", "MyPage.aspx");
-                       CopyResource (typeof (WebTest), "MyPage.aspx.cs", "MyPage.aspx.cs");
-                       CopyResource (typeof (WebTest), "MyPageWithMaster.aspx", "MyPageWithMaster.aspx");
-                       CopyResource (typeof (WebTest), "My.master", "My.master");
+                       CopyResource (myself, "MyPage.aspx", "MyPage.aspx");
+                       CopyResource (myself, "MyPage.aspx.cs", "MyPage.aspx.cs");
+                       CopyResource (myself, "MyPageWithMaster.aspx", "MyPageWithMaster.aspx");
+                       CopyResource (myself, "My.master", "My.master");
                }
 #endif
        }
diff --git a/mcs/class/System.Web/Test/mainsoft/NunitWebResources/App_Code/CustomCheckBoxColumn.cs b/mcs/class/System.Web/Test/mainsoft/NunitWebResources/App_Code/CustomCheckBoxColumn.cs
new file mode 100644 (file)
index 0000000..9c5ba12
--- /dev/null
@@ -0,0 +1,118 @@
+using System;
+using System.Web;
+using System.Web.UI;
+using System.Web.UI.WebControls;
+
+namespace Tests
+{
+       public class CustomCheckBoxColumn : CheckBoxField
+       {
+               string caseId;
+
+               public CustomCheckBoxColumn (string id)
+               {
+                       this.caseId = id;
+               }
+
+               protected override void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)
+               {
+                       switch (caseId) {
+                               default:
+                               case "0":
+                                       Case0 (cell);
+                               break;
+                       
+                               case "1":
+                                       Case1 (cell);
+                                       break;
+                       
+                               case "2":
+                                       Case2 (cell);
+                                       break;
+                       
+                               case "3":
+                                       Case3 (cell);
+                                       break;
+               
+                               case "4":
+                                       Case4 (cell);
+                                       break;
+               
+                               case "5":
+                                       Case5 (cell);
+                                       break;
+               
+                               case "6":
+                                       Case6 (cell);
+                                       break;
+               
+                               case "7":
+                                       Case7 (cell);
+                                       break;
+                       }
+               }
+       
+               void Case0 (DataControlFieldCell cell)
+               {
+                       CheckBox checkBox = new CheckBox();
+                       checkBox.ToolTip = "Dummy";
+                       cell.Controls.Add(checkBox);
+                       checkBox.DataBinding += OnDataBindField;
+               }
+        
+               void Case1 (DataControlFieldCell cell)
+               {
+                       ListBox lb = new ListBox ();
+                       cell.Controls.Add(lb);
+                       Case0 (cell);
+               }
+        
+               void Case2 (DataControlFieldCell cell)
+               {
+                       cell.Controls.Add(new CheckBox ());
+                       Case0 (cell);
+                       cell.Controls.Add(new CheckBox ());
+               }
+        
+               void Case3 (DataControlFieldCell cell)
+               {
+                       Content content = new Content ();
+           
+                       CheckBox checkBox = new CheckBox();
+                       checkBox.ToolTip = "Dummy";
+                       content.Controls.Add(checkBox);
+                       checkBox.DataBinding += OnDataBindField;
+            
+                       cell.Controls.Add (content);
+               }
+        
+               void Case4 (DataControlFieldCell cell)
+               {
+                       CheckBox checkBox = new CheckBox();
+                       checkBox.ToolTip = "Dummy";
+                       cell.Controls.Add(checkBox);
+            
+                       ListBox lb = new ListBox ();
+                       lb.DataBinding += OnDataBindField;
+                       cell.Controls.Add(lb);
+               }
+        
+               void Case5 (DataControlFieldCell cell)
+               {
+                       cell.Controls.Add (new ListBox ());
+               }
+       
+               void Case6 (DataControlFieldCell cell)
+               {
+                       cell.Controls.Add (new ListBox ());
+                       cell.Controls.Add (new CheckBox ());
+               }
+       
+               void Case7 (DataControlFieldCell cell)
+               {
+                       cell.Controls.Add (new CheckBox ());
+                       cell.Controls.Add (new ListBox ());
+               }
+       }
+}
+
diff --git a/mcs/class/System.Web/Test/mainsoft/NunitWebResources/App_Code/MyContainer.cs b/mcs/class/System.Web/Test/mainsoft/NunitWebResources/App_Code/MyContainer.cs
new file mode 100644 (file)
index 0000000..a2a9c1f
--- /dev/null
@@ -0,0 +1,36 @@
+// Bug #594238
+using System;
+using System.Web.UI;
+using System.Web.UI.WebControls;
+
+namespace TestNamedHolders
+{
+       public class MyContainer : WebControl, INamingContainer
+       {
+               Control whereTheChildrenPlay;
+               
+               // can't do this if it is an INamingContainer
+               public override ControlCollection Controls 
+               {
+                       get { return whereTheChildrenPlay.Controls;     }
+               }
+               
+               public MyContainer()
+               {
+                       whereTheChildrenPlay = new Content();
+                       whereTheChildrenPlay.ID = "children";
+               }
+
+               protected override void OnLoad (EventArgs e)
+               {
+                       base.OnLoad (e);
+                       
+                       // would normally put other stuff here
+                       
+                       base.Controls.Add(whereTheChildrenPlay);
+
+                       // and possibly here
+               }
+
+       }
+}
diff --git a/mcs/class/System.Web/Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_0.aspx b/mcs/class/System.Web/Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_0.aspx
new file mode 100644 (file)
index 0000000..67d0e1d
--- /dev/null
@@ -0,0 +1,35 @@
+<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyPage.aspx.cs" Inherits="MyPage" %>
+<%@ Import Namespace="Tests" %>
+
+<script runat="server">
+    protected void Page_Load(object sender, EventArgs e)
+    {
+        if (IsPostBack) return;
+        
+        bool[] ba = new bool [3];
+        ba [0] = true;
+        gridView.DataSource = ba;
+        gridView.DataBind();
+    }
+
+    protected void OnGridViewInit(object sender, EventArgs e)
+    {
+        CustomCheckBoxColumn column = new CustomCheckBoxColumn("0");
+        column.DataField = "!";
+        gridView.Columns.Add(column);
+    }
+</script>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head runat="server">
+    <title></title>
+</head>
+<body>
+    <form id="form1" method="GET" runat="server">
+    <div>
+        <%= MonoTests.stand_alone.WebHarness.HtmlDiff.BEGIN_TAG %><asp:GridView runat="server" ID="gridView" OnInit="OnGridViewInit" AutoGenerateColumns="False" /><%= MonoTests.stand_alone.WebHarness.HtmlDiff.END_TAG %>
+    </div>
+    </form>
+</body>
+</html>
diff --git a/mcs/class/System.Web/Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_1.aspx b/mcs/class/System.Web/Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_1.aspx
new file mode 100644 (file)
index 0000000..37c965e
--- /dev/null
@@ -0,0 +1,35 @@
+<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyPage.aspx.cs" Inherits="MyPage" %>
+<%@ Import Namespace="Tests" %>
+
+<script runat="server">
+    protected void Page_Load(object sender, EventArgs e)
+    {
+        if (IsPostBack) return;
+        
+        bool[] ba = new bool [3];
+        ba [0] = true;
+        gridView.DataSource = ba;
+        gridView.DataBind();
+    }
+
+    protected void OnGridViewInit(object sender, EventArgs e)
+    {
+        CustomCheckBoxColumn column = new CustomCheckBoxColumn("1");
+        column.DataField = "!";
+        gridView.Columns.Add(column);
+    }
+</script>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head runat="server">
+    <title></title>
+</head>
+<body>
+    <form id="form1" method="GET" runat="server">
+    <div>
+        <%= MonoTests.stand_alone.WebHarness.HtmlDiff.BEGIN_TAG %><asp:GridView runat="server" ID="gridView" OnInit="OnGridViewInit" AutoGenerateColumns="False" /><%= MonoTests.stand_alone.WebHarness.HtmlDiff.END_TAG %>
+    </div>
+    </form>
+</body>
+</html>
diff --git a/mcs/class/System.Web/Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_2.aspx b/mcs/class/System.Web/Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_2.aspx
new file mode 100644 (file)
index 0000000..e477f9a
--- /dev/null
@@ -0,0 +1,35 @@
+<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyPage.aspx.cs" Inherits="MyPage" %>
+<%@ Import Namespace="Tests" %>
+
+<script runat="server">
+    protected void Page_Load(object sender, EventArgs e)
+    {
+        if (IsPostBack) return;
+        
+        bool[] ba = new bool [3];
+        ba [0] = true;
+        gridView.DataSource = ba;
+        gridView.DataBind();
+    }
+
+    protected void OnGridViewInit(object sender, EventArgs e)
+    {
+        CustomCheckBoxColumn column = new CustomCheckBoxColumn("2");
+        column.DataField = "!";
+        gridView.Columns.Add(column);
+    }
+</script>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head runat="server">
+    <title></title>
+</head>
+<body>
+    <form id="form1" method="GET" runat="server">
+    <div>
+        <%= MonoTests.stand_alone.WebHarness.HtmlDiff.BEGIN_TAG %><asp:GridView runat="server" ID="gridView" OnInit="OnGridViewInit" AutoGenerateColumns="False" /><%= MonoTests.stand_alone.WebHarness.HtmlDiff.END_TAG %>
+    </div>
+    </form>
+</body>
+</html>
diff --git a/mcs/class/System.Web/Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_5.aspx b/mcs/class/System.Web/Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_5.aspx
new file mode 100644 (file)
index 0000000..ce7567d
--- /dev/null
@@ -0,0 +1,35 @@
+<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyPage.aspx.cs" Inherits="MyPage" %>
+<%@ Import Namespace="Tests" %>
+
+<script runat="server">
+    protected void Page_Load(object sender, EventArgs e)
+    {
+        if (IsPostBack) return;
+        
+        bool[] ba = new bool [3];
+        ba [0] = true;
+        gridView.DataSource = ba;
+        gridView.DataBind();
+    }
+
+    protected void OnGridViewInit(object sender, EventArgs e)
+    {
+        CustomCheckBoxColumn column = new CustomCheckBoxColumn("5");
+        column.DataField = "!";
+        gridView.Columns.Add(column);
+    }
+</script>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head runat="server">
+    <title></title>
+</head>
+<body>
+    <form id="form1" method="GET" runat="server">
+    <div>
+        <%= MonoTests.stand_alone.WebHarness.HtmlDiff.BEGIN_TAG %><asp:GridView runat="server" ID="gridView" OnInit="OnGridViewInit" AutoGenerateColumns="False" /><%= MonoTests.stand_alone.WebHarness.HtmlDiff.END_TAG %>
+    </div>
+    </form>
+</body>
+</html>
diff --git a/mcs/class/System.Web/Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_6.aspx b/mcs/class/System.Web/Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_6.aspx
new file mode 100644 (file)
index 0000000..c9c93e9
--- /dev/null
@@ -0,0 +1,35 @@
+<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyPage.aspx.cs" Inherits="MyPage" %>
+<%@ Import Namespace="Tests" %>
+
+<script runat="server">
+    protected void Page_Load(object sender, EventArgs e)
+    {
+        if (IsPostBack) return;
+        
+        bool[] ba = new bool [3];
+        ba [0] = true;
+        gridView.DataSource = ba;
+        gridView.DataBind();
+    }
+
+    protected void OnGridViewInit(object sender, EventArgs e)
+    {
+        CustomCheckBoxColumn column = new CustomCheckBoxColumn("6");
+        column.DataField = "!";
+        gridView.Columns.Add(column);
+    }
+</script>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head runat="server">
+    <title></title>
+</head>
+<body>
+    <form id="form1" method="GET" runat="server">
+    <div>
+        <%= MonoTests.stand_alone.WebHarness.HtmlDiff.BEGIN_TAG %><asp:GridView runat="server" ID="gridView" OnInit="OnGridViewInit" AutoGenerateColumns="False" /><%= MonoTests.stand_alone.WebHarness.HtmlDiff.END_TAG %>
+    </div>
+    </form>
+</body>
+</html>
diff --git a/mcs/class/System.Web/Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_7.aspx b/mcs/class/System.Web/Test/mainsoft/NunitWebResources/CheckBoxField_Bug595568_7.aspx
new file mode 100644 (file)
index 0000000..8461ee7
--- /dev/null
@@ -0,0 +1,35 @@
+<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyPage.aspx.cs" Inherits="MyPage" %>
+<%@ Import Namespace="Tests" %>
+
+<script runat="server">
+    protected void Page_Load(object sender, EventArgs e)
+    {
+        if (IsPostBack) return;
+        
+        bool[] ba = new bool [3];
+        ba [0] = true;
+        gridView.DataSource = ba;
+        gridView.DataBind();
+    }
+
+    protected void OnGridViewInit(object sender, EventArgs e)
+    {
+        CustomCheckBoxColumn column = new CustomCheckBoxColumn("7");
+        column.DataField = "!";
+        gridView.Columns.Add(column);
+    }
+</script>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head runat="server">
+    <title></title>
+</head>
+<body>
+    <form id="form1" method="GET" runat="server">
+    <div>
+        <%= MonoTests.stand_alone.WebHarness.HtmlDiff.BEGIN_TAG %><asp:GridView runat="server" ID="gridView" OnInit="OnGridViewInit" AutoGenerateColumns="False" /><%= MonoTests.stand_alone.WebHarness.HtmlDiff.END_TAG %>
+    </div>
+    </form>
+</body>
+</html>
diff --git a/mcs/class/System.Web/Test/mainsoft/NunitWebResources/FormViewPagerVisibility.aspx b/mcs/class/System.Web/Test/mainsoft/NunitWebResources/FormViewPagerVisibility.aspx
new file mode 100644 (file)
index 0000000..328a350
--- /dev/null
@@ -0,0 +1,38 @@
+<%@ Page Language="C#" %>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+  <head>
+    <title>Bug #578863</title>
+  </head>
+  <body>
+    <form id="form1" runat="server">
+      <%= MonoTests.stand_alone.WebHarness.HtmlDiff.BEGIN_TAG %><asp:FormView ID="FormView1" runat="server" AllowPaging="True" BackColor="#DEBA84"
+                   BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2"
+                   DataSourceID="ObjectDataSource1" GridLines="Both">
+       <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
+       <EditRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
+       <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
+       <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
+       <ItemTemplate>
+          <asp:Label ID="Label1" runat="server" Text="<%# FormView1.DataItem.ToString() %>"></asp:Label>
+       </ItemTemplate>
+       <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
+       <PagerSettings Visible="false"/>
+      </asp:FormView><%= MonoTests.stand_alone.WebHarness.HtmlDiff.END_TAG %>
+      <asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
+                           DeleteMethod="DeleteList" InsertMethod="InsertList" SelectMethod="GetMyList"
+                           TypeName="MonoTests.System.Web.UI.WebControls.TestMyData" UpdateMethod="UpdateList">
+       <DeleteParameters>
+          <asp:Parameter Name="value" Type="Int32" />
+       </DeleteParameters>
+       <InsertParameters>
+          <asp:Parameter Name="value" Type="Int32" />
+       </InsertParameters>
+       <UpdateParameters>
+          <asp:Parameter Name="index" Type="Int32" />
+          <asp:Parameter Name="value" Type="Int32" />
+       </UpdateParameters>
+      </asp:ObjectDataSource>
+    </form>
+  </body>
+</html>
diff --git a/mcs/class/System.Web/Test/mainsoft/NunitWebResources/GlobalizationEncodingName.aspx b/mcs/class/System.Web/Test/mainsoft/NunitWebResources/GlobalizationEncodingName.aspx
new file mode 100644 (file)
index 0000000..f8928ba
--- /dev/null
@@ -0,0 +1,17 @@
+<%@ Page Language="C#" CodeFile="MyPage.aspx.cs" Inherits="MyPage" %>
+<%@ Import Namespace="System.Web.Configuration" %>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" >
+</head>
+<body>
+<%= MonoTests.stand_alone.WebHarness.HtmlDiff.BEGIN_TAG %><%
+        Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");
+        GlobalizationSection configSection = (GlobalizationSection)config.GetSection("system.web/globalization");
+        configSection.RequestEncoding = Encoding.UTF7;
+        if (configSection.RequestEncoding == Encoding.UTF7)
+               Response.Write ("GOOD");
+       else
+               Response.Write ("BAD");
+%><%= MonoTests.stand_alone.WebHarness.HtmlDiff.END_TAG %>
+</body>
+</html>
diff --git a/mcs/class/System.Web/Test/mainsoft/NunitWebResources/GridView_Bug595567.aspx b/mcs/class/System.Web/Test/mainsoft/NunitWebResources/GridView_Bug595567.aspx
new file mode 100644 (file)
index 0000000..e16ea71
--- /dev/null
@@ -0,0 +1,28 @@
+<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyPage.aspx.cs" Inherits="MyPage" %>
+<script runat="server">
+    protected void Page_Load(object sender, EventArgs e)
+    {
+        if (IsPostBack) return;
+        
+        gridView.DataSource = new int[3];
+        gridView.DataBind();
+
+        GridViewRow row = gridView.FooterRow;
+        if (row.RowType == DataControlRowType.Footer && !gridView.ShowFooter && row.Visible)
+            throw new InvalidOperationException("Unexpected state: GridView.ShowFooter is False but the Footer row is Visible!");
+    }
+</script>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head runat="server">
+    <title></title>
+</head>
+<body>
+    <form id="form1" runat="server">
+    <div>
+       <%= MonoTests.stand_alone.WebHarness.HtmlDiff.BEGIN_TAG %><asp:GridView runat="server" ID="gridView" /><%= MonoTests.stand_alone.WebHarness.HtmlDiff.END_TAG %>
+    </div>
+    </form>
+</body>
+</html>
diff --git a/mcs/class/System.Web/Test/mainsoft/NunitWebResources/OverridenControlsPropertyAndPostBack_Bug594238.aspx b/mcs/class/System.Web/Test/mainsoft/NunitWebResources/OverridenControlsPropertyAndPostBack_Bug594238.aspx
new file mode 100644 (file)
index 0000000..7d361d7
--- /dev/null
@@ -0,0 +1,29 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<%@ Page Language="C#" CodeFile="MyPage.aspx.cs" Inherits="MyPage" %>
+<%@ Register Assembly="App_Code" Namespace="TestNamedHolders" TagPrefix="tnh" %>
+<script runat="server">
+       protected override void OnLoad (EventArgs e)
+       {
+               base.OnLoad (e);
+               LinkButton lb = new LinkButton();
+               lb.ID = "lb";
+               lb.Text = "Click me!";
+               lb.Click += delegate {
+                       lb.Text = "Woot! I got clicked!";
+               };
+               this.container.Controls.Add(lb);
+       }
+</script>
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head runat="server">
+       <title>Default</title>
+</head>
+<body>
+       <form id="form1" runat="server">
+       <div>
+               <%= MonoTests.stand_alone.WebHarness.HtmlDiff.BEGIN_TAG %><tnh:MyContainer id="container" runat="server">
+               </tnh:MyContainer><hr/><%= MonoTests.stand_alone.WebHarness.HtmlDiff.END_TAG %>
+       </div>
+       </form>
+</body>
+</html>
\ No newline at end of file
index 65e38e01ea979402a4e40d4b2c046b6a938515fd..c29a137c1392c2616f12dacdd96a37c627a70a41 100644 (file)
@@ -1,3 +1,8 @@
+2010-04-02  Marek Habersack  <mhabersack@novell.com>
+
+       * Unhandled_Exception_Global_Asax.cs: added - tests for bug
+       #572469
+
 2010-03-06  Marek Habersack  <mhabersack@novell.com>
 
        * RequestValidatorTestGenerated.cs: added
diff --git a/mcs/class/System.Web/Test/standalone-tests/Unhandled_Exception_Global_Asax.cs b/mcs/class/System.Web/Test/standalone-tests/Unhandled_Exception_Global_Asax.cs
new file mode 100644 (file)
index 0000000..bcb569c
--- /dev/null
@@ -0,0 +1,169 @@
+//
+// Authors:
+//   Marek Habersack (mhabersack@novell.com)
+//
+// (C) 2010 Novell, Inc http://novell.com/
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Configuration;
+using System.Configuration.Provider;
+using System.IO;
+using System.Web;
+using System.Web.Hosting;
+
+using StandAloneRunnerSupport;
+using StandAloneTests;
+
+using NUnit.Framework;
+
+namespace StandAloneTests.Unhandled_Exception_Global_Asax
+{
+       [TestCase ("Unhandled_Exception_Global_Asax 01", "Unhandled exception not handled in Global.asax, test 01")]
+       public sealed class Unhandled_Exception_Global_Asax_01 : ITestCase
+       {
+               public string PhysicalPath {
+                       get {
+                               return Path.Combine (
+                                       Consts.BasePhysicalDir,
+                                       Path.Combine ("Unhandled_Exception_Global_Asax", "test_01")
+                               );
+                       }
+               }
+               
+               public string VirtualPath  {
+                       get { return "/"; }
+               }
+
+               public bool SetUp (List <TestRunItem> runItems)
+               {
+                       runItems.Add (new TestRunItem ("/default.aspx", Default_Aspx));
+                       
+                       return true;
+               }
+
+               void Default_Aspx (string result, TestRunItem runItem)
+               {
+                       string originalHtml1 = @"[System.Web.HttpUnhandledException]: Exception of type 'System.Web.HttpUnhandledException' was thrown.";
+                       string originalHtml2 = @"[System.InvalidOperationException]: test";
+                       
+                       Assert.IsTrue (result.IndexOf (originalHtml1) != -1, "#A1");
+                       Assert.IsTrue (result.IndexOf (originalHtml2) != -1, "#A2");
+               }
+       }
+
+       [TestCase ("Unhandled_Exception_Global_Asax 02", "Parsing exception is not handled in Global.asax, test 02")]
+       public sealed class Unhandled_Exception_Global_Asax_02 : ITestCase
+       {
+               public string PhysicalPath {
+                       get {
+                               return Path.Combine (
+                                       Consts.BasePhysicalDir,
+                                       Path.Combine ("Unhandled_Exception_Global_Asax", "test_02")
+                               );
+                       }
+               }
+               
+               public string VirtualPath  {
+                       get { return "/"; }
+               }
+
+               public bool SetUp (List <TestRunItem> runItems)
+               {
+                       runItems.Add (new TestRunItem ("/default.aspx", Default_Aspx));
+                       
+                       return true;
+               }
+
+               void Default_Aspx (string result, TestRunItem runItem)
+               {
+                       string originalHtml = @"<p><strong>Parser Error Message: </strong><code>Cannot find type DoesNotExist</code></p><p><strong>Source Error: </strong></p>";
+
+                       Assert.IsTrue (result.IndexOf (originalHtml) != -1, "#A1");
+               }
+       }
+
+       [TestCase ("Unhandled_Exception_Global_Asax 03", "Unhandled exception handled in Global.asax, test 03")]
+       public sealed class Unhandled_Exception_Global_Asax_03 : ITestCase
+       {
+               public string PhysicalPath {
+                       get {
+                               return Path.Combine (
+                                       Consts.BasePhysicalDir,
+                                       Path.Combine ("Unhandled_Exception_Global_Asax", "test_03")
+                               );
+                       }
+               }
+               
+               public string VirtualPath  {
+                       get { return "/"; }
+               }
+
+               public bool SetUp (List <TestRunItem> runItems)
+               {
+                       runItems.Add (new TestRunItem ("/default.aspx", Default_Aspx));
+                       
+                       return true;
+               }
+
+               void Default_Aspx (string result, TestRunItem runItem)
+               {
+                       string originalHtml = @"<strong>Application error handled</strong>";
+                       
+                       Helpers.ExtractAndCompareCodeFromHtml (result, originalHtml, "#A1");
+               }
+       }
+
+       [TestCase ("Unhandled_Exception_Global_Asax 04", "Unhandled exception handled in Global.asax, test 04")]
+       public sealed class Unhandled_Exception_Global_Asax_04 : ITestCase
+       {
+               public string PhysicalPath {
+                       get {
+                               return Path.Combine (
+                                       Consts.BasePhysicalDir,
+                                       Path.Combine ("Unhandled_Exception_Global_Asax", "test_04")
+                               );
+                       }
+               }
+               
+               public string VirtualPath  {
+                       get { return "/"; }
+               }
+
+               public bool SetUp (List <TestRunItem> runItems)
+               {
+                       runItems.Add (new TestRunItem ("/default.aspx", Default_Aspx));
+                       
+                       return true;
+               }
+
+               void Default_Aspx (string result, TestRunItem runItem)
+               {
+                       string originalHtml = @"<h2>Object moved to <a href=""http://google.com/"">here</a></h2>";
+                       
+                       Assert.IsTrue (result.IndexOf (originalHtml) != -1, "#A1");
+               }
+       }
+}
+
diff --git a/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_01/default.aspx b/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_01/default.aspx
new file mode 100644 (file)
index 0000000..5f7522e
--- /dev/null
@@ -0,0 +1,17 @@
+<%@ Page Language="C#" %>
+<script runat="server">
+       void Page_Load (object sender, EventArgs e)
+       {
+               throw new InvalidOperationException ("test");
+       }
+</script>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html>
+<head runat="server">
+       <title>Default</title>
+</head>
+<body>
+       <form id="form1" runat="server">
+       </form>
+</body>
+</html>
\ No newline at end of file
diff --git a/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_01/global.asax b/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_01/global.asax
new file mode 100644 (file)
index 0000000..4bc28a6
--- /dev/null
@@ -0,0 +1 @@
+<%@ Application CodeFile="global.asax.cs" Inherits="TestWebApp.Global" %>
diff --git a/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_01/global.asax.cs b/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_01/global.asax.cs
new file mode 100644 (file)
index 0000000..5c133d2
--- /dev/null
@@ -0,0 +1,22 @@
+using System;
+using System.Collections;
+using System.ComponentModel;
+using System.Web;
+using System.Web.SessionState;
+
+namespace TestWebApp
+{
+       public partial class Global : System.Web.HttpApplication
+       {
+               protected virtual void Application_Error (Object sender, EventArgs e)
+               {
+                       HttpResponse response = Response;
+
+                       if (response != null) {
+                               string begin = (string)AppDomain.CurrentDomain.GetData ("BEGIN_CODE_MARKER");
+                               string end = (string)AppDomain.CurrentDomain.GetData ("END_CODE_MARKER");
+                               response.Write (begin + "<strong>Application error handled</strong>" + end);
+                       }
+               }
+       }
+}
diff --git a/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_01/web.config b/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_01/web.config
new file mode 100644 (file)
index 0000000..27ba12c
--- /dev/null
@@ -0,0 +1,30 @@
+<?xml version="1.0"?>
+<!--
+Web.config file for TestWebApp.
+
+The settings that can be used in this file are documented at 
+http://www.mono-project.com/Config_system.web and 
+http://msdn2.microsoft.com/en-us/library/b5ysx397.aspx
+-->
+<configuration>
+  <system.web>
+    <compilation defaultLanguage="C#" debug="true">
+      <assemblies>
+      </assemblies>
+    </compilation>
+    <customErrors mode="RemoteOnly">
+    </customErrors>
+    <authentication mode="None">
+    </authentication>
+    <authorization>
+      <allow users="*" />
+    </authorization>
+    <httpHandlers>
+    </httpHandlers>
+    <trace enabled="false" localOnly="true" pageOutput="false" requestLimit="10" traceMode="SortByTime" />
+    <sessionState mode="InProc" cookieless="false" timeout="20" />
+    <globalization requestEncoding="utf-8" responseEncoding="utf-8" />
+    <pages>
+    </pages>
+  </system.web>
+</configuration>
\ No newline at end of file
diff --git a/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_02/default.aspx b/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_02/default.aspx
new file mode 100644 (file)
index 0000000..b0be59d
--- /dev/null
@@ -0,0 +1,17 @@
+<%@ Page Language="C#" Inherits="DoesNotExist" %>
+<script runat="server">
+       void Page_Load (object sender, EventArgs e)
+       {
+               throw new InvalidOperationException ("test");
+       }
+</script>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html>
+<head runat="server">
+       <title>Default</title>
+</head>
+<body>
+       <form id="form1" runat="server">
+       </form>
+</body>
+</html>
\ No newline at end of file
diff --git a/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_02/global.asax b/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_02/global.asax
new file mode 100644 (file)
index 0000000..4bc28a6
--- /dev/null
@@ -0,0 +1 @@
+<%@ Application CodeFile="global.asax.cs" Inherits="TestWebApp.Global" %>
diff --git a/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_02/global.asax.cs b/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_02/global.asax.cs
new file mode 100644 (file)
index 0000000..9703668
--- /dev/null
@@ -0,0 +1,19 @@
+
+using System;
+using System.Collections;
+using System.ComponentModel;
+using System.Web;
+using System.Web.SessionState;
+
+namespace TestWebApp
+{
+       public partial class Global : System.Web.HttpApplication
+       {
+               protected virtual void Application_Error (Object sender, EventArgs e)
+               {
+                       Console.WriteLine (Environment.StackTrace);
+                       Console.WriteLine ("Handling apperror:");
+                       Console.WriteLine (HttpContext.Current.Error);
+               }
+       }
+}
diff --git a/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_02/web.config b/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_02/web.config
new file mode 100644 (file)
index 0000000..27ba12c
--- /dev/null
@@ -0,0 +1,30 @@
+<?xml version="1.0"?>
+<!--
+Web.config file for TestWebApp.
+
+The settings that can be used in this file are documented at 
+http://www.mono-project.com/Config_system.web and 
+http://msdn2.microsoft.com/en-us/library/b5ysx397.aspx
+-->
+<configuration>
+  <system.web>
+    <compilation defaultLanguage="C#" debug="true">
+      <assemblies>
+      </assemblies>
+    </compilation>
+    <customErrors mode="RemoteOnly">
+    </customErrors>
+    <authentication mode="None">
+    </authentication>
+    <authorization>
+      <allow users="*" />
+    </authorization>
+    <httpHandlers>
+    </httpHandlers>
+    <trace enabled="false" localOnly="true" pageOutput="false" requestLimit="10" traceMode="SortByTime" />
+    <sessionState mode="InProc" cookieless="false" timeout="20" />
+    <globalization requestEncoding="utf-8" responseEncoding="utf-8" />
+    <pages>
+    </pages>
+  </system.web>
+</configuration>
\ No newline at end of file
diff --git a/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_03/default.aspx b/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_03/default.aspx
new file mode 100644 (file)
index 0000000..5f7522e
--- /dev/null
@@ -0,0 +1,17 @@
+<%@ Page Language="C#" %>
+<script runat="server">
+       void Page_Load (object sender, EventArgs e)
+       {
+               throw new InvalidOperationException ("test");
+       }
+</script>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html>
+<head runat="server">
+       <title>Default</title>
+</head>
+<body>
+       <form id="form1" runat="server">
+       </form>
+</body>
+</html>
\ No newline at end of file
diff --git a/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_03/global.asax b/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_03/global.asax
new file mode 100644 (file)
index 0000000..4bc28a6
--- /dev/null
@@ -0,0 +1 @@
+<%@ Application CodeFile="global.asax.cs" Inherits="TestWebApp.Global" %>
diff --git a/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_03/global.asax.cs b/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_03/global.asax.cs
new file mode 100644 (file)
index 0000000..01a6f3c
--- /dev/null
@@ -0,0 +1,23 @@
+using System;
+using System.Collections;
+using System.ComponentModel;
+using System.Web;
+using System.Web.SessionState;
+
+namespace TestWebApp
+{
+       public partial class Global : System.Web.HttpApplication
+       {
+               protected virtual void Application_Error (Object sender, EventArgs e)
+               {
+                       HttpResponse response = Response;
+
+                       if (response != null) {
+                               string begin = (string)AppDomain.CurrentDomain.GetData ("BEGIN_CODE_MARKER");
+                               string end = (string)AppDomain.CurrentDomain.GetData ("END_CODE_MARKER");
+                               response.Write (begin + "<strong>Application error handled</strong>" + end);
+                       }
+                       Server.ClearError ();
+               }
+       }
+}
diff --git a/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_03/web.config b/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_03/web.config
new file mode 100644 (file)
index 0000000..27ba12c
--- /dev/null
@@ -0,0 +1,30 @@
+<?xml version="1.0"?>
+<!--
+Web.config file for TestWebApp.
+
+The settings that can be used in this file are documented at 
+http://www.mono-project.com/Config_system.web and 
+http://msdn2.microsoft.com/en-us/library/b5ysx397.aspx
+-->
+<configuration>
+  <system.web>
+    <compilation defaultLanguage="C#" debug="true">
+      <assemblies>
+      </assemblies>
+    </compilation>
+    <customErrors mode="RemoteOnly">
+    </customErrors>
+    <authentication mode="None">
+    </authentication>
+    <authorization>
+      <allow users="*" />
+    </authorization>
+    <httpHandlers>
+    </httpHandlers>
+    <trace enabled="false" localOnly="true" pageOutput="false" requestLimit="10" traceMode="SortByTime" />
+    <sessionState mode="InProc" cookieless="false" timeout="20" />
+    <globalization requestEncoding="utf-8" responseEncoding="utf-8" />
+    <pages>
+    </pages>
+  </system.web>
+</configuration>
\ No newline at end of file
diff --git a/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_04/default.aspx b/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_04/default.aspx
new file mode 100644 (file)
index 0000000..5f7522e
--- /dev/null
@@ -0,0 +1,17 @@
+<%@ Page Language="C#" %>
+<script runat="server">
+       void Page_Load (object sender, EventArgs e)
+       {
+               throw new InvalidOperationException ("test");
+       }
+</script>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html>
+<head runat="server">
+       <title>Default</title>
+</head>
+<body>
+       <form id="form1" runat="server">
+       </form>
+</body>
+</html>
\ No newline at end of file
diff --git a/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_04/global.asax b/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_04/global.asax
new file mode 100644 (file)
index 0000000..4bc28a6
--- /dev/null
@@ -0,0 +1 @@
+<%@ Application CodeFile="global.asax.cs" Inherits="TestWebApp.Global" %>
diff --git a/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_04/global.asax.cs b/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_04/global.asax.cs
new file mode 100644 (file)
index 0000000..ff8b54d
--- /dev/null
@@ -0,0 +1,16 @@
+using System;
+using System.Collections;
+using System.ComponentModel;
+using System.Web;
+using System.Web.SessionState;
+
+namespace TestWebApp
+{
+       public partial class Global : System.Web.HttpApplication
+       {
+               protected virtual void Application_Error (Object sender, EventArgs e)
+               {
+                       Response.Redirect ("http://google.com/");
+               }
+       }
+}
diff --git a/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_04/web.config b/mcs/class/System.Web/Test/standalone/Unhandled_Exception_Global_Asax/test_04/web.config
new file mode 100644 (file)
index 0000000..27ba12c
--- /dev/null
@@ -0,0 +1,30 @@
+<?xml version="1.0"?>
+<!--
+Web.config file for TestWebApp.
+
+The settings that can be used in this file are documented at 
+http://www.mono-project.com/Config_system.web and 
+http://msdn2.microsoft.com/en-us/library/b5ysx397.aspx
+-->
+<configuration>
+  <system.web>
+    <compilation defaultLanguage="C#" debug="true">
+      <assemblies>
+      </assemblies>
+    </compilation>
+    <customErrors mode="RemoteOnly">
+    </customErrors>
+    <authentication mode="None">
+    </authentication>
+    <authorization>
+      <allow users="*" />
+    </authorization>
+    <httpHandlers>
+    </httpHandlers>
+    <trace enabled="false" localOnly="true" pageOutput="false" requestLimit="10" traceMode="SortByTime" />
+    <sessionState mode="InProc" cookieless="false" timeout="20" />
+    <globalization requestEncoding="utf-8" responseEncoding="utf-8" />
+    <pages>
+    </pages>
+  </system.web>
+</configuration>
\ No newline at end of file
index cc6b0faa22c221dbbed81f916ee43b3cf154e7d7..366c0dd5810943b685507aa015dae25fca7cbdba 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * Makefile: rename the net_2_1 profile to moonlight.
+       * net_2_1_*.dll.sources: rename to moonlight_*.dll.sources.
+
 2009-11-30  Jonathan Pryor  <jpryor@novell.com>
 
        * monotouch_System.Xml.dll.sources: Add System.Xml/NamespaceHandling.cs 
index 6dd6a391add1155c4a23c643b98aeb1c048e8145..ff68bdcee1ae80717741b01cabed6212b9571190 100644 (file)
@@ -94,7 +94,7 @@ Mono.Xml.Xsl/PatternTokenizer.cs: System.Xml.XPath/Tokenizer.cs
        echo "#define XSLT_PATTERN" > $@
        cat $< >>$@
 
-ifneq (net_2_1_raw, $(PROFILE))
+ifneq (moonlight_raw, $(PROFILE))
 BUILT_SOURCES = System.Xml.XPath/Parser.cs \
        Mono.Xml.Xsl/PatternParser.cs \
        Mono.Xml.Xsl/PatternTokenizer.cs
index 39e04c5129f369acb49782441e8461348f1b9de1..09806da55435b9af1eac6131275536012925e43d 100644 (file)
@@ -1,3 +1,7 @@
+2010-04-16  Atsushi Enomoto <atsushi@ximian.com>
+
+       * XmlFilterReader.cs : implement IXmlNamespaceResolver.
+
 2009-03-02  Chris Toshok  <toshok@ximian.com>
 
        * SubtreeXmlReader.cs, XmlFilterReader.cs: 2.1 has HasValue.
index fdc1aa54f34eb8a5081287a7e91ee56db02d179a..628f4ce989cc4ec7cd49b4471dc39751c3814e86 100644 (file)
 \r
 #if NET_2_0\r
 using System;\r
+using System.Collections.Generic;\r
 using System.Xml;\r
 using System.Xml.Schema;\r
 \r
 namespace Mono.Xml\r
 {\r
-       internal class XmlFilterReader : XmlReader, IXmlLineInfo\r
+       internal class XmlFilterReader : XmlReader, IXmlLineInfo, IXmlNamespaceResolver\r
        {\r
                XmlReader reader;\r
                XmlReaderSettings settings;\r
@@ -281,6 +282,17 @@ namespace Mono.Xml
                public override bool ReadAttributeValue () {\r
                        return reader.ReadAttributeValue ();\r
                }\r
+\r
+               string IXmlNamespaceResolver.LookupPrefix (string ns)\r
+               {\r
+                       return ((IXmlNamespaceResolver) reader).LookupPrefix (ns);\r
+               }\r
+\r
+               IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope (XmlNamespaceScope scope)\r
+               {\r
+                       return ((IXmlNamespaceResolver) reader).GetNamespacesInScope (scope);\r
+               }\r
+\r
                #endregion\r
        }\r
 }\r
index c2edf583dca9db9540c7d9f1883997a44cf5a1b9..fc5f9a2936f83c8e454638f976befc81965daca6 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XmlSchemaComplexType.cs : quick fix for bug #584664. Fill base
+         content type particles in prior to filling its own.
+
 2010-02-16  Atsushi Enomoto  <atsushi@ximian.com>
 
        * XmlSchemaComplexType.cs : in modern .NET, xs:anyType has the
index 2fc6e0db289c623806230790f9ebb7c66eb19993..9ee6609a6a0dc141e06d0c3a22236ff6d2f8c270 100644 (file)
@@ -414,6 +414,14 @@ namespace System.Xml.Schema
 
                void FillContentTypeParticle (ValidationEventHandler h, XmlSchema schema)
                {
+                       if (CollectProcessId == schema.CompilationId)
+                               return;
+                       CollectProcessId = schema.CompilationId;
+
+                       var ct = BaseXmlSchemaType as XmlSchemaComplexType;
+                       if (ct != null)
+                               ct.FillContentTypeParticle (h, schema);
+
                        // {content type} => ContentType and ContentTypeParticle (later)
                        if (ContentModel != null) {
                                CollectContentTypeFromContentModel (h, schema);
@@ -423,8 +431,6 @@ namespace System.Xml.Schema
                        contentTypeParticle = validatableParticle.GetOptimizedParticle (true);
                        if (contentTypeParticle == XmlSchemaParticle.Empty && resolvedContentType == XmlSchemaContentType.ElementOnly)
                                resolvedContentType = XmlSchemaContentType.Empty;
-
-                       CollectProcessId = schema.CompilationId;
                }
 
                #region {content type}
@@ -480,7 +486,7 @@ namespace System.Xml.Schema
                        if (BaseSchemaTypeName == XmlSchemaComplexType.AnyTypeName)
                                baseComplexType = XmlSchemaComplexType.AnyType;
 
-                       // On error case, it simple reject any contents
+                       // On error case, it simply rejects any contents
                        if (baseComplexType == null) {
                                validatableParticle = XmlSchemaParticle.Empty;
                                resolvedContentType = XmlSchemaContentType.Empty;
@@ -488,6 +494,7 @@ namespace System.Xml.Schema
                        }
 
                        // 3.4.2 complex content {content type}
+                       // FIXME: this part is looking different than the spec. sections.
                        if (cce.Particle == null || cce.Particle == XmlSchemaParticle.Empty) {
                                // - 2.1
                                if (baseComplexType == null) {
index c32317932accccc1a92b8606f7e3a14d3f1dd434..6300882155a6a2ba38e14b5e3aaf03f751473d41 100644 (file)
@@ -1,3 +1,14 @@
+2010-03-29  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XmlTypeMapping.cs, XmlReflectionImporter.cs: XmlRoot takes higher
+         priority to XmlSchemaProvider QName.
+         This fixes WCF EndpointAddress serialization.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * SerializationSource.cs: use MOONLIGHT symbol to disambiguate
+       MonoTouch and Moonlight code.
+
 2010-03-10  Atsushi Enomoto  <atsushi@ximian.com>
 
        * XmlAnyElementAttribute.cs : add internal IsNullableSpecified
index 9df5c844067ff0899f522907b87c774013014a56..0ecac0ee0bc7bac7924ca4a55acc274d7fcd8cec 100644 (file)
@@ -34,7 +34,7 @@ using System.Text;
 
 namespace System.Xml.Serialization 
 {
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
        internal abstract class SerializationSource 
        {
                Type[] includedTypes;
index 00f4221d9e0fc764f924a9d4e8685adf1aeefc62..50c430a9346f0b184ec7a80f696ea8f145515c0e 100644 (file)
@@ -293,7 +293,7 @@ namespace System.Xml.Serialization {
                        XmlTypeMapping map;
                        switch (typeData.SchemaType) {
                                case SchemaTypes.XmlSerializable:
-                                       map = new XmlSerializableMapping (elementName, rootNamespace, typeData, defaultXmlType, typeNamespace);
+                                       map = new XmlSerializableMapping (root, elementName, rootNamespace, typeData, defaultXmlType, typeNamespace);
                                        break;
                                case SchemaTypes.Primitive:
                                        if (!typeData.IsXsdType)
index 703bd82c51ae267de4b247e6250e02cd8c22f8ed..5c2cd4d5ce3316c0a41254c4a326fecfed8d72e5 100644 (file)
@@ -196,7 +196,7 @@ namespace System.Xml.Serialization
                XmlQualifiedName _schemaTypeName;
 #endif
 
-               internal XmlSerializableMapping(string elementName, string ns, TypeData typeData, string xmlType, string xmlTypeNamespace)
+               internal XmlSerializableMapping(XmlRootAttribute root, string elementName, string ns, TypeData typeData, string xmlType, string xmlTypeNamespace)
                        : base(elementName, ns, typeData, xmlType, xmlTypeNamespace)
                {
 #if NET_2_0
@@ -233,7 +233,7 @@ namespace System.Xml.Serialization
                                                String.Format ("Method {0}.{1}() specified by XmlSchemaProviderAttribute has invalid signature: return type must be compatible with System.Xml.XmlQualifiedName.", typeData.Type.Name, method));
 
                                // defaultNamespace at XmlReflectionImporter takes precedence for Namespace, but not for XsdTypeNamespace.
-                               UpdateRoot (new XmlQualifiedName (_schemaTypeName.Name, Namespace ?? _schemaTypeName.Namespace));
+                               UpdateRoot (new XmlQualifiedName (root != null ? root.ElementName : _schemaTypeName.Name, root != null ? root.Namespace : Namespace ?? _schemaTypeName.Namespace));
                                XmlTypeNamespace = _schemaTypeName.Namespace;
                                XmlType = _schemaTypeName.Name;
 
index 844607641ce7c5bdd66c8f079fc92b2316dea787..04d45073ed08980ef8be0031d48e2e1c6cb0727a 100644 (file)
@@ -1,3 +1,38 @@
+2010-04-21  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XmlTextReader.cs, DTDReader.cs : 0xFFFF was treated as if it were
+         0x10000. (It is invalid and should be rejected by decent
+         XmlReaders usage though.) Fixed bug #594628.
+
+2010-03-29  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XmlQualifiedName.cs : do not reject names in no namespace.
+
+2010-03-26  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XmlReader.cs, XmlQualifiedName.cs : ReadElementContentAs() when
+         used for qname, treats non-prefixed name as in default namespace.
+
+2010-03-17  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XmlTextWriter2.cs : fix cosmetic 2.0 compatibility issue in 
+         WriteStartAttribute() which allows "" for prefixed xmlns and brings
+         incompatibility with XmlTextWriter class.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * XmlNodeReader2.cs
+       * DTDValidatingReader2.cs
+       * XmlReader.cs
+       * XmlTextReader.cs
+       * XmlWriter.cs
+       * XmlResolver.cs
+       * XmlNodeReaderImpl.cs
+       * XmlInputStream.cs
+       * XmlReaderSettings.cs
+       * XmlWriterSettings.cs:
+               Use MOONLIGHT symbol to disambiguate MonoTouch and Moonlight code.
+
 2010-02-20  Geoff Norton  <gnorton@novell.com>
 
        * XmlInputStream.cs: Disable this codepath on monotouch.  Fixes
index a918a7b6f186c28291e5b5a2ea20cd3ef41451b0..a2d1b04d56e53372dcae442bd17a939dbf1fecee 100644 (file)
@@ -1508,7 +1508,7 @@ namespace System.Xml
                private void AppendNameChar (int ch)
                {
                        CheckNameCapacity ();
-                       if (ch < Char.MaxValue)
+                       if (ch <= Char.MaxValue)
                                nameBuffer [nameLength++] = (char) ch;
                        else {
                                nameBuffer [nameLength++] = (char) (ch / 0x10000 + 0xD800 - 1);
index 65c8b19e756783316938476aa5482bc8ad08a45c..bfc183beb7d5fe7b10e0e678c7ce3ca213df04d7 100644 (file)
@@ -966,7 +966,7 @@ namespace Mono.Xml
                        }
                }
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                internal
 #else
                public
@@ -988,7 +988,7 @@ namespace Mono.Xml
                                return reader.ReadAttributeValue ();
                }
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                internal
 #else
                public
@@ -1031,7 +1031,7 @@ namespace Mono.Xml
                        get { return reader.EOF; }
                }
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                internal
 #else
                public
index 75a3f806b9859f2ddca3fd52096fbf6173e19c2a..44932ebeb40beca10c54f34e1d8876a676ed99c6 100644 (file)
@@ -361,7 +361,7 @@ namespace System.Xml
 
                static string GetStringFromBytes (byte [] bytes, int index, int count)
                {
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        char [] chars = new char [count];
                        for (int i = index; i < count; i++)
                                chars [i] = (char) bytes [i];
index ce4f47a7963e869428b41b8f33a499f6eb8c1e8a..4c58656206c0631b2efe20965c4403144beee22e 100644 (file)
@@ -126,7 +126,7 @@ namespace System.Xml
                        get { return Current.HasAttributes; }
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public override bool HasValue {
                        get { return Current.HasValue; }
                }
@@ -436,7 +436,7 @@ namespace System.Xml
                        return base.ReadString ();
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public override void ResolveEntity ()
                {
                        if (entity != null)
index 34f104346829e9707bfceb6b5a7e9d4f244ce297..35ce8963f93a13db75a87437598bbfa54d8fb84b 100644 (file)
@@ -161,7 +161,7 @@ namespace System.Xml
                        }
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public override bool HasValue {
                        get {
                                if (current == null)
@@ -816,7 +816,7 @@ namespace System.Xml
                        return base.ReadString ();
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public override void ResolveEntity ()
                {
                        throw new NotSupportedException ("Should not happen.");
index 58b962205d508b04857f4015299b8293a47478f6..e0bfd505886ea366c446a6920dac0a1667ec50b4 100644 (file)
@@ -121,20 +121,29 @@ namespace System.Xml
                        string prefix = index < 0 ? String.Empty : name.Substring (0, index);
                        string localName = index < 0 ? name : name.Substring (index + 1);
                        string ns = resolver.LookupNamespace (prefix);
-                       if (ns == null)
-                               throw new ArgumentException ("Invalid qualified name.");
+                       if (ns == null) {
+                               if (prefix.Length > 0)
+                                       throw new ArgumentException ("Invalid qualified name.");
+                               else
+                                       ns = String.Empty;
+                       }
                        return new XmlQualifiedName (localName, ns);
                }
 
                internal static XmlQualifiedName Parse (string name, XmlReader reader)
+               {
+                       return Parse (name, reader, false);
+               }
+
+               internal static XmlQualifiedName Parse (string name, XmlReader reader, bool considerDefaultNamespace)
                {
                        int index = name.IndexOf (':');
-                       if (index < 0)
+                       if (index < 0 && !considerDefaultNamespace)
                                return new XmlQualifiedName (name);
-                       string ns = reader.LookupNamespace (name.Substring (0, index));
+                       string ns = reader.LookupNamespace (index < 0 ? String.Empty : name.Substring (0, index));
                        if (ns == null)
                                throw new ArgumentException ("Invalid qualified name.");
-                       return new XmlQualifiedName (name.Substring (index + 1), ns);
+                       return new XmlQualifiedName (index < 0 ? name : name.Substring (index + 1), ns);
                }
 
                // Operators
index f100bfa800e3f8eb2109ff14929c0649ada5c6c6..bf36030b03bfda5ab3bbf73cfe37c9fd70f7e11c 100644 (file)
@@ -35,7 +35,7 @@ using System.Collections;
 using System.Diagnostics;
 using System.IO;
 using System.Text;
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 using System.Xml.Schema; // only required for NET_2_0 (SchemaInfo)
 using System.Xml.Serialization; // only required for NET_2_0 (SchemaInfo)
 using Mono.Xml.Schema; // only required for NET_2_0
@@ -186,7 +186,7 @@ namespace System.Xml
                public abstract ReadState ReadState { get; }
 
 #if NET_2_0
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public virtual IXmlSchemaInfo SchemaInfo {
                        get { return null; }
                }
@@ -414,7 +414,7 @@ namespace System.Xml
 
                private static XmlReader CreateValidatingXmlReader (XmlReader reader, XmlReaderSettings settings)
                {
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        return reader;
 #else
                        XmlValidatingReader xvr = null;
@@ -989,9 +989,9 @@ namespace System.Xml
                                        return text;
                                if (type == typeof (XmlQualifiedName)) {
                                        if (resolver != null)
-                                               return XmlQualifiedName.Parse (text, resolver);
+                                               return XmlQualifiedName.Parse (text, resolver, true);
                                        else
-                                               return XmlQualifiedName.Parse (text, this);
+                                               return XmlQualifiedName.Parse (text, this, true);
                                }
                                if (type == typeof (DateTimeOffset))
                                        return XmlConvert.ToDateTimeOffset (text);
index 4e9bb846c4b8bbc1294879dc62cb7499a353289e..444ec804691546844618bd3b0ded907058f5bb1f 100644 (file)
@@ -35,7 +35,7 @@ using System.IO;
 using System.Net;
 using System.Xml.Schema;
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 using XsValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags;
 #endif
 
@@ -53,14 +53,14 @@ namespace System.Xml
                private int linePositionOffset;
                private bool prohibitDtd;
                private XmlNameTable nameTable;
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                private XmlSchemaSet schemas;
                private bool schemasNeedsInitialization;
                private XsValidationFlags validationFlags;
                private ValidationType validationType;
 #endif
                private XmlResolver xmlResolver;
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                private DtdProcessing dtdProcessing;
                private long maxCharactersFromEntities;
                private long maxCharactersInDocument;
@@ -71,7 +71,7 @@ namespace System.Xml
                        Reset ();
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public event ValidationEventHandler ValidationEventHandler;
 #endif
 
@@ -91,7 +91,7 @@ namespace System.Xml
                        lineNumberOffset = 0;
                        linePositionOffset = 0;
                        prohibitDtd = true;
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        xmlResolver = new XmlXapResolver ();
 #else
                        schemas = null;
@@ -118,7 +118,7 @@ namespace System.Xml
                        get { return conformance; }
                        set { conformance = value; }
                }
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                public DtdProcessing DtdProcessing {
                        get { return dtdProcessing; }
                        set {
@@ -177,7 +177,7 @@ namespace System.Xml
                        set { nameTable = value; }
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public XmlSchemaSet Schemas {
                        get {
                                if (schemasNeedsInitialization) {
index 6c0829f44211120ab822ce0bfd1310ac8c8475f3..0cf9f3172593eaead0697d0b073cef54db557841 100644 (file)
@@ -38,7 +38,7 @@ namespace System.Xml
 {
        public abstract class XmlResolver
        {
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public abstract ICredentials Credentials { set; }
 #endif
 
@@ -53,7 +53,7 @@ namespace System.Xml
                        if (baseUri == null) {
                                if (relativeUri == null)
                                        throw new ArgumentNullException ("Either baseUri or relativeUri are required.");
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                                return new Uri (relativeUri, UriKind.RelativeOrAbsolute);
 #else
                                // Don't ignore such case that relativeUri is in fact absolute uri (e.g. ResolveUri (null, "http://foo.com")).
@@ -82,7 +82,7 @@ namespace System.Xml
                                .Replace ("%", "%25")
                                .Replace ("\"", "%22");
                }
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                public virtual bool SupportsType (Uri absoluteUri, Type type)
                {
                        if (absoluteUri == null)
index 106ae5a35e98e765482c0951cf47830ceba7bbf9..7c80182e12792a236a0df7c4b349596c8aa12c2d 100644 (file)
@@ -130,7 +130,7 @@ namespace System.Xml
                internal XmlTextReader (bool dummy, XmlResolver resolver, string url, XmlNodeType fragType, XmlParserContext context)
                {
                        if (resolver == null) {
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                                resolver = new XmlXapResolver ();
 #else
                                resolver = new XmlUrlResolver ();
@@ -958,7 +958,7 @@ namespace System.Xml
                // These values are never re-initialized.
                private bool namespaces = true;
                private WhitespaceHandling whitespaceHandling = WhitespaceHandling.All;
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                private XmlResolver resolver = new XmlXapResolver ();
 #else
                private XmlResolver resolver = new XmlUrlResolver ();
@@ -1580,7 +1580,7 @@ namespace System.Xml
 
                private void AppendValueChar (int ch)
                {
-                       if (ch < Char.MaxValue)
+                       if (ch <= Char.MaxValue)
                                valueBuffer.Append ((char) ch);
                        else
                                AppendSurrogatePairValueChar (ch);
@@ -1662,7 +1662,7 @@ namespace System.Xml
                                // FIXME: it might be optimized by the JIT later,
 //                             AppendValueChar (ch);
                                {
-                                       if (ch < Char.MaxValue)
+                                       if (ch <= Char.MaxValue)
                                                valueBuffer.Append ((char) ch);
                                        else
                                                AppendSurrogatePairValueChar (ch);
@@ -1983,7 +1983,7 @@ namespace System.Xml
                                        // FIXME: it might be optimized by the JIT later,
 //                                     AppendValueChar (ch);
                                        {
-                                               if (ch < Char.MaxValue)
+                                               if (ch <= Char.MaxValue)
                                                        valueBuffer.Append ((char) ch);
                                                else
                                                        AppendSurrogatePairValueChar (ch);
@@ -2376,7 +2376,7 @@ namespace System.Xml
                                // FIXME: it might be optimized by the JIT later,
 //                             AppendValueChar (ch);
                                {
-                                       if (ch < Char.MaxValue)
+                                       if (ch <= Char.MaxValue)
                                                valueBuffer.Append ((char) ch);
                                        else
                                                AppendSurrogatePairValueChar (ch);
@@ -2774,7 +2774,7 @@ namespace System.Xml
                        // AppendNameChar (ch);
                        {
                                // nameBuffer.Length is always non-0 so no need to ExpandNameCapacity () here
-                               if (ch < Char.MaxValue)
+                               if (ch <= Char.MaxValue)
                                        nameBuffer [nameLength++] = (char) ch;
                                else
                                        AppendSurrogatePairNameChar (ch);
@@ -2791,7 +2791,7 @@ namespace System.Xml
                                {
                                        if (nameLength == nameCapacity)
                                                ExpandNameCapacity ();
-                                       if (ch < Char.MaxValue)
+                                       if (ch <= Char.MaxValue)
                                                nameBuffer [nameLength++] = (char) ch;
                                        else
                                                AppendSurrogatePairNameChar (ch);
@@ -2947,7 +2947,7 @@ namespace System.Xml
                                        return i;
                                default:
                                        Advance (c);
-                                       if (c < Char.MaxValue)
+                                       if (c <= Char.MaxValue)
                                                buffer [bufIndex++] = (char) c;
                                        else {
                                                buffer [bufIndex++] = (char) ((c - 0x10000) / 0x400 + 0xD800);
index edb537a3982f1d648c730e89b92ed5d7bd57cc83..a47d0edc80b5fb13c25696cb5891d83240d5f2d2 100644 (file)
@@ -841,7 +841,7 @@ namespace Mono.Xml
                                if (prefix == "xml")
                                        namespaceUri = XmlNamespace;
                                // infer namespace URI.
-                               else if ((object) namespaceUri == null) {
+                               else if ((object) namespaceUri == null || (v2 && namespaceUri.Length == 0)) {
                                        if (isNSDecl)
                                                namespaceUri = XmlnsNamespace;
                                        else
index 4fc3c44024fe12eb765d9054e850fc99ddba8172..58fc211b86645a33dff2cf15f4f97902ecaf7a35 100644 (file)
@@ -35,17 +35,13 @@ using System;
 using System.Collections;
 using System.IO;
 using System.Text;
-#if NET_2_0 && (!NET_2_1 || MONOTOUCH)
+#if !MOONLIGHT
 using System.Xml.XPath;
 #endif
 
 namespace System.Xml
 {
-#if NET_2_0
        public abstract class XmlWriter : IDisposable
-#else
-       public abstract class XmlWriter
-#endif
        {
 #if NET_2_0
                XmlWriterSettings settings;
@@ -179,7 +175,7 @@ namespace System.Xml
                                return;
 
                        WriteStartAttribute (reader.Prefix, reader.LocalName, reader.NamespaceURI);
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        // no ReadAttributeValue() in 2.1 profile.
                        WriteString (reader.Value);
 #else
@@ -392,7 +388,7 @@ namespace System.Xml
                                WriteString (localName);
                }
 
-#if NET_2_0 && (!NET_2_1 || MONOTOUCH)
+#if !MOONLIGHT
                public virtual void WriteNode (XPathNavigator navigator, bool defattr)
                {
                        if (navigator == null)
index 90d66534fae5a1fd9f57aa28b68c1e60da8879fd..8cfb78d3e5850987010b667d71a4455b41d09a71 100644 (file)
@@ -146,7 +146,7 @@ namespace System.Xml
                        //set { outputMethod = value; }
                }
 
-#if (NET_2_1 || NET_4_0) && !MONOTOUCH
+#if MOONLIGHT || NET_4_0
                public
 #else
                internal
index 39c4dec4398601b2408b5f10cf02daa95759330d..b5a4f30dc55a0b43e106d60babdf5c5dbdb2b3fd 100644 (file)
@@ -1,3 +1,7 @@
+2010-03-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XmlSchemaValidatorTests.cs : added test for bug #584664.
+
 2010-01-27  Atsushi Enomoto  <atsushi@ximian.com>
 
        * XmlSchemaValidatorTests.cs : added test for bug #557452, by
index 853a3f4f117378a82ee4f41dcd18df76b1ff9794..e58e24c359077077d5b0215f3ac8f418cc9c587a 100644 (file)
@@ -290,6 +290,13 @@ namespace MonoTests.System.Xml
                        doc.Schemas.Add (XmlSchema.Read (XmlReader.Create (new StringReader (xsd)), null));
                        doc.Validate (null);
                }
+
+               [Test]
+               public void Bug584664 ()
+               {
+                       Validate (File.ReadAllText ("Test/XmlFiles/xsd/584664a.xml"), File.ReadAllText ("Test/XmlFiles/xsd/584664a.xsd"));
+                       Validate (File.ReadAllText ("Test/XmlFiles/xsd/584664b.xml"), File.ReadAllText ("Test/XmlFiles/xsd/584664b.xsd"));
+               }
        }
 }
 
index 2fcf86d2de394cb9f581825001296c2a8aed1061..a38db95d1b9e9be6cbc8f340ee91b2416f5db5e7 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-29  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XmlSerializerTests.cs : test for XmlRoot and XmlSchemaProvider
+         QName conflict case.
+
 2010-01-26  Atsushi Enomoto  <atsushi@ximian.com>
 
        * XmlSerializerTests.cs : added test for bug #553032.
index 2fd5597998de9faa6e106f600a169edf83fca4db..8061423ee01e46a1651e37751b8b2caed410b81c 100644 (file)
@@ -2844,6 +2844,19 @@ namespace MonoTests.System.XmlSerialization
                {
                        new XmlSerializer (typeof (XmlAnyElementForObjectsType)).Serialize (TextWriter.Null, new XmlAnyElementForObjectsType ());
                }
+
+               [Test]
+               public void XmlRootOverridesSchemaProviderQName ()
+               {
+                       var obj = new XmlRootOverridesSchemaProviderQNameType ();
+
+                       XmlSerializer xs = new XmlSerializer (obj.GetType ());
+
+                       var sw = new StringWriter ();
+                       using (XmlWriter xw = XmlWriter.Create (sw))
+                               xs.Serialize (xw, obj);
+                       Assert.IsTrue (sw.ToString ().IndexOf ("foo") > 0, "#1");
+               }
 #endif
 
                #endregion //GenericsSeralizationTests
@@ -3002,6 +3015,33 @@ namespace MonoTests.System.XmlSerialization
                        [XmlAnyElement]
                        public object [] arr = new object [] {3,4,5};
                }
+
+               [XmlRoot ("foo")]
+               [XmlSchemaProvider ("GetSchema")]
+               public class XmlRootOverridesSchemaProviderQNameType : IXmlSerializable
+               {
+                       public static XmlQualifiedName GetSchema (XmlSchemaSet xss)
+                       {
+                               var xs = new XmlSchema ();
+                               var xse = new XmlSchemaComplexType () { Name = "bar" };
+                               xs.Items.Add (xse);
+                               xss.Add (xs);
+                               return new XmlQualifiedName ("bar");
+                       }
+
+                       XmlSchema IXmlSerializable.GetSchema ()
+                       {
+                               return null;
+                       }
+
+                       void IXmlSerializable.ReadXml (XmlReader reader)
+                       {
+                       }
+                       void IXmlSerializable.WriteXml (XmlWriter writer)
+                       {
+                       }
+               }
+
 #endif
 
                void CDataTextNodes_BadNode (object s, XmlNodeEventArgs e)
index f4ea90a545dee2e3246595c63c37ef712279feae..6582a26e1e85d59e718539960fb32169387e91c3 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-26  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XmlReaderCommonTests.cs : added test for ReadElementContentAs() for
+         qname, with default namespace.
+
 2010-01-28  Atsushi Enomoto  <atsushi@ximian.com>
 
        * XmlReaderCommonTests.cs : added test for bug #543332.
index 7495ebaee1d6fd54641796c0ab15219a8c4f5f7c..1f6ee9bb39a8fc5c061b77b491600d4c0cd7290b 100644 (file)
@@ -2203,6 +2203,21 @@ namespace MonoTests.System.Xml
                        Assert.AreEqual (0, bytesRead, "#3");\r
                        Assert.AreEqual (XmlNodeType.EndElement, reader.NodeType, "#4");\r
                }\r
+\r
+               [Test]\r
+               public void ReadElementContentAsQNameDefaultNS ()\r
+               {\r
+                       var sw = new StringWriter ();\r
+                       var xw = XmlWriter.Create (sw);\r
+                       xw.WriteStartElement ("", "foo", "urn:foo");\r
+                       xw.WriteValue (new XmlQualifiedName ("x", "urn:foo"));\r
+                       xw.WriteEndElement ();\r
+                       xw.Close ();\r
+                       var xr = XmlReader.Create (new StringReader (sw.ToString ()));\r
+                       xr.MoveToContent ();\r
+                       var q = (XmlQualifiedName) xr.ReadElementContentAs (typeof (XmlQualifiedName), xr as IXmlNamespaceResolver);\r
+                       Assert.AreEqual ("urn:foo", q.Namespace, "#1");\r
+               }\r
 #endif\r
        }\r
 }\r
diff --git a/mcs/class/System.XML/Test/XmlFiles/xsd/584664a.xml b/mcs/class/System.XML/Test/XmlFiles/xsd/584664a.xml
new file mode 100644 (file)
index 0000000..50db974
--- /dev/null
@@ -0,0 +1,4 @@
+<?xml version="1.0"?>
+<root xmlns="http://a">
+  <leaf/>
+</root>
\ No newline at end of file
diff --git a/mcs/class/System.XML/Test/XmlFiles/xsd/584664a.xsd b/mcs/class/System.XML/Test/XmlFiles/xsd/584664a.xsd
new file mode 100644 (file)
index 0000000..7260c0c
--- /dev/null
@@ -0,0 +1,19 @@
+<?xml version="1.0"?>
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://a" xmlns="http://a" elementFormDefault="qualified" attributeFormDefault="unqualified">
+
+<xs:complexType name="base">
+  <xs:sequence>
+    <xs:element name="leaf" type="xs:string"/>
+    <xs:element name="nested" type="derived" minOccurs="0" maxOccurs="unbounded"/>
+  </xs:sequence>
+</xs:complexType>
+
+<xs:complexType name="derived">
+  <xs:complexContent>
+    <xs:extension base="base"/>
+  </xs:complexContent>
+</xs:complexType>
+
+<xs:element name="root" type="derived"/>
+
+</xs:schema>
diff --git a/mcs/class/System.XML/Test/XmlFiles/xsd/584664b.xml b/mcs/class/System.XML/Test/XmlFiles/xsd/584664b.xml
new file mode 100644 (file)
index 0000000..58c5907
--- /dev/null
@@ -0,0 +1,4 @@
+<?xml version="1.0"?>
+<root xmlns="http://b">
+  <leaf/>
+</root>
\ No newline at end of file
diff --git a/mcs/class/System.XML/Test/XmlFiles/xsd/584664b.xsd b/mcs/class/System.XML/Test/XmlFiles/xsd/584664b.xsd
new file mode 100644 (file)
index 0000000..da5e5ca
--- /dev/null
@@ -0,0 +1,18 @@
+<?xml version="1.0"?>
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://b" xmlns="http://b" elementFormDefault="qualified" attributeFormDefault="unqualified">
+
+<xs:complexType name="base">
+  <xs:sequence>
+    <xs:element name="leaf" type="xs:string"/>
+  </xs:sequence>
+</xs:complexType>
+
+<xs:complexType name="derived">
+  <xs:complexContent>
+    <xs:extension base="base"/>
+  </xs:complexContent>
+</xs:complexType>
+
+<xs:element name="root" type="derived"/>
+
+</xs:schema>
\ No newline at end of file
index 64bdb6c1fa629c35fad58f1ea97c31ccdd8b21dd..1ee824d36c558d742b32aa1c53793746151d25b1 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * 584664b.xsd, 584664a.xml, 584664b.xml, 584664a.xsd: new test files
+         by Florian Haag.
+
 2009-05-21  Gert Driesen  <drieseng@users.sourceforge.net>
 
        * extension-attr-redefine-*.xsd: new test files.
diff --git a/mcs/class/System.XML/moonlight_raw_System.Xml.dll.sources b/mcs/class/System.XML/moonlight_raw_System.Xml.dll.sources
new file mode 100644 (file)
index 0000000..867f13f
--- /dev/null
@@ -0,0 +1,70 @@
+Assembly/AssemblyInfo.cs
+Mono.Xml/IHasXmlParserContext.cs
+Mono.Xml/SubtreeXmlReader.cs
+Mono.Xml/XmlFilterReader.cs
+System.Xml.Schema/XmlSeverityType.cs
+System.Xml.Schema/XmlSchemaForm.cs
+System.Xml.Schema/XmlTypeCode.cs
+System.Xml/ConformanceLevel.cs
+System.Xml/DtdProcessing.cs
+System.Xml/DTDAutomata.cs
+System.Xml/DTDObjectModel.cs
+System.Xml/DTDReader.cs
+System.Xml/EntityHandling.cs
+System.Xml/EntityResolvingXmlReader.cs
+System.Xml/Formatting.cs
+System.Xml/IXmlLineInfo.cs
+System.Xml/IXmlNamespaceResolver.cs
+System.Xml/NamespaceHandling.cs
+System.Xml/NameTable.cs
+System.Xml/NewLineHandling.cs
+System.Xml/ReadState.cs
+System.Xml/WhitespaceHandling.cs
+System.Xml/WriteState.cs
+System.Xml/XQueryConvert.cs
+System.Xml/XmlChar.cs
+System.Xml/XmlConvert.cs
+System.Xml/XmlDateTimeSerializationMode.cs
+System.Xml/XmlException.cs
+System.Xml/XmlInputStream.cs
+System.Xml/XmlNameTable.cs
+System.Xml/XmlNamespaceManager.cs
+System.Xml/XmlNamespaceScope.cs
+System.Xml/XmlNodeType.cs
+System.Xml/XmlOutputMethod.cs
+System.Xml/XmlParserContext.cs
+System.Xml/XmlParserInput.cs
+System.Xml/XmlQualifiedName.cs
+System.Xml/XmlReader.cs
+System.Xml/XmlReaderBinarySupport.cs
+System.Xml/XmlReaderSettings.cs
+System.Xml/XmlResolver.cs
+System.Xml/XmlSpace.cs
+System.Xml/XmlTextReader.cs
+System.Xml/XmlTextReader2.cs
+System.Xml/XmlTextWriter2.cs
+System.Xml/XmlTokenizedType.cs
+System.Xml/XmlWriter.cs
+System.Xml/XmlWriterSettings.cs
+System.Xml/XmlXapResolver.cs
+System.Xml.Schema/XmlSchemaDatatype_2_1.cs
+System.Xml.Schema/XmlSchema_2_1.cs
+System.Xml.Schema/XmlSchemaObject_2_1.cs
+System.Xml.Schema/XmlSchemaSet_2_1.cs
+System.Xml.Serialization/IXmlSerializable.cs
+System.Xml.Serialization/KeyHelper.cs
+System.Xml.Serialization/SerializationSource.cs
+System.Xml.Serialization/XmlAnyElementAttribute.cs
+System.Xml.Serialization/XmlArrayAttribute.cs
+System.Xml.Serialization/XmlArrayItemAttribute.cs
+System.Xml.Serialization/XmlAttributeAttribute.cs
+System.Xml.Serialization/XmlChoiceIdentifierAttribute.cs
+System.Xml.Serialization/XmlElementAttribute.cs
+System.Xml.Serialization/XmlEnumAttribute.cs
+System.Xml.Serialization/XmlIgnoreAttribute.cs
+System.Xml.Serialization/XmlIncludeAttribute.cs
+System.Xml.Serialization/XmlNamespaceDeclarationsAttribute.cs
+System.Xml.Serialization/XmlRootAttribute.cs
+System.Xml.Serialization/XmlSchemaProviderAttribute.cs
+System.Xml.Serialization/XmlTextAttribute.cs
+System.Xml.Serialization/XmlTypeAttribute.cs
diff --git a/mcs/class/System.XML/net_2_1_raw_System.Xml.dll.sources b/mcs/class/System.XML/net_2_1_raw_System.Xml.dll.sources
deleted file mode 100644 (file)
index 867f13f..0000000
+++ /dev/null
@@ -1,70 +0,0 @@
-Assembly/AssemblyInfo.cs
-Mono.Xml/IHasXmlParserContext.cs
-Mono.Xml/SubtreeXmlReader.cs
-Mono.Xml/XmlFilterReader.cs
-System.Xml.Schema/XmlSeverityType.cs
-System.Xml.Schema/XmlSchemaForm.cs
-System.Xml.Schema/XmlTypeCode.cs
-System.Xml/ConformanceLevel.cs
-System.Xml/DtdProcessing.cs
-System.Xml/DTDAutomata.cs
-System.Xml/DTDObjectModel.cs
-System.Xml/DTDReader.cs
-System.Xml/EntityHandling.cs
-System.Xml/EntityResolvingXmlReader.cs
-System.Xml/Formatting.cs
-System.Xml/IXmlLineInfo.cs
-System.Xml/IXmlNamespaceResolver.cs
-System.Xml/NamespaceHandling.cs
-System.Xml/NameTable.cs
-System.Xml/NewLineHandling.cs
-System.Xml/ReadState.cs
-System.Xml/WhitespaceHandling.cs
-System.Xml/WriteState.cs
-System.Xml/XQueryConvert.cs
-System.Xml/XmlChar.cs
-System.Xml/XmlConvert.cs
-System.Xml/XmlDateTimeSerializationMode.cs
-System.Xml/XmlException.cs
-System.Xml/XmlInputStream.cs
-System.Xml/XmlNameTable.cs
-System.Xml/XmlNamespaceManager.cs
-System.Xml/XmlNamespaceScope.cs
-System.Xml/XmlNodeType.cs
-System.Xml/XmlOutputMethod.cs
-System.Xml/XmlParserContext.cs
-System.Xml/XmlParserInput.cs
-System.Xml/XmlQualifiedName.cs
-System.Xml/XmlReader.cs
-System.Xml/XmlReaderBinarySupport.cs
-System.Xml/XmlReaderSettings.cs
-System.Xml/XmlResolver.cs
-System.Xml/XmlSpace.cs
-System.Xml/XmlTextReader.cs
-System.Xml/XmlTextReader2.cs
-System.Xml/XmlTextWriter2.cs
-System.Xml/XmlTokenizedType.cs
-System.Xml/XmlWriter.cs
-System.Xml/XmlWriterSettings.cs
-System.Xml/XmlXapResolver.cs
-System.Xml.Schema/XmlSchemaDatatype_2_1.cs
-System.Xml.Schema/XmlSchema_2_1.cs
-System.Xml.Schema/XmlSchemaObject_2_1.cs
-System.Xml.Schema/XmlSchemaSet_2_1.cs
-System.Xml.Serialization/IXmlSerializable.cs
-System.Xml.Serialization/KeyHelper.cs
-System.Xml.Serialization/SerializationSource.cs
-System.Xml.Serialization/XmlAnyElementAttribute.cs
-System.Xml.Serialization/XmlArrayAttribute.cs
-System.Xml.Serialization/XmlArrayItemAttribute.cs
-System.Xml.Serialization/XmlAttributeAttribute.cs
-System.Xml.Serialization/XmlChoiceIdentifierAttribute.cs
-System.Xml.Serialization/XmlElementAttribute.cs
-System.Xml.Serialization/XmlEnumAttribute.cs
-System.Xml.Serialization/XmlIgnoreAttribute.cs
-System.Xml.Serialization/XmlIncludeAttribute.cs
-System.Xml.Serialization/XmlNamespaceDeclarationsAttribute.cs
-System.Xml.Serialization/XmlRootAttribute.cs
-System.Xml.Serialization/XmlSchemaProviderAttribute.cs
-System.Xml.Serialization/XmlTextAttribute.cs
-System.Xml.Serialization/XmlTypeAttribute.cs
diff --git a/mcs/class/System.Xaml/Assembly/AssemblyInfo.cs b/mcs/class/System.Xaml/Assembly/AssemblyInfo.cs
new file mode 100644 (file)
index 0000000..5f375c5
--- /dev/null
@@ -0,0 +1,72 @@
+//
+// AssemblyInfo.cs
+//
+// Author:
+//   Andreas Nahr (ClassDevelopment@A-SoftTech.com)
+//
+// (C) 2003 Ximian, Inc.  http://www.ximian.com
+//
+
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Reflection;
+using System.Resources;
+using System.Security;
+using System.Security.Permissions;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about the System.Xaml assembly
+// v3.0 Assembly
+
+[assembly: AssemblyTitle ("System.Xaml.dll")]
+[assembly: AssemblyDescription ("System.Xaml.dll")]
+[assembly: AssemblyDefaultAlias ("System.Xaml.dll")]
+
+[assembly: AssemblyCompany (Consts.MonoCompany)]
+[assembly: AssemblyProduct (Consts.MonoProduct)]
+[assembly: AssemblyCopyright (Consts.MonoCopyright)]
+[assembly: AssemblyVersion (Consts.FxVersion)]
+[assembly: SatelliteContractVersion (Consts.FxVersion)]
+[assembly: AssemblyInformationalVersion (Consts.FxFileVersion)]
+[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
+
+[assembly: NeutralResourcesLanguage ("en-US")]
+[assembly: CLSCompliant (true)]
+[assembly: AssemblyDelaySign (true)]
+#if NET_2_1
+[assembly: AssemblyKeyFile ("../silverlight.pub")]
+#else
+[assembly: AssemblyKeyFile ("../ecma.pub")]
+[assembly: AllowPartiallyTrustedCallers]
+[assembly: ComCompatibleVersion (1, 0, 3300, 0)]
+[assembly: Debuggable (DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
+[assembly: SecurityCritical (SecurityCriticalScope.Explicit)]
+#endif
+
+[assembly: ComVisible (false)]
+
+[assembly: CompilationRelaxations (CompilationRelaxations.NoStringInterning)]
+[assembly: RuntimeCompatibility (WrapNonExceptionThrows = true)]
+[assembly: SecurityPermission (SecurityAction.RequestMinimum, SkipVerification = true)]
diff --git a/mcs/class/System.Xaml/Assembly/ChangeLog b/mcs/class/System.Xaml/Assembly/ChangeLog
new file mode 100644 (file)
index 0000000..bea57bc
--- /dev/null
@@ -0,0 +1,3 @@
+2010-04-08  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * AssemblyInfo.cs : initial checkin.
diff --git a/mcs/class/System.Xaml/ChangeLog b/mcs/class/System.Xaml/ChangeLog
new file mode 100644 (file)
index 0000000..bbd519f
--- /dev/null
@@ -0,0 +1,68 @@
+2010-04-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * System.Xaml_test.dll.sources : add XDataTest.cs.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * System.Xaml_test.dll.sources : add XamlTypeNameTest.cs.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * System.Xaml_test.dll.sources : add XamlXmlReaderTest.cs.
+       * Makefile: added test files as EXTRA_DISTFILES.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * System.Xaml_test.dll.sources : add ValueSerializerTest.cs.
+
+2010-04-13  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * System.Xaml_test.dll.sources : add XamlObjectWriterTest.cs.
+
+2010-04-12  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * System.Xaml.dll.sources : add new internal type.
+
+2010-04-11  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * System.Xaml_test.dll.sources : add XamlObjectReaderTest.cs.
+
+2010-04-10  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * System.Xaml_test.dll.sources : add XamlXmlWriterTest.cs.
+
+2010-04-09  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * System.Xaml.dll.sources : add new internal types.
+
+2010-04-09  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * System.Xaml_test.dll.sources : add more tests.
+
+2010-04-09  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * System.Xaml_test.dll.sources : add more tests.
+
+2010-04-09  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * System.Xaml.dll.sources : renamed TypeExtension.cs.
+
+2010-04-09  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * System.Xaml_test.dll.sources : add XamlLanguageTest.cs.
+
+2010-04-09  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * System.Xaml.dll.sources
+         System.Xaml_test.dll.sources : more new types.
+
+2010-04-08  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * System.Xaml.dll.sources
+         System.Xaml_test.dll.sources : add a lot of new types.
+
+2010-04-08  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * Makefile
+         System.Xaml.dll.sources
+         System.Xaml_test.dll.sources : initial checkin.
diff --git a/mcs/class/System.Xaml/Makefile b/mcs/class/System.Xaml/Makefile
new file mode 100644 (file)
index 0000000..2d19490
--- /dev/null
@@ -0,0 +1,32 @@
+thisdir = class/System.Xaml
+SUBDIRS = 
+include ../../build/rules.make
+
+RESOURCE_FILES = 
+
+LIBRARY = System.Xaml.dll
+LIB_MCS_FLAGS = \
+               /r:System.dll \
+               /r:System.Xml.dll \
+               /r:System.Core.dll \
+               $(RESOURCE_FILES:%=/resource:%)
+
+ifneq (2.1, $(FRAMEWORK_VERSION))
+LIB_MCS_FLAGS += /r:System.Configuration.dll
+endif
+
+TEST_MCS_FLAGS = $(LIB_MCS_FLAGS)
+
+EXTRA_DISTFILES = $(RESOURCE_FILES) $(TEST_EXTRA_DISTFILES)
+TEST_EXTRA_DISTFILES = \
+       Test/XmlFiles/*.xml
+
+VALID_PROFILE := $(filter 4.0, $(FRAMEWORK_VERSION))
+ifndef VALID_PROFILE
+LIBRARY_NAME = dummy-System.Xaml.dll
+NO_INSTALL = yes
+NO_SIGN_ASSEMBLY = yes
+NO_TEST = yes
+endif
+
+include ../../build/library.make
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/AmbientAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/AmbientAttribute.cs
new file mode 100755 (executable)
index 0000000..003f0c7
--- /dev/null
@@ -0,0 +1,38 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsage (AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property, Inherited = true)]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public sealed class AmbientAttribute : Attribute
+       {
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/ArrayExtension.cs b/mcs/class/System.Xaml/System.Windows.Markup/ArrayExtension.cs
new file mode 100755 (executable)
index 0000000..7b1a929
--- /dev/null
@@ -0,0 +1,99 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [MarkupExtensionReturnType (typeof (Array))]
+       [ContentProperty ("Items")]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyPresentationFramework_3_5)]
+       public class ArrayExtension : MarkupExtension
+       {
+               public ArrayExtension ()
+               {
+                       Items = new List<object> ();
+               }
+
+               public ArrayExtension (Array elements)
+               {
+                       if (elements == null)
+                               throw new ArgumentNullException ("elements");
+                       Type = elements.GetType ().GetElementType ();
+                       Items = new List<object> (elements.Length);
+                       foreach (var o in elements)
+                               Items.Add (o);
+               }
+
+               public ArrayExtension (Type arrayType)
+               {
+                       if (arrayType == null)
+                               throw new ArgumentNullException ("arrayType");
+                       Type = arrayType;
+                       Items = new List<object> ();
+               }
+
+               public IList Items { get; private set; }
+
+               [ConstructorArgument ("arrayType")]
+               public Type Type { get; set; }
+
+               public void AddChild (Object value)
+               {
+                       // null is allowed.
+                       Items.Add (value);
+               }
+               
+               public void AddText (string text)
+               {
+                       // null is allowed.
+                       Items.Add (text);
+               }
+               
+               public override object ProvideValue (IServiceProvider serviceProvider)
+               {
+                       if (Type == null)
+                               throw new InvalidOperationException ("Type property must be set before calling ProvideValue method");
+
+                       bool invalid = false;
+                       foreach (var item in Items) {
+                               if (item == null) {
+                                       if (Type.IsValueType)
+                                               invalid = true;
+                               }
+                               else if (!Type.IsAssignableFrom (item.GetType ()))
+                                       invalid = true;
+                               if (invalid)
+                                       throw new InvalidOperationException (String.Format ("Item in the array must be an instance of '{0}'", Type));
+                       }
+                       Array a = Array.CreateInstance (Type, Items.Count);
+                       Items.CopyTo (a, 0);
+                       return a;
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/ChangeLog b/mcs/class/System.Xaml/System.Windows.Markup/ChangeLog
new file mode 100644 (file)
index 0000000..510a2b8
--- /dev/null
@@ -0,0 +1,137 @@
+2010-04-22  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReader.cs, TypeExtensionMethods.cs : now it can return
+         Type name correctly, with INamespacePrefixLookup implementation.
+
+2010-04-20  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ArrayExtension.cs : remove MonoTODO.
+
+2010-04-16  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * DateTimeValueSerializer.cs, NameReferenceConverter.cs :
+         implement.
+
+2010-04-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XmlnsCompatibleWithAttribute.cs
+         IComponentConnector.cs
+         XmlLangPropertyAttribute.cs
+         XamlSetMarkupExtensionEventArgs.cs
+         PropertyDefinition.cs
+         XmlnsDefinitionAttribute.cs
+         XmlnsPrefixAttribute.cs : another corcompare fix.
+
+2010-04-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XData.cs : actual implementation.
+
+2010-04-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ArrayExtension.cs
+         TrimSurroundingWhitespaceAttribute.cs
+         RuntimeNamePropertyAttribute.cs
+         TypeExtension.cs
+         MarkupExtensionReturnTypeAttribute.cs
+         DateTimeValueSerializer.cs
+         IValueSerializerContext.cs
+         RootNamespaceAttribute.cs
+         MarkupExtension.cs
+         Reference.cs
+         AmbientAttribute.cs
+         NameScopePropertyAttribute.cs
+         ValueSerializer.cs
+         DictionaryKeyPropertyAttribute.cs
+         WhitespaceSignificantCollectionAttribute.cs
+         ConstructorArgumentAttribute.cs
+         IUriContext.cs
+         INameScope.cs
+         StaticExtension.cs
+         IProvideValueTarget.cs
+         ValueSerializerAttribute.cs
+         IXamlTypeResolver.cs
+         ContentWrapperAttribute.cs
+         ContentPropertyAttribute.cs
+         DependsOnAttribute.cs
+         NullExtension.cs
+         UidPropertyAttribute.cs : several corcompare fixes.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * TypeExtensionConverter.cs : implement.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ValueSerializer.cs : implement most of them.
+
+2010-04-12  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * TypeExtension.cs, StaticExtension.cs : add [TypeConverter].
+
+2010-04-09  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * StaticExtensionConverter.cs, TypeExtensionConverter.cs :
+         new internal converter types (almost dummy yet).
+
+2010-04-09  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ArrayExtension.cs
+         TypeExtension.cs
+         StaticExtension.cs
+         PropertyDefinition.cs : implemented.
+
+2010-04-09  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ArrayExtension.cs, TypeExtension.cs : add missing members.
+
+2010-04-08  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ValueSerializer.cs : add missing members.
+       * AmbientAttribute.cs
+         ArrayExtension.cs
+         ConstructorArgumentAttribute.cs
+         ContentPropertyAttribute.cs
+         ContentWrapperAttribute.cs
+         DateTimeValueSerializer.cs
+         DependsOnAttribute.cs
+         DictionaryKeyPropertyAttribute.cs
+         IComponentConnector.cs
+         INameScopeDictionary.cs
+         IProvideValueTarget.cs
+         IQueryAmbient.cs
+         IUriContext.cs
+         IXamlTypeResolver.cs
+         MarkupExtensionReturnTypeAttribute.cs
+         MemberDefinition.cs
+         NameReferenceConverter.cs
+         NameScopePropertyAttribute.cs
+         NullExtension.cs
+         PropertyDefinition.cs
+         Reference.cs
+         RootNamespaceAttribute.cs
+         RuntimeNamePropertyAttribute.cs
+         StaticExtension.cs
+         TrimSurroundingWhitespaceAttribute.cs
+         TypeExtension.cs
+         UidPropertyAttribute.cs
+         UsableDuringInitializationAttribute.cs
+         ValueSerializerAttribute.cs
+         WhitespaceSignificantCollectionAttribute.cs
+         XData.cs
+         XamlDeferLoadAttribute.cs
+         XamlSetMarkupExtensionAttribute.cs
+         XamlSetTypeConverterAttribute.cs
+         XmlLangPropertyAttribute.cs
+         XmlnsCompatibleWithAttribute.cs
+         XmlnsDefinitionAttribute.cs
+         XmlnsPrefixAttribute.cs : new types.
+
+2010-04-08  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ValueSerializer.cs
+         INameScope.cs
+         XamlSetMarkupExtensionEventArgs.cs
+         IValueSerializerContext.cs
+         XamlSetTypeConverterEventArgs.cs
+         MarkupExtension.cs
+         XamlSetValueEventArgs.cs : initial checkin (incomplete here).
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/ConstructorArgumentAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/ConstructorArgumentAttribute.cs
new file mode 100755 (executable)
index 0000000..7708fe7
--- /dev/null
@@ -0,0 +1,38 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsage (AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public sealed class ConstructorArgumentAttribute : Attribute
+       {
+               public ConstructorArgumentAttribute (string argumentName)
+               {
+                       ArgumentName = argumentName;
+               }
+               
+               public string ArgumentName { get; private set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/ContentPropertyAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/ContentPropertyAttribute.cs
new file mode 100755 (executable)
index 0000000..e07000b
--- /dev/null
@@ -0,0 +1,42 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsage (AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public sealed class ContentPropertyAttribute : Attribute
+       {
+               public ContentPropertyAttribute ()
+               {
+               }
+
+               public ContentPropertyAttribute (string name)
+               {
+                       Name = name;
+               }
+               
+               public string Name { get; private set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/ContentWrapperAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/ContentWrapperAttribute.cs
new file mode 100755 (executable)
index 0000000..0407a18
--- /dev/null
@@ -0,0 +1,54 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsage (AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public sealed class ContentWrapperAttribute : Attribute
+       {
+               public ContentWrapperAttribute (Type contentWrapper)
+               {
+                       ContentWrapper = contentWrapper;
+               }
+               
+               public Type ContentWrapper { get; private set; }
+               public override Object TypeId {
+                       get { return ContentWrapper; }
+               }
+
+               public override bool Equals (object other)
+               {
+                       var cwa = other as ContentWrapperAttribute;
+                       if (cwa == null)
+                               return false;
+                       return ContentWrapper != null ? ContentWrapper == cwa.ContentWrapper : cwa.ContentWrapper == null;
+               }
+
+               public override int GetHashCode ()
+               {
+                       return ContentWrapper != null ? ContentWrapper.GetHashCode () : 0;
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/DateTimeValueSerializer.cs b/mcs/class/System.Xaml/System.Windows.Markup/DateTimeValueSerializer.cs
new file mode 100755 (executable)
index 0000000..720a351
--- /dev/null
@@ -0,0 +1,70 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Globalization;
+
+namespace System.Windows.Markup
+{
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public class DateTimeValueSerializer : ValueSerializer
+       {
+               const DateTimeStyles styles = DateTimeStyles.RoundtripKind | DateTimeStyles.NoCurrentDateDefault | DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite;
+
+               public override bool CanConvertFromString (string value, IValueSerializerContext context)
+               {
+                       return true; // documented
+               }
+
+               public override bool CanConvertToString (object value, IValueSerializerContext context)
+               {
+                       return value is DateTime;
+               }
+
+               public override object ConvertFromString (string value, IValueSerializerContext context)
+               {
+                       if (value == null)
+                               throw new NotSupportedException ();
+                       if (value.Length == 0)
+                               return DateTime.MinValue;
+                       return DateTime.Parse (value, CultureInfo.InvariantCulture, styles);
+               }
+
+               public override string ConvertToString (object value,     IValueSerializerContext context)
+               {
+                       if (!(value is DateTime))
+                               throw new NotSupportedException ();
+                       DateTime dt = (DateTime) value;
+                       if (dt.Millisecond != 0)
+                               return dt.ToString ("yyyy-MM-dd'T'HH:mm:ss.F");
+                       if (dt.Second != 0)
+                               return dt.ToString ("yyyy-MM-dd'T'HH:mm:ss");
+                       if (dt.Minute != 0)
+                               return dt.ToString ("yyyy-MM-dd'T'HH:mm");
+                       else
+                               return dt.ToString ("yyyy-MM-dd");
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/DependsOnAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/DependsOnAttribute.cs
new file mode 100755 (executable)
index 0000000..0ae0fa7
--- /dev/null
@@ -0,0 +1,43 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsage (AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public sealed class DependsOnAttribute : Attribute
+       {
+               public DependsOnAttribute (string name)
+               {
+                       Name = name;
+               }
+               
+               public string Name { get; private set; }
+
+               // really? I doubt it should be overriden.
+               public override Object TypeId {
+                       get { return base.TypeId; }
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/DictionaryKeyPropertyAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/DictionaryKeyPropertyAttribute.cs
new file mode 100755 (executable)
index 0000000..1664fe2
--- /dev/null
@@ -0,0 +1,38 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsageAttribute(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public sealed class DictionaryKeyPropertyAttribute : Attribute
+       {
+               public DictionaryKeyPropertyAttribute (string name)
+               {
+                       Name = name;
+               }
+               
+               public string Name { get; private set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/IComponentConnector.cs b/mcs/class/System.Xaml/System.Windows.Markup/IComponentConnector.cs
new file mode 100755 (executable)
index 0000000..5e60816
--- /dev/null
@@ -0,0 +1,37 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public interface IComponentConnector
+       {
+               void Connect (int connectionId, object target);
+               void InitializeComponent ();
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/INameScope.cs b/mcs/class/System.Xaml/System.Windows.Markup/INameScope.cs
new file mode 100644 (file)
index 0000000..3035a7c
--- /dev/null
@@ -0,0 +1,35 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Windows.Markup
+{
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public interface INameScope
+       {
+               object FindName (string name);
+               void RegisterName (string name, object scopedElement);
+               void UnregisterName (string name);
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/INameScopeDictionary.cs b/mcs/class/System.Xaml/System.Windows.Markup/INameScopeDictionary.cs
new file mode 100755 (executable)
index 0000000..77240d6
--- /dev/null
@@ -0,0 +1,32 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace System.Windows.Markup
+{
+       public interface INameScopeDictionary : INameScope, IDictionary<string, object>, ICollection<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable
+       {
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/IProvideValueTarget.cs b/mcs/class/System.Xaml/System.Windows.Markup/IProvideValueTarget.cs
new file mode 100755 (executable)
index 0000000..6a44ce0
--- /dev/null
@@ -0,0 +1,37 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyPresentationFramework_3_5)]
+       public interface IProvideValueTarget
+       {
+               object TargetObject { get; }
+               object TargetProperty { get; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/IQueryAmbient.cs b/mcs/class/System.Xaml/System.Windows.Markup/IQueryAmbient.cs
new file mode 100755 (executable)
index 0000000..7ea16bd
--- /dev/null
@@ -0,0 +1,35 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       public interface IQueryAmbient
+       {
+               bool IsAmbientPropertyAvailable (string propertyName);
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/IUriContext.cs b/mcs/class/System.Xaml/System.Windows.Markup/IUriContext.cs
new file mode 100755 (executable)
index 0000000..252ab69
--- /dev/null
@@ -0,0 +1,36 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyPresentationCore_3_5)]
+       public interface IUriContext
+       {
+               Uri BaseUri { get; set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/IValueSerializerContext.cs b/mcs/class/System.Xaml/System.Windows.Markup/IValueSerializerContext.cs
new file mode 100644 (file)
index 0000000..bfc1e0a
--- /dev/null
@@ -0,0 +1,38 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Xaml;
+
+namespace System.Windows.Markup
+{
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public interface IValueSerializerContext : ITypeDescriptorContext, IServiceProvider
+       {
+               ValueSerializer GetValueSerializerFor (PropertyDescriptor descriptor);
+               ValueSerializer GetValueSerializerFor (Type type);
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/IXamlTypeResolver.cs b/mcs/class/System.Xaml/System.Windows.Markup/IXamlTypeResolver.cs
new file mode 100755 (executable)
index 0000000..563387c
--- /dev/null
@@ -0,0 +1,36 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public interface IXamlTypeResolver
+       {
+               Type Resolve (string qualifiedTypeName);
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/MarkupExtension.cs b/mcs/class/System.Xaml/System.Windows.Markup/MarkupExtension.cs
new file mode 100644 (file)
index 0000000..f79cefd
--- /dev/null
@@ -0,0 +1,37 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Xaml;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public abstract class MarkupExtension
+       {
+               public abstract object ProvideValue (IServiceProvider serviceProvider);
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/MarkupExtensionReturnTypeAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/MarkupExtensionReturnTypeAttribute.cs
new file mode 100755 (executable)
index 0000000..763a902
--- /dev/null
@@ -0,0 +1,51 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsage (AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
+       public sealed class MarkupExtensionReturnTypeAttribute : Attribute
+       {
+               public MarkupExtensionReturnTypeAttribute ()
+               {
+               }
+
+               public MarkupExtensionReturnTypeAttribute (Type returnType)
+               {
+                       ReturnType = returnType;
+               }
+
+               [Obsolete ("Unused. Use MarkupExtensionReturnTypeAttribute(Type) or XamlSetMarkupExtensionAttribute.")]
+               public MarkupExtensionReturnTypeAttribute (Type returnType, Type expressionType)
+                       : this (returnType)
+               {
+                       ExpressionType = expressionType;
+               }
+
+               public Type ReturnType { get; private set; }
+
+               [ObsoleteAttribute ("Unused. Use XamlSetMarkupExtensionAttribute functionality instead.")]
+               public Type ExpressionType { get; private set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/MemberDefinition.cs b/mcs/class/System.Xaml/System.Windows.Markup/MemberDefinition.cs
new file mode 100755 (executable)
index 0000000..8d96847
--- /dev/null
@@ -0,0 +1,37 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       public abstract class MemberDefinition
+       {
+               public abstract string Name { get; set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/NameReferenceConverter.cs b/mcs/class/System.Xaml/System.Windows.Markup/NameReferenceConverter.cs
new file mode 100755 (executable)
index 0000000..dc75a87
--- /dev/null
@@ -0,0 +1,66 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Globalization;
+using System.Xaml;
+
+namespace System.Windows.Markup
+{
+       public class NameReferenceConverter : TypeConverter
+       {
+               public override bool CanConvertFrom (ITypeDescriptorContext context, Type sourceType)
+               {
+                       return sourceType == typeof (string);
+               }
+
+               public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType)
+               {
+                       if (context == null)
+                               return false;
+                       var p = context.GetService (typeof (IXamlNameProvider)) as IXamlNameProvider;
+                       return p != null && destinationType == typeof (string);
+               }
+
+               public override object ConvertFrom (ITypeDescriptorContext context, CultureInfo culture, object value)
+               {
+                       if (context == null)
+                               throw new ArgumentNullException ("context");
+                       var s = value as string;
+                       if (String.IsNullOrEmpty (s))
+                               throw new InvalidOperationException ("Value must be non-null string.");
+                       
+                       return s;
+               }
+
+               public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
+               {
+                       if (context == null)
+                               return null;
+                       var p = context.GetService (typeof (IXamlNameProvider)) as IXamlNameProvider;
+                       return p != null ? p.GetName (value) : null;
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/NameScopePropertyAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/NameScopePropertyAttribute.cs
new file mode 100755 (executable)
index 0000000..8e33e01
--- /dev/null
@@ -0,0 +1,44 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsage (AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public sealed class NameScopePropertyAttribute : Attribute
+       {
+               public NameScopePropertyAttribute (string name)
+               {
+               }
+               
+               public NameScopePropertyAttribute (string name, Type type)
+               {
+                       Name = name;
+                       Type = type;
+               }
+               
+               public string Name { get; private set; }
+               public Type Type { get; private set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/NullExtension.cs b/mcs/class/System.Xaml/System.Windows.Markup/NullExtension.cs
new file mode 100755 (executable)
index 0000000..19cd2cb
--- /dev/null
@@ -0,0 +1,40 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [MarkupExtensionReturnType (typeof (Object))]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyPresentationFramework_3_5)]
+       public class NullExtension : MarkupExtension
+       {
+               public override Object ProvideValue (IServiceProvider serviceProvider)
+               {
+                       return null;
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/PropertyDefinition.cs b/mcs/class/System.Xaml/System.Windows.Markup/PropertyDefinition.cs
new file mode 100755 (executable)
index 0000000..4a4e9fe
--- /dev/null
@@ -0,0 +1,53 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Xaml;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       public class PropertyDefinition : MemberDefinition
+       {
+               public PropertyDefinition ()
+               {
+                       Attributes = new List<Attribute> ();
+               }
+
+               public IList<Attribute> Attributes { get; private set; }
+
+               [DefaultValue ("public")]
+               public string Modifier { get; set; }
+
+               string name;
+               public override string Name { 
+                       get { return name; }
+                       set { name = value; }
+               }
+
+               [TypeConverter (typeof (XamlTypeTypeConverter))]
+               public XamlType Type { get; set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/Reference.cs b/mcs/class/System.Xaml/System.Windows.Markup/Reference.cs
new file mode 100755 (executable)
index 0000000..6d3429e
--- /dev/null
@@ -0,0 +1,60 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Xaml;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [ContentProperty ("Name")]
+       public class Reference : MarkupExtension
+       {
+               public Reference ()
+               {
+               }
+
+               public Reference (string name)
+               {
+                       Name = name;
+               }
+
+               [ConstructorArgument ("name")]
+               public string Name { get; set; }
+
+               public override object ProvideValue (IServiceProvider serviceProvider)
+               {
+                       if (serviceProvider == null)
+                               throw new ArgumentNullException ("serviceProvider");
+                       if (Name == null)
+                               throw new InvalidOperationException ("Name property is not set");
+                       var r = ((object) serviceProvider) as IXamlNameResolver;
+                       if (r == null)
+                               throw new ArgumentException ("serviceProvider does not implement IXamlNameResolver");
+                       return r.Resolve (Name);
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/RootNamespaceAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/RootNamespaceAttribute.cs
new file mode 100755 (executable)
index 0000000..040f194
--- /dev/null
@@ -0,0 +1,38 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsage (AttributeTargets.Assembly)]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public sealed class RootNamespaceAttribute : Attribute
+       {
+               public RootNamespaceAttribute (string nameSpace)
+               {
+                       Namespace = nameSpace;
+               }
+               
+               public string Namespace { get; private set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/RuntimeNamePropertyAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/RuntimeNamePropertyAttribute.cs
new file mode 100755 (executable)
index 0000000..44c3706
--- /dev/null
@@ -0,0 +1,38 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsage (AttributeTargets.Class)]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public sealed class RuntimeNamePropertyAttribute : Attribute
+       {
+               public RuntimeNamePropertyAttribute (string name)
+               {
+                       Name = name;
+               }
+               
+               public string Name { get; private set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/StaticExtension.cs b/mcs/class/System.Xaml/System.Windows.Markup/StaticExtension.cs
new file mode 100755 (executable)
index 0000000..24df4f5
--- /dev/null
@@ -0,0 +1,69 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [MarkupExtensionReturnType (typeof (object))]
+       [TypeConverter (typeof (StaticExtensionConverter))]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyPresentationFramework_3_5)]
+       public class StaticExtension : MarkupExtension
+       {
+               public StaticExtension ()
+               {
+               }
+
+               public StaticExtension (string member)
+               {
+                       Member = member;
+               }
+
+               [ConstructorArgument ("member")]
+               public string Member { get; set; }
+
+               [DefaultValue (null)]
+               public Type MemberType { get; set; }
+
+               public override object ProvideValue (IServiceProvider serviceProvider)
+               {
+                       if (Member == null)
+                               throw new InvalidOperationException ("Member property must be set to StaticExtension before calling ProvideValue method.");
+                       if (MemberType != null) {
+                               var pi = MemberType.GetProperty (Member, BindingFlags.Public | BindingFlags.Static);
+                               if (pi != null)
+                                       return pi.GetValue (null, null);
+                               var fi = MemberType.GetField (Member, BindingFlags.Public | BindingFlags.Static);
+                               if (fi != null)
+                                       return fi.GetValue (null);
+                       }
+                       // there might be some cases that it could still
+                       // resolve a static member without MemberType, 
+                       // but we don't know any of such so far.
+                       throw new ArgumentException (String.Format ("Member '{0}' could not be resolved to a static member", Member));
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/StaticExtensionConverter.cs b/mcs/class/System.Xaml/System.Windows.Markup/StaticExtensionConverter.cs
new file mode 100644 (file)
index 0000000..d428607
--- /dev/null
@@ -0,0 +1,34 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       internal class StaticExtensionConverter : TypeConverter
+       {
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/TrimSurroundingWhitespaceAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/TrimSurroundingWhitespaceAttribute.cs
new file mode 100755 (executable)
index 0000000..371e3e0
--- /dev/null
@@ -0,0 +1,38 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsage (AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public sealed class TrimSurroundingWhitespaceAttribute : Attribute
+       {
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/TypeExtension.cs b/mcs/class/System.Xaml/System.Windows.Markup/TypeExtension.cs
new file mode 100755 (executable)
index 0000000..83c13d3
--- /dev/null
@@ -0,0 +1,80 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [MarkupExtensionReturnType (typeof (Type))]
+       [TypeConverter (typeof (TypeExtensionConverter))]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyPresentationFramework_3_5)]
+       public class TypeExtension : MarkupExtension
+       {
+               public TypeExtension ()
+               {
+               }
+
+               public TypeExtension (string typeName)
+               {
+                       if (typeName == null)
+                               throw new ArgumentNullException ("typeName");
+                       TypeName = typeName;
+               }
+
+               public TypeExtension (Type type)
+               {
+                       if (type == null)
+                               throw new ArgumentNullException ("type");
+                       Type = type;
+               }
+
+               [ConstructorArgument ("type")]
+               [DefaultValue (null)]
+               public Type Type { get; set; }
+               public string TypeName { get; set; }
+
+               public override object ProvideValue (IServiceProvider serviceProvider)
+               {
+                       if (Type != null)
+                               return Type;
+
+                       if (TypeName == null)
+                               throw new InvalidOperationException ("Either TypeName or Type must be filled before calling ProvideValue method");
+
+                       if (serviceProvider == null) // it can be null when Type is supplied.
+                               throw new ArgumentNullException ("serviceProvider");
+
+                       var p = serviceProvider.GetService (typeof (IXamlTypeResolver)) as IXamlTypeResolver;
+                       if (p == null)
+                               throw new InvalidOperationException ("serviceProvider does not provide IXamlTypeResolver service.");
+
+                       var ret = p.Resolve (TypeName);
+                       if (ret == null)
+                               throw new InvalidOperationException (String.Format ("Type '{0}' is not resolved as a valid type by the type resolver '{1}'.", TypeName, p.GetType ()));
+                       return ret;
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/TypeExtensionConverter.cs b/mcs/class/System.Xaml/System.Windows.Markup/TypeExtensionConverter.cs
new file mode 100644 (file)
index 0000000..de4e357
--- /dev/null
@@ -0,0 +1,62 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Globalization;
+using System.Reflection;
+using System.Xaml;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       internal class TypeExtensionConverter : TypeConverter
+       {
+               public override bool CanConvertFrom (ITypeDescriptorContext context, Type sourceType)
+               {
+                       return false;
+               }
+
+               public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType)
+               {
+                       return destinationType == typeof (string);
+               }
+
+               public override object ConvertFrom (ITypeDescriptorContext context, CultureInfo culture, object value)
+               {
+                       throw new NotSupportedException (String.Format ("Conversion from type {0} is not supported", value != null ? value.GetType () : null));
+               }
+
+               public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
+               {
+                       var xt = value as XamlType;
+                       if (xt != null) {
+                               if (destinationType == typeof (string))
+                                       return xt.ToString ();
+                               throw new NotSupportedException (String.Format ("Conversion to type {0} is not supported", destinationType));
+                       }
+                       else
+                               return base.ConvertTo (context, culture, value, destinationType); // it seems it still handles not-supported types (such as int).
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/UidPropertyAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/UidPropertyAttribute.cs
new file mode 100755 (executable)
index 0000000..1898e16
--- /dev/null
@@ -0,0 +1,44 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsage (AttributeTargets.Class, AllowMultiple = false)]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public sealed class UidPropertyAttribute : Attribute
+       {
+               public UidPropertyAttribute (string name)
+               {
+                       Name = name;
+               }
+               
+               public string Name { get; private set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/UsableDuringInitializationAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/UsableDuringInitializationAttribute.cs
new file mode 100755 (executable)
index 0000000..c3b2bf9
--- /dev/null
@@ -0,0 +1,44 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsage (AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
+       public sealed class UsableDuringInitializationAttribute : Attribute
+       {
+               public UsableDuringInitializationAttribute (bool usable)
+               {
+                       Usable = usable;
+               }
+               
+               public bool Usable { get; private set; }
+       }
+}
+
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/ValueSerializer.cs b/mcs/class/System.Xaml/System.Windows.Markup/ValueSerializer.cs
new file mode 100644 (file)
index 0000000..157f098
--- /dev/null
@@ -0,0 +1,178 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Xaml;
+
+namespace System.Windows.Markup
+{
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public abstract class ValueSerializer
+       {
+               public static ValueSerializer GetSerializerFor (PropertyDescriptor descriptor)
+               {
+                       return GetSerializerFor (descriptor, null);
+               }
+
+               public static ValueSerializer GetSerializerFor (Type type)
+               {
+                       return GetSerializerFor (type, null);
+               }
+
+               public static ValueSerializer GetSerializerFor (PropertyDescriptor descriptor, IValueSerializerContext context)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               [MonoTODO ("IValueSerializerContext parameter is not supported")]
+               public static ValueSerializer GetSerializerFor (Type type, IValueSerializerContext context)
+               {
+                       if (type == null)
+                               throw new ArgumentNullException ("type");
+
+                       // FIXME: it is likely a hack.
+                       if (Type.GetTypeCode (type) != TypeCode.Object)
+                               return new TypeConverterValueSerializer (type);
+                       if (type == typeof (TimeSpan))
+                               return new TypeConverterValueSerializer (typeof (TimeSpan));
+                       if (type == typeof (Uri))
+                               return new TypeConverterValueSerializer (typeof (Uri));
+                       return null;
+               }
+
+               // instance members
+
+               public virtual bool CanConvertFromString (string value, IValueSerializerContext context)
+               {
+                       return false;
+               }
+
+               public virtual bool CanConvertToString (object value, IValueSerializerContext context)
+               {
+                       return false;
+               }
+
+               public virtual object ConvertFromString (string value, IValueSerializerContext context)
+               {
+                       throw new NotSupportedException (String.Format ("Conversion from string '{0}' is not supported", value));
+               }
+
+               public virtual string ConvertToString (object value,     IValueSerializerContext context)
+               {
+                       throw new NotSupportedException (String.Format ("Conversion from '{0}' to string is not supported", value != null ? value.GetType ().Name : "(null)"));
+               }
+
+               protected Exception GetConvertFromException (object value)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               protected Exception GetConvertToException (object value, Type destinationType)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public virtual IEnumerable<Type> TypeReferences (object value, IValueSerializerContext context)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+
+       internal class StringValueSerializer : ValueSerializer
+       {
+               public override bool CanConvertFromString (string value, IValueSerializerContext context)
+               {
+                       return true;
+               }
+
+               public override bool CanConvertToString (object value, IValueSerializerContext context)
+               {
+                       return true;
+               }
+
+               public override object ConvertFromString (string value, IValueSerializerContext context)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override string ConvertToString (object value,     IValueSerializerContext context)
+               {
+                       return (string) value;
+               }
+
+               public override IEnumerable<Type> TypeReferences (object value, IValueSerializerContext context)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+
+       #region Internal implementations.
+
+       internal class TypeConverterValueSerializer<T> : TypeConverterValueSerializer
+       {
+               public TypeConverterValueSerializer ()
+                       : base (typeof (T))
+               {
+               }
+       }
+
+       internal class TypeConverterValueSerializer : ValueSerializer
+       {
+               public TypeConverterValueSerializer (Type type)
+               {
+                       c = TypeDescriptor.GetConverter (type);
+               }
+
+               TypeConverter c;
+
+               public override bool CanConvertFromString (string value, IValueSerializerContext context)
+               {
+                       return c.CanConvertFrom (typeof (string));
+               }
+
+               public override bool CanConvertToString (object value, IValueSerializerContext context)
+               {
+                       return c.CanConvertTo (typeof (string));
+               }
+
+               public override object ConvertFromString (string value, IValueSerializerContext context)
+               {
+                       return c.ConvertFromInvariantString (value);
+               }
+
+               public override string ConvertToString (object value,     IValueSerializerContext context)
+               {
+                       return value == null ? String.Empty : c.ConvertToInvariantString (value);
+               }
+
+               public override IEnumerable<Type> TypeReferences (object value, IValueSerializerContext context)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+       
+       #endregion
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/ValueSerializerAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/ValueSerializerAttribute.cs
new file mode 100755 (executable)
index 0000000..37dec52
--- /dev/null
@@ -0,0 +1,51 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsage (AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Interface, AllowMultiple = false, Inherited = true)]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public sealed class ValueSerializerAttribute : Attribute
+       {
+               public ValueSerializerAttribute (string valueSerializerTypeName)
+               {
+                       ValueSerializerTypeName = valueSerializerTypeName;
+               }
+               
+               public ValueSerializerAttribute (Type valueSerializerType)
+               {
+                       ValueSerializerType = valueSerializerType;
+               }
+               
+               public Type ValueSerializerType { get; private set; }
+               public string ValueSerializerTypeName { get; private set; }
+       }
+}
+
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/WhitespaceSignificantCollectionAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/WhitespaceSignificantCollectionAttribute.cs
new file mode 100755 (executable)
index 0000000..36cdf56
--- /dev/null
@@ -0,0 +1,39 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsage (AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public sealed class WhitespaceSignificantCollectionAttribute : Attribute
+       {
+       }
+}
+
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/XData.cs b/mcs/class/System.Xaml/System.Windows.Markup/XData.cs
new file mode 100755 (executable)
index 0000000..0352f39
--- /dev/null
@@ -0,0 +1,66 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.IO;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+using System.Xml;
+
+namespace System.Windows.Markup
+{
+       [ContentProperty ("Text")]
+       public sealed class XData
+       {
+               string text;
+               XmlReader reader;
+
+               public string Text {
+                       get { return text; }
+                       set {
+                               if (value == null) {
+                                       text = null;
+                                       reader = null;
+                               }
+                               else
+                                       text = value;
+                       }
+               }
+
+               public object XmlReader {
+                       get {
+                               if (reader == null)
+                                       reader = System.Xml.XmlReader.Create (new StringReader (text));
+                               return reader;
+                       }
+                       set {
+                               // silly? yes, it's also a hack in .NET - who cares?
+                               reader = value as XmlReader;
+                               text = null;
+                       }
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/XamlDeferLoadAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/XamlDeferLoadAttribute.cs
new file mode 100755 (executable)
index 0000000..4e37219
--- /dev/null
@@ -0,0 +1,55 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
+       public sealed class XamlDeferLoadAttribute : Attribute
+       {
+               public XamlDeferLoadAttribute (string loaderType, string contentType)
+               {
+                       LoaderTypeName = loaderType;
+                       ContentTypeName = contentType;
+               }
+
+               public XamlDeferLoadAttribute (Type loaderType, Type contentType)
+               {
+                       LoaderType = loaderType;
+                       ContentType = contentType;
+               }
+               
+               public Type ContentType { get; private set; }
+               public string ContentTypeName { get; private set; }
+               public Type LoaderType { get; private set; }
+               public string LoaderTypeName { get; private set; }
+
+       }
+}
+
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/XamlSetMarkupExtensionAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/XamlSetMarkupExtensionAttribute.cs
new file mode 100755 (executable)
index 0000000..58ffcbb
--- /dev/null
@@ -0,0 +1,44 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsageAttribute(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
+       public sealed class XamlSetMarkupExtensionAttribute : Attribute
+       {
+               public XamlSetMarkupExtensionAttribute (string xamlSetMarkupExtensionHandler)
+               {
+                       XamlSetMarkupExtensionHandler = xamlSetMarkupExtensionHandler;
+               }
+               
+               public string XamlSetMarkupExtensionHandler { get; private set; }
+       }
+}
+
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/XamlSetMarkupExtensionEventArgs.cs b/mcs/class/System.Xaml/System.Windows.Markup/XamlSetMarkupExtensionEventArgs.cs
new file mode 100644 (file)
index 0000000..6ffe3e5
--- /dev/null
@@ -0,0 +1,49 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Xaml;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       public class XamlSetMarkupExtensionEventArgs : XamlSetValueEventArgs
+       {
+               public XamlSetMarkupExtensionEventArgs (XamlMember member, MarkupExtension value, IServiceProvider serviceProvider)
+                       : base (member, null)
+               {
+                       MarkupExtension = value;
+                       ServiceProvider = serviceProvider;
+               }
+
+               public MarkupExtension MarkupExtension { get; private set; }
+               public IServiceProvider ServiceProvider { get; private set; }
+
+               public override void CallBase ()
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/XamlSetTypeConverterAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/XamlSetTypeConverterAttribute.cs
new file mode 100755 (executable)
index 0000000..8a5cec2
--- /dev/null
@@ -0,0 +1,44 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsage (AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
+       public sealed class XamlSetTypeConverterAttribute : Attribute
+       {
+               public XamlSetTypeConverterAttribute (string xamlSetTypeConverterHandler)
+               {
+                       XamlSetTypeConverterHandler = xamlSetTypeConverterHandler;
+               }
+               
+               public string XamlSetTypeConverterHandler { get; private set; }
+       }
+}
+
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/XamlSetTypeConverterEventArgs.cs b/mcs/class/System.Xaml/System.Windows.Markup/XamlSetTypeConverterEventArgs.cs
new file mode 100644 (file)
index 0000000..132df7a
--- /dev/null
@@ -0,0 +1,52 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Globalization;
+using System.Reflection;
+using System.Xaml;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       public class XamlSetTypeConverterEventArgs : XamlSetValueEventArgs
+       {
+               public XamlSetTypeConverterEventArgs (XamlMember member, TypeConverter typeConverter, object value, ITypeDescriptorContext serviceProvider, CultureInfo cultureInfo)
+                       : base (member, value)
+               {
+                       CultureInfo = cultureInfo;
+                       ServiceProvider = serviceProvider;
+                       TypeConverter = typeConverter;
+               }
+               
+               public CultureInfo CultureInfo { get; private set; }
+               public ITypeDescriptorContext ServiceProvider { get; private set; }
+               public TypeConverter TypeConverter { get; private set; }
+
+               public override void CallBase ()
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/XamlSetValueEventArgs.cs b/mcs/class/System.Xaml/System.Windows.Markup/XamlSetValueEventArgs.cs
new file mode 100644 (file)
index 0000000..15af43c
--- /dev/null
@@ -0,0 +1,49 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Xaml;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       public class XamlSetValueEventArgs : EventArgs
+       {
+               public XamlSetValueEventArgs (XamlMember member, object value)
+               {
+                       Member = member;
+                       Value = value;
+               }
+               
+               public bool Handled { get; set; }
+               public XamlMember Member { get; private set; }
+               public object Value { get; private set; }
+
+               public virtual void CallBase ()
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/XmlLangPropertyAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/XmlLangPropertyAttribute.cs
new file mode 100755 (executable)
index 0000000..4789120
--- /dev/null
@@ -0,0 +1,45 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsage (AttributeTargets.Class, AllowMultiple = false)]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public sealed class XmlLangPropertyAttribute : Attribute
+       {
+               public XmlLangPropertyAttribute (string name)
+               {
+                       Name = name;
+               }
+               
+               public string Name { get; private set; }
+       }
+}
+
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/XmlnsCompatibleWithAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/XmlnsCompatibleWithAttribute.cs
new file mode 100755 (executable)
index 0000000..0e16db2
--- /dev/null
@@ -0,0 +1,46 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsage (AttributeTargets.Assembly, AllowMultiple = true)]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public sealed class XmlnsCompatibleWithAttribute : Attribute
+       {
+               public XmlnsCompatibleWithAttribute (string oldNamespace, string newNamespace)
+               {
+                       OldNamespace = oldNamespace;
+                       NewNamespace = newNamespace;
+               }
+               
+               public string NewNamespace { get; private set; }
+               public string OldNamespace { get; private set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/XmlnsDefinitionAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/XmlnsDefinitionAttribute.cs
new file mode 100755 (executable)
index 0000000..81be2da
--- /dev/null
@@ -0,0 +1,47 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsage (AttributeTargets.Assembly, AllowMultiple = true)]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public sealed class XmlnsDefinitionAttribute : Attribute
+       {
+               public XmlnsDefinitionAttribute (string xmlNamespace, string clrNamespace)
+               {
+                       XmlNamespace = xmlNamespace;
+                       ClrNamespace = clrNamespace;
+               }
+               
+               public string AssemblyName { get; set; }
+               public string ClrNamespace { get; private set; }
+               public string XmlNamespace { get; private set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Windows.Markup/XmlnsPrefixAttribute.cs b/mcs/class/System.Xaml/System.Windows.Markup/XmlnsPrefixAttribute.cs
new file mode 100755 (executable)
index 0000000..c907c8e
--- /dev/null
@@ -0,0 +1,46 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Windows.Markup
+{
+       [AttributeUsage (AttributeTargets.Assembly, AllowMultiple = true)]
+       [System.Runtime.CompilerServices.TypeForwardedFrom (Consts.AssemblyWindowsBase)]
+       public sealed class XmlnsPrefixAttribute : Attribute
+       {
+               public XmlnsPrefixAttribute (string xmlNamespace, string prefix)
+               {
+                       XmlNamespace = xmlNamespace;
+                       Prefix = prefix;
+               }
+               
+               public string Prefix { get; private set; }
+               public string XmlNamespace { get; private set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml.Permissions/ChangeLog b/mcs/class/System.Xaml/System.Xaml.Permissions/ChangeLog
new file mode 100644 (file)
index 0000000..38dc8e7
--- /dev/null
@@ -0,0 +1,7 @@
+2010-04-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlAccessLevel.cs : add missing methods.
+
+2010-04-08  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlAccessLevel.cs  XamlLoadPermission.cs : initial checkin.
diff --git a/mcs/class/System.Xaml/System.Xaml.Permissions/XamlAccessLevel.cs b/mcs/class/System.Xaml/System.Xaml.Permissions/XamlAccessLevel.cs
new file mode 100644 (file)
index 0000000..d1739c2
--- /dev/null
@@ -0,0 +1,75 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Xaml;
+
+namespace System.Xaml.Permissions
+{
+       [SerializableAttribute]
+       public class XamlAccessLevel
+       {
+               public static XamlAccessLevel AssemblyAccessTo (Assembly assembly)
+               {
+                       if (assembly == null)
+                               throw new ArgumentNullException ("assembly");
+
+                       return new XamlAccessLevel (assembly.GetName ());
+               }
+               public static XamlAccessLevel AssemblyAccessTo (AssemblyName assemblyName)
+               {
+                       if (assemblyName == null)
+                               throw new ArgumentNullException ("assemblyName");
+                       return new XamlAccessLevel (assemblyName);
+               }
+
+               public static XamlAccessLevel PrivateAccessTo (string assemblyQualifiedTypeName)
+               {
+                       if (assemblyQualifiedTypeName == null)
+                               throw new ArgumentNullException ("assemblyQualifiedTypeName");
+                       return new XamlAccessLevel (assemblyQualifiedTypeName);
+               }
+
+               public static XamlAccessLevel PrivateAccessTo (Type type)
+               {
+                       if (type == null)
+                               throw new ArgumentNullException ("type");
+                       return new XamlAccessLevel (type.AssemblyQualifiedName);
+               }
+
+               internal XamlAccessLevel (AssemblyName assemblyAccessToAssemblyName)
+               {
+                       AssemblyAccessToAssemblyName = assemblyAccessToAssemblyName;
+               }
+
+               internal XamlAccessLevel (string privateAccessToTypeName)
+               {
+                       PrivateAccessToTypeName = privateAccessToTypeName;
+               }
+
+               public AssemblyName AssemblyAccessToAssemblyName { get; private set; }
+               public string PrivateAccessToTypeName { get; private set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml.Permissions/XamlLoadPermission.cs b/mcs/class/System.Xaml/System.Xaml.Permissions/XamlLoadPermission.cs
new file mode 100644 (file)
index 0000000..ae2b93b
--- /dev/null
@@ -0,0 +1,82 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Security;
+using System.Security.Permissions;
+using System.Xaml;
+
+namespace System.Xaml.Permissions
+{
+       [Serializable]
+       public sealed class XamlLoadPermission : CodeAccessPermission, IUnrestrictedPermission
+       {
+               public XamlLoadPermission (IEnumerable<XamlAccessLevel> allowedAccess)
+               {
+                       AllowedAccess = new List<XamlAccessLevel> (allowedAccess);
+               }
+               public XamlLoadPermission (PermissionState state)
+               {
+                       throw new NotImplementedException ();
+               }
+               public XamlLoadPermission (XamlAccessLevel allowedAccess)
+                       : this (new XamlAccessLevel [] {allowedAccess})
+               {
+               }
+
+               public IList<XamlAccessLevel> AllowedAccess { get; private set; }
+
+               public override IPermission Copy ()
+               {
+                       throw new NotImplementedException ();
+               }
+               public override void FromXml (SecurityElement elem)
+               {
+                       throw new NotImplementedException ();
+               }
+               public bool Includes (XamlAccessLevel requestedAccess)
+               {
+                       throw new NotImplementedException ();
+               }
+               public override IPermission Intersect (IPermission target)
+               {
+                       throw new NotImplementedException ();
+               }
+               public override bool IsSubsetOf (IPermission target)
+               {
+                       throw new NotImplementedException ();
+               }
+               public bool IsUnrestricted ()
+               {
+                       throw new NotImplementedException ();
+               }
+               public override SecurityElement ToXml ()
+               {
+                       throw new NotImplementedException ();
+               }
+               public override IPermission Union (IPermission other)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml.Schema/AllowedMemberLocations.cs b/mcs/class/System.Xaml/System.Xaml.Schema/AllowedMemberLocations.cs
new file mode 100644 (file)
index 0000000..0b37d4e
--- /dev/null
@@ -0,0 +1,36 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Xaml.Schema
+{
+       [FlagsAttribute]
+       public enum AllowedMemberLocations
+       {
+               None = 0,
+               Attribute = 1,
+               MemberElement = 2,
+               Any = 3
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml.Schema/ChangeLog b/mcs/class/System.Xaml/System.Xaml.Schema/ChangeLog
new file mode 100644 (file)
index 0000000..1d56e12
--- /dev/null
@@ -0,0 +1,48 @@
+2010-04-22  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlMemberInvoker.cs : make sure GetValue() is not supported
+         on directives.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlTypeTypeConverter.cs : this prefers UnderlyingType.ToString()
+         unlike XamlType.ToString().
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlTypeName.cs : corcompare shows I was missing useful two.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlTypeName.cs : implemented.
+
+2010-04-13  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlTypeInvoker.cs : implement AddToCollection and AddToDictionary.
+
+2010-04-13  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlTypeInvoker.cs : implement CreateInstance() for object writer.
+
+2010-04-12  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlTypeName.cs : methods were missing.
+
+2010-04-09  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlTypeTypeConverter.cs, XamlValueConverter.cs : implemented.
+
+2010-04-08  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlMemberInvoker.cs : implement most of it.
+
+2010-04-08  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * AllowedMemberLocations.cs
+         ShouldSerializeResult.cs
+         XamlCollectionKind.cs
+         XamlMemberInvoker.cs
+         XamlTypeInvoker.cs
+         XamlTypeName.cs
+         XamlTypeTypeConverter.cs
+         XamlValueConverter.cs : initial checkin.
diff --git a/mcs/class/System.Xaml/System.Xaml.Schema/ShouldSerializeResult.cs b/mcs/class/System.Xaml/System.Xaml.Schema/ShouldSerializeResult.cs
new file mode 100644 (file)
index 0000000..d50bcc6
--- /dev/null
@@ -0,0 +1,34 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Xaml.Schema
+{
+       public enum ShouldSerializeResult
+       {
+               Default,
+               True,
+               False
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml.Schema/XamlCollectionKind.cs b/mcs/class/System.Xaml/System.Xaml.Schema/XamlCollectionKind.cs
new file mode 100644 (file)
index 0000000..3e32539
--- /dev/null
@@ -0,0 +1,35 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Xaml.Schema
+{
+       public enum XamlCollectionKind
+       {
+               None,
+               Collection,
+               Dictionary,
+               Array,
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml.Schema/XamlMemberInvoker.cs b/mcs/class/System.Xaml/System.Xaml.Schema/XamlMemberInvoker.cs
new file mode 100644 (file)
index 0000000..7295679
--- /dev/null
@@ -0,0 +1,82 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+
+namespace System.Xaml.Schema
+{
+       public class XamlMemberInvoker
+       {
+               public static XamlMemberInvoker UnknownInvoker {
+                       get { throw new NotImplementedException (); }
+               }
+
+               protected XamlMemberInvoker ()
+               {
+               }
+
+               public XamlMemberInvoker (XamlMember member)
+               {
+                       if (member == null)
+                               throw new ArgumentNullException ("member");
+                       this.member = member;
+               }
+
+               XamlMember member;
+
+               public MethodInfo UnderlyingGetter {
+                       get { return member != null ? member.UnderlyingGetter : null; }
+               }
+
+               public MethodInfo UnderlyingSetter {
+                       get { return member != null ? member.UnderlyingSetter : null; }
+               }
+
+               public virtual object GetValue (object instance)
+               {
+                       if (instance == null)
+                               throw new ArgumentNullException ("instance");
+                       if (this is XamlDirective)
+                               throw new NotSupportedException ("not supported operation on directive members.");
+                       if (UnderlyingGetter == null)
+                               throw new NotSupportedException ("Attempt to get value from write-only property or event");
+                       return UnderlyingGetter.Invoke (instance, new object [0]);
+               }
+               public virtual void SetValue (object instance, object value)
+               {
+                       if (instance == null)
+                               throw new ArgumentNullException ("instance");
+                       if (this is XamlDirective)
+                               throw new NotSupportedException ("not supported operation on directive members.");
+                       if (UnderlyingSetter == null)
+                               throw new NotSupportedException ("Attempt to get value from read-only property");
+                       UnderlyingSetter.Invoke (instance, new object [] {value});
+               }
+
+               public virtual ShouldSerializeResult ShouldSerializeValue (object instance)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml.Schema/XamlTypeInvoker.cs b/mcs/class/System.Xaml/System.Xaml.Schema/XamlTypeInvoker.cs
new file mode 100644 (file)
index 0000000..09f85b6
--- /dev/null
@@ -0,0 +1,111 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Windows.Markup;
+
+namespace System.Xaml.Schema
+{
+       public class XamlTypeInvoker
+       {
+               public static XamlTypeInvoker UnknownInvoker {
+                       get { throw new NotImplementedException (); }
+               }
+
+               protected XamlTypeInvoker ()
+               {
+               }
+               
+               public XamlTypeInvoker (XamlType type)
+               {
+                       if (type == null)
+                               throw new ArgumentNullException ("type");
+                       this.type = type;
+               }
+               
+               XamlType type;
+
+               void ThrowIfUnknown ()
+               {
+                       if (type.UnderlyingType == null)
+                               throw new InvalidOperationException (String.Format ("Current operation is valid only when the underlying type on a XamlType is known, but it is unknown for '{0}'", type));
+               }
+
+               public EventHandler<XamlSetMarkupExtensionEventArgs> SetMarkupExtensionHandler {
+                       get { return type.SetMarkupExtensionHandler; }
+               }
+
+               public EventHandler<XamlSetTypeConverterEventArgs> SetTypeConverterHandler {
+                       get { return type.SetTypeConverterHandler; }
+               }
+
+               public virtual void AddToCollection (object instance, object item)
+               {
+                       if (instance == null)
+                               throw new ArgumentNullException ("instance");
+
+                       var t = instance.GetType ();
+                       MethodInfo mi;
+                       if (t.IsGenericType)
+                               mi = instance.GetType ().GetMethod ("Add", t.GetGenericArguments ());
+                       else
+                               mi = instance.GetType ().GetMethod ("Add", new Type [] {typeof (object)});
+                       if (mi == null)
+                               throw new InvalidOperationException (String.Format ("The collection type '{0}' does not have 'Add' method", t));
+                       mi.Invoke (instance, new object [] {item});
+               }
+
+               public virtual void AddToDictionary (object instance, object key, object item)
+               {
+                       if (instance == null)
+                               throw new ArgumentNullException ("instance");
+
+                       var t = instance.GetType ();
+                       if (t.IsGenericType)
+                               instance.GetType ().GetMethod ("Add", t.GetGenericArguments ()).Invoke (instance, new object [] {key, item});
+                       else
+                               instance.GetType ().GetMethod ("Add", new Type [] {typeof (object), typeof (object)}).Invoke (instance, new object [] {key, item});
+               }
+
+               public virtual object CreateInstance (object [] arguments)
+               {
+                       ThrowIfUnknown ();
+                       return Activator.CreateInstance (type.UnderlyingType, arguments);
+               }
+
+               public virtual MethodInfo GetAddMethod (XamlType contentType)
+               {
+                       throw new NotImplementedException ();
+               }
+               public virtual MethodInfo GetEnumeratorMethod ()
+               {
+                       throw new NotImplementedException ();
+               }
+               public virtual IEnumerator GetItems (object instance)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml.Schema/XamlTypeName.cs b/mcs/class/System.Xaml/System.Xaml.Schema/XamlTypeName.cs
new file mode 100644 (file)
index 0000000..137c03e
--- /dev/null
@@ -0,0 +1,214 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace System.Xaml.Schema
+{
+       public class XamlTypeName
+       {
+               public static XamlTypeName Parse (string typeName, IXamlNamespaceResolver namespaceResolver)
+               {
+                       XamlTypeName n;
+                       if (!TryParse (typeName, namespaceResolver, out n))
+                               throw new FormatException (String.Format ("Invalid typeName: '{0}'", typeName));
+                       return n;
+               }
+
+               public static bool TryParse (string typeName, IXamlNamespaceResolver namespaceResolver, out XamlTypeName result)
+               {
+                       if (typeName == null)
+                               throw new ArgumentNullException ("typeName");
+                       if (namespaceResolver == null)
+                               throw new ArgumentNullException ("namespaceResolver");
+
+                       result = null;
+                       IList<XamlTypeName> args = null;
+
+                       int idx = typeName.IndexOf ('(');
+                       if (idx >= 0) {
+                               if (typeName [typeName.Length - 1] != ')')
+                                       return false;
+                               if (!TryParseList (typeName.Substring (idx + 1, typeName.Length - idx - 2), namespaceResolver, out args))
+                                       return false;
+                               typeName = typeName.Substring (0, idx);
+                       }
+
+                       idx = typeName.IndexOf (':');
+                       string prefix, local;
+                       if (idx < 0) {
+                               prefix = String.Empty;
+                               local = typeName;
+                       } else {
+                               prefix = typeName.Substring (0, idx);
+                               local = typeName.Substring (idx + 1);
+                               if (!XamlLanguage.IsValidXamlName (prefix))
+                                       return false;
+                       }
+                       if (!XamlLanguage.IsValidXamlName (local))
+                               return false;
+                       string ns = namespaceResolver.GetNamespace (prefix);
+                       if (ns == null)
+                               return false;
+
+                       result = new XamlTypeName (ns, local, args);
+                       return true;
+               }
+
+               static readonly char [] commas = {','};
+
+               public static IList<XamlTypeName> ParseList (string typeNameList, IXamlNamespaceResolver namespaceResolver)
+               {
+                       IList<XamlTypeName> list;
+                       if (!TryParseList (typeNameList, namespaceResolver, out list))
+                               throw new FormatException (String.Format ("Invalid type name list: '{0}'", typeNameList));
+                       return list;
+               }
+
+               public static bool TryParseList (string typeNameList, IXamlNamespaceResolver namespaceResolver, out IList<XamlTypeName> list)
+               {
+                       if (typeNameList == null)
+                               throw new ArgumentNullException ("typeNameList");
+                       if (namespaceResolver == null)
+                               throw new ArgumentNullException ("namespaceResolver");
+
+                       list = null;
+                       var split = typeNameList.Split (commas);
+                       if (split.Length == 0)
+                               return false;
+
+                       var arr = new XamlTypeName [split.Length];
+
+                       for (int i = 0; i < split.Length; i++) {
+                               var s = split [i].Trim ();
+                               XamlTypeName tn;
+                               if (!TryParse (s, namespaceResolver, out tn))
+                                       return false;
+                               arr [i] = tn;
+                       }
+
+                       list = arr;
+                       return true;
+               }
+
+               public static string ToString (IList<XamlTypeName> typeNameList, INamespacePrefixLookup prefixLookup)
+               {
+                       if (typeNameList == null)
+                               throw new ArgumentNullException ("typeNameList");
+                       if (prefixLookup == null)
+                               throw new ArgumentNullException ("prefixLookup");
+
+                       return DoToString (typeNameList, prefixLookup);
+               }
+
+               static string DoToString (IList<XamlTypeName> typeNameList, INamespacePrefixLookup prefixLookup)
+               {
+                       bool comma = false;
+                       string ret = "";
+                       foreach (var ta in typeNameList) {
+                               if (comma)
+                                       ret += ", ";
+                               else
+                                       comma = true;
+                               ret += ta.ToString (prefixLookup);
+                       }
+                       return ret;
+               }
+
+               // instance members
+
+               public XamlTypeName ()
+               {
+               }
+
+               static readonly XamlTypeName [] empty_type_args = new XamlTypeName [0];
+
+               public XamlTypeName (XamlType xamlType)
+               {
+                       if (xamlType == null)
+                               throw new ArgumentNullException ("xamlType");
+                       Namespace = xamlType.PreferredXamlNamespace;
+                       Name = xamlType.Name;
+                       if (xamlType.TypeArguments != null && xamlType.TypeArguments.Count > 0) {
+                               var l = new List<XamlTypeName> ();
+                               l.AddRange (from x in xamlType.TypeArguments.AsQueryable () select new XamlTypeName (x));
+                               TypeArguments = l;
+                       }
+                       else
+                               TypeArguments = empty_type_args;
+               }
+               
+               public XamlTypeName (string xamlNamespace, string name)
+                       : this (xamlNamespace, name, null)
+               {
+               }
+
+               public XamlTypeName (string xamlNamespace, string name, IEnumerable<XamlTypeName> typeArguments)
+               {
+                       Namespace = xamlNamespace;
+                       Name = name;
+                       if (typeArguments != null) {
+                               if (typeArguments.Any (t => t == null))
+                                       throw new ArgumentNullException ("typeArguments", "typeArguments array contains one or more null XamlTypeName");
+                               var l = new List<XamlTypeName> ();
+                               l.AddRange (typeArguments);
+                               TypeArguments = l;
+                       }
+                       else
+                               TypeArguments = empty_type_args;
+               }
+
+               public string Name { get; set; }
+               public string Namespace { get; set; }
+               public IList<XamlTypeName> TypeArguments { get; private set; }
+
+               public override string ToString ()
+               {
+                       return ToString (null);
+               }
+
+               public string ToString (INamespacePrefixLookup prefixLookup)
+               {
+                       if (Namespace == null)
+                               throw new InvalidOperationException ("Namespace must be set before calling ToString method.");
+                       if (Name == null)
+                               throw new InvalidOperationException ("Name must be set before calling ToString method.");
+
+                       string ret;
+                       if (prefixLookup == null)
+                               ret = String.Concat ("{", Namespace, "}", Name);
+                       else {
+                               string p = prefixLookup.LookupPrefix (Namespace);
+                               if (p == null)
+                                       throw new InvalidOperationException (String.Format ("Could not lookup prefix for namespace '{0}'", Namespace));
+                               ret = p.Length == 0 ? Name : p + ":" + Name;
+                       }
+
+                       if (TypeArguments.Count > 0)
+                               ret += String.Concat ("(", DoToString (TypeArguments, prefixLookup), ")");
+
+                       return ret;
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml.Schema/XamlTypeTypeConverter.cs b/mcs/class/System.Xaml/System.Xaml.Schema/XamlTypeTypeConverter.cs
new file mode 100644 (file)
index 0000000..acb6926
--- /dev/null
@@ -0,0 +1,59 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Globalization;
+
+namespace System.Xaml.Schema
+{
+       public class XamlTypeTypeConverter : TypeConverter
+       {
+               public override bool CanConvertFrom (ITypeDescriptorContext context, Type sourceType)
+               {
+                       return sourceType == typeof (string);
+               }
+
+               public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType)
+               {
+                       return destinationType == typeof (string);
+               }
+
+               public override Object ConvertFrom (ITypeDescriptorContext context, CultureInfo culture, Object value)
+               {
+                       throw new NotSupportedException (String.Format ("Conversion from type {0} is not supported", value != null ? value.GetType () : null));
+               }
+
+               public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
+               {
+                       var xt = value as XamlType;
+                       if (xt != null) {
+                               if (destinationType == typeof (string))
+                                       return xt.UnderlyingType != null ? xt.UnderlyingType.ToString () : xt.ToString ();
+                               throw new NotSupportedException (String.Format ("Conversion to type {0} is not supported", destinationType));
+                       }
+                       else
+                               return base.ConvertTo (context, culture, value, destinationType); // it seems it still handles not-supported types (such as int).
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml.Schema/XamlValueConverter.cs b/mcs/class/System.Xaml/System.Xaml.Schema/XamlValueConverter.cs
new file mode 100644 (file)
index 0000000..995f283
--- /dev/null
@@ -0,0 +1,119 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Xaml.Schema
+{
+       public class XamlValueConverter<TConverterBase> : IEquatable<XamlValueConverter<TConverterBase>>
+               where TConverterBase : class
+       {
+               public XamlValueConverter (Type converterType, XamlType targetType)
+                       : this (converterType, targetType, null)
+               {
+               }
+
+               public XamlValueConverter (Type converterType, XamlType targetType, string name)
+               {
+                       if (converterType == null && targetType == null && name == null)
+                               throw new ArgumentException ("Either of converterType, targetType or name must be non-null");
+                       ConverterType = converterType;
+                       TargetType = targetType;
+                       Name = name;
+               }
+
+               TConverterBase converter_instance;
+               public TConverterBase ConverterInstance {
+                       get {
+                               if (converter_instance == null)
+                                       converter_instance = CreateInstance ();
+                               return converter_instance;
+                       }
+               }
+               public Type ConverterType { get; private set; }
+               public string Name { get; private set; }
+               public XamlType TargetType { get; private set; }
+
+               
+               public static bool operator == (XamlValueConverter<TConverterBase> left, XamlValueConverter<TConverterBase> right)
+               {
+                       return IsNull (left) ? IsNull (right) : left.Equals (right);
+               }
+
+               static bool IsNull (XamlValueConverter<TConverterBase> a)
+               {
+                       return Object.ReferenceEquals (a, null);
+               }
+
+               public static bool operator != (XamlValueConverter<TConverterBase> left, XamlValueConverter<TConverterBase> right)
+               {
+                       return IsNull (left) ? !IsNull (right) : IsNull (right) || left.ConverterType != right.ConverterType || left.TargetType != right.TargetType || left.Name != right.Name;
+               }
+               
+               public bool Equals (XamlValueConverter<TConverterBase> other)
+               {
+                       return !IsNull (other) && ConverterType == other.ConverterType && TargetType == other.TargetType && Name == other.Name;
+               }
+
+               public override bool Equals (object obj)
+               {
+                       var a = obj as XamlValueConverter<TConverterBase>;
+                       return Equals (a);
+               }
+
+               protected virtual TConverterBase CreateInstance ()
+               {
+                       if (ConverterType == null)
+                               return null;
+
+                       if (!typeof (TConverterBase).IsAssignableFrom (ConverterType))
+                               throw new XamlSchemaException (String.Format ("ConverterType '{0}' is not derived from '{1}' type", ConverterType, typeof (TConverterBase)));
+
+                       return (TConverterBase) Activator.CreateInstance (ConverterType);
+               }
+
+               public override int GetHashCode ()
+               {
+                       var ret = ConverterType != null ? ConverterType.GetHashCode () : 0;
+                       ret <<= 5;
+                       if (TargetType != null)
+                               ret += TargetType.GetHashCode ();
+                       ret <<= 5;
+                       if (Name != null)
+                               ret += Name.GetHashCode ();
+                       return ret;
+               }
+
+               public override string ToString ()
+               {
+                       if (Name != null)
+                               return Name;
+                       if (ConverterType != null && TargetType != null)
+                               return String.Concat (ConverterType.Name, "(", TargetType.Name, ")");
+                       else if (ConverterType != null)
+                               return ConverterType.Name;
+                       else
+                               return TargetType.Name;
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml.dll.sources b/mcs/class/System.Xaml/System.Xaml.dll.sources
new file mode 100644 (file)
index 0000000..0b60bbf
--- /dev/null
@@ -0,0 +1,114 @@
+../../build/common/Consts.cs
+../../build/common/Locale.cs
+../../build/common/MonoTODOAttribute.cs
+../../build/common/basic-profile-check.cs
+Assembly/AssemblyInfo.cs
+System.Windows.Markup/AmbientAttribute.cs
+System.Windows.Markup/ArrayExtension.cs
+System.Windows.Markup/ConstructorArgumentAttribute.cs
+System.Windows.Markup/ContentPropertyAttribute.cs
+System.Windows.Markup/ContentWrapperAttribute.cs
+System.Windows.Markup/DateTimeValueSerializer.cs
+System.Windows.Markup/DependsOnAttribute.cs
+System.Windows.Markup/DictionaryKeyPropertyAttribute.cs
+System.Windows.Markup/IComponentConnector.cs
+System.Windows.Markup/INameScope.cs
+System.Windows.Markup/INameScopeDictionary.cs
+System.Windows.Markup/IProvideValueTarget.cs
+System.Windows.Markup/IQueryAmbient.cs
+System.Windows.Markup/IUriContext.cs
+System.Windows.Markup/IValueSerializerContext.cs
+System.Windows.Markup/IXamlTypeResolver.cs
+System.Windows.Markup/MarkupExtension.cs
+System.Windows.Markup/MarkupExtensionReturnTypeAttribute.cs
+System.Windows.Markup/MemberDefinition.cs
+System.Windows.Markup/NameReferenceConverter.cs
+System.Windows.Markup/NameScopePropertyAttribute.cs
+System.Windows.Markup/NullExtension.cs
+System.Windows.Markup/PropertyDefinition.cs
+System.Windows.Markup/Reference.cs
+System.Windows.Markup/RootNamespaceAttribute.cs
+System.Windows.Markup/RuntimeNamePropertyAttribute.cs
+System.Windows.Markup/StaticExtension.cs
+System.Windows.Markup/StaticExtensionConverter.cs
+System.Windows.Markup/TrimSurroundingWhitespaceAttribute.cs
+System.Windows.Markup/TypeExtension.cs
+System.Windows.Markup/TypeExtensionConverter.cs
+System.Windows.Markup/UidPropertyAttribute.cs
+System.Windows.Markup/UsableDuringInitializationAttribute.cs
+System.Windows.Markup/ValueSerializer.cs
+System.Windows.Markup/ValueSerializerAttribute.cs
+System.Windows.Markup/WhitespaceSignificantCollectionAttribute.cs
+System.Windows.Markup/XData.cs
+System.Windows.Markup/XamlDeferLoadAttribute.cs
+System.Windows.Markup/XamlSetMarkupExtensionAttribute.cs
+System.Windows.Markup/XamlSetMarkupExtensionEventArgs.cs
+System.Windows.Markup/XamlSetTypeConverterAttribute.cs
+System.Windows.Markup/XamlSetTypeConverterEventArgs.cs
+System.Windows.Markup/XamlSetValueEventArgs.cs
+System.Windows.Markup/XmlLangPropertyAttribute.cs
+System.Windows.Markup/XmlnsCompatibleWithAttribute.cs
+System.Windows.Markup/XmlnsDefinitionAttribute.cs
+System.Windows.Markup/XmlnsPrefixAttribute.cs
+System.Xaml.Permissions/XamlAccessLevel.cs
+System.Xaml.Permissions/XamlLoadPermission.cs
+System.Xaml.Schema/AllowedMemberLocations.cs
+System.Xaml.Schema/ShouldSerializeResult.cs
+System.Xaml.Schema/XamlCollectionKind.cs
+System.Xaml.Schema/XamlMemberInvoker.cs
+System.Xaml.Schema/XamlTypeInvoker.cs
+System.Xaml.Schema/XamlTypeName.cs
+System.Xaml.Schema/XamlTypeTypeConverter.cs
+System.Xaml.Schema/XamlValueConverter.cs
+System.Xaml/AmbientPropertyValue.cs
+System.Xaml/AttachableMemberIdentifier.cs
+System.Xaml/AttachablePropertyServices.cs
+System.Xaml/IAmbientProvider.cs
+System.Xaml/IAttachedPropertyStore.cs
+System.Xaml/IDestinationTypeProvider.cs
+System.Xaml/INamespacePrefixLookup.cs
+System.Xaml/IRootObjectProvider.cs
+System.Xaml/IXamlIndexingReader.cs
+System.Xaml/IXamlLineInfo.cs
+System.Xaml/IXamlLineInfoConsumer.cs
+System.Xaml/IXamlNameProvider.cs
+System.Xaml/IXamlNameResolver.cs
+System.Xaml/IXamlNamespaceResolver.cs
+System.Xaml/IXamlObjectWriterFactory.cs
+System.Xaml/IXamlSchemaContextProvider.cs
+System.Xaml/NamespaceDeclaration.cs
+System.Xaml/TypeExtensionMethods.cs
+System.Xaml/XamlBackgroundReader.cs
+System.Xaml/XamlDeferringLoader.cs
+System.Xaml/XamlDirective.cs
+System.Xaml/XamlDuplicateMemberException.cs
+System.Xaml/XamlException.cs
+System.Xaml/XamlInternalException.cs
+System.Xaml/XamlLanguage.cs
+System.Xaml/XamlMember.cs
+System.Xaml/XamlNodeList.cs
+System.Xaml/XamlNodeQueue.cs
+System.Xaml/XamlNodeType.cs
+System.Xaml/XamlObjectEventArgs.cs
+System.Xaml/XamlObjectReader.cs
+System.Xaml/XamlObjectReaderException.cs
+System.Xaml/XamlObjectReaderSettings.cs
+System.Xaml/XamlObjectWriter.cs
+System.Xaml/XamlObjectWriterException.cs
+System.Xaml/XamlObjectWriterSettings.cs
+System.Xaml/XamlParseException.cs
+System.Xaml/XamlReader.cs
+System.Xaml/XamlReaderSettings.cs
+System.Xaml/XamlSchemaContext.cs
+System.Xaml/XamlSchemaContextSettings.cs
+System.Xaml/XamlSchemaException.cs
+System.Xaml/XamlServices.cs
+System.Xaml/XamlType.cs
+System.Xaml/XamlWriter.cs
+System.Xaml/XamlWriterSettings.cs
+System.Xaml/XamlWriterStateManager.cs
+System.Xaml/XamlXmlReader.cs
+System.Xaml/XamlXmlReaderSettings.cs
+System.Xaml/XamlXmlWriter.cs
+System.Xaml/XamlXmlWriterException.cs
+System.Xaml/XamlXmlWriterSettings.cs
diff --git a/mcs/class/System.Xaml/System.Xaml/AmbientPropertyValue.cs b/mcs/class/System.Xaml/System.Xaml/AmbientPropertyValue.cs
new file mode 100644 (file)
index 0000000..c344969
--- /dev/null
@@ -0,0 +1,42 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public class AmbientPropertyValue
+       {
+               public AmbientPropertyValue (XamlMember property, object value)
+               {
+                       // null arguments are allowed (4.0RC).
+                       RetrievedProperty = property;
+                       Value = value;
+               }
+
+               public XamlMember RetrievedProperty { get; private set; }
+
+               public object Value { get; private set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/AttachableMemberIdentifier.cs b/mcs/class/System.Xaml/System.Xaml/AttachableMemberIdentifier.cs
new file mode 100644 (file)
index 0000000..5d49dc6
--- /dev/null
@@ -0,0 +1,75 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public class AttachableMemberIdentifier : IEquatable<AttachableMemberIdentifier>
+       {
+               public AttachableMemberIdentifier (Type declaringType, string memberName)
+               {
+                       DeclaringType = declaringType;
+                       MemberName = memberName;
+               }
+               
+               public Type DeclaringType { get; private set; }
+               public string MemberName { get; private set; }
+               
+               public static bool operator == (AttachableMemberIdentifier left, AttachableMemberIdentifier right)
+               {
+                       return IsNull (left) ? IsNull (right) : left.Equals (right);
+               }
+
+               static bool IsNull (AttachableMemberIdentifier a)
+               {
+                       return Object.ReferenceEquals (a, null);
+               }
+
+               public static bool operator != (AttachableMemberIdentifier left, AttachableMemberIdentifier right)
+               {
+                       return IsNull (left) ? !IsNull (right) : IsNull (right) || left.DeclaringType != right.DeclaringType || left.MemberName != right.MemberName;
+               }
+               
+               public bool Equals (AttachableMemberIdentifier other)
+               {
+                       return !IsNull (other) && DeclaringType == other.DeclaringType && MemberName == other.MemberName;
+               }
+
+               public override bool Equals (object obj)
+               {
+                       var a = obj as AttachableMemberIdentifier;
+                       return Equals (a);
+               }
+
+               public override int GetHashCode ()
+               {
+                       return (DeclaringType != null ? DeclaringType.GetHashCode () : 0) << 5 + (MemberName != null ? MemberName.GetHashCode () : 0);
+               }
+
+               public override string ToString ()
+               {
+                       return DeclaringType != null ? String.Concat (DeclaringType.FullName, ".", MemberName) : MemberName;
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/AttachablePropertyServices.cs b/mcs/class/System.Xaml/System.Xaml/AttachablePropertyServices.cs
new file mode 100644 (file)
index 0000000..575a281
--- /dev/null
@@ -0,0 +1,39 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public static class AttachablePropertyServices
+       {
+               public static void CopyPropertiesTo (object instance, KeyValuePair<AttachableMemberIdentifier,object> [] array, int index)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public static int GetAttachedPropertyCount (object instance)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public static bool RemoveProperty (object instance, AttachableMemberIdentifier name)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public static void SetProperty (object instance, AttachableMemberIdentifier name, object value)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public static bool TryGetProperty (object instance, AttachableMemberIdentifier name, out object value)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public static bool TryGetProperty<T> (object instance, AttachableMemberIdentifier name, out T value)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/ChangeLog b/mcs/class/System.Xaml/System.Xaml/ChangeLog
new file mode 100644 (file)
index 0000000..e68b84d
--- /dev/null
@@ -0,0 +1,347 @@
+2010-04-26  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlMember.cs : hack GetHashCode().
+
+2010-04-26  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReader.cs : now it can look into values and pick up
+         more required namespace prefixes.
+
+2010-04-22  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReader.cs, TypeExtensionMethods.cs : handle System.Type
+         as predefined type that returns Value instead of StartObject.
+         Rename some member getter methods to explicitly limit the scope to
+         object readers so far.
+
+2010-04-22  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReader.cs
+         XamlMember.cs
+         TypeExtensionMethods.cs
+         XamlType.cs : handle PositionalParameters, for Type type support.
+
+2010-04-20  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * TypeExtensionMethods.cs : add IsContentValue() for member and
+         return true for "_Initialization".
+       * XamlObjectReader.cs : use above.
+
+2010-04-20  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlType.cs : implement LookupPositionalParameters().
+
+2010-04-20  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReader.cs : use Type, not TargetType.
+
+2010-04-18  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlType.cs : do not return index property.
+       * TypeExtensionMethods.cs : return Initialization only for value nodes.
+       * XamlObjectReader.cs : member content can be either a value or a new
+         object. Fix certain EndObject transition to become EndMember, not
+         EndObject twice.
+
+2010-04-18  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReader.cs, XamlSchemaContext.cs, XamlLanguage.cs:
+         collect namespace declarations first. Remove extra [XmlnsPrefix]
+         on the assembly, and handle it specially in GetPreferredPrefix(),
+
+2010-04-18  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReader.cs : check constructible type. Remove extra ns node.
+
+2010-04-18  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlType.cs : ignore ReferenceConverter which is used for IList<T>.
+
+2010-04-16  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlType.cs : cache member lookup.
+
+2010-04-16  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlMember.cs : cosmetic equivalence change.
+
+2010-04-16  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlXmlReader.cs : Resolve generic type names. Process attribute
+         members.
+       * XamlLanguage.cs : add XamlTypeName-to-ClrType method.
+       * XmlSchemaContext.cs : extracted special type name handling to above.
+
+2010-04-16  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlType.cs : sort of reverted AllowedContentTypes.
+         msdn explanation is so wrong.
+
+2010-04-16  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlSchemaContext.cs : implement GetXamlDirective().
+
+2010-04-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlType.cs : implement AllowedContentTypes and ContentWrappers.
+
+2010-04-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlXmlReader.cs : handle types in clr-namespace.
+       * XamlType.cs : replaced Type-to-typename hack with better-working one.
+       * XamlLanguage,cs : add internal clr type name resolver method.
+       * XamlXmlWriter.cs : for Initialization, value is passed as a string,
+         so don't try to verify it with the object type.
+
+2010-04-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlXmlReader.cs : ongoing bugfixes to pass start object.
+
+2010-04-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReader.cs, TypeExtensionMethods.cs :
+         Value serialization improvements. Improved namespace handling.
+         Remove unused code.
+
+2010-04-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlXmlReader.cs : Return Member. Remove NIE.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlXmlWriter.cs : use TypeConverter to get string value to write.
+         (TimeSpan shows the difference; the type's ValueSerializer is null,
+         while TypeConverter is not, and gives the expected non-xsd output.)
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlSchemaContext.cs, TypeExtensionMethods.cs : reimplement some
+         GetXamlType() overloads. Protected one should be the actual
+         implementation.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlType.cs : fixed ToString() to ignore UnderlyingType.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlMember.cs : implemented ToString().
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlXmlReader.cs :
+         Skip irrelevant nodes. Remove extra member (Dispose).
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlXmlReader.cs : basic implementation.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReader.cs : Type is consumed as TypeExtension.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlServices.cs : fix Transform implementation.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlServices.cs : added a couple of missing methods.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReader.cs
+         XamlSchemaContext.cs
+         XamlObjectReaderException.cs
+         XamlXmlWriterException.cs
+         XamlXmlWriterSettings.cs
+         XamlObjectWriterException.cs
+         XamlParseException.cs
+         XamlInternalException.cs
+         XamlException.cs
+         XamlSchemaException.cs
+         XamlDuplicateMemberException.cs : a handful of corcompare fixes.
+
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlMember.cs
+         XamlDirective.cs
+         XamlType.cs
+         XamlLanguage.cs : implement (Lookup)ValueSerializer.
+
+2010-04-13  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlXmlWriter.cs :
+         Do not write element or attribute for Initialization.
+
+2010-04-13  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlXmlWriter.cs
+         XamlObjectWriter.cs
+         XamlWriterStateManager.cs : basic object writer implementation.
+         Needed non-trivial changes to state manager, as it turned out that
+         the state transition does not seem to be well designed to be common.
+
+2010-04-13  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlType.cs : IsArray, IsCollection and IsGeneric are based on
+         LookupCollectionKind(). Removed buggy documented behavior from the
+         lookup method too.
+
+2010-04-12  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlXmlWriter.cs : check null args.
+
+2010-04-12  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlWriterStateManager.cs, XamlXmlWriter.cs : extracted former
+         from latter, to reuse it in XamlObjectWriter too.
+
+2010-04-12  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlSchemaContext.cs
+         TypeExtensionMethods.cs
+         XamlType.cs : implement type lookup by name in schema context.
+
+2010-04-12  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReader.cs
+         XamlSchemaContext.cs
+         XamlMember.cs
+         XamlType.cs
+         XamlLanguage.cs : more type system implementation. Now it creates
+         XamlType indirectly all around.
+
+2010-04-12  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlType.cs : make implementation a bit cleaner.
+
+2010-04-12  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlLanguage.cs : implement namespaces properties.
+       * XamlType.cs : implement member lookup methods and IsConstructible.
+       * XamlMember.cs : do not use PropertyInfo's CanRead and CanWrite
+         which both return True for private getter and setter.
+       * TypeExtensionMethods.cs : add member retriever method that convers
+         Initialization (for XamlXmlWriter).
+       * XamlObjectReader.cs : use above.
+
+2010-04-11  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlSchemaContext.cs : implement some methods.
+       * XamlLanguage.cs : add assembly attributes.
+
+2010-04-11  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlXmlReader.cs : implemented cosmetic members.
+       * XamlSchemaContext.cs : looks like I missed all methods here.
+
+2010-04-11  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReader.cs : basic implementation.
+       * XamlReader.cs : implemented Skip().
+       * XamlType.cs : hacked GetAllMembers() for XamlObjectReader work.
+       * TypeExtensionMethods.cs : added an extension to get member value.
+
+2010-04-10  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlXmlWriter.cs : Process closing only once (disposing).
+         Close output only when required.
+
+2010-04-10  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * TypeExtensionMethods.cs, XamlType.cs :
+         implement LookupCustomAttributeProvider() and use it.
+       * XamlLanguage.cs : add internal const for xmlns ns.
+       * XamlServices.cs : implement some.
+
+2010-04-09  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlMember.cs
+         XamlDirective.cs
+         XamlType.cs : implement TypeConverter support.
+
+2010-04-09  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * TypeExtension.cs, TypeExtensionMethods.cs : renamed to avoid
+         confusion between Sys.Win.Markup.TypeExtension.
+
+2010-04-09  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * TypeExtension.cs
+         XamlMember.cs
+         XamlDirective.cs
+         XamlType.cs
+         XamlLanguage.cs : ongoing implementation.
+
+2010-04-09  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlType.cs : implemented lots of members.
+       * TypeExtension.cs : split out from above.
+
+2010-04-08  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlMember.cs, XamlDirective.cs :
+         Implemented lots of directive members.
+
+2010-04-08  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlDirective.cs
+         XamlLanguage.cs
+         XamlMember.cs
+         XamlType.cs : add more members and implement some.
+
+2010-04-08  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * AmbientPropertyValue.cs
+         AttachableMemberIdentifier.cs
+         AttachablePropertyServices.cs
+         ChangeLog
+         IAmbientProvider.cs
+         IAttachedPropertyStore.cs
+         IDestinationTypeProvider.cs
+         INamespacePrefixLookup.cs
+         IRootObjectProvider.cs
+         IXamlIndexingReader.cs
+         IXamlLineInfo.cs
+         IXamlLineInfoConsumer.cs
+         IXamlNameProvider.cs
+         IXamlNameResolver.cs
+         IXamlNamespaceResolver.cs
+         IXamlObjectWriterFactory.cs
+         IXamlSchemaContextProvider.cs
+         NamespaceDeclaration.cs
+         XamlBackgroundReader.cs
+         XamlDeferringLoader.cs
+         XamlDirective.cs
+         XamlDuplicateMemberException.cs
+         XamlException.cs
+         XamlInternalException.cs
+         XamlLanguage.cs
+         XamlMember.cs
+         XamlNodeList.cs
+         XamlNodeQueue.cs
+         XamlNodeType.cs
+         XamlObjectEventArgs.cs
+         XamlObjectReader.cs
+         XamlObjectReaderException.cs
+         XamlObjectReaderSettings.cs
+         XamlObjectWriter.cs
+         XamlObjectWriterException.cs
+         XamlObjectWriterSettings.cs
+         XamlParseException.cs
+         XamlReader.cs
+         XamlReaderSettings.cs
+         XamlSchemaContext.cs
+         XamlSchemaContextSettings.cs
+         XamlSchemaException.cs
+         XamlServices.cs
+         XamlType.cs
+         XamlWriter.cs
+         XamlWriterSettings.cs
+         XamlXmlReader.cs
+         XamlXmlReaderSettings.cs
+         XamlXmlWriter.cs
+         XamlXmlWriterException.cs
+         XamlXmlWriterSettings.cs : initial checkin.
diff --git a/mcs/class/System.Xaml/System.Xaml/IAmbientProvider.cs b/mcs/class/System.Xaml/System.Xaml/IAmbientProvider.cs
new file mode 100644 (file)
index 0000000..211edba
--- /dev/null
@@ -0,0 +1,36 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public interface IAmbientProvider
+       {
+               IEnumerable<Object> GetAllAmbientValues (params XamlType[] types);
+               IEnumerable<AmbientPropertyValue> GetAllAmbientValues (IEnumerable<XamlType> ceilingTypes, params XamlMember [] properties);
+               Object GetFirstAmbientValue (params XamlType [] types);
+               AmbientPropertyValue GetFirstAmbientValue (IEnumerable<XamlType> ceilingTypes, params XamlMember [] properties);
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/IAttachedPropertyStore.cs b/mcs/class/System.Xaml/System.Xaml/IAttachedPropertyStore.cs
new file mode 100644 (file)
index 0000000..81fa7b0
--- /dev/null
@@ -0,0 +1,37 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public interface IAttachedPropertyStore
+       {
+               int PropertyCount { get; }
+               void CopyPropertiesTo (KeyValuePair<AttachableMemberIdentifier, object>[] array, int index);
+               bool RemoveProperty (AttachableMemberIdentifier attachableMemberIdentifier);
+               void SetProperty (AttachableMemberIdentifier attachableMemberIdentifier, object value);
+               bool TryGetProperty (AttachableMemberIdentifier attachableMemberIdentifier, out object value);
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/IDestinationTypeProvider.cs b/mcs/class/System.Xaml/System.Xaml/IDestinationTypeProvider.cs
new file mode 100644 (file)
index 0000000..d08a2f3
--- /dev/null
@@ -0,0 +1,33 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public interface IDestinationTypeProvider
+       {
+               Type GetDestinationType ();
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/INamespacePrefixLookup.cs b/mcs/class/System.Xaml/System.Xaml/INamespacePrefixLookup.cs
new file mode 100644 (file)
index 0000000..62400af
--- /dev/null
@@ -0,0 +1,33 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public interface INamespacePrefixLookup
+       {
+               string LookupPrefix (string ns);
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/IRootObjectProvider.cs b/mcs/class/System.Xaml/System.Xaml/IRootObjectProvider.cs
new file mode 100644 (file)
index 0000000..eb1dd4c
--- /dev/null
@@ -0,0 +1,32 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public interface IRootObjectProvider
+       {
+               object RootObject { get; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/IXamlIndexingReader.cs b/mcs/class/System.Xaml/System.Xaml/IXamlIndexingReader.cs
new file mode 100644 (file)
index 0000000..2587d49
--- /dev/null
@@ -0,0 +1,33 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public interface IXamlIndexingReader
+       {
+               int Count { get; }
+               int CurrentIndex { get; set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/IXamlLineInfo.cs b/mcs/class/System.Xaml/System.Xaml/IXamlLineInfo.cs
new file mode 100644 (file)
index 0000000..31702c7
--- /dev/null
@@ -0,0 +1,34 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public interface IXamlLineInfo
+       {
+               bool HasLineInfo { get; }
+               int LineNumber { get; }
+               int LinePosition { get; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/IXamlLineInfoConsumer.cs b/mcs/class/System.Xaml/System.Xaml/IXamlLineInfoConsumer.cs
new file mode 100644 (file)
index 0000000..d44e5fb
--- /dev/null
@@ -0,0 +1,33 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public interface IXamlLineInfoConsumer
+       {
+               bool ShouldProvideLineInfo { get; }
+               void SetLineInfo (int lineNumber, int linePosition);
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/IXamlNameProvider.cs b/mcs/class/System.Xaml/System.Xaml/IXamlNameProvider.cs
new file mode 100644 (file)
index 0000000..f933845
--- /dev/null
@@ -0,0 +1,32 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public interface IXamlNameProvider
+       {
+               string GetName (object value);
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/IXamlNameResolver.cs b/mcs/class/System.Xaml/System.Xaml/IXamlNameResolver.cs
new file mode 100644 (file)
index 0000000..a958510
--- /dev/null
@@ -0,0 +1,38 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public interface IXamlNameResolver
+       {
+               bool IsFixupTokenAvailable { get; }
+               event EventHandler OnNameScopeInitializationComplete;
+               object GetFixupToken (IEnumerable<string> names);
+               object GetFixupToken (IEnumerable<string> names, bool canAssignDirectly);
+               IEnumerable<KeyValuePair<string, object>> GetAllNamesAndValuesInScope ();
+               object Resolve (string name);
+               object Resolve (string name, out bool isFullyInitialized);
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/IXamlNamespaceResolver.cs b/mcs/class/System.Xaml/System.Xaml/IXamlNamespaceResolver.cs
new file mode 100644 (file)
index 0000000..a31684e
--- /dev/null
@@ -0,0 +1,33 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public interface IXamlNamespaceResolver
+       {
+               string GetNamespace (string prefix);
+               IEnumerable<NamespaceDeclaration> GetNamespacePrefixes ();
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/IXamlObjectWriterFactory.cs b/mcs/class/System.Xaml/System.Xaml/IXamlObjectWriterFactory.cs
new file mode 100644 (file)
index 0000000..be64098
--- /dev/null
@@ -0,0 +1,33 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public interface IXamlObjectWriterFactory
+       {
+               XamlObjectWriterSettings GetParentSettings ();
+               XamlObjectWriter GetXamlObjectWriter (XamlObjectWriterSettings settings);
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/IXamlSchemaContextProvider.cs b/mcs/class/System.Xaml/System.Xaml/IXamlSchemaContextProvider.cs
new file mode 100644 (file)
index 0000000..8691a84
--- /dev/null
@@ -0,0 +1,33 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public interface IXamlSchemaContextProvider
+       {
+               XamlSchemaContext SchemaContext { get; }
+       }
+
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/NamespaceDeclaration.cs b/mcs/class/System.Xaml/System.Xaml/NamespaceDeclaration.cs
new file mode 100644 (file)
index 0000000..abfaff0
--- /dev/null
@@ -0,0 +1,40 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public class NamespaceDeclaration
+       {
+               public NamespaceDeclaration (string ns, string prefix)
+               {
+                       // null arguments are allowed.
+                       Namespace = ns;
+                       Prefix = prefix;
+               }
+               
+               public string Namespace { get; private set; }
+               public string Prefix { get; private set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/TypeExtensionMethods.cs b/mcs/class/System.Xaml/System.Xaml/TypeExtensionMethods.cs
new file mode 100644 (file)
index 0000000..2baf023
--- /dev/null
@@ -0,0 +1,199 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Xaml
+{
+       static class TypeExtensionMethods
+       {
+               // FIXME: this likely needs to be replaced with XamlTypeName
+               public static string GetXamlName (this Type type)
+               {
+                       if (!type.IsNested)
+                               return type.Name;
+                       return type.DeclaringType.GetXamlName () + "+" + type.Name;
+               }
+
+               #region inheritance search and custom attribute provision
+
+               public static T GetCustomAttribute<T> (this ICustomAttributeProvider type, bool inherit) where T : Attribute
+               {
+                       foreach (var a in type.GetCustomAttributes (typeof (T), inherit))
+                               return (T) (object) a;
+                       return null;
+               }
+
+               public static T GetCustomAttribute<T> (this XamlType type) where T : Attribute
+               {
+                       if (type.UnderlyingType == null)
+                               return null;
+
+                       T ret = type.CustomAttributeProvider.GetCustomAttribute<T> (true);
+                       if (ret != null)
+                               return ret;
+                       if (type.BaseType != null)
+                               return type.BaseType.GetCustomAttribute<T> ();
+                       return null;
+               }
+
+               public static bool ImplementsAnyInterfacesOf (this Type type, params Type [] definitions)
+               {
+                       return definitions.Any (t => ImplementsInterface (type, t));
+               }
+
+               public static bool ImplementsInterface (this Type type, Type definition)
+               {
+                       if (type == null)
+                               throw new ArgumentNullException ("type");
+                       if (definition == null)
+                               throw new ArgumentNullException ("definition");
+
+                       foreach (var iface in type.GetInterfaces ())
+                               if (iface == definition || (iface.IsGenericType && iface.GetGenericTypeDefinition () == definition))
+                                       return true;
+                       return false;
+               }
+               
+               #endregion
+               
+               #region type conversion and member value retrieval
+               
+               public static string GetStringValue (this XamlType xt, object obj, INamespacePrefixLookup prefixLookup)
+               {
+                       if (obj == null)
+                               return String.Empty;
+                       if (obj is Type)
+                               return new XamlTypeName (xt.SchemaContext.GetXamlType ((Type) obj)).ToString (prefixLookup);
+
+                       if (obj is DateTime)
+                               // FIXME: DateTimeValueSerializer should apply
+                               return (string) TypeDescriptor.GetConverter (typeof (DateTime)).ConvertToInvariantString (obj);
+                       else
+                               return (string) xt.ConvertObject (obj, typeof (string));
+               }
+
+               public static object ConvertObject (this XamlType xt, object target, Type explicitTargetType)
+               {
+                       return DoConvert (xt.TypeConverter, target, explicitTargetType ?? xt.UnderlyingType);
+               }
+               
+               public static object GetMemberValueForObjectReader (this XamlMember xm, XamlType xt, object target, INamespacePrefixLookup prefixLookup)
+               {
+                       object native = GetPropertyOrFieldValueForObjectReader (xm, xt, target, prefixLookup);
+                       var convertedType = xm.Type == null ? null : xm.Type.UnderlyingType;
+                       return DoConvert (xm.TypeConverter, native, convertedType);
+               }
+               
+               static object DoConvert (XamlValueConverter<TypeConverter> converter, object value, Type targetType)
+               {
+                       // First get member value, then convert it to appropriate target type.
+                       var tc = converter != null ? converter.ConverterInstance : null;
+                       if (tc != null && targetType != null && tc.CanConvertTo (targetType))
+                               return tc.ConvertTo (value, targetType);
+                       return value;
+               }
+
+               static object GetPropertyOrFieldValueForObjectReader (this XamlMember xm, XamlType xt, object target, INamespacePrefixLookup prefixLookup)
+               {
+                       // FIXME: should this be done here??
+                       if (xm == XamlLanguage.Initialization)
+                               return target;
+                       if (xm == XamlLanguage.PositionalParameters) {
+                               var argdefs = xt.GetConstructorArguments ().ToArray ();
+                               string [] args = new string [argdefs.Length];
+                               for (int i = 0; i < args.Length; i++) {
+                                       var am = argdefs [i];
+                                       args [i] = GetStringValue (am.Type, GetMemberValueForObjectReader (am, xt, target, prefixLookup), prefixLookup);
+                               }
+                               return String.Join (", ", args);
+                       }
+
+                       var mi = xm.UnderlyingMember;
+                       var fi = mi as FieldInfo;
+                       if (fi != null)
+                               return fi.GetValue (target);
+                       var pi = mi as PropertyInfo;
+                       if (pi != null)
+                               return pi.GetValue (target, null);
+
+                       throw new NotImplementedException (String.Format ("Cannot get value for {0}", xm));
+               }
+               
+               #endregion
+
+               public static bool IsContentValue (this XamlMember member)
+               {
+                       if (member == XamlLanguage.Initialization)
+                               return true;
+                       if (member == XamlLanguage.PositionalParameters)
+                               return true;
+                       return IsContentValue (member.Type);
+               }
+
+               public static bool IsContentValue (this XamlType type)
+               {
+                       var t = type.UnderlyingType;
+                       if (Type.GetTypeCode (t) != TypeCode.Object)
+                               return true;
+                       else if (t == typeof (Type) || t == typeof (TimeSpan) || t == typeof (Uri)) // special predefined types
+                               return true;
+                       return false;
+               }
+
+               public static IEnumerable<XamlMember> GetAllReadWriteMembers (this XamlType type)
+               {
+                       // FIXME: find out why only TypeExtension yields this directive. Seealso XamlObjectReaderTest
+                       if (type == XamlLanguage.Type) {
+                               yield return XamlLanguage.PositionalParameters;
+                               yield break;
+                       }
+
+                       if (type.IsContentValue ())
+                               yield return XamlLanguage.Initialization;
+
+                       foreach (var m in type.GetAllMembers ())
+                               yield return m;
+               }
+
+               public static bool ListEquals (this IList<XamlType> a1, IList<XamlType> a2)
+               {
+                       if (a1 == null || a1.Count == 0)
+                               return a2 == null || a2.Count == 0;
+                       if (a2 == null || a2.Count == 0)
+                               return false;
+                       if (a1.Count != a2.Count)
+                               return false;
+                       for (int i = 0; i < a1.Count; i++)
+                               if (a1 [i] != a2 [i])
+                                       return false;
+                       return true;
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlBackgroundReader.cs b/mcs/class/System.Xaml/System.Xaml/XamlBackgroundReader.cs
new file mode 100644 (file)
index 0000000..eea7175
--- /dev/null
@@ -0,0 +1,86 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public class XamlBackgroundReader : XamlReader, IXamlLineInfo
+       {
+               public XamlBackgroundReader (XamlReader wrappedReader)
+               {
+                       throw new NotImplementedException ();
+               }
+               
+               public bool HasLineInfo {
+                       get { throw new NotImplementedException (); }
+               }
+               public override bool IsEof {
+                       get { throw new NotImplementedException (); }
+               }
+               public int LineNumber {
+                       get { throw new NotImplementedException (); }
+               }
+               public int LinePosition {
+                       get { throw new NotImplementedException (); }
+               }
+               public override XamlMember Member {
+                       get { throw new NotImplementedException (); }
+               }
+               public override NamespaceDeclaration Namespace {
+                       get { throw new NotImplementedException (); }
+               }
+               public override XamlNodeType NodeType {
+                       get { throw new NotImplementedException (); }
+               }
+               public override XamlSchemaContext SchemaContext {
+                       get { throw new NotImplementedException (); }
+               }
+               public override XamlType Type {
+                       get { throw new NotImplementedException (); }
+               }
+               public override object Value {
+                       get { throw new NotImplementedException (); }
+               }
+
+               protected override void Dispose (bool disposing)
+               {
+                       throw new NotImplementedException ();
+               }
+               
+               public override bool Read ()
+               {
+                       throw new NotImplementedException ();
+               }
+               
+               public void StartThread ()
+               {
+                       throw new NotImplementedException ();
+               }
+               
+               public void StartThread (string threadName)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlDeferringLoader.cs b/mcs/class/System.Xaml/System.Xaml/XamlDeferringLoader.cs
new file mode 100644 (file)
index 0000000..058e247
--- /dev/null
@@ -0,0 +1,33 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public abstract class XamlDeferringLoader
+       {
+               public abstract object Load (XamlReader xamlReader, IServiceProvider serviceProvider);
+               public abstract XamlReader Save (object value, IServiceProvider serviceProvider);
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlDirective.cs b/mcs/class/System.Xaml/System.Xaml/XamlDirective.cs
new file mode 100644 (file)
index 0000000..65e4dcc
--- /dev/null
@@ -0,0 +1,181 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Reflection;
+using System.Xaml.Schema;
+
+namespace System.Xaml
+{
+       public class XamlDirective : XamlMember
+       {
+               class DirectiveMemberInvoker : XamlMemberInvoker
+               {
+                       XamlDirective directive;
+
+                       public DirectiveMemberInvoker (XamlDirective directive)
+                       {
+                       }
+               }
+
+               public XamlDirective (string xamlNamespace, string name)
+                       : this (new string [] {xamlNamespace}, name, new XamlType (typeof (object), new XamlSchemaContext (new XamlSchemaContextSettings ())), null, AllowedMemberLocations.Any)
+               {
+                       if (xamlNamespace == null)
+                               throw new ArgumentNullException ("xamlNamespace");
+                       is_unknown = true;
+               }
+
+               public XamlDirective (IEnumerable<string> xamlNamespaces, string name, XamlType xamlType, XamlValueConverter<TypeConverter> typeConverter, AllowedMemberLocations allowedLocation)
+                       : base (true, xamlNamespaces != null ? xamlNamespaces.FirstOrDefault () : null, name)
+               {
+                       if (xamlNamespaces == null)
+                               throw new ArgumentNullException ("xamlNamespaces");
+                       if (xamlType == null)
+                               throw new ArgumentNullException ("xamlType");
+
+                       type = xamlType;
+                       xaml_namespaces = new List<string> (xamlNamespaces);
+                       AllowedLocation = allowedLocation;
+                       type_converter = typeConverter;
+                       
+                       invoker = new DirectiveMemberInvoker (this);
+               }
+
+               public AllowedMemberLocations AllowedLocation { get; private set; }
+               XamlValueConverter<TypeConverter> type_converter;
+               XamlType type;
+               XamlMemberInvoker invoker;
+               bool is_unknown;
+               IList<string> xaml_namespaces;
+
+               // this is for XamlLanguage.UnknownContent
+               internal bool InternalIsUnknown {
+                       set { is_unknown = value; }
+               }
+
+               public override int GetHashCode ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public override IList<string> GetXamlNamespaces ()
+               {
+                       return xaml_namespaces;
+               }
+
+               protected override sealed ICustomAttributeProvider LookupCustomAttributeProvider ()
+               {
+                       return null; // as documented.
+               }
+
+               protected override sealed XamlValueConverter<XamlDeferringLoader> LookupDeferringLoader ()
+               {
+                       return null; // as documented.
+               }
+
+               protected override sealed IList<XamlMember> LookupDependsOn ()
+               {
+                       return null; // as documented.
+               }
+
+               protected override sealed XamlMemberInvoker LookupInvoker ()
+               {
+                       return invoker;
+               }
+
+               protected override sealed bool LookupIsAmbient ()
+               {
+                       return false;
+               }
+
+               protected override sealed bool LookupIsEvent ()
+               {
+                       return false;
+               }
+
+               protected override sealed bool LookupIsReadOnly ()
+               {
+                       return false;
+               }
+
+               protected override sealed bool LookupIsReadPublic ()
+               {
+                       return true;
+               }
+
+               protected override sealed bool LookupIsUnknown ()
+               {
+                       return is_unknown;
+               }
+
+               protected override sealed bool LookupIsWriteOnly ()
+               {
+                       return false;
+               }
+
+               protected override sealed bool LookupIsWritePublic ()
+               {
+                       return true;
+               }
+
+               protected override sealed XamlType LookupTargetType ()
+               {
+                       return null;
+               }
+
+               protected override sealed XamlType LookupType ()
+               {
+                       return type;
+               }
+
+               protected override sealed XamlValueConverter<TypeConverter> LookupTypeConverter ()
+               {
+                       if (type_converter == null)
+                               type_converter = base.LookupTypeConverter ();
+                       return type_converter;
+               }
+
+               protected override sealed MethodInfo LookupUnderlyingGetter ()
+               {
+                       return null;
+               }
+
+               protected override sealed MemberInfo LookupUnderlyingMember ()
+               {
+                       return null;
+               }
+
+               protected override sealed MethodInfo LookupUnderlyingSetter ()
+               {
+                       return null;
+               }
+
+               public override string ToString ()
+               {
+                       return String.IsNullOrEmpty (PreferredXamlNamespace) ? Name : String.Concat ("{", PreferredXamlNamespace, "}", Name);
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlDuplicateMemberException.cs b/mcs/class/System.Xaml/System.Xaml/XamlDuplicateMemberException.cs
new file mode 100644 (file)
index 0000000..10e1858
--- /dev/null
@@ -0,0 +1,72 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Runtime.Serialization;
+
+namespace System.Xaml
+{
+       [Serializable]
+       public class XamlDuplicateMemberException : XamlException
+       {
+               public XamlDuplicateMemberException ()
+                       : this ("Duplicate members are found in the type")
+               {
+               }
+
+               public XamlDuplicateMemberException (XamlMember member, XamlType type)
+                       : this (String.Format ("duplicate member '{0}' in type '{1}'", member, type))
+               {
+                       DuplicateMember = member;
+                       ParentType = type;
+               }
+
+               public XamlDuplicateMemberException (string message)
+                       : this (message, null)
+               {
+               }
+
+               public XamlDuplicateMemberException (string message, Exception innerException)
+                       : base (message, innerException)
+               {
+               }
+
+               protected XamlDuplicateMemberException (SerializationInfo info, StreamingContext context)
+                       : base (info, context)
+               {
+                       DuplicateMember = (XamlMember) info.GetValue ("member", typeof (XamlMember));
+                       ParentType = (XamlType) info.GetValue ("type", typeof (XamlType));
+               }
+
+               public XamlMember DuplicateMember { get; set; }
+               public XamlType ParentType { get; set; }
+
+               public override void GetObjectData (SerializationInfo info, StreamingContext context)
+               {
+                       base.GetObjectData (info, context);
+                       info.AddValue ("member", DuplicateMember);
+                       info.AddValue ("type", ParentType);
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlException.cs b/mcs/class/System.Xaml/System.Xaml/XamlException.cs
new file mode 100644 (file)
index 0000000..216a606
--- /dev/null
@@ -0,0 +1,83 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Runtime.Serialization;
+
+namespace System.Xaml
+{
+       [Serializable]
+       public class XamlException : Exception
+       {
+               public XamlException ()
+                       : this ("XAML error")
+               {
+               }
+
+               public XamlException (string message)
+                       : this (message, null)
+               {
+               }
+
+               public XamlException (string message, Exception innerException)
+                       : this (message, null, 0, 0)
+               {
+               }
+
+               static string FormatLine (string message, int lineNumber, int linePosition)
+               {
+                       if (lineNumber <= 0)
+                               return message;
+                       if (linePosition <= 0)
+                               return String.Format ("{0} at line {1}", message, lineNumber);
+                       return String.Format ("{0} at line {1}, position {2}", message, lineNumber, linePosition);
+               }
+
+               public XamlException (string message, Exception innerException, int lineNumber, int linePosition)
+                       : base (message, innerException)
+               {
+                       LineNumber = lineNumber;
+                       LinePosition = linePosition;
+               }
+
+               protected XamlException (SerializationInfo info, StreamingContext context)
+                       : base (info, context)
+               {
+                       LineNumber = info.GetInt32 ("lineNumber");
+                       LinePosition = info.GetInt32 ("linePosition");
+               }
+
+               public int LineNumber { get; protected set; }
+               public int LinePosition { get; protected set; }
+               public override string Message {
+                       get { return FormatLine (base.Message, LineNumber, LinePosition); }
+               }
+
+               public override void GetObjectData (SerializationInfo info, StreamingContext context)
+               {
+                       info.AddValue ("lineNumber", LineNumber);
+                       info.AddValue ("linePosition", LinePosition);
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlInternalException.cs b/mcs/class/System.Xaml/System.Xaml/XamlInternalException.cs
new file mode 100644 (file)
index 0000000..d98aa4c
--- /dev/null
@@ -0,0 +1,53 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Runtime.Serialization;
+
+namespace System.Xaml
+{
+       [Serializable]
+       public class XamlInternalException : XamlException
+       {
+               public XamlInternalException ()
+                       : this ("XAML internal error")
+               {
+               }
+
+               public XamlInternalException (string message)
+                       : this (message, null)
+               {
+               }
+
+               public XamlInternalException (string message, Exception innerException)
+                       : base (message, innerException)
+               {
+               }
+
+               protected XamlInternalException (SerializationInfo info, StreamingContext context)
+                       : base (info, context)
+               {
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlLanguage.cs b/mcs/class/System.Xaml/System.Xaml/XamlLanguage.cs
new file mode 100644 (file)
index 0000000..7113059
--- /dev/null
@@ -0,0 +1,286 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Globalization;
+using System.Linq;
+using System.Reflection;
+using System.Xaml.Schema;
+using System.Windows.Markup;
+
+[assembly:XmlnsDefinition (System.Xaml.XamlLanguage.Xaml2006Namespace, "System.Windows.Markup")] // FIXME: verify.
+
+namespace System.Xaml
+{
+       public static class XamlLanguage
+       {
+               public const string Xaml2006Namespace = "http://schemas.microsoft.com/winfx/2006/xaml";
+               public const string Xml1998Namespace = "http://www.w3.org/XML/1998/namespace";
+               internal const string Xmlns2000Namespace = "http://www.w3.org/2000/xmlns/";
+
+               static readonly XamlSchemaContext sctx = new XamlSchemaContext (new Assembly [] {typeof (XamlType).Assembly});
+
+               static XamlType XT<T> ()
+               {
+                       return sctx.GetXamlType (typeof (T));
+               }
+
+               internal static readonly bool InitializingDirectives;
+               internal static readonly bool InitializingTypes;
+
+               static XamlLanguage ()
+               {
+                       InitializingTypes = true;
+                       // types
+
+                       Array = XT<ArrayExtension> ();
+                       Boolean = XT<bool> ();
+                       Byte = XT<byte> ();
+                       Char = XT<char> ();
+                       Decimal = XT<decimal> ();
+                       Double = XT<double> ();
+                       Int16 = XT<short> ();
+                       Int32 = XT<int> ();
+                       Int64 = XT<long> ();
+                       Member = XT<MemberDefinition> ();
+                       Null = XT<NullExtension> ();
+                       Object = XT<object> ();
+                       Property = XT<PropertyDefinition> ();
+                       Reference = XT<Reference> ();
+                       Single = XT<float> ();
+                       Static = XT<StaticExtension> ();
+                       String = XT<string> ();
+                       TimeSpan = XT<TimeSpan> ();
+                       Type = XT<TypeExtension> ();
+                       Uri = XT<Uri> ();
+                       XData = XT<XData> ();
+
+                       InitializingTypes = false;
+
+                       AllTypes = new ReadOnlyCollection<XamlType> (new XamlType [] {Array, Boolean, Byte, Char, Decimal, Double, Int16, Int32, Int64, Member, Null, Object, Property, Reference, Single, Static, String, TimeSpan, Type, Uri, XData});
+
+                       // directives
+
+                       // Looks like predefined XamlDirectives have no ValueSerializer. 
+                       // To handle this situation, differentiate them from non-primitive XamlMembers.
+                       InitializingDirectives = true;
+
+                       var nss = new string [] {XamlLanguage.Xaml2006Namespace};
+                       var nssXml = new string [] {XamlLanguage.Xml1998Namespace};
+
+                       Arguments = new XamlDirective (nss, "Arguments", XT<List<object>> (), null, AllowedMemberLocations.Any);
+                       AsyncRecords = new XamlDirective (nss, "AsyncRecords", XT<string> (), null, AllowedMemberLocations.Attribute);
+                       Base = new XamlDirective (nssXml, "base", XT<string> (), null, AllowedMemberLocations.Attribute);
+                       Class = new XamlDirective (nss, "Class", XT<string> (), null, AllowedMemberLocations.Attribute);
+                       ClassAttributes = new XamlDirective (nss, "ClassAttributes", XT<List<Attribute>> (), null, AllowedMemberLocations.MemberElement);
+                       ClassModifier = new XamlDirective (nss, "ClassModifier", XT<string> (), null, AllowedMemberLocations.Attribute);
+                       Code = new XamlDirective (nss, "Code", XT<string> (), null, AllowedMemberLocations.Attribute);
+                       ConnectionId = new XamlDirective (nss, "ConnectionId", XT<string> (), null, AllowedMemberLocations.Any);
+                       FactoryMethod = new XamlDirective (nss, "FactoryMethod", XT<string> (), null, AllowedMemberLocations.Any);
+                       FieldModifier = new XamlDirective (nss, "FieldModifier", XT<string> (), null, AllowedMemberLocations.Attribute);
+                       Initialization = new XamlDirective (nss, "_Initialization", XT<object> (), null, AllowedMemberLocations.Any);
+                       Items = new XamlDirective (nss, "_Items", XT<List<object>> (), null, AllowedMemberLocations.Any);
+                       Key = new XamlDirective (nss, "Key", XT<object> (), null, AllowedMemberLocations.Any);
+                       Lang = new XamlDirective (nssXml, "lang", XT<string> (), null, AllowedMemberLocations.Attribute);
+                       Members = new XamlDirective (nss, "Members", XT<List<MemberDefinition>> (), null, AllowedMemberLocations.MemberElement);
+                       Name = new XamlDirective (nss, "Name", XT<string> (), null, AllowedMemberLocations.Attribute);
+                       PositionalParameters = new XamlDirective (nss, "_PositionalParameters", XT<List<object>> (), null, AllowedMemberLocations.Any);
+                       Space = new XamlDirective (nssXml, "space", XT<string> (), null, AllowedMemberLocations.Attribute);
+                       Subclass = new XamlDirective (nss, "Subclass", XT<string> (), null, AllowedMemberLocations.Attribute);
+                       SynchronousMode = new XamlDirective (nss, "SynchronousMode", XT<string> (), null, AllowedMemberLocations.Attribute);
+                       Shared = new XamlDirective (nss, "Shared", XT<string> (), null, AllowedMemberLocations.Attribute);
+                       TypeArguments = new XamlDirective (nss, "TypeArguments", XT<string> (), null, AllowedMemberLocations.Attribute);
+                       Uid = new XamlDirective (nss, "Uid", XT<string> (), null, AllowedMemberLocations.Attribute);
+                       UnknownContent = new XamlDirective (nss, "_UnknownContent", XT<object> (), null, AllowedMemberLocations.MemberElement) { InternalIsUnknown = true };
+
+                       AllDirectives = new ReadOnlyCollection<XamlDirective> (new XamlDirective [] {Arguments, AsyncRecords, Base, Class, ClassAttributes, ClassModifier, Code, ConnectionId, FactoryMethod, FieldModifier, Initialization, Items, Key, Lang, Members, Name, PositionalParameters, Space, Subclass, SynchronousMode, Shared, TypeArguments, Uid, UnknownContent});
+
+                       InitializingDirectives = false;
+               }
+
+               static readonly string [] xaml_nss = new string [] {Xaml2006Namespace};
+
+               public static IList<string> XamlNamespaces {
+                       get { return xaml_nss; }
+               }
+
+               static readonly string [] xml_nss = new string [] {Xml1998Namespace};
+
+               public static IList<string> XmlNamespaces {
+                       get { return xml_nss; }
+               }
+
+               public static ReadOnlyCollection<XamlDirective> AllDirectives { get; private set; }
+
+               public static XamlDirective Arguments { get; private set; }
+               public static XamlDirective AsyncRecords { get; private set; }
+               public static XamlDirective Base { get; private set; }
+               public static XamlDirective Class { get; private set; }
+               public static XamlDirective ClassAttributes { get; private set; }
+               public static XamlDirective ClassModifier { get; private set; }
+               public static XamlDirective Code { get; private set; }
+               public static XamlDirective ConnectionId { get; private set; }
+               public static XamlDirective FactoryMethod { get; private set; }
+               public static XamlDirective FieldModifier { get; private set; }
+               public static XamlDirective Initialization { get; private set; }
+               public static XamlDirective Items { get; private set; }
+               public static XamlDirective Key { get; private set; }
+               public static XamlDirective Lang { get; private set; }
+               public static XamlDirective Members { get; private set; }
+               public static XamlDirective Name { get; private set; }
+               public static XamlDirective PositionalParameters { get; private set; }
+               public static XamlDirective Subclass { get; private set; }
+               public static XamlDirective SynchronousMode { get; private set; }
+               public static XamlDirective Shared { get; private set; }
+               public static XamlDirective Space { get; private set; }
+               public static XamlDirective TypeArguments { get; private set; }
+               public static XamlDirective Uid { get; private set; }
+               public static XamlDirective UnknownContent { get; private set; }
+
+               public static ReadOnlyCollection<XamlType> AllTypes { get; private set; }
+
+               public static XamlType Array { get; private set; }
+               public static XamlType Boolean { get; private set; }
+               public static XamlType Byte { get; private set; }
+               public static XamlType Char { get; private set; }
+               public static XamlType Decimal { get; private set; }
+               public static XamlType Double { get; private set; }
+               public static XamlType Int16 { get; private set; }
+               public static XamlType Int32 { get; private set; }
+               public static XamlType Int64 { get; private set; }
+               public static XamlType Member { get; private set; }
+               public static XamlType Null { get; private set; }
+               public static XamlType Object { get; private set; }
+               public static XamlType Property { get; private set; }
+               public static XamlType Reference { get; private set; }
+               public static XamlType Single { get; private set; }
+               public static XamlType Static { get; private set; }
+               public static XamlType String { get; private set; }
+               public static XamlType TimeSpan { get; private set; }
+               public static XamlType Type { get; private set; }
+               public static XamlType Uri { get; private set; }
+               public static XamlType XData { get; private set; }
+
+               internal static bool IsValidXamlName (string name)
+               {
+                       if (string.IsNullOrEmpty (name))
+                               return false;
+                       if (!IsValidXamlName (name [0], true))
+                               return false;
+                       foreach (char c in name)
+                               if (!IsValidXamlName (c, false))
+                                       return false;
+                       return true;
+               }
+
+               static bool IsValidXamlName (char c, bool first)
+               {
+                       if (c == '_')
+                               return true;
+                       switch (char.GetUnicodeCategory (c)) {
+                       case UnicodeCategory.LowercaseLetter:
+                       case UnicodeCategory.UppercaseLetter:
+                       case UnicodeCategory.TitlecaseLetter:
+                       case UnicodeCategory.OtherLetter:
+                       case UnicodeCategory.LetterNumber:
+                               return true;
+                       case UnicodeCategory.NonSpacingMark:
+                       case UnicodeCategory.DecimalDigitNumber:
+                       case UnicodeCategory.SpacingCombiningMark:
+                       case UnicodeCategory.ModifierLetter:
+                               return !first;
+                       default:
+                               return false;
+                       }
+               }
+
+               internal static XamlType GetSpecialXaml2006Type (string name)
+               {
+                       // FIXME: I'm not really sure if these *special* names 
+                       // should be resolved here and there. There just does
+                       // not seem to be any other appropriate places.
+                       switch (name) {
+                       case "Array":
+                               return XamlLanguage.Array;
+                       case "Member":
+                               return XamlLanguage.Member;
+                       case "Null":
+                               return XamlLanguage.Null;
+                       case "Property":
+                               return XamlLanguage.Property;
+                       case "Static":
+                               return XamlLanguage.Static;
+                       case "Type":
+                               return XamlLanguage.Type;
+                       }
+                       return null;
+               }
+
+               static readonly int clr_ns_len = "clr-namespace:".Length;
+               static readonly int clr_ass_len = "assembly=".Length;
+
+               internal static Type ResolveXamlTypeName (string xmlNamespace, string xmlLocalName, IList<XamlTypeName> typeArguments, IXamlNamespaceResolver nsResolver)
+               {
+                       string ns = xmlNamespace;
+                       string name = xmlLocalName;
+
+                       if (ns == XamlLanguage.Xaml2006Namespace) {
+                               var xt = GetSpecialXaml2006Type (name);
+                               if (xt == null)
+                                       xt = AllTypes.FirstOrDefault (t => t.Name == xmlLocalName);
+                               if (xt == null)
+                                       throw new FormatException (string.Format ("There is no type '{0}' in XAML namespace", name));
+                               return xt.UnderlyingType;
+                       }
+                       else if (!ns.StartsWith ("clr-namespace:", StringComparison.Ordinal))
+                               throw new FormatException (string.Format ("Unexpected XAML namespace '{0}'", ns));
+
+                       Type [] genArgs = null;
+                       if (typeArguments != null) {
+                               var xtns = typeArguments;
+                               genArgs = new Type [xtns.Count];
+                               for (int i = 0; i < genArgs.Length; i++) {
+                                       var xtn = xtns [i];
+                                       genArgs [i] = ResolveXamlTypeName (xtn.Namespace, xtn.Name, xtn.TypeArguments, nsResolver);
+                               }
+                       }
+
+                       // convert xml namespace to clr namespace and assembly
+                       string [] split = ns.Split (';');
+                       if (split.Length != 2 || split [0].Length <= clr_ns_len || split [1].Length <= clr_ass_len)
+                               throw new XamlParseException (string.Format ("Cannot resolve runtime namespace from XML namespace '{0}'", ns));
+                       string tns = split [0].Substring (clr_ns_len);
+                       string aname = split [1].Substring (clr_ass_len);
+
+                       string tfn = tns.Length > 0 ? tns + '.' + name : name;
+                       if (genArgs != null)
+                               tfn += "`" + genArgs.Length;
+                       string taqn = tfn + (aname.Length > 0 ? ", " + aname : string.Empty);
+                       var ret = System.Type.GetType (taqn);
+                       if (ret == null)
+                               throw new XamlParseException (string.Format ("Cannot resolve runtime type from XML namespace '{0}', local name '{1}' with {2} type arguments ({3})", ns, name, typeArguments.Count, taqn));
+                       return genArgs == null ? ret : ret.MakeGenericType (genArgs);
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlMember.cs b/mcs/class/System.Xaml/System.Xaml/XamlMember.cs
new file mode 100644 (file)
index 0000000..6700d16
--- /dev/null
@@ -0,0 +1,451 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Xaml
+{
+       public class XamlMember : IEquatable<XamlMember>
+       {
+               public XamlMember (EventInfo eventInfo, XamlSchemaContext schemaContext)
+                       : this (eventInfo, schemaContext, null)
+               {
+               }
+
+               public XamlMember (EventInfo eventInfo, XamlSchemaContext schemaContext, XamlMemberInvoker invoker)
+                       : this (schemaContext, invoker)
+               {
+                       if (eventInfo == null)
+                               throw new ArgumentNullException ("eventInfo");
+                       Name = eventInfo.Name;
+                       underlying_member = eventInfo;
+                       DeclaringType = schemaContext.GetXamlType (eventInfo.DeclaringType);
+                       target_type = DeclaringType;
+                       UnderlyingSetter = eventInfo.GetAddMethod ();
+                       is_event = true;
+               }
+
+               public XamlMember (PropertyInfo propertyInfo, XamlSchemaContext schemaContext)
+                       : this (propertyInfo, schemaContext, null)
+               {
+               }
+
+               public XamlMember (PropertyInfo propertyInfo, XamlSchemaContext schemaContext, XamlMemberInvoker invoker)
+                       : this (schemaContext, invoker)
+               {
+                       if (propertyInfo == null)
+                               throw new ArgumentNullException ("propertyInfo");
+                       Name = propertyInfo.Name;
+                       underlying_member = propertyInfo;
+                       DeclaringType = schemaContext.GetXamlType (propertyInfo.DeclaringType);
+                       target_type = DeclaringType;
+                       UnderlyingGetter = propertyInfo.GetGetMethod ();
+                       UnderlyingSetter = propertyInfo.GetSetMethod ();
+               }
+
+               public XamlMember (string attachableEventName, MethodInfo adder, XamlSchemaContext schemaContext)
+                       : this (attachableEventName, adder, schemaContext, null)
+               {
+               }
+
+               public XamlMember (string attachableEventName, MethodInfo adder, XamlSchemaContext schemaContext, XamlMemberInvoker invoker)
+                       : this (schemaContext, invoker)
+               {
+                       if (attachableEventName == null)
+                               throw new ArgumentNullException ("attachableEventName");
+                       if (adder == null)
+                               throw new ArgumentNullException ("adder");
+                       Name = attachableEventName;
+                       VerifyAdderSetter (adder);
+                       underlying_member = adder;
+                       DeclaringType = schemaContext.GetXamlType (adder.DeclaringType);
+                       target_type = schemaContext.GetXamlType (typeof (object));
+                       UnderlyingSetter = adder;
+                       is_event = true;
+                       is_attachable = true;
+               }
+
+               public XamlMember (string attachablePropertyName, MethodInfo getter, MethodInfo setter, XamlSchemaContext schemaContext)
+                       : this (attachablePropertyName, getter, setter, schemaContext, null)
+               {
+               }
+
+               public XamlMember (string attachablePropertyName, MethodInfo getter, MethodInfo setter, XamlSchemaContext schemaContext, XamlMemberInvoker invoker)
+                       : this (schemaContext, invoker)
+               {
+                       if (attachablePropertyName == null)
+                               throw new ArgumentNullException ("attachablePropertyName");
+                       if (getter == null && setter == null)
+                               throw new ArgumentNullException ("getter", "Either property getter or setter must be non-null.");
+                       Name = attachablePropertyName;
+                       VerifyGetter (getter);
+                       VerifyAdderSetter (setter);
+                       underlying_member = getter ?? setter;
+                       DeclaringType = schemaContext.GetXamlType (underlying_member.DeclaringType);
+                       target_type = schemaContext.GetXamlType (typeof (object));
+                       UnderlyingGetter = getter;
+                       UnderlyingSetter = setter;
+                       is_attachable = true;
+               }
+
+               public XamlMember (string name, XamlType declaringType, bool isAttachable)
+               {
+                       if (name == null)
+                               throw new ArgumentNullException ("name");
+                       if (declaringType == null)
+                               throw new ArgumentNullException ("declaringType");
+                       Name = name;
+                       this.invoker = new XamlMemberInvoker (this);
+                       context = declaringType.SchemaContext;
+                       DeclaringType = declaringType;
+                       target_type = DeclaringType;
+                       is_attachable = isAttachable;
+               }
+
+               XamlMember (XamlSchemaContext schemaContext, XamlMemberInvoker invoker)
+               {
+                       if (schemaContext == null)
+                               throw new ArgumentNullException ("schemaContext");
+                       context = schemaContext;
+                       this.invoker = invoker ?? new XamlMemberInvoker (this);
+               }
+
+               internal XamlMember (bool isDirective, string ns, string name)
+               {
+                       directive_ns = ns;
+                       Name = name;
+                       is_directive = isDirective;
+               }
+
+               XamlType type, target_type;
+               MemberInfo underlying_member;
+               MethodInfo underlying_getter, underlying_setter;
+               XamlSchemaContext context;
+               XamlMemberInvoker invoker;
+               bool is_attachable, is_event, is_directive;
+               bool is_predefined_directive = XamlLanguage.InitializingDirectives;
+               string directive_ns;
+
+               internal ICustomAttributeProvider CustomAttributeProvider {
+                       get { return LookupCustomAttributeProvider (); }
+               }
+
+               internal MethodInfo UnderlyingGetter {
+                       get { return LookupUnderlyingGetter (); }
+                       private set { underlying_getter = value; }
+               }
+               internal MethodInfo UnderlyingSetter {
+                       get { return LookupUnderlyingSetter (); }
+                       private set { underlying_setter = value; }
+               }
+
+               public XamlType DeclaringType { get; private set; }
+               public string Name { get; private set; }
+
+               public string PreferredXamlNamespace {
+                       get { return directive_ns ?? (DeclaringType == null ? null : DeclaringType.PreferredXamlNamespace); }
+               }
+               
+               [MonoTODO]
+               public DesignerSerializationVisibility SerializationVisibility {
+                       get {
+                               // FIXME: probably use attribute.
+                               return DesignerSerializationVisibility.Visible;
+                       }
+               }
+
+               public bool IsAttachable {
+                       get { return is_attachable; }
+               }
+
+               public bool IsDirective {
+                       get { return is_directive; }
+               }
+
+               public bool IsNameValid {
+                       get { return XamlLanguage.IsValidXamlName (Name); }
+               }
+
+               public XamlValueConverter<XamlDeferringLoader> DeferringLoader {
+                       get { return LookupDeferringLoader (); }
+               }
+               
+               static readonly XamlMember [] empty_members = new XamlMember [0];
+               
+               public IList<XamlMember> DependsOn {
+                       get { return LookupDependsOn () ?? empty_members; }
+               }
+
+               public XamlMemberInvoker Invoker {
+                       get { return LookupInvoker (); }
+               }
+               public bool IsAmbient {
+                       get { return LookupIsAmbient (); }
+               }
+               public bool IsEvent {
+                       get { return LookupIsEvent (); }
+               }
+               public bool IsReadOnly {
+                       get { return LookupIsReadOnly (); }
+               }
+               public bool IsReadPublic {
+                       get { return LookupIsReadPublic (); }
+               }
+               public bool IsUnknown {
+                       get { return LookupIsUnknown (); }
+               }
+               public bool IsWriteOnly {
+                       get { return LookupIsWriteOnly (); }
+               }
+               public bool IsWritePublic {
+                       get { return LookupIsWritePublic (); }
+               }
+               public XamlType TargetType {
+                       get { return LookupTargetType (); }
+               }
+               public XamlType Type {
+                       get { return LookupType (); }
+               }
+               public XamlValueConverter<TypeConverter> TypeConverter {
+                       get { return LookupTypeConverter (); }
+               }
+               public MemberInfo UnderlyingMember {
+                       get { return LookupUnderlyingMember (); }
+               }
+               public XamlValueConverter<ValueSerializer> ValueSerializer {
+                       get { return LookupValueSerializer (); }
+               }
+
+               public static bool operator == (XamlMember left, XamlMember right)
+               {
+                       return IsNull (left) ? IsNull (right) : left.Equals (right);
+               }
+
+               static bool IsNull (XamlMember a)
+               {
+                       return Object.ReferenceEquals (a, null);
+               }
+
+               public static bool operator != (XamlMember left, XamlMember right)
+               {
+                       return !(left == right);
+               }
+               
+               public override bool Equals (object other)
+               {
+                       var x = other as XamlMember;
+                       return Equals (x);
+               }
+               
+               public bool Equals (XamlMember other)
+               {
+                       // this should be in general correct; XamlMembers are almost not comparable.
+                       if (Object.ReferenceEquals (this, other))
+                               return true;
+                       return !IsNull (other) &&
+                               context == other.context &&
+                               underlying_member == other.underlying_member &&
+                               underlying_getter == other.underlying_getter &&
+                               underlying_setter == other.underlying_setter &&
+                               Name == other.Name &&
+                               PreferredXamlNamespace == other.PreferredXamlNamespace &&
+                               directive_ns == other.directive_ns &&
+                               is_attachable == other.is_attachable;
+               }
+
+               public override int GetHashCode ()
+               {
+                       return ToString ().GetHashCode (); // should in general work.
+               }
+
+               public override string ToString ()
+               {
+                       if (is_attachable || String.IsNullOrEmpty (PreferredXamlNamespace)) {
+                               if (DeclaringType == null)
+                                       return Name;
+                               else
+                                       return String.Concat (DeclaringType.UnderlyingType.FullName, ".", Name);
+                       }
+                       else
+                               return String.Concat ("{", PreferredXamlNamespace, "}", DeclaringType.Name, ".", Name);
+               }
+
+               public virtual IList<string> GetXamlNamespaces ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               // lookups
+
+               protected virtual ICustomAttributeProvider LookupCustomAttributeProvider ()
+               {
+                       return UnderlyingMember;
+               }
+
+               protected virtual XamlValueConverter<XamlDeferringLoader> LookupDeferringLoader ()
+               {
+                       // FIXME: probably fill from attribute.
+                       return null;
+               }
+
+               static readonly XamlMember [] empty_list = new XamlMember [0];
+
+               protected virtual IList<XamlMember> LookupDependsOn ()
+               {
+                       return empty_list;
+               }
+
+               protected virtual XamlMemberInvoker LookupInvoker ()
+               {
+                       return invoker;
+               }
+               protected virtual bool LookupIsAmbient ()
+               {
+                       var t = Type != null ? Type.UnderlyingType : null;
+                       return t != null && t.GetCustomAttributes (typeof (AmbientAttribute), false).Length > 0;
+               }
+
+               protected virtual bool LookupIsEvent ()
+               {
+                       return is_event;
+               }
+
+               protected virtual bool LookupIsReadOnly ()
+               {
+                       return UnderlyingGetter != null && UnderlyingSetter == null;
+               }
+               protected virtual bool LookupIsReadPublic ()
+               {
+                       if (underlying_member == null)
+                               return true;
+                       if (UnderlyingGetter != null)
+                               return UnderlyingGetter.IsPublic;
+                       return false;
+               }
+
+               protected virtual bool LookupIsUnknown ()
+               {
+                       return underlying_member == null;
+               }
+
+               protected virtual bool LookupIsWriteOnly ()
+               {
+                       var pi = underlying_member as PropertyInfo;
+                       if (pi != null)
+                               return !pi.CanRead && pi.CanWrite;
+                       return UnderlyingGetter == null && UnderlyingSetter != null;
+               }
+
+               protected virtual bool LookupIsWritePublic ()
+               {
+                       if (underlying_member == null)
+                               return true;
+                       if (UnderlyingSetter != null)
+                               return UnderlyingSetter.IsPublic;
+                       return false;
+               }
+
+               protected virtual XamlType LookupTargetType ()
+               {
+                       return target_type;
+               }
+
+               protected virtual XamlType LookupType ()
+               {
+                       if (type == null)
+                               type = context.GetXamlType (DoGetType ());
+                       return type;
+               }
+               
+
+               Type DoGetType ()
+               {
+                       var pi = underlying_member as PropertyInfo;
+                       if (pi != null)
+                               return pi.PropertyType;
+                       var ei = underlying_member as EventInfo;
+                       if (ei != null)
+                               return ei.EventHandlerType;
+                       if (underlying_setter != null)
+                               return underlying_setter.GetParameters () [1].ParameterType;
+                       if (underlying_getter != null)
+                               return underlying_getter.GetParameters () [0].ParameterType;
+                       return typeof (object);
+               }
+
+               protected virtual XamlValueConverter<TypeConverter> LookupTypeConverter ()
+               {
+                       var t = Type.UnderlyingType;
+                       if (t == null)
+                               return null;
+                       if (t == typeof (object)) // it is different from XamlType.LookupTypeConverter().
+                               return null;
+                       return Type.TypeConverter;
+               }
+
+               protected virtual MethodInfo LookupUnderlyingGetter ()
+               {
+                       return underlying_getter;
+               }
+
+               protected virtual MemberInfo LookupUnderlyingMember ()
+               {
+                       return underlying_member;
+               }
+
+               protected virtual MethodInfo LookupUnderlyingSetter ()
+               {
+                       return underlying_setter;
+               }
+
+               protected virtual XamlValueConverter<ValueSerializer> LookupValueSerializer ()
+               {
+                       if (is_predefined_directive) // FIXME: this is likely a hack.
+                               return null;
+                       if (Type == null)
+                               return null;
+
+                       return XamlType.LookupValueSerializer (Type, LookupCustomAttributeProvider ()) ?? Type.ValueSerializer;
+               }
+
+               void VerifyGetter (MethodInfo method)
+               {
+                       if (method == null)
+                               return;
+                       if (method.GetParameters ().Length != 1 || method.ReturnType == typeof (void))
+                               throw new ArgumentException (String.Format ("Property getter for {0} must have exactly one argument and must have non-void return type.", Name));
+               }
+
+               void VerifyAdderSetter (MethodInfo method)
+               {
+                       if (method == null)
+                               return;
+                       if (method.GetParameters ().Length != 2)
+                               throw new ArgumentException (String.Format ("Property getter or event adder for {0} must have exactly one argument and must have non-void return type.", Name));
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlNodeList.cs b/mcs/class/System.Xaml/System.Xaml/XamlNodeList.cs
new file mode 100644 (file)
index 0000000..848b3a0
--- /dev/null
@@ -0,0 +1,58 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public class XamlNodeList
+       {
+               public XamlNodeList (XamlSchemaContext schemaContext)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public XamlNodeList (XamlSchemaContext schemaContext, int size)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public int Count {
+                       get {throw new NotImplementedException (); }
+               }
+
+               public XamlWriter Writer {
+                       get {throw new NotImplementedException (); }
+               }
+
+               public void Clear ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public XamlReader GetReader ()
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlNodeQueue.cs b/mcs/class/System.Xaml/System.Xaml/XamlNodeQueue.cs
new file mode 100644 (file)
index 0000000..40917e2
--- /dev/null
@@ -0,0 +1,51 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Windows.Markup;
+
+namespace System.Xaml
+{
+       public class XamlNodeQueue
+       {
+               public XamlNodeQueue (XamlSchemaContext schemaContext)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public int Count {
+                       get {throw new NotImplementedException (); }
+               }
+               public bool IsEmpty {
+                       get {throw new NotImplementedException (); }
+               }
+               public XamlReader Reader {
+                       get {throw new NotImplementedException (); }
+               }
+               public XamlWriter Writer {
+                       get {throw new NotImplementedException (); }
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlNodeType.cs b/mcs/class/System.Xaml/System.Xaml/XamlNodeType.cs
new file mode 100644 (file)
index 0000000..b71fcdd
--- /dev/null
@@ -0,0 +1,42 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Windows.Markup;
+
+namespace System.Xaml
+{
+       public enum XamlNodeType
+       {
+               None,
+               StartObject,
+               GetObject,
+               EndObject,
+               StartMember,
+               EndMember,
+               Value,
+               NamespaceDeclaration
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlObjectEventArgs.cs b/mcs/class/System.Xaml/System.Xaml/XamlObjectEventArgs.cs
new file mode 100644 (file)
index 0000000..2b51561
--- /dev/null
@@ -0,0 +1,42 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Windows.Markup;
+
+namespace System.Xaml
+{
+       public class XamlObjectEventArgs : EventArgs
+       {
+               public XamlObjectEventArgs (object instance)
+               {
+                       if (instance == null)
+                               throw new ArgumentNullException ("instance");
+                       Instance = instance;
+               }
+
+               public object Instance { get; private set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlObjectReader.cs b/mcs/class/System.Xaml/System.Xaml/XamlObjectReader.cs
new file mode 100644 (file)
index 0000000..aa8c8d0
--- /dev/null
@@ -0,0 +1,404 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Xaml
+{
+       public class XamlObjectReader : XamlReader
+       {
+               #region nested types
+
+               class NSList : List<NamespaceDeclaration>
+               {
+                       public NSList (XamlNodeType ownerType, IEnumerable<NamespaceDeclaration> nsdecls)
+                               : base (nsdecls)
+                       {
+                               OwnerType = ownerType;
+                       }
+                       
+                       public XamlNodeType OwnerType { get; set; }
+
+                       public IEnumerator<NamespaceDeclaration> GetEnumerator ()
+                       {
+                               return new NSEnumerator (this, base.GetEnumerator ());
+                       }
+               }
+
+               class NSEnumerator : IEnumerator<NamespaceDeclaration>
+               {
+                       NSList list;
+                       IEnumerator<NamespaceDeclaration> e;
+
+                       public NSEnumerator (NSList list, IEnumerator<NamespaceDeclaration> e)
+                       {
+                               this.list= list;
+                               this.e = e;
+                       }
+                       
+                       public XamlNodeType OwnerType {
+                               get { return list.OwnerType; }
+                       }
+
+                       public void Dispose ()
+                       {
+                       }
+
+                       public bool MoveNext ()
+                       {
+                               return e.MoveNext ();
+                       }
+
+                       public NamespaceDeclaration Current {
+                               get { return e.Current; }
+                       }
+
+                       object IEnumerator.Current {
+                               get { return Current; }
+                       }
+
+                       public void Reset ()
+                       {
+                               throw new NotSupportedException ();
+                       }
+               }
+       
+               class PrefixLookup : INamespacePrefixLookup
+               {
+                       XamlObjectReader source;
+
+                       public PrefixLookup (XamlObjectReader source)
+                       {
+                               this.source = source;
+                       }
+
+                       public string LookupPrefix (string ns)
+                       {
+                               return source.LookupPrefix (ns);
+                       }
+               }
+
+               #endregion nested types
+
+               public XamlObjectReader (object instance)
+                       : this (instance, new XamlSchemaContext (null, null), null)
+               {
+               }
+
+               public XamlObjectReader (object instance, XamlObjectReaderSettings settings)
+                       : this (instance, new XamlSchemaContext (null, null), settings)
+               {
+               }
+
+               public XamlObjectReader (object instance, XamlSchemaContext schemaContext)
+                       : this (instance, schemaContext, null)
+               {
+               }
+
+               public XamlObjectReader (object instance, XamlSchemaContext schemaContext, XamlObjectReaderSettings settings)
+               {
+                       if (schemaContext == null)
+                               throw new ArgumentNullException ("schemaContext");
+                       // FIXME: special case? or can it be generalized?
+                       if (instance is Type)
+                               instance = new TypeExtension ((Type) instance);
+
+                       this.instance = instance;
+                       sctx = schemaContext;
+                       this.settings = settings;
+
+                       prefix_lookup = new PrefixLookup (this);
+
+                       if (instance != null) {
+                               // check type validity. Note that some checks are done at Read() phase.
+                               var type = instance.GetType ();
+                               if (!type.IsPublic)
+                                       throw new XamlObjectReaderException (String.Format ("instance type '{0}' must be public and non-nested.", type));
+                               root_type = SchemaContext.GetXamlType (instance.GetType ());
+                               if (root_type.ConstructionRequiresArguments && root_type.TypeConverter == null)
+                                       throw new XamlObjectReaderException (String.Format ("instance type '{0}' has no default constructor.", type));
+                       }
+                       else
+                               root_type = XamlLanguage.Null;
+               }
+
+               object instance;
+               XamlType root_type;
+               XamlSchemaContext sctx;
+               XamlObjectReaderSettings settings;
+
+               INamespacePrefixLookup prefix_lookup;
+
+               Stack<XamlType> types = new Stack<XamlType> ();
+               Stack<object> objects = new Stack<object> ();
+               Stack<IEnumerator<XamlMember>> members_stack = new Stack<IEnumerator<XamlMember>> ();
+               NSList namespaces;
+               IEnumerator<NamespaceDeclaration> ns_iterator;
+               XamlNodeType node_type = XamlNodeType.None;
+               bool is_eof;
+
+               public virtual object Instance {
+                       get { return NodeType == XamlNodeType.StartObject && objects.Count > 0 ? objects.Peek () : null; }
+               }
+
+               public override bool IsEof {
+                       get { return is_eof; }
+               }
+
+               public override XamlMember Member {
+                       get { return NodeType == XamlNodeType.StartMember ? members_stack.Peek ().Current : null; }
+               }
+
+               public override NamespaceDeclaration Namespace {
+                       get { return NodeType == XamlNodeType.NamespaceDeclaration ? ns_iterator.Current : null; }
+               }
+
+               public override XamlNodeType NodeType {
+                       get { return node_type; }
+               }
+
+               public override XamlSchemaContext SchemaContext {
+                       get { return sctx; }
+               }
+
+               public override XamlType Type {
+                       get { return NodeType == XamlNodeType.StartObject ? types.Peek () : null; }
+               }
+
+               public override object Value {
+                       get { return NodeType == XamlNodeType.Value ? objects.Peek () : null; }
+               }
+
+               internal string LookupPrefix (string ns)
+               {
+                       foreach (var nsd in namespaces)
+                               if (nsd.Namespace == ns)
+                                       return nsd.Prefix;
+                       return null;
+               }
+
+               public override bool Read ()
+               {
+                       if (IsDisposed)
+                               throw new ObjectDisposedException ("reader");
+                       if (IsEof)
+                               return false;
+                       IEnumerator<XamlMember> members;
+                       switch (NodeType) {
+                       case XamlNodeType.None:
+                       default:
+                               // -> namespaces
+                               var d = new Dictionary<string,string> ();
+                               //l.Sort ((p1, p2) => String.CompareOrdinal (p1.Key, p2.Key));
+                               CollectNamespaces (d, instance, root_type);
+                               var nss = from k in d.Keys select new NamespaceDeclaration (k, d [k]);
+                               namespaces = new NSList (XamlNodeType.StartObject, nss);
+                               namespaces.Sort ((n1, n2) => String.CompareOrdinal (n1.Prefix, n2.Prefix));
+                               ns_iterator = namespaces.GetEnumerator ();
+
+                               ns_iterator.MoveNext ();
+                               node_type = XamlNodeType.NamespaceDeclaration;
+                               return true;
+
+                       case XamlNodeType.NamespaceDeclaration:
+                               if (ns_iterator.MoveNext ())
+                                       return true;
+                               node_type = ((NSEnumerator) ns_iterator).OwnerType; // StartObject or StartMember
+                               if (node_type == XamlNodeType.StartObject)
+                                       StartNextObject ();
+                               else
+                                       StartNextMemberOrNamespace ();
+                               return true;
+
+                       case XamlNodeType.StartObject:
+                               var xt = types.Peek ();
+                               members = xt.GetAllReadWriteMembers ().GetEnumerator ();
+                               if (members.MoveNext ()) {
+                                       members_stack.Push (members);
+                                       StartNextMemberOrNamespace ();
+                                       return true;
+                               }
+                               else
+                                       node_type = XamlNodeType.EndObject;
+                               return true;
+
+                       case XamlNodeType.StartMember:
+                               if (!members_stack.Peek ().Current.IsContentValue ())
+                                       StartNextObject ();
+                               else {
+                                       var obj = GetMemberValueOrRootInstance ();
+                                       objects.Push (obj);
+                                       node_type = XamlNodeType.Value;
+                               }
+                               return true;
+
+                       case XamlNodeType.Value:
+                               objects.Pop ();
+                               node_type = XamlNodeType.EndMember;
+                               return true;
+
+                       case XamlNodeType.GetObject:
+                               // how do we get here?
+                               throw new NotImplementedException ();
+
+                       case XamlNodeType.EndMember:
+                               members = members_stack.Peek ();
+                               if (members.MoveNext ()) {
+                                       members_stack.Push (members);
+                                       StartNextMemberOrNamespace ();
+                               } else {
+                                       members_stack.Pop ();
+                                       node_type = XamlNodeType.EndObject;
+                               }
+                               return true;
+
+                       case XamlNodeType.EndObject:
+                               // It might be either end of the entire object tree or just the end of an object value.
+                               types.Pop ();
+                               objects.Pop ();
+                               if (objects.Count == 0) {
+                                       node_type = XamlNodeType.None;
+                                       is_eof = true;
+                                       return false;
+                               }
+                               members = members_stack.Peek ();
+                               if (members.MoveNext ()) {
+                                       StartNextMemberOrNamespace ();
+                                       return true;
+                               }
+                               // then, move to the end of current object member.
+                               node_type = XamlNodeType.EndMember;
+                               return true;
+                       }
+               }
+
+               void CollectNamespaces (Dictionary<string,string> d, object o, XamlType xt)
+               {
+                       if (xt == null)
+                               return;
+                       if (o == null) {
+                               // it becomes NullExtension, so check standard ns.
+                               CheckAddNamespace (d, XamlLanguage.Xaml2006Namespace);
+                               return;
+                       }
+                       var ns = xt.PreferredXamlNamespace;
+                       CheckAddNamespace (d, ns);
+
+                       foreach (var xm in xt.GetAllMembers ()) {
+                               ns = xm.PreferredXamlNamespace;
+                               if (xm is XamlDirective && ns == XamlLanguage.Xaml2006Namespace)
+                                       continue;
+                               if (xm.Type.IsCollection || xm.Type.IsDictionary || xm.Type.IsArray)
+                                       continue; // FIXME: process them too.
+                               var mv = GetMemberValueOf (xm, o, xt, d);
+                               CollectNamespaces (d, mv, xm.Type);
+                       }
+               }
+
+               // This assumes that the next member is already on current position on current iterator.
+               void StartNextMemberOrNamespace ()
+               {
+                       // FIXME: there might be NamespaceDeclarations.
+                       node_type = XamlNodeType.StartMember;
+               }
+
+               void StartNextObject ()
+               {
+                       var obj = GetMemberValueOrRootInstance ();
+                       var xt = Object.ReferenceEquals (obj, instance) ? root_type : obj != null ? SchemaContext.GetXamlType (obj.GetType ()) : XamlLanguage.Null;
+
+                       // FIXME: enable these lines.
+                       // FIXME: if there is an applicable instance descriptor, then it could be still valid.
+                       //var type = xt.UnderlyingType;
+                       //if (type.GetConstructor (System.Type.EmptyTypes) == null)
+                       //      throw new XamlObjectReaderException (String.Format ("Type {0} has no default constructor or an instance descriptor.", type));
+
+                       objects.Push (obj);
+                       types.Push (xt);
+                       node_type = XamlNodeType.StartObject;
+               }
+               
+               object GetMemberValueOrRootInstance ()
+               {
+                       if (objects.Count == 0)
+                               return instance;
+
+                       var xm = members_stack.Peek ().Current;
+                       var obj = objects.Peek ();
+                       var xt = types.Peek ();
+                       return GetMemberValueOf (xm, obj, xt, null);
+               }
+
+               object GetMemberValueOf (XamlMember xm, object obj, XamlType xt, Dictionary<string,string> collectingNamespaces)
+               {
+                       object retobj;
+                       XamlType retxt;
+                       if (xt.IsContentValue ()) {
+                               retxt = xt;
+                               retobj = obj;
+                       } else {
+                               retxt = xm.Type;
+                               retobj = xm.GetMemberValueForObjectReader (xt, obj, prefix_lookup);
+                       }
+
+                       if (collectingNamespaces != null) {
+                               if (retobj is Type || retobj is TypeExtension) {
+                                       var type = (retobj as Type) ?? ((TypeExtension) retobj).Type;
+                                       if (type == null) // only TypeExtension.TypeName
+                                               return null;
+                                       var xtt = SchemaContext.GetXamlType (type);
+                                       var ns = xtt.PreferredXamlNamespace;
+                                       var nss = collectingNamespaces;
+                                       CheckAddNamespace (collectingNamespaces, ns);
+                                       return null;
+                               }
+                               else if (retxt.IsContentValue ())
+                                       return null;
+                               else
+                                       return retobj;
+                       } else if (retxt.IsContentValue ()) {
+                               // FIXME: I'm not sure if this should be really done 
+                               // here, but every primitive values seem to be exposed
+                               // as a string, not a typed object in XamlObjectReader.
+                               return retxt.GetStringValue (retobj, prefix_lookup);
+                       }
+                       else
+                               return retobj;
+               }
+
+               void CheckAddNamespace (Dictionary<string,string> d, string ns)
+               {
+                       if (ns == XamlLanguage.Xaml2006Namespace)
+                               d [XamlLanguage.Xaml2006Namespace] = "x";
+                       else if (!d.ContainsValue (String.Empty))
+                               d [ns] = String.Empty;
+                       else if (!d.ContainsKey (ns))
+                               d.Add (ns, SchemaContext.GetPreferredPrefix (ns));
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlObjectReaderException.cs b/mcs/class/System.Xaml/System.Xaml/XamlObjectReaderException.cs
new file mode 100644 (file)
index 0000000..0bad880
--- /dev/null
@@ -0,0 +1,53 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Runtime.Serialization;
+
+namespace System.Xaml
+{
+       [Serializable]
+       public class XamlObjectReaderException : XamlException
+       {
+               public XamlObjectReaderException ()
+                       : this ("XAML object reader error")
+               {
+               }
+
+               public XamlObjectReaderException (string message)
+                       : this (message, null)
+               {
+               }
+
+               public XamlObjectReaderException (string message, Exception innerException)
+                       : base (message, innerException)
+               {
+               }
+
+               protected XamlObjectReaderException (SerializationInfo info, StreamingContext context)
+                       : base (info, context)
+               {
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlObjectReaderSettings.cs b/mcs/class/System.Xaml/System.Xaml/XamlObjectReaderSettings.cs
new file mode 100644 (file)
index 0000000..fab3faa
--- /dev/null
@@ -0,0 +1,37 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Xaml
+{
+       public class XamlObjectReaderSettings : XamlReaderSettings
+       {
+               public bool RequireExplicitContentVisibility { get; set; }
+       }
+}
+
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlObjectWriter.cs b/mcs/class/System.Xaml/System.Xaml/XamlObjectWriter.cs
new file mode 100644 (file)
index 0000000..19b98ff
--- /dev/null
@@ -0,0 +1,296 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.Windows.Markup;
+
+namespace System.Xaml
+{
+       public class XamlObjectWriter : XamlWriter, IXamlLineInfoConsumer
+       {
+               public XamlObjectWriter (XamlSchemaContext schemaContext)
+                       : this (schemaContext, null)
+               {
+               }
+
+               public XamlObjectWriter (XamlSchemaContext schemaContext, XamlObjectWriterSettings settings)
+               {
+                       if (schemaContext == null)
+                               throw new ArgumentNullException ("schemaContext");
+                       this.sctx = schemaContext;
+                       this.settings = settings ?? new XamlObjectWriterSettings ();
+               }
+
+               XamlSchemaContext sctx;
+               XamlObjectWriterSettings settings;
+
+               XamlWriterStateManager manager = new XamlWriterStateManager<XamlObjectWriterException, XamlObjectWriterException> (false);
+               object result;
+               int line = -1, column = -1;
+               Stack<object> objects = new Stack<object> ();
+               Stack<XamlType> types = new Stack<XamlType> ();
+               Stack<XamlMember> members = new Stack<XamlMember> ();
+
+               List<object> arguments = new List<object> ();
+               string factory_method;
+               bool object_instantiated;
+               List<object> contents = new List<object> ();
+               List<object> objects_from_getter = new List<object> ();
+               Stack<List<XamlMember>> written_properties_stack = new Stack<List<XamlMember>> ();
+
+               public virtual object Result {
+                       get { return result; }
+               }
+
+               public INameScope RootNameScope {
+                       get { throw new NotImplementedException (); }
+               }
+
+               public override XamlSchemaContext SchemaContext {
+                       get { return sctx; }
+               }
+
+               public bool ShouldProvideLineInfo {
+                       get { return line > 0 && column > 0; }
+               }
+               
+               public void Clear ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               protected override void Dispose (bool disposing)
+               {
+                       if (!disposing)
+                               return;
+
+                       while (types.Count > 0) {
+                               WriteEndObject ();
+                               if (types.Count > 0)
+                                       WriteEndMember ();
+                       }
+               }
+
+               protected virtual void OnAfterBeginInit (object value)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               protected virtual void OnAfterEndInit (object value)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               protected virtual void OnAfterProperties (object value)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               protected virtual void OnBeforeProperties (object value)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               protected virtual bool OnSetValue (object eventSender, XamlMember member, object value)
+               {
+                       if (settings.XamlSetValueHandler != null) {
+                               settings.XamlSetValueHandler (eventSender, new XamlSetValueEventArgs (member, value));
+                               return true;
+                       }
+                       return false;
+               }
+
+               public void SetLineInfo (int lineNumber, int linePosition)
+               {
+                       line = lineNumber;
+                       column = linePosition;
+               }
+
+               [MonoTODO ("Array and Dictionary needs implementation")]
+               public override void WriteEndMember ()
+               {
+                       manager.EndMember ();
+                       
+                       var xm = members.Pop ();
+                       var xt = xm.Type;
+
+                       if (xt.IsArray) {
+                               throw new NotImplementedException ();
+                       } else if (xt.IsCollection) {
+                               var obj = objects.Peek ();
+                               foreach (var content in contents)
+                                       xt.Invoker.AddToCollection (obj, content);
+                       } else if (xt.IsDictionary) {
+                               throw new NotImplementedException ();
+                       } else {
+                               if (contents.Count > 1)
+                                       throw new XamlDuplicateMemberException (String.Format ("Value for {0} is assigned more than once", xm.Name));
+                               if (contents.Count == 1) {
+                                       var value = GetCorrectlyTypedValue (xm, contents [0]);
+                                       if (!objects_from_getter.Remove (value))
+                                               if (!OnSetValue (this, xm, value))
+                                                       xm.Invoker.SetValue (objects.Peek (), value);
+                               }
+                       }
+
+                       contents.Clear ();
+                       written_properties_stack.Peek ().Add (xm);
+               }
+
+               object GetCorrectlyTypedValue (XamlMember xm, object value)
+               {
+                       var xt = xm.Type;
+                       if (IsAllowedType (xt, value))
+                               return value;
+                       if (xt.TypeConverter != null && value != null) {
+                               var tc = xt.TypeConverter.ConverterInstance;
+                               if (tc != null && tc.CanConvertFrom (value.GetType ()))
+                                       value = tc.ConvertFrom (value);
+                               if (IsAllowedType (xt, value))
+                                       return value;
+                       }
+                       throw new XamlObjectWriterException (String.Format ("Value is not of type {0}", xt));
+               }
+
+               bool IsAllowedType (XamlType xt, object value)
+               {
+                       return xt == null || xt.UnderlyingType == null || xt.UnderlyingType.IsInstanceOfType (value);
+               }
+
+               public override void WriteEndObject ()
+               {
+                       manager.EndObject (types.Count > 0);
+
+                       InitializeObjectIfRequired (); // this is required for such case that there was no StartMember call.
+
+                       types.Pop ();
+                       written_properties_stack.Pop ();
+                       var obj = objects.Pop ();
+                       if (members.Count > 0)
+                               contents.Add (obj);
+               }
+
+               public override void WriteGetObject ()
+               {
+                       manager.GetObject ();
+
+                       var xm = members.Peek ();
+                       if (!xm.Type.IsCollection)
+                               throw new XamlObjectWriterException (String.Format ("WriteGetObject method can be invoked only when current member '{0}' is of collection type", xm.Name));
+
+                       var obj = xm.Invoker.GetValue (objects.Peek ());
+                       if (obj == null)
+                               throw new XamlObjectWriterException (String.Format ("The value  for '{0}' property is null", xm.Name));
+
+                       types.Push (SchemaContext.GetXamlType (obj.GetType ()));
+                       ObjectInitialized (obj);
+                       objects_from_getter.Add (obj);
+               }
+
+               public override void WriteNamespace (NamespaceDeclaration namespaceDeclaration)
+               {
+                       if (namespaceDeclaration == null)
+                               throw new ArgumentNullException ("namespaceDeclaration");
+
+                       manager.Namespace ();
+
+                       // FIXME: find out what to do.
+               }
+
+               public override void WriteStartMember (XamlMember property)
+               {
+                       if (property == null)
+                               throw new ArgumentNullException ("property");
+
+                       manager.StartMember ();
+
+                       var wpl = written_properties_stack.Peek ();
+                       if (wpl.Contains (property))
+                               throw new XamlDuplicateMemberException (String.Format ("Property '{0}' is already set to this '{1}' object", property.Name, types.Peek ().Name));
+                       wpl.Add (property);
+
+                       members.Push (property);
+
+                       if (property == XamlLanguage.Initialization)
+                               return;
+                       else
+                               InitializeObjectIfRequired ();
+               }
+
+               void InitializeObjectIfRequired ()
+               {
+                       if (object_instantiated)
+                               return;
+
+                       // FIXME: "The default techniques in absence of a factory method are to attempt to find a default constructor, then attempt to find an identified type converter on type, member, or destination type."
+                       // http://msdn.microsoft.com/en-us/library/system.xaml.xamllanguage.factorymethod%28VS.100%29.aspx
+                       object obj;
+                       var args = arguments.ToArray ();
+                       if (factory_method != null)
+                               obj = types.Peek ().UnderlyingType.GetMethod (factory_method).Invoke (null, args);
+                       else
+                               obj = types.Peek ().Invoker.CreateInstance (args);
+                       ObjectInitialized (obj);
+               }
+
+               public override void WriteStartObject (XamlType xamlType)
+               {
+                       if (xamlType == null)
+                               throw new ArgumentNullException ("xamlType");
+
+                       manager.StartObject ();
+
+                       types.Push (xamlType);
+
+                       object_instantiated = false;
+
+                       written_properties_stack.Push (new List<XamlMember> ());
+               }
+
+               public override void WriteValue (object value)
+               {
+                       manager.Value ();
+
+                       var xm = members.Peek ();
+
+                       if (xm == XamlLanguage.Initialization)
+                               ObjectInitialized (value);
+                       else if (xm == XamlLanguage.Arguments)
+                               arguments.Add (value);
+                       else if (xm == XamlLanguage.FactoryMethod)
+                               factory_method = (string) value;
+                       else
+                               contents.Add (value);
+               }
+
+               void ObjectInitialized (object obj)
+               {
+                       objects.Push (obj);
+                       object_instantiated = true;
+                       if (objects.Count == 1)
+                               result = objects.Peek ();
+                       arguments.Clear ();
+                       factory_method = null;
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlObjectWriterException.cs b/mcs/class/System.Xaml/System.Xaml/XamlObjectWriterException.cs
new file mode 100644 (file)
index 0000000..17708cc
--- /dev/null
@@ -0,0 +1,53 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Runtime.Serialization;
+
+namespace System.Xaml
+{
+       [Serializable]
+       public class XamlObjectWriterException : XamlException
+       {
+               public XamlObjectWriterException ()
+                       : this ("XAML object writer error")
+               {
+               }
+
+               public XamlObjectWriterException (string message)
+                       : this (message, null)
+               {
+               }
+
+               public XamlObjectWriterException (string message, Exception innerException)
+                       : base (message, innerException)
+               {
+               }
+
+               protected XamlObjectWriterException (SerializationInfo info, StreamingContext context)
+                       : base (info, context)
+               {
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlObjectWriterSettings.cs b/mcs/class/System.Xaml/System.Xaml/XamlObjectWriterSettings.cs
new file mode 100644 (file)
index 0000000..ba5ff21
--- /dev/null
@@ -0,0 +1,73 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Permissions;
+using System.Xaml.Schema;
+
+namespace System.Xaml
+{
+       public class XamlObjectWriterSettings : XamlWriterSettings
+       {
+               public XamlObjectWriterSettings ()
+               {
+               }
+
+               public XamlObjectWriterSettings (XamlObjectWriterSettings settings)
+                       : base (settings)
+               {
+                       var s = settings;
+                       AccessLevel = s.AccessLevel;
+                       AfterBeginInitHandler = s.AfterBeginInitHandler;
+                       AfterEndInitHandler = s.AfterEndInitHandler;
+                       AfterPropertiesHandler = s.AfterPropertiesHandler;
+                       BeforePropertiesHandler = s.BeforePropertiesHandler;
+                       ExternalNameScope = s.ExternalNameScope;
+                       IgnoreCanConvert = s.IgnoreCanConvert;
+                       PreferUnconvertedDictionaryKeys = s.PreferUnconvertedDictionaryKeys;
+                       RegisterNamesOnExternalNamescope = s.RegisterNamesOnExternalNamescope;
+                       RootObjectInstance = s.RootObjectInstance;
+                       SkipDuplicatePropertyCheck = s.SkipDuplicatePropertyCheck;
+                       SkipProvideValueOnRoot = s.SkipProvideValueOnRoot;
+                       XamlSetValueHandler = s.XamlSetValueHandler;
+               }
+
+               public XamlAccessLevel AccessLevel { get; set; }
+               public EventHandler<XamlObjectEventArgs> AfterBeginInitHandler { get; set; }
+               public EventHandler<XamlObjectEventArgs> AfterEndInitHandler { get; set; }
+               public EventHandler<XamlObjectEventArgs> AfterPropertiesHandler { get; set; }
+               public EventHandler<XamlObjectEventArgs> BeforePropertiesHandler { get; set; }
+               public INameScope ExternalNameScope { get; set; }
+               public bool IgnoreCanConvert { get; set; }
+               public bool PreferUnconvertedDictionaryKeys { get; set; }
+               public bool RegisterNamesOnExternalNamescope { get; set; }
+               public object RootObjectInstance { get; set; }
+               public bool SkipDuplicatePropertyCheck { get; set; }
+               public bool SkipProvideValueOnRoot { get; set; }
+               public EventHandler<XamlSetValueEventArgs> XamlSetValueHandler { get; set; }
+
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlParseException.cs b/mcs/class/System.Xaml/System.Xaml/XamlParseException.cs
new file mode 100644 (file)
index 0000000..4bb8340
--- /dev/null
@@ -0,0 +1,53 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Runtime.Serialization;
+
+namespace System.Xaml
+{
+       [Serializable]
+       public class XamlParseException : XamlException
+       {
+               public XamlParseException ()
+                       : this ("XAML parse error")
+               {
+               }
+
+               public XamlParseException (string message)
+                       : this (message, null)
+               {
+               }
+
+               public XamlParseException (string message, Exception innerException)
+                       : base (message, innerException)
+               {
+               }
+
+               protected XamlParseException (SerializationInfo info, StreamingContext context)
+                       : base (info, context)
+               {
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlReader.cs b/mcs/class/System.Xaml/System.Xaml/XamlReader.cs
new file mode 100644 (file)
index 0000000..039daab
--- /dev/null
@@ -0,0 +1,92 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public abstract class XamlReader : IDisposable
+       {
+               protected bool IsDisposed { get; private set; }
+
+               public abstract bool IsEof { get; }
+               public abstract XamlMember Member { get; }
+               public abstract NamespaceDeclaration Namespace { get; }
+               public abstract XamlNodeType NodeType { get; }
+               public abstract XamlSchemaContext SchemaContext { get; }
+               public abstract XamlType Type { get; }
+               public abstract object Value { get; }
+               
+               public void Close ()
+               {
+                       Dispose (true);
+               }
+               
+               protected virtual void Dispose (bool disposing)
+               {
+                       IsDisposed = true;
+               }
+               
+               void IDisposable.Dispose ()
+               {
+                       Dispose (true);
+               }
+               
+               public abstract bool Read ();
+               
+               [MonoTODO]
+               public virtual XamlReader ReadSubtree ()
+               {
+                       throw new NotImplementedException ();
+               }
+               
+               public virtual void Skip ()
+               {
+                       switch (NodeType) {
+                       case XamlNodeType.StartMember:
+                       case XamlNodeType.StartObject:
+                               if (!Read ())
+                                       return;
+                               while (true) {
+                                       switch (NodeType) {
+                                       case XamlNodeType.StartMember:
+                                       case XamlNodeType.StartObject:
+                                               Skip ();
+                                               continue;
+                                       case XamlNodeType.EndMember:
+                                       case XamlNodeType.EndObject:
+                                               Read ();
+                                               return;
+                                       default:
+                                               Read ();
+                                               continue;
+                                       }
+                               }
+                               return;
+                       default:
+                               Read ();
+                               return;
+                       }
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlReaderSettings.cs b/mcs/class/System.Xaml/System.Xaml/XamlReaderSettings.cs
new file mode 100644 (file)
index 0000000..3f7fd94
--- /dev/null
@@ -0,0 +1,60 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Xaml
+{
+       public class XamlReaderSettings
+       {
+               public XamlReaderSettings ()
+               {
+               }
+
+               public XamlReaderSettings (XamlReaderSettings settings)
+               {
+                       // null settings is allowed (!)
+                       var s = settings;
+                       if (s == null)
+                               return;
+
+                       AllowProtectedMembersOnRoot = s.AllowProtectedMembersOnRoot;
+                       BaseUri = s.BaseUri;
+                       IgnoreUidsOnPropertyElements = s.IgnoreUidsOnPropertyElements;
+                       LocalAssembly = s.LocalAssembly;
+                       ProvideLineInfo = s.ProvideLineInfo;
+                       ValuesMustBeString = s.ValuesMustBeString;
+               }
+
+               public bool AllowProtectedMembersOnRoot { get; set; }
+               public Uri BaseUri { get; set; }
+               public bool IgnoreUidsOnPropertyElements { get; set; }
+               public Assembly LocalAssembly { get; set; }
+               public bool ProvideLineInfo { get; set; }
+               public bool ValuesMustBeString { get; set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlSchemaContext.cs b/mcs/class/System.Xaml/System.Xaml/XamlSchemaContext.cs
new file mode 100644 (file)
index 0000000..7a9d13b
--- /dev/null
@@ -0,0 +1,270 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+using Pair = System.Collections.Generic.KeyValuePair<string,string>;
+
+namespace System.Xaml
+{
+       // This type caches assembly attribute search results. To do this,
+       // it registers AssemblyLoaded event on CurrentDomain when it should
+       // reflect dynamic in-scope asemblies.
+       // It should be released at finalizer.
+       public class XamlSchemaContext
+       {
+               public XamlSchemaContext ()
+                       : this (null, null)
+               {
+               }
+
+               public XamlSchemaContext (IEnumerable<Assembly> referenceAssemblies)
+                       : this (referenceAssemblies, null)
+               {
+               }
+
+               public XamlSchemaContext (XamlSchemaContextSettings settings)
+                       : this (null, settings)
+               {
+               }
+
+               public XamlSchemaContext (IEnumerable<Assembly> referenceAssemblies, XamlSchemaContextSettings settings)
+               {
+                       if (referenceAssemblies != null)
+                               reference_assemblies = new List<Assembly> (referenceAssemblies);
+                       else
+                               AppDomain.CurrentDomain.AssemblyLoad += OnAssemblyLoaded;
+
+                       if (settings == null)
+                               return;
+
+                       FullyQualifyAssemblyNamesInClrNamespaces = settings.FullyQualifyAssemblyNamesInClrNamespaces;
+                       SupportMarkupExtensionsWithDuplicateArity = settings.SupportMarkupExtensionsWithDuplicateArity;
+               }
+
+               ~XamlSchemaContext ()
+               {
+                       if (reference_assemblies == null)
+                               AppDomain.CurrentDomain.AssemblyLoad -= OnAssemblyLoaded;
+               }
+
+               IList<Assembly> reference_assemblies;
+
+               // assembly attribute caches
+               List<string> xaml_nss;
+               Dictionary<string,string> prefixes;
+               Dictionary<string,string> compat_nss;
+               Dictionary<string,List<XamlType>> all_xaml_types;
+               XamlType [] empty_xaml_types = new XamlType [0];
+
+               public bool FullyQualifyAssemblyNamesInClrNamespaces { get; private set; }
+
+               public IList<Assembly> ReferenceAssemblies {
+                       get { return reference_assemblies; }
+               }
+
+               IEnumerable<Assembly> AssembliesInScope {
+                       get { return reference_assemblies ?? AppDomain.CurrentDomain.GetAssemblies (); }
+               }
+
+               public bool SupportMarkupExtensionsWithDuplicateArity { get; private set; }
+
+               public virtual IEnumerable<string> GetAllXamlNamespaces ()
+               {
+                       if (xaml_nss == null) {
+                               xaml_nss = new List<string> ();
+                               foreach (var ass in AssembliesInScope)
+                                       FillXamlNamespaces (ass);
+                       }
+                       return xaml_nss;
+               }
+
+               public virtual ICollection<XamlType> GetAllXamlTypes (string xamlNamespace)
+               {
+                       if (xamlNamespace == null)
+                               throw new ArgumentNullException ("xamlNamespace");
+                       if (all_xaml_types == null) {
+                               all_xaml_types = new Dictionary<string,List<XamlType>> ();
+                               foreach (var ass in AssembliesInScope)
+                                       FillAllXamlTypes (ass);
+                       }
+
+                       List<XamlType> l;
+                       if (all_xaml_types.TryGetValue (xamlNamespace, out l))
+                               return l;
+                       else
+                               return empty_xaml_types;
+               }
+
+               public virtual string GetPreferredPrefix (string xmlns)
+               {
+                       if (xmlns == null)
+                               throw new ArgumentNullException ("xmlns");
+                       if (xmlns == XamlLanguage.Xaml2006Namespace)
+                               return "x";
+                       if (prefixes == null) {
+                               prefixes = new Dictionary<string,string> ();
+                               foreach (var ass in AssembliesInScope)
+                                       FillPrefixes (ass);
+                       }
+                       string ret;
+                       return prefixes.TryGetValue (xmlns, out ret) ? ret : "p"; // default
+               }
+
+               protected internal XamlValueConverter<TConverterBase> GetValueConverter<TConverterBase> (Type converterType, XamlType targetType)
+                       where TConverterBase : class
+               {
+                       return new XamlValueConverter<TConverterBase> (converterType, targetType);
+               }
+               
+               Dictionary<Pair,XamlDirective> xaml_directives = new Dictionary<Pair,XamlDirective> ();
+               
+               public virtual XamlDirective GetXamlDirective (string xamlNamespace, string name)
+               {
+                       XamlDirective t;
+                       var p = new Pair (xamlNamespace, name);
+                       if (!xaml_directives.TryGetValue (p, out t)) {
+                               t = new XamlDirective (xamlNamespace, name);
+                               xaml_directives.Add (p, t);
+                       }
+                       return t;
+               }
+               
+               Dictionary<Type,XamlType> xaml_types = new Dictionary<Type,XamlType> ();
+               
+               public virtual XamlType GetXamlType (Type type)
+               {
+                       XamlType t;
+                       if (!xaml_types.TryGetValue (type, out t)) {
+                               t = new XamlType (type, this);
+                               xaml_types.Add (type, t);
+                       }
+                       return t;
+               }
+               
+               public XamlType GetXamlType (XamlTypeName xamlTypeName)
+               {
+                       if (xamlTypeName == null)
+                               throw new ArgumentNullException ("xamlTypeName");
+
+                       var n = xamlTypeName;
+                       if (n.TypeArguments.Count == 0) // non-generic
+                               return GetXamlType (n.Namespace, n.Name);
+
+                       // generic
+                       XamlType [] typeArgs = new XamlType [n.TypeArguments.Count];
+                       for (int i = 0; i < typeArgs.Length; i++)
+                               typeArgs [i] = GetXamlType (n.TypeArguments [i]);
+                       return GetXamlType (n.Namespace, n.Name, typeArgs);
+               }
+               
+               protected internal virtual XamlType GetXamlType (string xamlNamespace, string name, params XamlType [] typeArguments)
+               {
+                       string dummy;
+                       if (TryGetCompatibleXamlNamespace (xamlNamespace, out dummy))
+                               xamlNamespace = dummy;
+
+                       XamlType ret;
+                       if (xamlNamespace == XamlLanguage.Xaml2006Namespace) {
+                               ret = XamlLanguage.GetSpecialXaml2006Type (name);
+                               if (ret == null)
+                                       ret = XamlLanguage.AllTypes.FirstOrDefault (t => TypeMatches (t, xamlNamespace, name, typeArguments));
+                               if (ret != null)
+                                       return ret;
+                       }
+                       return GetAllXamlTypes (xamlNamespace).FirstOrDefault (t => TypeMatches (t, xamlNamespace, name, typeArguments));
+               }
+
+               bool TypeMatches (XamlType t, string ns, string name, XamlType [] typeArgs)
+               {
+                       return t.PreferredXamlNamespace == ns && t.Name == name && t.TypeArguments.ListEquals (typeArgs);
+               }
+
+               protected internal virtual Assembly OnAssemblyResolve (string assemblyName)
+               {
+                       return null;
+               }
+
+               public virtual bool TryGetCompatibleXamlNamespace (string xamlNamespace, out string compatibleNamespace)
+               {
+                       if (xamlNamespace == null)
+                               throw new ArgumentNullException ("xamlNamespace");
+                       if (compat_nss == null) {
+                               compat_nss = new Dictionary<string,string> ();
+                               foreach (var ass in AssembliesInScope)
+                                       FillCompatibilities (ass);
+                       }
+                       return compat_nss.TryGetValue (xamlNamespace, out compatibleNamespace);
+               }
+
+               void OnAssemblyLoaded (object o, AssemblyLoadEventArgs e)
+               {
+                       if (reference_assemblies != null)
+                               return; // do nothing
+
+                       if (xaml_nss != null)
+                               FillXamlNamespaces (e.LoadedAssembly);
+                       if (prefixes != null)
+                               FillPrefixes (e.LoadedAssembly);
+                       if (compat_nss != null)
+                               FillCompatibilities (e.LoadedAssembly);
+                       if (all_xaml_types != null)
+                               FillAllXamlTypes (e.LoadedAssembly);
+               }
+               
+               // cache updater methods
+               void FillXamlNamespaces (Assembly ass)
+               {
+                       foreach (XmlnsDefinitionAttribute xda in ass.GetCustomAttributes (typeof (XmlnsDefinitionAttribute), false))
+                               xaml_nss.Add (xda.XmlNamespace);
+               }
+               
+               void FillPrefixes (Assembly ass)
+               {
+                       foreach (XmlnsPrefixAttribute xpa in ass.GetCustomAttributes (typeof (XmlnsPrefixAttribute), false))
+                               prefixes.Add (xpa.XmlNamespace, xpa.Prefix);
+               }
+               
+               void FillCompatibilities (Assembly ass)
+               {
+                       foreach (XmlnsCompatibleWithAttribute xca in ass.GetCustomAttributes (typeof (XmlnsCompatibleWithAttribute), false))
+                               compat_nss.Add (xca.OldNamespace, xca.NewNamespace);
+               }
+
+               void FillAllXamlTypes (Assembly ass)
+               {
+                       foreach (XmlnsDefinitionAttribute xda in ass.GetCustomAttributes (typeof (XmlnsDefinitionAttribute), false)) {
+                               var l = new List<XamlType> ();
+                               all_xaml_types.Add (xda.XmlNamespace, l);
+                               foreach (var t in ass.GetTypes ())
+                                       if (t.Namespace == xda.ClrNamespace)
+                                               l.Add (GetXamlType (t));
+                       }
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlSchemaContextSettings.cs b/mcs/class/System.Xaml/System.Xaml/XamlSchemaContextSettings.cs
new file mode 100644 (file)
index 0000000..7285bdd
--- /dev/null
@@ -0,0 +1,52 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Xaml
+{
+       public class XamlSchemaContextSettings
+       {
+               public XamlSchemaContextSettings ()
+               {
+               }
+
+               public XamlSchemaContextSettings (XamlSchemaContextSettings settings)
+               {
+                       // null is allowed.
+                       var s = settings;
+                       if (s == null)
+                               return;
+                       FullyQualifyAssemblyNamesInClrNamespaces = s.FullyQualifyAssemblyNamesInClrNamespaces;
+                       SupportMarkupExtensionsWithDuplicateArity = s.SupportMarkupExtensionsWithDuplicateArity;
+               }
+
+               public bool FullyQualifyAssemblyNamesInClrNamespaces { get; set; }
+               public bool SupportMarkupExtensionsWithDuplicateArity { get; set; }
+
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlSchemaException.cs b/mcs/class/System.Xaml/System.Xaml/XamlSchemaException.cs
new file mode 100644 (file)
index 0000000..78de4f8
--- /dev/null
@@ -0,0 +1,53 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Runtime.Serialization;
+
+namespace System.Xaml
+{
+       [Serializable]
+       public class XamlSchemaException : XamlException
+       {
+               public XamlSchemaException ()
+                       : this ("XAML schema error")
+               {
+               }
+
+               public XamlSchemaException (string message)
+                       : this (message, null)
+               {
+               }
+
+               public XamlSchemaException (string message, Exception innerException)
+                       : base (message, innerException)
+               {
+               }
+
+               protected XamlSchemaException (SerializationInfo info, StreamingContext context)
+                       : base (info, context)
+               {
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlServices.cs b/mcs/class/System.Xaml/System.Xaml/XamlServices.cs
new file mode 100644 (file)
index 0000000..b70f876
--- /dev/null
@@ -0,0 +1,126 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Xml;
+
+namespace System.Xaml
+{
+       public static class XamlServices
+       {
+               public static Object Load (string fileName)
+               {
+                       using (var xr = XmlReader.Create (fileName))
+                               return Load (xr);
+               }
+
+               public static Object Load (Stream stream)
+               {
+                       return Load (new XamlXmlReader (stream));
+               }
+
+               public static Object Load (TextReader textReader)
+               {
+                       return Load (new XamlXmlReader (textReader));
+               }
+
+               public static Object Load (XmlReader xmlReader)
+               {
+                       return Load (new XamlXmlReader (xmlReader));
+               }
+
+               public static Object Load (XamlReader xamlReader)
+               {
+                       if (xamlReader == null)
+                               throw new ArgumentNullException ("xamlReader");
+                       var w = new XamlObjectWriter (xamlReader.SchemaContext);
+                       Transform (xamlReader, w);
+                       return w.Result;
+               }
+
+               public static Object Parse (string xaml)
+               {
+                       return Load (new StringReader (xaml));
+               }
+
+               public static string Save (object instance)
+               {
+                       var sw = new StringWriter ();
+                       Save (sw, instance);
+                       return sw.ToString ();
+               }
+
+               public static void Save (string fileName, object instance)
+               {
+                       using (var xw = XmlWriter.Create (fileName, new XmlWriterSettings () { OmitXmlDeclaration = true }))
+                               Save (xw, instance);
+               }
+
+               public static void Save (Stream stream, object instance)
+               {
+                       Save (new XamlXmlWriter (stream, new XamlSchemaContext ()), instance);
+               }
+
+               public static void Save (TextWriter textWriter, object instance)
+               {
+                       Save (new XamlXmlWriter (textWriter, new XamlSchemaContext ()), instance);
+               }
+
+               public static void Save (XmlWriter xmlWriter, object instance)
+               {
+                       Save (new XamlXmlWriter (xmlWriter, new XamlSchemaContext ()), instance);
+               }
+
+               public static void Save (XamlWriter xamlWriter, object instance)
+               {
+                       if (xamlWriter == null)
+                               throw new ArgumentNullException ("xamlWriter");
+                       var r = new XamlObjectReader (instance, xamlWriter.SchemaContext);
+                       Transform (r, xamlWriter);
+               }
+
+               public static void Transform (XamlReader xamlReader, XamlWriter xamlWriter)
+               {
+                       Transform (xamlReader, xamlWriter, true);
+               }
+
+               public static void Transform (XamlReader xamlReader, XamlWriter xamlWriter, bool closeWriter)
+               {
+                       if (xamlReader == null)
+                               throw new ArgumentNullException ("xamlReader");
+                       if (xamlWriter == null)
+                               throw new ArgumentNullException ("xamlWriter");
+
+                       if (xamlReader.NodeType == XamlNodeType.None)
+                               xamlReader.Read ();
+
+                       while (!xamlReader.IsEof) {
+                               xamlWriter.WriteNode (xamlReader);
+                               xamlReader.Read ();
+                       }
+                       if (closeWriter)
+                               xamlWriter.Close ();
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlType.cs b/mcs/class/System.Xaml/System.Xaml/XamlType.cs
new file mode 100644 (file)
index 0000000..9113484
--- /dev/null
@@ -0,0 +1,716 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Xaml
+{
+       public class XamlType : IEquatable<XamlType>
+       {
+               public XamlType (Type underlyingType, XamlSchemaContext schemaContext)
+                       : this (underlyingType, schemaContext, null)
+               {
+               }
+
+               static readonly Type [] predefined_types = {
+                               typeof (XData), typeof (Uri), typeof (TimeSpan), typeof (PropertyDefinition), typeof (MemberDefinition), typeof (Reference)
+                       };
+
+               public XamlType (Type underlyingType, XamlSchemaContext schemaContext, XamlTypeInvoker invoker)
+                       : this (schemaContext, invoker)
+               {
+                       if (underlyingType == null)
+                               throw new ArgumentNullException ("underlyingType");
+                       type = underlyingType;
+                       underlying_type = type;
+
+                       XamlType xt;
+                       if (XamlLanguage.InitializingTypes) {
+                               Name = type.GetXamlName ();
+                               PreferredXamlNamespace = XamlLanguage.Xaml2006Namespace;
+                       } else if ((xt = XamlLanguage.AllTypes.FirstOrDefault (t => t.UnderlyingType == type)) != null) {
+                               Name = xt.Name;
+                               PreferredXamlNamespace = XamlLanguage.Xaml2006Namespace;
+                       } else {
+                               Name = type.GetXamlName ();
+                               PreferredXamlNamespace = String.Format ("clr-namespace:{0};assembly={1}", type.Namespace, type.Assembly.GetName ().Name);
+                       }
+               }
+
+               public XamlType (string unknownTypeNamespace, string unknownTypeName, IList<XamlType> typeArguments, XamlSchemaContext schemaContext)
+                       : this (schemaContext, null)
+               {
+                       if (unknownTypeNamespace == null)
+                               throw new ArgumentNullException ("unknownTypeNamespace");
+                       if (unknownTypeName == null)
+                               throw new ArgumentNullException ("unknownTypeName");
+                       if (schemaContext == null)
+                               throw new ArgumentNullException ("schemaContext");
+
+                       type = typeof (object);
+                       Name = unknownTypeName;
+                       PreferredXamlNamespace = unknownTypeNamespace;
+                       TypeArguments = typeArguments != null && typeArguments.Count == 0 ? null : typeArguments;
+                       explicit_ns = unknownTypeNamespace;
+               }
+
+               protected XamlType (string typeName, IList<XamlType> typeArguments, XamlSchemaContext schemaContext)
+                       : this (String.Empty, typeName, typeArguments, schemaContext)
+               {
+               }
+
+               XamlType (XamlSchemaContext schemaContext, XamlTypeInvoker invoker)
+               {
+                       if (schemaContext == null)
+                               throw new ArgumentNullException ("schemaContext");
+                       SchemaContext = schemaContext;
+                       this.invoker = invoker ?? new XamlTypeInvoker (this);
+               }
+
+               Type type, underlying_type;
+
+               string explicit_ns;
+
+               // populated properties
+               XamlType base_type;
+               XamlTypeInvoker invoker;
+
+               internal EventHandler<XamlSetMarkupExtensionEventArgs> SetMarkupExtensionHandler {
+                       get { return LookupSetMarkupExtensionHandler (); }
+               }
+
+               internal EventHandler<XamlSetTypeConverterEventArgs> SetTypeConverterHandler {
+                       get { return LookupSetTypeConverterHandler (); }
+               }
+
+               public IList<XamlType> AllowedContentTypes {
+                       get { return LookupAllowedContentTypes (); }
+               }
+
+               public XamlType BaseType {
+                       get { return LookupBaseType (); }
+               }
+
+               public bool ConstructionRequiresArguments {
+                       get { return LookupConstructionRequiresArguments (); }
+               }
+
+               public XamlMember ContentProperty {
+                       get { return LookupContentProperty (); }
+               }
+
+               public IList<XamlType> ContentWrappers {
+                       get { return LookupContentWrappers (); }
+               }
+
+               public XamlValueConverter<XamlDeferringLoader> DeferringLoader {
+                       get { return LookupDeferringLoader (); }
+               }
+
+               public XamlTypeInvoker Invoker {
+                       get { return LookupInvoker (); }
+               }
+
+               public bool IsAmbient {
+                       get { return LookupIsAmbient (); }
+               }
+
+               public bool IsArray {
+                       get { return LookupCollectionKind () == XamlCollectionKind.Array; }
+               }
+
+               // it somehow treats array as not a collection...
+               public bool IsCollection {
+                       get { return LookupCollectionKind () == XamlCollectionKind.Collection; }
+               }
+
+               public bool IsConstructible {
+                       get { return LookupIsConstructible (); }
+               }
+
+               public bool IsDictionary {
+                       get { return LookupCollectionKind () == XamlCollectionKind.Dictionary; }
+               }
+
+               public bool IsGeneric {
+                       get { return type.IsGenericType; }
+               }
+
+               public bool IsMarkupExtension {
+                       get { return LookupIsMarkupExtension (); }
+               }
+               public bool IsNameScope {
+                       get { return LookupIsNameScope (); }
+               }
+               public bool IsNameValid {
+                       get { return XamlLanguage.IsValidXamlName (Name); }
+               }
+
+               public bool IsNullable {
+                       get { return LookupIsNullable (); }
+               }
+
+               public bool IsPublic {
+                       get { return LookupIsPublic (); }
+               }
+
+               public bool IsUnknown {
+                       get { return LookupIsUnknown (); }
+               }
+
+               public bool IsUsableDuringInitialization {
+                       get { return LookupUsableDuringInitialization (); }
+               }
+
+               public bool IsWhitespaceSignificantCollection {
+                       get { return LookupIsWhitespaceSignificantCollection (); }
+               }
+
+               public bool IsXData {
+                       get { return LookupIsXData (); }
+               }
+
+               public XamlType ItemType {
+                       get { return LookupItemType (); }
+               }
+
+               public XamlType KeyType {
+                       get { return LookupKeyType (); }
+               }
+
+               public XamlType MarkupExtensionReturnType {
+                       get { return LookupMarkupExtensionReturnType (); }
+               }
+
+               public string Name { get; private set; }
+
+               public string PreferredXamlNamespace { get; private set; }
+
+               public XamlSchemaContext SchemaContext { get; private set; }
+
+               public bool TrimSurroundingWhitespace {
+                       get { return LookupTrimSurroundingWhitespace (); }
+               }
+
+               public IList<XamlType> TypeArguments { get; private set; }
+
+               public XamlValueConverter<TypeConverter> TypeConverter {
+                       get { return LookupTypeConverter (); }
+               }
+
+               public Type UnderlyingType {
+                       get { return LookupUnderlyingType (); }
+               }
+
+               public XamlValueConverter<ValueSerializer> ValueSerializer {
+                       get { return LookupValueSerializer (); }
+               }
+
+               public static bool operator == (XamlType left, XamlType right)
+               {
+                       return IsNull (left) ? IsNull (right) : left.Equals (right);
+               }
+
+               static bool IsNull (XamlType a)
+               {
+                       return Object.ReferenceEquals (a, null);
+               }
+
+               public static bool operator != (XamlType left, XamlType right)
+               {
+                       return !(left == right);
+               }
+               
+               public bool Equals (XamlType other)
+               {
+                       return !IsNull (other) &&
+                               UnderlyingType == other.UnderlyingType &&
+                               Name == other.Name &&
+                               PreferredXamlNamespace == other.PreferredXamlNamespace && TypeArguments.ListEquals (other.TypeArguments);
+               }
+
+               public override bool Equals (object obj)
+               {
+                       var a = obj as XamlType;
+                       return Equals (a);
+               }
+               
+               public override int GetHashCode ()
+               {
+                       if (UnderlyingType != null)
+                               return UnderlyingType.GetHashCode ();
+                       int x = Name.GetHashCode () << 7 + PreferredXamlNamespace.GetHashCode ();
+                       if (TypeArguments != null)
+                               foreach (var t in TypeArguments)
+                                       x = t.GetHashCode () + x << 5;
+                       return x;
+               }
+
+               public override string ToString ()
+               {
+                       return String.IsNullOrEmpty (PreferredXamlNamespace) ? Name : String.Concat ("{", PreferredXamlNamespace, "}", Name);
+               }
+
+               public virtual bool CanAssignTo (XamlType xamlType)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               public XamlMember GetAliasedProperty (XamlDirective directive)
+               {
+                       return LookupAliasedProperty (directive);
+               }
+
+               public ICollection<XamlMember> GetAllAttachableMembers ()
+               {
+                       return new List<XamlMember> (LookupAllAttachableMembers ());
+               }
+
+               public ICollection<XamlMember> GetAllMembers ()
+               {
+                       return new List<XamlMember> (LookupAllMembers ());
+               }
+
+               public XamlMember GetAttachableMember (string name)
+               {
+                       return LookupAttachableMember (name);
+               }
+
+               public XamlMember GetMember (string name)
+               {
+                       return LookupMember (name, false);
+               }
+
+               public IList<XamlType> GetPositionalParameters (int parameterCount)
+               {
+                       return LookupPositionalParameters (parameterCount);
+               }
+
+               public virtual IList<string> GetXamlNamespaces ()
+               {
+                       throw new NotImplementedException ();
+                       /* this does not work like documented!
+                       if (explicit_ns != null)
+                               return new string [] {explicit_ns};
+                       var l = SchemaContext.GetAllXamlNamespaces ();
+                       if (l != null)
+                               return new List<string> (l);
+                       return new string [] {String.Empty};
+                       */
+               }
+
+               // lookups
+
+               protected virtual XamlMember LookupAliasedProperty (XamlDirective directive)
+               {
+                       if (directive == XamlLanguage.Key) {
+                               var a = this.GetCustomAttribute<DictionaryKeyPropertyAttribute> ();
+                               return a != null ? GetMember (a.Name) : null;
+                       }
+                       if (directive == XamlLanguage.Name) {
+                               var a = this.GetCustomAttribute<RuntimeNamePropertyAttribute> ();
+                               return a != null ? GetMember (a.Name) : null;
+                       }
+                       if (directive == XamlLanguage.Uid) {
+                               var a = this.GetCustomAttribute<UidPropertyAttribute> ();
+                               return a != null ? GetMember (a.Name) : null;
+                       }
+                       if (directive == XamlLanguage.Lang) {
+                               var a = this.GetCustomAttribute<XmlLangPropertyAttribute> ();
+                               return a != null ? GetMember (a.Name) : null;
+                       }
+                       return null;
+               }
+
+               protected virtual IEnumerable<XamlMember> LookupAllAttachableMembers ()
+               {
+                       if (UnderlyingType == null)
+                               return BaseType != null ? BaseType.GetAllMembers () : null;
+                       return DoLookupAllAttachableMembers ();
+               }
+
+               IEnumerable<XamlMember> DoLookupAllAttachableMembers ()
+               {
+                       yield break; // FIXME: what to return here?
+               }
+
+               protected virtual IEnumerable<XamlMember> LookupAllMembers ()
+               {
+                       if (UnderlyingType == null)
+                               return BaseType != null ? BaseType.GetAllMembers () : null;
+                       if (all_members_cache == null)
+                               all_members_cache = new List<XamlMember> (DoLookupAllMembers ());
+                       return all_members_cache;
+               }
+
+               List<XamlMember> all_members_cache;
+
+               IEnumerable<XamlMember> DoLookupAllMembers ()
+               {
+                       foreach (var pi in UnderlyingType.GetProperties ())
+                               if (pi.CanRead && pi.CanWrite && pi.GetIndexParameters ().Length == 0)
+                                       yield return new XamlMember (pi, SchemaContext);
+               }
+
+               protected virtual IList<XamlType> LookupAllowedContentTypes ()
+               {
+                       // the actual implementation is very different from what is documented :(
+                       return null;
+
+                       /*
+                       var l = new List<XamlType> ();
+                       if (ContentWrappers != null)
+                               l.AddRange (ContentWrappers);
+                       if (ContentProperty != null)
+                               l.Add (ContentProperty.Type);
+                       if (ItemType != null)
+                               l.Add (ItemType);
+                       return l.Count > 0 ? l : null;
+                       */
+               }
+
+               protected virtual XamlMember LookupAttachableMember (string name)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               [MonoTODO]
+               protected virtual XamlType LookupBaseType ()
+               {
+                       if (base_type == null) {
+                               if (UnderlyingType == null)
+                                       // FIXME: probably something advanced is needed here.
+                                       base_type = new XamlType (typeof (object), SchemaContext, Invoker);
+                               else
+                                       base_type = type.BaseType == null || type.BaseType == typeof (object) ? null : new XamlType (type.BaseType, SchemaContext, Invoker);
+                       }
+                       return base_type;
+               }
+
+               // This implementation is not verified. (No place to use.)
+               protected virtual XamlCollectionKind LookupCollectionKind ()
+               {
+                       if (UnderlyingType == null)
+                               return BaseType != null ? BaseType.LookupCollectionKind () : XamlCollectionKind.None;
+                       if (type.IsArray)
+                               return XamlCollectionKind.Array;
+
+                       if (type.ImplementsAnyInterfacesOf (typeof (IDictionary), typeof (IDictionary<,>)))
+                               return XamlCollectionKind.Dictionary;
+
+                       if (type.ImplementsAnyInterfacesOf (typeof (ICollection), typeof (ICollection<>)))
+                               return XamlCollectionKind.Collection;
+
+                       return XamlCollectionKind.None;
+               }
+
+               protected virtual bool LookupConstructionRequiresArguments ()
+               {
+                       if (UnderlyingType == null)
+                               return false;
+
+                       // not sure if it is required, but MemberDefinition return true while they are abstract and it makes no sense.
+                       if (UnderlyingType.IsAbstract)
+                               return true;
+
+                       // FIXME: probably some primitive types are treated as special.
+                       switch (Type.GetTypeCode (UnderlyingType)) {
+                       case TypeCode.String:
+                               return true;
+                       case TypeCode.Object:
+                               if (UnderlyingType == typeof (TimeSpan))
+                                       return false;
+                               break;
+                       default:
+                               return false;
+                       }
+
+                       return UnderlyingType.GetConstructor (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null) == null;
+               }
+
+               protected virtual XamlMember LookupContentProperty ()
+               {
+                       var a = this.GetCustomAttribute<ContentPropertyAttribute> ();
+                       return a != null && a.Name != null ? GetMember (a.Name) : null;
+               }
+
+               protected virtual IList<XamlType> LookupContentWrappers ()
+               {
+                       if (CustomAttributeProvider == null)
+                               return null;
+
+                       var arr = CustomAttributeProvider.GetCustomAttributes (typeof (ContentWrapperAttribute), false);
+                       if (arr == null || arr.Length == 0)
+                               return null;
+                       var l = new XamlType [arr.Length];
+                       for (int i = 0; i < l.Length; i++) 
+                               l [i] = SchemaContext.GetXamlType (((ContentWrapperAttribute) arr [i]).ContentWrapper);
+                       return l;
+               }
+
+               internal ICustomAttributeProvider CustomAttributeProvider {
+                       get { return LookupCustomAttributeProvider (); }
+               }
+
+               protected virtual ICustomAttributeProvider LookupCustomAttributeProvider ()
+               {
+                       return UnderlyingType;
+               }
+               protected virtual XamlValueConverter<XamlDeferringLoader> LookupDeferringLoader ()
+               {
+                       throw new NotImplementedException ();
+               }
+
+               protected virtual XamlTypeInvoker LookupInvoker ()
+               {
+                       return invoker;
+               }
+
+               protected virtual bool LookupIsAmbient ()
+               {
+                       return this.GetCustomAttribute<AmbientAttribute> () != null;
+               }
+
+               // It is documented as if it were to reflect spec. section 5.2,
+               // but the actual behavior shows it is *totally* wrong.
+               // Here I have implemented this based on the nunit test results. sigh.
+               protected virtual bool LookupIsConstructible ()
+               {
+                       if (UnderlyingType == null)
+                               return true;
+                       if (IsMarkupExtension)
+                               return true;
+                       if (UnderlyingType.IsAbstract)
+                               return false;
+                       if (!IsNameValid)
+                               return false;
+                       return true;
+               }
+
+               protected virtual bool LookupIsMarkupExtension ()
+               {
+                       return typeof (MarkupExtension).IsAssignableFrom (UnderlyingType);
+               }
+
+               protected virtual bool LookupIsNameScope ()
+               {
+                       return typeof (INameScope).IsAssignableFrom (UnderlyingType);
+               }
+
+               protected virtual bool LookupIsNullable ()
+               {
+                       return !type.IsValueType || type.ImplementsInterface (typeof (Nullable<>));
+               }
+
+               protected virtual bool LookupIsPublic ()
+               {
+                       return underlying_type == null || underlying_type.IsPublic || underlying_type.IsNestedPublic;
+               }
+
+               protected virtual bool LookupIsUnknown ()
+               {
+                       return UnderlyingType == null;
+               }
+
+               protected virtual bool LookupIsWhitespaceSignificantCollection ()
+               {
+                       // probably for unknown types, it should preserve whitespaces.
+                       return IsUnknown || this.GetCustomAttribute<WhitespaceSignificantCollectionAttribute> () != null;
+               }
+
+               protected virtual bool LookupIsXData ()
+               {
+                       // huh? XamlLanguage.XData.IsXData returns false(!)
+                       // return typeof (XData).IsAssignableFrom (UnderlyingType);
+                       return false;
+               }
+
+               protected virtual XamlType LookupItemType ()
+               {
+                       if (IsArray)
+                               return new XamlType (type.GetElementType (), SchemaContext);
+                       if (!IsCollection)
+                               return null;
+                       if (!IsGeneric)
+                               return new XamlType (typeof (object), SchemaContext);
+                       return new XamlType (type.GetGenericArguments () [0], SchemaContext);
+               }
+
+               protected virtual XamlType LookupKeyType ()
+               {
+                       if (!IsDictionary)
+                               return null;
+                       if (!IsGeneric)
+                               return new XamlType (typeof (object), SchemaContext);
+                       return new XamlType (type.GetGenericArguments () [0], SchemaContext);
+               }
+
+               protected virtual XamlType LookupMarkupExtensionReturnType ()
+               {
+                       var a = this.GetCustomAttribute<MarkupExtensionReturnTypeAttribute> ();
+                       return a != null ? new XamlType (a.ReturnType, SchemaContext) : null;
+               }
+
+               protected virtual XamlMember LookupMember (string name, bool skipReadOnlyCheck)
+               {
+                       var pi = UnderlyingType.GetProperty (name);
+                       if (pi != null && (skipReadOnlyCheck || pi.CanWrite))
+                               return new XamlMember (pi, SchemaContext);
+                       var ei = UnderlyingType.GetEvent (name);
+                       if (ei != null)
+                               return new XamlMember (ei, SchemaContext);
+                       return null;
+               }
+
+               protected virtual IList<XamlType> LookupPositionalParameters (int parameterCount)
+               {
+                       if (UnderlyingType == null/* || !IsMarkupExtension*/) // see nunit tests...
+                               return null;
+
+                       // check if there is applicable ConstructorArgumentAttribute.
+                       // If there is, then return its type.
+                       if (parameterCount == 1) {
+                               foreach (var xm in GetAllMembers ()) {
+                                       var ca = xm.CustomAttributeProvider.GetCustomAttribute<ConstructorArgumentAttribute> (false);
+                                       if (ca != null)
+                                               return new XamlType [] {xm.Type};
+                               }
+                       }
+
+                       var methods = (from m in UnderlyingType.GetConstructors (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) where m.GetParameters ().Length == parameterCount select m).ToArray ();
+                       if (methods.Length == 1)
+                               return (from p in methods [0].GetParameters () select SchemaContext.GetXamlType (p.ParameterType)).ToArray ();
+
+                       if (SchemaContext.SupportMarkupExtensionsWithDuplicateArity)
+                               throw new NotSupportedException ("The default LookupPositionalParameters implementation does not allow duplicate arity of markup extensions");
+                       return null;
+               }
+
+               BindingFlags flags_get_static = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
+
+               protected virtual EventHandler<XamlSetMarkupExtensionEventArgs> LookupSetMarkupExtensionHandler ()
+               {
+                       var a = this.GetCustomAttribute<XamlSetMarkupExtensionAttribute> ();
+                       if (a == null)
+                               return null;
+                       var mi = type.GetMethod (a.XamlSetMarkupExtensionHandler, flags_get_static);
+                       if (mi == null)
+                               throw new ArgumentException ("Binding to XamlSetMarkupExtensionHandler failed");
+                       return (EventHandler<XamlSetMarkupExtensionEventArgs>) Delegate.CreateDelegate (typeof (EventHandler<XamlSetMarkupExtensionEventArgs>), mi);
+               }
+
+               protected virtual EventHandler<XamlSetTypeConverterEventArgs> LookupSetTypeConverterHandler ()
+               {
+                       var a = this.GetCustomAttribute<XamlSetTypeConverterAttribute> ();
+                       if (a == null)
+                               return null;
+                       var mi = type.GetMethod (a.XamlSetTypeConverterHandler, flags_get_static);
+                       if (mi == null)
+                               throw new ArgumentException ("Binding to XamlSetTypeConverterHandler failed");
+                       return (EventHandler<XamlSetTypeConverterEventArgs>) Delegate.CreateDelegate (typeof (EventHandler<XamlSetTypeConverterEventArgs>), mi);
+               }
+
+               protected virtual bool LookupTrimSurroundingWhitespace ()
+               {
+                       return this.GetCustomAttribute<TrimSurroundingWhitespaceAttribute> () != null;
+               }
+
+               protected virtual XamlValueConverter<TypeConverter> LookupTypeConverter ()
+               {
+                       var t = UnderlyingType;
+                       if (t == null)
+                               return null;
+
+                       // equivalent to TypeExtension.
+                       // FIXME: not sure if it should be specially handled here.
+                       if (t == typeof (Type))
+                               t = typeof (TypeExtension);
+
+                       var a = CustomAttributeProvider.GetCustomAttribute<TypeConverterAttribute> (false);
+                       if (a != null)
+                               return SchemaContext.GetValueConverter<TypeConverter> (Type.GetType (a.ConverterTypeName), this);
+
+                       if (t == typeof (object))
+                               return SchemaContext.GetValueConverter<TypeConverter> (typeof (TypeConverter), this);
+
+                       // It's still not decent to check CollectionConverter.
+                       var tct = TypeDescriptor.GetConverter (t).GetType ();
+                       if (tct != typeof (TypeConverter) && tct != typeof (CollectionConverter) && tct != typeof (ReferenceConverter))
+                               return SchemaContext.GetValueConverter<TypeConverter> (tct, this);
+                       return null;
+               }
+
+               protected virtual Type LookupUnderlyingType ()
+               {
+                       return underlying_type;
+               }
+
+               protected virtual bool LookupUsableDuringInitialization ()
+               {
+                       var a = this.GetCustomAttribute<UsableDuringInitializationAttribute> ();
+                       return a != null && a.Usable;
+               }
+
+               static XamlValueConverter<ValueSerializer> string_value_serializer;
+
+               protected virtual XamlValueConverter<ValueSerializer> LookupValueSerializer ()
+               {
+                       return LookupValueSerializer (this, CustomAttributeProvider);
+               }
+
+               internal static XamlValueConverter<ValueSerializer> LookupValueSerializer (XamlType targetType, ICustomAttributeProvider provider)
+               {
+                       if (provider == null)
+                               return null;
+
+                       var a = provider.GetCustomAttribute<ValueSerializerAttribute> (true);
+                       if (a != null)
+                               return new XamlValueConverter<ValueSerializer> (a.ValueSerializerType ?? Type.GetType (a.ValueSerializerTypeName), targetType);
+
+                       if (targetType.BaseType != null) {
+                               var ret = targetType.BaseType.LookupValueSerializer ();
+                               if (ret != null)
+                                       return ret;
+                       }
+
+                       if (targetType.UnderlyingType == typeof (string)) {
+                               if (string_value_serializer == null)
+                                       string_value_serializer = new XamlValueConverter<ValueSerializer> (typeof (StringValueSerializer), targetType);
+                               return string_value_serializer;
+                       }
+
+                       return null;
+               }
+
+               internal IEnumerable<XamlMember> GetConstructorArguments ()
+               {
+                       return GetAllMembers ().Where (m => m.UnderlyingMember != null && m.CustomAttributeProvider.GetCustomAttribute<ConstructorArgumentAttribute> (false) != null);
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlWriter.cs b/mcs/class/System.Xaml/System.Xaml/XamlWriter.cs
new file mode 100644 (file)
index 0000000..7e397dc
--- /dev/null
@@ -0,0 +1,93 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+
+namespace System.Xaml
+{
+       public abstract class XamlWriter : IDisposable
+       {
+               protected bool IsDisposed { get; private set; }
+               public abstract XamlSchemaContext SchemaContext { get; }
+
+               public void Close ()
+               {
+                       Dispose (true);
+               }
+
+               protected virtual void Dispose (bool disposing)
+               {
+                       IsDisposed = true;
+               }
+
+               void IDisposable.Dispose ()
+               {
+                       Dispose (true);
+               }
+
+               public abstract void WriteEndMember ();
+               public abstract void WriteEndObject ();
+               public abstract void WriteGetObject ();
+               public abstract void WriteNamespace (NamespaceDeclaration namespaceDeclaration);
+               public abstract void WriteStartMember (XamlMember xamlMember);
+               public abstract void WriteStartObject (XamlType type);
+               public abstract void WriteValue (object value);
+
+               public void WriteNode (XamlReader reader)
+               {
+                       if (reader == null)
+                               throw new ArgumentNullException ("reader");
+
+                       switch (reader.NodeType) {
+                       case XamlNodeType.StartObject:
+                               WriteStartObject (reader.Type);
+                               break;
+                       case XamlNodeType.GetObject:
+                               WriteGetObject ();
+                               break;
+                       case XamlNodeType.EndObject:
+                               WriteEndObject ();
+                               break;
+                       case XamlNodeType.StartMember:
+                               WriteStartMember (reader.Member);
+                               break;
+                       case XamlNodeType.EndMember:
+                               WriteEndMember ();
+                               break;
+                       case XamlNodeType.Value:
+                               WriteValue (reader.Value);
+                               break;
+                       case XamlNodeType.NamespaceDeclaration:
+                               WriteNamespace (reader.Namespace);
+                               break;
+                       default:
+                               throw NotImplemented (); // documented behavior
+                       }
+               }
+
+               Exception NotImplemented ()
+               {
+                       return new NotImplementedException ();
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlWriterSettings.cs b/mcs/class/System.Xaml/System.Xaml/XamlWriterSettings.cs
new file mode 100644 (file)
index 0000000..78ca181
--- /dev/null
@@ -0,0 +1,43 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Xaml
+{
+       public class XamlWriterSettings
+       {
+               public XamlWriterSettings ()
+               {
+               }
+
+               public XamlWriterSettings (XamlWriterSettings settings)
+               {
+                       // huh, what to do?
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlWriterStateManager.cs b/mcs/class/System.Xaml/System.Xaml/XamlWriterStateManager.cs
new file mode 100644 (file)
index 0000000..b5d0005
--- /dev/null
@@ -0,0 +1,257 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Xml;
+
+/*
+
+* State transition
+
+Unlike XmlWriter, XAML nodes are not immediately writable because object
+output has to be delayed to be determined whether it should write
+an attribute or an element.
+
+** NamespaceDeclarations
+
+NamespaceDeclaration does not immediately participate in the state transition
+but some write methods reject stored namespaces (e.g. WriteEndObject cannot
+handle them). In such cases, they throw InvalidOperationException, while the
+writer throws XamlXmlWriterException for usual state transition.
+
+Though they still seems to affect some outputs. If a member with simple
+value is written after a namespace, then it becomes an element, not attribute.
+
+** state transition
+
+states are: Initial, ObjectStarted, MemberStarted, ValueWritten, MemberDone, End
+
+Initial + StartObject -> ObjectStarted : push(xt)
+ObjectStarted + StartMember -> MemberStarted : push(xm)
+ObjectStarted + EndObject -> ObjectWritten or End : pop()
+MemberStarted + StartObject -> ObjectStarted : push(xt)
+MemberStarted + Value -> ValueWritten
+MemberStarted + GetObject -> MemberDone : pop()
+ObjectWritten + StartObject -> ObjectStarted : push(x)
+ObjectWritten + Value -> ValueWritten : pop()
+ObjectWritten + EndMember -> MemberDone : pop()
+ValueWritten + StartObject -> invalid - or - ObjectStarted : push(x)
+ValueWritten + Value -> invalid - or - ValueWritten
+ValueWritten + EndMember -> MemberDone : pop()
+MemberDone + EndObject -> ObjectWritten or End : pop() // xt
+MemberDone + StartMember -> MemberStarted : push(xm)
+
+(in XamlObjectWriter, Value must be followed by EndMember.)
+
+*/
+
+namespace System.Xaml
+{
+       internal class XamlWriterStateManager<TError,TNSError> : XamlWriterStateManager
+               where TError : Exception
+               where TNSError : Exception
+       {
+               public XamlWriterStateManager (bool isXmlWriter)
+                       : base (isXmlWriter)
+               {
+               }
+
+               public override Exception CreateError (string msg)
+               {
+                       return (Exception) Activator.CreateInstance (typeof (TError), new object [] {msg});
+               }
+
+               public override Exception CreateNamespaceError (string msg)
+               {
+                       return (Exception) Activator.CreateInstance (typeof (TNSError), new object [] {msg});
+               }
+       }
+
+       internal abstract class XamlWriterStateManager
+       {
+               public XamlWriterStateManager (bool isXmlWriter)
+               {
+                       allow_ns_at_value = isXmlWriter;
+                       allow_object_after_value = isXmlWriter;
+                       allow_parallel_values = !isXmlWriter;
+                       allow_empty_member = !isXmlWriter;
+               }
+
+               enum XamlWriteState
+               {
+                       Initial,
+                       ObjectStarted,
+                       MemberStarted,
+                       ObjectWritten,
+                       ValueWritten,
+                       MemberDone,
+                       End
+               }
+
+               // configuration
+               bool allow_ns_at_value, allow_object_after_value, allow_parallel_values, allow_empty_member;
+
+               // state
+               XamlWriteState state = XamlWriteState.Initial;
+               bool ns_pushed;
+
+               public void OnClosingItem ()
+               {
+                       // somewhat hacky state change to not reject StartMember->EndMember.
+                       if (state == XamlWriteState.MemberStarted)
+                               state = XamlWriteState.ValueWritten;
+               }
+
+               public void EndMember ()
+               {
+                       RejectNamespaces (XamlNodeType.EndMember);
+                       CheckState (XamlNodeType.EndMember);
+                       state = XamlWriteState.MemberDone;
+               }
+
+               public void EndObject (bool hasMoreNodes)
+               {
+                       RejectNamespaces (XamlNodeType.EndObject);
+                       CheckState (XamlNodeType.EndObject);
+                       state = hasMoreNodes ? XamlWriteState.ObjectWritten : XamlWriteState.End;
+               }
+
+               public void GetObject ()
+               {
+                       CheckState (XamlNodeType.GetObject);
+                       RejectNamespaces (XamlNodeType.GetObject);
+                       state = XamlWriteState.MemberDone;
+               }
+
+               public void StartMember ()
+               {
+                       CheckState (XamlNodeType.StartMember);
+                       state = XamlWriteState.MemberStarted;
+                       ns_pushed = false;
+               }
+
+               public void StartObject ()
+               {
+                       CheckState (XamlNodeType.StartObject);
+                       state = XamlWriteState.ObjectStarted;
+                       ns_pushed = false;
+               }
+
+               public void Value ()
+               {
+                       CheckState (XamlNodeType.Value);
+                       RejectNamespaces (XamlNodeType.Value);
+                       state = XamlWriteState.ValueWritten;
+               }
+
+               public void Namespace ()
+               {
+                       if (!allow_ns_at_value && state == XamlWriteState.ValueWritten)
+                               throw CreateError (String.Format ("Namespace declarations cannot be written at {0} state", state));
+                       ns_pushed = true;
+               }
+
+               public void NamespaceCleanedUp ()
+               {
+                       ns_pushed = false;
+               }
+
+               void CheckState (XamlNodeType next)
+               {
+                       switch (state) {
+                       case XamlWriteState.Initial:
+                               switch (next) {
+                               case XamlNodeType.StartObject:
+                                       return;
+                               }
+                               break;
+                       case XamlWriteState.ObjectStarted:
+                               switch (next) {
+                               case XamlNodeType.StartMember:
+                               case XamlNodeType.EndObject:
+                                       return;
+                               }
+                               break;
+                       case XamlWriteState.MemberStarted:
+                               switch (next) {
+                               case XamlNodeType.StartObject:
+                               case XamlNodeType.Value:
+                               case XamlNodeType.GetObject:
+                                       return;
+                               case XamlNodeType.EndMember:
+                                       if (allow_empty_member)
+                                               return;
+                                       break;
+                               }
+                               break;
+                       case XamlWriteState.ObjectWritten:
+                               switch (next) {
+                               case XamlNodeType.StartObject:
+                               case XamlNodeType.Value:
+                               case XamlNodeType.EndMember:
+                                       return;
+                               }
+                               break;
+                       case XamlWriteState.ValueWritten:
+                               switch (next) {
+                               case XamlNodeType.Value:
+                                       if (allow_parallel_values)
+                                               return;
+                                       break;
+                               case XamlNodeType.StartObject:
+                                       if (allow_object_after_value)
+                                               return;
+                                       break;
+                               case XamlNodeType.EndMember:
+                                       return;
+                               }
+                               break;
+                       case XamlWriteState.MemberDone:
+                               switch (next) {
+                               case XamlNodeType.StartMember:
+                               case XamlNodeType.EndObject:
+                                       return;
+                               }
+                               break;
+                       }
+                       throw CreateError (String.Format ("{0} is not allowed at current state {1}", next, state));
+               }
+               
+               void RejectNamespaces (XamlNodeType next)
+               {
+                       if (ns_pushed) {
+                               // strange, but on WriteEndMember it throws XamlXmlWriterException, while for other nodes it throws IOE.
+                               string msg = String.Format ("Namespace declarations cannot be written before {0}", next);
+                               if (next == XamlNodeType.EndMember)
+                                       throw CreateError (msg);
+                               else
+                                       throw CreateNamespaceError (msg);
+                       }
+               }
+
+               public abstract Exception CreateError (string msg);
+               public abstract Exception CreateNamespaceError (string msg);
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlXmlReader.cs b/mcs/class/System.Xaml/System.Xaml/XamlXmlReader.cs
new file mode 100644 (file)
index 0000000..eab4174
--- /dev/null
@@ -0,0 +1,472 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Xml;
+using System.Xaml.Schema;
+
+using Pair = System.Collections.Generic.KeyValuePair<System.Xaml.XamlMember,string>;
+
+namespace System.Xaml
+{
+       // FIXME: is GetObject supported by this reader?
+       public class XamlXmlReader : XamlReader, IXamlLineInfo
+       {
+               #region constructors
+
+               public XamlXmlReader (Stream stream)
+                       : this (stream, (XamlXmlReaderSettings) null)
+               {
+               }
+
+               public XamlXmlReader (string fileName)
+                       : this (fileName, (XamlXmlReaderSettings) null)
+               {
+               }
+
+               public XamlXmlReader (TextReader textReader)
+                       : this (textReader, (XamlXmlReaderSettings) null)
+               {
+               }
+
+               public XamlXmlReader (XmlReader xmlReader)
+                       : this (xmlReader, (XamlXmlReaderSettings) null)
+               {
+               }
+
+               public XamlXmlReader (Stream stream, XamlSchemaContext schemaContext)
+                       : this (stream, schemaContext, null)
+               {
+               }
+
+               public XamlXmlReader (Stream stream, XamlXmlReaderSettings settings)
+                       : this (stream, new XamlSchemaContext (null, null), settings)
+               {
+               }
+
+               public XamlXmlReader (string fileName, XamlSchemaContext schemaContext)
+                       : this (fileName, schemaContext, null)
+               {
+               }
+
+               public XamlXmlReader (string fileName, XamlXmlReaderSettings settings)
+                       : this (fileName, new XamlSchemaContext (null, null), settings)
+               {
+               }
+
+               public XamlXmlReader (TextReader textReader, XamlSchemaContext schemaContext)
+                       : this (textReader, schemaContext, null)
+               {
+               }
+
+               public XamlXmlReader (TextReader textReader, XamlXmlReaderSettings settings)
+                       : this (textReader, new XamlSchemaContext (null, null), settings)
+               {
+               }
+
+               public XamlXmlReader (XmlReader xmlReader, XamlSchemaContext schemaContext)
+                       : this (xmlReader, schemaContext, null)
+               {
+               }
+
+               public XamlXmlReader (XmlReader xmlReader, XamlXmlReaderSettings settings)
+                       : this (xmlReader, new XamlSchemaContext (null, null), settings)
+               {
+               }
+
+               public XamlXmlReader (Stream stream, XamlSchemaContext schemaContext, XamlXmlReaderSettings settings)
+                       : this (XmlReader.Create (stream), schemaContext, settings)
+               {
+               }
+
+               static readonly XmlReaderSettings file_reader_settings = new XmlReaderSettings () { CloseInput =true };
+
+               public XamlXmlReader (string fileName, XamlSchemaContext schemaContext, XamlXmlReaderSettings settings)
+                       : this (XmlReader.Create (fileName, file_reader_settings), schemaContext, settings)
+               {
+               }
+
+               public XamlXmlReader (TextReader textReader, XamlSchemaContext schemaContext, XamlXmlReaderSettings settings)
+                       : this (XmlReader.Create (textReader), schemaContext, settings)
+               {
+               }
+
+               public XamlXmlReader (XmlReader xmlReader, XamlSchemaContext schemaContext, XamlXmlReaderSettings settings)
+               {
+                       if (xmlReader == null)
+                               throw new ArgumentNullException ("xmlReader");
+                       if (schemaContext == null)
+                               throw new ArgumentNullException ("schemaContext");
+
+                       sctx = schemaContext;
+                       this.settings = settings ?? new XamlXmlReaderSettings ();
+
+                       // filter out some nodes.
+                       var xrs = new XmlReaderSettings () {
+                               CloseInput = this.settings.CloseInput,
+                               IgnoreComments = true,
+                               IgnoreProcessingInstructions = true,
+                               IgnoreWhitespace = true };
+
+                       r = XmlReader.Create (xmlReader, xrs);
+                       line_info = r as IXmlLineInfo;
+                       xaml_namespace_resolver = new NamespaceResolver (r as IXmlNamespaceResolver);
+               }
+               
+               #endregion
+
+               XmlReader r;
+               IXmlLineInfo line_info;
+               XamlSchemaContext sctx;
+               XamlXmlReaderSettings settings;
+               bool is_eof;
+               XamlNodeType node_type;
+               
+               object current;
+               bool inside_object_not_member, is_empty_object, is_empty_member;
+               Stack<XamlType> types = new Stack<XamlType> ();
+               XamlMember current_member;
+
+               List<Pair> stored_members = new List<Pair> ();
+               IEnumerator<Pair> stored_member_enumerator;
+               IXamlNamespaceResolver xaml_namespace_resolver;
+
+               public bool HasLineInfo {
+                       get { return line_info != null && line_info.HasLineInfo (); }
+               }
+
+               public override bool IsEof {
+                       get { return is_eof; }
+               }
+
+               public int LineNumber {
+                       get { return line_info != null ? line_info.LineNumber : 0; }
+               }
+
+               public int LinePosition {
+                       get { return line_info != null ? line_info.LinePosition : 0; }
+               }
+
+               public override XamlMember Member {
+                       get { return current as XamlMember; }
+               }
+               public override NamespaceDeclaration Namespace {
+                       get { return current as NamespaceDeclaration; }
+               }
+
+               public override XamlNodeType NodeType {
+                       get { return node_type; }
+               }
+
+               public override XamlSchemaContext SchemaContext {
+                       get { return sctx; }
+               }
+
+               public override XamlType Type {
+                       get { return current as XamlType; }
+               }
+
+               public override object Value {
+                       get { return NodeType == XamlNodeType.Value ? current : null; }
+               }
+
+               public override bool Read ()
+               {
+                       if (IsDisposed)
+                               throw new ObjectDisposedException ("reader");
+                       if (is_eof)
+                               return false;
+
+                       // check this before is_empty_* so that they aren't ignored.
+                       if (MoveToNextAttributeMember ())
+                               return true;
+
+                       if (is_empty_object) {
+                               is_empty_object = false;
+                               ReadEndType ();
+                               return true;
+                       }
+                       if (is_empty_member) {
+                               is_empty_member = false;
+                               ReadEndMember ();
+                               return true;
+                       }
+
+                       bool attrIterated = false;
+                       if (r.NodeType == XmlNodeType.Attribute) {
+                               attrIterated = true;
+                               if (r.MoveToNextAttribute ())
+                                       if (CheckNextNamespace ())
+                                               return true;
+                       }
+
+                       if (!r.EOF)
+                               r.MoveToContent ();
+                       if (r.EOF) {
+                               is_eof = true;
+                               return false;
+                       }
+
+                       switch (r.NodeType) {
+                       case XmlNodeType.Element:
+
+                               // could be: StartObject, StartMember, optionally preceding NamespaceDeclarations
+                               if (!attrIterated && r.MoveToFirstAttribute ())
+                                       if (CheckNextNamespace ())
+                                               return true;
+                               r.MoveToElement ();
+                               
+                               if (inside_object_not_member)
+                                       ReadStartMember ();
+                               else
+                                       ReadStartType ();
+                               return true;
+
+                       case XmlNodeType.EndElement:
+
+                               // could be: EndObject, EndMember
+                               if (inside_object_not_member)
+                                       ReadEndType ();
+                               else
+                                       ReadEndMember ();
+                               return true;
+
+                       default:
+
+                               // could be: Value
+                               ReadValue ();
+                               return true;
+                       }
+               }
+
+               bool CheckNextNamespace ()
+               {
+                       do {
+                               if (r.NamespaceURI == XamlLanguage.Xmlns2000Namespace) {
+                                       current = new NamespaceDeclaration (r.Value, r.Prefix == "xmlns" ? r.LocalName : String.Empty);
+                                       node_type = XamlNodeType.NamespaceDeclaration;
+                                       return true;
+                               }
+                       } while (r.MoveToNextAttribute ());
+                       return false;
+               }
+
+               void ReadStartType ()
+               {
+                       string name = r.LocalName;
+                       string ns = r.NamespaceURI;
+                       string typeArgNames = null;
+                       var atts = ProcessAttributes ();
+
+                       if (!r.IsEmptyElement) {
+                               r.Read ();
+                               do {
+                                       r.MoveToContent ();
+                                       switch (r.NodeType) {
+                                       case XmlNodeType.Element:
+                                       // FIXME: parse type arguments etc.
+                                       case XmlNodeType.EndElement:
+                                               break;
+                                       default:
+                                               // this value is for Initialization
+                                               // FIXME: this could also be a WrappedContents
+                                               stored_members.Add (new Pair (XamlLanguage.Initialization, r.Value));
+                                               r.Read ();
+                                               continue;
+                                       }
+                                       break;
+                               } while (true);
+                       }
+                       else
+                               is_empty_object = true;
+
+                       // check TypeArguments to resolve Type, and remove them from the list. They don't appear as a node.
+                       foreach (var p in stored_members) {
+                               if (p.Key == XamlLanguage.TypeArguments) {
+                                       typeArgNames = p.Value;
+                                       stored_members.Remove (p);
+                                       break;
+                               }
+                       }
+
+                       XamlType xt;
+                       IList<XamlTypeName> typeArgs = typeArgNames == null ? null : XamlTypeName.ParseList (typeArgNames, xaml_namespace_resolver);
+                       Type rtype = XamlLanguage.ResolveXamlTypeName (ns, name, typeArgs, xaml_namespace_resolver);
+                       if (rtype == null)
+                               throw new XamlParseException (String.Format ("Cannot resolve runtime namespace from XML namespace '{0}', local name '{1}' and type argument '{2}'", ns, name, typeArgNames));
+                       xt = sctx.GetXamlType (rtype);
+                       if (xt == null)
+                               // FIXME: .NET just treats the node as empty!
+                               // we have to sort out what to do here.
+                               throw new XamlParseException (String.Format ("Failed to create a XAML type for '{0}' in namespace '{1}'", name, ns));
+                       types.Push (xt);
+                       current = xt;
+
+                       foreach (var p in atts) {
+                               var xm = xt.GetMember (p.Key);
+                               if (xm != null)
+                                       stored_members.Add (new Pair (xm, p.Value));
+                               // ignore unknown attribute
+                       }
+
+                       node_type = XamlNodeType.StartObject;
+                       inside_object_not_member = true;
+
+                       // The next Read() results are likely directives.
+                       stored_member_enumerator = stored_members.GetEnumerator ();
+               }
+               
+               void ReadStartMember ()
+               {
+                       var name = r.LocalName;
+
+                       current_member = types.Peek ().GetMember (name);
+                       current = current_member;
+
+                       node_type = XamlNodeType.StartMember;
+                       inside_object_not_member = false;
+               }
+               
+               void ReadEndType ()
+               {
+                       r.Read ();
+
+                       types.Pop ();
+                       current = null;
+                       node_type = XamlNodeType.EndObject;
+                       inside_object_not_member = false;
+               }
+               
+               void ReadEndMember ()
+               {
+                       r.Read ();
+
+                       current = current_member = null;
+                       node_type = XamlNodeType.EndMember;
+                       inside_object_not_member = true;
+               }
+
+               void ReadValue ()
+               {
+                       // FIXME: (probably) use ValueSerializer to deserialize the value to the expected type.
+                       current = r.Value;
+
+                       r.Read ();
+
+                       node_type = XamlNodeType.Value;
+               }
+
+               // returns remaining attributes to be processed
+               Dictionary<string,string> ProcessAttributes ()
+               {
+                       var l = stored_members;
+
+                       // base
+                       string xmlbase = r.GetAttribute ("base", XamlLanguage.Xml1998Namespace) ?? r.BaseURI;
+                       if (types.Count == 0 && xmlbase != null) // top
+                               l.Add (new Pair (XamlLanguage.Base, xmlbase));
+
+                       var atts = new Dictionary<string,string> ();
+
+                       if (r.MoveToFirstAttribute ()) {
+                               do {
+                                       if (r.NamespaceURI == XamlLanguage.Xmlns2000Namespace)
+                                               continue;
+                                       XamlDirective d = XamlLanguage.AllDirectives.FirstOrDefault (dd => (dd.AllowedLocation & AllowedMemberLocations.Attribute) != 0 && dd.Name == r.LocalName);
+                                       if (d != null) {
+                                               l.Add (new Pair (d, r.Value));
+                                               continue;
+                                       }
+                                       if (r.NamespaceURI == String.Empty) {
+                                               atts.Add (r.LocalName, r.Value);
+                                               continue;
+                                       }
+                                       // Should we just ignore unknown attribute in XAML namespace or any other namespaces ?
+                                       // Probably yes for compatibility with future version.
+                               } while (r.MoveToNextAttribute ());
+                               r.MoveToElement ();
+                       }
+                       return atts;
+               }
+
+               bool MoveToNextAttributeMember ()
+               {
+                       if (stored_member_enumerator != null) {
+                               // FIXME: value might have to be deserialized.
+                               switch (node_type) {
+                               case XamlNodeType.StartObject:
+                               case XamlNodeType.EndMember:
+                                       // -> StartMember
+                                       if (stored_member_enumerator.MoveNext ()) {
+                                               current = current_member = stored_member_enumerator.Current.Key;
+                                               node_type = XamlNodeType.StartMember;
+                                               return true;
+                                       }
+                                       break;
+                               case XamlNodeType.StartMember:
+                                       // -> Value
+                                       current = stored_member_enumerator.Current.Value;
+                                       node_type = XamlNodeType.Value;
+                                       return true;
+                               case XamlNodeType.Value:
+                                       // -> EndMember
+                                       current = null;
+                                       node_type = XamlNodeType.EndMember;
+                                       return true;
+                               }
+                       }
+
+                       stored_members.Clear ();
+                       stored_member_enumerator = null;
+                       return false;
+               }
+               
+               string GetLineString ()
+               {
+                       return HasLineInfo ? String.Format (" Line {0}, at {1}", LineNumber, LinePosition) : String.Empty;
+               }
+
+               class NamespaceResolver : IXamlNamespaceResolver
+               {
+                       IXmlNamespaceResolver source;
+
+                       public NamespaceResolver (IXmlNamespaceResolver source)
+                       {
+                               this.source = source;
+                       }
+
+                       public string GetNamespace (string prefix)
+                       {
+                               return source.LookupNamespace (prefix);
+                       }
+
+                       public IEnumerable<NamespaceDeclaration> GetNamespacePrefixes ()
+                       {
+                               foreach (var p in source.GetNamespacesInScope (XmlNamespaceScope.All))
+                                       yield return new NamespaceDeclaration (p.Value, p.Key);
+                       }
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlXmlReaderSettings.cs b/mcs/class/System.Xaml/System.Xaml/XamlXmlReaderSettings.cs
new file mode 100644 (file)
index 0000000..17b07d2
--- /dev/null
@@ -0,0 +1,55 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Xaml
+{
+       public class XamlXmlReaderSettings : XamlReaderSettings
+       {
+               public XamlXmlReaderSettings ()
+               {
+               }
+
+               public XamlXmlReaderSettings (XamlXmlReaderSettings settings)
+                       : base (settings)
+               {
+                       var s = settings;
+                       if (s == null)
+                               return;
+                       CloseInput = s.CloseInput;
+                       SkipXmlCompatibilityProcessing = s.SkipXmlCompatibilityProcessing;
+                       XmlLang = s.XmlLang;
+                       XmlSpacePreserve = s.XmlSpacePreserve;
+               }
+
+               public bool CloseInput { get; set; }
+               public bool SkipXmlCompatibilityProcessing { get; set; }
+               public string XmlLang { get; set; }
+               public bool XmlSpacePreserve { get; set; }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlXmlWriter.cs b/mcs/class/System.Xaml/System.Xaml/XamlXmlWriter.cs
new file mode 100644 (file)
index 0000000..9a583aa
--- /dev/null
@@ -0,0 +1,356 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.IO;
+using System.Linq;
+using System.Windows.Markup;
+using System.Xml;
+
+/*
+
+** Value output node type
+
+When an object contains a member:
+- it becomes an attribute when it contains a value.
+- it becomes an element when it contains an object.
+*/
+
+namespace System.Xaml
+{
+       public class XamlXmlWriter : XamlWriter
+       {
+               public XamlXmlWriter (Stream stream, XamlSchemaContext schemaContext)
+                       : this (stream, schemaContext, null)
+               {
+               }
+               
+               public XamlXmlWriter (Stream stream, XamlSchemaContext schemaContext, XamlXmlWriterSettings settings)
+                       : this (XmlWriter.Create (stream), schemaContext, null)
+               {
+               }
+               
+               public XamlXmlWriter (TextWriter textWriter, XamlSchemaContext schemaContext)
+                       : this (XmlWriter.Create (textWriter), schemaContext, null)
+               {
+               }
+               
+               public XamlXmlWriter (TextWriter textWriter, XamlSchemaContext schemaContext, XamlXmlWriterSettings settings)
+                       : this (XmlWriter.Create (textWriter), schemaContext, null)
+               {
+               }
+               
+               public XamlXmlWriter (XmlWriter xmlWriter, XamlSchemaContext schemaContext)
+                       : this (xmlWriter, schemaContext, null)
+               {
+               }
+               
+               public XamlXmlWriter (XmlWriter xmlWriter, XamlSchemaContext schemaContext, XamlXmlWriterSettings settings)
+               {
+                       if (xmlWriter == null)
+                               throw new ArgumentNullException ("xmlWriter");
+                       if (schemaContext == null)
+                               throw new ArgumentNullException ("schemaContext");
+                       this.w = xmlWriter;
+                       this.sctx = schemaContext;
+                       this.settings = settings ?? new XamlXmlWriterSettings ();
+                       this.manager = new XamlWriterStateManager<XamlXmlWriterException, InvalidOperationException> (true);
+               }
+
+               XmlWriter w;
+               XamlSchemaContext sctx;
+               XamlXmlWriterSettings settings;
+               IValueSerializerContext serializer_context;
+
+               XamlWriterStateManager manager;
+
+               Stack<object> nodes = new Stack<object> ();
+               bool is_first_member_content, has_namespace;
+               object first_member_value;
+
+               public override XamlSchemaContext SchemaContext {
+                       get { return sctx; }
+               }
+
+               public XamlXmlWriterSettings Settings {
+                       get { return settings; }
+               }
+
+               protected override void Dispose (bool disposing)
+               {
+                       if (!disposing)
+                               return;
+
+                       while (nodes.Count > 0) {
+                               var obj = nodes.Peek ();
+                               if (obj is XamlMember) {
+                                       manager.OnClosingItem ();
+                                       WriteEndMember ();
+                               }
+                               else if (obj is XamlType)
+                                       WriteEndObject ();
+                               else
+                                       nodes.Pop ();
+                       }
+                       if (settings.CloseOutput)
+                               w.Close ();
+               }
+
+               public void Flush ()
+               {
+                       w.Flush ();
+               }
+
+               public override void WriteEndMember ()
+               {
+                       manager.EndMember ();
+                       WriteStackedStartMember (XamlNodeType.EndMember);
+                       DoEndMember ();
+
+               }
+
+               public override void WriteEndObject ()
+               {
+                       manager.EndObject (nodes.Count > 1);
+                       w.WriteEndElement ();
+                       nodes.Pop ();
+               }
+
+               public override void WriteGetObject ()
+               {
+                       manager.GetObject ();
+                       WriteStackedStartMember (XamlNodeType.GetObject);
+
+                       var xm = (XamlMember) GetNonNamespaceNode ();
+                       if (!xm.Type.IsCollection)
+                               throw new InvalidOperationException (String.Format ("WriteGetObject method can be invoked only when current member '{0}' is of collection type", xm.Name));
+
+                       DoEndMember ();
+                       
+                       // FIXME: it likely has to write the "retrieved" object here.
+               }
+
+               public override void WriteNamespace (NamespaceDeclaration namespaceDeclaration)
+               {
+                       if (namespaceDeclaration == null)
+                               throw new ArgumentNullException ("namespaceDeclaration");
+
+                       manager.Namespace ();
+
+                       nodes.Push (namespaceDeclaration);
+                       has_namespace = true;
+               }
+
+               public override void WriteStartMember (XamlMember property)
+               {
+                       if (property == null)
+                               throw new ArgumentNullException ("property");
+
+                       manager.StartMember ();
+                       nodes.Push (property);
+
+                       is_first_member_content = true;
+               }
+
+               public override void WriteStartObject (XamlType xamlType)
+               {
+                       if (xamlType == null)
+                               throw new ArgumentNullException ("xamlType");
+
+                       manager.StartObject ();
+
+                       WriteStackedStartMember (XamlNodeType.StartObject);
+
+                       nodes.Push (xamlType);
+                       DoWriteStartObject (xamlType);
+               }
+               
+               public override void WriteValue (object value)
+               {
+                       manager.Value ();
+
+                       var xt = GetCurrentType ();
+                       
+                       var xm = GetNonNamespaceNode () as XamlMember;
+                       if (xm == XamlLanguage.Initialization) {
+                               // do not reject type mismatch, as the value will be a string.
+                       }
+                       else if (xt != null && xt.UnderlyingType != null && !xt.UnderlyingType.IsInstanceOfType (value))
+                               throw new ArgumentException (String.Format ("Value is not of type {0} but {1}", xt, value != null ? value.GetType ().FullName : "(null)"));
+
+                       if (!is_first_member_content) {
+                               WriteStackedStartMember (XamlNodeType.Value);
+                               DoWriteValue (value);
+                       }
+                       else
+                               first_member_value = value;
+               }
+
+               void DoEndMember ()
+               {
+                       var xm = nodes.Pop (); // XamlMember
+                       if (xm == XamlLanguage.Initialization)
+                               ; // do nothing
+                       else if (w.WriteState == WriteState.Content)
+                               w.WriteEndElement ();
+                       else
+                               w.WriteEndAttribute ();
+
+                       is_first_member_content = false;
+                       first_member_value = null;
+               }
+
+               void WriteStackedStartMember (XamlNodeType next)
+               {
+                       if (!is_first_member_content)
+                               return;
+
+                       var xm = GetNonNamespaceNode () as XamlMember;
+                       if (xm == null)
+                               return;
+
+                       if (xm == XamlLanguage.Initialization)
+                               ; // do nothing
+                       else if (next == XamlNodeType.StartObject || w.WriteState == WriteState.Content || has_namespace)
+                               DoWriteStartMemberElement (xm);
+                       else
+                               DoWriteStartMemberAttribute (xm);
+                       if (first_member_value != null)
+                               DoWriteValue (first_member_value);
+                       is_first_member_content = false;
+               }
+
+               void DoWriteStartObject (XamlType xamlType)
+               {
+                       string prefix = GetPrefix (xamlType.PreferredXamlNamespace);
+                       w.WriteStartElement (prefix, xamlType.Name, xamlType.PreferredXamlNamespace);
+                       WriteAndClearNamespaces ();
+               }
+               
+               void DoWriteStartMemberElement (XamlMember xm)
+               {
+                       var xt = GetCurrentType ();
+                       string prefix = GetPrefix (xm.PreferredXamlNamespace);
+                       w.WriteStartElement (prefix, String.Concat (xt.Name, ".", xm.Name), xm.PreferredXamlNamespace);
+                       WriteAndClearNamespaces ();
+               }
+               
+               void DoWriteStartMemberAttribute (XamlMember xm)
+               {
+                       WriteAndClearNamespaces ();
+                       
+                       var xt = GetCurrentType ();
+                       if (xt.PreferredXamlNamespace == xm.PreferredXamlNamespace)
+                               w.WriteStartAttribute (xm.Name);
+                       else {
+                               string prefix = GetPrefix (xm.PreferredXamlNamespace);
+                               w.WriteStartAttribute (prefix, xm.Name, xm.PreferredXamlNamespace);
+                       }
+               }
+
+               void DoWriteValue (object value)
+               {
+                       var xt = value == null ? XamlLanguage.Null : SchemaContext.GetXamlType (value.GetType ());
+                       var vs = xt.TypeConverter;
+                       var c = vs != null ? vs.ConverterInstance : null;
+                       if (c != null && c.CanConvertTo (typeof (string)))
+                               w.WriteString (c.ConvertToInvariantString (value));
+                       else
+                               w.WriteValue (value);
+               }
+
+               object GetNonNamespaceNode ()
+               {
+                       if (nodes.Count == 0)
+                               return null;
+                       var obj = nodes.Pop ();
+                       try {
+                               if (obj is NamespaceDeclaration)
+                                       return GetNonNamespaceNode ();
+                               else
+                                       return obj;
+                       } finally {
+                               nodes.Push (obj);
+                       }
+               }
+
+               XamlType GetCurrentType ()
+               {
+                       if (nodes.Count == 0)
+                               return null;
+                       var obj = nodes.Pop ();
+                       try {
+                               if (obj is XamlType)
+                                       return (XamlType) obj;
+                               else
+                                       return GetCurrentType ();
+                       } finally {
+                               nodes.Push (obj);
+                       }
+               }
+
+               string GetPrefix (string ns)
+               {
+                       var decl = nodes.LastOrDefault (d => d is NamespaceDeclaration && ((NamespaceDeclaration) d).Namespace == ns) as NamespaceDeclaration;
+                       if (decl != null)
+                               return decl.Prefix;
+                       return w.LookupPrefix (ns);
+               }
+
+               Stack<NamespaceDeclaration> tmp_nss = new Stack<NamespaceDeclaration> ();
+
+               void WriteAndClearNamespaces ()
+               {
+                       // write namespace that are put *before* current item.
+
+                       var top = nodes.Pop (); // temporarily pop out
+
+                       while (nodes.Count > 0) {
+                               var obj = nodes.Pop ();
+                               var nd = obj as NamespaceDeclaration;
+                               if (nd == null) {
+                                       nodes.Push (obj);
+                                       break;
+                               }
+                               tmp_nss.Push (nd);
+                       }
+                       while (tmp_nss.Count > 0) {
+                               var nd = tmp_nss.Pop ();
+                               DoWriteNamespace (nd);
+                       }
+                       has_namespace = false;
+                       manager.NamespaceCleanedUp ();
+
+                       nodes.Push (top); // push back
+               }
+
+               void DoWriteNamespace (NamespaceDeclaration nd)
+               {
+                       if (String.IsNullOrEmpty (nd.Prefix))
+                               w.WriteAttributeString ("xmlns", nd.Namespace);
+                       else
+                               w.WriteAttributeString ("xmlns", nd.Prefix, XamlLanguage.Xmlns2000Namespace, nd.Namespace);
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlXmlWriterException.cs b/mcs/class/System.Xaml/System.Xaml/XamlXmlWriterException.cs
new file mode 100644 (file)
index 0000000..ffa402c
--- /dev/null
@@ -0,0 +1,53 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Runtime.Serialization;
+
+namespace System.Xaml
+{
+       [Serializable]
+       public class XamlXmlWriterException : XamlException
+       {
+               public XamlXmlWriterException ()
+                       : this ("XAML writer error")
+               {
+               }
+
+               public XamlXmlWriterException (string message)
+                       : this (message, null)
+               {
+               }
+
+               public XamlXmlWriterException (string message, Exception innerException)
+                       : base (message, innerException)
+               {
+               }
+
+               protected XamlXmlWriterException (SerializationInfo info, StreamingContext context)
+                       : base (info, context)
+               {
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml/XamlXmlWriterSettings.cs b/mcs/class/System.Xaml/System.Xaml/XamlXmlWriterSettings.cs
new file mode 100644 (file)
index 0000000..4940f5f
--- /dev/null
@@ -0,0 +1,53 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml.Schema;
+
+namespace System.Xaml
+{
+       public class XamlXmlWriterSettings : XamlWriterSettings
+       {
+               public XamlXmlWriterSettings ()
+               {
+               }
+
+               XamlXmlWriterSettings (XamlXmlWriterSettings other)
+                       : base (other)
+               {
+                       AssumeValidInput = other.AssumeValidInput;
+                       CloseOutput = other.CloseOutput;
+               }
+
+               public bool AssumeValidInput { get; set; }
+               public bool CloseOutput { get; set; }
+
+               public XamlXmlWriterSettings Copy ()
+               {
+                       return new XamlXmlWriterSettings (this);
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/System.Xaml_test.dll.sources b/mcs/class/System.Xaml/System.Xaml_test.dll.sources
new file mode 100644 (file)
index 0000000..8a65b0d
--- /dev/null
@@ -0,0 +1,30 @@
+System.Windows.Markup/ArrayExtensionTest.cs
+System.Windows.Markup/StaticExtensionTest.cs
+System.Windows.Markup/TypeExtensionTest.cs
+System.Windows.Markup/ValueSerializerTest.cs
+System.Windows.Markup/XDataTest.cs
+System.Xaml.Schema/XamlMemberInvokerTest.cs
+System.Xaml.Schema/XamlTypeInvokerTest.cs
+System.Xaml.Schema/XamlTypeNameTest.cs
+System.Xaml.Schema/XamlTypeTypeConverterTest.cs
+System.Xaml.Schema/XamlValueConverterTest.cs
+System.Xaml/AmbientPropertyValueTest.cs
+System.Xaml/AttachableMemberIdentifierTest.cs
+System.Xaml/NamespaceDeclarationTest.cs
+System.Xaml/XamlDirectiveTest.cs
+System.Xaml/XamlDuplicateMemberExceptionTest.cs
+System.Xaml/XamlLanguageTest.cs
+System.Xaml/XamlMemberTest.cs
+System.Xaml/XamlObjectEventArgsTest.cs
+System.Xaml/XamlObjectReaderSettingsTest.cs
+System.Xaml/XamlObjectReaderTest.cs
+System.Xaml/XamlObjectWriterSettingsTest.cs
+System.Xaml/XamlObjectWriterTest.cs
+System.Xaml/XamlReaderSettingsTest.cs
+System.Xaml/XamlSchemaContextSettingsTest.cs
+System.Xaml/XamlSchemaContextTest.cs
+System.Xaml/XamlTypeTest.cs
+System.Xaml/XamlXmlReaderSettingsTest.cs
+System.Xaml/XamlXmlReaderTest.cs
+System.Xaml/XamlXmlWriterSettingsTest.cs
+System.Xaml/XamlXmlWriterTest.cs
diff --git a/mcs/class/System.Xaml/Test/System.Windows.Markup/ArrayExtensionTest.cs b/mcs/class/System.Xaml/Test/System.Windows.Markup/ArrayExtensionTest.cs
new file mode 100644 (file)
index 0000000..02ab144
--- /dev/null
@@ -0,0 +1,152 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml;
+using System.Xaml.Schema;
+using NUnit.Framework;
+
+using Category = NUnit.Framework.CategoryAttribute;
+
+namespace MonoTests.System.Windows.Markup
+{
+       [TestFixture]
+       public class ArrayExtensionTest
+       {
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorNullType ()
+               {
+                       new ArrayExtension ((Type) null);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorNullElement ()
+               {
+                       new ArrayExtension ((object []) null);
+               }
+
+               [Test]
+               public void AddChild ()
+               {
+                       var x = new ArrayExtension ();
+                       x.AddChild (new object ());
+                       x.AddChild (5);
+                       x.AddChild ("test");
+               }
+
+               [Test]
+               public void AddInconsistent ()
+               {
+                       var x = new ArrayExtension (typeof (int));
+                       Assert.AreEqual (typeof (int), x.Type, "#1");
+                       // adding inconsistent items is not rejected, while calling ProvideValue() results in an error.
+                       x.AddChild (new object ());
+                       Assert.AreEqual (typeof (int), x.Type, "#2");
+               }
+
+               [Test]
+               [ExpectedException (typeof (InvalidOperationException))]
+               public void ProvideValueInconsistent ()
+               {
+                       var x = new ArrayExtension (typeof (int));
+                       x.AddChild (new object ());
+                       x.ProvideValue (null);
+               }
+
+               [Test]
+               public void AddInconsistent2 ()
+               {
+                       var x = new ArrayExtension (new int [] {1, 3});
+                       Assert.AreEqual (typeof (int), x.Type, "#1");
+                       x.AddChild (new object ());
+                       Assert.AreEqual (typeof (int), x.Type, "#2");
+               }
+
+               [Test]
+               [ExpectedException (typeof (InvalidOperationException))]
+               public void ProvideValueWithoutType ()
+               {
+                       var x = new ArrayExtension ();
+                       x.ProvideValue (null); // Type must be set first.
+               }
+
+               [Test]
+               public void ProvideValueEmpty ()
+               {
+                       var x = new ArrayExtension (typeof (int));
+                       x.ProvideValue (null); // allowed.
+               }
+
+               [Test]
+               [ExpectedException (typeof (InvalidOperationException))]
+               public void ProvideValueInconsistent2 ()
+               {
+                       var x = new ArrayExtension (new int [] {1, 3});
+                       x.AddChild (new object ());
+                       x.AddChild (null); // allowed
+                       Assert.AreEqual (4, x.Items.Count);
+                       x.ProvideValue (null);
+               }
+
+               [Test]
+               public void ProvideValue ()
+               {
+                       var x = new ArrayExtension (new int [] {1, 3});
+                       x.AddChild (5);
+                       Assert.AreEqual (3, x.Items.Count);
+                       var ret = x.ProvideValue (null);
+                       Assert.IsNotNull (ret, "#1");
+                       var arr = ret as int [];
+                       Assert.IsNotNull (arr, "#2");
+                       Assert.AreEqual (3, arr.Length, "#3");
+                       Assert.AreEqual (5, arr [2], "#4");
+               }
+
+               [Test]
+               public void AddTextInconsistent ()
+               {
+                       var x = new ArrayExtension (new int [] {1, 3});
+                       Assert.AreEqual (typeof (int), x.Type, "#1");
+                       x.AddText ("test");
+                       x.AddText (null); // allowed
+                       Assert.AreEqual (4, x.Items.Count);
+                       Assert.AreEqual (typeof (int), x.Type, "#2");
+               }
+
+               [Test]
+               [ExpectedException (typeof (InvalidOperationException))]
+               public void ProvideValueInconsistent3 ()
+               {
+                       var x = new ArrayExtension (new int [] {1, 3});
+                       x.AddText ("test");
+                       x.ProvideValue (null);
+               }
+       }
+}
+
diff --git a/mcs/class/System.Xaml/Test/System.Windows.Markup/ChangeLog b/mcs/class/System.Xaml/Test/System.Windows.Markup/ChangeLog
new file mode 100644 (file)
index 0000000..932743f
--- /dev/null
@@ -0,0 +1,13 @@
+2010-04-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XDataTest.cs : new test.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ValueSerializerTest.cs : new test.
+
+2010-04-09  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * ArrayExtensionTest.cs
+         StaticExtensionTest.cs
+         TypeExtensionTest.cs : new tests.
diff --git a/mcs/class/System.Xaml/Test/System.Windows.Markup/StaticExtensionTest.cs b/mcs/class/System.Xaml/Test/System.Windows.Markup/StaticExtensionTest.cs
new file mode 100644 (file)
index 0000000..e737356
--- /dev/null
@@ -0,0 +1,114 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml;
+using System.Xaml.Schema;
+using NUnit.Framework;
+
+using Category = NUnit.Framework.CategoryAttribute;
+
+namespace MonoTests.System.Windows.Markup
+{
+       [TestFixture]
+       public class StaticExtensionTest
+       {
+               [Test]
+               [ExpectedException (typeof (ArgumentException))]
+               public void ProvideValueWithoutType ()
+               {
+                       var x = new StaticExtension ();
+                       // it fails because it cannot be resolved to a static member.
+                       // This possibly mean, there might be a member that 
+                       // could be resolved only with the name, without type.
+                       x.Member = "Foo";
+                       x.ProvideValue (null);
+               }
+
+               [Test]
+               [ExpectedException (typeof (InvalidOperationException))]
+               public void ProvideValueWithoutMember ()
+               {
+                       var x = new StaticExtension ();
+                       x.MemberType = typeof (int);
+                       x.ProvideValue (null);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentException))]
+               public void ProvideValueInstanceProperty ()
+               {
+                       var x = new StaticExtension ();
+                       x.MemberType = typeof (StaticExtension);
+                       x.Member = "MemberType"; // instance property is out of scope.
+                       x.ProvideValue (null);
+               }
+
+               [Test]
+               public void ProvideValueStaticProperty ()
+               {
+                       var x = new StaticExtension ();
+                       x.MemberType = typeof (XamlLanguage);
+                       x.Member = "Array";
+                       Assert.AreEqual (XamlLanguage.Array, x.ProvideValue (null), "#1");
+               }
+
+               [Test]
+               public void ProvideValueConst ()
+               {
+                       var x = new StaticExtension ();
+                       x.MemberType = typeof (XamlLanguage);
+                       x.Member = "Xaml2006Namespace";
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, x.ProvideValue (null), "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentException))]
+               public void ProvideValuePrivateConst ()
+               {
+                       var x = new StaticExtension ();
+                       x.MemberType = GetType ();
+                       x.Member = "FooBar"; // private const could not be resolved.
+                       Assert.AreEqual ("foobar", x.ProvideValue (null), "#1");
+               }
+
+               const string FooBar = "foobar";
+
+
+               [Test]
+               [ExpectedException (typeof (ArgumentException))]
+               public void ProvideValueEvent ()
+               {
+                       var x = new StaticExtension ();
+                       x.MemberType = GetType ();
+                       x.Member = "FooEvent"; // private const could not be resolved.
+                       Assert.IsNotNull (x.ProvideValue (null), "#1");
+               }
+
+               public static event EventHandler<EventArgs> FooEvent;
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Windows.Markup/TypeExtensionTest.cs b/mcs/class/System.Xaml/Test/System.Windows.Markup/TypeExtensionTest.cs
new file mode 100644 (file)
index 0000000..ae92b85
--- /dev/null
@@ -0,0 +1,121 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml;
+using System.Xaml.Schema;
+using NUnit.Framework;
+
+using Category = NUnit.Framework.CategoryAttribute;
+
+namespace MonoTests.System.Windows.Markup
+{
+       [TestFixture]
+       public class TypeExtensionTest
+       {
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorNullType ()
+               {
+                       new TypeExtension ((Type) null);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorNullName ()
+               {
+                       new TypeExtension ((string) null);
+               }
+
+               [Test]
+               [ExpectedException (typeof (InvalidOperationException))]
+               public void ProvideValueWithoutTypeOrName ()
+               {
+                       new TypeExtension ().ProvideValue (null);
+               }
+
+               [Test]
+               public void ProvideValueWithType ()
+               {
+                       var x = new TypeExtension (typeof (int));
+                       Assert.AreEqual (typeof (int), x.ProvideValue (null), "#1"); // serviceProvider is not required.
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ProvideValueWithNameWithoutResolver ()
+               {
+                       var x = new TypeExtension ("System.Int32");
+                       x.ProvideValue (null); // serviceProvider is required.
+               }
+
+               [Test]
+               [ExpectedException (typeof (InvalidOperationException))]
+               public void ProvideValueWithNameWithProviderNoResolver ()
+               {
+                       var x = new TypeExtension ("System.Int32");
+                       x.ProvideValue (new Resolver (false, false));
+               }
+
+               [Test]
+               [ExpectedException (typeof (InvalidOperationException))]
+               public void ProvideValueWithNameWithProviderResolveFail ()
+               {
+                       var x = new TypeExtension ("System.Int32");
+                       x.ProvideValue (new Resolver (true, false)); // raise an error (do not return null)
+               }
+
+               [Test]
+               public void ProvideValueWithNameWithProviderResolveSuccess ()
+               {
+                       var x = new TypeExtension ("System.Int32");
+                       x.ProvideValue (new Resolver (true, true));
+               }
+
+               class Resolver : IServiceProvider, IXamlTypeResolver
+               {
+                       bool works, resolves;
+
+                       public Resolver (bool worksFine, bool resolvesFine)
+                       {
+                               works = worksFine;
+                               resolves = resolvesFine;
+                       }
+
+                       public object GetService (Type serviceType)
+                       {
+                               Assert.AreEqual (typeof (IXamlTypeResolver), serviceType, "TypeToResolve");
+                               return works ? this : null;
+                       }
+
+                       public Type Resolve (string name)
+                       {
+                               return resolves ? Type.GetType (name) : null;
+                       }
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Windows.Markup/ValueSerializerTest.cs b/mcs/class/System.Xaml/Test/System.Windows.Markup/ValueSerializerTest.cs
new file mode 100644 (file)
index 0000000..a88cbd9
--- /dev/null
@@ -0,0 +1,136 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml;
+using System.Xaml.Schema;
+using NUnit.Framework;
+
+using Category = NUnit.Framework.CategoryAttribute;
+
+namespace MonoTests.System.Windows.Markup
+{
+       [TestFixture]
+       public class ValueSerializerTest
+       {
+               static ValueSerializerTest ()
+               {
+                       std_types = new List<XamlType> (XamlLanguage.AllTypes);
+                       std_types.Sort ((t1, t2) => String.CompareOrdinal (t1.Name, t2.Name));
+               }
+
+               static readonly List<XamlType> std_types;
+               object [] test_values = {null, true, "test", 3, 'x', 5.5, -1.414m, (byte) 255, new Uri ("urn:foo"), new NullExtension (), new object (), new PropertyDefinition (), new Reference ("Foo"), new StaticExtension (), TimeSpan.FromMinutes (5), new TypeExtension ("TypeExt"), new XData () { Text = "test xdata"} }; // can we instantiate MemberDefinition?
+               string [] test_strings = {String.Empty, "True", "test", "3", "x", "5.5", "-1.414", "255", "urn:foo", "System.Windows.Markup.NullExtension", "System.Object", "System.Windows.Markup.PropertyDefinition", "System.Windows.Markup.Reference", "System.Windows.Markup.StaticExtension", "00:05:00", "System.Windows.Markup.TypeExtension", "System.Windows.Markup.XData"};
+
+               [Test]
+               public void SerializerInAllTypes ()
+               {
+                       var sctx = new XamlSchemaContext (new Assembly [] { typeof (XamlType).Assembly });
+                       foreach (var t in std_types) {
+                               if (t != XamlLanguage.String) {
+                                       Assert.IsNull (t.ValueSerializer, "IsNull? " + t.Name);
+                                       continue;
+                               }
+                               var v = t.ValueSerializer.ConverterInstance;
+                               foreach (var val in test_values)
+                                       Assert.IsTrue (v.CanConvertToString (val, null), t.Name + "_" + (val != null ? val.GetType () : null));
+                       }
+               }
+
+               static readonly Type [] no_ser_types = {typeof (object), typeof (ArrayExtension), typeof (MemberDefinition), typeof (NullExtension), typeof (PropertyDefinition), typeof (Reference), typeof (StaticExtension), typeof (TypeExtension), typeof (XData)};
+
+               [Test]
+               public void GetSerializerForAllTypes ()
+               {
+                       // Serializers from GetSerializerFor() returns very 
+                       // different results from predefined ValueSerializer.
+                       foreach (var t in std_types) {
+                               var v = ValueSerializer.GetSerializerFor (t.UnderlyingType, null);
+                               if (no_ser_types.Any (ti => ti == t.UnderlyingType)) {
+                                       Assert.IsNull (v, "NoSerializer_" + t.Name);
+                                       continue;
+                               }
+
+                               // String ValueSerializer is the only exceptional one that mostly fails ConvertToString().
+                               // For remaining types, ConvertToString() should succeed.
+                               // What is funny or annoying here is, that always return true for CanConvertToString() while everything fails at ConvertToString() on .NET.
+                               if (t.UnderlyingType == typeof (string))
+                                       continue;
+
+                               int i = 0;
+                               foreach (var val in test_values) {
+                                       Assert.IsTrue (v.CanConvertToString (val, null), t.Name + "_" + (val != null ? val.GetType () : null));
+                                       Assert.AreEqual (test_strings [i++], v.ConvertToString (val, null), "value-" + t.Name + "_" + val);
+                               }
+
+                               // The funny thing also applies to CanConvertToString() and ConvertToString().
+
+                               i = 0;
+                               foreach (var str in test_strings) {
+                                       Assert.IsTrue (v.CanConvertFromString (str, null), t.Name + "_" + str);
+                                       // FIXME: add tests for this large matrix someday.
+                                       //Assert.AreEqual (test_values [i++], v.ConvertFromString (str, null), "value-" + t.Name + "_" + str);
+                               }
+                       }
+               }
+
+               [Test]
+               public void DefaultImplementation ()
+               {
+                       var v = new MyValueSerializer ();
+
+                       int i = 0;
+                       foreach (var val in test_values) {
+                               Assert.IsFalse (v.CanConvertToString (val, null), "CanConvertTo." + val);
+                               try {
+                                       v.ConvertToString (val, null);
+                                       Assert.Fail ("ConvertTo." + val);
+                               } catch (NotSupportedException) {
+                               }
+                       }
+
+                       // The funny thing also applies to CanConvertToString() and ConvertToString().
+
+                       i = 0;
+                       foreach (var str in test_strings) {
+                               Assert.IsFalse (v.CanConvertFromString (str, null), "CanConvertFrom." + str);
+                               try {
+                                       v.ConvertFromString (str, null);
+                                       Assert.Fail ("ConvertFrom." + str);
+                               } catch (NotSupportedException) {
+                               }
+                       }
+               }
+
+               class MyValueSerializer : ValueSerializer
+               {
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Windows.Markup/XDataTest.cs b/mcs/class/System.Xaml/Test/System.Windows.Markup/XDataTest.cs
new file mode 100644 (file)
index 0000000..dfe9175
--- /dev/null
@@ -0,0 +1,96 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.IO;
+using System.Reflection;
+using System.Text;
+using System.Windows.Markup;
+using System.Xaml;
+using System.Xaml.Schema;
+using System.Xml;
+using NUnit.Framework;
+
+using Category = NUnit.Framework.CategoryAttribute;
+
+namespace MonoTests.System.Windows.Markup
+{
+       [TestFixture]
+       public class XDataTest
+       {
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void GetXmlReaderWithNullText ()
+               {
+                       var x = new XData ();
+                       Assert.IsNull (x.Text, "#1");
+                       Assert.IsNull (x.XmlReader, "#2");
+               }
+
+               [Test]
+               public void TextSetsXmlReader ()
+               {
+                       var x = new XData ();
+                       x.Text = "foobar";
+                       Assert.IsNotNull (x.Text, "#3");
+                       var r = x.XmlReader as XmlReader;
+                       Assert.IsNotNull (r, "#4");
+                       Assert.AreEqual (XmlNodeType.None, r.NodeType, "#5");
+                       try {
+                               r.Read (); // invalid xml
+                               Assert.Fail ("#6");
+                       } catch (XmlException) {
+                       }
+               }
+
+               [Test]
+               public void SetTextNull ()
+               {
+                       var x = new XData ();
+                       // allowed.
+                       x.Text = null;
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void SetNonXmlReader ()
+               {
+                       var x = new XData ();
+                       XmlReader r;
+                       x.XmlReader = "<foo/>"; // not allowed. It does *not* raise an error, but the value becomes null.
+                       r = x.XmlReader as XmlReader; // and thus it causes ANE.
+               }
+
+               [Test]
+               public void SetXmlReader ()
+               {
+                       var x = new XData ();
+                       x.XmlReader = XmlReader.Create (new StringReader ("<root/>"));
+                       Assert.IsNull (x.Text, "#1");
+                       Assert.IsNotNull (x.XmlReader, "#2");
+                       x.XmlReader = null;
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml.Schema/ChangeLog b/mcs/class/System.Xaml/Test/System.Xaml.Schema/ChangeLog
new file mode 100755 (executable)
index 0000000..df73ea2
--- /dev/null
@@ -0,0 +1,31 @@
+2010-04-22  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlMemberInvokerTest.cs : make sure GetValue() is not supported
+         on directives.
+
+2010-04-22  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlMemberInvokerTest.cs : make sure that the invoker returns Type
+         for Type member here. (XamlObjectReader returns string for some
+         cases, so I wanted to make sure it is *not* here.)
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlTypeTypeConverterTest.cs : more conversion tests.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlTypeNameTest.cs : new test.
+
+2010-04-09  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlTypeTypeConverterTest.cs, XamlValueConverterTest.cs :
+         new tests.
+
+2010-04-09  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlTypeInvokerTest.cs : new test.
+
+2010-04-08  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlMemberInvokerTest.cs : new test.
diff --git a/mcs/class/System.Xaml/Test/System.Xaml.Schema/XamlMemberInvokerTest.cs b/mcs/class/System.Xaml/Test/System.Xaml.Schema/XamlMemberInvokerTest.cs
new file mode 100644 (file)
index 0000000..093309b
--- /dev/null
@@ -0,0 +1,256 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Text;
+using System.Windows.Markup;
+using System.Xaml;
+using System.Xaml.Schema;
+using System.Xml;
+using NUnit.Framework;
+
+namespace MonoTests.System.Xaml.Schema
+{
+       [TestFixture]
+       public class XamlMemberInvokerTest
+       {
+               XamlSchemaContext sctx = new XamlSchemaContext (new XamlSchemaContextSettings ());
+               PropertyInfo str_len = typeof (string).GetProperty ("Length");
+               PropertyInfo sb_len = typeof (StringBuilder).GetProperty ("Length");
+               PropertyInfo xr_resolver = typeof (XmlResolver).GetProperty ("Credentials");
+               EventInfo ass_load = typeof (AppDomain).GetEvent ("AssemblyLoad");
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorNull ()
+               {
+                       new XamlMemberInvoker (null);
+               }
+
+               // Property
+
+               [Test]
+               public void FromProperty ()
+               {
+                       var pi = str_len;
+                       var i = new XamlMemberInvoker (new XamlMember (pi, sctx));
+                       Assert.AreEqual (pi.GetGetMethod (), i.UnderlyingGetter, "#1");
+                       Assert.IsNull (i.UnderlyingSetter, "#2");
+                       Assert.AreEqual (5, i.GetValue ("hello"), "#3");
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void GetValueNullObject ()
+               {
+                       var pi = str_len;
+                       var i = new XamlMemberInvoker (new XamlMember (pi, sctx));
+                       i.GetValue (null);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void SetValueNullObject ()
+               {
+                       var pi = sb_len;
+                       var i = new XamlMemberInvoker (new XamlMember (pi, sctx));
+                       i.SetValue (null, 5);
+               }
+
+               [Test]
+               [ExpectedException (typeof (NotSupportedException))]
+               public void GetValueOnWriteOnlyProperty ()
+               {
+                       var pi = xr_resolver;
+                       var i = new XamlMemberInvoker (new XamlMember (pi, sctx));
+                       i.GetValue (new XmlUrlResolver ());
+               }
+
+               [Test]
+               [ExpectedException (typeof (NotSupportedException))]
+               public void SetValueOnReadOnlyProperty ()
+               {
+                       var pi = str_len;
+                       var i = new XamlMemberInvoker (new XamlMember (pi, sctx));
+                       i.SetValue ("hello", 5);
+               }
+
+               [Test]
+               public void SetValueOnReadWriteProperty ()
+               {
+                       var pi = sb_len;
+                       var i = new XamlMemberInvoker (new XamlMember (pi, sctx));
+                       var sb = new StringBuilder ();
+                       i.SetValue (sb, 5);
+                       Assert.AreEqual (5, sb.Length, "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (TargetException))]
+               public void GetValueOnIrrelevantObject ()
+               {
+                       var pi = str_len;
+                       var i = new XamlMemberInvoker (new XamlMember (pi, sctx));
+                       i.GetValue (new StringBuilder ());
+               }
+
+               [Test]
+               public void GetValueOnTypeValue ()
+               {
+                       var xm = XamlLanguage.Type.GetMember ("Type");
+                       var i = new XamlMemberInvoker (xm);
+                       var o = i.GetValue (new TypeExtension (typeof (int)));
+                       Assert.AreEqual (typeof (int), o, "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (NotSupportedException))]
+               public void GetValueInitialization ()
+               {
+                       var xm = XamlLanguage.Initialization;
+                       var i = xm.Invoker;
+                       i.GetValue ("foo");
+               }
+
+               [Test]
+               [ExpectedException (typeof (NotSupportedException))]
+               public void GetValuePositionalParameter ()
+               {
+                       var xm = XamlLanguage.PositionalParameters;
+                       var i = xm.Invoker;
+                       i.GetValue (new TypeExtension (typeof (int)));
+               }
+
+               [Test]
+               [ExpectedException (typeof (TargetException))]
+               public void SetValueOnIrrelevantObject ()
+               {
+                       var pi = sb_len;
+                       var i = new XamlMemberInvoker (new XamlMember (pi, sctx));
+                       i.SetValue ("hello", 5);
+               }
+
+               // Event
+
+               [Test]
+               public void FromEvent ()
+               {
+                       var ei = ass_load;
+                       var i = new XamlMemberInvoker (new XamlMember (ei, sctx));
+                       Assert.IsNull (i.UnderlyingGetter, "#1");
+                       Assert.AreEqual (ei.GetAddMethod (), i.UnderlyingSetter, "#2");
+               }
+
+               [Test]
+               [ExpectedException (typeof (NotSupportedException))]
+               public void GetValueOnEvent ()
+               {
+                       var ei = ass_load;
+                       var i = new XamlMemberInvoker (new XamlMember (ei, sctx));
+                       i.GetValue (AppDomain.CurrentDomain);
+               }
+
+               [Test]
+               public void SetValueOnEventNull ()
+               {
+                       var ei = ass_load;
+                       var i = new XamlMemberInvoker (new XamlMember (ei, sctx));
+                       i.SetValue (AppDomain.CurrentDomain, null);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentException))]
+               public void SetValueOnEventValueMismatch ()
+               {
+                       var ei = ass_load;
+                       var i = new XamlMemberInvoker (new XamlMember (ei, sctx));
+                       i.SetValue (AppDomain.CurrentDomain, 5);
+               }
+
+               void DummyAssemblyLoad (object o, AssemblyLoadEventArgs e)
+               {
+               }
+
+               [Test]
+               public void SetValueOnEvent ()
+               {
+                       var ei = ass_load;
+                       var i = new XamlMemberInvoker (new XamlMember (ei, sctx));
+                       i.SetValue (AppDomain.CurrentDomain, new AssemblyLoadEventHandler (DummyAssemblyLoad));
+               }
+
+               [Test]
+               public void CustomTypeDefaultValues ()
+               {
+                       var i = new MyXamlMemberInvoker ();
+                       Assert.IsNull (i.UnderlyingGetter, "#1");
+                       Assert.IsNull (i.UnderlyingSetter, "#2");
+               }
+
+               [Test]
+               [ExpectedException (typeof (MyException))]
+               public void UnderlyingGetter ()
+               {
+                       var i = new XamlMemberInvoker (new MyXamlMember (str_len, sctx));
+                       // call XamlMember's UnderlyingGetter.
+                       Assert.IsNotNull (i.UnderlyingGetter, "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (MyException))]
+               public void UnderlyingSetter ()
+               {
+                       var i = new XamlMemberInvoker (new MyXamlMember (str_len, sctx));
+                       // call XamlMember's UnderlyingSetter.
+                       Assert.IsNull (i.UnderlyingSetter, "#1");
+               }
+
+               class MyXamlMember : XamlMember
+               {
+                       public MyXamlMember (PropertyInfo pi, XamlSchemaContext context)
+                               : base (pi, context)
+                       {
+                       }
+                       
+                       protected override MethodInfo LookupUnderlyingGetter ()
+                       {
+                               throw new MyException ();
+                       }
+
+                       protected override MethodInfo LookupUnderlyingSetter ()
+                       {
+                               throw new MyException ();
+                       }
+               }
+
+               class MyException : Exception
+               {
+               }
+
+               class MyXamlMemberInvoker : XamlMemberInvoker
+               {
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml.Schema/XamlTypeInvokerTest.cs b/mcs/class/System.Xaml/Test/System.Xaml.Schema/XamlTypeInvokerTest.cs
new file mode 100644 (file)
index 0000000..d8c0c40
--- /dev/null
@@ -0,0 +1,182 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Text;
+using System.Windows.Markup;
+using System.Xaml;
+using System.Xaml.Schema;
+using System.Xml;
+using NUnit.Framework;
+
+namespace MonoTests.System.Xaml.Schema
+{
+       [TestFixture]
+       public class XamlTypeInvokerTest
+       {
+               XamlSchemaContext sctx = new XamlSchemaContext (new XamlSchemaContextSettings ());
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorTypeNull ()
+               {
+                       new XamlTypeInvoker (null);
+               }
+
+               [Test]
+               public void DefaultValues ()
+               {
+                       var i = new XamlTypeInvoker (new XamlType (typeof (object), sctx));
+                       Assert.IsNull (i.SetMarkupExtensionHandler, "#1");
+                       Assert.IsNull (i.SetTypeConverterHandler, "#2");
+               }
+
+               [XamlSetMarkupExtension ("HandleMarkupExtension")]
+               public class TestClassMarkupExtension1
+               {
+               }
+               
+               [Test]
+               [ExpectedException (typeof (ArgumentException))]
+               public void SetHandleMarkupExtensionInvalid ()
+               {
+                       var i = new XamlTypeInvoker (new XamlType (typeof (TestClassMarkupExtension1), sctx));
+                       Assert.IsNull (i.SetMarkupExtensionHandler, "#1");
+               }
+
+               [XamlSetMarkupExtension ("HandleMarkupExtension")]
+               public class TestClassMarkupExtension2
+               {
+                       // delegate type mismatch
+                       void HandleMarkupExtension ()
+                       {
+                       }
+               }
+               
+               [Test]
+               [ExpectedException (typeof (ArgumentException))]
+               public void SetHandleMarkupExtensionInvalid2 ()
+               {
+                       var i = new XamlTypeInvoker (new XamlType (typeof (TestClassMarkupExtension2), sctx));
+                       Assert.IsNull (i.SetMarkupExtensionHandler, "#1");
+               }
+
+               [XamlSetMarkupExtension ("HandleMarkupExtension")]
+               public class TestClassMarkupExtension3
+               {
+                       // must be static
+                       public void HandleMarkupExtension (object o, XamlSetMarkupExtensionEventArgs a)
+                       {
+                       }
+               }
+               
+               [Test]
+               [ExpectedException (typeof (ArgumentException))]
+               public void SetHandleMarkupExtensionInvalid3 ()
+               {
+                       var i = new XamlTypeInvoker (new XamlType (typeof (TestClassMarkupExtension3), sctx));
+                       Assert.IsNull (i.SetMarkupExtensionHandler, "#1");
+               }
+
+               [XamlSetMarkupExtension ("HandleMarkupExtension")]
+               public class TestClassMarkupExtension4
+               {
+                       // can be private.
+                       static void HandleMarkupExtension (object o, XamlSetMarkupExtensionEventArgs a)
+                       {
+                       }
+               }
+               
+               [Test]
+               public void SetHandleMarkupExtension ()
+               {
+                       var i = new XamlTypeInvoker (new XamlType (typeof (TestClassMarkupExtension4), sctx));
+                       Assert.IsNotNull (i.SetMarkupExtensionHandler, "#1");
+               }
+
+               [XamlSetTypeConverter ("HandleTypeConverter")]
+               public class TestClassTypeConverter1
+               {
+               }
+               
+               [Test]
+               [ExpectedException (typeof (ArgumentException))]
+               public void SetHandleTypeConverterInvalid ()
+               {
+                       var i = new XamlTypeInvoker (new XamlType (typeof (TestClassTypeConverter1), sctx));
+                       Assert.IsNull (i.SetTypeConverterHandler, "#1");
+               }
+
+               [XamlSetTypeConverter ("HandleTypeConverter")]
+               public class TestClassTypeConverter2
+               {
+                       // delegate type mismatch
+                       void HandleTypeConverter ()
+                       {
+                       }
+               }
+               
+               [Test]
+               [ExpectedException (typeof (ArgumentException))]
+               public void SetHandleTypeConverterInvalid2 ()
+               {
+                       var i = new XamlTypeInvoker (new XamlType (typeof (TestClassTypeConverter2), sctx));
+                       Assert.IsNull (i.SetTypeConverterHandler, "#1");
+               }
+
+               [XamlSetTypeConverter ("HandleTypeConverter")]
+               public class TestClassTypeConverter3
+               {
+                       // must be static
+                       public void HandleTypeConverter (object o, XamlSetTypeConverterEventArgs a)
+                       {
+                       }
+               }
+               
+               [Test]
+               [ExpectedException (typeof (ArgumentException))]
+               public void SetHandleTypeConverterInvalid3 ()
+               {
+                       var i = new XamlTypeInvoker (new XamlType (typeof (TestClassTypeConverter3), sctx));
+                       Assert.IsNull (i.SetTypeConverterHandler, "#1");
+               }
+
+               [XamlSetTypeConverter ("HandleTypeConverter")]
+               public class TestClassTypeConverter4
+               {
+                       // can be private.
+                       static void HandleTypeConverter (object o, XamlSetTypeConverterEventArgs a)
+                       {
+                       }
+               }
+               
+               [Test]
+               public void SetHandleTypeConverter ()
+               {
+                       var i = new XamlTypeInvoker (new XamlType (typeof (TestClassTypeConverter4), sctx));
+                       Assert.IsNotNull (i.SetTypeConverterHandler, "#1");
+               }
+       }
+}
\ No newline at end of file
diff --git a/mcs/class/System.Xaml/Test/System.Xaml.Schema/XamlTypeNameTest.cs b/mcs/class/System.Xaml/Test/System.Xaml.Schema/XamlTypeNameTest.cs
new file mode 100644 (file)
index 0000000..22928cc
--- /dev/null
@@ -0,0 +1,416 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Text;
+using System.Xaml;
+using System.Xaml.Schema;
+using System.Xml;
+using NUnit.Framework;
+
+namespace MonoTests.System.Xaml.Schema
+{
+       [TestFixture]
+       public class XamlTypeNameTest
+       {
+               [Test]
+               public void ConstructorDefault ()
+               {
+                       new XamlTypeName ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorXamlTypeNull ()
+               {
+                       new XamlTypeName (null);
+               }
+
+               [Test]
+               public void ConstructorNameNull ()
+               {
+                       // allowed.
+                       new XamlTypeName ("urn:foo", null);
+               }
+
+               [Test]
+               public void ConstructorNamespaceNull ()
+               {
+                       // allowed.
+                       new XamlTypeName (null, "FooBar");
+               }
+
+               [Test]
+               public void ConstructorName ()
+               {
+                       var n = new XamlTypeName ("urn:foo", "FooBar");
+                       Assert.IsNotNull (n.TypeArguments, "#1");
+                       Assert.AreEqual (0, n.TypeArguments.Count, "#2");
+               }
+
+               [Test]
+               public void ConstructorTypeArgumentsNull ()
+               {
+                       var n = new XamlTypeName ("urn:foo", "FooBar", (XamlTypeName []) null);
+                       Assert.IsNotNull (n.TypeArguments, "#1");
+                       Assert.AreEqual (0, n.TypeArguments.Count, "#2");
+               }
+
+               [Test]
+               [Ignore (".NET causes NRE on ToString(). It is not really intended and should raise an error")]
+               public void ConstructorTypeArgumentsNullEntry ()
+               {
+                       new XamlTypeName ("urn:foo", "FooBar", new XamlTypeName [] {null});
+               }
+
+               [Test]
+               public void ConstructorTypeArguments ()
+               {
+                       new XamlTypeName ("urn:foo", "FooBar", new XamlTypeName [] {new XamlTypeName ("urn:bar", "FooBarBaz")});
+               }
+
+               [Test]
+               public void ConstructorTypeArgumentsEmpty ()
+               {
+                       var n = new XamlTypeName ("urn:foo", "FooBar", new XamlTypeName [0]);
+                       Assert.IsNotNull (n.TypeArguments, "#1");
+                       Assert.AreEqual (0, n.TypeArguments.Count, "#2");
+               }
+
+               [Test]
+               [ExpectedException (typeof (InvalidOperationException))]
+               public void ToStringDefault ()
+               {
+                       var n = new XamlTypeName ();
+                       n.ToString ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (InvalidOperationException))]
+               public void ToStringNameNull ()
+               {
+                       var n = new XamlTypeName ("urn:foo", null);
+                       n.ToString ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (InvalidOperationException))]
+               public void ToStringNamespaceNull ()
+               {
+                       // allowed.
+                       var n = new XamlTypeName (null, "FooBar");
+                       n.ToString ();
+               }
+
+               [Test]
+               public void ToStringTypeArgumentsNull ()
+               {
+                       var n = new XamlTypeName ("urn:foo", "FooBar", (XamlTypeName []) null);
+                       Assert.AreEqual ("{urn:foo}FooBar", n.ToString (), "#1");
+               }
+
+               [Test]
+               [Ignore (".NET raises NRE")]
+               public void ToStringTypeArgumentsNullEntry ()
+               {
+                       var n = new XamlTypeName ("urn:foo", "FooBar", new XamlTypeName [] {null, new XamlTypeName ("urn:bar", "FooBarBaz")});
+                       Assert.AreEqual ("{urn:foo}FooBar()", n.ToString (), "#1");
+               }
+
+               [Test]
+               public void ToStringTypeArguments ()
+               {
+                       var n = new XamlTypeName ("urn:foo", "FooBar", new XamlTypeName [] {new XamlTypeName ("urn:bar", "FooBarBaz")});
+                       Assert.AreEqual ("{urn:foo}FooBar({urn:bar}FooBarBaz)", n.ToString (), "#1");
+               }
+
+               [Test]
+               public void ToStringTypeArguments2 ()
+               {
+                       var n = new XamlTypeName ("urn:foo", "Foo", new XamlTypeName [] {new XamlTypeName ("urn:bar", "Bar"), new XamlTypeName ("urn:baz", "Baz")});
+                       Assert.AreEqual ("{urn:foo}Foo({urn:bar}Bar, {urn:baz}Baz)", n.ToString (), "#1");
+               }
+
+               [Test]
+               public void ToStringEmptyNamespace ()
+               {
+                       var n = new XamlTypeName (string.Empty, "Foo");
+                       Assert.AreEqual ("{}Foo", n.ToString (), "#1");
+               }
+
+               [Test]
+               public void ToStringXamlTypePredefined ()
+               {
+                       var n = new XamlTypeName (XamlLanguage.Int32);
+                       Assert.AreEqual ("{http://schemas.microsoft.com/winfx/2006/xaml}Int32", n.ToString (), "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (InvalidOperationException))]
+               public void ToStringNamespaceLookupInsufficient ()
+               {
+                       var n = new XamlTypeName ("urn:foo", "Foo", new XamlTypeName [] {new XamlTypeName ("urn:bar", "Bar"), new XamlTypeName ("urn:baz", "Baz")});
+                       var lookup = new MyNamespaceLookup ();
+                       lookup.Add ("a", "urn:foo");
+                       lookup.Add ("c", "urn:baz");
+                       // it fails because there is missing mapping for urn:bar.
+                       Assert.AreEqual ("a:Foo({urn:bar}Bar, c:Baz)", n.ToString (lookup), "#1");
+               }
+
+               [Test]
+               public void ToStringNullLookup ()
+               {
+                       var n = new XamlTypeName ("urn:foo", "Foo", new XamlTypeName [] {new XamlTypeName ("urn:bar", "Bar"), new XamlTypeName ("urn:baz", "Baz")});
+                       Assert.AreEqual ("{urn:foo}Foo({urn:bar}Bar, {urn:baz}Baz)", n.ToString (null), "#1");
+               }
+
+               [Test]
+               public void ToStringNamespaceLookup ()
+               {
+                       var n = new XamlTypeName ("urn:foo", "Foo", new XamlTypeName [] {new XamlTypeName ("urn:bar", "Bar"), new XamlTypeName ("urn:baz", "Baz")});
+                       var lookup = new MyNamespaceLookup ();
+                       lookup.Add ("a", "urn:foo");
+                       lookup.Add ("b", "urn:bar");
+                       lookup.Add ("c", "urn:baz");
+                       Assert.AreEqual ("a:Foo(b:Bar, c:Baz)", n.ToString (lookup), "#1");
+                       Assert.AreEqual ("b:Bar, c:Baz", XamlTypeName.ToString (n.TypeArguments, lookup), "#2");
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void StaticToStringNullLookup ()
+               {
+                       XamlTypeName.ToString (new XamlTypeName [] {new XamlTypeName ("urn:foo", "bar")}, null);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void StaticToStringNullTypeNameList ()
+               {
+                       XamlTypeName.ToString (null, new MyNamespaceLookup ());
+               }
+
+               [Test]
+               public void StaticToStringEmptyArray ()
+               {
+                       Assert.AreEqual ("", XamlTypeName.ToString (new XamlTypeName [0], new MyNamespaceLookup ()), "#1");
+               }
+
+               class MyNamespaceLookup : INamespacePrefixLookup
+               {
+                       Dictionary<string,string> dic = new Dictionary<string,string> ();
+
+                       public void Add (string prefix, string ns)
+                       {
+                               dic [ns] = prefix;
+                       }
+
+                       public string LookupPrefix (string ns)
+                       {
+                               string p;
+                               return dic.TryGetValue (ns, out p) ? p : null;
+                       }
+               }
+
+               XamlTypeName dummy;
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void TryParseNullName ()
+               {
+                       XamlTypeName.TryParse (null, new MyNSResolver (), out dummy);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void TryParseNullResolver ()
+               {
+                       XamlTypeName.TryParse ("Foo", null, out dummy);
+               }
+
+               [Test]
+               public void TryParseEmptyName ()
+               {
+                       Assert.IsFalse (XamlTypeName.TryParse (String.Empty, new MyNSResolver (), out dummy), "#1");
+               }
+
+               [Test]
+               public void TryParseColon ()
+               {
+                       var r = new MyNSResolver ();
+                       r.Add ("a", "urn:foo");
+                       Assert.IsFalse (XamlTypeName.TryParse (":", r, out dummy), "#1");
+                       Assert.IsFalse (XamlTypeName.TryParse ("a:", r, out dummy), "#2");
+                       Assert.IsFalse (XamlTypeName.TryParse (":b", r, out dummy), "#3");
+               }
+
+               [Test]
+               public void TryParseInvalidName ()
+               {
+                       var r = new MyNSResolver ();
+                       r.Add ("a", "urn:foo");
+                       r.Add ("#", "urn:bar");
+                       Assert.IsFalse (XamlTypeName.TryParse ("$%#___!", r, out dummy), "#1");
+                       Assert.IsFalse (XamlTypeName.TryParse ("a:#$#", r, out dummy), "#2");
+                       Assert.IsFalse (XamlTypeName.TryParse ("#:foo", r, out dummy), "#3");
+               }
+
+               [Test]
+               public void TryParseNoFillEmpty ()
+               {
+                       Assert.IsFalse (XamlTypeName.TryParse ("Foo", new MyNSResolver (true), out dummy), "#1");
+               }
+
+               [Test]
+               public void TryParseFillEmpty ()
+               {
+                       var r = new MyNSResolver ();
+                       Assert.IsTrue (XamlTypeName.TryParse ("Foo", r, out dummy), "#1");
+                       Assert.IsNotNull (dummy, "#2");
+                       Assert.AreEqual (String.Empty, dummy.Namespace, "#2-2");
+                       Assert.AreEqual ("Foo", dummy.Name, "#2-3");
+               }
+
+               [Test]
+               public void TryParseAlreadyQualified ()
+               {
+                       Assert.IsFalse (XamlTypeName.TryParse ("{urn:foo}Foo", new MyNSResolver (), out dummy), "#1");
+               }
+
+               [Test]
+               public void TryParseResolveFailure ()
+               {
+                       Assert.IsFalse (XamlTypeName.TryParse ("x:Foo", new MyNSResolver (), out dummy), "#1");
+               }
+
+               [Test]
+               public void TryParseResolveSuccess ()
+               {
+                       var r = new MyNSResolver ();
+                       r.Add ("x", "urn:foo");
+                       Assert.IsTrue (XamlTypeName.TryParse ("x:Foo", r, out dummy), "#1");
+                       Assert.IsNotNull (dummy, "#2");
+                       Assert.AreEqual ("urn:foo", dummy.Namespace, "#2-2");
+                       Assert.AreEqual ("Foo", dummy.Name, "#2-3");
+               }
+
+               [Test]
+               public void TryParseInvalidGenericName ()
+               {
+                       var r = new MyNSResolver ();
+                       r.Add ("x", "urn:foo");
+                       Assert.IsFalse (XamlTypeName.TryParse ("x:Foo()", r, out dummy), "#1");
+               }
+
+               [Test]
+               public void TryParseGenericName ()
+               {
+                       var r = new MyNSResolver ();
+                       r.Add ("x", "urn:foo");
+                       Assert.IsTrue (XamlTypeName.TryParse ("x:Foo(x:Foo,x:Bar)", r, out dummy), "#1");
+                       Assert.AreEqual (2, dummy.TypeArguments.Count, "#2");
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ParseListNullNames ()
+               {
+                       XamlTypeName.ParseList (null, new MyNSResolver ());
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ParseListNullResolver ()
+               {
+                       XamlTypeName.ParseList ("foo", null);
+               }
+
+               [Test]
+               [ExpectedException (typeof (FormatException))]
+               public void ParseListInvalid ()
+               {
+                       XamlTypeName.ParseList ("foo bar", new MyNSResolver ());
+               }
+
+               [Test]
+               [ExpectedException (typeof (FormatException))]
+               public void ParseListInvalid2 ()
+               {
+                       XamlTypeName.ParseList ("foo,", new MyNSResolver ());
+               }
+
+               [Test]
+               [ExpectedException (typeof (FormatException))]
+               public void ParseListInvalid3 ()
+               {
+                       XamlTypeName.ParseList ("", new MyNSResolver ());
+               }
+
+               [Test]
+               public void ParseListValid ()
+               {
+                       var l = XamlTypeName.ParseList ("foo,  bar", new MyNSResolver ());
+                       Assert.AreEqual (2, l.Count, "#1");
+                       Assert.AreEqual ("{}foo", l [0].ToString (), "#2");
+                       Assert.AreEqual ("{}bar", l [1].ToString (), "#3");
+                       l = XamlTypeName.ParseList ("foo,bar", new MyNSResolver ());
+                       Assert.AreEqual ("{}foo", l [0].ToString (), "#4");
+                       Assert.AreEqual ("{}bar", l [1].ToString (), "#5");
+               }
+
+               class MyNSResolver : IXamlNamespaceResolver
+               {
+                       public MyNSResolver ()
+                               : this (false)
+                       {
+                       }
+
+                       public MyNSResolver (bool returnNullForEmpty)
+                       {
+                               if (!returnNullForEmpty)
+                                       dic.Add (String.Empty, String.Empty);
+                       }
+
+                       Dictionary<string,string> dic = new Dictionary<string,string> ();
+
+                       public void Add (string prefix, string ns)
+                       {
+                               dic [prefix] = ns;
+                       }
+
+                       public string GetNamespace (string prefix)
+                       {
+                               string ns;
+                               return dic.TryGetValue (prefix, out ns) ? ns : null;
+                       }
+                       
+                       public IEnumerable<NamespaceDeclaration> GetNamespacePrefixes ()
+                       {
+                               foreach (var p in dic)
+                                       yield return new NamespaceDeclaration (p.Value, p.Key);
+                       }
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml.Schema/XamlTypeTypeConverterTest.cs b/mcs/class/System.Xaml/Test/System.Xaml.Schema/XamlTypeTypeConverterTest.cs
new file mode 100644 (file)
index 0000000..bffd20e
--- /dev/null
@@ -0,0 +1,113 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Globalization;
+using System.Reflection;
+using System.Text;
+using System.Windows.Markup;
+using System.Xaml;
+using System.Xaml.Schema;
+using System.Xml;
+using NUnit.Framework;
+
+namespace MonoTests.System.Xaml.Schema
+{
+       [TestFixture]
+       public class XamlTypeTypeConverterTest
+       {
+               XamlTypeTypeConverter c = new XamlTypeTypeConverter ();
+               XamlSchemaContext sctx = new XamlSchemaContext (null, null);
+
+               [Test]
+               [Ignore ("It should return True for XamlType")]
+               public void CanConvertFrom ()
+               {
+                       Assert.IsFalse (c.CanConvertFrom (null, typeof (XamlType)), "#1");
+                       Assert.IsTrue (c.CanConvertFrom (null, typeof (string)), "#2");
+                       Assert.IsFalse (c.CanConvertFrom (null, typeof (int)), "#3");
+                       Assert.IsFalse (c.CanConvertFrom (null, typeof (object)), "#4");
+               }
+
+               [Test]
+               public void CanConvertTo ()
+               {
+                       Assert.IsFalse (c.CanConvertTo (null, typeof (XamlType)), "#1");
+                       Assert.IsTrue (c.CanConvertTo (null, typeof (string)), "#2");
+                       Assert.IsFalse (c.CanConvertTo (null, typeof (int)), "#3");
+                       Assert.IsFalse (c.CanConvertTo (null, typeof (object)), "#4");
+               }
+
+               // ConvertFrom() is not supported in either way.
+
+               [Test]
+               [ExpectedException (typeof (NotSupportedException))]
+               public void ConvertFrom ()
+               {
+                       c.ConvertFrom (null, null, XamlLanguage.String);
+               }
+
+               [Test]
+               [ExpectedException (typeof (NotSupportedException))]
+               public void ConvertFrom2 ()
+               {
+                       c.ConvertFrom (null, null, "System.Int32");
+               }
+
+               [Test]
+               [ExpectedException (typeof (NotSupportedException))]
+               public void ConvertXamlTypeToXamlType ()
+               {
+                       Assert.AreEqual ("", c.ConvertTo (null, null, XamlLanguage.String, typeof (XamlType)), "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (NotSupportedException))]
+               public void ConvertXamlTypeToType ()
+               {
+                       c.ConvertTo (null, null, XamlLanguage.String, typeof (Type));
+               }
+
+               [Test]
+               public void ConvertXamlTypeToString ()
+               {
+                       // ... so, it does not seem to just call XamlType.ToString(), but rather first try to use UnderlyingType if possible.
+                       Assert.AreEqual ("System.String", c.ConvertTo (null, null, XamlLanguage.String, typeof (string)), "#1"); // huh?
+                       Assert.AreEqual ("System.Windows.Markup.TypeExtension", c.ConvertTo (null, null, XamlLanguage.Type, typeof (string)), "#1"); // huh?
+                       Assert.AreEqual ("{urn:foo}Foo", c.ConvertTo (null, null, new XamlType ("urn:foo", "Foo", null, sctx), typeof (string)), "#2");
+               }
+
+               [Test]
+               public void ConvertStringToString ()
+               {
+                       Assert.AreEqual ("foo", c.ConvertTo (null, CultureInfo.InvariantCulture, "foo", typeof (string)), "#1");
+               }
+
+               [Test]
+               public void ConvertIntToString ()
+               {
+                       Assert.AreEqual ("5", c.ConvertTo (null, null, 5, typeof (string)), "#1");
+               }
+       }
+}
\ No newline at end of file
diff --git a/mcs/class/System.Xaml/Test/System.Xaml.Schema/XamlValueConverterTest.cs b/mcs/class/System.Xaml/Test/System.Xaml.Schema/XamlValueConverterTest.cs
new file mode 100644 (file)
index 0000000..3baf0b2
--- /dev/null
@@ -0,0 +1,124 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Text;
+using System.Xaml;
+using System.Xaml.Schema;
+using System.Xml;
+using NUnit.Framework;
+
+namespace MonoTests.System.Xaml.Schema
+{
+       [TestFixture]
+       public class XamlValueConverterTest
+       {
+               [Test]
+               [ExpectedException (typeof (ArgumentException))]
+               public void ConstructorNullConverterTypeTargetType ()
+               {
+                       // either of them must be non-null.
+                       new XamlValueConverter<TypeConverter> (null, null);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentException))]
+               public void ConstructorNullConverterTypeTargetTypeNull ()
+               {
+                       // either of them must be non-null.
+                       new XamlValueConverter<TypeConverter> (null, null, null);
+               }
+
+               [Test]
+               public void ConstructorOnlyWithName ()
+               {
+                       // ok
+                       new XamlValueConverter<TypeConverter> (null, null, "Foo");
+               }
+
+               [Test]
+               public void ConstructorNullConverterType ()
+               {
+                       // ok
+                       var c = new XamlValueConverter<TypeConverter> (null, XamlLanguage.Int32);
+                       Assert.IsNull (c.ConverterInstance, "#1");
+               }
+
+               [Test]
+               public void ConstructorNullTargetType ()
+               {
+                       // ok
+                       var c = new XamlValueConverter<TypeConverter> (typeof (Int32Converter), null);
+                       Assert.IsTrue (c.ConverterInstance is Int32Converter, "#1");
+               }
+
+               [Test]
+               public void ConstructorNullName ()
+               {
+                       // ok
+                       new XamlValueConverter<TypeConverter> (typeof (Int32Converter), XamlLanguage.Int32, null);
+               }
+
+               [Test]
+               public void ConverterTargetMismatch ()
+               {
+                       // ok
+                       var c = new XamlValueConverter<TypeConverter> (typeof (Int32Converter), XamlLanguage.String, null);
+                       Assert.IsTrue (c.ConverterInstance is Int32Converter, "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlSchemaException))]
+               public void InconsistentConverterType ()
+               {
+                       var c = new XamlValueConverter<TypeConverter> (typeof (int), XamlLanguage.String, null);
+                       Assert.IsNull (c.ConverterInstance, "#1");
+               }
+
+               [Test]
+               public void Equality ()
+               {
+                       // ok
+                       var c1 = new XamlValueConverter<TypeConverter> (null, XamlLanguage.Int32);
+                       var c2 = new XamlValueConverter<TypeConverter> (null, XamlLanguage.Int32);
+                       var c3 = new XamlValueConverter<TypeConverter> (typeof (Int32Converter), XamlLanguage.Int32);
+                       var c4 = new XamlValueConverter<TypeConverter> (typeof (Int32Converter), XamlLanguage.Int32, null);
+                       var c5 = new XamlValueConverter<TypeConverter> (typeof (Int32Converter), XamlLanguage.Int32, "Foo");
+                       Assert.IsTrue (c1 == c2, "#1");
+                       Assert.IsFalse (c1 == c3, "#2");
+                       Assert.IsTrue (c3 == c4, "#3");
+                       Assert.IsFalse (c4 == c5, "#4");
+               }
+               
+               [Test]
+               public void TestToString ()
+               {
+                       Assert.AreEqual ("Int32Converter(Int32)", new XamlValueConverter<TypeConverter> (typeof (Int32Converter), XamlLanguage.Int32).ToString (), "#1");
+                       Assert.AreEqual ("Foo", new XamlValueConverter<TypeConverter> (typeof (Int32Converter), XamlLanguage.Int32, "Foo").ToString (), "#2");
+                       Assert.AreEqual ("Int32Converter", new XamlValueConverter<TypeConverter> (typeof (Int32Converter), null).ToString (), "#1");
+                       Assert.AreEqual ("Int32", new XamlValueConverter<TypeConverter> (null, XamlLanguage.Int32).ToString (), "#3"); // huh, really? no difference from ConverterType?
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/AmbientPropertyValueTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/AmbientPropertyValueTest.cs
new file mode 100644 (file)
index 0000000..7e7d522
--- /dev/null
@@ -0,0 +1,41 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Xaml;
+using NUnit.Framework;
+
+namespace MonoTests.System.Xaml
+{
+       [TestFixture]
+       public class AmbientPropertyValueTest
+       {
+               [Test]
+               public void ConstructorNullProperty ()
+               {
+                       new AmbientPropertyValue (null, 5);
+                       new AmbientPropertyValue (null, null);
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/AttachableMemberIdentifierTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/AttachableMemberIdentifierTest.cs
new file mode 100644 (file)
index 0000000..e17b623
--- /dev/null
@@ -0,0 +1,84 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Xaml;
+using NUnit.Framework;
+
+namespace MonoTests.System.Xaml
+{
+       [TestFixture]
+       public class AttachableMemberIdentifierTest
+       {
+               [Test]
+               public void NullTypeName ()
+               {
+                       // It is not rejected. No dot.
+                       Assert.AreEqual ("Foo", new AttachableMemberIdentifier (null, "Foo").ToString (), "#1");
+               }
+               
+               [Test]
+               public void EmptyMemberName ()
+               {
+                       // It is not rejected. Trailing dot.
+                       Assert.AreEqual ("System.String.", new AttachableMemberIdentifier (typeof (string), "").ToString (), "#1");
+               }
+
+               [Test]
+               public void ToStringTest ()
+               {
+                       Assert.AreEqual ("System.String.Foo", new AttachableMemberIdentifier (typeof (string), "Foo").ToString (), "#1");
+                       Assert.AreEqual ("System.Int32.Foo", new AttachableMemberIdentifier (typeof (int), "Foo").ToString (), "#2");
+               }
+
+               [Test]
+               public void Equivalence ()
+               {
+                       var a1 = new AttachableMemberIdentifier (typeof (string), "Foo");
+                       var a2 = new AttachableMemberIdentifier (typeof (string), "Foo");
+                       var a3 = new AttachableMemberIdentifier (null, "Foo");
+                       var a4 = new AttachableMemberIdentifier (null, "Foo");
+                       var a5 = new AttachableMemberIdentifier (typeof (string), null);
+                       var a6 = new AttachableMemberIdentifier (typeof (string), null);
+                       Assert.IsTrue (a1 == a2, "#1");
+                       Assert.IsFalse (a1 == a3, "#2");
+                       Assert.IsFalse (a1 == a5, "#3");
+                       Assert.IsTrue (a3 == a4, "#4");
+                       Assert.IsFalse (a3 == a1, "#5");
+                       Assert.IsFalse (a3 == a5, "#6");
+                       Assert.IsTrue (a5 == a6, "#7");
+                       Assert.IsFalse (a5 == a1, "#8");
+                       Assert.IsFalse (a5 == a3, "#9");
+                       Assert.IsTrue (a1.Equals (a2),"#11");
+                       Assert.IsFalse (a1.Equals (a3),"#12");
+                       Assert.IsFalse (a1.Equals (a5),"#13");
+                       Assert.IsTrue (a3.Equals (a4),"#14");
+                       Assert.IsFalse (a3.Equals (a1),"#15");
+                       Assert.IsFalse (a3.Equals (a5),"#16");
+                       Assert.IsTrue (a5.Equals (a6),"#17");
+                       Assert.IsFalse (a5.Equals (a1),"#18");
+                       Assert.IsFalse (a5.Equals (a3),"#19");
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/ChangeLog b/mcs/class/System.Xaml/Test/System.Xaml/ChangeLog
new file mode 100644 (file)
index 0000000..28744c5
--- /dev/null
@@ -0,0 +1,187 @@
+2010-04-26  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReaderTest.cs : more test use cases.
+
+2010-04-26  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReaderTest.cs : enable working tests.
+       * XamlTypeTest.cs : added a test for GetAliasedProperty().
+
+2010-04-22  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReaderTest.cs : enabled working tests. Add decent
+         namespace declaration node assertions in the next tests.
+
+2010-04-22  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReaderTest.cs : add another MarkupExtension test.
+
+2010-04-20  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReaderTest.cs : added a bunch of read detail tests (lots
+         on not-working ones).
+
+2010-04-20  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlTypeTest.cs : added tests for GetPositionalParameters().
+
+2010-04-18  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReaderTest.cs : enable working test.
+
+2010-04-18  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReaderTest.cs : enable working tests and remove invalid
+         comment.
+
+2010-04-18  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReaderTest.cs : add simple read tests for some types.
+
+2010-04-16  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlMemberTest.cs, XamlXmlReaderTest.cs :
+         a few correction and additions on member equality.
+
+2010-04-16  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlMemberTest.cs, XamlXmlReaderTest.cs : some member equivalence
+         tests. Commented out some assertions that won't work for a while.
+
+2010-04-16  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlXmlReaderTest.cs : add more detailed read tests, and more
+         file-based tests (not working yet).
+
+2010-04-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlTypeTest.cs, XamlLanguageTest.cs : enable AllowedContentTypes
+         and ContentWrappers tests.
+
+2010-04-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlXmlReaderTest.cs : enable DateTime tests.
+       * XamlSchemaContextTest.cs : add a type name resolver test.
+
+2010-04-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlXmlReaderTest.cs : added a couple more of read and load tests.
+
+2010-04-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReaderTest.cs : add more read tests (lots of them are
+         not fully working yet).
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlXmlReaderTest.cs : add primitive TimeSpan reader test.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlTypeTest.cs : add more TypeConverter and ToString() tests.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlMemberTest.cs : remove extra type that I wrote when I thought
+         there were no public UnderlyingMember.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlMemberTest.cs : added ToStringTest().
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlXmlReaderTest.cs : new, too insufficient yet.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReaderTest.cs
+         XamlSchemaContextTest.cs
+         XamlTypeTest.cs : a couple of Type/TypeExtension-related tests.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlTypeTest.cs, XamlLanguageTest.cs : enable ValueSerializer tests.
+
+2010-04-13  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlXmlWriterTest.cs : enable WriteNode() tests.
+
+2010-04-13  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectWriterTest.cs : new test.
+       * XamlXmlWriterTest.cs : added some not-working tests.
+
+2010-04-13  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlTypeTest.cs : assert that dictionary types are *not* collection.
+
+2010-04-12  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlSchemaContextTest.cs, XamlTypeTest.cs : more type system tests.
+
+2010-04-12  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlSchemaContextTest.cs, XamlTypeTest.cs : more type system tests.
+
+2010-04-12  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlTypeTest.cs : add a few more TypeConverter assertions.
+
+2010-04-12  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlLanguageTest.cs : add member lookup tests and properties tests
+         on those members.
+       * XamlTypeTest.cs : add GetAllAttachableMembers() test.
+         Enable IsConstructible().
+
+2010-04-11  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlSchemaContextTest.cs : add some tests for methods.
+
+2010-04-11  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlObjectReaderTest.cs : new test.
+
+2010-04-10  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlXmlWriterTest.cs : new test.
+
+2010-04-09  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlTypeTest.cs, XamlLanguageTest.cs : enable TypeConverter tests.
+
+2010-04-09  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlLanguageTest.cs : new test.
+       * XamlDirectiveTest.cs : add another ns test.
+
+2010-04-09  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlTypeTest.cs : added a lot of new tests.
+
+2010-04-08  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlMemberTest.cs, XamlDirectiveTest.cs :
+         Add more tests. Enable working tests.
+
+2010-04-08  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XamlDirectiveTest.cs
+         XamlMemberTest.cs : new tests.
+
+2010-04-08  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * AmbientPropertyValueTest.cs
+         XamlObjectWriterSettingsTest.cs
+         AttachableMemberIdentifierTest.cs
+         XamlReaderSettingsTest.cs
+         XamlSchemaContextSettingsTest.cs
+         NamespaceDeclarationTest.cs
+         XamlSchemaContextTest.cs
+         XamlDuplicateMemberExceptionTest.cs
+         XamlTypeTest.cs
+         XamlObjectEventArgsTest.cs
+         XamlXmlReaderSettingsTest.cs
+         XamlObjectReaderSettingsTest.cs
+         XamlXmlWriterSettingsTest.cs : initial checkin.
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/NamespaceDeclarationTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/NamespaceDeclarationTest.cs
new file mode 100644 (file)
index 0000000..7693654
--- /dev/null
@@ -0,0 +1,41 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Xaml;
+using NUnit.Framework;
+
+namespace MonoTests.System.Xaml
+{
+       [TestFixture]
+       public class NamespaceDeclarationTest
+       {
+               [Test]
+               public void ConstructorNull ()
+               {
+                       // allowed.
+                       new NamespaceDeclaration (null, null);
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlDirectiveTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlDirectiveTest.cs
new file mode 100755 (executable)
index 0000000..30d584a
--- /dev/null
@@ -0,0 +1,154 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Reflection;
+using System.Xaml;
+using System.Xaml.Schema;
+using NUnit.Framework;
+
+using Category = NUnit.Framework.CategoryAttribute;
+
+namespace MonoTests.System.Xaml
+{
+       [TestFixture]
+       public class XamlDirectiveTest
+       {
+               XamlSchemaContext sctx = new XamlSchemaContext (new XamlSchemaContextSettings ());
+
+               [Test]
+               public void ConstructorNameNull ()
+               {
+                       // wow, it is allowed.
+                       var d = new XamlDirective (String.Empty, null);
+                       Assert.IsNull (d.Name, "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorNamespaceNull ()
+               {
+                       new XamlDirective (null, "Foo");
+               }
+
+               [Test]
+               public void ConstructorNamespaceXamlNS ()
+               {
+                       new XamlDirective (XamlLanguage.Xaml2006Namespace, "Foo");
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorComplexParamsTypeNull ()
+               {
+                       new XamlDirective (new string [] {"urn:foo"}, "Foo", null, null, AllowedMemberLocations.Any);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorComplexParamsNullNamespaces ()
+               {
+                       var d = new XamlDirective (null, "Foo", new XamlType (typeof (object), sctx), null, AllowedMemberLocations.Any);
+               }
+
+               [Test]
+               public void ConstructorComplexParamsEmptyNamespaces ()
+               {
+                       var d = new XamlDirective (new string [0], "Foo", new XamlType (typeof (object), sctx), null, AllowedMemberLocations.Any);
+               }
+
+               [Test]
+               public void ConstructorComplexParams ()
+               {
+                       var d = new XamlDirective (new string [] {"urn:foo"}, "Foo", new XamlType (typeof (object), sctx), null, AllowedMemberLocations.Any);
+               }
+
+               [Test]
+               public void DefaultValuesWithName ()
+               {
+                       var d = new XamlDirective ("urn:foo", "Foo");
+                       Assert.AreEqual (AllowedMemberLocations.Any, d.AllowedLocation, "#1");
+                       Assert.IsNull (d.DeclaringType, "#2");
+                       Assert.IsNotNull (d.Invoker, "#3");
+                       Assert.IsNull (d.Invoker.UnderlyingGetter, "#3-2");
+                       Assert.IsNull (d.Invoker.UnderlyingSetter, "#3-3");
+                       Assert.IsTrue (d.IsUnknown, "#4");
+                       Assert.IsTrue (d.IsReadPublic, "#5");
+                       Assert.IsTrue (d.IsWritePublic, "#6");
+                       Assert.AreEqual ("Foo", d.Name, "#7");
+                       Assert.IsTrue (d.IsNameValid, "#8");
+                       Assert.AreEqual ("urn:foo", d.PreferredXamlNamespace, "#9");
+                       Assert.IsNull (d.TargetType, "#10");
+                       Assert.IsNotNull (d.Type, "#11");
+                       Assert.AreEqual (typeof (object), d.Type.UnderlyingType, "#11-2");
+                       Assert.IsNull (d.TypeConverter, "#12");
+                       Assert.IsNull (d.ValueSerializer, "#13");
+                       Assert.IsNull (d.DeferringLoader, "#14");
+                       Assert.IsNull (d.UnderlyingMember, "#15");
+                       Assert.IsFalse (d.IsReadOnly, "#16");
+                       Assert.IsFalse (d.IsWriteOnly, "#17");
+                       Assert.IsFalse (d.IsAttachable, "#18");
+                       Assert.IsFalse (d.IsEvent, "#19");
+                       Assert.IsTrue (d.IsDirective, "#20");
+                       Assert.IsNotNull (d.DependsOn, "#21");
+                       Assert.AreEqual (0, d.DependsOn.Count, "#21-2");
+                       Assert.IsFalse (d.IsAmbient, "#22");
+                       Assert.AreEqual (DesignerSerializationVisibility.Visible, d.SerializationVisibility, "#23");
+               }
+
+               [Test]
+               public void DefaultValuesWithComplexParams ()
+               {
+                       var d = new XamlDirective (new string [0], "Foo", new XamlType (typeof (object), sctx), null, AllowedMemberLocations.Any);
+                       Assert.AreEqual (AllowedMemberLocations.Any, d.AllowedLocation, "#1");
+                       Assert.IsNull (d.DeclaringType, "#2");
+                       Assert.IsNotNull (d.Invoker, "#3");
+                       Assert.IsNull (d.Invoker.UnderlyingGetter, "#3-2");
+                       Assert.IsNull (d.Invoker.UnderlyingSetter, "#3-3");
+                       Assert.IsFalse (d.IsUnknown, "#4"); // different from another test
+                       Assert.IsTrue (d.IsReadPublic, "#5");
+                       Assert.IsTrue (d.IsWritePublic, "#6");
+                       Assert.AreEqual ("Foo", d.Name, "#7");
+                       Assert.IsTrue (d.IsNameValid, "#8");
+                       Assert.AreEqual (null, d.PreferredXamlNamespace, "#9"); // different from another test (as we specified empty array above)
+                       Assert.IsNull (d.TargetType, "#10");
+                       Assert.IsNotNull (d.Type, "#11");
+                       Assert.AreEqual (typeof (object), d.Type.UnderlyingType, "#11-2");
+                       Assert.IsNull (d.TypeConverter, "#12");
+                       Assert.IsNull (d.ValueSerializer, "#13");
+                       Assert.IsNull (d.DeferringLoader, "#14");
+                       Assert.IsNull (d.UnderlyingMember, "#15");
+                       Assert.IsFalse (d.IsReadOnly, "#16");
+                       Assert.IsFalse (d.IsWriteOnly, "#17");
+                       Assert.IsFalse (d.IsAttachable, "#18");
+                       Assert.IsFalse (d.IsEvent, "#19");
+                       Assert.IsTrue (d.IsDirective, "#20");
+                       Assert.IsNotNull (d.DependsOn, "#21");
+                       Assert.AreEqual (0, d.DependsOn.Count, "#21-2");
+                       Assert.IsFalse (d.IsAmbient, "#22");
+                       Assert.AreEqual (DesignerSerializationVisibility.Visible, d.SerializationVisibility, "#23");
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlDuplicateMemberExceptionTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlDuplicateMemberExceptionTest.cs
new file mode 100644 (file)
index 0000000..257e649
--- /dev/null
@@ -0,0 +1,44 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Xaml;
+using NUnit.Framework;
+
+namespace MonoTests.System.Xaml
+{
+       [TestFixture]
+       public class XamlDuplicateMemberExceptionTest
+       {
+               [Test]
+               public void ConstructorNullArg ()
+               {
+                       // allowed.
+                       var ex = new XamlDuplicateMemberException ((XamlMember) null, (XamlType) null);
+                       Assert.IsNull (ex.DuplicateMember, "#1");
+                       Assert.IsNull (ex.ParentType, "#2");
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlLanguageTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlLanguageTest.cs
new file mode 100644 (file)
index 0000000..36f3295
--- /dev/null
@@ -0,0 +1,836 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml;
+using System.Xaml.Schema;
+using System.Xml;
+using NUnit.Framework;
+
+using Category = NUnit.Framework.CategoryAttribute;
+
+namespace MonoTests.System.Xaml
+{
+       [TestFixture]
+       public class XamlLanguageTest
+       {
+               [Test]
+               public void XamlNamepaces ()
+               {
+                       var l = XamlLanguage.XamlNamespaces;
+                       Assert.AreEqual (1, l.Count, "#1");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, l [0], "#2");
+               }
+
+               [Test]
+               public void XmlNamepaces ()
+               {
+                       var l = XamlLanguage.XmlNamespaces;
+                       Assert.AreEqual (1, l.Count, "#1");
+                       Assert.AreEqual (XamlLanguage.Xml1998Namespace, l [0], "#2");
+               }
+
+               [Test]
+               public void AllDirectives ()
+               {
+                       var l = XamlLanguage.AllDirectives;
+                       Assert.AreEqual (24, l.Count, "count");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Arguments), "#0");
+                       Assert.IsTrue (l.Contains (XamlLanguage.AsyncRecords), "#1");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Base), "#2");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Class), "#3");
+                       Assert.IsTrue (l.Contains (XamlLanguage.ClassAttributes), "#4");
+                       Assert.IsTrue (l.Contains (XamlLanguage.ClassModifier), "#5");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Code), "#6");
+                       Assert.IsTrue (l.Contains (XamlLanguage.ConnectionId), "#7");
+                       Assert.IsTrue (l.Contains (XamlLanguage.FactoryMethod), "#8");
+                       Assert.IsTrue (l.Contains (XamlLanguage.FieldModifier), "#9");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Initialization), "#10");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Items), "#11");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Key), "#12");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Lang), "#13");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Members), "#14");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Name), "#15");
+                       Assert.IsTrue (l.Contains (XamlLanguage.PositionalParameters), "#16");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Space), "#17");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Subclass), "#18");
+                       Assert.IsTrue (l.Contains (XamlLanguage.SynchronousMode), "#19");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Shared), "#20");
+                       Assert.IsTrue (l.Contains (XamlLanguage.TypeArguments), "#21");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Uid), "#22");
+                       Assert.IsTrue (l.Contains (XamlLanguage.UnknownContent), "#23");
+               }
+
+               [Test]
+               public void AllTypes ()
+               {
+                       var l = XamlLanguage.AllTypes;
+                       Assert.AreEqual (21, l.Count, "count");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Array), "#0");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Boolean), "#1");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Byte), "#2");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Char), "#3");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Decimal), "#4");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Double), "#5");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Int16), "#6");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Int32), "#7");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Int64), "#8");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Member), "#9");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Null), "#10");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Object), "#11");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Property), "#12");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Reference), "#13");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Single), "#14");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Static), "#15");
+                       Assert.IsTrue (l.Contains (XamlLanguage.String), "#16");
+                       Assert.IsTrue (l.Contains (XamlLanguage.TimeSpan), "#17");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Type), "#18");
+                       Assert.IsTrue (l.Contains (XamlLanguage.Uri), "#19");
+                       Assert.IsTrue (l.Contains (XamlLanguage.XData), "#20");
+               }
+
+               // directive property details
+
+               [Test]
+               public void Arguments ()
+               {
+                       var d = XamlLanguage.Arguments;
+                       TestXamlDirectiveCommon (d, "Arguments", AllowedMemberLocations.Any, typeof (List<object>));
+               }
+
+               [Test]
+               public void AsyncRecords ()
+               {
+                       var d = XamlLanguage.AsyncRecords;
+                       TestXamlDirectiveCommon (d, "AsyncRecords", AllowedMemberLocations.Attribute, typeof (string));
+               }
+
+               [Test]
+               public void Base ()
+               {
+                       var d = XamlLanguage.Base;
+                       TestXamlDirectiveCommon (d, "base", XamlLanguage.Xml1998Namespace, AllowedMemberLocations.Attribute, typeof (string));
+               }
+
+               [Test]
+               public void Class ()
+               {
+                       var d = XamlLanguage.Class;
+                       TestXamlDirectiveCommon (d, "Class", AllowedMemberLocations.Attribute, typeof (string));
+               }
+
+               [Test]
+               public void ClassAttributes ()
+               {
+                       var d = XamlLanguage.ClassAttributes;
+                       TestXamlDirectiveCommon (d, "ClassAttributes", AllowedMemberLocations.MemberElement, typeof (List<Attribute>));
+               }
+
+               [Test]
+               public void ClassModifier ()
+               {
+                       var d = XamlLanguage.ClassModifier;
+                       TestXamlDirectiveCommon (d, "ClassModifier", AllowedMemberLocations.Attribute, typeof (string));
+               }
+
+               [Test]
+               public void Code ()
+               {
+                       var d = XamlLanguage.Code;
+                       TestXamlDirectiveCommon (d, "Code", AllowedMemberLocations.Attribute, typeof (string));
+               }
+
+               [Test]
+               public void ConnectionId ()
+               {
+                       var d = XamlLanguage.ConnectionId;
+                       TestXamlDirectiveCommon (d, "ConnectionId", AllowedMemberLocations.Any, typeof (string));
+               }
+
+               [Test]
+               public void FactoryMethod ()
+               {
+                       var d = XamlLanguage.FactoryMethod;
+                       TestXamlDirectiveCommon (d, "FactoryMethod", AllowedMemberLocations.Any, typeof (string));
+               }
+
+               [Test]
+               public void FieldModifier ()
+               {
+                       var d = XamlLanguage.FieldModifier;
+                       TestXamlDirectiveCommon (d, "FieldModifier", AllowedMemberLocations.Attribute, typeof (string));
+               }
+
+               [Test]
+               public void Initialization ()
+               {
+                       var d = XamlLanguage.Initialization;
+                       // weird name
+                       TestXamlDirectiveCommon (d, "_Initialization", AllowedMemberLocations.Any, typeof (object));
+               }
+
+               [Test]
+               public void Items ()
+               {
+                       var d = XamlLanguage.Items;
+                       // weird name
+                       TestXamlDirectiveCommon (d, "_Items", AllowedMemberLocations.Any, typeof (List<object>));
+               }
+
+               [Test]
+               public void Key ()
+               {
+                       var d = XamlLanguage.Key;
+                       TestXamlDirectiveCommon (d, "Key", AllowedMemberLocations.Any, typeof (object));
+               }
+
+               [Test]
+               public void Lang ()
+               {
+                       var d = XamlLanguage.Lang;
+                       TestXamlDirectiveCommon (d, "lang", XamlLanguage.Xml1998Namespace, AllowedMemberLocations.Attribute, typeof (string));
+               }
+
+               [Test]
+               public void Members ()
+               {
+                       var d = XamlLanguage.Members;
+                       TestXamlDirectiveCommon (d, "Members", AllowedMemberLocations.MemberElement, typeof (List<MemberDefinition>));
+               }
+
+               [Test]
+               public void Name ()
+               {
+                       var d = XamlLanguage.Name;
+                       TestXamlDirectiveCommon (d, "Name", AllowedMemberLocations.Attribute, typeof (string));
+               }
+
+               [Test]
+               public void PositionalParameters ()
+               {
+                       var d = XamlLanguage.PositionalParameters;
+                       // weird name
+                       TestXamlDirectiveCommon (d, "_PositionalParameters", AllowedMemberLocations.Any, typeof (List<object>));
+               }
+
+               [Test]
+               public void Subclass ()
+               {
+                       var d = XamlLanguage.Subclass;
+                       TestXamlDirectiveCommon (d, "Subclass", AllowedMemberLocations.Attribute, typeof (string));
+               }
+
+               [Test]
+               public void SynchronousMode ()
+               {
+                       var d = XamlLanguage.SynchronousMode;
+                       TestXamlDirectiveCommon (d, "SynchronousMode", AllowedMemberLocations.Attribute, typeof (string));
+               }
+
+               [Test]
+               public void Shared ()
+               {
+                       var d = XamlLanguage.Shared;
+                       TestXamlDirectiveCommon (d, "Shared", AllowedMemberLocations.Attribute, typeof (string));
+               }
+
+               [Test]
+               public void Space ()
+               {
+                       var d = XamlLanguage.Space;
+                       TestXamlDirectiveCommon (d, "space", XamlLanguage.Xml1998Namespace, AllowedMemberLocations.Attribute, typeof (string));
+               }
+
+               [Test]
+               public void TypeArguments ()
+               {
+                       var d = XamlLanguage.TypeArguments;
+                       TestXamlDirectiveCommon (d, "TypeArguments", AllowedMemberLocations.Attribute, typeof (string));
+               }
+
+               [Test]
+               public void Uid ()
+               {
+                       var d = XamlLanguage.Uid;
+                       TestXamlDirectiveCommon (d, "Uid", AllowedMemberLocations.Attribute, typeof (string));
+               }
+
+               [Test]
+               public void UnknownContent ()
+               {
+                       var d = XamlLanguage.UnknownContent;
+                       // weird name
+                       TestXamlDirectiveCommon (d, "_UnknownContent", XamlLanguage.Xaml2006Namespace, AllowedMemberLocations.MemberElement, typeof (object), true);
+               }
+
+               void TestXamlDirectiveCommon (XamlDirective d, string name, AllowedMemberLocations allowedLocation, Type type)
+               {
+                       TestXamlDirectiveCommon (d, name, XamlLanguage.Xaml2006Namespace, allowedLocation, type);
+               }
+
+               void TestXamlDirectiveCommon (XamlDirective d, string name, string ns, AllowedMemberLocations allowedLocation, Type type)
+               {
+                       TestXamlDirectiveCommon (d, name, ns, allowedLocation, type, false);
+               }
+
+               void TestXamlDirectiveCommon (XamlDirective d, string name, string ns, AllowedMemberLocations allowedLocation, Type type, bool isUnknown)
+               {
+                       Assert.AreEqual (allowedLocation, d.AllowedLocation, "#1");
+                       Assert.IsNull (d.DeclaringType, "#2");
+                       Assert.IsNotNull (d.Invoker, "#3");
+                       Assert.IsNull (d.Invoker.UnderlyingGetter, "#3-2");
+                       Assert.IsNull (d.Invoker.UnderlyingSetter, "#3-3");
+                       Assert.AreEqual (isUnknown, d.IsUnknown, "#4");
+                       Assert.IsTrue (d.IsReadPublic, "#5");
+                       Assert.IsTrue (d.IsWritePublic, "#6");
+                       Assert.AreEqual (name, d.Name, "#7");
+                       Assert.IsTrue (d.IsNameValid, "#8");
+                       Assert.AreEqual (ns, d.PreferredXamlNamespace, "#9");
+                       Assert.IsNull (d.TargetType, "#10");
+                       Assert.IsNotNull (d.Type, "#11");
+                       Assert.AreEqual (type, d.Type.UnderlyingType, "#11-2");
+
+                       // .NET returns StringConverter, but it should not premise that key must be string (it is object)
+                       if (name == "Key")
+                               ;//Assert.IsNull (d.TypeConverter, "#12")
+                       else if (type.IsGenericType || name == "_Initialization" || name == "_UnknownContent")
+                               Assert.IsNull (d.TypeConverter, "#12");
+                       else
+                               Assert.IsNotNull (d.TypeConverter, "#12");
+                       Assert.IsNull (d.ValueSerializer, "#13");
+                       Assert.IsNull (d.DeferringLoader, "#14");
+                       Assert.IsNull (d.UnderlyingMember, "#15");
+                       Assert.IsFalse (d.IsReadOnly, "#16");
+                       Assert.IsFalse (d.IsWriteOnly, "#17");
+                       Assert.IsFalse (d.IsAttachable, "#18");
+                       Assert.IsFalse (d.IsEvent, "#19");
+                       Assert.IsTrue (d.IsDirective, "#20");
+                       Assert.IsNotNull (d.DependsOn, "#21");
+                       Assert.AreEqual (0, d.DependsOn.Count, "#21-2");
+                       Assert.IsFalse (d.IsAmbient, "#22");
+                       Assert.AreEqual (DesignerSerializationVisibility.Visible, d.SerializationVisibility, "#23");
+               }
+
+               // type property details
+
+               // extension types
+               [Test]
+               public void Array ()
+               {
+                       var t = XamlLanguage.Array;
+                       TestXamlTypeExtension (t, "ArrayExtension", typeof (ArrayExtension), typeof (Array), true);
+                       Assert.IsNotNull (t.ContentProperty, "#27");
+                       Assert.AreEqual ("Items", t.ContentProperty.Name, "#27-2");
+
+                       var l = t.GetAllMembers ().ToArray ();
+                       Assert.AreEqual (2, l.Length, "#31");
+                       var items = l.First (m => m.Name == "Items");
+                       Assert.IsFalse (items == XamlLanguage.Items, "#31-2");
+                       l.First (m => m.Name == "Type");
+
+                       l = t.GetAllAttachableMembers ().ToArray ();
+                       Assert.AreEqual (0, l.Length, "#32");
+               }
+
+               [Test]
+               public void Array_Items ()
+               {
+                       var m = XamlLanguage.Array.GetMember ("Items");
+                       TestMemberCommon (m, "Items", typeof (IList), typeof (ArrayExtension), false);
+               }
+
+               [Test]
+               public void Array_Type ()
+               {
+                       var m = XamlLanguage.Array.GetMember ("Type");
+                       TestMemberCommon (m, "Type", typeof (Type), typeof (ArrayExtension), true);
+               }
+
+               [Test]
+               public void Null ()
+               {
+                       var t = XamlLanguage.Null;
+                       TestXamlTypeExtension (t, "NullExtension", typeof (NullExtension), typeof (object), true);
+                       Assert.IsNull (t.ContentProperty, "#27");
+
+                       var l = t.GetAllMembers ().ToArray ();
+                       Assert.AreEqual (0, l.Length, "#31");
+
+                       l = t.GetAllAttachableMembers ().ToArray ();
+                       Assert.AreEqual (0, l.Length, "#32");
+               }
+
+               [Test]
+               public void Static ()
+               {
+                       var t = XamlLanguage.Static;
+                       TestXamlTypeExtension (t, "StaticExtension", typeof (StaticExtension), typeof (object), false);
+                       Assert.IsNotNull (t.TypeConverter.ConverterInstance, "#25-2");
+                       Assert.IsNull (t.ContentProperty, "#27");
+
+                       var l = t.GetAllMembers ().ToArray ();
+                       Assert.AreEqual (2, l.Length, "#31");
+                       l.First (m => m.Name == "Member");
+                       l.First (m => m.Name == "MemberType");
+
+                       l = t.GetAllAttachableMembers ().ToArray ();
+                       Assert.AreEqual (0, l.Length, "#32");
+               }
+
+               [Test]
+               public void Static_Member ()
+               {
+                       var m = XamlLanguage.Static.GetMember ("Member");
+                       TestMemberCommon (m, "Member", typeof (string), typeof (StaticExtension), true);
+               }
+
+               [Test]
+               public void Static_MemberType ()
+               {
+                       var m = XamlLanguage.Static.GetMember ("MemberType");
+                       TestMemberCommon (m, "MemberType", typeof (Type), typeof (StaticExtension), true);
+               }
+
+               [Test]
+               public void Type ()
+               {
+                       var t = XamlLanguage.Type;
+                       TestXamlTypeExtension (t, "TypeExtension", typeof (TypeExtension), typeof (Type), false);
+                       Assert.IsNotNull (t.TypeConverter.ConverterInstance, "#25-2");
+                       Assert.IsNull (t.ContentProperty, "#27");
+
+                       var l = t.GetAllMembers ().ToArray ();
+                       Assert.AreEqual (2, l.Length, "#31");
+                       l.First (m => m.Name == "TypeName");
+                       l.First (m => m.Name == "Type");
+
+                       l = t.GetAllAttachableMembers ().ToArray ();
+                       Assert.AreEqual (0, l.Length, "#32");
+               }
+
+               [Test]
+               public void Type_TypeName ()
+               {
+                       var m = XamlLanguage.Type.GetMember ("TypeName");
+                       TestMemberCommon (m, "TypeName", typeof (string), typeof (TypeExtension), true);
+               }
+
+               [Test]
+               public void Type_Type ()
+               {
+                       var m = XamlLanguage.Type.GetMember ("Type");
+                       TestMemberCommon (m, "Type", typeof (Type), typeof (TypeExtension), true);
+               }
+
+               // primitive types
+
+               [Test]
+               public void Byte ()
+               {
+                       var t = XamlLanguage.Byte;
+                       TestXamlTypePrimitive (t, "Byte", typeof (byte), false, false);
+
+                       /* Those properties are pointless regarding practical use. Those "members" does not participate in serialization.
+                       var l = t.GetAllAttachableMembers ().ToArray ();
+                       Assert.AreEqual (1, l.Length, "#32");
+                       */
+               }
+
+               [Test]
+               public void Char ()
+               {
+                       var t = XamlLanguage.Char;
+                       TestXamlTypePrimitive (t, "Char", typeof (char), false, false);
+
+                       /* Those properties are pointless regarding practical use. Those "members" does not participate in serialization.
+                       var l = t.GetAllAttachableMembers ().ToArray ();
+                       Assert.AreEqual (3, l.Length, "#32");
+                       l.First (m => m.Name == "UnicodeCategory");
+                       l.First (m => m.Name == "NumericValue");
+                       l.First (m => m.Name == "HashCodeOfPtr");
+                       */
+               }
+
+               [Test]
+               public void Decimal ()
+               {
+                       var t = XamlLanguage.Decimal;
+                       TestXamlTypePrimitive (t, "Decimal", typeof (decimal), false, false);
+
+                       /* Those properties are pointless regarding practical use. Those "members" does not participate in serialization.
+                       var l = t.GetAllAttachableMembers ().ToArray ();
+                       Assert.AreEqual (2, l.Length, "#32");
+                       l.First (m => m.Name == "Bits");
+                       l.First (m => m.Name == "HashCodeOfPtr");
+                       */
+               }
+
+               [Test]
+               public void Double ()
+               {
+                       var t = XamlLanguage.Double;
+                       TestXamlTypePrimitive (t, "Double", typeof (double), false, false);
+
+                       /* Those properties are pointless regarding practical use. Those "members" does not participate in serialization.
+                       var l = t.GetAllAttachableMembers ().ToArray ();
+                       Assert.AreEqual (1, l.Length, "#32");
+                       l.First (m => m.Name == "HashCodeOfPtr");
+                       */
+               }
+
+               [Test]
+               public void Int16 ()
+               {
+                       var t = XamlLanguage.Int16;
+                       TestXamlTypePrimitive (t, "Int16", typeof (short), false, false);
+
+                       /* Those properties are pointless regarding practical use. Those "members" does not participate in serialization.
+                       var l = t.GetAllAttachableMembers ().ToArray ();
+                       Assert.AreEqual (1, l.Length, "#32");
+                       l.First (m => m.Name == "HashCodeOfPtr");
+                       */
+               }
+
+               [Test]
+               public void Int32 ()
+               {
+                       var t = XamlLanguage.Int32;
+                       TestXamlTypePrimitive (t, "Int32", typeof (int), false, false);
+
+                       /* Those properties are pointless regarding practical use. Those "members" does not participate in serialization.
+                       var l = t.GetAllAttachableMembers ().ToArray ();
+                       Assert.AreEqual (1, l.Length, "#32");
+                       l.First (m => m.Name == "HashCodeOfPtr");
+                       */
+               }
+
+               [Test]
+               public void Int64 ()
+               {
+                       var t = XamlLanguage.Int64;
+                       TestXamlTypePrimitive (t, "Int64", typeof (long), false, false);
+
+                       /* Those properties are pointless regarding practical use. Those "members" does not participate in serialization.
+                       var l = t.GetAllAttachableMembers ().ToArray ();
+                       Assert.AreEqual (1, l.Length, "#32");
+                       l.First (m => m.Name == "HashCodeOfPtr");
+                       */
+               }
+
+               [Test]
+               public void Object ()
+               {
+                       var t = XamlLanguage.Object;
+                       TestXamlTypePrimitive (t, "Object", typeof (object), true, false);
+
+                       /* Those properties are pointless regarding practical use. Those "members" does not participate in serialization.
+                       var l = t.GetAllAttachableMembers ().ToArray ();
+                       Assert.AreEqual (0, l.Length, "#32");
+                       */
+               }
+
+               [Test]
+               public void Single ()
+               {
+                       var t = XamlLanguage.Single;
+                       TestXamlTypePrimitive (t, "Single", typeof (float), false, false);
+
+                       /* Those properties are pointless regarding practical use. Those "members" does not participate in serialization.
+                       var l = t.GetAllAttachableMembers ().ToArray ();
+                       Assert.AreEqual (1, l.Length, "#32");
+                       l.First (m => m.Name == "HashCodeOfPtr");
+                       */
+               }
+
+               [Test]
+               public void String ()
+               {
+                       var t = XamlLanguage.String;
+                       TestXamlTypePrimitive (t, "String", typeof (string), true, true);
+                       Assert.IsNotNull (XamlLanguage.AllTypes.First (tt => tt.Name == "String").ValueSerializer, "#x");
+                       Assert.IsNotNull (XamlLanguage.String.ValueSerializer, "#y");
+
+                       /* Those properties are pointless regarding practical use. Those "members" does not participate in serialization.
+                       var l = t.GetAllAttachableMembers ().ToArray ();
+                       Assert.AreEqual (0, l.Length, "#32");
+                       */
+               }
+
+               [Test]
+               public void TimeSpan ()
+               {
+                       var t = XamlLanguage.TimeSpan;
+                       TestXamlTypePrimitive (t, "TimeSpan", typeof (TimeSpan), false, false);
+
+                       /* Those properties are pointless regarding practical use. Those "members" does not participate in serialization.
+                       var l = t.GetAllAttachableMembers ().ToArray ();
+                       Assert.AreEqual (1, l.Length, "#32");
+                       l.First (m => m.Name == "HashCodeOfPtr");
+                       */
+               }
+
+               [Test]
+               public void Uri ()
+               {
+                       var t = XamlLanguage.Uri;
+                       TestXamlTypePrimitive (t, "Uri", typeof (Uri), true, true);
+
+                       /* Those properties are pointless regarding practical use. Those "members" does not participate in serialization.
+                       var l = t.GetAllAttachableMembers ().ToArray ();
+                       Assert.AreEqual (0, l.Length, "#32");
+                       */
+               }
+
+               // miscellaneous
+
+               [Test]
+               public void Member ()
+               {
+                       var t = XamlLanguage.Member;
+                       TestXamlTypeCommon (t, "Member", typeof (MemberDefinition), true, true, false);
+                       Assert.IsNull (t.TypeConverter, "#25");
+                       // FIXME: test remaining members
+
+                       var l = t.GetAllMembers ().ToArray ();
+                       Assert.AreEqual (1, l.Length, "#31");
+                       l.First (m => m.Name == "Name");
+               }
+
+               [Test]
+               public void Member_Name ()
+               {
+                       var m = XamlLanguage.Member.GetMember ("Name");
+                       TestMemberCommon (m, "Name", typeof (string), typeof (MemberDefinition), true);
+               }
+
+               [Test]
+               public void Property ()
+               {
+                       var t = XamlLanguage.Property;
+                       TestXamlTypeCommon (t, "Property", typeof (PropertyDefinition), true);
+                       Assert.IsNull (t.TypeConverter, "#25");
+                       // FIXME: test remaining members
+
+                       var l = t.GetAllMembers ().ToArray ();
+                       Assert.AreEqual (4, l.Length, "#31");
+                       l.First (m => m.Name == "Name");
+                       l.First (m => m.Name == "Type");
+                       l.First (m => m.Name == "Modifier");
+                       l.First (m => m.Name == "Attributes");
+               }
+
+               [Test]
+               public void Property_Name ()
+               {
+                       var m = XamlLanguage.Property.GetMember ("Name");
+                       TestMemberCommon (m, "Name", typeof (string), typeof (PropertyDefinition), true);
+               }
+
+               [Test]
+               public void Property_Type ()
+               {
+                       var m = XamlLanguage.Property.GetMember ("Type");
+                       TestMemberCommon (m, "Type", typeof (XamlType), typeof (PropertyDefinition), true);
+               }
+
+               [Test]
+               public void Property_Modifier ()
+               {
+                       var m = XamlLanguage.Property.GetMember ("Modifier");
+                       TestMemberCommon (m, "Modifier", typeof (string), typeof (PropertyDefinition), true);
+               }
+
+               [Test]
+               public void Property_Attributes ()
+               {
+                       var m = XamlLanguage.Property.GetMember ("Attributes");
+                       TestMemberCommon (m, "Attributes", typeof (IList<Attribute>), typeof (PropertyDefinition), false);
+               }
+
+               [Test]
+               public void Reference ()
+               {
+                       var t = XamlLanguage.Reference;
+                       TestXamlTypeCommon (t, "Reference", typeof (Reference), true);
+                       Assert.IsNull (t.TypeConverter, "#25");
+                       // FIXME: test remaining members
+
+                       var l = t.GetAllMembers ().ToArray ();
+                       Assert.AreEqual (1, l.Length, "#31");
+                       l.First (m => m.Name == "Name");
+               }
+
+               [Test]
+               public void Reference_Name ()
+               {
+                       var m = XamlLanguage.Reference.GetMember ("Name");
+                       TestMemberCommon (m, "Name", typeof (string), typeof (Reference), true);
+               }
+
+               [Test]
+               public void XData ()
+               {
+                       var t = XamlLanguage.XData;
+                       TestXamlTypeCommon (t, "XData", typeof (XData), true);
+                       Assert.IsNull (t.TypeConverter, "#25");
+                       // FIXME: test remaining members
+
+                       var l = t.GetAllMembers ().ToArray ();
+                       Assert.AreEqual (2, l.Length, "#31");
+                       l.First (m => m.Name == "Text");
+                       l.First (m => m.Name == "XmlReader");
+               }
+
+               [Test]
+               public void XData_Text ()
+               {
+                       var m = XamlLanguage.XData.GetMember ("Text");
+                       TestMemberCommon (m, "Text", typeof (string), typeof (XData), true);
+               }
+
+               [Test]
+               public void XData_XmlReader ()
+               {
+                       var m = XamlLanguage.XData.GetMember ("XmlReader");
+                       // it does not use XmlReader type ...
+                       TestMemberCommon (m, "XmlReader", typeof (object), typeof (XData), true);
+               }
+
+               // common test methods
+
+               void TestXamlTypeCommon (XamlType t, string name, Type underlyingType, bool nullable)
+               {
+                       TestXamlTypeCommon (t, name, underlyingType, nullable, false);
+               }
+
+               void TestXamlTypeCommon (XamlType t, string name, Type underlyingType, bool nullable, bool constructionRequiresArguments)
+               {
+                       TestXamlTypeCommon (t, name, underlyingType, nullable, constructionRequiresArguments, true);
+               }
+
+               void TestXamlTypeCommon (XamlType t, string name, Type underlyingType, bool nullable, bool constructionRequiresArguments, bool isConstructible)
+               {
+                       Assert.IsNotNull (t.Invoker, "#1");
+                       Assert.IsTrue (t.IsNameValid, "#2");
+                       Assert.IsFalse (t.IsUnknown, "#3");
+                       // FIXME: test names (some extension types have wrong name.
+                       //Assert.AreEqual (name, t.Name, "#4");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, t.PreferredXamlNamespace, "#5");
+                       Assert.IsNull (t.TypeArguments, "#6");
+                       Assert.AreEqual (underlyingType, t.UnderlyingType, "#7");
+                       Assert.AreEqual (constructionRequiresArguments, t.ConstructionRequiresArguments, "#8");
+                       Assert.IsFalse (t.IsArray, "#9");
+                       Assert.IsFalse (t.IsCollection, "#10");
+                       // FIXME: test here (very inconsistent with the spec)
+                       Assert.AreEqual (isConstructible, t.IsConstructible, "#11");
+                       Assert.IsFalse (t.IsDictionary, "#12");
+                       Assert.IsFalse (t.IsGeneric, "#13");
+                       Assert.IsFalse (t.IsNameScope, "#15");
+                       Assert.AreEqual (nullable, t.IsNullable, "#16");
+                       Assert.IsTrue (t.IsPublic, "#17");
+                       Assert.IsFalse (t.IsUsableDuringInitialization, "#18");
+                       Assert.IsFalse (t.IsWhitespaceSignificantCollection, "#19");
+                       Assert.IsFalse (t.IsXData, "#20");
+                       Assert.IsFalse (t.TrimSurroundingWhitespace, "#21");
+                       Assert.IsFalse (t.IsAmbient, "#22");
+                       Assert.IsNull (t.AllowedContentTypes, "#23");
+                       Assert.IsNull (t.ContentWrappers, "#24");
+                       // string is a special case.
+                       if (t == XamlLanguage.String)
+                               Assert.IsNotNull (t.ValueSerializer, "#26");
+                       else
+                               Assert.IsNull (t.ValueSerializer, "#26");
+                       //Assert.IsNull (t.DeferringLoader, "#28");
+               }
+
+               void TestXamlTypePrimitive (XamlType t, string name, Type underlyingType, bool nullable, bool constructorRequiresArguments)
+               {
+                       TestXamlTypeCommon (t, name, underlyingType, nullable, constructorRequiresArguments);
+                       Assert.IsFalse (t.IsMarkupExtension, "#14");
+                       Assert.IsNotNull (t.TypeConverter, "#25");
+                       Assert.IsNull (t.ContentProperty, "#27");
+                       Assert.IsNull (t.MarkupExtensionReturnType, "#29");
+
+                       var l = t.GetAllMembers ().ToArray ();
+                       Assert.AreEqual (0, l.Length, "#31");
+               }
+
+               void TestXamlTypeExtension (XamlType t, string name, Type underlyingType, Type extReturnType, bool noTypeConverter)
+               {
+                       TestXamlTypeCommon (t, name, underlyingType, true, false);
+                       Assert.IsTrue (t.IsMarkupExtension, "#14");
+                       if (noTypeConverter)
+                               Assert.IsNull (t.TypeConverter, "#25");
+                       else
+                               Assert.IsNotNull (t.TypeConverter, "#25");
+                       Assert.IsNotNull (t.MarkupExtensionReturnType, "#29");
+                       Assert.AreEqual (extReturnType, t.MarkupExtensionReturnType.UnderlyingType, "#29-2");
+               }
+
+               void TestMemberCommon (XamlMember m, string name, Type type, Type declType, bool hasSetter)
+               {
+                       Assert.IsNotNull (m, "#1");
+                       Assert.IsNotNull (m.DeclaringType, "#2");
+                       Assert.AreEqual (declType, m.DeclaringType.UnderlyingType, "#2-2");
+                       Assert.IsNotNull (m.Invoker, "#3");
+                       Assert.IsNotNull (m.Invoker.UnderlyingGetter, "#3-2");
+                       if (hasSetter)
+                               Assert.IsNotNull (m.Invoker.UnderlyingSetter, "#3-3");
+                       else
+                               Assert.IsNull (m.Invoker.UnderlyingSetter, "#3-3");
+                       Assert.IsFalse (m.IsUnknown, "#4");
+                       Assert.IsTrue (m.IsReadPublic, "#5");
+                       Assert.AreEqual (hasSetter, m.IsWritePublic, "#6");
+                       Assert.AreEqual (name, m.Name, "#7");
+                       Assert.IsTrue (m.IsNameValid, "#8");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, m.PreferredXamlNamespace, "#9");
+                       // use declType here (mostly identical to targetType)
+                       Assert.AreEqual (new XamlType (declType, m.TargetType.SchemaContext), m.TargetType, "#10");
+                       Assert.IsNotNull (m.Type, "#11");
+                       Assert.AreEqual (type, m.Type.UnderlyingType, "#11-2");
+                       // Property.Type is a special case here.
+                       if (name == "Type" && m.DeclaringType != XamlLanguage.Property)
+                               Assert.AreEqual (m.Type.TypeConverter, m.TypeConverter, "#12");
+                       // String type is a special case here.
+                       if (type == typeof (string))
+                               Assert.AreEqual (m.Type.ValueSerializer, m.ValueSerializer, "#13a");
+                       else
+                               Assert.IsNull (m.ValueSerializer, "#13b");
+                       Assert.IsNull (m.DeferringLoader, "#14");
+                       Assert.IsNotNull (m.UnderlyingMember, "#15");
+                       Assert.AreEqual (!hasSetter, m.IsReadOnly, "#16");
+                       Assert.IsFalse (m.IsWriteOnly, "#17");
+                       Assert.IsFalse (m.IsAttachable, "#18");
+                       Assert.IsFalse (m.IsEvent, "#19");
+                       Assert.IsFalse (m.IsDirective, "#20");
+                       Assert.IsNotNull (m.DependsOn, "#21");
+                       Assert.AreEqual (0, m.DependsOn.Count, "#21-2");
+                       Assert.IsFalse (m.IsAmbient, "#22");
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlMemberTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlMemberTest.cs
new file mode 100755 (executable)
index 0000000..71cf4c0
--- /dev/null
@@ -0,0 +1,423 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Reflection;
+using System.Text;
+using System.Xaml;
+using System.Xaml.Schema;
+using NUnit.Framework;
+
+namespace MonoTests.System.Xaml
+{
+       [TestFixture]
+       // FIXME: uncomment TypeConverter tests
+       public class XamlMemberTest
+       {
+               XamlSchemaContext sctx = new XamlSchemaContext (new XamlSchemaContextSettings ());
+               EventInfo ass_load = typeof (AppDomain).GetEvent ("AssemblyLoad");
+               PropertyInfo str_len = typeof (string).GetProperty ("Length");
+               PropertyInfo sb_len = typeof (StringBuilder).GetProperty ("Length");
+               MethodInfo dummy_add = typeof (XamlMemberTest).GetMethod ("DummyAddMethod");
+               MethodInfo dummy_get = typeof (XamlMemberTest).GetMethod ("DummyGetMethod");
+               MethodInfo dummy_set = typeof (XamlMemberTest).GetMethod ("DummySetMethod");
+               MethodInfo dummy_set2 = typeof (Dummy).GetMethod ("DummySetMethod");
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorEventInfoNullEventInfo ()
+               {
+                       new XamlMember ((EventInfo) null, sctx);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorEventInfoNullSchemaContext ()
+               {
+                       new XamlMember (ass_load, null);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorPropertyInfoNullPropertyInfo ()
+               {
+                       new XamlMember ((PropertyInfo) null, sctx);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorPropertyInfoNullSchemaContext ()
+               {
+                       new XamlMember (str_len, null);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorAddMethodNullName ()
+               {
+                       new XamlMember (null, GetType ().GetMethod ("DummyAddMEthod"), sctx);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorAddMethodNullMethod ()
+               {
+                       new XamlMember ("DummyAddMethod", null, sctx);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorAddMethodNullSchemaContext ()
+               {
+                       new XamlMember ("DummyAddMethod", dummy_add, null);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorGetSetMethodNullName ()
+               {
+                       new XamlMember (null, dummy_get, dummy_set, sctx);
+               }
+
+               [Test]
+               public void ConstructorGetSetMethodNullGetMethod ()
+               {
+                       new XamlMember ("DummyProp", null, dummy_set, sctx);
+               }
+
+               [Test]
+               public void ConstructorGetSetMethodNullSetMethod ()
+               {
+                       new XamlMember ("DummyProp", dummy_get, null, sctx);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorGetSetMethodNullGetSetMethod ()
+               {
+                       new XamlMember ("DummyProp", null, null, sctx);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorGetSetMethodNullSchemaContext ()
+               {
+                       new XamlMember ("DummyProp", dummy_get, dummy_set, null);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorNameTypeNullName ()
+               {
+                       new XamlMember (null, new XamlType (typeof (string), sctx), false);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorNameTypeNullType ()
+               {
+                       new XamlMember ("Length", null, false);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentException))]
+               public void AddMethodInvalid ()
+               {
+                       // It is not of expected kind of member here:
+                       // "Attached property setter and attached event adder methods must have two parameters."
+                       new XamlMember ("AssemblyLoad", ass_load.GetAddMethod (), sctx);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentException))]
+               public void GetMethodInvlaid ()
+               {
+                       // It is not of expected kind of member here:
+                       // "Attached property getter methods must have one parameter and a non-void return type."
+                       new XamlMember ("Length", sb_len.GetGetMethod (), null, sctx);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentException))]
+               public void SetMethodInvalid ()
+               {
+                       // It is not of expected kind of member here:
+                       // "Attached property setter and attached event adder methods must have two parameters."
+                       new XamlMember ("Length", null, sb_len.GetSetMethod (), sctx);
+               }
+
+               [Test]
+               public void MethodsFromDifferentType ()
+               {
+                       // allowed...
+                       var i = new XamlMember ("Length", dummy_get, dummy_set2, sctx);
+                       Assert.IsNotNull (i.DeclaringType, "#1");
+                       // hmm...
+                       Assert.AreEqual (GetType (), i.DeclaringType.UnderlyingType, "#2");
+               }
+
+               // default values.
+
+               [Test]
+               public void EventInfoDefaultValues ()
+               {
+                       var m = new XamlMember (typeof (AppDomain).GetEvent ("AssemblyLoad"), sctx);
+
+                       Assert.IsNotNull (m.DeclaringType, "#2");
+                       Assert.AreEqual (typeof (AppDomain), m.DeclaringType.UnderlyingType, "#2-2");
+                       Assert.IsNotNull (m.Invoker, "#3");
+                       Assert.IsNull (m.Invoker.UnderlyingGetter, "#3-2");
+                       Assert.AreEqual (ass_load.GetAddMethod (), m.Invoker.UnderlyingSetter, "#3-3");
+                       Assert.IsFalse (m.IsUnknown, "#4");
+                       Assert.IsFalse (m.IsReadPublic, "#5");
+                       Assert.IsTrue (m.IsWritePublic, "#6");
+                       Assert.AreEqual ("AssemblyLoad", m.Name, "#7");
+                       Assert.IsTrue (m.IsNameValid, "#8");
+                       Assert.AreEqual ("clr-namespace:System;assembly=mscorlib", m.PreferredXamlNamespace, "#9");
+                       Assert.AreEqual (new XamlType (typeof (AppDomain), sctx), m.TargetType, "#10");
+                       Assert.IsNotNull (m.Type, "#11");
+                       Assert.AreEqual (typeof (AssemblyLoadEventHandler), m.Type.UnderlyingType, "#11-2");
+//                     Assert.IsNotNull (m.TypeConverter, "#12"); // EventConverter
+                       Assert.IsNull (m.ValueSerializer, "#13");
+                       Assert.IsNull (m.DeferringLoader, "#14");
+                       Assert.AreEqual (ass_load, m.UnderlyingMember, "#15");
+                       Assert.IsFalse (m.IsReadOnly, "#16");
+                       Assert.IsTrue (m.IsWriteOnly, "#17");
+                       Assert.IsFalse (m.IsAttachable, "#18");
+                       Assert.IsTrue (m.IsEvent, "#19");
+                       Assert.IsFalse (m.IsDirective, "#20");
+                       Assert.IsNotNull (m.DependsOn, "#21");
+                       Assert.AreEqual (0, m.DependsOn.Count, "#21-2");
+                       Assert.IsFalse (m.IsAmbient, "#22");
+               }
+
+               [Test]
+               public void PropertyInfoDefaultValues ()
+               {
+                       var m = new XamlMember (typeof (string).GetProperty ("Length"), sctx);
+
+                       Assert.IsNotNull (m.DeclaringType, "#2");
+                       Assert.AreEqual (typeof (string), m.DeclaringType.UnderlyingType, "#2-2");
+                       Assert.IsNotNull (m.Invoker, "#3");
+                       Assert.AreEqual (str_len.GetGetMethod (), m.Invoker.UnderlyingGetter, "#3-2");
+                       Assert.AreEqual (str_len.GetSetMethod (), m.Invoker.UnderlyingSetter, "#3-3");
+                       Assert.IsFalse (m.IsUnknown, "#4");
+                       Assert.IsTrue (m.IsReadPublic, "#5");
+                       Assert.IsFalse (m.IsWritePublic, "#6");
+                       Assert.AreEqual ("Length", m.Name, "#7");
+                       Assert.IsTrue (m.IsNameValid, "#8");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, m.PreferredXamlNamespace, "#9");
+                       Assert.AreEqual (new XamlType (typeof (string), sctx), m.TargetType, "#10");
+                       Assert.IsNotNull (m.Type, "#11");
+                       Assert.AreEqual (typeof (int), m.Type.UnderlyingType, "#11-2");
+//                     Assert.IsNotNull (m.TypeConverter, "#12");
+                       Assert.IsNull (m.ValueSerializer, "#13");
+                       Assert.IsNull (m.DeferringLoader, "#14");
+                       Assert.AreEqual (str_len, m.UnderlyingMember, "#15");
+                       Assert.IsTrue (m.IsReadOnly, "#16");
+                       Assert.IsFalse (m.IsWriteOnly, "#17");
+                       Assert.IsFalse (m.IsAttachable, "#18");
+                       Assert.IsFalse (m.IsEvent, "#19");
+                       Assert.IsFalse (m.IsDirective, "#20");
+                       Assert.IsNotNull (m.DependsOn, "#21");
+                       Assert.AreEqual (0, m.DependsOn.Count, "#21-2");
+                       Assert.IsFalse (m.IsAmbient, "#22");
+               }
+
+               public void DummyAddMethod (object o, AssemblyLoadEventHandler h)
+               {
+               }
+
+               public int DummyGetMethod (object o)
+               {
+                       return 5;
+               }
+
+               public void DummySetMethod (object o, int v)
+               {
+               }
+
+               public class Dummy
+               {
+                       public int DummyGetMethod (object o)
+                       {
+                               return 5;
+                       }
+
+                       public void DummySetMethod (object o, int v)
+                       {
+                       }
+               }
+
+               [Test]
+               public void AddMethodDefaultValues ()
+               {
+                       var m = new XamlMember ("DummyAddMethod", dummy_add, sctx);
+
+                       Assert.IsNotNull (m.DeclaringType, "#2");
+                       Assert.AreEqual (GetType (), m.DeclaringType.UnderlyingType, "#2-2");
+                       Assert.IsNotNull (m.Invoker, "#3");
+                       Assert.IsNull (m.Invoker.UnderlyingGetter, "#3-2");
+                       Assert.AreEqual (dummy_add, m.Invoker.UnderlyingSetter, "#3-3");
+                       Assert.IsFalse (m.IsUnknown, "#4");
+                       Assert.IsFalse (m.IsReadPublic, "#5");
+                       Assert.IsTrue (m.IsWritePublic, "#6");
+                       Assert.AreEqual ("DummyAddMethod", m.Name, "#7");
+                       Assert.IsTrue (m.IsNameValid, "#8");
+                       var ns = "clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name;
+                       Assert.AreEqual (ns, m.PreferredXamlNamespace, "#9");
+                       // since it is unknown.
+                       Assert.AreEqual (new XamlType (typeof (object), sctx), m.TargetType, "#10");
+                       Assert.IsNotNull (m.Type, "#11");
+                       Assert.AreEqual (typeof (AssemblyLoadEventHandler), m.Type.UnderlyingType, "#11-2");
+//                     Assert.IsNotNull (m.TypeConverter, "#12");
+                       Assert.IsNull (m.ValueSerializer, "#13");
+                       Assert.IsNull (m.DeferringLoader, "#14");
+                       Assert.AreEqual (dummy_add, m.UnderlyingMember, "#15");
+                       Assert.IsFalse (m.IsReadOnly, "#16");
+                       Assert.IsTrue (m.IsWriteOnly, "#17");
+                       Assert.IsTrue (m.IsAttachable, "#18");
+                       Assert.IsTrue (m.IsEvent, "#19");
+                       Assert.IsFalse (m.IsDirective, "#20");
+                       Assert.IsNotNull (m.DependsOn, "#21");
+                       Assert.AreEqual (0, m.DependsOn.Count, "#21-2");
+                       Assert.IsFalse (m.IsAmbient, "#22");
+               }
+
+               [Test]
+               public void GetSetMethodDefaultValues ()
+               {
+                       var m = new XamlMember ("DummyProp", dummy_get, dummy_set, sctx);
+
+                       Assert.IsNotNull (m.DeclaringType, "#2");
+                       Assert.AreEqual (GetType (), m.DeclaringType.UnderlyingType, "#2-2");
+                       Assert.IsNotNull (m.Invoker, "#3");
+                       Assert.AreEqual (dummy_get, m.Invoker.UnderlyingGetter, "#3-2");
+                       Assert.AreEqual (dummy_set, m.Invoker.UnderlyingSetter, "#3-3");
+                       Assert.IsFalse (m.IsUnknown, "#4");
+                       Assert.IsTrue (m.IsReadPublic, "#5");
+                       Assert.IsTrue (m.IsWritePublic, "#6");
+                       Assert.AreEqual ("DummyProp", m.Name, "#7");
+                       Assert.IsTrue (m.IsNameValid, "#8");
+                       var ns = "clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name;
+                       Assert.AreEqual (ns, m.PreferredXamlNamespace, "#9");
+                       // since it is unknown.
+                       Assert.AreEqual (new XamlType (typeof (object), sctx), m.TargetType, "#10");
+                       Assert.IsNotNull (m.Type, "#11");
+                       Assert.AreEqual (typeof (int), m.Type.UnderlyingType, "#11-2");
+//                     Assert.IsNotNull (m.TypeConverter, "#12");
+                       Assert.IsNull (m.ValueSerializer, "#13");
+                       Assert.IsNull (m.DeferringLoader, "#14");
+                       Assert.AreEqual (dummy_get, m.UnderlyingMember, "#15");
+                       Assert.IsFalse (m.IsReadOnly, "#16");
+                       Assert.IsFalse (m.IsWriteOnly, "#17");
+                       Assert.IsTrue (m.IsAttachable, "#18");
+                       Assert.IsFalse (m.IsEvent, "#19");
+                       Assert.IsFalse (m.IsDirective, "#20");
+                       Assert.IsNotNull (m.DependsOn, "#21");
+                       Assert.AreEqual (0, m.DependsOn.Count, "#21-2");
+                       Assert.IsFalse (m.IsAmbient, "#22");
+               }
+
+               [Test]
+               public void NameTypeDefaultValues ()
+               {
+                       var m = new XamlMember ("Length", new XamlType (typeof (string), sctx), false);
+
+                       Assert.IsNotNull (m.DeclaringType, "#2");
+                       Assert.AreEqual (typeof (string), m.DeclaringType.UnderlyingType, "#2-2");
+                       Assert.IsNotNull (m.Invoker, "#3");
+                       Assert.IsNull (m.Invoker.UnderlyingGetter, "#3-2");
+                       Assert.IsNull (m.Invoker.UnderlyingSetter, "#3-3");
+                       Assert.IsTrue (m.IsUnknown, "#4");
+                       Assert.IsTrue (m.IsReadPublic, "#5");
+                       Assert.IsTrue (m.IsWritePublic, "#6");
+                       Assert.AreEqual ("Length", m.Name, "#7");
+                       Assert.IsTrue (m.IsNameValid, "#8");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, m.PreferredXamlNamespace, "#9");
+                       Assert.AreEqual (new XamlType (typeof (string), sctx), m.TargetType, "#10");
+                       Assert.IsNotNull (m.Type, "#11");
+                       Assert.AreEqual (typeof (object), m.Type.UnderlyingType, "#11-2");
+//                     Assert.IsNull (m.TypeConverter, "#12");
+                       Assert.IsNull (m.ValueSerializer, "#13");
+                       Assert.IsNull (m.DeferringLoader, "#14");
+                       Assert.IsNull (m.UnderlyingMember, "#15");
+                       Assert.IsFalse (m.IsReadOnly, "#16");
+                       Assert.IsFalse (m.IsWriteOnly, "#17");
+                       Assert.IsFalse (m.IsAttachable, "#18");
+                       Assert.IsFalse (m.IsEvent, "#19");
+                       Assert.IsFalse (m.IsDirective, "#20");
+                       Assert.IsNotNull (m.DependsOn, "#21");
+                       Assert.AreEqual (0, m.DependsOn.Count, "#21-2");
+                       Assert.IsFalse (m.IsAmbient, "#22");
+               }
+
+               [Test]
+               public void UnderlyingMember ()
+               {
+                       Assert.IsTrue (new XamlMember (ass_load, sctx).UnderlyingMember is EventInfo, "#1");
+                       Assert.IsTrue (new XamlMember (str_len, sctx).UnderlyingMember is PropertyInfo, "#2");
+                       Assert.AreEqual (dummy_get, new XamlMember ("DummyProp", dummy_get, dummy_set, sctx).UnderlyingMember, "#3");
+                       Assert.AreEqual (dummy_add, new XamlMember ("DummyAddMethod", dummy_add, sctx).UnderlyingMember, "#4");
+                       Assert.IsNull (new XamlMember ("Length", new XamlType (typeof (string), sctx), false).UnderlyingMember, "#5");
+               }
+
+               [Test]
+               public void EqualsTest ()
+               {
+                       XamlMember m;
+                       var xt = XamlLanguage.Type;
+                       m = new XamlMember ("Type", xt, false);
+                       var type_type = xt.GetMember ("Type");
+                       Assert.AreNotEqual (m, xt.GetMember ("Type"), "#1"); // whoa!
+                       Assert.AreNotEqual (type_type, m, "#2"); // whoa!
+                       Assert.AreEqual (type_type, xt.GetMember ("Type"), "#3");
+                       Assert.AreEqual (type_type.ToString (), m.ToString (), "#4");
+
+                       Assert.AreEqual (xt.GetAllMembers ().FirstOrDefault (mm => mm.Name == "Type"), xt.GetAllMembers ().FirstOrDefault (mm => mm.Name == "Type"), "#5");
+                       Assert.AreEqual (xt.GetAllMembers ().FirstOrDefault (mm => mm.Name == "Type"), xt.GetMember ("Type"), "#6");
+               }
+
+               [Test]
+               public void ToStringTest ()
+               {
+                       Assert.AreEqual ("{http://schemas.microsoft.com/winfx/2006/xaml}_Initialization", XamlLanguage.Initialization.ToString (), "#1");
+
+                       // Wow. Uncomment this, and it will show .NET returns the XamlMember.ToString() results *inconsistently*.
+                       //Assert.AreEqual ("System.Windows.Markup.XData", XamlLanguage.XData.ToString (), "#2pre");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, XamlLanguage.XData.PreferredXamlNamespace, "#2pre2");
+
+                       Assert.AreEqual ("{http://schemas.microsoft.com/winfx/2006/xaml}XData.Text", XamlLanguage.XData.GetMember ("Text").ToString (), "#2");
+
+                       var pi = typeof (string).GetProperty ("Length");
+                       Assert.AreEqual ("{http://schemas.microsoft.com/winfx/2006/xaml}String.Length", new XamlMember (pi, sctx).ToString (), "#3");
+
+                       Assert.AreEqual ("System.Xaml.XamlSchemaContext.FooBar", new XamlMember ("FooBar", typeof (XamlSchemaContext).GetMethod ("GetPreferredPrefix"), null, sctx).ToString (), "#4");
+
+                       Assert.AreEqual ("{urn:foo}bar", new XamlDirective ("urn:foo", "bar").ToString (), "#5");
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlObjectEventArgsTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlObjectEventArgsTest.cs
new file mode 100644 (file)
index 0000000..c912166
--- /dev/null
@@ -0,0 +1,43 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Xaml;
+using NUnit.Framework;
+
+namespace MonoTests.System.Xaml
+{
+       [TestFixture]
+       public class XamlObjectEventArgsTest
+       {
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorNullArg ()
+               {
+                       // allowed.
+                       new XamlObjectEventArgs (null);
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlObjectReaderSettingsTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlObjectReaderSettingsTest.cs
new file mode 100644 (file)
index 0000000..7b933b1
--- /dev/null
@@ -0,0 +1,43 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Xaml;
+using System.Xaml.Schema;
+using NUnit.Framework;
+
+namespace MonoTests.System.Xaml
+{
+       [TestFixture]
+       public class XamlObjectReaderSettingsTest
+       {
+               [Test]
+               public void DefaultValues ()
+               {
+                       var s = new XamlObjectReaderSettings ();
+                       Assert.IsFalse (s.RequireExplicitContentVisibility, "#1");
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlObjectReaderTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlObjectReaderTest.cs
new file mode 100644 (file)
index 0000000..6da433a
--- /dev/null
@@ -0,0 +1,830 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml;
+using System.Xaml.Schema;
+using System.Xml;
+using NUnit.Framework;
+
+using Category = NUnit.Framework.CategoryAttribute;
+
+// Some test result remarks:
+// - TypeExtension: [ConstructorArgument] -> PositionalParameters
+// - StaticExtension: almost identical to TypeExtension
+// - Reference: [ConstructorArgument], [ContentProperty] -> only ordinal member.
+// - ArrayExtension: [ConstrutorArgument], [ContentProperty] -> no PositionalParameters, Items.
+// - NullExtension: no member.
+// - MyExtension: [ConstructorArgument] -> only ordinal members...hmm?
+
+namespace MonoTests.System.Xaml
+{
+       [TestFixture]
+       public class XamlObjectReaderTest
+       {
+               [Test]
+               public void ConstructorNullObject ()
+               {
+                       // allowed.
+                       new XamlObjectReader (null);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorNullSchemaContext ()
+               {
+                       new XamlObjectReader ("foo", (XamlSchemaContext) null);
+               }
+
+               [Test]
+               public void ConstructorNullSettings ()
+               {
+                       new XamlObjectReader ("foo", (XamlObjectReaderSettings) null);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorNullSchemaContext2 ()
+               {
+                       new XamlObjectReader ("foo", null, new XamlObjectReaderSettings ());
+               }
+
+               [Test]
+               public void ConstructorNullSettings2 ()
+               {
+                       new XamlObjectReader ("foo", new XamlSchemaContext (null, null), null);
+               }
+
+               [Test]
+               public void ReadNull ()
+               {
+                       var r = new XamlObjectReader (null);
+                       Assert.IsTrue (r.Read (), "#1");
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#1-2");
+                       Assert.IsTrue (r.Read (), "#2");
+                       Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#2-2");
+                       Assert.AreEqual (XamlLanguage.Null, r.Type, "#2-3");
+                       Assert.IsTrue (r.Read (), "#3");
+                       Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#3-2");
+                       Assert.IsFalse (r.Read (), "#4");
+                       Assert.AreEqual (XamlNodeType.None, r.NodeType, "#4-2");
+               }
+
+               [Test]
+               public void Read1 ()
+               {
+                       var r = new XamlObjectReader ("Foo");
+                       Assert.AreEqual (XamlNodeType.None, r.NodeType, "#1");
+                       Assert.IsNull (r.Member, "#2");
+                       Assert.IsNull (r.Namespace, "#3");
+                       Assert.IsNull (r.Member, "#4");
+                       Assert.IsNull (r.Type, "#5");
+                       Assert.IsNull (r.Value, "#6");
+
+                       Assert.IsTrue (r.Read (), "#11");
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
+                       Assert.IsNotNull (r.Namespace, "#13");
+                       Assert.AreEqual ("x", r.Namespace.Prefix, "#13-2");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#13-3");
+
+                       Assert.IsTrue (r.Read (), "#21");
+                       Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
+                       Assert.IsNotNull (r.Type, "#23");
+                       Assert.AreEqual (new XamlType (typeof (string), r.SchemaContext), r.Type, "#23-2");
+                       Assert.IsNull (r.Namespace, "#25");
+
+                       Assert.IsTrue (r.Read (), "#31");
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#32");
+                       Assert.IsNotNull (r.Member, "#33");
+                       Assert.AreEqual (XamlLanguage.Initialization, r.Member, "#33-2");
+                       Assert.IsNull (r.Type, "#34");
+
+                       Assert.IsTrue (r.Read (), "#41");
+                       Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#42");
+                       Assert.AreEqual ("Foo", r.Value, "#43");
+                       Assert.IsNull (r.Member, "#44");
+
+                       Assert.IsTrue (r.Read (), "#51");
+                       Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#52");
+                       Assert.IsNull (r.Type, "#53");
+                       Assert.IsNull (r.Member, "#54");
+
+                       Assert.IsTrue (r.Read (), "#61");
+                       Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#62");
+                       Assert.IsNull (r.Type, "#63");
+
+                       Assert.IsFalse (r.Read (), "#71");
+                       Assert.IsTrue (r.IsEof, "#72");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectReaderException))]
+               public void ReadNonConstructible ()
+               {
+                       // XamlType has no default constructor.
+                       var r = new XamlObjectReader (XamlLanguage.String);
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectReaderException))]
+               public void NonPublicType ()
+               {
+                       new XamlObjectReader (new TestClass1 ());
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectReaderException))]
+               public void NestedType ()
+               {
+                       new XamlObjectReader (new TestClass2 ());
+               }
+               
+               public class TestClass2
+               {
+               }
+
+               [Test]
+               public void ConstructibleType ()
+               {
+                       new XamlObjectReader (new TestClass3 ());
+               }
+
+               [Test]
+               public void Skip ()
+               {
+                       var r = new XamlObjectReader ("Foo");
+                       r.Skip ();
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#1");
+                       r.Skip ();
+                       Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#2");
+                       r.Skip ();
+                       Assert.IsTrue (r.IsEof, "#3");
+               }
+
+               [Test]
+               public void Skip2 ()
+               {
+                       var r = new XamlObjectReader ("Foo");
+                       r.Read (); // NamespaceDeclaration
+                       r.Read (); // Type
+                       r.Read (); // Member (Initialization)
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#1");
+                       r.Skip ();
+                       Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#2");
+                       r.Skip ();
+                       Assert.IsTrue (r.IsEof, "#3");
+               }
+
+               [Test]
+               [Category ("NotWorking")]
+               public void Read2 ()
+               {
+                       var doc = new XmlDocument ();
+                       doc.LoadXml ("<root xmlns='urn:foo'><elem attr='val' /></root>");
+                       var r = new XamlObjectReader (doc);
+
+                       for (int i = 0; i < 3; i++) {
+                               r.Read ();
+                               Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#1-" + i);
+                       }
+                       r.Read ();
+
+                       Assert.AreEqual (new XamlType (typeof (XmlDocument), r.SchemaContext), r.Type, "#2");
+                       r.Read ();
+                       var l = new List<XamlMember> ();
+                       for (int i = 0; i < 5; i++) {
+                               Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#3-" + i);
+                               l.Add (r.Member);
+                               r.Skip ();
+                       }
+                       l.First (m => m.Name == "Value");
+                       l.First (m => m.Name == "InnerXml");
+                       l.First (m => m.Name == "Prefix");
+                       l.First (m => m.Name == "PreserveWhitespace");
+                       l.First (m => m.Name == "Schemas");
+                       Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#4");
+                       Assert.IsFalse (r.Read (), "#5");
+               }
+
+               [Test]
+               public void Read_NonPrimitive ()
+               {
+                       var r = new XamlObjectReader (new TestClass3 ());
+                       Assert.AreEqual (XamlNodeType.None, r.NodeType, "#1");
+                       Assert.IsTrue (r.Read (), "#6");
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#7");
+                       Assert.AreEqual (String.Empty, r.Namespace.Prefix, "#7-2");
+                       Assert.AreEqual ("clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name, r.Namespace.Namespace, "#7-3");
+
+                       Assert.IsTrue (r.Read (), "#11");
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
+                       Assert.AreEqual ("x", r.Namespace.Prefix, "#12-2");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#12-3");
+
+                       Assert.IsTrue (r.Read (), "#16");
+                       Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#17");
+                       var xt = new XamlType (typeof (TestClass3), r.SchemaContext);
+                       Assert.AreEqual (xt, r.Type, "#17-2");
+                       Assert.IsTrue (r.Instance is TestClass3, "#17-3");
+
+                       Assert.IsTrue (r.Read (), "#21");
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#22");
+                       Assert.AreEqual (xt.GetMember ("Nested"), r.Member, "#22-2");
+
+                       Assert.IsTrue (r.Read (), "#26");
+                       Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#27");
+                       Assert.AreEqual (XamlLanguage.Null, r.Type, "#27-2");
+                       Assert.IsNull (r.Instance, "#27-3");
+
+                       Assert.IsTrue (r.Read (), "#31");
+                       Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#32");
+
+                       Assert.IsTrue (r.Read (), "#36");
+                       Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#37");
+
+                       Assert.IsTrue (r.Read (), "#41");
+                       Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#42");
+
+                       Assert.IsFalse (r.Read (), "#46");
+                       Assert.IsTrue (r.IsEof, "#47");
+               }
+
+               [Test]
+               public void Read_Type ()
+               {
+                       var r = new XamlObjectReader (typeof (int));
+                       Read_TypeOrTypeExtension (r);
+               }
+               
+               [Test]
+               public void Read_TypeExtension ()
+               {
+                       var r = new XamlObjectReader (new TypeExtension (typeof (int)));
+                       Read_TypeOrTypeExtension (r);
+               }
+
+               void Read_TypeOrTypeExtension (XamlObjectReader r)
+               {
+                       Assert.IsTrue (r.Read (), "#11");
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
+                       Assert.IsNotNull (r.Namespace, "#13");
+                       Assert.AreEqual ("x", r.Namespace.Prefix, "#13-2");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#13-3");
+                       Assert.IsNull (r.Instance, "#14");
+
+                       Assert.IsTrue (r.Read (), "#21");
+                       Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
+                       Assert.IsNotNull (r.Type, "#23");
+                       Assert.AreEqual (new XamlType (typeof (TypeExtension), r.SchemaContext), r.Type, "#23-2");
+                       Assert.IsNull (r.Namespace, "#25");
+                       Assert.IsTrue (r.Instance is TypeExtension, "#26");
+
+                       Assert.IsTrue (r.Read (), "#31");
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#32");
+                       Assert.IsNotNull (r.Member, "#33");
+                       Assert.AreEqual (XamlLanguage.PositionalParameters, r.Member, "#33-2");
+                       Assert.IsNull (r.Type, "#34");
+                       Assert.IsNull (r.Instance, "#35");
+
+                       Assert.IsTrue (r.Read (), "#41");
+                       Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#42");
+                       Assert.IsNotNull (r.Value, "#43");
+                       Assert.AreEqual ("x:Int32", r.Value, "#43-2");
+                       Assert.IsNull (r.Member, "#44");
+                       Assert.IsNull (r.Instance, "#45");
+
+                       Assert.IsTrue (r.Read (), "#51");
+                       Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#52");
+                       Assert.IsNull (r.Type, "#53");
+                       Assert.IsNull (r.Member, "#54");
+                       Assert.IsNull (r.Instance, "#55");
+
+                       Assert.IsTrue (r.Read (), "#61");
+                       Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#62");
+                       Assert.IsNull (r.Type, "#63");
+
+                       Assert.IsFalse (r.Read (), "#71");
+                       Assert.IsTrue (r.IsEof, "#72");
+               }
+
+               [Test]
+               public void Read_Type2 ()
+               {
+                       var r = new XamlObjectReader (typeof (TestClass1));
+                       Read_TypeOrTypeExtension2 (r);
+               }
+               
+               [Test]
+               public void Read_TypeExtension2 ()
+               {
+                       var r = new XamlObjectReader (new TypeExtension (typeof (TestClass1)));
+                       Read_TypeOrTypeExtension2 (r);
+               }
+
+               void Read_TypeOrTypeExtension2 (XamlObjectReader r)
+               {
+                       Assert.IsTrue (r.Read (), "#11");
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
+
+                       var defns = "clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name;
+
+                       Assert.AreEqual (String.Empty, r.Namespace.Prefix, "#13-2");
+                       Assert.AreEqual (defns, r.Namespace.Namespace, "#13-3:" + r.Namespace.Prefix);
+
+                       Assert.IsTrue (r.Read (), "#16");
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#17");
+                       Assert.IsNotNull (r.Namespace, "#18");
+                       Assert.AreEqual ("x", r.Namespace.Prefix, "#18-2");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#18-3:" + r.Namespace.Prefix);
+
+                       Assert.IsTrue (r.Read (), "#21");
+                       Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
+                       Assert.AreEqual (new XamlType (typeof (TypeExtension), r.SchemaContext), r.Type, "#23-2");
+                       Assert.IsTrue (r.Instance is TypeExtension, "#26");
+
+                       Assert.IsTrue (r.Read (), "#31");
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#32");
+                       Assert.AreEqual (XamlLanguage.PositionalParameters, r.Member, "#33-2");
+
+                       Assert.IsTrue (r.Read (), "#41");
+                       Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#42");
+                       Assert.AreEqual ("TestClass1", r.Value, "#43-2");
+
+                       Assert.IsTrue (r.Read (), "#51");
+                       Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#52");
+
+                       Assert.IsTrue (r.Read (), "#61");
+                       Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#62");
+
+                       Assert.IsFalse (r.Read (), "#71");
+                       Assert.IsTrue (r.IsEof, "#72");
+               }
+
+               [Test]
+               public void Read_Reference ()
+               {
+                       var r = new XamlObjectReader (new Reference ("TestName"));
+                       Assert.IsTrue (r.Read (), "#11");
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
+                       Assert.AreEqual ("x", r.Namespace.Prefix, "#13-2");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#13-3");
+
+                       Assert.IsTrue (r.Read (), "#21");
+                       Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
+                       var xt = new XamlType (typeof (Reference), r.SchemaContext);
+                       Assert.AreEqual (xt, r.Type, "#23-2");
+                       Assert.IsTrue (r.Instance is Reference, "#26");
+
+                       Assert.IsTrue (r.Read (), "#31");
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#32");
+                       // unlike TypeExtension there is no PositionalParameters.
+                       Assert.AreEqual (xt.GetMember ("Name"), r.Member, "#33-2");
+
+                       // It is a ContentProperty (besides [ConstructorArgument])
+                       Assert.IsTrue (r.Read (), "#41");
+                       Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#42");
+                       Assert.AreEqual ("TestName", r.Value, "#43-2");
+
+                       Assert.IsTrue (r.Read (), "#51");
+                       Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#52");
+
+                       Assert.IsTrue (r.Read (), "#61");
+                       Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#62");
+
+                       Assert.IsFalse (r.Read (), "#71");
+                       Assert.IsTrue (r.IsEof, "#72");
+               }
+
+
+               [Test]
+               public void Read_Null ()
+               {
+                       var r = new XamlObjectReader (null);
+                       Read_NullOrNullExtension (r, null);
+               }
+
+               [Test]
+               public void Read_NullExtension ()
+               {
+                       var o = new NullExtension ();
+                       var r = new XamlObjectReader (o);
+                       Read_NullOrNullExtension (r, o);
+               }
+               
+               void Read_NullOrNullExtension (XamlObjectReader r, object instance)
+               {
+                       Assert.IsTrue (r.Read (), "#11");
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
+                       Assert.IsNotNull (r.Namespace, "#13");
+                       Assert.AreEqual ("x", r.Namespace.Prefix, "#13-2");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#13-3");
+                       Assert.IsNull (r.Instance, "#14");
+
+                       Assert.IsTrue (r.Read (), "#21");
+                       Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
+                       Assert.AreEqual (new XamlType (typeof (NullExtension), r.SchemaContext), r.Type, "#23-2");
+                       Assert.AreEqual (instance, r.Instance, "#26"); // null and NullExtension are different here.
+
+                       Assert.IsTrue (r.Read (), "#61");
+                       Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#62");
+
+                       Assert.IsFalse (r.Read (), "#71");
+                       Assert.IsTrue (r.IsEof, "#72");
+               }
+
+               [Test] // almost identical to TypeExtension (only type/instance difference)
+               [Category ("NotWorking")]
+               public void Read_StaticExtension ()
+               {
+                       var r = new XamlObjectReader (new StaticExtension ("MyMember"));
+                       Assert.IsTrue (r.Read (), "#11");
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
+                       Assert.IsNotNull (r.Namespace, "#13");
+                       Assert.AreEqual ("x", r.Namespace.Prefix, "#13-2");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#13-3");
+                       Assert.IsNull (r.Instance, "#14");
+
+                       Assert.IsTrue (r.Read (), "#21");
+                       Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
+                       Assert.AreEqual (new XamlType (typeof (StaticExtension), r.SchemaContext), r.Type, "#23-2");
+                       Assert.IsTrue (r.Instance is StaticExtension, "#26");
+
+                       Assert.IsTrue (r.Read (), "#31");
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#32");
+                       Assert.AreEqual (XamlLanguage.PositionalParameters, r.Member, "#33-2");
+
+                       Assert.IsTrue (r.Read (), "#41");
+                       Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#42");
+                       Assert.AreEqual ("MyMember", r.Value, "#43-2");
+
+                       Assert.IsTrue (r.Read (), "#51");
+                       Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#52");
+
+                       Assert.IsTrue (r.Read (), "#61");
+                       Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#62");
+
+                       Assert.IsFalse (r.Read (), "#71");
+                       Assert.IsTrue (r.IsEof, "#72");
+               }
+
+               [Test]
+               [Category ("NotWorking")]
+               public void Read_Array ()
+               {
+                       var obj = new int [] {5, -3, 0};
+                       var r = new XamlObjectReader (obj);
+                       Read_ArrayOrArrayExtension (r, obj);
+               }
+               
+               [Test]
+               [Category ("NotWorking")]
+               public void Read_ArrayExtension ()
+               {
+                       var obj = new ArrayExtension (new int [] {5, -3, 0});
+                       var r = new XamlObjectReader (obj);
+                       Read_ArrayOrArrayExtension (r, obj);
+               }
+
+               void Read_ArrayOrArrayExtension (XamlObjectReader r, object instance)
+               {
+                       Assert.IsTrue (r.Read (), "#11");
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
+                       Assert.IsNotNull (r.Namespace, "#13");
+                       Assert.AreEqual ("x", r.Namespace.Prefix, "#13-2");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#13-3");
+
+                       Assert.IsTrue (r.Read (), "#21");
+                       Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
+                       var xt = new XamlType (typeof (ArrayExtension), r.SchemaContext);
+                       Assert.AreEqual (xt, r.Type, "#23");
+                       Assert.AreEqual (instance, r.Instance, "#26"); // different between Array and ArrayExtension
+
+                       Assert.IsTrue (r.Read (), "#31");
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#32");
+                       Assert.AreEqual (xt.GetMember ("Type"), r.Member, "#33");
+
+                       Assert.IsTrue (r.Read (), "#41");
+                       Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#42");
+                       Assert.AreEqual ("x:Int32", r.Value, "#43");
+
+                       Assert.IsTrue (r.Read (), "#51");
+                       Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#52");
+
+                       Assert.IsTrue (r.Read (), "#61");
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#62");
+                       Assert.AreEqual (xt.GetMember ("Items"), r.Member, "#63");
+
+                       Assert.IsTrue (r.Read (), "#71");
+                       Assert.AreEqual (XamlNodeType.GetObject, r.NodeType, "#71-2");
+                       Assert.IsNull (r.Type, "#71-3");
+                       Assert.IsNull (r.Member, "#71-4");
+                       Assert.IsNull (r.Value, "#71-5");
+
+                       Assert.IsTrue (r.Read (), "#72");
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#72-2");
+                       Assert.AreEqual (XamlLanguage.Items, r.Member, "#72-3");
+
+                       string [] values = {"5", "-3", "0"};
+                       for (int i = 0; i < 3; i++) {
+                               Assert.IsTrue (r.Read (), i + "#73");
+                               Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, i + "#73-2");
+                               Assert.IsTrue (r.Read (), i + "#74");
+                               Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, i + "#74-2");
+                               Assert.AreEqual (XamlLanguage.Initialization, r.Member, i + "#74-3");
+                               Assert.IsTrue (r.Read (), i + "#75");
+                               Assert.IsNotNull (r.Value, i + "#75-2");
+                               Assert.AreEqual (values [i], r.Value, i + "#73-3");
+                               Assert.IsTrue (r.Read (), i + "#74");
+                               Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, i + "#74-2");
+                               Assert.IsTrue (r.Read (), i + "#75");
+                               Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, i + "#75-2");
+                       }
+
+                       Assert.IsTrue (r.Read (), "#81");
+                       Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#82"); // XamlLanguage.Items
+
+                       Assert.IsTrue (r.Read (), "#83");
+                       Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#84"); // GetObject
+
+                       Assert.IsTrue (r.Read (), "#85");
+                       Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#86"); // ArrayExtension.Items
+
+                       Assert.IsTrue (r.Read (), "#87");
+                       Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#88"); // ArrayExtension
+
+                       Assert.IsFalse (r.Read (), "#89");
+               }
+
+               [Test] // It gives Type member, not PositionalParameters... and no Items member here.
+               [Category ("NotWorking")]
+               public void Read_ArrayExtension2 ()
+               {
+                       var r = new XamlObjectReader (new ArrayExtension (typeof (int)));
+                       Assert.IsTrue (r.Read (), "#11");
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#12");
+                       Assert.IsNotNull (r.Namespace, "#13");
+                       Assert.AreEqual ("x", r.Namespace.Prefix, "#13-2");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "#13-3");
+                       Assert.IsNull (r.Instance, "#14");
+
+                       Assert.IsTrue (r.Read (), "#21");
+                       Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "#22");
+                       var xt = new XamlType (typeof (ArrayExtension), r.SchemaContext);
+                       Assert.AreEqual (xt, r.Type, "#23-2");
+                       Assert.IsTrue (r.Instance is ArrayExtension, "#26");
+
+                       Assert.IsTrue (r.Read (), "#31");
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "#32");
+                       Assert.AreEqual (xt.GetMember ("Type"), r.Member, "#33-2");
+
+                       Assert.IsTrue (r.Read (), "#41");
+                       Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#42");
+                       Assert.AreEqual ("x:Int32", r.Value, "#43-2");
+
+                       Assert.IsTrue (r.Read (), "#51");
+                       Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "#52");
+
+                       Assert.IsTrue (r.Read (), "#61");
+                       Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "#62");
+
+                       Assert.IsFalse (r.Read (), "#71");
+                       Assert.IsTrue (r.IsEof, "#72");
+               }
+
+               [Test]
+               public void Read_DateTime ()
+               {
+                       var obj = new DateTime (2010, 4, 15);
+                       var r = new XamlObjectReader (obj);
+                       Read_CommonClrType (r, obj);
+                       Assert.AreEqual ("2010-04-15", Read_Initialization (r, null), "#1");
+               }
+
+               [Test]
+               public void Read_TimeSpan ()
+               {
+                       Read_CommonXamlPrimitive (TimeSpan.FromMinutes (4));
+               }
+
+               [Test]
+               public void Read_Uri ()
+               {
+                       Read_CommonXamlPrimitive (new Uri ("urn:foo"));
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectReaderException))]
+               [Category ("NotWorking")]
+               public void Read_XData ()
+               {
+                       var r = new XamlObjectReader (new XData () {Text = "xdata text"}); // XmlReader implementation is not visible.
+                       while (!r.IsEof)
+                               r.Read ();
+               }
+
+               [Test]
+               public void ReadStandardTypes ()
+               {
+                       SimpleReadStandardType (new ArrayExtension ());
+                       SimpleReadStandardType (new NullExtension ());
+                       SimpleReadStandardType (new PropertyDefinition ());
+                       SimpleReadStandardType (new Reference ());
+                       SimpleReadStandardType (new StaticExtension ());
+                       SimpleReadStandardType (new TypeExtension ());
+               }
+
+               [Test]
+               public void Read_CustomMarkupExtension ()
+               {
+                       var r = new XamlObjectReader (new MyExtension () { Foo = typeof (int), Bar = "v2"});
+                       while (!r.IsEof) {
+                               r.Read ();
+                               if (r.Type != null && r.Type.UnderlyingType == typeof (MyExtension))
+                                       break;
+                       }
+                       Assert.IsFalse (r.IsEof, "#1");
+                       var xt = r.Type;
+                       while (!r.IsEof) {
+                               r.Read ();
+                               if (r.Member != null && r.Member.Name == "Foo")
+                                       break;
+                       }
+                       Assert.IsFalse (r.IsEof, "#2");
+                       Assert.AreEqual (xt.GetMember ("Foo"), r.Member, "#3");
+                       Assert.IsTrue (r.Read (), "#4");
+                       Assert.AreEqual (XamlNodeType.Value, r.NodeType, "#5");
+                       Assert.AreEqual ("x:Int32", r.Value, "#6");
+               }
+
+               [Test]
+               [Category ("NotWorking")]
+               public void Read_CustomMarkupExtension2 ()
+               {
+                       var r = new XamlObjectReader (new MyExtension2 () { Foo = typeof (int), Bar = "v2"});
+                       r.Read (); // ns
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "#1");
+                       r.Read ();
+                       var xt = r.Type;
+                       Assert.AreEqual (r.SchemaContext.GetXamlType (typeof (MyExtension2)), xt, "#2");
+                       Assert.IsTrue (r.Read (), "#3");
+                       Assert.AreEqual (XamlLanguage.Initialization, r.Member, "#4");
+                       Assert.IsTrue (r.Read (), "#5");
+                       Assert.AreEqual ("MonoTests.System.Xaml.MyExtension2", r.Value, "#6");
+                       Assert.IsTrue (r.Read (), "#7"); // EndMember
+                       Assert.IsTrue (r.Read (), "#8"); // EndObject
+                       Assert.IsFalse (r.Read (), "#9");
+               }
+
+               void SimpleReadStandardType (object instance)
+               {
+                       var r = new XamlObjectReader (instance);
+                       while (!r.IsEof)
+                               r.Read ();
+               }
+
+               void Read_CommonXamlPrimitive (object obj)
+               {
+                       var r = new XamlObjectReader (obj);
+                       Read_CommonXamlType (r);
+                       Read_Initialization (r, obj);
+               }
+
+               // from StartMember of Initialization to EndMember
+               string Read_Initialization (XamlObjectReader r, object comparableValue)
+               {
+                       Assert.IsTrue (r.Read (), "init#1");
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "init#2");
+                       Assert.IsNotNull (r.Member, "init#3");
+                       Assert.AreEqual (XamlLanguage.Initialization, r.Member, "init#3-2");
+                       Assert.IsTrue (r.Read (), "init#4");
+                       Assert.AreEqual (XamlNodeType.Value, r.NodeType, "init#5");
+                       Assert.AreEqual (typeof (string), r.Value.GetType (), "init#6");
+                       string ret = (string) r.Value;
+                       if (comparableValue != null)
+                               Assert.AreEqual (comparableValue.ToString (), r.Value, "init#6-2");
+                       Assert.IsTrue (r.Read (), "init#7");
+                       Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "init#8");
+                       return ret;
+               }
+
+               // from initial to StartObject
+               void Read_CommonXamlType (XamlObjectReader r)
+               {
+                       Assert.IsTrue (r.Read (), "ct#1");
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ct#2");
+                       Assert.IsNotNull (r.Namespace, "ct#3");
+                       Assert.AreEqual ("x", r.Namespace.Prefix, "ct#3-2");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "ct#3-3");
+                       Assert.IsNull (r.Instance, "ct#4");
+
+                       Assert.IsTrue (r.Read (), "ct#5");
+                       Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "ct#6");
+               }
+
+               // from initial to StartObject
+               void Read_CommonClrType (XamlObjectReader r, object obj)
+               {
+                       Assert.IsTrue (r.Read (), "ct#1");
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ct#2");
+                       Assert.IsNotNull (r.Namespace, "ct#3");
+                       Assert.AreEqual (String.Empty, r.Namespace.Prefix, "ct#3-2");
+                       Assert.AreEqual ("clr-namespace:" + obj.GetType ().Namespace + ";assembly=" + obj.GetType ().Assembly.GetName ().Name, r.Namespace.Namespace, "ct#3-3");
+
+/*
+                       Assert.IsTrue (r.Read (), "ct#4");
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ct#5");
+                       Assert.IsNotNull (r.Namespace, "ct#6");
+                       Assert.AreEqual ("x", r.Namespace.Prefix, "ct#6-2");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "ct#6-3");
+*/
+
+                       Assert.IsTrue (r.Read (), "ct#7");
+                       Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "ct#8");
+               }
+       }
+
+       class TestClass1
+       {
+       }
+
+       public class TestClass3
+       {
+               public TestClass3 Nested { get; set; }
+       }
+
+       [MarkupExtensionReturnType (typeof (Type))]
+       public class MyExtension : MarkupExtension
+       {
+               public MyExtension ()
+               {
+               }
+
+               public MyExtension (Type arg1, string arg2)
+               {
+                       Foo = arg1;
+                       Bar = arg2;
+               }
+
+               [ConstructorArgument ("arg1")]
+               public Type Foo { get; set; }
+               
+               [ConstructorArgument ("arg2")]
+               public string Bar { get; set; }
+
+               public override object ProvideValue (IServiceProvider provider)
+               {
+                       return "provided_value";
+               }
+       }
+
+       [TypeConverter (typeof (StringConverter))] // This attribute is *the* difference between MyExtension and this type.
+       public class MyExtension2 : MarkupExtension
+       {
+               public MyExtension2 ()
+               {
+               }
+
+               public MyExtension2 (Type arg1, string arg2)
+               {
+                       Foo = arg1;
+                       Bar = arg2;
+               }
+
+               [ConstructorArgument ("arg1")]
+               public Type Foo { get; set; }
+               
+               [ConstructorArgument ("arg2")]
+               public string Bar { get; set; }
+
+               public override object ProvideValue (IServiceProvider provider)
+               {
+                       return "provided_value";
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlObjectWriterSettingsTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlObjectWriterSettingsTest.cs
new file mode 100644 (file)
index 0000000..8b9b7b4
--- /dev/null
@@ -0,0 +1,55 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Xaml;
+using System.Xaml.Schema;
+using NUnit.Framework;
+
+namespace MonoTests.System.Xaml
+{
+       [TestFixture]
+       public class XamlObjectWriterSettingsTest
+       {
+               [Test]
+               public void DefaultValues ()
+               {
+                       var s = new XamlObjectWriterSettings ();
+                       Assert.IsNull (s.AccessLevel, "#1");
+                       Assert.IsNull (s.AfterBeginInitHandler, "#2");
+                       Assert.IsNull (s.AfterEndInitHandler, "#3");
+                       Assert.IsNull (s.AfterPropertiesHandler, "#4");
+                       Assert.IsNull (s.BeforePropertiesHandler, "#5");
+                       Assert.IsNull (s.ExternalNameScope, "#6");
+                       Assert.IsFalse (s.IgnoreCanConvert, "#7");
+                       Assert.IsFalse (s.PreferUnconvertedDictionaryKeys, "#8");
+                       Assert.IsFalse (s.RegisterNamesOnExternalNamescope, "#9");
+                       Assert.IsNull (s.RootObjectInstance, "#10");
+                       Assert.IsFalse (s.SkipDuplicatePropertyCheck, "#11");
+                       Assert.IsFalse (s.SkipProvideValueOnRoot, "#12");
+                       Assert.IsNull (s.XamlSetValueHandler, "#13");
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlObjectWriterTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlObjectWriterTest.cs
new file mode 100644 (file)
index 0000000..f709ac6
--- /dev/null
@@ -0,0 +1,681 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.IO;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml;
+using System.Xaml.Schema;
+using NUnit.Framework;
+
+using Category = NUnit.Framework.CategoryAttribute;
+
+namespace MonoTests.System.Xaml
+{
+       [TestFixture]
+       public class XamlObjectWriterTest
+       {
+               PropertyInfo str_len = typeof (string).GetProperty ("Length");
+               XamlSchemaContext sctx = new XamlSchemaContext (null, null);
+               XamlType xt, xt2, xt3, xt4;
+               XamlMember xm, xm2, xm3;
+
+               public XamlObjectWriterTest ()
+               {
+                       xt = new XamlType (typeof (string), sctx);
+                       xt2 = new XamlType (typeof (List<int>), sctx);
+                       xt3 = new XamlType (typeof (TestClass1), sctx);
+                       xt4 = new XamlType (typeof (Foo), sctx);
+                       xm = new XamlMember (str_len, sctx);
+                       xm2 = new XamlMember (typeof (TestClass1).GetProperty ("TestProp1"), sctx);
+                       xm3 = new XamlMember (typeof (TestClass1).GetProperty ("TestProp2"), sctx);
+               }
+               
+               public class TestClass1
+               {
+                       public TestClass1 ()
+                       {
+                               TestProp3 = "foobar";
+                       }
+                       public string TestProp1 { get; set; }
+                       // nested.
+                       public TestClass1 TestProp2 { get; set; }
+                       public string TestProp3 { get; set; }
+                       public int TestProp4 { get; set; }
+               }
+
+               public class Foo : List<int>
+               {
+                       public Foo ()
+                       {
+                               Bar = new List<string> ();
+                       }
+                       public List<string> Bar { get; private set; }
+                       public List<string> Baz { get; set; }
+                       public string Ext { get; set; }
+               }
+               
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void SchemaContextNull ()
+               {
+                       new XamlObjectWriter (null);
+               }
+
+               [Test]
+               public void SettingsNull ()
+               {
+                       // allowed.
+                       var w = new XamlObjectWriter (sctx, null);
+                       Assert.AreEqual (sctx, w.SchemaContext, "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void InitWriteEndMember ()
+               {
+                       new XamlObjectWriter (sctx, null).WriteEndMember ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void InitWriteEndObject ()
+               {
+                       new XamlObjectWriter (sctx, null).WriteEndObject ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void InitWriteGetObject ()
+               {
+                       new XamlObjectWriter (sctx, null).WriteGetObject ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void InitWriteValue ()
+               {
+                       new XamlObjectWriter (sctx, null).WriteValue ("foo");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void InitWriteStartMember ()
+               {
+                       new XamlObjectWriter (sctx, null).WriteStartMember (new XamlMember (str_len, sctx));
+               }
+
+               [Test]
+               public void InitWriteNamespace ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteNamespace (new NamespaceDeclaration ("urn:foo", "x")); // ignored.
+                       xw.Close ();
+                       Assert.IsNull (xw.Result, "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void WriteNamespaceNull ()
+               {
+                       new XamlObjectWriter (sctx, null).WriteNamespace (null);
+               }
+
+               [Test]
+               public void InitWriteStartObject ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (new XamlType (typeof (int), sctx));
+                       xw.Close ();
+                       Assert.AreEqual (0, xw.Result, "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void GetObjectAfterStartObject ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteGetObject ();
+               }
+
+               [Test]
+               //[ExpectedException (typeof (XamlObjectWriterException))]
+               public void WriteStartObjectAfterTopLevel ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteEndObject ();
+                       // writing another root is <del>not</del> allowed.
+                       xw.WriteStartObject (xt3);
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void WriteEndObjectExcess ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteEndObject ();
+                       xw.WriteEndObject ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void StartObjectWriteEndMember ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteEndMember ();
+               }
+
+               [Test]
+               public void WriteObjectAndMember ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xm2);
+                       xw.WriteValue ("foo");
+                       xw.WriteEndMember ();
+                       xw.Close ();
+               }
+
+               [Test]
+               public void StartMemberWriteEndMember ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xm3);
+                       xw.WriteEndMember (); // unlike XamlXmlWriter, it is not treated as an error...
+                       xw.Close ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void StartMemberWriteStartMember ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xm3);
+                       xw.WriteStartMember (xm3);
+               }
+
+               [Test]
+               public void WriteObjectInsideMember ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xm3);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteEndObject ();
+                       xw.WriteEndMember ();
+                       xw.Close ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlDuplicateMemberException))]
+               public void ValueAfterObject ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xm3);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteEndObject ();
+                       // passes here, but ...
+                       xw.WriteValue ("foo");
+                       // rejected here, unlike XamlXmlWriter.
+                       //
+                       // Basically, assume that no content could be written 
+                       // for an object member within XamlObjectWriter.
+                       xw.WriteEndMember ();
+               }
+
+               [Test]
+               public void ValueAfterObject2 ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xm3);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteEndObject ();
+                       // passes here, but should be rejected later.
+                       xw.WriteValue ("foo");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlDuplicateMemberException))]
+               public void DuplicateAssignment ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xm3);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteEndObject ();
+                       xw.WriteValue ("foo"); // causes duplicate assignment.
+                       xw.WriteEndMember ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlDuplicateMemberException))]
+               public void DuplicateAssignment2 ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xm3);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteEndObject ();
+                       xw.WriteEndMember ();
+                       xw.WriteStartMember (xm3);
+               }
+
+               [Test]
+               //[ExpectedException (typeof (ArgumentException))] // oh? XamlXmlWriter raises this.
+               public void WriteValueTypeMismatch ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartMember (XamlLanguage.Initialization);
+                       xw.WriteValue (new TestClass1 ());
+                       xw.WriteEndMember ();
+                       xw.Close ();
+                       Assert.IsNotNull (xw.Result, "#1");
+                       Assert.AreEqual (typeof (TestClass1), xw.Result.GetType (), "#2");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))] // it fails to convert type and set property value.
+               public void WriteValueTypeMismatch2 ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xm3);
+                       xw.WriteValue ("foo");
+                       xw.WriteEndMember ();
+               }
+
+               [Test]
+               public void WriteValueTypeOK ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartMember (XamlLanguage.Initialization);
+                       xw.WriteValue ("foo");
+                       xw.WriteEndMember ();
+                       xw.Close ();
+                       Assert.AreEqual ("foo", xw.Result, "#1");
+               }
+
+               [Test]
+               public void WriteValueList ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (new XamlType (typeof (List<string>), sctx));
+                       xw.WriteStartMember (XamlLanguage.Items);
+                       xw.WriteValue ("foo");
+                       xw.WriteValue ("bar");
+                       xw.WriteEndMember ();
+                       xw.Close ();
+                       var l = xw.Result as List<string>;
+                       Assert.IsNotNull (l, "#1");
+                       Assert.AreEqual ("foo", l [0], "#2");
+                       Assert.AreEqual ("bar", l [1], "#3");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void CloseWithoutEndMember ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartMember (XamlLanguage.Initialization);
+                       xw.WriteValue ("foo");
+                       xw.Close ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void WriteValueAfterValue ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteValue ("foo");
+                       xw.WriteValue ("bar");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void WriteValueAfterNullValue ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteValue (null);
+                       xw.WriteValue ("bar");
+               }
+
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void StartMemberWriteEndObject ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xm3);
+                       xw.WriteEndObject ();
+               }
+
+               [Test]
+               public void WriteNamespace ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteNamespace (new NamespaceDeclaration (XamlLanguage.Xaml2006Namespace, "x"));
+                       xw.WriteNamespace (new NamespaceDeclaration ("urn:foo", "y"));
+                       xw.WriteStartObject (xt3);
+                       xw.WriteEndObject ();
+                       xw.Close ();
+                       var ret = xw.Result;
+                       Assert.IsTrue (ret is TestClass1, "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void StartObjectStartObject ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartObject (xt3);
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void StartObjectValue ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteValue ("foo");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlDuplicateMemberException))] // duplicate member assignment
+               public void ObjectContainsObjectAndObject ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xm3);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteEndObject ();
+                       xw.WriteStartObject (xt3);
+                       xw.WriteEndObject (); // the exception happens *here*
+                       // FIXME: so, WriteEndMember() should not be required, but we fail here. Practically this difference should not matter.
+                       xw.WriteEndMember (); // of xm3
+               }
+
+               [Test]
+               public void ObjectContainsObjectAndValue ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xm3);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteEndObject ();
+                       xw.WriteValue ("foo"); // but this is allowed ...
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlDuplicateMemberException))] // duplicate member assignment
+               public void ObjectContainsObjectAndValue2 ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xm3);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteEndObject ();
+                       xw.WriteValue ("foo");
+                       xw.WriteEndMember (); // ... until here.
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))] // unlike XamlXmlWriter (IOE)
+               public void EndObjectAfterNamespace ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteNamespace (new NamespaceDeclaration ("urn:foo", "y"));
+                       xw.WriteEndObject ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))] // ... unlike XamlXmlWriter (throws IOE)
+               public void WriteValueAfterNamespace ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartMember (XamlLanguage.Initialization);
+                       xw.WriteNamespace (new NamespaceDeclaration ("urn:foo", "y"));
+                       xw.WriteValue ("foo");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))] // ... unlike XamlXmlWriter (allowed)
+               public void ValueThenStartObject ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xm2);
+                       xw.WriteValue ("foo");
+                       xw.WriteStartObject (xt3);
+                       xw.Close ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))] // ... unlike XamlXmlWriter (allowed, as it allows StartObject after Value)
+               public void ValueThenNamespace ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xm2);
+                       xw.WriteValue ("foo");
+                       xw.WriteNamespace (new NamespaceDeclaration ("y", "urn:foo")); // this does not raise an error (since it might start another object)
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))] // strange, this does *not* result in IOE...
+               public void ValueThenNamespaceThenEndMember ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xm2);
+                       xw.WriteValue ("foo");
+                       xw.WriteNamespace (new NamespaceDeclaration ("y", "urn:foo"));
+                       xw.WriteEndMember ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))] // This is also very different, requires exactly opposite namespace output manner to XamlXmlWriter (namespace first, object follows).
+               [Category ("NotWorking")]
+               public void StartMemberAfterNamespace ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteNamespace (new NamespaceDeclaration ("urn:foo", "y"));
+               }
+
+               [Test]
+               [Category ("NotWorking")]
+               public void StartMemberBeforeNamespace ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xm2); // note that it should be done *after* WriteNamespace in XamlXmlWriter. SO inconsistent.
+                       xw.WriteNamespace (new NamespaceDeclaration ("urn:foo", "y"));
+                       xw.WriteEndMember ();
+                       xw.Close ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void StartMemberBeforeNamespace2 ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xm2);
+                       xw.WriteNamespace (new NamespaceDeclaration ("urn:foo", "y"));
+                       // and here, NamespaceDeclaration is written as if it 
+                       // were another value object( unlike XamlXmlWriter)
+                       // and rejects further value.
+                       xw.WriteValue ("foo");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void EndMemberThenStartObject ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xm2);
+                       xw.WriteValue ("foo");
+                       xw.WriteEndMember ();
+                       xw.WriteStartObject (xt3);
+               }
+
+               // The semantics on WriteGetObject() is VERY different from XamlXmlWriter.
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void GetObjectOnNullValue ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xm2);
+                       xw.WriteGetObject ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void GetObjectOnNullValue2 ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt4);
+                       xw.WriteStartMember (new XamlMember (typeof (Foo).GetProperty ("Baz"), sctx)); // unlike Bar, Baz is not initialized.
+                       xw.WriteGetObject (); // fails, because it is null.
+               }
+
+               [Test]
+               [Category ("NotWorking")]
+               public void GetObjectOnIntValue ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xt3.GetMember ("TestProp4")); // int
+                       xw.WriteGetObject (); // passes!!! WTF
+                       xw.WriteEndObject ();
+               }
+
+               [Test]
+               // String is not treated as a collection on XamlXmlWriter, while this XamlObjectReader does.
+               [Category ("NotWorking")]
+               public void GetObjectOnNonNullString ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt3);
+                       xw.WriteStartMember (xt3.GetMember ("TestProp3"));
+                       xw.WriteGetObject ();
+               }
+
+               [Test]
+               [Category ("NotWorking")]
+               public void GetObjectOnCollection ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt4);
+                       xw.WriteStartMember (new XamlMember (typeof (Foo).GetProperty ("Bar"), sctx));
+                       xw.WriteGetObject ();
+                       xw.Close ();
+                       // FIXME: enable it once we got generic type output fixed.
+                       //Assert.AreEqual (xml, sw.ToString ().Replace ('"', '\''), "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void ValueAfterGetObject ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt4);
+                       xw.WriteStartMember (new XamlMember (typeof (Foo).GetProperty ("Bar"), sctx));
+                       xw.WriteGetObject ();
+                       xw.WriteValue ("foo");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void StartObjectAfterGetObject ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt4);
+                       xw.WriteStartMember (new XamlMember (typeof (Foo).GetProperty ("Bar"), sctx));
+                       xw.WriteGetObject ();
+                       xw.WriteStartObject (xt);
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlObjectWriterException))]
+               public void EndMemberAfterGetObject ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt4);
+                       xw.WriteStartMember (new XamlMember (typeof (Foo).GetProperty ("Bar"), sctx));
+                       xw.WriteGetObject ();
+                       xw.WriteEndMember (); // ...!?
+               }
+
+               [Test]
+               [Category ("NotWorking")]
+               public void StartMemberAfterGetObject ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt4);
+                       var xmm = xt4.GetMember ("Bar");
+                       xw.WriteStartMember (xmm); // <List.Bar>
+                       xw.WriteGetObject (); // shifts current member to List<T>.
+                       xw.WriteStartMember (xmm.Type.GetMember ("Capacity"));
+                       xw.WriteValue (5);
+                       xw.WriteEndMember ();
+                       /*
+                       xw.WriteEndObject (); // got object
+                       xw.WriteEndMember (); // Bar
+                       xw.WriteEndObject (); // started object
+                       */
+                       xw.Close ();
+               }
+
+               [Test]
+               public void EndObjectAfterGetObject ()
+               {
+                       var xw = new XamlObjectWriter (sctx, null);
+                       xw.WriteStartObject (xt4);
+                       xw.WriteStartMember (new XamlMember (typeof (Foo).GetProperty ("Bar"), sctx));
+                       xw.WriteGetObject ();
+                       xw.WriteEndObject ();
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlReaderSettingsTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlReaderSettingsTest.cs
new file mode 100644 (file)
index 0000000..5ae44af
--- /dev/null
@@ -0,0 +1,75 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Xaml;
+using System.Xaml.Schema;
+using NUnit.Framework;
+
+namespace MonoTests.System.Xaml
+{
+       [TestFixture]
+       public class XamlReaderSettingsTest
+       {
+               [Test]
+               public void DefaultValues ()
+               {
+                       var s = new XamlReaderSettings ();
+                       Assert.IsFalse (s.AllowProtectedMembersOnRoot, "#1");
+                       Assert.IsNull (s.BaseUri, "#2");
+                       Assert.IsFalse (s.IgnoreUidsOnPropertyElements, "#3");
+                       Assert.IsNull (s.LocalAssembly, "#4");
+                       Assert.IsFalse (s.ProvideLineInfo, "#5");
+                       Assert.IsFalse (s.ValuesMustBeString, "#6");
+               }
+
+               [Test]
+               public void CopyConstructorNull ()
+               {
+                       new XamlReaderSettings (null);
+               }
+
+               [Test]
+               public void CopyConstructor ()
+               {
+                       var s = new XamlReaderSettings ();
+                       s.AllowProtectedMembersOnRoot = true;
+                       s.IgnoreUidsOnPropertyElements = true;
+                       s.ProvideLineInfo = true;
+                       s.ValuesMustBeString = true;
+                       s.BaseUri = new Uri ("urn:foo");
+                       s.LocalAssembly = typeof (object).Assembly;
+
+                       s = new XamlReaderSettings (s);
+
+                       Assert.IsTrue (s.AllowProtectedMembersOnRoot, "#1");
+                       Assert.IsTrue (s.BaseUri.Equals (new Uri ("urn:foo")), "#2");
+                       Assert.IsTrue (s.IgnoreUidsOnPropertyElements, "#3");
+                       Assert.AreEqual (typeof (int).Assembly, s.LocalAssembly, "#4");
+                       Assert.IsTrue (s.ProvideLineInfo, "#5");
+                       Assert.IsTrue (s.ValuesMustBeString, "#6");
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlSchemaContextSettingsTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlSchemaContextSettingsTest.cs
new file mode 100644 (file)
index 0000000..08aba9b
--- /dev/null
@@ -0,0 +1,62 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Xaml;
+using System.Xaml.Schema;
+using NUnit.Framework;
+
+namespace MonoTests.System.Xaml
+{
+       [TestFixture]
+       public class XamlSchemaContextSettingsTest
+       {
+               [Test]
+               public void ConstructorTypeNullSettings ()
+               {
+                       // ... allwed(!)
+                       new XamlSchemaContextSettings (null);
+               }
+
+               [Test]
+               public void DefaultValues ()
+               {
+                       var s = new XamlSchemaContextSettings ();
+                       Assert.IsFalse (s.FullyQualifyAssemblyNamesInClrNamespaces, "#1");
+                       Assert.IsFalse (s.SupportMarkupExtensionsWithDuplicateArity, "#2");
+               }
+
+               [Test]
+               public void CopyConstructor ()
+               {
+                       var s = new XamlSchemaContextSettings ();
+                       s.FullyQualifyAssemblyNamesInClrNamespaces = true;
+                       s.SupportMarkupExtensionsWithDuplicateArity = true;
+                       s = new XamlSchemaContextSettings (s);
+                       Assert.IsTrue (s.FullyQualifyAssemblyNamesInClrNamespaces, "#1");
+                       Assert.IsTrue (s.SupportMarkupExtensionsWithDuplicateArity, "#2");
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlSchemaContextTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlSchemaContextTest.cs
new file mode 100644 (file)
index 0000000..ff06fcf
--- /dev/null
@@ -0,0 +1,261 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml;
+using System.Xaml.Schema;
+using NUnit.Framework;
+
+[assembly:XmlnsDefinition ("urn:mono-test", "MonoTests.System.Xaml.NamespaceTest")]
+[assembly:XmlnsDefinition ("urn:mono-test2", "MonoTests.System.Xaml.NamespaceTest2")]
+[assembly:XmlnsCompatibleWith ("urn:foo", "urn:bar")]
+
+namespace MonoTests.System.Xaml
+{
+       [TestFixture]
+       public class XamlSchemaContextTest
+       {
+               XamlSchemaContext NewStandardContext ()
+               {
+                       return new XamlSchemaContext (new Assembly [] {typeof (XamlSchemaContext).Assembly });
+               }
+
+               XamlSchemaContext NewThisAssemblyContext ()
+               {
+                       return new XamlSchemaContext (new Assembly [] {GetType ().Assembly });
+               }
+
+               [Test]
+               public void ConstructorNullAssemblies ()
+               {
+                       // allowed.
+                       var ctx = new XamlSchemaContext ((Assembly []) null);
+                       Assert.IsFalse (ctx.FullyQualifyAssemblyNamesInClrNamespaces, "#1");
+                       Assert.IsFalse (ctx.SupportMarkupExtensionsWithDuplicateArity, "#2");
+                       Assert.IsNull (ctx.ReferenceAssemblies, "#3");
+               }
+
+               [Test]
+               public void ConstructorNullSettings ()
+               {
+                       // allowed.
+                       var ctx = new XamlSchemaContext ((XamlSchemaContextSettings) null);
+               }
+
+               [Test]
+               public void ConstructorNoAssembly ()
+               {
+                       var ctx = new XamlSchemaContext (new Assembly [0]);
+               }
+
+               [Test]
+               public void Constructor ()
+               {
+                       var ctx = new XamlSchemaContext (new Assembly [] {typeof (XamlSchemaContext).Assembly });
+                       Assert.AreEqual (1, ctx.ReferenceAssemblies.Count, "#1");
+               }
+
+               [Test]
+               public void GetAllXamlNamespaces ()
+               {
+                       var ctx = new XamlSchemaContext (null, null);
+                       var arr = ctx.GetAllXamlNamespaces ().ToArray ();
+                       Assert.AreEqual (3, arr.Length, "#1");
+                       Assert.IsTrue (arr.Contains (XamlLanguage.Xaml2006Namespace), "#1-2");
+                       Assert.IsTrue (arr.Contains ("urn:mono-test"), "#1-3");
+                       Assert.IsTrue (arr.Contains ("urn:mono-test2"), "#1-4");
+
+                       ctx = NewStandardContext ();
+                       arr = ctx.GetAllXamlNamespaces ().ToArray ();
+                       Assert.AreEqual (1, arr.Length, "#2");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, arr [0], "#2-2");
+
+                       ctx = NewThisAssemblyContext ();
+                       arr = ctx.GetAllXamlNamespaces ().ToArray ();
+                       Assert.AreEqual (2, arr.Length, "#3");
+                       Assert.IsTrue (arr.Contains ("urn:mono-test"), "#3-2");
+                       Assert.IsTrue (arr.Contains ("urn:mono-test2"), "#3-3");
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void GetPreferredPrefixNull ()
+               {
+                       var ctx = new XamlSchemaContext (null, null);
+                       ctx.GetPreferredPrefix (null);
+               }
+
+               [Test]
+               public void GetPreferredPrefix ()
+               {
+                       var ctx = new XamlSchemaContext (null, null);
+                       Assert.AreEqual ("x", ctx.GetPreferredPrefix (XamlLanguage.Xaml2006Namespace), "#1");
+                       Assert.AreEqual ("p", ctx.GetPreferredPrefix ("urn:4mbw93w89mbh"), "#2"); // ... WTF "p" ?
+                       Assert.AreEqual ("p", ctx.GetPreferredPrefix ("urn:etbeoesmj"), "#3"); // ... WTF "p" ?
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void TryGetCompatibleXamlNamespaceNull ()
+               {
+                       var ctx = new XamlSchemaContext (null, null);
+                       string dummy;
+                       ctx.TryGetCompatibleXamlNamespace (null, out dummy);
+               }
+
+               [Test]
+               [Category ("NotDotNet")] // TryGetCompatibleXamlNamespace() never worked like documented.
+               public void TryGetCompatibleXamlNamespace ()
+               {
+                       var ctx = new XamlSchemaContext (null, null);
+                       string dummy;
+                       Assert.IsFalse (ctx.TryGetCompatibleXamlNamespace (String.Empty, out dummy), "#1");
+                       Assert.IsNull (dummy, "#1-2"); // this shows the fact that the out result value for false case is not trustworthy.
+
+                       ctx = NewThisAssemblyContext ();
+                       Assert.IsFalse (ctx.TryGetCompatibleXamlNamespace (String.Empty, out dummy), "#2");
+                       Assert.IsFalse (ctx.TryGetCompatibleXamlNamespace ("urn:bar", out dummy), "#3");
+                       // why does .NET return false here?
+                       Assert.IsTrue (ctx.TryGetCompatibleXamlNamespace ("urn:foo", out dummy), "#4");
+                       Assert.AreEqual ("urn:bar", dummy, "#5");
+               }
+
+/*
+                       var settings = new XamlSchemaContextSettings () { FullyQualifyAssemblyNamesInClrNamespaces = true };
+                       ctx = new XamlSchemaContext (new Assembly [] {typeof (XamlSchemaContext).Assembly }, settings);
+
+                       ctx = new XamlSchemaContext (new Assembly [] {GetType ().Assembly }, settings);
+                       arr = ctx.GetAllXamlNamespaces ().ToArray ();
+                       Assert.AreEqual (2, arr.Length, "#5");
+                       Assert.IsTrue (arr.Contains ("urn:mono-test"), "#5-2");
+                       Assert.IsTrue (arr.Contains ("urn:mono-test2"), "#5-3");
+               }
+*/
+
+               [Test]
+               public void GetXamlTypeAndAllXamlTypes ()
+               {
+                       var ctx = new XamlSchemaContext (new Assembly [] {typeof (string).Assembly}); // build with corlib.
+                       Assert.AreEqual (0, ctx.GetAllXamlTypes (XamlLanguage.Xaml2006Namespace).Count (), "#0"); // premise
+
+                       var xt = ctx.GetXamlType (typeof (string));
+                       Assert.IsNotNull (xt, "#1");
+                       Assert.AreEqual (typeof (string), xt.UnderlyingType, "#2");
+                       Assert.IsTrue (object.ReferenceEquals (xt, ctx.GetXamlType (typeof (string))), "#3");
+
+                       // non-primitive type example
+                       Assert.IsTrue (object.ReferenceEquals (ctx.GetXamlType (GetType ()), ctx.GetXamlType (GetType ())), "#4");
+
+                       // after getting these types, it still returns 0. So it's not all about caching.
+                       Assert.AreEqual (0, ctx.GetAllXamlTypes (XamlLanguage.Xaml2006Namespace).Count (), "#5");
+               }
+
+               [Test]
+               public void GetAllXamlTypesInXaml2006Namespace ()
+               {
+                       var ctx = NewStandardContext ();
+
+                       // There are some special types that have non-default name: MemberDefinition, PropertyDefinition
+
+                       var l = ctx.GetAllXamlTypes (XamlLanguage.Xaml2006Namespace);
+                       Assert.IsTrue (l.Count () > 40, "#1");
+                       Assert.IsTrue (l.Any (t => t.UnderlyingType == typeof (MemberDefinition)), "#2");
+                       Assert.IsTrue (l.Any (t => t.Name == "AmbientAttribute"), "#3");
+                       Assert.IsTrue (l.Any (t => t.Name == "XData"), "#4");
+                       Assert.IsTrue (l.Any (t => t.Name == "ArrayExtension"), "#5");
+                       Assert.IsTrue (l.Any (t => t.Name == "StaticExtension"), "#6");
+                       // FIXME: enable these tests when I sort out how these special names are filled.
+                       //Assert.IsTrue (l.Any (t => t.Name == "Member"), "#7");
+                       //Assert.IsTrue (l.Any (t => t.Name == "Property"), "#8");
+                       //Assert.IsFalse (l.Any (t => t.Name == "MemberDefinition"), "#9");
+                       //Assert.IsFalse (l.Any (t => t.Name == "PropertyDefinition"), "#10");
+                       Assert.IsFalse (l.Any (t => t.Name == "Array"), "#11");
+                       Assert.IsFalse (l.Any (t => t.Name == "Null"), "#12");
+                       Assert.IsFalse (l.Any (t => t.Name == "Static"), "#13");
+                       Assert.IsFalse (l.Any (t => t.Name == "Type"), "#14");
+                       //Assert.AreEqual ("MemberDefinition", new XamlType (typeof (MemberDefinition), new XamlSchemaContext (null, null)).Name);
+                       //Assert.AreEqual ("Member", l.GetAllXamlTypes (XamlLanguage.Xaml2006Namespace).First (t => t.UnderlyingType == typeof (MemberDefinition)));
+               }
+
+               [Test]
+               public void GetXamlTypeByName ()
+               {
+                       var ns = XamlLanguage.Xaml2006Namespace;
+                       var ctx = NewThisAssemblyContext ();
+                       //var ctx = NewStandardContext ();
+                       XamlType xt;
+
+                       Assert.IsNull (ctx.GetXamlType (new XamlTypeName ("urn:foobarbaz", "bar")));
+
+                       xt = ctx.GetXamlType (new XamlTypeName (ns, "Int32"));
+                       Assert.IsNotNull (xt, "#1");
+                       xt = ctx.GetXamlType (new XamlTypeName (ns, "Int32", new XamlTypeName [] {new XamlTypeName (ns, "Int32")}));
+                       Assert.IsNull (xt, "#1-2");
+                       xt = ctx.GetXamlType (new XamlTypeName (ns, "Uri"));
+                       Assert.IsNotNull (xt, "#2");
+
+                       // Compare those results to GetAllXamlTypesInXaml2006Namespace() results,
+                       // which asserts that types with those names are *not* included.
+                       xt = ctx.GetXamlType (new XamlTypeName (ns, "Array"));
+                       Assert.IsNotNull (xt, "#3");
+                       xt = ctx.GetXamlType (new XamlTypeName (ns, "Property"));
+                       Assert.IsNotNull (xt, "#4");
+                       xt = ctx.GetXamlType (new XamlTypeName (ns, "Null"));
+                       Assert.IsNotNull (xt, "#5");
+                       xt = ctx.GetXamlType (new XamlTypeName (ns, "Static"));
+                       Assert.IsNotNull (xt, "#6");
+                       xt = ctx.GetXamlType (new XamlTypeName (ns, "Type"));
+                       Assert.IsNotNull (xt, "#7");
+               }
+
+               [Test]
+               public void GetTypeForRuntimeType ()
+               {
+                       var ctx = NewStandardContext ();
+
+                       // There are some special types that have non-default name: MemberDefinition, PropertyDefinition
+
+                       var xt = ctx.GetXamlType (typeof (Type));
+                       Assert.AreEqual ("Type", xt.Name, "#1-1");
+                       Assert.AreEqual (typeof (Type), xt.UnderlyingType, "#1-2");
+
+                       xt = ctx.GetXamlType (new XamlTypeName (XamlLanguage.Xaml2006Namespace, "Type")); // becomes TypeExtension, not Type
+                       Assert.AreEqual ("TypeExtension", xt.Name, "#2-1");
+                       Assert.AreEqual (typeof (TypeExtension), xt.UnderlyingType, "#2-2");
+               }
+
+               [Test]
+               public void GetTypeFromXamlTypeNameWithClrName ()
+               {
+                       // ensure that this does *not* resolve clr type name.
+                       var xn = new XamlTypeName ("clr-namespace:System;assembly=mscorlib", "DateTime");
+                       var ctx = NewStandardContext ();
+                       var xt = ctx.GetXamlType (xn);
+                       Assert.IsNull (xt, "#1");
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlTypeTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlTypeTest.cs
new file mode 100644 (file)
index 0000000..5a6e2ab
--- /dev/null
@@ -0,0 +1,611 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml;
+using System.Xaml.Schema;
+using NUnit.Framework;
+
+using Category = NUnit.Framework.CategoryAttribute;
+
+namespace MonoTests.System.Xaml
+{
+       // FIXME: enable DeferringLoader tests.
+       [TestFixture]
+       public class XamlTypeTest
+       {
+               XamlSchemaContext sctx = new XamlSchemaContext (null, null);
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorTypeNullType ()
+               {
+                       new XamlType (null, sctx);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorTypeNullSchemaContext ()
+               {
+                       new XamlType (typeof (int), null);
+               }
+
+               [Test]
+               public void ConstructorSimpleType ()
+               {
+                       var t = new XamlType (typeof (int), sctx);
+                       Assert.AreEqual ("Int32", t.Name, "#1");
+                       Assert.AreEqual (typeof (int), t.UnderlyingType, "#2");
+                       Assert.IsNotNull (t.BaseType, "#3-1");
+                       // So, it is type aware. It's weird that t.Name still returns full name just as it is passed to the .ctor.
+                       Assert.AreEqual ("ValueType", t.BaseType.Name, "#3-2");
+                       Assert.AreEqual ("clr-namespace:System;assembly=mscorlib", t.BaseType.PreferredXamlNamespace, "#3-3");
+                       // It is likely only for primitive types such as int.
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, t.PreferredXamlNamespace, "#4");
+
+                       t = new XamlType (typeof (XamlXmlReader), sctx);
+                       Assert.AreEqual ("XamlXmlReader", t.Name, "#11");
+                       Assert.AreEqual (typeof (XamlXmlReader), t.UnderlyingType, "#12");
+                       Assert.IsNotNull (t.BaseType, "#13");
+                       Assert.AreEqual (typeof (XamlReader), t.BaseType.UnderlyingType, "#13-2");
+                       Assert.AreEqual ("clr-namespace:System.Xaml;assembly=System.Xaml", t.BaseType.PreferredXamlNamespace, "#13-3");
+                       Assert.AreEqual ("clr-namespace:System.Xaml;assembly=System.Xaml", t.PreferredXamlNamespace, "#14");
+               }
+
+               [Test]
+               public void ConstructorNullTypeInvoker ()
+               {
+                       // allowed.
+                       new XamlType (typeof (int), sctx, null);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorNamesNullName ()
+               {
+                       new XamlType (String.Empty, null, null, sctx);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorNamesNullSchemaContext ()
+               {
+                       new XamlType ("System", "Int32", null, null);
+               }
+
+               [Test]
+               public void ConstructorNames ()
+               {
+                       // null typeArguments is allowed.
+                       new XamlType ("System", "Int32", null, sctx);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorNameNullName ()
+               {
+                       new MyXamlType (null, null, sctx);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void ConstructorNameNullSchemaContext ()
+               {
+                       new MyXamlType ("System.Int32", null, null);
+               }
+
+               [Test]
+               public void ConstructorNameInvalid ()
+               {
+                       // ... all allowed.
+                       new XamlType (String.Empty, ".", null, sctx);
+                       new XamlType (String.Empty, "<>", null, sctx);
+                       new XamlType (String.Empty, "", null, sctx);
+               }
+
+               [Test]
+               public void ConstructorNameWithFullName ()
+               {
+                       // null typeArguments is allowed.
+                       var t = new MyXamlType ("System.Int32", null, sctx);
+                       Assert.AreEqual ("System.Int32", t.Name, "#1");
+                       Assert.IsNull (t.UnderlyingType, "#2");
+                       Assert.IsNotNull (t.BaseType, "#3-1");
+                       // So, it is type aware. It's weird that t.Name still returns full name just as it is passed to the .ctor.
+                       Assert.AreEqual ("Object", t.BaseType.Name, "#3-2");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, t.BaseType.PreferredXamlNamespace, "#3-3");
+                       Assert.IsNull (t.BaseType.BaseType, "#3-4");
+                       Assert.AreEqual (String.Empty, t.PreferredXamlNamespace, "#4");
+                       Assert.IsFalse (t.IsArray, "#5");
+                       Assert.IsFalse (t.IsGeneric, "#6");
+                       Assert.IsTrue (t.IsPublic, "#7");
+               }
+
+               [Test]
+               public void NoSuchTypeByName ()
+               {
+                       var t = new MyXamlType ("System.NoSuchType", null, sctx);
+                       Assert.AreEqual ("System.NoSuchType", t.Name, "#1");
+                       Assert.IsNull (t.UnderlyingType, "#2");
+                       Assert.IsNotNull (t.BaseType, "#3-1");
+                       // So, it is type aware. It's weird that t.Name still returns full name just as it is passed to the .ctor.
+                       Assert.AreEqual ("Object", t.BaseType.Name, "#3-2");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, t.BaseType.PreferredXamlNamespace, "#3-3");
+                       Assert.AreEqual (String.Empty, t.PreferredXamlNamespace, "#4");
+               }
+
+               [Test]
+               public void NoSuchTypeByNames ()
+               {
+                       var t = new XamlType ("urn:foo", "System.NoSuchType", null, sctx);
+                       Assert.AreEqual ("System.NoSuchType", t.Name, "#1");
+                       Assert.IsNull (t.UnderlyingType, "#2");
+                       Assert.IsNotNull (t.BaseType, "#3-1");
+                       // So, it is type aware. It's weird that t.Name still returns full name just as it is passed to the .ctor.
+                       Assert.AreEqual ("Object", t.BaseType.Name, "#3-2");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, t.BaseType.PreferredXamlNamespace, "#3-3");
+                       Assert.AreEqual ("urn:foo", t.PreferredXamlNamespace, "#4");
+               }
+
+               [Test]
+               [Ignore ("It results in NRE on .NET 4.0 RTM")]
+               public void EmptyTypeArguments ()
+               {
+                       var t1 = new MyXamlType ("System.Int32", null, sctx);
+                       var t2 = new MyXamlType ("System.Int32", new XamlType [0], sctx);
+                       Assert.IsTrue (t1 == t2, "#1");
+                       Assert.IsTrue (t1.Equals (t2), "#2");
+               }
+
+               [Test]
+               public void EmptyTypeArguments2 ()
+               {
+                       var t1 = new XamlType ("System", "Int32", null, sctx);
+                       var t2 = new XamlType ("System", "Int32", new XamlType [0], sctx);
+                       Assert.IsNull (t1.TypeArguments, "#1");
+                       Assert.IsNull (t2.TypeArguments, "#2");
+                       Assert.IsTrue (t1 == t2, "#3");
+                       Assert.IsTrue (t1.Equals (t2), "#4");
+               }
+
+               [Test]
+               public void EqualityAcrossConstructors ()
+               {
+                       var t1 = new XamlType (typeof (int), sctx);
+                       var t2 = new XamlType (t1.PreferredXamlNamespace, t1.Name, null, sctx);
+                       // not sure if it always returns false for different .ctor comparisons...
+                       Assert.IsFalse (t1 == t2, "#3");
+               }
+
+               [Test]
+               public void ArrayAndCollection ()
+               {
+                       var t = new XamlType (typeof (int), sctx);
+                       Assert.IsFalse (t.IsArray, "#1.1");
+                       Assert.IsFalse (t.IsCollection, "#1.2");
+                       Assert.IsNull (t.ItemType, "#1.3");
+                       t = new XamlType (typeof (ArrayList), sctx);
+                       Assert.IsFalse (t.IsArray, "#2.1");
+                       Assert.IsTrue (t.IsCollection, "#2.2");
+                       Assert.IsNotNull (t.ItemType, "#2.3");
+                       Assert.AreEqual ("Object", t.ItemType.Name, "#2.4");
+                       t = new XamlType (typeof (int []), sctx);
+                       Assert.IsTrue (t.IsArray, "#3.1");
+                       // why?
+                       Assert.IsFalse (t.IsCollection, "#3.2");
+                       Assert.IsNotNull (t.ItemType, "#3.3");
+                       Assert.AreEqual (typeof (int), t.ItemType.UnderlyingType, "#3.4");
+               }
+
+               [Test]
+               public void Dictionary ()
+               {
+                       var t = new XamlType (typeof (int), sctx);
+                       Assert.IsFalse (t.IsDictionary, "#1.1");
+                       Assert.IsFalse (t.IsCollection, "#1.1-2");
+                       Assert.IsNull (t.KeyType, "#1.2");
+                       t = new XamlType (typeof (Hashtable), sctx);
+                       Assert.IsTrue (t.IsDictionary, "#2.1");
+                       Assert.IsFalse (t.IsCollection, "#2.1-2");
+                       Assert.IsNotNull (t.KeyType, "#2.2");
+                       Assert.AreEqual ("Object", t.KeyType.Name, "#2.3");
+                       t = new XamlType (typeof (Dictionary<int,string>), sctx);
+                       Assert.IsTrue (t.IsDictionary, "#3.1");
+                       Assert.IsFalse (t.IsCollection, "#3.1-2");
+                       Assert.IsNotNull (t.KeyType, "#3.2");
+                       Assert.AreEqual ("Int32", t.KeyType.Name, "#3.3");
+               }
+
+               public class TestClass1
+               {
+               }
+       
+               class TestClass2
+               {
+                       internal TestClass2 () {}
+               }
+
+               [Test]
+               public void IsConstructible ()
+               {
+                       // ... is it?
+                       Assert.IsTrue (new XamlType (typeof (int), sctx).IsConstructible, "#1");
+                       // ... is it?
+                       Assert.IsFalse (new XamlType (typeof (TestClass1), sctx).IsConstructible, "#2");
+                       Assert.IsFalse (new XamlType (typeof (TestClass2), sctx).IsConstructible, "#3");
+                       Assert.IsTrue (new XamlType (typeof (object), sctx).IsConstructible, "#4");
+               }
+
+               class AttachableClass
+               {
+                       public event EventHandler<EventArgs> SimpleEvent;
+                       public void AddSimpleHandler (object o, EventHandler h)
+                       {
+                       }
+               }
+
+               // hmm, what can we use to verify this method?
+               [Test]
+               public void GetAllAttachableMembers ()
+               {
+                       var xt = new XamlType (typeof (AttachableClass), sctx);
+                       var l = xt.GetAllAttachableMembers ();
+                       Assert.AreEqual (0, l.Count, "#1");
+               }
+
+               [Test]
+               public void DefaultValuesType ()
+               {
+                       var t = new XamlType (typeof (int), sctx);
+                       Assert.IsNotNull (t.Invoker, "#1");
+                       Assert.IsTrue (t.IsNameValid, "#2");
+                       Assert.IsFalse (t.IsUnknown, "#3");
+                       Assert.AreEqual ("Int32", t.Name, "#4");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, t.PreferredXamlNamespace, "#5");
+                       Assert.IsNull (t.TypeArguments, "#6");
+                       Assert.AreEqual (typeof (int), t.UnderlyingType, "#7");
+                       Assert.IsFalse (t.ConstructionRequiresArguments, "#8");
+                       Assert.IsFalse (t.IsArray, "#9");
+                       Assert.IsFalse (t.IsCollection, "#10");
+                       Assert.IsTrue (t.IsConstructible, "#11");
+                       Assert.IsFalse (t.IsDictionary, "#12");
+                       Assert.IsFalse (t.IsGeneric, "#13");
+                       Assert.IsFalse (t.IsMarkupExtension, "#14");
+                       Assert.IsFalse (t.IsNameScope, "#15");
+                       Assert.IsFalse (t.IsNullable, "#16");
+                       Assert.IsTrue (t.IsPublic, "#17");
+                       Assert.IsFalse (t.IsUsableDuringInitialization, "#18");
+                       Assert.IsFalse (t.IsWhitespaceSignificantCollection, "#19");
+                       Assert.IsFalse (t.IsXData, "#20");
+                       Assert.IsFalse (t.TrimSurroundingWhitespace, "#21");
+                       Assert.IsFalse (t.IsAmbient, "#22");
+                       Assert.IsNull (t.AllowedContentTypes, "#23");
+                       Assert.IsNull (t.ContentWrappers, "#24");
+                       Assert.IsNotNull (t.TypeConverter, "#25");
+                       Assert.IsTrue (t.TypeConverter.ConverterInstance is Int32Converter, "#25-2");
+                       Assert.IsNull (t.ValueSerializer, "#26");
+                       Assert.IsNull (t.ContentProperty, "#27");
+                       //Assert.IsNull (t.DeferringLoader, "#28");
+                       Assert.IsNull (t.MarkupExtensionReturnType, "#29");
+                       Assert.AreEqual (sctx, t.SchemaContext, "#30");
+               }
+
+               [Test]
+               public void DefaultValuesType2 ()
+               {
+                       var t = new XamlType (typeof (Type), sctx);
+                       Assert.IsNotNull (t.Invoker, "#1");
+                       Assert.IsTrue (t.IsNameValid, "#2");
+                       Assert.IsFalse (t.IsUnknown, "#3");
+                       Assert.AreEqual ("Type", t.Name, "#4");
+                       // Note that Type is not a standard type. An instance of System.Type is usually represented as TypeExtension.
+                       Assert.AreEqual ("clr-namespace:System;assembly=mscorlib", t.PreferredXamlNamespace, "#5");
+                       Assert.IsNull (t.TypeArguments, "#6");
+                       Assert.AreEqual (typeof (Type), t.UnderlyingType, "#7");
+                       Assert.IsTrue (t.ConstructionRequiresArguments, "#8"); // yes, true.
+                       Assert.IsFalse (t.IsArray, "#9");
+                       Assert.IsFalse (t.IsCollection, "#10");
+                       Assert.IsFalse (t.IsConstructible, "#11"); // yes, false.
+                       Assert.IsFalse (t.IsDictionary, "#12");
+                       Assert.IsFalse (t.IsGeneric, "#13");
+                       Assert.IsFalse (t.IsMarkupExtension, "#14");
+                       Assert.IsFalse (t.IsNameScope, "#15");
+                       Assert.IsTrue (t.IsNullable, "#16");
+                       Assert.IsTrue (t.IsPublic, "#17");
+                       Assert.IsFalse (t.IsUsableDuringInitialization, "#18");
+                       Assert.IsFalse (t.IsWhitespaceSignificantCollection, "#19");
+                       Assert.IsFalse (t.IsXData, "#20");
+                       Assert.IsFalse (t.TrimSurroundingWhitespace, "#21");
+                       Assert.IsFalse (t.IsAmbient, "#22");
+                       Assert.IsNull (t.AllowedContentTypes, "#23");
+                       Assert.IsNull (t.ContentWrappers, "#24");
+                       // FIXME: enable this when we fixed TypeConverter for Type.
+                       //Assert.IsNotNull (t.TypeConverter, "#25"); // TypeTypeConverter
+                       Assert.IsNull (t.ValueSerializer, "#26");
+                       Assert.IsNull (t.ContentProperty, "#27");
+                       //Assert.IsNull (t.DeferringLoader, "#28");
+                       Assert.IsNull (t.MarkupExtensionReturnType, "#29");
+                       Assert.AreEqual (sctx, t.SchemaContext, "#30");
+               }
+
+               [Test]
+               public void DefaultValuesName ()
+               {
+                       var t = new XamlType ("urn:foo", ".", null, sctx);
+
+                       Assert.IsNotNull (t.Invoker, "#1");
+                       Assert.IsFalse (t.IsNameValid, "#2");
+                       Assert.IsTrue (t.IsUnknown, "#3");
+                       Assert.AreEqual (".", t.Name, "#4");
+                       Assert.AreEqual ("urn:foo", t.PreferredXamlNamespace, "#5");
+                       Assert.IsNull (t.TypeArguments, "#6");
+                       Assert.IsNull (t.UnderlyingType, "#7");
+                       Assert.IsFalse (t.ConstructionRequiresArguments, "#8");
+                       Assert.IsFalse (t.IsArray, "#9");
+                       Assert.IsFalse (t.IsCollection, "#10");
+                       Assert.IsTrue (t.IsConstructible, "#11");
+                       Assert.IsFalse (t.IsDictionary, "#12");
+                       Assert.IsFalse (t.IsGeneric, "#13");
+                       Assert.IsFalse (t.IsMarkupExtension, "#14");
+                       Assert.IsFalse (t.IsNameScope, "#15");
+                       Assert.IsTrue (t.IsNullable, "#16"); // different from int
+                       Assert.IsTrue (t.IsPublic, "#17");
+                       Assert.IsFalse (t.IsUsableDuringInitialization, "#18");
+                       Assert.IsTrue (t.IsWhitespaceSignificantCollection, "#19"); // somehow true ...
+                       Assert.IsFalse (t.IsXData, "#20");
+                       Assert.IsFalse (t.TrimSurroundingWhitespace, "#21");
+                       Assert.IsFalse (t.IsAmbient, "#22");
+                       Assert.IsNull (t.AllowedContentTypes, "#23");
+                       Assert.IsNull (t.ContentWrappers, "#24");
+                       Assert.IsNull (t.TypeConverter, "#25");
+                       Assert.IsNull (t.ValueSerializer, "#26");
+                       Assert.IsNull (t.ContentProperty, "#27");
+                       //Assert.IsNull (t.DeferringLoader, "#28");
+                       Assert.IsNull (t.MarkupExtensionReturnType, "#29");
+                       Assert.AreEqual (sctx, t.SchemaContext, "#30");
+               }
+
+               [Test]
+               public void DefaultValuesCustomType ()
+               {
+                       var t = new MyXamlType ("System.Int32", null, sctx);
+
+                       Assert.IsNotNull (t.Invoker, "#1");
+                       Assert.IsFalse (t.IsNameValid, "#2");
+                       Assert.IsTrue (t.IsUnknown, "#3");
+                       Assert.AreEqual ("System.Int32", t.Name, "#4");
+                       Assert.AreEqual (String.Empty, t.PreferredXamlNamespace, "#5");
+                       Assert.IsNull (t.TypeArguments, "#6");
+                       Assert.IsNull (t.UnderlyingType, "#7");
+                       Assert.IsFalse (t.ConstructionRequiresArguments, "#8");
+                       Assert.IsFalse (t.IsArray, "#9");
+                       Assert.IsFalse (t.IsCollection, "#10");
+                       Assert.IsTrue (t.IsConstructible, "#11");
+                       Assert.IsFalse (t.IsDictionary, "#12");
+                       Assert.IsFalse (t.IsGeneric, "#13");
+                       Assert.IsFalse (t.IsMarkupExtension, "#14");
+                       Assert.IsFalse (t.IsNameScope, "#15");
+                       Assert.IsTrue (t.IsNullable, "#16"); // different from int
+                       Assert.IsTrue (t.IsPublic, "#17");
+                       Assert.IsFalse (t.IsUsableDuringInitialization, "#18");
+                       Assert.IsTrue (t.IsWhitespaceSignificantCollection, "#19"); // somehow true ...
+                       Assert.IsFalse (t.IsXData, "#20");
+                       Assert.IsFalse (t.TrimSurroundingWhitespace, "#21");
+                       Assert.IsFalse (t.IsAmbient, "#22");
+                       Assert.IsNull (t.AllowedContentTypes, "#23");
+                       Assert.IsNull (t.ContentWrappers, "#24");
+                       Assert.IsNull (t.TypeConverter, "#25");
+                       Assert.IsNull (t.ValueSerializer, "#26");
+                       Assert.IsNull (t.ContentProperty, "#27");
+                       //Assert.IsNull (t.DeferringLoader, "#28");
+                       Assert.IsNull (t.MarkupExtensionReturnType, "#29");
+                       Assert.AreEqual (sctx, t.SchemaContext, "#30");
+               }
+
+               [Ambient]
+               [ContentProperty ("Name")]
+               [WhitespaceSignificantCollection]
+               [UsableDuringInitialization (true)]
+               public class TestClass3
+               {
+                       public TestClass3 (string name)
+                       {
+                               Name = name;
+                       }
+                       
+                       public string Name { get; set; }
+               }
+
+               [Test]
+               public void DefaultValuesSeverlyAttributed ()
+               {
+                       var t = new XamlType (typeof (TestClass3), sctx);
+                       Assert.IsNotNull (t.Invoker, "#1");
+                       Assert.IsFalse (t.IsNameValid, "#2"); // see #4
+                       Assert.IsFalse (t.IsUnknown, "#3");
+                       Assert.AreEqual ("XamlTypeTest+TestClass3", t.Name, "#4");
+                       Assert.AreEqual ("clr-namespace:MonoTests.System.Xaml;assembly=" + GetType ().Assembly.GetName ().Name, t.PreferredXamlNamespace, "#5");
+                       Assert.IsNull (t.TypeArguments, "#6");
+                       Assert.AreEqual (typeof (TestClass3), t.UnderlyingType, "#7");
+                       Assert.IsTrue (t.ConstructionRequiresArguments, "#8");
+                       Assert.IsFalse (t.IsArray, "#9");
+                       Assert.IsFalse (t.IsCollection, "#10");
+                       Assert.IsFalse (t.IsConstructible, "#11");
+                       Assert.IsFalse (t.IsDictionary, "#12");
+                       Assert.IsFalse (t.IsGeneric, "#13");
+                       Assert.IsFalse (t.IsMarkupExtension, "#14");
+                       Assert.IsFalse (t.IsNameScope, "#15");
+                       Assert.IsTrue (t.IsNullable, "#16");
+                       Assert.IsTrue (t.IsPublic, "#17");
+                       Assert.IsTrue (t.IsUsableDuringInitialization, "#18");
+                       Assert.IsTrue (t.IsWhitespaceSignificantCollection, "#19");
+                       Assert.IsFalse (t.IsXData, "#20");
+                       Assert.IsFalse (t.TrimSurroundingWhitespace, "#21");
+                       Assert.IsTrue (t.IsAmbient, "#22");
+                       Assert.IsNull (t.AllowedContentTypes, "#23");
+                       Assert.IsNull (t.ContentWrappers, "#24");
+                       Assert.IsNull (t.TypeConverter, "#25");
+                       Assert.IsNull (t.ValueSerializer, "#26");
+                       Assert.IsNotNull (t.ContentProperty, "#27");
+                       Assert.AreEqual ("Name", t.ContentProperty.Name, "#27-2");
+                       // Assert.IsNull (t.DeferringLoader, "#28");
+                       Assert.IsNull (t.MarkupExtensionReturnType, "#29");
+                       Assert.AreEqual (sctx, t.SchemaContext, "#30");
+               }
+
+               [Test]
+               public void TypeConverter ()
+               {
+                       Assert.IsNull (new XamlType (typeof (List<object>), sctx).TypeConverter, "#1");
+                       Assert.IsNotNull (new XamlType (typeof (object), sctx).TypeConverter, "#2");
+                       Assert.IsTrue (new XamlType (typeof (Uri), sctx).TypeConverter.ConverterInstance is UriTypeConverter, "#3");
+                       Assert.IsTrue (new XamlType (typeof (TimeSpan), sctx).TypeConverter.ConverterInstance is TimeSpanConverter, "#4");
+                       Assert.IsNull (new XamlType (typeof (XamlType), sctx).TypeConverter, "#5");
+                       Assert.IsTrue (new XamlType (typeof (char), sctx).TypeConverter.ConverterInstance is CharConverter, "#6");
+               }
+               
+               [Test]
+               public void TypeConverter_Type ()
+               {
+                       TypeConveter_TypeOrTypeExtension (typeof (Type));
+               }
+               
+               [Test]
+               public void TypeConverter_TypeExtension ()
+               {
+                       TypeConveter_TypeOrTypeExtension (typeof (TypeExtension));
+               }
+               
+               void TypeConveter_TypeOrTypeExtension (Type type)
+               {
+                       var xtc = new XamlType (type, sctx).TypeConverter;
+                       Assert.IsNotNull (xtc, "#7");
+                       var tc = xtc.ConverterInstance;
+                       Assert.IsNotNull (tc, "#7-2");
+                       Assert.IsFalse (tc.CanConvertTo (typeof (Type)), "#7-3");
+                       Assert.IsFalse (tc.CanConvertTo (typeof (XamlType)), "#7-4");
+                       Assert.IsTrue (tc.CanConvertTo (typeof (string)), "#7-5");
+                       Assert.AreEqual ("{http://schemas.microsoft.com/winfx/2006/xaml}TypeExtension", tc.ConvertToString (XamlLanguage.Type), "#7-6");
+                       Assert.IsFalse (tc.CanConvertFrom (typeof (Type)), "#7-7");
+                       Assert.IsFalse (tc.CanConvertFrom (typeof (XamlType)), "#7-8");
+                       // .NET returns true for type == typeof(Type) case here, which does not make sense. Disabling it now.
+                       //Assert.IsFalse (tc.CanConvertFrom (typeof (string)), "#7-9");
+                       try {
+                               tc.ConvertFromString ("{http://schemas.microsoft.com/winfx/2006/xaml}TypeExtension");
+                               Assert.Fail ("failure");
+                       } catch (NotSupportedException) {
+                       }
+               }
+
+               [Test]
+               [Category ("NotWorking")]
+               public void GetXamlNamespaces ()
+               {
+                       var xt = new XamlType (typeof (string), new XamlSchemaContext (null, null));
+                       var l = xt.GetXamlNamespaces ();
+                       Assert.AreEqual (2, l.Count, "#1");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, l [0], "#2");
+                       Assert.AreEqual ("clr-namespace:System;assembly=mscorlib", l [1], "#3");
+               }
+               
+               [Test]
+               public void GetAliasedProperty ()
+               {
+                       XamlMember xm;
+                       var xt = new XamlType (typeof (SeverlyAliasedClass), new XamlSchemaContext (null, null));
+                       xm = xt.GetAliasedProperty (XamlLanguage.Key);
+                       Assert.IsNotNull (xm, "#1");
+                       xm = xt.GetAliasedProperty (XamlLanguage.Name);
+                       Assert.IsNotNull (xm, "#2");
+                       xm = xt.GetAliasedProperty (XamlLanguage.Uid);
+                       Assert.IsNotNull (xm, "#3");
+                       xm = xt.GetAliasedProperty (XamlLanguage.Lang);
+                       Assert.IsNotNull (xm, "#4");
+               }
+
+               [Test]
+               public void GetAliasedPropertyOnAllTypes ()
+               {
+                       foreach (var xt in XamlLanguage.AllTypes)
+                               foreach (var xd in XamlLanguage.AllDirectives)
+                                       Assert.IsNull (xt.GetAliasedProperty (xd), xt.Name + " and " + xd.Name);
+               }
+
+               [DictionaryKeyProperty ("Key")]
+               [RuntimeNameProperty ("RuntimeTypeName")]
+               [UidProperty ("UUID")]
+               [XmlLangProperty ("XmlLang")]
+               public class SeverlyAliasedClass
+               {
+                       public string Key { get; set; }
+                       public string RuntimeTypeName { get; set; }
+                       public string UUID { get; set; }
+                       public string XmlLang { get; set; }
+               }
+
+               [Test]
+               public void ToStringTest ()
+               {
+                       Assert.AreEqual ("{http://schemas.microsoft.com/winfx/2006/xaml}String", XamlLanguage.String.ToString (), "#1");
+                       Assert.AreEqual ("{http://schemas.microsoft.com/winfx/2006/xaml}TypeExtension", XamlLanguage.Type.ToString (), "#2");
+                       Assert.AreEqual ("{http://schemas.microsoft.com/winfx/2006/xaml}ArrayExtension", XamlLanguage.Array.ToString (), "#3");
+               }
+
+               [Test]
+               public void GetPositionalParameters ()
+               {
+                       IList<XamlType> l;
+                       l = XamlLanguage.Type.GetPositionalParameters (1);
+                       Assert.IsNotNull (l, "#1");
+                       Assert.AreEqual (1, l.Count, "#2");
+                       Assert.AreEqual (typeof (Type), l [0].UnderlyingType, "#3"); // not TypeExtension but Type.
+                       Assert.AreEqual ("Type", l [0].Name, "#4");
+               }
+
+               [Test]
+               public void GetPositionalParametersWrongCount ()
+               {
+                       Assert.IsNull (XamlLanguage.Type.GetPositionalParameters (2), "#1");
+               }
+
+               [Test]
+               public void GetPositionalParametersNoMemberExtension ()
+               {
+                       // wow, so it returns some meaningless method parameters.
+                       Assert.IsNotNull (new XamlType (typeof (MyXamlType), sctx).GetPositionalParameters (3), "#1");
+               }
+       }
+
+       class MyXamlType : XamlType
+       {
+               public MyXamlType (string fullName, IList<XamlType> typeArguments, XamlSchemaContext context)
+                       : base (fullName, typeArguments, context)
+               {
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlXmlReaderSettingsTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlXmlReaderSettingsTest.cs
new file mode 100644 (file)
index 0000000..044c1e3
--- /dev/null
@@ -0,0 +1,70 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Xaml;
+using System.Xaml.Schema;
+using NUnit.Framework;
+
+namespace MonoTests.System.Xaml
+{
+       [TestFixture]
+       public class XamlXmlReaderSettingsTest
+       {
+               [Test]
+               public void DefaultValues ()
+               {
+                       var s = new XamlXmlReaderSettings ();
+                       Assert.IsFalse (s.CloseInput, "#1");
+                       Assert.IsFalse (s.SkipXmlCompatibilityProcessing, "#2");
+                       Assert.IsNull (s.XmlLang, "#3");
+                       Assert.IsFalse (s.XmlSpacePreserve, "#4");
+               }
+
+               [Test]
+               public void CopyConstructorNull ()
+               {
+                       new XamlXmlReaderSettings (null);
+               }
+
+               [Test]
+               public void CopyConstructor ()
+               {
+                       var s = new XamlXmlReaderSettings ();
+                       s.CloseInput = true;
+                       s.SkipXmlCompatibilityProcessing = true;
+                       s.XmlLang = "ja-JP";
+                       s.XmlSpacePreserve = true;
+
+                       s = new XamlXmlReaderSettings (s);
+
+                       // .NET fails to copy this value.
+                       //Assert.IsTrue (s.CloseInput, "#1");
+                       Assert.IsTrue (s.SkipXmlCompatibilityProcessing, "#2");
+                       Assert.AreEqual ("ja-JP", s.XmlLang, "#3");
+                       Assert.IsTrue (s.XmlSpacePreserve, "#4");
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlXmlReaderTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlXmlReaderTest.cs
new file mode 100644 (file)
index 0000000..ce9ab01
--- /dev/null
@@ -0,0 +1,330 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml;
+using System.Xaml.Schema;
+using System.Xml;
+using NUnit.Framework;
+
+using Category = NUnit.Framework.CategoryAttribute;
+
+namespace MonoTests.System.Xaml
+{
+       [TestFixture]
+       public class XamlXmlReaderTest
+       {
+
+               // read test
+
+               XamlReader GetReader (string filename)
+               {
+                       return new XamlXmlReader (XmlReader.Create (Path.Combine ("Test/XmlFiles", filename), new XmlReaderSettings () { CloseInput =true }));
+               }
+
+               void ReadTest (string filename)
+               {
+                       var r = GetReader (filename);
+                       while (!r.IsEof)
+                               r.Read ();
+               }
+
+               void LoadTest (string filename, Type type)
+               {
+                       var obj = XamlServices.Load (GetReader (filename));
+                       Assert.AreEqual (type, obj.GetType (), "type");
+               }
+
+               [Test]
+               public void Read_String ()
+               {
+                       ReadTest ("String.xml");
+                       //LoadTest ("String.xml", typeof (string));
+               }
+
+               [Test]
+               public void Read_Int32 ()
+               {
+                       ReadTest ("Int32.xml");
+                       //LoadTest ("Int32.xml", typeof (int));
+               }
+
+               [Test]
+               public void Read_DateTime ()
+               {
+                       ReadTest ("DateTime.xml");
+                       //LoadTest ("DateTime.xml", typeof (DateTime));
+               }
+
+               [Test]
+               public void Read_TimeSpan ()
+               {
+                       ReadTest ("TimeSpan.xml");
+                       //LoadTest ("TimeSpan.xml", typeof (TimeSpan));
+               }
+
+               [Test]
+               public void Read_ArrayInt32 ()
+               {
+                       ReadTest ("Array_Int32.xml");
+                       //LoadTest ("Array_Int32.xml", typeof (int []));
+               }
+
+               [Test]
+               public void Read_ListInt32 ()
+               {
+                       ReadTest ("List_Int32.xml");
+                       //LoadTest ("List_Int32.xml", typeof (List<int>));
+               }
+
+               [Test]
+               [Category ("NotWorking")]
+               public void Read_DictionaryInt32String ()
+               {
+                       ReadTest ("Dictionary_Int32_String.xml");
+                       //LoadTest ("Dictionary_Int32_String.xml", typeof (Dictionary<int,string>));
+               }
+
+               [Test]
+               [Category ("NotWorking")]
+               public void Read_DictionaryStringType ()
+               {
+                       ReadTest ("Dictionary_String_Type.xml");
+                       //LoadTest ("Dictionary_String_Type.xml", typeof (Dictionary<string,Type>));
+               }
+
+               [Test]
+               public void Read1 ()
+               {
+                       var r = GetReader ("Int32.xml");
+
+                       Assert.IsTrue (r.Read (), "ns#1");
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#2");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "ns#3");
+
+                       Assert.IsTrue (r.Read (), "so#1");
+                       Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#2");
+                       Assert.AreEqual (XamlLanguage.Int32, r.Type, "so#3");
+
+                       Assert.IsTrue (r.Read (), "sbase#1");
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sbase#2");
+                       Assert.AreEqual (XamlLanguage.Base, r.Member, "sbase#3");
+
+                       Assert.IsTrue (r.Read (), "vbase#1");
+                       Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vbase#2");
+                       Assert.IsTrue (r.Value is string, "vbase#3");
+
+                       Assert.IsTrue (r.Read (), "ebase#1");
+                       Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "ebase#2");
+
+                       Assert.IsTrue (r.Read (), "sinit#1");
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sinit#2");
+                       Assert.AreEqual (XamlLanguage.Initialization, r.Member, "sinit#3");
+
+                       Assert.IsTrue (r.Read (), "vinit#1");
+                       Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vinit#2");
+                       Assert.AreEqual ("5", r.Value, "vinit#3"); // string
+
+                       Assert.IsTrue (r.Read (), "einit#1");
+                       Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "einit#2");
+
+                       Assert.IsTrue (r.Read (), "eo#1");
+                       Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#2");
+
+                       Assert.IsFalse (r.Read (), "end");
+               }
+
+               [Test]
+               public void Read2 ()
+               {
+                       var r = GetReader ("DateTime.xml");
+
+                       Assert.IsTrue (r.Read (), "ns#1");
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#2");
+                       Assert.AreEqual ("clr-namespace:System;assembly=mscorlib", r.Namespace.Namespace, "ns#3");
+
+                       Assert.IsTrue (r.Read (), "so#1");
+                       Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#2");
+                       Assert.AreEqual (r.SchemaContext.GetXamlType (typeof (DateTime)), r.Type, "so#3");
+
+                       Assert.IsTrue (r.Read (), "sbase#1");
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sbase#2");
+                       Assert.AreEqual (XamlLanguage.Base, r.Member, "sbase#3");
+
+                       Assert.IsTrue (r.Read (), "vbase#1");
+                       Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vbase#2");
+                       Assert.IsTrue (r.Value is string, "vbase#3");
+
+                       Assert.IsTrue (r.Read (), "ebase#21");
+
+                       Assert.IsTrue (r.Read (), "sinit#1");
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sinit#2");
+                       Assert.AreEqual (XamlLanguage.Initialization, r.Member, "sinit#3");
+
+                       Assert.IsTrue (r.Read (), "vinit#1");
+                       Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vinit#2");
+                       Assert.AreEqual ("2010-04-14", r.Value, "vinit#3"); // string
+
+                       Assert.IsTrue (r.Read (), "einit#1");
+                       Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "einit#2");
+
+                       Assert.IsTrue (r.Read (), "eo#1");
+                       Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#2");
+                       Assert.IsFalse (r.Read (), "end");
+               }
+
+               [Test]
+               public void Read3 ()
+               {
+                       var r = GetReader ("Type.xml");
+
+                       Assert.IsTrue (r.Read (), "ns#1");
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#2");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "ns#3");
+
+                       Assert.IsTrue (r.Read (), "so#1");
+                       Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#2");
+                       Assert.AreEqual (XamlLanguage.Type, r.Type, "so#3");
+
+                       Assert.IsTrue (r.Read (), "sbase#1");
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sbase#2");
+                       Assert.AreEqual (XamlLanguage.Base, r.Member, "sbase#3");
+
+                       Assert.IsTrue (r.Read (), "vbase#1");
+                       Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vbase#2");
+                       Assert.IsTrue (r.Value is string, "vbase#3");
+
+                       Assert.IsTrue (r.Read (), "ebase#1");
+                       Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "ebase#2");
+
+                       Assert.IsTrue (r.Read (), "sinit#1");
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sinit#2");
+                       // FIXME: They are identical on .NET.
+                       // They aren't on mono, every GetMember() returns different object
+                       // (it is the same as .NET; see XamlMemberTest.EqualsTest.) 
+                       // and XamlMember is almost non-comparable unless they
+                       // are identical, so we fail here.
+                       Assert.AreEqual (XamlLanguage.Type.GetMember ("Type").ToString (), r.Member.ToString (), "sinit#3");
+                       //Assert.AreEqual (XamlLanguage.Type.GetMember ("Type"), r.Member, "sinit#3-2");
+                       //Assert.IsTrue (Object.ReferenceEquals (XamlLanguage.Type.GetMember ("Type"), r.Member), "sinit#3-3");
+
+                       Assert.IsTrue (r.Read (), "vinit#1");
+                       Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vinit#2");
+                       Assert.AreEqual ("x:Int32", r.Value, "vinit#3"); // string
+
+                       Assert.IsTrue (r.Read (), "einit#1");
+                       Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "einit#2");
+
+                       Assert.IsTrue (r.Read (), "eo#1");
+                       Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#2");
+
+                       Assert.IsFalse (r.Read (), "end");
+               }
+
+               [Test]
+               [Category ("NotWorking")]
+               public void Read4 ()
+               {
+                       var r = GetReader ("List_Int32.xml");
+
+                       Assert.IsTrue (r.Read (), "ns#1");
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns#2");
+                       Assert.AreEqual ("clr-namespace:System.Collections.Generic;assembly=mscorlib", r.Namespace.Namespace, "ns#3");
+                       Assert.AreEqual (String.Empty, r.Namespace.Prefix, "ns#4");
+
+                       Assert.IsTrue (r.Read (), "ns2#1");
+                       Assert.AreEqual (XamlNodeType.NamespaceDeclaration, r.NodeType, "ns2#2");
+                       Assert.AreEqual (XamlLanguage.Xaml2006Namespace, r.Namespace.Namespace, "ns2#3");
+                       Assert.AreEqual ("x", r.Namespace.Prefix, "ns2#4");
+
+                       Assert.IsTrue (r.Read (), "so#1");
+                       Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "so#2");
+                       var xt = new XamlType (typeof (List<int>), r.SchemaContext);
+                       Assert.AreEqual (xt, r.Type, "so#3");
+
+                       Assert.IsTrue (r.Read (), "sbase#1");
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sbase#2");
+                       Assert.AreEqual (XamlLanguage.Base, r.Member, "sbase#3");
+
+                       Assert.IsTrue (r.Read (), "vbase#1");
+                       Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vbase#2");
+                       Assert.IsTrue (r.Value is string, "vbase#3");
+
+                       Assert.IsTrue (r.Read (), "ebase#1");
+                       Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "ebase#2");
+
+                       Assert.IsTrue (r.Read (), "scap#1");
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "scap#2");
+                       Assert.AreEqual (xt.GetMember ("Capacity"), r.Member, "scap#3");
+
+                       Assert.IsTrue (r.Read (), "vcap#1");
+                       Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vcap#2");
+                       Assert.AreEqual ("5", r.Value, "vcap#3"); // string
+
+                       Assert.IsTrue (r.Read (), "ecap#1");
+                       Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "ecap#2");
+
+                       Assert.IsTrue (r.Read (), "sItems#1");
+                       Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sItems#2");
+                       Assert.AreEqual (XamlLanguage.Items, r.Member, "sItems#3");
+
+                       int [] values = {4, -5, 0, 255, int.MaxValue};
+                       var ci = new CultureInfo ("en-US");
+
+                       for (int i = 0; i < 5; i++) {
+                               Assert.IsTrue (r.Read (), "soItem#1." + i);
+                               Assert.AreEqual (XamlNodeType.StartObject, r.NodeType, "soItem#2." + i);
+                               Assert.AreEqual (XamlLanguage.Int32, r.Type, "soItem#3." + i);
+
+                               Assert.IsTrue (r.Read (), "sItem#1." + i);
+                               Assert.AreEqual (XamlNodeType.StartMember, r.NodeType, "sItem#2." + i);
+                               Assert.AreEqual (XamlLanguage.Initialization, r.Member, "sItem#3." + i);
+
+                               Assert.IsTrue (r.Read (), "vItem#1." + i);
+                               Assert.AreEqual (XamlNodeType.Value, r.NodeType, "vItem#2." + i);
+                               Assert.AreEqual (values [i].ToString (ci), r.Value, "vItem#3." + i);
+
+                               Assert.IsTrue (r.Read (), "eItem#1." + i);
+                               Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "eItem#2." + i);
+
+                               Assert.IsTrue (r.Read (), "eoItem#1");
+                               Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eoItem#2");
+                       }
+
+                       Assert.IsTrue (r.Read (), "eItems#1");
+                       Assert.AreEqual (XamlNodeType.EndMember, r.NodeType, "eItems#2");
+
+                       Assert.IsTrue (r.Read (), "eo#1");
+                       Assert.AreEqual (XamlNodeType.EndObject, r.NodeType, "eo#2");
+
+                       Assert.IsFalse (r.Read (), "end");
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlXmlWriterSettingsTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlXmlWriterSettingsTest.cs
new file mode 100644 (file)
index 0000000..087321a
--- /dev/null
@@ -0,0 +1,44 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Xaml;
+using System.Xaml.Schema;
+using NUnit.Framework;
+
+namespace MonoTests.System.Xaml
+{
+       [TestFixture]
+       public class XamlXmlWriterSettingsTest
+       {
+               [Test]
+               public void DefaultValues ()
+               {
+                       var s = new XamlXmlWriterSettings ();
+                       Assert.IsFalse (s.AssumeValidInput, "#1");
+                       Assert.IsFalse (s.CloseOutput, "#2");
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/System.Xaml/XamlXmlWriterTest.cs b/mcs/class/System.Xaml/Test/System.Xaml/XamlXmlWriterTest.cs
new file mode 100644 (file)
index 0000000..5d20e1b
--- /dev/null
@@ -0,0 +1,610 @@
+//
+// Copyright (C) 2010 Novell Inc. http://novell.com
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.IO;
+using System.Reflection;
+using System.Windows.Markup;
+using System.Xaml;
+using System.Xaml.Schema;
+using NUnit.Framework;
+
+using Category = NUnit.Framework.CategoryAttribute;
+
+namespace MonoTests.System.Xaml
+{
+       [TestFixture]
+       public class XamlXmlWriterTest
+       {
+               PropertyInfo str_len = typeof (string).GetProperty ("Length");
+               XamlSchemaContext sctx = new XamlSchemaContext (null, null);
+               XamlType xt, xt2;
+               XamlMember xm;
+
+               public XamlXmlWriterTest ()
+               {
+                       xt = new XamlType (typeof (string), sctx);
+                       xt2 = new XamlType (typeof (List<int>), sctx);
+                       xm = new XamlMember (str_len, sctx);
+               }
+
+               public class Foo : List<int>
+               {
+                       public List<string> Bar { get; set; }
+               }
+               
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void SchemaContextNull ()
+               {
+                       new XamlXmlWriter (new MemoryStream (), null);
+               }
+
+               [Test]
+               public void SettingsNull ()
+               {
+                       // allowed.
+                       var w = new XamlXmlWriter (new MemoryStream (), sctx, null);
+                       Assert.AreEqual (sctx, w.SchemaContext, "#1");
+                       Assert.IsNotNull (w.Settings, "#2");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               public void InitWriteEndMember ()
+               {
+                       new XamlXmlWriter (new MemoryStream (), sctx, null).WriteEndMember ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               public void InitWriteEndObject ()
+               {
+                       new XamlXmlWriter (new MemoryStream (), sctx, null).WriteEndObject ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               public void InitWriteGetObject ()
+               {
+                       new XamlXmlWriter (new MemoryStream (), sctx, null).WriteGetObject ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               public void InitWriteValue ()
+               {
+                       new XamlXmlWriter (new StringWriter (), sctx, null).WriteValue ("foo");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               public void InitWriteStartMember ()
+               {
+                       new XamlXmlWriter (new StringWriter (), sctx, null).WriteStartMember (new XamlMember (str_len, sctx));
+               }
+
+               [Test]
+               public void InitWriteNamespace ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteNamespace (new NamespaceDeclaration ("urn:foo", "x")); // ignored.
+                       xw.Close ();
+                       Assert.AreEqual ("", sw.ToString (), "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void WriteNamespaceNull ()
+               {
+                       new XamlXmlWriter (new StringWriter (), sctx, null).WriteNamespace (null);
+               }
+
+               [Test]
+               public void InitWriteStartObject ()
+               {
+                       string xml = @"<?xml version='1.0' encoding='utf-16'?><Int32 xmlns='http://schemas.microsoft.com/winfx/2006/xaml' />";
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (new XamlType (typeof (int), sctx));
+                       xw.Close ();
+                       Assert.AreEqual (xml, sw.ToString ().Replace ('"', '\''), "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               public void GetObjectAfterStartObject ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteGetObject ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               public void WriteStartObjectAfterTopLevel ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteEndObject ();
+                       // writing another root is not allowed.
+                       xw.WriteStartObject (xt);
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               public void WriteEndObjectExcess ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteEndObject ();
+                       xw.WriteEndObject ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               public void StartObjectWriteEndMember ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteEndMember ();
+               }
+
+               [Test]
+               public void WriteObjectAndMember ()
+               {
+                       string xml = @"<?xml version='1.0' encoding='utf-16'?><String Length='foo' xmlns='http://schemas.microsoft.com/winfx/2006/xaml' />";
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartMember (xm);
+                       xw.WriteValue ("foo");
+                       xw.WriteEndMember ();
+                       xw.Close ();
+                       Assert.AreEqual (xml, sw.ToString ().Replace ('"', '\''), "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               public void StartMemberWriteEndMember ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartMember (xm);
+                       xw.WriteEndMember (); // wow, really?
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               public void StartMemberWriteStartMember ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartMember (xm);
+                       xw.WriteStartMember (xm);
+               }
+
+               [Test]
+               public void WriteObjectInsideMember ()
+               {
+                       string xml = @"<?xml version='1.0' encoding='utf-16'?><String xmlns='http://schemas.microsoft.com/winfx/2006/xaml'><String.Length><String /></String.Length></String>";
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartMember (xm);
+                       xw.WriteStartObject (xt);
+                       xw.WriteEndObject ();
+                       xw.WriteEndMember ();
+                       xw.Close ();
+                       Assert.AreEqual (xml, sw.ToString ().Replace ('"', '\''), "#1");
+               }
+
+               [Test]
+               public void ValueAfterObject ()
+               {
+                       string xml = @"<?xml version='1.0' encoding='utf-16'?><String xmlns='http://schemas.microsoft.com/winfx/2006/xaml'><String.Length><String />foo</String.Length></String>";
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartMember (xm);
+                       xw.WriteStartObject (xt);
+                       xw.WriteEndObject ();
+                       // allowed.
+                       xw.WriteValue ("foo");
+                       xw.WriteEndMember ();
+                       xw.Close ();
+                       Assert.AreEqual (xml, sw.ToString ().Replace ('"', '\''), "#1");
+               }
+
+               [Test]
+               public void ValueAfterObject2 ()
+               {
+                       string xml = @"<?xml version='1.0' encoding='utf-16'?><String xmlns='http://schemas.microsoft.com/winfx/2006/xaml'><String.Length>foo<String />foo</String.Length></String>";
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartMember (xm);
+                       xw.WriteValue ("foo");
+                       xw.WriteStartObject (xt);
+                       xw.WriteEndObject ();
+                       // allowed.
+                       xw.WriteValue ("foo");
+                       xw.WriteEndMember ();
+                       xw.Close ();
+                       Assert.AreEqual (xml, sw.ToString ().Replace ('"', '\''), "#1");
+               }
+
+               [Test]
+               public void ValueAfterObject3 ()
+               {
+                       string xml = @"<?xml version='1.0' encoding='utf-16'?><String xmlns='http://schemas.microsoft.com/winfx/2006/xaml'><String.Length><String />foo<String />foo</String.Length></String>";
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartMember (xm);
+                       xw.WriteStartObject (xt);
+                       xw.WriteEndObject ();
+                       xw.WriteValue ("foo");
+                       xw.WriteStartObject (xt);
+                       xw.WriteEndObject ();
+                       xw.WriteValue ("foo");
+                       xw.WriteEndMember ();
+                       xw.Close ();
+                       Assert.AreEqual (xml, sw.ToString ().Replace ('"', '\''), "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentException))]
+               public void WriteValueTypeMismatch ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartMember (xm);
+                       xw.WriteValue (5);
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               public void WriteValueAfterValue ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteValue ("foo");
+                       xw.WriteValue ("bar");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               public void WriteValueAfterNullValue ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteValue (null);
+                       xw.WriteValue ("bar");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               [Category ("NotWorking")] // it raises ArgumentException earlier, which should not matter.
+               public void WriteValueList ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (new XamlType (typeof (List<string>), sctx));
+                       xw.WriteStartMember (XamlLanguage.Items);
+                       xw.WriteValue ("foo");
+                       xw.WriteValue ("bar");
+               }
+
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               public void StartMemberWriteEndObject ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartMember (xm);
+                       xw.WriteEndObject ();
+               }
+
+               [Test]
+               public void WriteNamespace ()
+               {
+                       string xml = @"<?xml version='1.0' encoding='utf-16'?><x:String xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' xmlns:y='urn:foo' />";
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteNamespace (new NamespaceDeclaration (XamlLanguage.Xaml2006Namespace, "x"));
+                       xw.WriteNamespace (new NamespaceDeclaration ("urn:foo", "y"));
+                       xw.WriteStartObject (xt);
+                       xw.WriteEndObject ();
+                       xw.Close ();
+                       Assert.AreEqual (xml, sw.ToString ().Replace ('"', '\''), "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               public void StartObjectStartObject ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartObject (xt);
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               public void StartObjectValue ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteValue ("foo");
+               }
+
+               [Test]
+               public void ObjectThenNamespaceThenObjectThenObject ()
+               {
+                       string xml = @"<?xml version='1.0' encoding='utf-16'?><String xmlns='http://schemas.microsoft.com/winfx/2006/xaml'><String.Length><String /><String /></String.Length></String>";
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt); // <String>
+                       xw.WriteStartMember (xm); // <String.Length>
+                       xw.WriteStartObject (xt); // <String />
+                       xw.WriteEndObject ();
+                       xw.WriteStartObject (xt); // <String />
+                       xw.WriteEndObject ();
+                       xw.Close ();
+                       Assert.AreEqual (xml, sw.ToString ().Replace ('"', '\''), "#1");
+               }
+
+               // This doesn't result in XamlXmlWriterException. Instead,
+               // IOE is thrown. WriteValueAfterNamespace() too.
+               // It is probably because namespaces are verified independently
+               // from state transition (and borks when the next write is not
+               // appropriate).
+               [Test]
+               [ExpectedException (typeof (InvalidOperationException))]
+               public void EndObjectAfterNamespace ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteNamespace (new NamespaceDeclaration ("urn:foo", "y"));
+                       xw.WriteEndObject ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (InvalidOperationException))] // ... shouldn't it be XamlXmlWriterException?
+               public void WriteValueAfterNamespace ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartMember (XamlLanguage.Initialization);
+                       xw.WriteNamespace (new NamespaceDeclaration ("urn:foo", "y"));
+                       xw.WriteValue ("foo");
+               }
+
+               [Test]
+               public void ValueThenStartObject ()
+               {
+                       string xml = @"<?xml version='1.0' encoding='utf-16'?><String xmlns='http://schemas.microsoft.com/winfx/2006/xaml'><String.Length>foo<String /></String.Length></String>";
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartMember (xm);
+                       xw.WriteValue ("foo");
+                       xw.WriteStartObject (xt);
+                       xw.Close ();
+                       Assert.AreEqual (xml, sw.ToString ().Replace ('"', '\''), "#1");
+               }
+
+               [Test]
+               public void ValueThenNamespace ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartMember (xm);
+                       xw.WriteValue ("foo");
+                       xw.WriteNamespace (new NamespaceDeclaration ("y", "urn:foo")); // this does not raise an error (since it might start another object)
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))] // strange, this does *not* result in IOE...
+               public void ValueThenNamespaceThenEndMember ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartMember (xm);
+                       xw.WriteValue ("foo");
+                       xw.WriteNamespace (new NamespaceDeclaration ("y", "urn:foo"));
+                       xw.WriteEndMember ();
+               }
+
+               [Test]
+               public void StartMemberAfterNamespace ()
+               {
+                       // This test shows:
+                       // 1) StartMember after NamespaceDeclaration is valid
+                       // 2) Member is written as an element (not attribute)
+                       //    if there is a NamespaceDeclaration in the middle.
+                       string xml = @"<?xml version='1.0' encoding='utf-16'?><String xmlns='http://schemas.microsoft.com/winfx/2006/xaml'><String.Length xmlns:y='urn:foo'>foo</String.Length></String>";
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteNamespace (new NamespaceDeclaration ("urn:foo", "y"));
+                       xw.WriteStartMember (xm);
+                       xw.WriteValue ("foo");
+                       xw.Close ();
+                       Assert.AreEqual (xml, sw.ToString ().Replace ('"', '\''), "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               public void EndMemberThenStartObject ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartMember (xm);
+                       xw.WriteValue ("foo");
+                       xw.WriteEndMember ();
+                       xw.WriteStartObject (xt);
+               }
+
+               [Test]
+               [ExpectedException (typeof (InvalidOperationException))]
+               public void GetObjectOnNonCollection ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartMember (xm);
+                       xw.WriteGetObject ();
+               }
+
+               [Test]
+               [ExpectedException (typeof (InvalidOperationException))]
+               public void GetObjectOnNonCollection2 ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt);
+                       xw.WriteStartMember (new XamlMember (typeof (string).GetProperty ("Length"), sctx)); // Length is of type int, which is not a collection
+                       xw.WriteGetObject ();
+               }
+
+               [Test]
+               public void GetObjectOnCollection ()
+               {
+                       string xml = @"<?xml version='1.0' encoding='utf-16'?><List xmlns='clr-namespace:System.Collections.Generic;assembly=mscorlib'><x:TypeArguments xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>x:Int32</x:TypeArguments><List.Bar /></List>";
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt2);
+                       xw.WriteStartMember (new XamlMember (typeof (Foo).GetProperty ("Bar"), sctx));
+                       xw.WriteGetObject ();
+                       xw.Close ();
+                       // FIXME: enable it once we got generic type output fixed.
+                       //Assert.AreEqual (xml, sw.ToString ().Replace ('"', '\''), "#1");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               public void ValueAfterGetObject ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt2);
+                       xw.WriteStartMember (new XamlMember (typeof (Foo).GetProperty ("Bar"), sctx));
+                       xw.WriteGetObject ();
+                       xw.WriteValue ("foo");
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               public void StartObjectAfterGetObject ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt2);
+                       xw.WriteStartMember (new XamlMember (typeof (Foo).GetProperty ("Bar"), sctx));
+                       xw.WriteGetObject ();
+                       xw.WriteStartObject (xt);
+               }
+
+               [Test]
+               [ExpectedException (typeof (XamlXmlWriterException))]
+               public void EndMemberAfterGetObject ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt2);
+                       xw.WriteStartMember (new XamlMember (typeof (Foo).GetProperty ("Bar"), sctx));
+                       xw.WriteGetObject ();
+                       xw.WriteEndMember (); // ...!?
+               }
+
+               [Test]
+               public void StartMemberAfterGetObject ()
+               {
+                       string xml = @"<?xml version='1.0' encoding='utf-16'?><List xmlns='clr-namespace:System.Collections.Generic;assembly=mscorlib'><x:TypeArguments xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>x:Int32</x:TypeArguments><List.Bar><List.Length /></List.Bar></List>";
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt2); // <List
+                       xw.WriteStartMember (new XamlMember (typeof (Foo).GetProperty ("Bar"), sctx)); // <List.Bar>
+                       xw.WriteGetObject ();
+                       xw.WriteStartMember (xm); // <List.Length /> . Note that the corresponding member is String.Length(!)
+                       xw.Close ();
+                       // FIXME: enable it once we got generic type output fixed.
+                       //Assert.AreEqual (xml, sw.ToString ().Replace ('"', '\''), "#1");
+               }
+
+               [Test]
+               public void EndObjectAfterGetObject ()
+               {
+                       var sw = new StringWriter ();
+                       var xw = new XamlXmlWriter (sw, sctx, null);
+                       xw.WriteStartObject (xt2);
+                       xw.WriteStartMember (new XamlMember (typeof (Foo).GetProperty ("Bar"), sctx));
+                       xw.WriteGetObject ();
+                       xw.WriteEndObject ();
+               }
+
+               [Test]
+               public void WriteNode ()
+               {
+                       string xml = @"<?xml version='1.0' encoding='utf-16'?><x:String xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>foo</x:String>";
+                       var r = new XamlObjectReader ("foo", sctx);
+                       var sw = new StringWriter ();
+                       var w = new XamlXmlWriter (sw, sctx, null);
+                       while (r.Read ())
+                               w.WriteNode (r);
+                       w.Close ();
+                       Assert.AreEqual (xml, sw.ToString ().Replace ('"', '\''), "#1");
+               }
+
+               [Test]
+               public void WriteNode2 ()
+               {
+                       var r = new XamlObjectReader ("foo", sctx);
+                       var w = new XamlObjectWriter (sctx, null);
+                       while (r.Read ())
+                               w.WriteNode (r);
+                       w.Close ();
+                       Assert.AreEqual ("foo", w.Result, "#1");
+               }
+       }
+}
diff --git a/mcs/class/System.Xaml/Test/XmlFiles/Array_Int32.xml b/mcs/class/System.Xaml/Test/XmlFiles/Array_Int32.xml
new file mode 100644 (file)
index 0000000..9a4c0ce
--- /dev/null
@@ -0,0 +1,7 @@
+<x:Array Type="x:Int32" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
+  <x:Int32>4</x:Int32>
+  <x:Int32>-5</x:Int32>
+  <x:Int32>0</x:Int32>
+  <x:Int32>255</x:Int32>
+  <x:Int32>2147483647</x:Int32>
+</x:Array>
\ No newline at end of file
diff --git a/mcs/class/System.Xaml/Test/XmlFiles/ChangeLog b/mcs/class/System.Xaml/Test/XmlFiles/ChangeLog
new file mode 100644 (file)
index 0000000..a4a430c
--- /dev/null
@@ -0,0 +1,20 @@
+2010-04-16  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * Dictionary_Int32_String.xml, Dictionary_String_Type.xml :
+         add more test files (not working though).
+
+2010-04-15  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * DateTime.xml : new test file. (not working though)
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * TimeSpan.xml : new test file.
+
+2010-04-14  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * Type.xml
+         String.xml
+         List_Int32.xml
+         Array_Int32.xml
+         Int32.xml : New, example reader test xml files.
diff --git a/mcs/class/System.Xaml/Test/XmlFiles/DateTime.xml b/mcs/class/System.Xaml/Test/XmlFiles/DateTime.xml
new file mode 100644 (file)
index 0000000..e4ab8dc
--- /dev/null
@@ -0,0 +1 @@
+<DateTime xmlns="clr-namespace:System;assembly=mscorlib">2010-04-14</DateTime>
\ No newline at end of file
diff --git a/mcs/class/System.Xaml/Test/XmlFiles/Dictionary_Int32_String.xml b/mcs/class/System.Xaml/Test/XmlFiles/Dictionary_Int32_String.xml
new file mode 100644 (file)
index 0000000..04d5a56
--- /dev/null
@@ -0,0 +1,5 @@
+<Dictionary x:TypeArguments="x:Int32, x:String" xmlns="clr-namespace:System.Collections.Generic;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
+  <x:String x:Key="0">foo</x:String>
+  <x:String x:Key="5">bar</x:String>
+  <x:String x:Key="-2">baz</x:String>
+</Dictionary>
\ No newline at end of file
diff --git a/mcs/class/System.Xaml/Test/XmlFiles/Dictionary_String_Type.xml b/mcs/class/System.Xaml/Test/XmlFiles/Dictionary_String_Type.xml
new file mode 100644 (file)
index 0000000..90520b2
--- /dev/null
@@ -0,0 +1,8 @@
+<Dictionary x:TypeArguments="x:String, s:Type" xmlns="clr-namespace:System.Collections.Generic;assembly=mscorlib" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
+  <x:Type Type="x:Int32" x:Key="t1" />
+  <x:Type Type="s:Int32[]" x:Key="t2" />
+  <x:Type Type="s:Nullable(x:Int32)" x:Key="t3" />
+  <x:Type Type="List(x:Int32)" x:Key="t4" />
+  <x:Type Type="Dictionary(x:Int32, s:DateTime)" x:Key="t5" />
+  <x:Type Type="List(KeyValuePair(x:Int32, s:DateTime))" x:Key="t6" />
+</Dictionary>
\ No newline at end of file
diff --git a/mcs/class/System.Xaml/Test/XmlFiles/Int32.xml b/mcs/class/System.Xaml/Test/XmlFiles/Int32.xml
new file mode 100644 (file)
index 0000000..401debd
--- /dev/null
@@ -0,0 +1 @@
+<x:Int32 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">5</x:Int32>
\ No newline at end of file
diff --git a/mcs/class/System.Xaml/Test/XmlFiles/List_Int32.xml b/mcs/class/System.Xaml/Test/XmlFiles/List_Int32.xml
new file mode 100644 (file)
index 0000000..b2f35f9
--- /dev/null
@@ -0,0 +1,7 @@
+<List x:TypeArguments="x:Int32" Capacity="5" xmlns="clr-namespace:System.Collections.Generic;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
+  <x:Int32>4</x:Int32>
+  <x:Int32>-5</x:Int32>
+  <x:Int32>0</x:Int32>
+  <x:Int32>255</x:Int32>
+  <x:Int32>2147483647</x:Int32>
+</List>
\ No newline at end of file
diff --git a/mcs/class/System.Xaml/Test/XmlFiles/String.xml b/mcs/class/System.Xaml/Test/XmlFiles/String.xml
new file mode 100644 (file)
index 0000000..3652cc1
--- /dev/null
@@ -0,0 +1 @@
+<x:String xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">foo</x:String>
\ No newline at end of file
diff --git a/mcs/class/System.Xaml/Test/XmlFiles/TimeSpan.xml b/mcs/class/System.Xaml/Test/XmlFiles/TimeSpan.xml
new file mode 100644 (file)
index 0000000..327f5f2
--- /dev/null
@@ -0,0 +1 @@
+<x:TimeSpan xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">00:07:00</x:TimeSpan>
\ No newline at end of file
diff --git a/mcs/class/System.Xaml/Test/XmlFiles/Type.xml b/mcs/class/System.Xaml/Test/XmlFiles/Type.xml
new file mode 100644 (file)
index 0000000..13c6cae
--- /dev/null
@@ -0,0 +1 @@
+<x:Type Type="x:Int32" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" />
\ No newline at end of file
index 15210973344b65fe0bc7e77d518bca67464ce49b..d65d2ac63693d1b426316106e10595ccf3b4a7bf 100644 (file)
@@ -1,3 +1,33 @@
+2010-04-21  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * XDocument.cs: Don't use XmlReaderSettings.ProhibitDtd when 
+       building Moonlight SDK assemblies
+
+2010-04-21  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XDocument.cs : don't prohibit DTD.
+       * XNodeNavigator.cs : do not return true in MoveToFirstChild()
+         when there is no child node. Fixed bug #594877.
+
+2010-04-02  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XContainer.cs : create snapshot copy first before removal of nodes.
+         Fixed bug #592435.
+
+2010-03-16  Rolf Bjarne Kvinge  <RKvinge@novell.com>
+
+       * XElement.cs:
+       * SaveOptions.cs: Add more 4.0 api to Moonlight.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * XElement.cs, XNodeNavigator.cs: use MOONLIGHT symbol to
+       disambiguate MonoTouch and Moonlight code.
+
+2010-03-15  Rolf Bjarne Kvinge  <RKvinge@novell.com>
+
+       * XElement.cs: Added two new Load overloads for NET 4.0 and Moonlight.
+
 2010-02-12  Miguel de Icaza  <miguel@novell.com>
 
        * XStreamingElement.cs: Avoid an extra indirect call, by calling
        * XAttribute.cs, XIterators.cs, XName.cs, XElementSequence.cs,
          System.Xml.XLinq.cs :
          Minimum implementation to run ms XLinqIntro.
-
index f2753fc07cf201243b7a75c148b98d40fc4773ad..f0a4d4efeef9250c54f69827ac80c70981b1cf5b 100644 (file)
@@ -33,7 +33,7 @@ namespace System.Xml.Linq
        {
                None = 0,
                DisableFormatting = 1,
-#if NET_4_0
+#if NET_4_0 || MOONLIGHT
                OmitDuplicateNamespaces = 2
 #endif
        }
index 112f4c1deccfaf27b0030c0d86f7fe992b2130c1..7a49543813e610770b2ef1f91f6e289dc7a84af0 100644 (file)
@@ -205,26 +205,19 @@ namespace System.Xml.Linq
 
                public void ReplaceNodes (object content)
                {
-                       // First, it adds new nodes and then removes existing
-                       // nodes, for bug #540198. When the "content" is
-                       // existing children, it has to be added first, because
-                       // once "content" is removed, then they are not linked
-                       // anymore and it does not iterate linked nodes as
-                       // it did when it was passed to this method as argument.
-                       var first = FirstNode;
-                       var last = LastNode;
+                       // First, it creates a snapshot copy, then removes the contents, and then adds the copy. http://msdn.microsoft.com/en-us/library/system.xml.linq.xcontainer.replacenodes.aspx
 
-                       Add (content);
-
-                       if (first == null)
+                       if (FirstNode == null) {
+                               Add (content);
                                return;
-
-                       XNode next;
-                       for (var n = first; n != last; n = next) {
-                               next = n.NextNode;
-                               n.Remove ();
                        }
-                       last.Remove ();
+
+                       var l = new List<object> ();
+                       foreach (var obj in XUtil.ExpandArray (content))
+                               l.Add (obj);
+
+                       RemoveNodes ();
+                       Add (l);
                }
 
                public void ReplaceNodes (params object [] content)
index 73271ac03df8bae86f54fda3a30c927b0a1c9c6c..32f5f7e61af166c032eea303b8986bf0e5910d7d 100644 (file)
@@ -119,6 +119,9 @@ namespace System.Xml.Linq
                public static XDocument Load (TextReader reader, LoadOptions options)
                {
                        XmlReaderSettings s = new XmlReaderSettings ();
+#if !MOONLIGHT
+                       s.ProhibitDtd = false; // see XNodeNavigatorTest.MoveToId().
+#endif
                        s.IgnoreWhitespace = (options & LoadOptions.PreserveWhitespace) == 0;
                        using (XmlReader r = XmlReader.Create (reader, s)) {
                                return LoadCore (r, options);
index 92c6e7f84555fc9ded3c29785b7e22b950adaee9..16c969c332aaf5a2d89e334b1327b2b5d45a4dc1 100644 (file)
@@ -394,7 +394,7 @@ namespace System.Xml.Linq
 
                static void DefineDefaultSettings (XmlReaderSettings settings, LoadOptions options)
                {
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        // 2.1 has a DtdProcessing property which defaults to DtdProcessing.Prohibit
                        settings.DtdProcessing = DtdProcessing.Parse;
 #else
@@ -454,6 +454,23 @@ namespace System.Xml.Linq
                        }
                }
 
+#if MOONLIGHT || NET_4_0
+               public static XElement Load (Stream stream)
+               {
+                       return Load (stream, LoadOptions.None);
+               }
+
+               public static XElement Load (Stream stream, LoadOptions options)
+               {
+                       XmlReaderSettings s = new XmlReaderSettings ();
+                       DefineDefaultSettings (s, options);
+
+                       using (XmlReader r = XmlReader.Create (stream, s)) {
+                               return LoadCore (r, options);
+                       }
+               }
+#endif
+
                internal static XElement LoadCore (XmlReader r, LoadOptions options)
                {
                        r.MoveToContent ();
@@ -519,7 +536,7 @@ namespace System.Xml.Linq
 
                        if ((options & SaveOptions.DisableFormatting) == SaveOptions.None)
                                s.Indent = true;
-#if NET_4_0
+#if NET_4_0 || MOONLIGHT
                        if ((options & SaveOptions.OmitDuplicateNamespaces) == SaveOptions.OmitDuplicateNamespaces)
                                s.NamespaceHandling |= NamespaceHandling.OmitDuplicates;
 #endif
@@ -539,7 +556,7 @@ namespace System.Xml.Linq
                        
                        if ((options & SaveOptions.DisableFormatting) == SaveOptions.None)
                                s.Indent = true;
-#if NET_4_0
+#if NET_4_0 || MOONLIGHT
                        if ((options & SaveOptions.OmitDuplicateNamespaces) == SaveOptions.OmitDuplicateNamespaces)
                                s.NamespaceHandling |= NamespaceHandling.OmitDuplicates;
 #endif
@@ -553,7 +570,7 @@ namespace System.Xml.Linq
                        WriteTo (w);
                }
 
-#if NET_4_0
+#if NET_4_0 || MOONLIGHT
                public void Save (Stream stream)
                {
                        Save (stream, SaveOptions.None);
index 429954cb8dfac7fab121765bb2307a05d720a8c8..ab252001f42e95e18620b29a14245e760e54ae02 100644 (file)
@@ -24,7 +24,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System;
 using System.IO;
@@ -280,7 +280,7 @@ namespace System.Xml.Linq
                public override bool MoveToFirstChild ()
                {
                        XContainer c = node as XContainer;
-                       if (c == null)
+                       if (c == null || c.FirstNode == null)
                                return false;
                        node = c.FirstNode;
                        attr = null;
index c403ee2420da2fd859c565e5c551460d786b81e7..f4641d77fa98274f4a5afc5161851591d6ae5f6e 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * Extensions.cs: use MOONLIGHT symbol to
+       disambiguate MonoTouch and Moonlight code.
+
 2009-07-20  Jb Evain  <jbevain@novell.com>
 
        * Extensions.cs: do not compile for a NET_2_1 profile.
index 86c0beb6039f473dca3e8173f208420e9d6fc736..cc3f448733aefca7b56c973270c3eb919e2b6fb3 100644 (file)
@@ -24,7 +24,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System;
 using System.Collections.Generic;
index 344f6a2fcaf1b881c201ec8d76ae31cd43981570..937106c79001adb31dd31c0effdfdd8ccc5bbb66 100644 (file)
@@ -1,3 +1,17 @@
+2010-04-23  Jonathan Pobst  <monkey@jpobst.com>
+
+       * XAttributeTest.cs, XElementTest.cs: Try to standardize DST usage
+       to fix failing tests in buildbot.
+
+2010-04-21  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XNodeNavigatorTest.cs : added test for bug #594877. Enable and fix
+         tests that were commented out.
+
+2010-04-02  Atsushi Enomoto  <atsushi@ximian.com>
+
+       * XElementTest.cs : added test for bug #592435.
+
 2010-01-25  Atsushi Enomoto  <atsushi@ximian.com>
 
        * XElementTest.cs, XAttributeTest.cs : add corner case value conversion
index 03f942d2a8bad53b478f388d91256b951da37857..5e81c3c25701140716097f05c6bde9f99c9ebc25 100644 (file)
@@ -858,7 +858,7 @@ namespace MonoTests.System.Xml.Linq
                        DateTime rz = DateTime.UtcNow;
 
                        XAttribute a = new XAttribute ("a", "1987-01-23T21:45:36.089");
-                       XAttribute b = new XAttribute ("b", " \n 2001-02-03T04:05:06.789" + DateTime.Now.ToString ("zzz") + "  \r   ");
+                       XAttribute b = new XAttribute ("b", " \n 2001-02-03T04:05:06.789" + rb.ToString ("zzz") + "  \r   ");
                        XAttribute c = new XAttribute ("c", "2010-01-02T00:00:00." + weirdTicks.ToString ("d7").TrimEnd ('0') + "Z");
                        XAttribute d = new XAttribute ("d", "  Nov 2, 1956  12:34 AM \r\n   \t");
                        XAttribute e = new XAttribute ("e", " \t 17:13:11.7654321 ");
index ef3b5df9e628a40bbe2e941553ac4146e8258a76..b951dc6a406bca40963a84541751c3d7fe4949b3 100644 (file)
@@ -1278,7 +1278,7 @@ namespace MonoTests.System.Xml.Linq
                        DateTime rz = DateTime.UtcNow;
 
                        XElement a = new XElement ("a", "1987-01-23T21:45:36.089");
-                       XElement b = new XElement ("b", "2001-02-03T04:05:06.789" + DateTime.Now.ToString ("zzz"));
+                       XElement b = new XElement ("b", "2001-02-03T04:05:06.789" + rb.ToString ("zzz"));
                        XElement c = new XElement ("c", "2010-01-02T00:00:00Z");
                        XElement d = new XElement ("d", "  Nov 2, 1956  12:34 AM \r\n   \t");
                        XElement e = new XElement ("e", "  2013-07-04T05:06:08.3456297Z   ");  // UTC, all the way
@@ -1576,5 +1576,30 @@ namespace MonoTests.System.Xml.Linq
 
                        Assert.AreEqual (2, container.Elements ().Count (), "#3");
                }
+
+               [Test]
+               public void ReplaceCreatesSnapshotBeforeRemoval ()
+               {
+                       // bug #592435
+                       XElement data1 = new XElement ("A");
+                       XElement data3 = new XElement ("C");
+                       XElement data4 = new XElement ("D");
+                       XElement root = new XElement ("rt", 
+                                                     new XElement ("z", new XElement ("Name", data1), new XElement ("Desc", data4)), data3);
+                       var elements = root.Elements ().Elements ();
+                       root.ReplaceNodes (elements);
+                       root.Add (elements);
+                       string xml = @"<rt>
+  <Name>
+    <A />
+  </Name>
+  <Desc>
+    <D />
+  </Desc>
+  <A />
+  <D />
+</rt>";
+                       Assert.AreEqual (xml, root.ToString ().Replace ("\r\n", "\n"), "#1");
+               }
        }
 }
index 3e9ef5d92e2dff226fee2de0a0c78275187be2bc..c0694df42d1e48d2cbb8bb419ce3e420621fe660 100644 (file)
@@ -37,7 +37,6 @@ namespace MonoTests.System.Xml.Linq
        [TestFixture]
        public class XNodeNavigatorTest
        {
-/* It does not compile probably due to bug #359733.
                [Test]
                public void MoveToNext ()
                {
@@ -50,7 +49,8 @@ namespace MonoTests.System.Xml.Linq
                }
 
                [Test]
-               public void MoveToId () // Not supported
+               [ExpectedException (typeof (NotSupportedException))]
+               public void MoveToId () // ID is not supported here.
                {
                        string xml = @"
 <!DOCTYPE root [
@@ -59,11 +59,20 @@ namespace MonoTests.System.Xml.Linq
 <!ATTLIST foo id ID #IMPLIED>
 <!ATTLIST bar id ID #IMPLIED>
 ]>
-<root><foo id='foo' /><bar id='bar' /></root>",
+<root><foo id='foo' /><bar id='bar' /></root>";
                        XDocument doc = XDocument.Parse (xml, LoadOptions.SetLineInfo);
                        XPathNavigator nav = doc.CreateNavigator ();
                        nav.MoveToId ("foo");
                }
-*/
+
+               [Test]
+               public void Bug594877 ()
+               {
+                       string data = "<rt> <objsur t=\"o\" guid=\"06974d9a-ff86-4e1c-a3e5-7ce8c961dcb9\" /> </rt>";
+                       XElement xeOldOwner = XElement.Parse(data);
+                       string xpathOld = String.Format(".//objsur[@t='o']");
+                       XElement xeOldRef = xeOldOwner.XPathSelectElement(xpathOld);
+                       Assert.AreEqual ("<objsur t='o' guid='06974d9a-ff86-4e1c-a3e5-7ce8c961dcb9' />".Replace ('\'', '"'), xeOldRef.ToString (), "#1");
+               }
        }
 }
diff --git a/mcs/class/System.Xml.Serialization/Assembly/AssemblyInfo.cs b/mcs/class/System.Xml.Serialization/Assembly/AssemblyInfo.cs
new file mode 100644 (file)
index 0000000..b86fa22
--- /dev/null
@@ -0,0 +1,62 @@
+//
+// AssemblyInfo.cs
+//
+// Author:
+//   Rolf Bjarne Kvinge  (RKvinge@novell.com)
+//
+// Copyright (c) 2010 Novell, Inc. (http://www.novell.com)
+//
+//
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Reflection;
+using System.Resources;
+using System.Security;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about the System.Xml.Serialization assembly
+
+[assembly: AssemblyTitle ("System.Xml.Serialization.dll")]
+[assembly: AssemblyDescription ("System.Xml.Serialization.dll")]
+[assembly: AssemblyDefaultAlias ("System.Xml.Serialization.dll")]
+
+[assembly: AssemblyCompany (Consts.MonoCompany)]
+[assembly: AssemblyProduct (Consts.MonoProduct)]
+[assembly: AssemblyCopyright (Consts.MonoCopyright)]
+[assembly: AssemblyVersion (Consts.FxVersion)]
+[assembly: SatelliteContractVersion (Consts.FxVersion)]
+[assembly: AssemblyInformationalVersion (Consts.FxFileVersion)]
+
+[assembly: NeutralResourcesLanguage ("en-US")]
+
+[assembly: ComVisible (false)]
+
+[assembly: CLSCompliant (true)]
+[assembly: AssemblyDelaySign (true)]
+[assembly: AssemblyKeyFile ("../silverlight.pub")]
+[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
+[assembly: CompilationRelaxations (CompilationRelaxations.NoStringInterning)]
+[assembly: Debuggable (DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
+[assembly: RuntimeCompatibility (WrapNonExceptionThrows = true)]
diff --git a/mcs/class/System.Xml.Serialization/Assembly/ChangeLog b/mcs/class/System.Xml.Serialization/Assembly/ChangeLog
new file mode 100644 (file)
index 0000000..872b6a8
--- /dev/null
@@ -0,0 +1,4 @@
+2010-03-16  Rolf Bjarne Kvinge  <RKvinge@novell.com>
+
+       * AssemblyInfo.cs: Added.
+
diff --git a/mcs/class/System.Xml.Serialization/ChangeLog b/mcs/class/System.Xml.Serialization/ChangeLog
new file mode 100644 (file)
index 0000000..8038f0a
--- /dev/null
@@ -0,0 +1,6 @@
+2010-03-16  Rolf Bjarne Kvinge  <RKvinge@novell.com>
+
+       * Makefile: 
+       * System.Xml.Serialization.dll.sources:
+       * moonlight_raw_System.Xml.Serialization.dll.sources: Added.
+
diff --git a/mcs/class/System.Xml.Serialization/Makefile b/mcs/class/System.Xml.Serialization/Makefile
new file mode 100644 (file)
index 0000000..ee8337a
--- /dev/null
@@ -0,0 +1,24 @@
+thisdir = class/System.Xml.Serialization
+SUBDIRS = 
+include ../../build/rules.make
+
+LIBRARY = System.Xml.Serialization.dll
+LIB_MCS_FLAGS =  -unsafe -r:System.dll -r:System.Core.dll -r:System.Xml.dll -d:NET_2_1 -d:NET_2_0 -d:NET_1_1
+
+ifneq (2.1, $(FRAMEWORK_VERSION))
+LIB_MCS_FLAGS += -d:NET_3_5 -nowarn:1720
+endif
+
+TEST_MCS_FLAGS = $(LIB_MCS_FLAGS)
+
+EXTRA_DISTFILES =
+
+VALID_PROFILE := $(filter 2.1, $(FRAMEWORK_VERSION))
+ifndef VALID_PROFILE
+LIBRARY_NAME = dummy-System.Xml.Serialization.dll
+NO_INSTALL = yes
+NO_SIGN_ASSEMBLY = yes
+NO_TEST = yes
+endif
+
+include ../../build/library.make
diff --git a/mcs/class/System.Xml.Serialization/System.Xml.Serialization.dll.sources b/mcs/class/System.Xml.Serialization/System.Xml.Serialization.dll.sources
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/mcs/class/System.Xml.Serialization/System.Xml.Serialization/ChangeLog b/mcs/class/System.Xml.Serialization/System.Xml.Serialization/ChangeLog
new file mode 100644 (file)
index 0000000..10fa384
--- /dev/null
@@ -0,0 +1,14 @@
+2010-03-16  Rolf Bjarne Kvinge  <RKvinge@novell.com>
+
+       * XmlMapping.cs:
+       * XmlAttributes.cs:
+       * XmlSerializer.cs:
+       * XmlTypeMapping.cs:
+       * XmlAttributeOverrides.cs:
+       * XmlSerializationWriter.cs:
+       * XmlSerializationReader.cs:
+       * XmlSerializerNamespaces.cs:
+       * XmlSerializationGeneratedCode.cs: Added a partially stubbed out version of
+       System.Xml.Serialization.dll, required for the Silverlight test suite to
+       compile. A real implementation based on the same classes in System.Xml should
+       eventually be done.
diff --git a/mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlAttributeOverrides.cs b/mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlAttributeOverrides.cs
new file mode 100644 (file)
index 0000000..3f7a66c
--- /dev/null
@@ -0,0 +1,58 @@
+//
+// XmlAttributeOverrides.cs
+//
+// Authors:
+//   Rolf Bjarne Kvinge (RKvinge@novell.com)
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+//
+// This class is just a stub of the same class in System.Xml/System.Xml.Serialization
+//
+
+namespace System.Xml.Serialization {
+       public class XmlAttributeOverrides {
+               public XmlAttributeOverrides ()
+               {
+                       throw new NotImplementedException ();
+               }
+               public void Add (Type type, XmlAttributes attributes)
+               {
+                       throw new NotImplementedException ();
+               }
+               public void Add (Type type, string member, XmlAttributes attributes)
+               {
+                       throw new NotImplementedException ();
+               }
+               public XmlAttributes this [Type type, string member] {
+                       get {
+                               throw new NotImplementedException ();
+                       }
+               }
+               public XmlAttributes this [Type type] {
+                       get {
+                               throw new NotImplementedException ();
+                       }
+               }
+       }
+}
diff --git a/mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlAttributes.cs b/mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlAttributes.cs
new file mode 100644 (file)
index 0000000..903b463
--- /dev/null
@@ -0,0 +1,36 @@
+//
+// XmlAttributes.cs
+//
+// Authors:
+//   Rolf Bjarne Kvinge (RKvinge@novell.com)
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+//
+// This class is just a stub of the same class in System.Xml/System.Xml.Serialization
+//
+
+namespace System.Xml.Serialization {
+       public class XmlAttributes {
+       }
+}
\ No newline at end of file
diff --git a/mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlMapping.cs b/mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlMapping.cs
new file mode 100644 (file)
index 0000000..e5e9600
--- /dev/null
@@ -0,0 +1,43 @@
+//
+// XmlMapping.cs
+//
+// Authors:
+//   Rolf Bjarne Kvinge (RKvinge@novell.com)
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+//
+// This class is just a stub of the same class in System.Xml/System.Xml.Serialization
+//
+
+namespace System.Xml.Serialization {
+       public abstract class XmlMapping {
+               public void SetKey (string key)
+               {
+                       throw new NotImplementedException ();
+               }
+               public string ElementName { get; private set; }
+               public string Namespace { get; private set; }
+               public string XsdElementName { get; private set; }
+       }
+}
\ No newline at end of file
diff --git a/mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlSerializationGeneratedCode.cs b/mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlSerializationGeneratedCode.cs
new file mode 100644 (file)
index 0000000..04a2a8d
--- /dev/null
@@ -0,0 +1,40 @@
+//
+// XmlSerializationGeneratedCode.cs
+//
+// Authors:
+//   Rolf Bjarne Kvinge (RKvinge@novell.com)
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+//
+// This class is just a stub of the same class in System.Xml/System.Xml.Serialization
+//
+
+namespace System.Xml.Serialization {
+       public abstract class XmlSerializationGeneratedCode {
+               protected XmlSerializationGeneratedCode ()
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
\ No newline at end of file
diff --git a/mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlSerializationReader.cs b/mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlSerializationReader.cs
new file mode 100644 (file)
index 0000000..1b5f1f1
--- /dev/null
@@ -0,0 +1,36 @@
+//
+// XmlSerializationReader.cs
+//
+// Authors:
+//   Rolf Bjarne Kvinge (RKvinge@novell.com)
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+//
+// This class is just a stub of the same class in System.Xml/System.Xml.Serialization
+//
+
+namespace System.Xml.Serialization {
+       public abstract class XmlSerializationReader : XmlSerializationGeneratedCode {
+       }
+}
\ No newline at end of file
diff --git a/mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlSerializationWriter.cs b/mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlSerializationWriter.cs
new file mode 100644 (file)
index 0000000..97acb4a
--- /dev/null
@@ -0,0 +1,37 @@
+//
+// XmlSerializationWriter.cs
+//
+// Authors:
+//   Rolf Bjarne Kvinge (RKvinge@novell.com)
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+//
+// This class is just a stub of the same class in System.Xml/System.Xml.Serialization
+//
+
+namespace System.Xml.Serialization {
+       public abstract class XmlSerializationWriter : XmlSerializationGeneratedCode {
+               
+       }
+}
\ No newline at end of file
diff --git a/mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlSerializer.cs b/mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlSerializer.cs
new file mode 100644 (file)
index 0000000..bda6b9c
--- /dev/null
@@ -0,0 +1,142 @@
+//
+// XmlSerializer.cs
+//
+// Authors:
+//   Rolf Bjarne Kvinge (RKvinge@novell.com)
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+//
+// This class is just a stub of the same class in System.Xml/System.Xml.Serialization
+//
+
+using System;
+using System.IO;
+namespace System.Xml.Serialization {
+       public class XmlSerializer {
+               public XmlSerializer ()
+               {
+                       throw new NotImplementedException ();
+               }
+               public XmlSerializer (Type type)
+               {
+                       throw new NotImplementedException ();
+               }
+               public XmlSerializer (XmlTypeMapping xmlTYpeMapping)
+               {
+                       throw new NotImplementedException ();
+               }
+               public XmlSerializer (Type type, Type [] extraTypes)
+               {
+                       throw new NotImplementedException ();
+               }
+               public XmlSerializer (Type type, string defaultNamespace)
+               {
+                       throw new NotImplementedException ();
+               }
+               public XmlSerializer (Type type, XmlAttributeOverrides overrides)
+               {
+                       throw new NotImplementedException ();
+               }
+               public XmlSerializer (Type type, XmlRootAttribute root)
+               {
+                       throw new NotImplementedException ();
+               }
+               public XmlSerializer (Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace)
+               {
+                       throw new NotImplementedException ();
+               }
+               public XmlSerializer (Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, object location, object evidence)
+               {
+                       throw new NotImplementedException ();
+               }
+               public bool CanDeserializer (XmlReader xmlReader)
+               {
+                       throw new NotImplementedException ();
+               }
+               public XmlSerializationReader CreateReader ()
+               {
+                       throw new NotImplementedException ();
+               }
+               public XmlSerializationWriter CreateWriter ()
+               {
+                       throw new NotImplementedException ();
+               }
+               public object Deserialize (Stream stream)
+               {
+                       throw new NotImplementedException ();
+               }
+               public object Deserialize (XmlSerializationReader reader)
+               {
+                       throw new NotImplementedException ();
+               }
+               public object Deserialize (TextReader textReader)
+               {
+                       throw new NotImplementedException ();
+               }
+               public object Deserialize (XmlReader xmlReader)
+               {
+                       throw new NotImplementedException ();
+               }
+               public XmlSerializer [] FromMappings (XmlMapping [] mappings)
+               {
+                       throw new NotImplementedException ();
+               }
+               public XmlSerializer [] FromMappings (XmlMapping [] mappings, Type type)
+               {
+                       throw new NotImplementedException ();
+               }
+               public XmlSerializer [] FromTypes (Type [] types)
+               {
+                       throw new NotImplementedException ();
+               }
+               protected virtual void Serialize (object o, XmlSerializationWriter writer)
+               {
+                       throw new NotImplementedException ();
+               }
+               public void Serialize (Stream stream, object o)
+               {
+                       throw new NotImplementedException ();
+               }
+               public void Serialize (TextWriter textWriter, object o)
+               {
+                       throw new NotImplementedException ();
+               }
+               public void Serialize (XmlWriter xmlWriter, object o)
+               {
+                       throw new NotImplementedException ();
+               }
+               public void Serialize (TextWriter textWriter, object o, XmlSerializerNamespaces namespaces)
+               {
+                       throw new NotImplementedException ();
+               }
+               public void Serialize (XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces)
+               {
+                       throw new NotImplementedException ();
+               }
+               public void Serialize (Stream stream, object o, XmlSerializerNamespaces namespaces)
+               {
+                       throw new NotImplementedException ();
+               }
+       }
+}
\ No newline at end of file
diff --git a/mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlSerializerNamespaces.cs b/mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlSerializerNamespaces.cs
new file mode 100644 (file)
index 0000000..4dcb738
--- /dev/null
@@ -0,0 +1,57 @@
+//
+// XmlSerializerNamespaces.cs
+//
+// Authors:
+//   Rolf Bjarne Kvinge (RKvinge@novell.com)
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+//
+// This class is just a stub of the same class in System.Xml/System.Xml.Serialization
+//
+
+namespace System.Xml.Serialization {
+       public class XmlSerializerNamespaces {
+               public XmlSerializerNamespaces ()
+               {
+                       throw new NotImplementedException ();
+               }
+               public XmlSerializerNamespaces (XmlSerializerNamespaces namespaces)
+               {
+                       throw new NotImplementedException ();
+               }
+               public XmlSerializerNamespaces (XmlQualifiedName [] namespaces)
+               {
+                       throw new NotImplementedException ();
+               }
+               public void Add (string prefix, string ns)
+               {
+                       throw new NotImplementedException ();
+               }
+               public XmlQualifiedName [] ToArray ()
+               {
+                       throw new NotImplementedException ();
+               }
+               public int Count { get; private set; }
+       }
+}
\ No newline at end of file
diff --git a/mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlTypeMapping.cs b/mcs/class/System.Xml.Serialization/System.Xml.Serialization/XmlTypeMapping.cs
new file mode 100644 (file)
index 0000000..d789df6
--- /dev/null
@@ -0,0 +1,40 @@
+//
+// XmlTypeMapping.cs
+//
+// Authors:
+//   Rolf Bjarne Kvinge (RKvinge@novell.com)
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+//
+// This class is just a stub of the same class in System.Xml/System.Xml.Serialization
+//
+
+namespace System.Xml.Serialization {
+       public class XmlTypeMapping : XmlMapping {
+               public string TypeFullName { get; private set; }
+               public string TypeName { get; private set; }
+               public string XsdTypeName { get; private set; }
+               public string XsdTypeNamespace { get; private set; }
+       }
+}
\ No newline at end of file
diff --git a/mcs/class/System.Xml.Serialization/moonlight_raw_System.Xml.Serialization.dll.sources b/mcs/class/System.Xml.Serialization/moonlight_raw_System.Xml.Serialization.dll.sources
new file mode 100644 (file)
index 0000000..1e0ecb0
--- /dev/null
@@ -0,0 +1,13 @@
+Assembly/AssemblyInfo.cs
+../System.XML/../../build/common/Consts.cs
+../System.XML/../../build/common/Locale.cs
+../System.XML/../../build/common/MonoTODOAttribute.cs
+System.Xml.Serialization/XmlAttributeOverrides.cs
+System.Xml.Serialization/XmlAttributes.cs
+System.Xml.Serialization/XmlMapping.cs
+System.Xml.Serialization/XmlSerializationGeneratedCode.cs
+System.Xml.Serialization/XmlSerializationReader.cs
+System.Xml.Serialization/XmlSerializationWriter.cs
+System.Xml.Serialization/XmlSerializer.cs
+System.Xml.Serialization/XmlSerializerNamespaces.cs
+System.Xml.Serialization/XmlTypeMapping.cs
index e3474f10dc6b04e1a780b18e4a5de69d606cca1e..3e34ed93f6b7b999837bb1def288c8fceb306ce3 100644 (file)
@@ -1,3 +1,38 @@
+2010-04-23  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * moonlight_raw_System.dll.sources: Add new (for SL4) types
+       to moonlight build
+
+2010-04-16  Raja R Harinath  <harinath@hurrynot.org>
+       and Marek Habersack  <mhabersack@novell.com>
+
+       * Makefile (LIBRARY_COMPILE) [USE_BOOT_COMPILE]:
+       Don't override if the profile says it isn't necessary by setting
+       PROFILE_MCS_HAS_BOOTSTRAP_FALLBACK.
+
+2010-04-01  Jb Evain  <jbevain@novell.com>
+
+       * System.dll.sources: add SortedSet to the build.
+
+2010-03-20  Miguel de Icaza  <miguel@novell.com>
+
+       * Eliminate warnings in a bunch of places.
+
+2010-03-19  Miguel de Icaza  <miguel@novell.com>
+
+       * Eliminate warnings in a bunch of places.
+
+2010-03-19  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * moonlight_*_System.dll.sources: Bring extra types so we can
+       build a full, managed, internal HTTP stack to be reused for SL3+
+       * Makefile: Add a INSIDE_SYSTEM define when compiling System.dll
+       to makes it possible to rebuild the same types in System.Net.dll
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * net_2_1_*.dll.sources: rename to moonlight_*.dll.sources.
+
 2010-03-11  Sebastien Pouliot  <sebastien@ximian.com>
 
        * net_2_1_raw_System.dll.sources: Add existing files that are 
index 1a408b072551750e0be210ef74c92fc16557b88c..16f511676ae42bfaf80f4a78209c532859e9c04b 100644 (file)
@@ -29,6 +29,9 @@ TEST_MCS_FLAGS += -r:System.Configuration
 PROFILE_2_OR_4 := $(filter net_2_0 net_4_0, $(PROFILE))
 NOT_SL := $(filter net_2_0 net_4_0 monotouch, $(PROFILE))
 endif
+ifeq (2.1, $(FRAMEWORK_VERSION))
+LIB_MCS_FLAGS += -d:INSIDE_SYSTEM
+endif
 
 EXTRA_DISTFILES = \
        System.Text.RegularExpressions/notes.txt        \
@@ -52,8 +55,10 @@ USE_BOOT_COMPILE = yes
 endif
 
 ifdef USE_BOOT_COMPILE
+ifndef PROFILE_MCS_HAS_BOOTSTRAP_FALLBACK
 LIBRARY_COMPILE = $(BOOT_COMPILE)
 endif
+endif
 
 # Because System.dll, Mono.Security.dll System.Xml.dll have a cyclic dependency, we need a two-pass build.
 # 1st pass - build System.dll without System.Xml.dll or Mono.Security.dll or System.Configuration.dll references
index 01212b6ba76fe465bfd7ebf0b208c097af5c96fc..730900881c7368c0af9c904b06926ba8d0faf596 100644 (file)
@@ -183,6 +183,15 @@ namespace Mono.CSharp
                        GenerateCompileUnitEnd (compileUnit);
                }
 
+#if NET_2_0
+               protected override void GenerateDefaultValueExpression (CodeDefaultValueExpression e)
+               {
+                       Output.Write ("default(");
+                       OutputType (e.Type);
+                       Output.Write (')');
+               }
+#endif
+
                protected override void GenerateDelegateCreateExpression (CodeDelegateCreateExpression expression)
                {
                        TextWriter output = Output;
index fdb64e84c8146e3b54d7c69ca0f09d8ce47dbfa8..eb1944db7588095df2ef27dbe582b98445e4944c 100644 (file)
@@ -1,3 +1,7 @@
+2010-04-12  Jonathan Pryor  <jpryor@novell.com>
+
+       * CSharpCodeGenerator.cs: Support generating default(T) expressions.
+
 2010-03-06  Marek Habersack  <mhabersack@novell.com>
 
        * CSharpCodeCompiler.cs: in the 4.0 profile, the latest C#
index 6d2dc2785b9d4b77c8477d3109416348ca0a39cb..add3550eda216214b5056138759faed01b7d685a 100644 (file)
@@ -1,3 +1,19 @@
+2010-04-13  Jonathan Pryor  <jpryor@novell.com>
+
+       * CodeGenerator.cs: Clear out the current member when beginning Type
+         generation.  This prevents "invalid" `#endregion`s; if the
+         CodeGenerator instance is reused for multiple types, the last member
+         of the first type has an EndDirective, then the EndDirectvies will
+         be generated before any members of the 2nd type.  Don't do that.
+
+2010-04-07  Jb Evain  <jbevain@novell.com>
+
+       * Executor.cs: make class static.
+
+2010-04-01  Jb Evain  <jbevain@novell.com>
+
+       * CodeDomProvider.cs, CompilerInfo.cs: add .net 4.0 overloads.
+
 2010-03-06  Marek Habersack  <mhabersack@novell.com>
 
        * CompilerCollection.cs: in the 4.0 profile, the latest C#
index 7ff01b07d8b160ccca624fddf59b49d14dc2aa5b..417c3c67eeeb0be2227e6789d2058564f1f7e856 100644 (file)
@@ -30,6 +30,7 @@
 //
 
 using System.Collections;
+using System.Collections.Generic;
 using System.ComponentModel;
 using System.Configuration;
 using System.IO;
@@ -143,8 +144,16 @@ namespace System.CodeDom.Compiler {
                        CompilerInfo ci = GetCompilerInfo (language);
                        return (ci == null) ? null : ci.CreateProvider ();
                }
+#if NET_4_0
+               [ComVisible (false)]
+               public static CodeDomProvider CreateProvider (string language, IDictionary<string, string> providerOptions)
+               {
+                       CompilerInfo ci = GetCompilerInfo (language);
+                       return ci == null ? null : ci.CreateProvider (providerOptions);
+               }
 #endif
 
+#endif
                public virtual string CreateValidIdentifier (string value)
                {
                        ICodeGenerator cg = CreateGenerator ();
index ba1842250ef8ea47d3d1633a17806ad75ce61fab..f2103ff1f070e4866ef406069a8d2cac92d2b932 100644 (file)
@@ -896,6 +896,7 @@ namespace System.CodeDom.Compiler {
                private void GenerateType (CodeTypeDeclaration type)
                {
                        this.currentType = type;
+                       this.currentMember = null;
 
 #if NET_2_0
                        if (type.StartDirectives.Count > 0)
index 1e74c37c99112c19efe7eb1e4fd9f3ee7b14970c..09c5ad954ca25bce7f055785928887d2089cc72a 100644 (file)
@@ -101,12 +101,20 @@ namespace System.CodeDom.Compiler {
                }
 
                public CodeDomProvider CreateProvider ()
+               {
+                       return CreateProvider (ProviderOptions);
+               }
+
+#if NET_4_0
+               public          
+#endif
+               CodeDomProvider CreateProvider (IDictionary<string, string> providerOptions)
                {
                        Type providerType = CodeDomProviderType;
-                       if (ProviderOptions != null && ProviderOptions.Count > 0) {
-                               ConstructorInfo ctor = providerType.GetConstructor (new Type[] {typeof (Dictionary <string, string>)});
+                       if (providerOptions != null && providerOptions.Count > 0) {
+                               ConstructorInfo ctor = providerType.GetConstructor (new [] { typeof (IDictionary <string, string>) });
                                if (ctor != null)
-                                       return (CodeDomProvider) ctor.Invoke (new object[] {ProviderOptions});
+                                       return (CodeDomProvider) ctor.Invoke (new object[] { providerOptions });
                        }
                        
                        return (CodeDomProvider) Activator.CreateInstance (providerType);
index 39919637845271f0dc5d9ef2945893264560f98d..cb06f3efd01472bd828fa063b20178eb3eb1bcfc 100644 (file)
@@ -38,7 +38,7 @@ using System.Threading;
 namespace System.CodeDom.Compiler {
 
        [PermissionSet (SecurityAction.LinkDemand, Unrestricted = true)]
-       public sealed class Executor {
+       public static class Executor {
 
                class ProcessResultReader
                {
@@ -68,10 +68,6 @@ namespace System.CodeDom.Compiler {
                        }
                }
 
-               private Executor ()
-               {
-               }
-
                public static void ExecWait (string cmd, TempFileCollection tempFiles)
                {
                        string outputName = null;
index 0f98a1d85781d09e6483b33c6c8b976d8ded7387..9ef0707f18dd7671def762cf4dc66d7679aed05e 100644 (file)
@@ -45,11 +45,9 @@ namespace System.CodeDom
                private CodeTypeReference returnType;
                private CodeStatementCollection statements;
                private CodeAttributeDeclarationCollection returnAttributes;
-               int populated;
+               //int populated;
 
-#if NET_2_0
                CodeTypeParameterCollection typeParameters;
-#endif
                //
                // Constructors
                //
@@ -122,7 +120,6 @@ namespace System.CodeDom
                        }
                }
 
-#if NET_2_0
                [ComVisible (false)]
                public CodeTypeParameterCollection TypeParameters {
                        get {
@@ -131,7 +128,6 @@ namespace System.CodeDom
                                return typeParameters;
                        }
                }
-#endif
 
                //
                // Events
index 22e05cb7ba88a7f9b5a847cf612042faf51ea6c5..8a709865b4149519aa388fe7ba56963d8346188e 100644 (file)
@@ -40,10 +40,10 @@ namespace System.CodeDom
        {
                private CodeCommentStatementCollection comments;
                private CodeNamespaceImportCollection imports;
-               private CodeNamespaceCollection namespaces;
+               //private CodeNamespaceCollection namespaces;
                private CodeTypeDeclarationCollection classes;
                private string name;
-               int populated;
+               //int populated;
 
                //
                // Constructors
index ed75aeea9174019db90dfa04a5005a310f14c431..ea6551a4af6026561f81fa56bf3a942150c4b417 100644 (file)
@@ -46,7 +46,7 @@ namespace System.CodeDom
                private TypeAttributes attributes = TypeAttributes.Public;
                private bool isEnum;
                private bool isStruct;
-               int populated;
+               //int populated;
 
 #if NET_2_0
                bool isPartial;
index cffd919fe40142b82d09fb775798250a018d0824..a61df458f7393e363d4053106b299a7d58780265 100644 (file)
@@ -43,7 +43,7 @@ namespace System.CodeDom
                private CodeTypeReference arrayElementType;
                private int arrayRank;
                private bool isInterface;
-               bool needsFixup;
+               //bool needsFixup;
 
 #if NET_2_0
                CodeTypeReferenceCollection typeArguments;
index 53388ae0a67aa558abc132e4bd9dc8ba90ad202b..741e092539ceb0e6454c9712ea4a7b0b84d51701 100644 (file)
@@ -23,7 +23,7 @@
 //
 //
 
-#if NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0
 
 using System;
 using System.Threading;
@@ -41,31 +41,29 @@ namespace System.Collections.Concurrent
        {
                readonly IProducerConsumerCollection<T> underlyingColl;
                readonly int upperBound;
-               
-               readonly SpinWait sw = new SpinWait ();
-               
+
                AtomicBoolean isComplete;
                long completeId;
 
                long addId = long.MinValue;
                long removeId = long.MinValue;
-               
+
                #region ctors
                public BlockingCollection ()
                        : this (new ConcurrentQueue<T> (), -1)
                {
                }
-               
+
                public BlockingCollection (int upperBound)
                        : this (new ConcurrentQueue<T> (), upperBound)
                {
                }
-               
+
                public BlockingCollection (IProducerConsumerCollection<T> underlyingColl)
                        : this (underlyingColl, -1)
                {
                }
-               
+
                public BlockingCollection (IProducerConsumerCollection<T> underlyingColl, int upperBound)
                {
                        this.underlyingColl = underlyingColl;
@@ -73,196 +71,196 @@ namespace System.Collections.Concurrent
                        this.isComplete     = new AtomicBoolean ();
                }
                #endregion
-               
+
                #region Add & Remove (+ Try)
                public void Add (T item)
                {
                        Add (item, null);
                }
-               
+
                public void Add (T item, CancellationToken token)
                {
                        Add (item, () => token.IsCancellationRequested);
                }
-               
+
                void Add (T item, Func<bool> cancellationFunc)
                {
                        while (true) {
                                long cachedAddId = addId;
                                long cachedRemoveId = removeId;
-                               
+
                                if (upperBound != -1) {
                                        if (cachedAddId - cachedRemoveId > upperBound) {
                                                Block ();
                                                continue;
                                        }
                                }
-                               
+
                                // Check our transaction id against completed stored one
                                if (isComplete.Value && cachedAddId >= completeId)
                                        throw new InvalidOperationException ("The BlockingCollection<T> has"
                                                                             + " been marked as complete with regards to additions.");
-                               
+
                                if (Interlocked.CompareExchange (ref addId, cachedAddId + 1, cachedAddId) == cachedAddId)
                                        break;
-                               
+
                                if (cancellationFunc != null && cancellationFunc ())
                                        throw new OperationCanceledException ("CancellationToken triggered");
                        }
-                       
-                       
+
+
                        if (!underlyingColl.TryAdd (item))
                                throw new InvalidOperationException ("The underlying collection didn't accept the item.");
                }
-               
+
                public T Take ()
                {
                        return Take (null);
                }
-               
+
                public T Take (CancellationToken token)
                {
                        return Take (() => token.IsCancellationRequested);
                }
-               
+
                T Take (Func<bool> cancellationFunc)
                {
                        while (true) {
                                long cachedRemoveId = removeId;
                                long cachedAddId = addId;
-                               
+
                                // Empty case
                                if (cachedRemoveId == cachedAddId) {
-                                       if (isComplete.Value && cachedRemoveId >= completeId)
+                                       if (IsCompleted)
                                                throw new OperationCanceledException ("The BlockingCollection<T> has"
                                                                                      + " been marked as complete with regards to additions.");
-                                       
+
                                        Block ();
                                        continue;
                                }
-                               
+
                                if (Interlocked.CompareExchange (ref removeId, cachedRemoveId + 1, cachedRemoveId) == cachedRemoveId)
                                        break;
-                               
+
                                if (cancellationFunc != null && cancellationFunc ())
                                        throw new OperationCanceledException ("The CancellationToken has had cancellation requested.");
                        }
-                       
+
                        T item;
                        while (!underlyingColl.TryTake (out item));
-                       
+
                        return item;
                }
-               
+
                public bool TryAdd (T item)
                {
                        return TryAdd (item, null, null);
                }
-               
+
                bool TryAdd (T item, Func<bool> contFunc, CancellationToken? token)
                {
                        do {
                                if (token.HasValue && token.Value.IsCancellationRequested)
                                        throw new OperationCanceledException ("The CancellationToken has had cancellation requested.");
-                               
+
                                long cachedAddId = addId;
                                long cachedRemoveId = removeId;
-                               
+
                                if (upperBound != -1) {
                                        if (cachedAddId - cachedRemoveId > upperBound) {
                                                continue;
                                        }
                                }
-                               
+
                                // Check our transaction id against completed stored one
                                if (isComplete.Value && cachedAddId >= completeId)
                                        throw new InvalidOperationException ("The BlockingCollection<T> has"
                                                                             + " been marked as complete with regards to additions.");
-                               
+
                                if (Interlocked.CompareExchange (ref addId, cachedAddId + 1, cachedAddId) != cachedAddId)
                                        continue;
-                       
+
                                if (!underlyingColl.TryAdd (item))
                                        throw new InvalidOperationException ("The underlying collection didn't accept the item.");
-                               
+
                                return true;
                        } while (contFunc != null && contFunc ());
-                       
+
                        return false;
                }
-               
+
                public bool TryAdd (T item, TimeSpan ts)
                {
                        return TryAdd (item, (int)ts.TotalMilliseconds);
                }
-               
+
                public bool TryAdd (T item, int millisecondsTimeout)
                {
                        Stopwatch sw = Stopwatch.StartNew ();
                        return TryAdd (item, () => sw.ElapsedMilliseconds < millisecondsTimeout, null);
                }
-               
+
                public bool TryAdd (T item, int millisecondsTimeout, CancellationToken token)
                {
                        Stopwatch sw = Stopwatch.StartNew ();
                        return TryAdd (item, () => sw.ElapsedMilliseconds < millisecondsTimeout, token);
                }
-               
+
                public bool TryTake (out T item)
                {
                        return TryTake (out item, null, null);
                }
-               
+
                bool TryTake (out T item, Func<bool> contFunc, CancellationToken? token)
                {
                        item = default (T);
-                       
+
                        do {
                                if (token.HasValue && token.Value.IsCancellationRequested)
                                        throw new OperationCanceledException ("The CancellationToken has had cancellation requested.");
-                               
+
                                long cachedRemoveId = removeId;
                                long cachedAddId = addId;
-                               
+
                                // Empty case
                                if (cachedRemoveId == cachedAddId) {
-                                       if (isComplete.Value && cachedRemoveId >= completeId)
-                                               continue;
-                                       
+                                       if (IsCompleted)
+                                               return false;
+
                                        continue;
                                }
-                               
+
                                if (Interlocked.CompareExchange (ref removeId, cachedRemoveId + 1, cachedRemoveId) != cachedRemoveId)
                                        continue;
-                               
+
                                return underlyingColl.TryTake (out item);
                        } while (contFunc != null && contFunc ());
-                       
+
                        return false;
                }
-               
+
                public bool TryTake (out T item, TimeSpan ts)
                {
                        return TryTake (out item, (int)ts.TotalMilliseconds);
                }
-               
+
                public bool TryTake (out T item, int millisecondsTimeout)
                {
                        item = default (T);
                        Stopwatch sw = Stopwatch.StartNew ();
-                       
+
                        return TryTake (out item, () => sw.ElapsedMilliseconds < millisecondsTimeout, null);
                }
-               
+
                public bool TryTake (out T item, int millisecondsTimeout, CancellationToken token)
                {
                        item = default (T);
                        Stopwatch sw = Stopwatch.StartNew ();
-                       
+
                        return TryTake (out item, () => sw.ElapsedMilliseconds < millisecondsTimeout, token);
                }
                #endregion
-               
+
                #region static methods
                static void CheckArray (BlockingCollection<T>[] collections)
                {
@@ -271,7 +269,7 @@ namespace System.Collections.Concurrent
                        if (collections.Length == 0 || IsThereANullElement (collections))
                                throw new ArgumentException ("The collections argument is a 0-length array or contains a null element.", "collections");
                }
-               
+
                static bool IsThereANullElement (BlockingCollection<T>[] collections)
                {
                        foreach (BlockingCollection<T> e in collections)
@@ -279,7 +277,7 @@ namespace System.Collections.Concurrent
                                        return true;
                        return false;
                }
-               
+
                public static int AddToAny (BlockingCollection<T>[] collections, T item)
                {
                        CheckArray (collections);
@@ -293,7 +291,7 @@ namespace System.Collections.Concurrent
                        }
                        return -1;
                }
-               
+
                public static int AddToAny (BlockingCollection<T>[] collections, T item, CancellationToken token)
                {
                        CheckArray (collections);
@@ -307,7 +305,7 @@ namespace System.Collections.Concurrent
                        }
                        return -1;
                }
-               
+
                public static int TryAddToAny (BlockingCollection<T>[] collections, T item)
                {
                        CheckArray (collections);
@@ -319,7 +317,7 @@ namespace System.Collections.Concurrent
                        }
                        return -1;
                }
-               
+
                public static int TryAddToAny (BlockingCollection<T>[] collections, T item, TimeSpan ts)
                {
                        CheckArray (collections);
@@ -331,7 +329,7 @@ namespace System.Collections.Concurrent
                        }
                        return -1;
                }
-               
+
                public static int TryAddToAny (BlockingCollection<T>[] collections, T item, int millisecondsTimeout)
                {
                        CheckArray (collections);
@@ -343,7 +341,7 @@ namespace System.Collections.Concurrent
                        }
                        return -1;
                }
-               
+
                public static int TryAddToAny (BlockingCollection<T>[] collections, T item, int millisecondsTimeout,
                                               CancellationToken token)
                {
@@ -356,7 +354,7 @@ namespace System.Collections.Concurrent
                        }
                        return -1;
                }
-               
+
                public static int TakeFromAny (BlockingCollection<T>[] collections, out T item)
                {
                        item = default (T);
@@ -371,7 +369,7 @@ namespace System.Collections.Concurrent
                        }
                        return -1;
                }
-               
+
                public static int TakeFromAny (BlockingCollection<T>[] collections, out T item, CancellationToken token)
                {
                        item = default (T);
@@ -386,11 +384,11 @@ namespace System.Collections.Concurrent
                        }
                        return -1;
                }
-               
+
                public static int TryTakeFromAny (BlockingCollection<T>[] collections, out T item)
                {
                        item = default (T);
-                       
+
                        CheckArray (collections);
                        int index = 0;
                        foreach (var coll in collections) {
@@ -400,11 +398,11 @@ namespace System.Collections.Concurrent
                        }
                        return -1;
                }
-               
+
                public static int TryTakeFromAny (BlockingCollection<T>[] collections, out T item, TimeSpan ts)
                {
                        item = default (T);
-                       
+
                        CheckArray (collections);
                        int index = 0;
                        foreach (var coll in collections) {
@@ -414,11 +412,11 @@ namespace System.Collections.Concurrent
                        }
                        return -1;
                }
-               
+
                public static int TryTakeFromAny (BlockingCollection<T>[] collections, out T item, int millisecondsTimeout)
                {
                        item = default (T);
-                       
+
                        CheckArray (collections);
                        int index = 0;
                        foreach (var coll in collections) {
@@ -428,12 +426,12 @@ namespace System.Collections.Concurrent
                        }
                        return -1;
                }
-               
+
                public static int TryTakeFromAny (BlockingCollection<T>[] collections, out T item, int millisecondsTimeout,
                                                  CancellationToken token)
                {
                        item = default (T);
-                       
+
                        CheckArray (collections);
                        int index = 0;
                        foreach (var coll in collections) {
@@ -444,110 +442,113 @@ namespace System.Collections.Concurrent
                        return -1;
                }
                #endregion
-               
+
                public void CompleteAdding ()
                {
                  // No further add beside that point
                  completeId = addId;
                  isComplete.Value = true;
                }
-               
+
                void ICollection.CopyTo (Array array, int index)
                {
                        underlyingColl.CopyTo (array, index);
                }
-               
+
                public void CopyTo (T[] array, int index)
                {
                        underlyingColl.CopyTo (array, index);
                }
-               
+
                public IEnumerable<T> GetConsumingEnumerable ()
                {
                        return GetConsumingEnumerable (Take);
                }
-               
+
                public IEnumerable<T> GetConsumingEnumerable (CancellationToken token)
                {
                        return GetConsumingEnumerable (() => Take (token));
                }
-               
+
                IEnumerable<T> GetConsumingEnumerable (Func<T> getFunc)
                {
                        while (true) {
                                T item = default (T);
-                               
+
                                try {
                                        item = getFunc ();
                                } catch {
                                        break;
                                }
-                               
+
                                yield return item;
                        }
                }
-               
+
                IEnumerator IEnumerable.GetEnumerator ()
                {
                        return ((IEnumerable)underlyingColl).GetEnumerator ();
                }
-               
+
                IEnumerator<T> IEnumerable<T>.GetEnumerator ()
                {
                        return ((IEnumerable<T>)underlyingColl).GetEnumerator ();
                }
-               
+
                public void Dispose ()
                {
-                       
+
                }
-               
+
                protected virtual void Dispose (bool managedRes)
                {
-                       
+
                }
-               
+
                public T[] ToArray ()
                {
                        return underlyingColl.ToArray ();
                }
                
+               [ThreadStatic]
+               SpinWait sw;
+
                // Method used to stall the thread for a limited period of time before retrying an operation
                void Block ()
                {
                        sw.SpinOnce ();
                }
-               
+
                public int BoundedCapacity {
                        get {
                                return upperBound;
                        }
                }
-               
+
                public int Count {
                        get {
                                return underlyingColl.Count;
                        }
                }
-               
+
                public bool IsAddingCompleted {
                        get {
                                return isComplete.Value;
                        }
                }
-               
+
                public bool IsCompleted {
                        get {
                                return isComplete.Value && addId == removeId;
                        }
                }
-               
+
                object ICollection.SyncRoot {
                        get {
                                return underlyingColl.SyncRoot;
                        }
                }
-               
+
                bool ICollection.IsSynchronized {
                        get {
                                return underlyingColl.IsSynchronized;
index 3c0f5605c6b00b553aa9feaf7bd393b989d0f21b..e16569fc2d998c8c1a40988245f7f1e5c80f7195 100644 (file)
@@ -1,3 +1,8 @@
+2010-04-15  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * BlockingCollection.cs:
+       * ConcurrentBag.cs: Add BOOTSTRAP_NET_4_0
+
 2009-12-03  Marek Safar  <marek.safar@gmail.com>
 
        * BlockingCollection.cs, ConcurrentBag.cs: Updated to Beta 2 API.
index 02fcc03e974d56a04b61e9eef9510a51b166f103..984a4a69767459c78fa7b7642e45309fa623949a 100644 (file)
@@ -41,8 +41,8 @@ namespace System.Collections.Concurrent
        [DebuggerTypeProxy (typeof (CollectionDebuggerView<>))]
        public class ConcurrentBag<T> : IProducerConsumerCollection<T>, IEnumerable<T>, IEnumerable
        {
+               const int multiplier = 2;
                int size = Environment.ProcessorCount + 1;
-               int multiplier = 2;
                int count;
                
                CyclicDeque<T>[] container;
index 650521244b9de5d54939a01d250ea83f727ded4d..75074d15d433ad68b2f4100661a5991680c22b21 100644 (file)
@@ -1,3 +1,94 @@
+2010-04-09  Raja R Harinath  <harinath@hurrynot.org>
+
+       Don't maintain state in the view
+       * SortedSet.cs (SortedSubSet.count): Remove.
+       (SortedSubSet..ctor): Move counting loop ...
+       (SortedSubSet.Count): ... here.
+       (SortedSubSet.TryAdd, SortedSubSet.TryRemove): Update to changes.
+       (SortedSubSet.GetMin, SortedSubSet.GetMax): Likewise.  Use bounds
+       to determine if the view is empty, rather than the count.
+
+2010-04-07  Raja R Harinath  <harinath@hurrynot.org>
+
+       Enable set comparision operations on views, and improve performance
+       * RBTree.cs (Bound): New.  Returns the greatest lower bound and
+       least upper bound of the given key.
+       (GetSuffixEnumerator): New.  Returns an enumerator that starts at
+       the given key.
+       (NodeEnumerator): Provide suffix enumerator functionality.
+       * SortedSet.cs (GetEnumerator): Delegate to ...
+       (TryGetEnumerator): ... this.  New virtual function.
+       (Enumerator): Provide subset enumeration using RBTree's suffix enumerators.
+       (SortedSubSet.count): New.
+       (SortedSubSet.GetCount): Use it.
+       (SortedSubSet.TryAdd, SortedSubSet.TryRemove): Update count.
+       (SortedSubSet.GetMin, SortedSubSet.GetMax): Use RBTree.Bound().
+       (SortedSubSet.GetEnumerator): Remove.
+       (SortedSubSet.TryGetEnumerator): New.  Use ranged enumerators.
+
+2010-04-06  Jb Evain  <jbevain@novell.com>
+
+       * SortedSet.cs: implement Count for SortedSubSet.
+
+2010-04-05  Raja R Harinath  <harinath@hurrynot.org>
+
+       * SortedSet.cs (IsProperSubsetOf, IsSubsetOf): Implement using ...
+       (is_subset_of): ... new helper.
+       (IsProperSupersetOf, IsSupersetOf): Implement using ...
+       (is_superset_of): ... new helper.
+       (covers, nodups, overlaps): New helpers.
+       (SetEquals): Implement.
+       (Overlaps): Implement using overlaps().
+       (SymmetricExceptWith): Use nodups() helper.
+
+2010-04-04  Raja R Harinath  <harinath@hurrynot.org>
+
+       * SortedSet.cs (CheckArgumentNotNull): New helper.
+       (IntersectWith, UnionWith): Implement.
+       (ExceptWith, SymmetricExceptWith): Likewise.
+       (SortedSubSet.IntersectWith): Implement override.
+
+       * RBTree.cs (do_remove): Ensure the node returned is suitable for
+       re-insertion.
+
+2010-04-02  Jb Evain  <jbevain@novell.com>
+
+       * SortedSet.cs: implement Mix and Max for subsets.
+
+2010-04-02  Jb Evain  <jbevain@novell.com>
+
+       * SortedSet.cs: implement GetViewBetween.
+
+2010-04-02  Jb Evain  <jbevain@novell.com>
+
+       * SortedSet.cs: optimize Reverse. Add a virtual TryAdd and TryRemove
+       to override in sub trees.
+
+2010-04-02  Jb Evain  <jbevain@novell.com>
+
+       * SortedSet.cs: implement Min and Max.
+
+2010-04-02  Jb Evain  <jbevain@novell.com>
+
+       * SortedSet.cs: implement RemoveWhere.
+
+2010-04-02  Jb Evain  <jbevain@novell.com>
+
+       * SortedSet.cs: implement Reverse.
+
+2010-04-01  Jb Evain  <jbevain@novell.com>
+
+       * SortedSet.cs: fix API.
+
+2010-04-01  Jb Evain  <jbevain@novell.com>
+
+       * SortedSet.cs: add new SortedSet type in .net 4.0
+
+2010-03-03  Miguel de Icaza  <miguel@novell.com>
+
+       * RBTree.cs: Make these serializable, should fix the serialization
+       across appdomains of SortedDictionaries
+
 2010-03-11  Sebastien Pouliot  <sebastien@ximian.com>
 
        * ISet.cs: Add NET_2_1 since this is part of SL4
index aebca0bcfe8651feaefc65864745a884e65f91f2..74f142f006b9e04e719ecca121eacd6cb508ada6 100644 (file)
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 #if NET_2_1 || NET_4_0 || BOOTSTRAP_NET_4_0
-using System.Collections.Generic;
 
 namespace System.Collections.Generic {
-       public interface ISet<T> : ICollection<T>, IEnumerable<T>, IEnumerable
+       public interface ISet<T> : ICollection<T>
        {
-               bool Add (T item);
+               new bool Add (T item);
                void ExceptWith (IEnumerable<T> other);
                void IntersectWith (IEnumerable<T> other);
                bool IsProperSubsetOf (IEnumerable<T> other);
index 6325f32ff2e75df60cb886c22ff08fa1d2d33d24..de0fe796fef9a9f52e95728f8024ee8681abc454 100644 (file)
@@ -36,6 +36,7 @@ using System.Collections;
 
 namespace System.Collections.Generic
 {
+       [Serializable]
        internal class RBTree : IEnumerable, IEnumerable<RBTree.Node> {
                public interface INodeHelper<T> {
                        int Compare (T key, Node node);
@@ -221,6 +222,22 @@ namespace System.Collections.Generic
                        return current;
                }
 
+               public void Bound<T> (T key, ref Node lower, ref Node upper)
+               {
+                       INodeHelper<T> hlp = (INodeHelper<T>) this.hlp;
+                       Node current = root;
+                       while (current != null) {
+                               int c = hlp.Compare (key, current);
+                               if (c <= 0)
+                                       upper = current;
+                               if (c >= 0)
+                                       lower = current;
+                               if (c == 0)
+                                       break;
+                               current = c < 0 ? current.left : current.right;
+                       }
+               }
+
                public int Count {
                        get { return root == null ? 0 : (int) root.Size; }
                }
@@ -251,6 +268,23 @@ namespace System.Collections.Generic
                        return new NodeEnumerator (this);
                }
 
+               // Get an enumerator that starts at 'key' or the next higher element in the tree
+               public NodeEnumerator GetSuffixEnumerator<T> (T key)
+               {
+                       var pennants = new Stack<Node> ();
+                       INodeHelper<T> hlp = (INodeHelper<T>) this.hlp;
+                       Node current = root;
+                       while (current != null) {
+                               int c = hlp.Compare (key, current);
+                               if (c <= 0)
+                                       pennants.Push (current);
+                               if (c == 0)
+                                       break;
+                               current = c < 0 ? current.left : current.right;
+                       }
+                       return new NodeEnumerator (this, pennants);
+               }
+
                IEnumerator<Node> IEnumerable<Node>.GetEnumerator ()
                {
                        return GetEnumerator ();
@@ -365,8 +399,11 @@ namespace System.Collections.Generic
                        for (int i = 0; i < path.Count - 2; i += 2)
                                -- path [i].Size;
 
-                       if (curpos != 0 && current.IsBlack)
-                               rebalance_delete (path);
+                       if (current.IsBlack) {
+                               current.IsBlack = false;
+                               if (curpos != 0)
+                                       rebalance_delete (path);
+                       }
 
                        if (root != null && !root.IsBlack)
                                throw new SystemException ("Internal Error: root is not black");
@@ -576,17 +613,24 @@ namespace System.Collections.Generic
                        }
                }
 
+               [Serializable]
                public struct NodeEnumerator : IEnumerator, IEnumerator<Node> {
                        RBTree tree;
                        uint version;
 
-                       Stack<Node> pennants;
+                       Stack<Node> pennants, init_pennants;
 
                        internal NodeEnumerator (RBTree tree)
+                               : this ()
                        {
                                this.tree = tree;
                                version = tree.version;
-                               pennants = null;
+                       }
+
+                       internal NodeEnumerator (RBTree tree, Stack<Node> init_pennants)
+                               : this (tree)
+                       {
+                               this.init_pennants = init_pennants;
                        }
 
                        public void Reset ()
@@ -614,6 +658,11 @@ namespace System.Collections.Generic
                                if (pennants == null) {
                                        if (tree.root == null)
                                                return false;
+                                       if (init_pennants != null) {
+                                               pennants = init_pennants;
+                                               init_pennants = null;
+                                               return pennants.Count != 0;
+                                       }
                                        pennants = new Stack<Node> ();
                                        next = tree.root;
                                } else {
@@ -812,10 +861,13 @@ namespace Mono.ValidationTest {
                        Dictionary<int, int> d = new Dictionary<int, int> ();
                        TreeSet<int> t = new TreeSet<int> ();
                        int iters = args.Length == 0 ? 100000 : Int32.Parse (args [0]);
+                       int watermark = 1;
 
                        for (int i = 0; i < iters; ++i) {
-                               if ((i % 100) == 0)
+                               if (i >= watermark) {
+                                       watermark += 1 + watermark/4;
                                        t.VerifyInvariants ();
+                               }
 
                                int n = r.Next ();
                                if (d.ContainsKey (n))
@@ -866,14 +918,18 @@ namespace Mono.ValidationTest {
                                }
                        }
 
-                       int j = 0;
+                       int count = t.Count;
                        foreach (int n in d.Keys) {
-                               if ((j++ % 100) == 0)
+                               if (count <= watermark) {
+                                       watermark -= watermark/4;
                                        t.VerifyInvariants ();
+                               }
                                try {
                                        if (!t.Remove (n))
                                                throw new Exception ("tree says it doesn't have a number it should");
-
+                                       --count;
+                                       if (t.Count != count)
+                                               throw new Exception ("Remove didn't remove exactly one element");
                                } catch {
                                        Console.Error.WriteLine ("While trying to remove {0} from tree of size {1}", n, t.Count);
                                        t.Dump ();
diff --git a/mcs/class/System/System.Collections.Generic/SortedSet.cs b/mcs/class/System/System.Collections.Generic/SortedSet.cs
new file mode 100644 (file)
index 0000000..75b8157
--- /dev/null
@@ -0,0 +1,748 @@
+//
+// SortedSet.cs
+//
+// Authors:
+//  Jb Evain  <jbevain@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Runtime.Serialization;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Security.Permissions;
+using System.Diagnostics;
+
+// SortedSet is basically implemented as a reduction of SortedDictionary<K, V>
+
+#if NET_4_0
+
+namespace System.Collections.Generic {
+
+       [Serializable]
+       [DebuggerDisplay ("Count={Count}")]
+       [DebuggerTypeProxy (typeof (CollectionDebuggerView))]
+       public class SortedSet<T> : ISet<T>, ICollection, ISerializable, IDeserializationCallback
+       {
+               class Node : RBTree.Node {
+
+                       public T item;
+
+                       public Node (T item)
+                       {
+                               this.item = item;
+                       }
+
+                       public override void SwapValue (RBTree.Node other)
+                       {
+                               var o = (Node) other;
+                               var i = this.item;
+                               this.item = o.item;
+                               o.item = i;
+                       }
+               }
+
+               class NodeHelper : RBTree.INodeHelper<T> {
+
+                       static NodeHelper Default = new NodeHelper (Comparer<T>.Default);
+
+                       public IComparer<T> comparer;
+
+                       public int Compare (T item, RBTree.Node node)
+                       {
+                               return comparer.Compare (item, ((Node) node).item);
+                       }
+
+                       public RBTree.Node CreateNode (T item)
+                       {
+                               return new Node (item);
+                       }
+
+                       NodeHelper (IComparer<T> comparer)
+                       {
+                               this.comparer = comparer;
+                       }
+
+                       public static NodeHelper GetHelper (IComparer<T> comparer)
+                       {
+                               if (comparer == null || comparer == Comparer<T>.Default)
+                                       return Default;
+
+                               return new NodeHelper (comparer);
+                       }
+               }
+
+               RBTree tree;
+               NodeHelper helper;
+               SerializationInfo si;
+
+               public SortedSet ()
+                       : this (Comparer<T>.Default)
+               {
+               }
+
+               public SortedSet (IEnumerable<T> collection)
+                       : this (collection, Comparer<T>.Default)
+               {
+               }
+
+               public SortedSet (IEnumerable<T> collection, IComparer<T> comparer)
+                       : this (comparer)
+               {
+                       if (collection == null)
+                               throw new ArgumentNullException ("collection");
+
+                       foreach (var item in collection)
+                               Add (item);
+               }
+
+               public SortedSet (IComparer<T> comparer)
+               {
+                       this.helper = NodeHelper.GetHelper (comparer);
+                       this.tree = new RBTree (this.helper);
+               }
+
+               protected SortedSet (SerializationInfo info, StreamingContext context)
+               {
+                       this.si = info;
+               }
+
+               public IComparer<T> Comparer {
+                       get { return helper.comparer; }
+               }
+
+               public int Count {
+                       get { return GetCount (); }
+               }
+
+               public T Max {
+                       get { return GetMax (); }
+               }
+
+               public T Min {
+                       get {  return GetMin (); }
+               }
+
+               internal virtual T GetMax ()
+               {
+                       if (tree.Count == 0)
+                               return default (T);
+
+                       return GetItem (tree.Count - 1);
+               }
+
+               internal virtual T GetMin ()
+               {
+                       if (tree.Count == 0)
+                               return default (T);
+
+                       return GetItem (0);
+               }
+
+               internal virtual int GetCount ()
+               {
+                       return tree.Count;
+               }
+
+               T GetItem (int index)
+               {
+                       return ((Node) tree [index]).item;
+               }
+
+               public bool Add (T item)
+               {
+                       return TryAdd (item);
+               }
+
+               internal virtual bool TryAdd (T item)
+               {
+                       var node = new Node (item);
+                       return tree.Intern (item, node) == node;
+               }
+
+               public virtual void Clear ()
+               {
+                       tree.Clear ();
+               }
+
+               public virtual bool Contains (T item)
+               {
+                       return tree.Lookup (item) != null;
+               }
+
+               public void CopyTo (T [] array)
+               {
+                       CopyTo (array, 0, Count);
+               }
+
+               public void CopyTo (T [] array, int index)
+               {
+                       CopyTo (array, index, Count);
+               }
+
+               public void CopyTo (T [] array, int index, int count)
+               {
+                       if (array == null)
+                               throw new ArgumentNullException ("array");
+                       if (index < 0)
+                               throw new ArgumentOutOfRangeException ("index");
+                       if (index > array.Length)
+                               throw new ArgumentException ("index larger than largest valid index of array");
+                       if (array.Length - index < count)
+                               throw new ArgumentException ("destination array cannot hold the requested elements");
+
+                       foreach (Node node in tree) {
+                               if (count-- == 0)
+                                       break;
+
+                               array [index++] = node.item;
+                       }
+               }
+
+               public bool Remove (T item)
+               {
+                       return TryRemove (item);
+               }
+
+               internal virtual bool TryRemove (T item)
+               {
+                       return tree.Remove (item) != null;
+               }
+
+               public int RemoveWhere (Predicate<T> match)
+               {
+                       var array = ToArray ();
+
+                       int count = 0;
+                       foreach (var item in array) {
+                               if (!match (item))
+                                       continue;
+
+                               Remove (item);
+                               count++;
+                       }
+
+                       return count;
+               }
+
+               public IEnumerable<T> Reverse ()
+               {
+                       for (int i = tree.Count - 1; i >= 0; i--)
+                               yield return GetItem (i);
+               }
+
+               T [] ToArray ()
+               {
+                       var array = new T [this.Count];
+                       CopyTo (array);
+                       return array;
+               }
+
+               public Enumerator GetEnumerator ()
+               {
+                       return TryGetEnumerator ();
+               }
+
+               internal virtual Enumerator TryGetEnumerator ()
+               {
+                       return new Enumerator (this);
+               }
+
+               IEnumerator<T> IEnumerable<T>.GetEnumerator ()
+               {
+                       return GetEnumerator ();
+               }
+
+               IEnumerator IEnumerable.GetEnumerator ()
+               {
+                       return GetEnumerator ();
+               }
+
+               public static IEqualityComparer<SortedSet<T>> CreateSetComparer ()
+               {
+                       return CreateSetComparer (EqualityComparer<T>.Default);
+               }
+
+               [MonoTODO]
+               public static IEqualityComparer<SortedSet<T>> CreateSetComparer (IEqualityComparer<T> memberEqualityComparer)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               [MonoTODO]
+               protected virtual void GetObjectData (SerializationInfo info, StreamingContext context)
+               {
+                       throw new NotImplementedException ();
+               }
+
+               void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
+               {
+                       GetObjectData (info, context);
+               }
+
+               [MonoTODO]
+               protected virtual void OnDeserialization (object sender)
+               {
+                       if (si == null)
+                               return;
+
+                       throw new NotImplementedException ();
+               }
+
+               void IDeserializationCallback.OnDeserialization (object sender)
+               {
+                       OnDeserialization (sender);
+               }
+
+               [MonoLimitation ("Isn't O(n) when other is SortedSet<T>")]
+               public void ExceptWith (IEnumerable<T> other)
+               {
+                       CheckArgumentNotNull (other, "other");
+                       foreach (T item in other)
+                               Remove (item);
+               }
+
+               public virtual SortedSet<T> GetViewBetween (T lowerValue, T upperValue)
+               {
+                       if (Comparer.Compare (lowerValue, upperValue) > 0)
+                               throw new ArgumentException ("The lowerValue is bigger than upperValue");
+
+                       return new SortedSubSet (this, lowerValue, upperValue);
+               }
+
+               [MonoLimitation ("Isn't O(n) when other is SortedSet<T>")]
+               public virtual void IntersectWith (IEnumerable<T> other)
+               {
+                       CheckArgumentNotNull (other, "other");
+
+                       RBTree newtree = new RBTree (helper);
+                       foreach (T item in other) {
+                               var node = tree.Remove (item);
+                               if (node != null)
+                                       newtree.Intern (item, node);
+                       }
+                       tree = newtree;
+               }
+
+               public bool IsProperSubsetOf (IEnumerable<T> other)
+               {
+                       CheckArgumentNotNull (other, "other");
+
+                       if (Count == 0) {
+                               foreach (T item in other)
+                                       return true; // this idiom means: if 'other' is non-empty, return true
+                               return false;
+                       }
+
+                       return is_subset_of (other, true);
+               }
+
+               public bool IsProperSupersetOf (IEnumerable<T> other)
+               {
+                       CheckArgumentNotNull (other, "other");
+
+                       if (Count == 0)
+                               return false;
+
+                       return is_superset_of (other, true);
+               }
+
+               public bool IsSubsetOf (IEnumerable<T> other)
+               {
+                       CheckArgumentNotNull (other, "other");
+
+                       if (Count == 0)
+                               return true;
+
+                       return is_subset_of (other, false);
+               }
+
+               public bool IsSupersetOf (IEnumerable<T> other)
+               {
+                       CheckArgumentNotNull (other, "other");
+
+                       if (Count == 0) {
+                               foreach (T item in other)
+                                       return false; // this idiom means: if 'other' is non-empty, return false
+                               return true;
+                       }
+
+                       return is_superset_of (other, false);
+               }
+
+               // Precondition: Count != 0, other != null
+               bool is_subset_of (IEnumerable<T> other, bool proper)
+               {
+                       SortedSet<T> that = nodups (other);
+
+                       if (Count > that.Count)
+                               return false;
+                       // Count != 0 && Count <= that.Count => that.Count != 0
+                       if (proper && Count == that.Count)
+                               return false;
+                       return that.covers (this);
+               }
+
+               // Precondition: Count != 0, other != null
+               bool is_superset_of (IEnumerable<T> other, bool proper)
+               {
+                       SortedSet<T> that = nodups (other);
+
+                       if (that.Count == 0)
+                               return true;
+                       if (Count < that.Count)
+                               return false;
+                       if (proper && Count == that.Count)
+                               return false;
+                       return this.covers (that);
+               }
+
+               public bool Overlaps (IEnumerable<T> other)
+               {
+                       CheckArgumentNotNull (other, "other");
+
+                       if (Count == 0)
+                               return false;
+
+                       // Don't use 'nodups' here.  Only optimize the SortedSet<T> case
+                       SortedSet<T> that = other as SortedSet<T>;
+                       if (that != null && that.Comparer != Comparer)
+                               that = null;
+
+                       if (that != null)
+                               return that.Count != 0 && overlaps (that);
+
+                       foreach (T item in other)
+                               if (Contains (item))
+                                       return true;
+                       return false;
+               }
+
+               public bool SetEquals (IEnumerable<T> other)
+               {
+                       CheckArgumentNotNull (other, "other");
+
+                       if (Count == 0) {
+                               foreach (T item in other)
+                                       return false;
+                               return true;
+                       }
+
+                       SortedSet<T> that = nodups (other);
+
+                       if (Count != that.Count)
+                               return false;
+
+                       using (var t = that.GetEnumerator ()) {
+                               foreach (T item in this) {
+                                       if (!t.MoveNext ())
+                                               throw new SystemException ("count wrong somewhere: this longer than that");
+                                       if (Comparer.Compare (item, t.Current) != 0)
+                                               return false;
+                               }
+                               if (t.MoveNext ())
+                                       throw new SystemException ("count wrong somewhere: this shorter than that");
+                               return true;
+                       }
+               }
+
+               SortedSet<T> nodups (IEnumerable<T> other)
+               {
+                       SortedSet<T> that = other as SortedSet<T>;
+                       if (that != null && that.Comparer == Comparer)
+                               return that;
+                       return new SortedSet<T> (other, Comparer);
+               }
+
+               bool covers (SortedSet<T> that)
+               {
+                       using (var t = that.GetEnumerator ()) {
+                               if (!t.MoveNext ())
+                                       return true;
+                               foreach (T item in this) {
+                                       int cmp = Comparer.Compare (item, t.Current);
+                                       if (cmp > 0)
+                                               return false;
+                                       if (cmp == 0 && !t.MoveNext ())
+                                               return true;
+                               }
+                               return false;
+                       }
+               }
+
+               bool overlaps (SortedSet<T> that)
+               {
+                       using (var t = that.GetEnumerator ()) {
+                               if (!t.MoveNext ())
+                                       return false;
+                               foreach (T item in this) {
+                                       int cmp;
+                                       while ((cmp = Comparer.Compare (item, t.Current)) > 0) {
+                                               if (!t.MoveNext ())
+                                                       return false;
+                                       }
+                                       if (cmp == 0)
+                                               return true;
+                               }
+                               return false;
+                       }
+               }
+
+               [MonoLimitation ("Isn't O(n) when other is SortedSet<T>")]
+               public void SymmetricExceptWith (IEnumerable<T> other)
+               {
+                       SortedSet<T> that_minus_this = new SortedSet<T> (Comparer);
+
+                       // compute this - that and that - this in parallel
+                       foreach (T item in nodups (other))
+                               if (!Remove (item))
+                                       that_minus_this.Add (item);
+
+                       UnionWith (that_minus_this);
+               }
+
+               [MonoLimitation ("Isn't O(n) when other is SortedSet<T>")]
+               public void UnionWith (IEnumerable<T> other)
+               {
+                       CheckArgumentNotNull (other, "other");
+
+                       foreach (T item in other)
+                               Add (item);
+               }
+
+               static void CheckArgumentNotNull (object arg, string name)
+               {
+                       if (arg == null)
+                               throw new ArgumentNullException (name);
+               }
+
+               void ICollection<T>.Add (T item)
+               {
+                       Add (item);
+               }
+
+               void ICollection<T>.CopyTo (T [] array, int index)
+               {
+                       CopyTo (array, index, Count);
+               }
+
+               bool ICollection<T>.IsReadOnly {
+                       get { return false; }
+               }
+
+               void ICollection.CopyTo (Array array, int index)
+               {
+                       if (Count == 0)
+                               return;
+                       if (array == null)
+                               throw new ArgumentNullException ("array");
+                       if (index < 0 || array.Length <= index)
+                               throw new ArgumentOutOfRangeException ("index");
+                       if (array.Length - index < Count)
+                               throw new ArgumentException ();
+
+                       foreach (Node node in tree)
+                               array.SetValue (node.item, index++);
+               }
+
+               bool ICollection.IsSynchronized {
+                       get { return false; }
+               }
+
+               // TODO:Is this correct? If this is wrong,please fix.
+               object ICollection.SyncRoot {
+                       get { return this; }
+               }
+
+               [Serializable]
+               public struct Enumerator : IEnumerator<T>, IDisposable {
+
+                       RBTree.NodeEnumerator host;
+
+                       IComparer<T> comparer;
+
+                       T current;
+                       T upper;
+
+                       internal Enumerator (SortedSet<T> set)
+                               : this ()
+                       {
+                               host = set.tree.GetEnumerator ();
+                       }
+
+                       internal Enumerator (SortedSet<T> set, T lower, T upper)
+                               : this ()
+                       {
+                               host = set.tree.GetSuffixEnumerator (lower);
+                               comparer = set.Comparer;
+                               this.upper = upper;
+                       }
+
+                       public T Current {
+                               get { return current; }
+                       }
+
+                       object IEnumerator.Current {
+                               get {
+                                       host.check_current ();
+                                       return ((Node) host.Current).item;
+                               }
+                       }
+
+                       public bool MoveNext ()
+                       {
+                               if (!host.MoveNext ())
+                                       return false;
+
+                               current = ((Node) host.Current).item;
+                               return comparer == null || comparer.Compare (upper, current) >= 0;
+                       }
+
+                       public void Dispose ()
+                       {
+                               host.Dispose ();
+                       }
+
+                       void IEnumerator.Reset ()
+                       {
+                               host.Reset ();
+                       }
+               }
+
+               [Serializable]
+               sealed class SortedSubSet : SortedSet<T>, IEnumerable<T>, IEnumerable {
+
+                       SortedSet<T> set;
+                       T lower;
+                       T upper;
+
+                       public SortedSubSet (SortedSet<T> set, T lower, T upper)
+                               : base (set.Comparer)
+                       {
+                               this.set = set;
+                               this.lower = lower;
+                               this.upper = upper;
+
+                       }
+
+                       internal override T GetMin ()
+                       {
+                               RBTree.Node lb = null, ub = null;
+                               set.tree.Bound (lower, ref lb, ref ub);
+
+                               if (ub == null || set.helper.Compare (upper, ub) < 0)
+                                       return default (T);
+
+                               return ((Node) ub).item;
+                       }
+
+                       internal override T GetMax ()
+                       {
+                               RBTree.Node lb = null, ub = null;
+                               set.tree.Bound (upper, ref lb, ref ub);
+
+                               if (lb == null || set.helper.Compare (lower, lb) > 0)
+                                       return default (T);
+
+                               return ((Node) lb).item;
+                       }
+
+                       internal override int GetCount ()
+                       {
+                               int count = 0;
+                               using (var e = set.tree.GetSuffixEnumerator (lower)) {
+                                       while (e.MoveNext () && set.helper.Compare (upper, e.Current) >= 0)
+                                               ++count;
+                               }
+                               return count;
+                       }
+
+                       internal override bool TryAdd (T item)
+                       {
+                               if (!InRange (item))
+                                       throw new ArgumentOutOfRangeException ("item");
+
+                               return set.TryAdd (item);
+                       }
+
+                       internal override bool TryRemove (T item)
+                       {
+                               if (!InRange (item))
+                                       return false;
+
+                               return set.TryRemove (item);
+                       }
+
+                       public override bool Contains (T item)
+                       {
+                               if (!InRange (item))
+                                       return false;
+
+                               return set.Contains (item);
+                       }
+
+                       public override void Clear ()
+                       {
+                               set.RemoveWhere (InRange);
+                       }
+
+                       bool InRange (T item)
+                       {
+                               return Comparer.Compare (item, lower) >= 0
+                                       && Comparer.Compare (item, upper) <= 0;
+                       }
+
+                       public override SortedSet<T> GetViewBetween (T lowerValue, T upperValue)
+                       {
+                               if (Comparer.Compare (lowerValue, upperValue) > 0)
+                                       throw new ArgumentException ("The lowerValue is bigger than upperValue");
+                               if (!InRange (lowerValue))
+                                       throw new ArgumentOutOfRangeException ("lowerValue");
+                               if (!InRange (upperValue))
+                                       throw new ArgumentOutOfRangeException ("upperValue");
+
+                               return new SortedSubSet (set, lowerValue, upperValue);
+                       }
+
+                       internal override Enumerator TryGetEnumerator ()
+                       {
+                               return new Enumerator (set, lower, upper);
+                       }
+
+                       public override void IntersectWith (IEnumerable<T> other)
+                       {
+                               CheckArgumentNotNull (other, "other");
+
+                               var slice = new SortedSet<T> (this);
+                               slice.IntersectWith (other);
+
+                               Clear ();
+                               set.UnionWith (slice);
+                       }
+               }
+       }
+}
+
+#endif
index e4e61199c69b9acef0b525e3906d97230ddb267f..8e68d59004f1aaaa1590ac2584798dd452e71f65 100644 (file)
@@ -1,3 +1,13 @@
+2010-03-20  Miguel de Icaza  <miguel@novell.com>
+
+       * TypeDescriptor.cs: Remove warning.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * TypeConverter_2_1.cs, ComponentCollection.cs,
+       PropertyDescriptor.cs: use MOONLIGHT symbol to disambiguate
+       MonoTouch and Moonlight code.
+
 2010-02-05  Carlos Alberto Cortez <calberto.cortez@gmail.com>
 
        * MaskedTextProvider.cs: In ToString() if we are a password, use the
index d09bc22bfae8e14bc4beb19f9013aaee10c0d3a8..cb34124823f9a1d8c71fa6c30fdae213af38187c 100644 (file)
@@ -38,7 +38,7 @@ using System.Reflection;
 
 namespace System.ComponentModel {
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
        public class ComponentCollection
        {
        }
index f636f59878482d8ad03d56a09108e52bcf00f4b8..74940e0787d9f660fcbd8a582e76ef16e121d14c 100644 (file)
@@ -39,7 +39,7 @@ using System.Runtime.InteropServices;
 
 namespace System.ComponentModel
 {
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
        public abstract class PropertyDescriptor
        {
        }
index ad4dd816db3c58b46dad6372bfc599e7d626b0b1..f27107bb010e25cfd1aa02ccea92c611c9d77a92 100644 (file)
@@ -23,7 +23,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
 
 using System;
 using System.Globalization;
index 614ede271fc479e93171733a0db92f6644e3d390..35df4f0410e2b3420fa350183039717c37bd10b0 100644 (file)
@@ -863,14 +863,14 @@ public sealed class TypeDescriptor
                if (instance == null)
                        throw new ArgumentNullException ("instance");
 
-               bool removed = false;
+               //bool removed = false;
                lock (componentDescriptionProvidersLock) {
                        LinkedList <TypeDescriptionProvider> plist;
                        WeakObjectWrapper instanceWrapper = new WeakObjectWrapper (instance);
 
                        if (componentDescriptionProviders.TryGetValue (instanceWrapper, out plist) && plist.Count > 0) {
                                RemoveProvider (provider, plist);
-                               removed = true;
+                               //removed = true;
                        }
                        
                        instanceWrapper = null;
@@ -889,13 +889,11 @@ public sealed class TypeDescriptor
                if (type == null)
                        throw new ArgumentNullException ("type");
 
-               bool removed = false;
                lock (typeDescriptionProvidersLock) {
                        LinkedList <TypeDescriptionProvider> plist;
 
                        if (typeDescriptionProviders.TryGetValue (type, out plist) && plist.Count > 0) {
                                RemoveProvider (provider, plist);
-                               removed = true;
                        }
                }
 
index 199d83fe7bb383121660fd6e0dc5199d262e4321..551a263b7316ce891b72c5af8a2bbc6c23084f0b 100644 (file)
@@ -240,7 +240,9 @@ namespace System.Configuration
                public readonly string TypeName;
                public readonly bool AllowLocation;
                public readonly AllowDefinition AllowDefinition;
+#if XML_DEP
                public string FileName;
+#endif
                public readonly bool RequirePermission;
 
                public SectionData (string sectionName, string typeName,
diff --git a/mcs/class/System/System.Diagnostics.CodeAnalysis/ChangeLog b/mcs/class/System/System.Diagnostics.CodeAnalysis/ChangeLog
new file mode 100644 (file)
index 0000000..17d25b0
--- /dev/null
@@ -0,0 +1,3 @@
+2010-04-06  Jb Evain  <jbevain@novell.com>
+
+       * ExcludeFromCodeCoverageAttribute.cs: new attribute.
diff --git a/mcs/class/System/System.Diagnostics.CodeAnalysis/ExcludeFromCodeCoverageAttribute.cs b/mcs/class/System/System.Diagnostics.CodeAnalysis/ExcludeFromCodeCoverageAttribute.cs
new file mode 100644 (file)
index 0000000..fb300c2
--- /dev/null
@@ -0,0 +1,51 @@
+//
+// ExcludeFromCodeCoverageAttribute.cs
+//
+// Authors:
+//  Jb Evain  <jbevain@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+
+#if NET_4_0
+
+namespace System.Diagnostics.CodeAnalysis {
+
+       [AttributeUsage (AttributeTargets.Class
+               | AttributeTargets.Struct
+               | AttributeTargets.Constructor
+               | AttributeTargets.Method
+               | AttributeTargets.Property
+               | AttributeTargets.Event,
+               AllowMultiple = false,
+               Inherited = false)]
+       public sealed class ExcludeFromCodeCoverageAttribute : Attribute
+       {
+               public ExcludeFromCodeCoverageAttribute ()
+               {
+               }
+       }
+}
+
+#endif
index 28c62cd012157bd6ac38b433f3c0059c5205cbe0..acad4d7b93c5c16b048366b4ae180ee270377ccb 100644 (file)
@@ -1,3 +1,11 @@
+2010-04-06  Jb Evain  <jbevain@novell.com>
+
+       * Debug.cs: make class static.
+
+2010-04-06  Jb Evain  <jbevain@novell.com>
+
+       * Debug.cs (Assert, WriteLine): add net_4_0 overloads.
+
 2010-03-11  Sebastien Pouliot  <sebastien@ximian.com>
 
        * Debug_2_1.cs: Change type to static to match SL4
index 34d6b20ff22a506ef102f9b19679f9506f652829..6e53d250e7a456a236cf835057b40a0d484ed917 100644 (file)
@@ -36,9 +36,7 @@ using System.Diagnostics;
 
 namespace System.Diagnostics {
 
-       public sealed class Debug {
-
-               private Debug () {}
+       public static class Debug {
 
                public static bool AutoFlush {
                        get {return TraceImpl.AutoFlush;}
@@ -78,6 +76,17 @@ namespace System.Diagnostics {
                        TraceImpl.Assert (condition, message, detailMessage);
                }
 
+#if NET_4_0
+               [Conditional ("DEBUG")]
+               public static void Assert (bool condition, string message,
+                       string detailMessageFormat, params object [] args)
+               {
+                       TraceImpl.Assert (condition,
+                               message,
+                               string.Format (detailMessageFormat, args));
+               }
+#endif
+
                [Conditional("DEBUG")]
                public static void Close ()
                {
@@ -176,6 +185,14 @@ namespace System.Diagnostics {
                        TraceImpl.WriteLine (message);
                }
 
+#if NET_4_0
+               [Conditional("DEBUG")]
+               public static void WriteLine (string format, params object [] args)
+               {
+                       TraceImpl.WriteLine (string.Format (format, args));
+               }
+#endif
+
                [Conditional("DEBUG")]
                public static void WriteLine (object value, string category)
                {
index 1ff7bf7edd20f91f42c672d8f8ca5d5137e31cdc..bb6f278ba7c2b7ba8a99bece7f3d3580b8bfbab2 100644 (file)
@@ -1,3 +1,13 @@
+2010-04-14 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * DeflateStream.cs: the delegate uses Cdecl calling convention on
+       windows too. Fixes bug #574713.
+
+2010-04-07 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * DeflateStream.cs: always use Cdecl, since the library is compiled
+       using that calling convention in windows too.
+
 2010-03-09 Gonzalo Paniagua Javier <gonzalo@novell.com>
 
        * DeflateStream.cs: don't call unmanaged code when the byte count
index b83ca4c486da965bac17aa4968a33310a1070840..5d484120745ac6c5dc46e8d5eac77f33b47ea855 100644 (file)
@@ -42,6 +42,7 @@ namespace System.IO.Compression {
        public class DeflateStream : Stream
        {
                const int BufferSize = 4096;
+               [UnmanagedFunctionPointer (CallingConvention.Cdecl)]
                delegate int UnmanagedReadOrWrite (IntPtr buffer, int length, IntPtr data);
                delegate int ReadMethod (byte[] array, int offset, int count);
                delegate void WriteMethod (byte[] array, int offset, int count);
@@ -421,19 +422,19 @@ namespace System.IO.Compression {
                const string LIBNAME = "MonoPosixHelper";
 #endif
 
-               [DllImport (LIBNAME)]
+               [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
                static extern IntPtr CreateZStream (CompressionMode compress, bool gzip, UnmanagedReadOrWrite feeder, IntPtr data);
 
-               [DllImport (LIBNAME)]
+               [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
                static extern int CloseZStream (IntPtr stream);
 
-               [DllImport (LIBNAME)]
+               [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
                static extern int Flush (IntPtr stream);
 
-               [DllImport (LIBNAME)]
+               [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
                static extern int ReadZStream (IntPtr stream, IntPtr buffer, int length);
 
-               [DllImport (LIBNAME)]
+               [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
                static extern int WriteZStream (IntPtr stream, IntPtr buffer, int length);
        }
 }
index dcc8fe73574507a2b06e954d7108f1d82fefa518..c15fe2df74085fb2343faf0b4a14ee5107735cb7 100644 (file)
@@ -1,3 +1,10 @@
+2010-04-22  Miguel de Icaza  <miguel@novell.com>
+
+       * SerialPort.cs: Try to detect serial devices in other Unix
+       systems. 
+
+       More tune ups for BSDs.
+
 2010-02-23  Carlos Alberto Cortez <calberto.cortez@gmail.com>
 
        * SerialPort.cs: DiscardNull should *not* report any error if the port
index d6f16be5d36c21991d8aaf6c7d1d2d54d54101a4..b5ac97e046eea1c8bbc656844f3ae557a0271a4e 100644 (file)
@@ -525,9 +525,26 @@ namespace System.IO.Ports
                        // Are we on Unix?
                        if (p == 4 || p == 128 || p == 6) {
                                string[] ttys = Directory.GetFiles("/dev/", "tty*");
+                               bool linux_style = false;
+
+                               //
+                               // Probe for Linux-styled devices: /dev/ttyS* or /dev/ttyUSB*
+                               // 
+                               foreach (string dev in ttys) {
+                                       if (dev.StartsWith("/dev/ttyS") || dev.StartsWith("/dev/ttyUSB")){
+                                               linux_style = true;
+                                               break;
+                                       }
+                               }
+
                                foreach (string dev in ttys) {
-                                       if (dev.StartsWith("/dev/ttyS") || dev.StartsWith("/dev/ttyUSB"))
-                                               serial_ports.Add(dev);
+                                       if (linux_style){
+                                               if (dev.StartsWith("/dev/ttyS") || dev.StartsWith("/dev/ttyUSB"))
+                                                       serial_ports.Add (dev);
+                                       } else {
+                                               if (dev != "/dev/tty" && dev.StartsWith ("/dev/tty") && !dev.StartsWith ("/dev/ttyC"))
+                                                       serial_ports.Add (dev);
+                                       }
                                }
                        } else {
                                using (RegistryKey subkey = Registry.LocalMachine.OpenSubKey("HARDWARE\\DEVICEMAP\\SERIALCOMM"))
index 347bcf82747b7e7017691f15bb5c0597d5b58c14..8fe2b6ae83df9d688041155c05132b316e178951 100644 (file)
@@ -140,6 +140,9 @@ namespace System.Net.Mail {
                                if (cfg.From != null)
                                        defaultFrom = new MailAddress (cfg.From);
                        }
+#else
+                       // Just to eliminate the warning, this codepath does not end up in production.
+                       defaultFrom = null;
 #endif
 
                        if (!String.IsNullOrEmpty (host))
index 4a6c38b3579723979af332880a0a052ba9659434..6c0f25c8a7e50e18250df5321fbd1e6fb1f5c5d5 100644 (file)
@@ -1,3 +1,7 @@
+2010-03-25  Marek Safar  <marek.safar@gmail.com>
+
+       * IPGlobalProperties.cs: Made Win32_IN6_ADDR verifiable.
+
 2009-12-07 Carlos Alberto Cortez <calberto.cortez@gmail.com>
 
        * Ping.cs: Try to detect the path to the bin command, since different
index 74928fb763f37ba1b32934cadee7a3495fe2457d..d3be931cbb03bcaa45d7fb5be6a47c17f8a1d0c1 100644 (file)
@@ -26,7 +26,7 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
-#if NET_2_0
+
 using System.Collections.Generic;
 using System.Collections.Specialized;
 using System.Globalization;
@@ -585,12 +585,6 @@ namespace System.Net.NetworkInformation {
                        [FieldOffset (0)]
                        [MarshalAs ((short) UnmanagedType.U1, SizeConst = 16)]
                        public byte [] Bytes;
-                       [FieldOffset (0)]
-                       [MarshalAs ((short) UnmanagedType.U2, SizeConst = 8)]
-                       public byte [] UInt16Array;
-                       [FieldOffset (0)]
-                       [MarshalAs ((short) UnmanagedType.U4, SizeConst = 4)]
-                       public byte [] UInt32Array;
                }
 
                [StructLayout (LayoutKind.Sequential)]
@@ -663,5 +657,3 @@ namespace System.Net.NetworkInformation {
                }
        }
 }
-#endif
-
index 4f5ac86d7e468df11a5d06773803f0a3438089af..d017319290834e409f659b9303c2c75df04e9d03 100644 (file)
@@ -80,7 +80,6 @@ namespace System.Net.NetworkInformation {
                        try {
                                gateways = new IPAddressCollection ();
                                using (StreamReader reader = new StreamReader ("/proc/net/route")) {
-                                       string str;
                                        string line;
                                        reader.ReadLine (); // Ignore first line
                                        while ((line = reader.ReadLine ()) != null) {
index d3b32c9ffc0dc5c10b33d8bc9ab8bd2be7addc1d..79b9e37ff1ad5749afba520641ae32ad8a5364f7 100644 (file)
@@ -206,11 +206,11 @@ namespace System.Net.NetworkInformation {
        // dummy class
        class MacOsIPv4InterfaceStatistics : IPv4InterfaceStatistics
        {
-               MacOsNetworkInterface macos;
+               //MacOsNetworkInterface macos;
                
                public MacOsIPv4InterfaceStatistics (MacOsNetworkInterface parent)
                {
-                       macos = parent;
+                       //macos = parent;
                }
 
                public override long BytesReceived {
index 5eefd797ed02c54efa9a4587ef2d9453df40fc7e..0dea7a9d19764f73c5f54ecaebfe8c64b3f585e7 100644 (file)
@@ -135,7 +135,7 @@ namespace System.Net.NetworkInformation {
                protected IPInterfaceProperties ipproperties;
                
                string               name;
-               int                  index;
+               //int                  index;
                protected List <IPAddress> addresses;
                byte[]               macAddress;
                NetworkInterfaceType type;
@@ -158,7 +158,7 @@ namespace System.Net.NetworkInformation {
 
                internal void SetLinkLayerInfo (int index, byte[] macAddress, NetworkInterfaceType type)
                {
-                       this.index = index;
+                       //this.index = index;
                        this.macAddress = macAddress;
                        this.type = type;
                }
@@ -233,7 +233,7 @@ namespace System.Net.NetworkInformation {
                const int AF_INET6  = 10;
                const int AF_PACKET = 17;
                
-               NetworkInterfaceType type;
+               //NetworkInterfaceType type;
                string               iface_path;
                string               iface_operstate_path;
                string               iface_flags_path;          
index 19bde8f1259da67627eee8b13990267936eb0b6e..4f7f7b7b998d1dec0ccc58a39c56a97efa6156ef 100644 (file)
@@ -288,7 +288,6 @@ namespace System.Net.NetworkInformation {
                        ping.StartInfo.RedirectStandardOutput = true;
                        ping.StartInfo.RedirectStandardError = true;
 
-                       DateTime start = DateTime.UtcNow;
                        try {
                                ping.Start ();
 
index d09d844a91859d44952034b0e7bdde46435a2c9c..9702cb7ef2c6f43ebcc5b02c171dc3c0b4682242 100644 (file)
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_0
-
 using System.Security.Cryptography.X509Certificates;
 
 namespace System.Net.Security 
 {
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
        public
 #endif
        delegate bool RemoteCertificateValidationCallback (
                object sender,
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                X509Certificate certificate,
                X509Chain chain,
 #else
@@ -49,6 +47,3 @@ namespace System.Net.Security
 #endif
                SslPolicyErrors sslPolicyErrors);
 }
-
-#endif
-
index 92eb11b778aca1875fd913b93860a9bc61fcc2d2..e3b6399a178f055bdfcc9907f931c8fda76c7dd3 100644 (file)
@@ -1,3 +1,29 @@
+2010-04-21  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * SocketAsyncEventArgs.cs: Add check for elevated permissions on
+       sockets (unrestricted). Add handling of new (SL4) 
+       SocketClientAccessPolicyProtocol and pass this option to the
+       CrossDomainPolicyManager
+
+2010-03-23 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * Socket.cs: error handling was totally broken in the synchronous
+       Connect() call.  Fixes bug #590488.
+
+2010-03-19  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * Socket.cs: Remove some NET_2_0 defines (using) and add a few
+       MOONLIGHT defines needed to reuse Socket in the client http stack
+       * Socket_2_1.cs: Remove some MOONLIGHT defines
+       * SocketAsyncEventArgs.cs: For Moonlight check policy if outside
+       System.dll (the client stack use sockets with it's own web 
+       xdomain policy)
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * Socket_2_1.cs, SocketAsyncEventArgs.cs: use MOONLIGHT symbol to
+       disambiguate MonoTouch and Moonlight code.
+
 2010-03-10  Sebastien Pouliot  <sebastien@ximian.com>
 
        * SocketAsyncEventArgs.cs: Remove the use of reflection to check
index 0d5d30baa3f3a2dd69aa3de4a6c8ee6824974ef1..35492a91aaa010b9c40ef8ed4c365206e70a0975 100644 (file)
@@ -36,6 +36,7 @@
 using System;
 using System.Net;
 using System.Collections;
+using System.Collections.Generic;
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
 using System.Threading;
@@ -43,11 +44,9 @@ using System.Reflection;
 using System.IO;
 using System.Net.Configuration;
 using System.Text;
-
-#if NET_2_0
-using System.Collections.Generic;
-using System.Net.NetworkInformation;
 using System.Timers;
+#if !MOONLIGHT
+using System.Net.NetworkInformation;
 #endif
 
 namespace System.Net.Sockets 
@@ -664,7 +663,6 @@ namespace System.Net.Sockets
                        IList currentList = checkRead;
                        int currentIdx = 0;
                        for (int i = 0; i < count; i++) {
-                               Socket cur_sock;
                                Socket sock = sockets [i];
                                if (sock == null) { // separator
                                        if (currentList != null) {
@@ -685,8 +683,8 @@ namespace System.Net.Sockets
                                }
 
                                // Remove non-signaled sockets before the current one
-                               int max = currentList.Count;
-                               while ((cur_sock = (Socket) currentList [currentIdx]) != sock) {
+                               //int max = currentList.Count;
+                               while (((Socket) currentList [currentIdx]) != sock) {
                                        currentList.RemoveAt (currentIdx);
                                }
                                currentIdx++;
@@ -1793,7 +1791,7 @@ namespace System.Net.Sockets
                        seed_endpoint = local_end;
                }
 
-#if NET_2_0
+#if !MOONLIGHT
                public bool ConnectAsync (SocketAsyncEventArgs e)
                {
                        // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
@@ -1836,11 +1834,10 @@ namespace System.Net.Sockets
                                throw new InvalidOperationException ();
 
                        /* FIXME: do non-blocking sockets Poll here? */
+                       int error = 0;
                        foreach (IPAddress address in addresses) {
-                               IPEndPoint iep = new IPEndPoint (address,
-                                                                port);
+                               IPEndPoint iep = new IPEndPoint (address, port);
                                SocketAddress serial = iep.Serialize ();
-                               int error = 0;
                                
                                Connect_internal (socket, serial, out error);
                                if (error == 0) {
@@ -1854,14 +1851,16 @@ namespace System.Net.Sockets
                                
                                if (!blocking) {
                                        Poll (-1, SelectMode.SelectWrite);
-                                       int success = (int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
-                                       if (success == 0) {
+                                       error = (int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
+                                       if (error == 0) {
                                                connected = true;
                                                seed_endpoint = iep;
                                                return;
                                        }
                                }
                        }
+                       if (error != 0)
+                               throw new SocketException (error);
                }
 
                public void Connect (string host, int port)
index 3f015e43e58a675292d7adf0371563c797ca8e63..22d763db5c53b14eeba9fdea4b979279d412f9b3 100644 (file)
@@ -32,7 +32,7 @@ using System.Collections.Generic;
 using System.Reflection;
 using System.Security;
 using System.Threading;
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT && !INSIDE_SYSTEM
 using System.Net.Policy;
 #endif
 
@@ -40,7 +40,7 @@ namespace System.Net.Sockets
 {
        public class SocketAsyncEventArgs : EventArgs, IDisposable
        {
-#if (NET_2_1 || NET_4_0) && !MONOTOUCH
+#if MOONLIGHT || NET_4_0
                public Exception ConnectByNameError { get; internal set; }
 #endif
 
@@ -78,6 +78,20 @@ namespace System.Net.Sockets
                public SocketFlags SocketFlags { get; set; }
                public object UserToken { get; set; }
 
+#if MOONLIGHT && !INSIDE_SYSTEM
+               private SocketClientAccessPolicyProtocol policy_protocol;
+
+               [MonoTODO ("Only TCP is currently supported by Moonlight")]
+               public SocketClientAccessPolicyProtocol SocketClientAccessPolicyProtocol {
+                       get { return policy_protocol; }
+                       set {
+                               if ((value != SocketClientAccessPolicyProtocol.Tcp) && (value != SocketClientAccessPolicyProtocol.Http))
+                                       throw new ArgumentException ("Invalid value");
+                               policy_protocol = value;
+                       }
+               }
+#endif
+
                Socket curSocket;
 #if NET_2_1
                public Socket ConnectSocket {
@@ -119,6 +133,10 @@ namespace System.Net.Sockets
                        SocketError = SocketError.Success;
                        SocketFlags = SocketFlags.None;
                        UserToken = null;
+
+#if MOONLIGHT && !INSIDE_SYSTEM
+                       policy_protocol = SocketClientAccessPolicyProtocol.Tcp;
+#endif
                }
 
                ~SocketAsyncEventArgs ()
@@ -206,7 +224,7 @@ namespace System.Net.Sockets
                        LastOperation = SocketAsyncOperation.Connect;
                        SocketError error = SocketError.AccessDenied;
                        try {
-#if (NET_2_1 || NET_4_0) && !MONOTOUCH
+#if MOONLIGHT || NET_4_0
                                // Connect to the first address that match the host name, like:
                                // http://blogs.msdn.com/ncl/archive/2009/07/20/new-ncl-features-in-net-4-0-beta-2.aspx
                                // while skipping entries that do not match the address family
@@ -245,11 +263,12 @@ namespace System.Net.Sockets
                {
                        curSocket.Connected = false;
                        SocketError error = SocketError.Success;
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT && !INSIDE_SYSTEM
                        // if we're not downloading a socket policy then check the policy
-                       if (!PolicyRestricted) {
+                       // and if we're not running with elevated permissions (SL4 OoB option)
+                       if (!PolicyRestricted && !SecurityManager.HasElevatedPermissions) {
                                error = SocketError.AccessDenied;
-                               if (!CrossDomainPolicyManager.CheckEndPoint (endpoint)) {
+                               if (!CrossDomainPolicyManager.CheckEndPoint (endpoint, policy_protocol)) {
                                        return error;
                                }
                                error = SocketError.Success;
index 540c9815a8f78d2337d624aacc51f1ff65ee25a6..af54044c3d50f2039abc56e331ebfc96c0462583 100644 (file)
@@ -227,7 +227,7 @@ namespace System.Net.Sockets {
                                                             bool block,
                                                             out int error);
 #endif
-#if !NET_2_1 || MONOTOUCH
+
                public bool Blocking {
                        get {
                                return(blocking);
@@ -246,7 +246,7 @@ namespace System.Net.Sockets {
                                blocking=value;
                        }
                }
-#endif
+
                public bool Connected {
                        get { return connected; }
                        internal set { connected = value; }
@@ -489,7 +489,7 @@ namespace System.Net.Sockets {
                                if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
                                        throw new SocketException ((int) SocketError.AddressNotAvailable);
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        if (protocol_type != ProtocolType.Tcp)
                                throw new SocketException ((int) SocketError.AccessDenied);
 #elif NET_2_0
@@ -565,7 +565,6 @@ namespace System.Net.Sockets {
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                extern static bool Poll_internal (IntPtr socket, SelectMode mode, int timeout, out int error);
 
-#if !NET_2_1 || MONOTOUCH
                /* This overload is needed as the async Connect method
                 * also needs to check the socket error status, but
                 * getsockopt(..., SO_ERROR) clears the error.
@@ -600,7 +599,7 @@ namespace System.Net.Sockets {
                        
                        return result;
                }
-#endif
+
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private extern static int Receive_internal(IntPtr sock,
                                                           byte[] buffer,
@@ -726,7 +725,7 @@ namespace System.Net.Sockets {
 #endif
                }
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                static void CheckConnect (SocketAsyncEventArgs e)
                {
                        // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
index 798448f1e6252703b9d7569bacf14e6c2c2f300a..876418bbc6f7f61fa17f2f0ed2949971330227c6 100644 (file)
 //
 
 using System.Collections;
+using System.Collections.Specialized;
 using System.Configuration;
-#if NET_2_0
 using System.Net.Configuration;
-using System.Collections.Specialized;
-#endif
 
 namespace System.Net
 {
-       public class AuthenticationManager
-       {
+#if MOONLIGHT
+       internal class AuthenticationManager {
+#else
+       public class AuthenticationManager {
+#endif
                static ArrayList modules;
                static object locker = new object ();
 
@@ -54,12 +55,11 @@ namespace System.Net
                                        return;
                                
                                modules = new ArrayList ();
-#if MONOTOUCH
+#if NET_2_1
                                modules.Add (new BasicClient ());
                                modules.Add (new DigestClient ());
                                modules.Add (new NtlmClient ());
-#else
-#if NET_2_0 && CONFIGURATION_DEP
+#elif NET_2_0 && CONFIGURATION_DEP
                                object cfg = ConfigurationManager.GetSection ("system.net/authenticationModules");
                                AuthenticationModulesSection s = cfg as AuthenticationModulesSection;
                                if (s != null) {
@@ -74,12 +74,10 @@ namespace System.Net
                                }
 #else
                                ConfigurationSettings.GetConfig ("system.net/authenticationModules");
-#endif
 #endif
                        }
                }
                
-#if NET_2_0
                static ICredentialPolicy credential_policy = null;
                
                public static ICredentialPolicy CredentialPolicy
@@ -104,7 +102,6 @@ namespace System.Net
                                throw GetMustImplement ();
                        }
                }
-#endif
 
                public static IEnumerator RegisteredModules {
                        get {
index 6c227732843b788a340f4c697639fa4a84a0452f..74586de66086115f29045b295ed50f41b9ebcf1f 100644 (file)
@@ -1,3 +1,99 @@
+2010-04-23 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * FtpDataStream.cs:
+       * FtpWebRequest.cs: use streams instead of sockets as soon as
+       possible. Correctly initialize the control connection when SSL
+       is used and protect the data connection by default.
+       Fixes bug #598908.
+
+2010-04-20 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * ChunkStream.cs: ignore chunk extensions when reading the chunk
+       size. Fixes bug #597556.
+
+2010-04-15 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * HttpWebRequest.cs: set content length to -1 on redirect. Reset
+       'FinishedReading' on redirects. Fixes bug #593596.
+
+2010-04-08 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * ServicePointManager.cs: obtain the SubjectAltName extension the
+       right way. Fixes bug #594110.
+
+2010-03-27 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * HttpWebRequest.cs: when PreAuthenticate is true, don't remove the
+       existing authorization related headers until we know we have a
+       replacement. Fixes bug #591633.
+
+2010-03-26 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * ServicePointManager.cs: errors parsing the certificate don't prevent
+       calling the callback now. Exceptions thrown parsing the certificate
+       are printed to stderr in case they are library errors.
+
+2010-03-21 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * WebClient.cs: fix handling of query string, whether it comes from
+       the address used or is part of the QueryString.
+
+2010-03-20  Miguel de Icaza  <miguel@novell.com>
+
+       * WebConnection.cs: Drop pre-2.0 and pre-1.1 support, and remove
+       warnings. 
+
+       * WebClient.cs: Drop the pre-2.0 support
+
+2010-03-19  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * AuthenticationManager.cs: Internal type for Moonlight.
+       Add BasicClient, DigestClient, NtlmClient for NET_2_1 since
+       this applies to both monotouch and moonlight (client stack).
+       Removed unneeded NET_2_0 defines
+       * CookieContainer.cs: For Moonlight it needs to be internal in 
+       System.dll and public in System.Net.dll. Removed unneeded NET_2_0
+       defines
+       * HttpContinueDelegate.cs: Internal type for Moonlight.
+       * HttpRequestCreator.cs: Remove a MOONLIGHT define
+       * HttpStatusCode.cs: For Moonlight it needs to be internal in 
+       System.dll and public in System.Net.dll
+       * HttpWebRequest.cs: Internal type for Moonlight. Change S.Config
+       to NET_2_1 defines (applies to both monotouch and moonlight).
+       Removed unneeded NET_2_0 and NET_1_1 defines
+       * HttpWebResponse.cs: Internal type for Moonlight. Removed 
+       unneeded NET_2_0 defines
+       * IAuthenticationModule.cs: Internal type for Moonlight.
+       * ICertificatePolicy.cs: Internal type for Moonlight.
+       * ICredentialPolicy.cs: Internal type for Moonlight. Removed 
+       unneeded NET_2_0 defines
+       * IWebRequestCreate.cs: For Moonlight it needs to be internal in 
+       System.dll and public in System.Net.dll
+       * ServicePoint.cs: Internal type for Moonlight. Change S.Config
+       to NET_2_1 defines (applies to both monotouch and moonlight)
+       * ServicePointManager.cs: Remove a MOONLIGHT define
+       * WebException.cs: For Moonlight it needs to be internal in 
+       System.dll and public in System.Net.dll. Removed unneeded NET_2_0
+       defines
+       * WebHeaderCollection.cs: Internal type for Moonlight. Removed 
+       unneeded NET_2_0 defines
+       * WebRequest.cs: Internal type for Moonlight. Change S.Config
+       to NET_2_1 defines (applies to both monotouch and moonlight)
+       * WebResponse.cs: Internal type for Moonlight. Removed unneeded
+       NET_2_0 defines
+
+2010-03-18 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * FtpWebResponse.cs:
+       * FtpWebRequest.cs: for non-data operations, make sure we send the
+       QUIT command upon completion when KeepAlive is false.
+       Fixes bug #589305.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * Dns.cs, HttpRequestCreator.cs, ServicePoint.cs: use MOONLIGHT
+       symbol to disambiguate MonoTouch and Moonlight code.
+
 2010-03-11 Gonzalo Paniagua Javier <gonzalo@novell.com>
 
        * ServicePointManager.cs: perform the entire chain validation here.
index 3e4c08f193010c04dfb05cfa6932b09e72b7f320..0edb422370b1d6c7e5d81bde4d48970bd4191cae 100644 (file)
@@ -230,8 +230,9 @@ namespace System.Net
                                        ThrowProtocolViolation ("Missing \\n");
 
                                try {
-                                       if (saved.Length > 0)
-                                               chunkSize = Int32.Parse (saved.ToString (), NumberStyles.HexNumber);
+                                       if (saved.Length > 0) {
+                                               chunkSize = Int32.Parse (RemoveChunkExtension (saved.ToString ()), NumberStyles.HexNumber);
+                                       }
                                } catch (Exception) {
                                        ThrowProtocolViolation ("Cannot parse chunk size.");
                                }
@@ -241,7 +242,7 @@ namespace System.Net
 
                        chunkRead = 0;
                        try {
-                               chunkSize = Int32.Parse (saved.ToString (), NumberStyles.HexNumber);
+                               chunkSize = Int32.Parse (RemoveChunkExtension (saved.ToString ()), NumberStyles.HexNumber);
                        } catch (Exception) {
                                ThrowProtocolViolation ("Cannot parse chunk size.");
                        }
@@ -254,6 +255,14 @@ namespace System.Net
                        return State.Body;
                }
 
+               static string RemoveChunkExtension (string input)
+               {
+                       int idx = input.IndexOf (';');
+                       if (idx == -1)
+                               return input;
+                       return input.Substring (0, idx);
+               }
+
                State ReadCRLF (byte [] buffer, ref int offset, int size)
                {
                        if (!sawCR) {
@@ -302,12 +311,14 @@ namespace System.Net
                                if (st > 0) {
                                        saved.Append (stString.Substring (0, saved.Length == 0? st-2: st));
                                        st = 0;
+                                       if (saved.Length > 4196)
+                                               ThrowProtocolViolation ("Error reading trailer (too long).");
                                }
                        }
 
                        if (st < 4) {
                                trailerState = st;
-                               if (offset <  size)
+                               if (offset < size)
                                        ThrowProtocolViolation ("Error reading trailer.");
 
                                return State.Trailer;
index 0068d5fca23e94c6bf82c97fae6c4774be2bf7db..84e507de60fd0e8c339cba5d5318eb2c10050c63 100644 (file)
@@ -41,8 +41,12 @@ using System.Text.RegularExpressions;
 namespace System.Net 
 {
        [Serializable]
-#if NET_2_1
+#if MOONLIGHT
+       #if INSIDE_SYSTEM
+       internal sealed class CookieContainer {
+       #else 
        public sealed class CookieContainer {
+       #endif
 #else
        public class CookieContainer {
 #endif
@@ -63,11 +67,7 @@ namespace System.Net
                public CookieContainer (int capacity)
                {
                        if (capacity <= 0)
-#if NET_2_0
                                throw new ArgumentException ("Must be greater than zero", "Capacity");
-#else
-                               throw new ArgumentException ("Capacity");
-#endif
 
                        this.capacity = capacity;
                }
@@ -76,21 +76,13 @@ namespace System.Net
                        : this (capacity)
                {
                        if (perDomainCapacity != Int32.MaxValue && (perDomainCapacity <= 0 || perDomainCapacity > capacity))
-#if NET_2_0
                                throw new ArgumentOutOfRangeException ("perDomainCapacity",
                                        string.Format ("PerDomainCapacity must be " +
                                        "greater than {0} and less than {1}.", 0,
                                        capacity));
-#else
-                               throw new ArgumentException ("PerDomainCapacity");
-#endif
 
                        if (maxCookieSize <= 0)
-#if NET_2_0
                                throw new ArgumentException ("Must be greater than zero", "MaxCookieSize");
-#else
-                               throw new ArgumentException ("MaxCookieSize");
-#endif
 
                        this.perDomainCapacity = perDomainCapacity;
                        this.maxCookieSize = maxCookieSize;
@@ -138,11 +130,7 @@ namespace System.Net
                                throw new ArgumentNullException ("cookie");
 
                        if (cookie.Domain.Length == 0)
-#if NET_2_0
                                throw new ArgumentException ("Cookie domain not set.", "cookie.Domain");
-#else
-                               throw new ArgumentException ("cookie.Domain");
-#endif
 
                        if (cookie.Value.Length > maxCookieSize)
                                throw new CookieException ("value is larger than MaxCookieSize.");
index 42e0d47a55ab3978e3d254b78ad37db1853a427e..15a17be550041196a7c988ed5845394c24d3ca08 100644 (file)
@@ -48,7 +48,7 @@ namespace System.Net {
                        System.Net.Sockets.Socket.CheckProtocolSupport();
                }
 
-#if !NET_2_1 || MONOTOUCH // global remove of async methods
+#if !MOONLIGHT // global remove of async methods
 
                private delegate IPHostEntry GetHostByNameCallback (string hostName);
                private delegate IPHostEntry ResolveCallback (string hostName);
@@ -177,7 +177,7 @@ namespace System.Net {
                }
 #endif
                
-#endif // !NET_2_1: global remove of async methods
+#endif // !MOONLIGHT: global remove of async methods
 
 #if !TARGET_JVM
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
index 45af275065506f8ac51b8da72dbc2f2a92f30bc9..e2685288ff3f68d0d9243cb10ff9fdaba519a606 100644 (file)
@@ -21,29 +21,19 @@ namespace System.Net
        class FtpDataStream : Stream, IDisposable
        {
                FtpWebRequest request;
-               NetworkStream networkStream;
-               Socket socket;
+               Stream networkStream;
                bool disposed;
                bool isRead;
                int totalRead;
 
-               internal FtpDataStream (FtpWebRequest request, Socket socket, bool isRead)
+               internal FtpDataStream (FtpWebRequest request, Stream stream, bool isRead)
                {
                        if (request == null)
                                throw new ArgumentNullException ("request");
-                       if (socket == null)
-                               throw new ArgumentNullException ("socket");
-                       if (!socket.Connected)
-                               throw new ArgumentException ("socket");
 
                        this.request = request;
-                       this.socket = socket;
-                       this.networkStream = new NetworkStream (socket, true);
+                       this.networkStream = stream;
                        this.isRead = isRead;
-
-                       if (request.EnableSsl) {
-                               FtpWebRequest.ChangeToSSLSocket (ref networkStream);
-                       }
                }
 
                public override bool CanRead {
@@ -79,7 +69,7 @@ namespace System.Net
                        }
                }
 
-               internal NetworkStream NetworkStream {
+               internal Stream NetworkStream {
                        get {
                                CheckDisposed ();
                                return networkStream;
@@ -108,8 +98,7 @@ namespace System.Net
 
                int ReadInternal (byte [] buffer, int offset, int size)
                {
-                       int nbytes;
-
+                       int nbytes = 0;
                        request.CheckIfAborted ();
 
                        try {
@@ -167,7 +156,6 @@ namespace System.Net
                        IAsyncResult ar = BeginRead (buffer, offset, size, null, null);
                        if (!ar.IsCompleted && !ar.AsyncWaitHandle.WaitOne (request.ReadWriteTimeout, false))
                                throw new WebException ("Read timed out.", WebExceptionStatus.Timeout);
-
                        return EndRead (ar);
                }
 
@@ -244,27 +232,15 @@ namespace System.Net
                                return;
 
                        disposed = true;
-                       if (socket != null) {
+                       if (networkStream != null)  {
                                try {
-                                       if (socket.Poll (0, SelectMode.SelectRead)) {
-                                               byte [] bytes = new byte [2048];
-                                               int nbytes;
-                                               do {
-                                                       nbytes = socket.Receive (bytes);
-                                               } while (nbytes > 0 && socket.Poll (0, SelectMode.SelectRead));
-                                       }
+                                       networkStream.Close ();
                                } catch {
-                                       // Ignore
                                }
 
-                               try {
-                                       networkStream.Close ();
-                               } catch {
-                               }
-                               networkStream = null;
-                               socket = null;
                                request.SetTransferCompleted ();
                                request = null;
+                               networkStream = null;
                        }
                }
 
index 32ae9a1b26325eeea03e13a82c7daabb2fc933c6..f766fc29a50d88d7e00fc3b7482bee4cabdbe176 100644 (file)
@@ -16,7 +16,8 @@ using System.Threading;
 using System.Net.Cache;
 using System.Security.Cryptography.X509Certificates;
 using System.Net;
-
+using System.Net.Security;
+using System.Security.Authentication;
 
 namespace System.Net
 {
@@ -25,8 +26,8 @@ namespace System.Net
                Uri requestUri;
                string file_name; // By now, used for upload
                ServicePoint servicePoint;
-               Socket dataSocket;
-               NetworkStream controlStream;
+               Stream dataStream;
+               Stream controlStream;
                StreamReader controlReader;
                NetworkCredential credentials;
                IPHostEntry hostEntry;
@@ -204,13 +205,14 @@ namespace System.Net
                        }
                }
 
+               [MonoTODO ("We don't support KeepAlive = true")]
                public bool KeepAlive {
                        get {
                                return keepAlive;
                        }
                        set {
                                CheckRequestStarted ();
-                               keepAlive = value;
+                               //keepAlive = value;
                        }
                }
 
@@ -366,7 +368,7 @@ namespace System.Net
 
                                if (!InFinalState ()) {
                                        State = RequestState.Aborted;
-                                       ftpResponse = new FtpWebResponse (requestUri, method, FtpStatusCode.FileActionAborted, "Aborted by request");
+                                       ftpResponse = new FtpWebResponse (this, requestUri, method, FtpStatusCode.FileActionAborted, "Aborted by request");
                                }
                        }
                }
@@ -500,7 +502,7 @@ namespace System.Net
                void ProcessRequest () {
 
                        if (State == RequestState.Scheduled) {
-                               ftpResponse = new FtpWebResponse (requestUri, method, keepAlive);
+                               ftpResponse = new FtpWebResponse (this, requestUri, method, keepAlive);
 
                                try {
                                        ProcessMethod ();
@@ -614,13 +616,18 @@ namespace System.Net
                }
 
                private void CloseControlConnection () {
-                       SendCommand (QuitCommand);
-                       controlStream.Close ();
+                       if (controlStream != null) {
+                               SendCommand (QuitCommand);
+                               controlStream.Close ();
+                               controlStream = null;
+                       }
                }
 
                private void CloseDataConnection () {
-                       if(dataSocket != null)
-                               dataSocket.Close ();
+                       if(dataStream != null) {
+                               dataStream.Close ();
+                               dataStream = null;
+                       }
                }
 
                private void CloseConnection () {
@@ -642,7 +649,7 @@ namespace System.Net
                        
                        status = SendCommand (method, file_name);
 
-                       ftpResponse.Stream = new EmptyStream ();
+                       ftpResponse.Stream = Stream.Null;
                        
                        string desc = status.StatusDescription;
 
@@ -711,7 +718,7 @@ namespace System.Net
                        OpenDataConnection ();
 
                        State = RequestState.TransferInProgress;
-                       requestStream = new FtpDataStream (this, dataSocket, false);
+                       requestStream = new FtpDataStream (this, dataStream, false);
                        asyncResult.Stream = requestStream;
                }
 
@@ -722,7 +729,7 @@ namespace System.Net
                        OpenDataConnection ();
 
                        State = RequestState.TransferInProgress;
-                       ftpResponse.Stream = new FtpDataStream (this, dataSocket, true);
+                       ftpResponse.Stream = new FtpDataStream (this, dataStream, true);
                }
 
                void CheckRequestStarted ()
@@ -855,7 +862,7 @@ namespace System.Net
 
                Exception CreateExceptionFromResponse (FtpStatus status)
                {
-                       FtpWebResponse ftpResponse = new FtpWebResponse (requestUri, method, status);
+                       FtpWebResponse ftpResponse = new FtpWebResponse (this, requestUri, method, status);
                        
                        WebException exc = new WebException ("Server returned an error: " + status.StatusDescription, 
                                null, WebExceptionStatus.ProtocolError, ftpResponse);
@@ -875,6 +882,12 @@ namespace System.Net
                                CloseConnection ();
                }
 
+               internal void OperationCompleted ()
+               {
+                       if(!keepAlive)
+                               CloseConnection ();
+               }
+
                void SetCompleteWithError (Exception exc)
                {
                        if (asyncResult != null) {
@@ -947,7 +960,9 @@ namespace System.Net
                                throw CreateExceptionFromResponse (status);
 
                        if (usePassive) {
-                               dataSocket = s;
+                               dataStream = new NetworkStream (s, false);
+                               if (EnableSsl)
+                                       ChangeToSSLSocket (ref dataStream);
                        }
                        else {
 
@@ -965,12 +980,9 @@ namespace System.Net
                                }
 
                                s.Close ();
-                               dataSocket = incoming;
-                       }
-
-                       if (EnableSsl) {
-                               InitiateSecureConnection (ref controlStream);
-                               controlReader = new StreamReader (controlStream, Encoding.ASCII);
+                               dataStream = new NetworkStream (incoming, false);
+                               if (EnableSsl)
+                                       ChangeToSSLSocket (ref dataStream);
                        }
 
                        ftpResponse.UpdateStatus (status);
@@ -1002,6 +1014,17 @@ namespace System.Net
                        if (EnableSsl) {
                                InitiateSecureConnection (ref controlStream);
                                controlReader = new StreamReader (controlStream, Encoding.ASCII);
+                               status = SendCommand ("PBSZ", "0");
+                               int st = (int) status.StatusCode;
+                               if (st < 200 || st >= 300)
+                                       throw CreateExceptionFromResponse (status);
+                               // TODO: what if "PROT P" is denied by the server? What does MS do?
+                               status = SendCommand ("PROT", "P");
+                               st = (int) status.StatusCode;
+                               if (st < 200 || st >= 300)
+                                       throw CreateExceptionFromResponse (status);
+
+                               status = new FtpStatus (FtpStatusCode.SendUserCommand, "");
                        }
                        
                        if (status.StatusCode != FtpStatusCode.SendUserCommand)
@@ -1097,20 +1120,40 @@ namespace System.Net
                        }
                }
 
-               private void InitiateSecureConnection (ref NetworkStream stream) {
+               private void InitiateSecureConnection (ref Stream stream) {
                        FtpStatus status = SendCommand (AuthCommand, "TLS");
-
-                       if (status.StatusCode != FtpStatusCode.ServerWantsSecureSession) {
+                       if (status.StatusCode != FtpStatusCode.ServerWantsSecureSession)
                                throw CreateExceptionFromResponse (status);
-                       }
 
                        ChangeToSSLSocket (ref stream);
                }
 
-               internal static bool ChangeToSSLSocket (ref NetworkStream stream) {
+#if SECURITY_DEP
+               RemoteCertificateValidationCallback callback = delegate (object sender,
+                                                                        X509Certificate certificate,
+                                                                        X509Chain chain,
+                                                                        SslPolicyErrors sslPolicyErrors) {
+                       // honor any exciting callback defined on ServicePointManager
+                       if (ServicePointManager.ServerCertificateValidationCallback != null)
+                               return ServicePointManager.ServerCertificateValidationCallback (sender, certificate, chain, sslPolicyErrors);
+                       // otherwise provide our own
+                       if (sslPolicyErrors != SslPolicyErrors.None)
+                               throw new InvalidOperationException ("SSL authentication error: " + sslPolicyErrors);
+                       return true;
+                       };
+#endif
+
+               internal bool ChangeToSSLSocket (ref Stream stream) {
 #if TARGET_JVM
                        stream.ChangeToSSLSocket ();
                        return true;
+#elif SECURITY_DEP
+                       SslStream sslStream = new SslStream (stream, true, callback, null);
+                       //sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
+                       //TODO: client certificates
+                       sslStream.AuthenticateAsClient (requestUri.Host, null, SslProtocols.Default, false);
+                       stream = sslStream;
+                       return true;
 #else
                        throw new NotImplementedException ();
 #endif
@@ -1133,13 +1176,6 @@ namespace System.Net
                        if (InFinalState ())
                                throw new InvalidOperationException ("Cannot change final state");
                }
-
-               class EmptyStream : MemoryStream
-               {
-                       internal EmptyStream ()
-                               : base (new byte [0], false) {
-                       }
-               }
        }
 }
 
index fe715922bc3de636afa99893d1f0e6706dda0dac..e42156efcb053c482a3fa7e92b87a62958a4cfe9 100644 (file)
@@ -29,24 +29,28 @@ namespace System.Net
                string method;
                //bool keepAlive;
                bool disposed;
+               FtpWebRequest request;
                internal long contentLength = -1;
                
-               internal FtpWebResponse (Uri uri, string method, bool keepAlive)
+               internal FtpWebResponse (FtpWebRequest request, Uri uri, string method, bool keepAlive)
                {
+                       this.request = request;
                        this.uri = uri;
                        this.method = method;
                        //this.keepAlive = keepAlive;
                }
 
-               internal FtpWebResponse (Uri uri, string method, FtpStatusCode statusCode, string statusDescription) {
+               internal FtpWebResponse (FtpWebRequest request, Uri uri, string method, FtpStatusCode statusCode, string statusDescription)
+               {
+                       this.request = request;
                        this.uri = uri;
                        this.method = method;
                        this.statusCode = statusCode;
                        this.statusDescription = statusDescription;
                }
 
-               internal FtpWebResponse (Uri uri, string method, FtpStatus status) :
-                       this (uri, method, status.StatusCode, status.StatusDescription)
+               internal FtpWebResponse (FtpWebRequest request, Uri uri, string method, FtpStatus status) :
+                       this (request, uri, method, status.StatusCode, status.StatusDescription)
                {
                }
                
@@ -128,8 +132,11 @@ namespace System.Net
                                return;
                        
                        disposed = true;
-                       if (stream != null)
+                       if (stream != null) {
                                stream.Close ();
+                               if (stream == Stream.Null)
+                                       request.OperationCompleted ();
+                       }
                        stream = null;
                }
 
index 482c7f916e259fcc27d05dcdfc3e5bf268c168ea..02283c62b6667eb32293eb7006db1f317da8445f 100644 (file)
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_0 && SECURITY_DEP
+#if SECURITY_DEP
 
 using System.IO;
 using System.Net.Sockets;
@@ -65,13 +65,9 @@ namespace System.Net {
                        if (secure == false) {
                                stream = new NetworkStream (sock, false);
                        } else {
-#if EMBEDDED_IN_1_0
-                               throw new NotImplementedException ();
-#else
                                SslServerStream ssl_stream = new SslServerStream (new NetworkStream (sock, false), cert, false, false);
                                ssl_stream.PrivateKeyCertSelectionDelegate += OnPVKSelection;
                                stream = ssl_stream;
-#endif
                        }
                        Init ();
                }
@@ -229,7 +225,7 @@ namespace System.Net {
                        try {
                                line = ReadLine (buffer, position, len - position, ref used);
                                position += used;
-                       } catch (Exception e) {
+                       } catch {
                                context.ErrorMessage = "Bad request";
                                context.ErrorStatus = 400;
                                return true;
@@ -267,7 +263,7 @@ namespace System.Net {
                                try {
                                        line = ReadLine (buffer, position, len - position, ref used);
                                        position += used;
-                               } catch (Exception e) {
+                               } catch {
                                        context.ErrorMessage = "Bad request";
                                        context.ErrorStatus = 400;
                                        return true;
index d71b746e630f192ff790f7af07eb8b488eff7e25..21bfee19119e9ff4d70174aee5b6f21907849924 100644 (file)
 \r
 namespace System.Net\r
 {\r
-       public delegate void HttpContinueDelegate (\r
+#if MOONLIGHT\r
+       internal\r
+#else\r
+       public\r
+#endif\r
+       delegate void HttpContinueDelegate (\r
                int StatusCode,\r
                WebHeaderCollection httpHeaders);\r
 }\r
index dc75c568ff498411f07b518b4b0add9c107dc540..cabc9db1f29a4aabec32fd4ad2b867d2dc8b5180 100644 (file)
@@ -38,11 +38,7 @@ namespace System.Net
 
                public WebRequest Create (Uri uri)
                {
-#if NET_2_1 && !MONOTOUCH
-                       throw new NotImplementedException ();
-#else
                        return new HttpWebRequest (uri);
-#endif
                }
        }
 }
index f6b72e03253d00caa337cf1bd4920209f2ff0089..123b7c37a2511e82864fb626ee619a8705ab4347 100644 (file)
 
 
 namespace System.Net {
+#if MOONLIGHT && INSIDE_SYSTEM
+       internal enum HttpStatusCode {
+#else
        public enum HttpStatusCode {
+#endif
                Continue = 100,
                SwitchingProtocols = 101,
                OK = 200,
index f35109c70005a248200efed867b2d08ade2aacf1..ede8a87a7e480cdd40dff25d032ddb1d86616bcd 100644 (file)
@@ -35,6 +35,7 @@ using System;
 using System.Collections;
 using System.Configuration;
 using System.IO;
+using System.Net.Cache;
 using System.Net.Sockets;
 using System.Runtime.Remoting.Messaging;
 using System.Runtime.Serialization;
@@ -42,15 +43,14 @@ using System.Security.Cryptography.X509Certificates;
 using System.Text;
 using System.Threading;
 
-#if NET_2_0
-using System.Net.Cache;
-#endif
-
 namespace System.Net 
 {
+#if MOONLIGHT
+       internal class HttpWebRequest : WebRequest, ISerializable {
+#else
        [Serializable]
-       public class HttpWebRequest : WebRequest, ISerializable
-       {
+       public class HttpWebRequest : WebRequest, ISerializable {
+#endif
                Uri requestUri;
                Uri actualUri;
                bool hostChanged;
@@ -99,10 +99,7 @@ namespace System.Net
                bool is_ntlm_auth;
                bool finished_reading;
                internal WebConnection WebConnection;
-#if NET_2_0
                DecompressionMethods auto_decomp;
-#endif
-#if NET_1_1
                int maxResponseHeadersLength;
                static int defaultMaxResponseHeadersLength;
                int readWriteTimeout = 300000; // ms
@@ -111,7 +108,7 @@ namespace System.Net
                static HttpWebRequest ()
                {
                        defaultMaxResponseHeadersLength = 64 * 1024;
-#if !MONOTOUCH
+#if !NET_2_1
                        NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
                        if (config != null) {
                                int x = config.MaxResponseHeadersLength;
@@ -122,7 +119,6 @@ namespace System.Net
                        }
 #endif
                }
-#endif
 
 #if NET_2_1
                public
@@ -136,9 +132,7 @@ namespace System.Net
                        this.proxy = GlobalProxySelection.Select;
                }               
                
-#if NET_2_0
                [Obsolete ("Serialization is obsoleted for this type", false)]
-#endif
                protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext) 
                {
                        SerializationInfo info = serializationInfo;
@@ -192,7 +186,6 @@ namespace System.Net
                        set { allowBuffering = value; }
                }
 
-#if NET_2_0
                static Exception GetMustImplement ()
                {
                        return new NotImplementedException ();
@@ -208,7 +201,6 @@ namespace System.Net
                                auto_decomp = value;
                        }
                }
-#endif
                
                internal bool InternalAllowBuffering {
                        get {
@@ -225,12 +217,10 @@ namespace System.Net
 
                                return certificates;
                        }
-#if NET_2_0
                        [MonoTODO]
                        set {
                                throw GetMustImplement ();
                        }
-#endif
                }
                
                public string Connection {
@@ -302,7 +292,6 @@ namespace System.Net
                        set { credentials = value; }
                }
 
-#if NET_2_0
                [MonoTODO]
                public static new RequestCachePolicy DefaultCachePolicy
                {
@@ -324,7 +313,6 @@ namespace System.Net
                                throw GetMustImplement ();
                        }
                }
-#endif
                
                public string Expect {
                        get { return webHeaders ["Expect"]; }
@@ -402,7 +390,6 @@ namespace System.Net
                        }                       
                }
 
-#if NET_1_1
                [MonoTODO ("Use this")]
                public int MaximumResponseHeadersLength {
                        get { return maxResponseHeadersLength; }
@@ -415,11 +402,7 @@ namespace System.Net
                        set { defaultMaxResponseHeadersLength = value; }
                }
 
-               public
-#else
-               internal
-#endif
-               int ReadWriteTimeout {
+               public  int ReadWriteTimeout {
                        get { return readWriteTimeout; }
                        set {
                                if (requestSent)
@@ -473,11 +456,6 @@ namespace System.Net
                        get { return proxy; }
                        set { 
                                CheckRequestStarted ();
-#if ONLY_1_1
-                               if (value == null)
-                                       throw new ArgumentNullException ("value");
-#endif
-
                                proxy = value;
                                servicePoint = null; // we may need a new one
                        }
@@ -544,27 +522,23 @@ namespace System.Net
                        }
                }
 
-#if NET_2_0
                public override bool UseDefaultCredentials
                {
                        get { return CredentialCache.DefaultCredentials == Credentials; }
                        set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
                }
-#endif
                
                public string UserAgent {
                        get { return webHeaders ["User-Agent"]; }
                        set { webHeaders.SetInternal ("User-Agent", value); }
                }
 
-#if NET_1_1
                bool unsafe_auth_blah;
                public bool UnsafeAuthenticatedConnectionSharing
                {
                        get { return unsafe_auth_blah; }
                        set { unsafe_auth_blah = value; }
                }
-#endif
 
                internal bool GotRequestStream {
                        get { return gotRequestStream; }
@@ -636,12 +610,6 @@ namespace System.Net
                                throw new InvalidOperationException ("rangeSpecifier");
                        webHeaders.RemoveAndAdd ("Range", value + from + "-" + to);     
                }
-#if !NET_2_0
-               public override int GetHashCode ()
-               {
-                       return base.GetHashCode ();
-               }
-#endif
                
                public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state) 
                {
@@ -743,16 +711,6 @@ namespace System.Net
                        if (method == null)
                                throw new ProtocolViolationException ("Method is null.");
 
-#if !NET_2_0
-                       bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
-                                               method == "TRACE" || method == "DELETE");
-                       if (send && contentLength < 0 && !sendChunked && !allowBuffering && KeepAlive)
-                               throw new ProtocolViolationException ("Buffering is disabled, ContentLength is negative and SendChunked is disabled.");
-
-                       if (!send && (contentLength > -1 || sendChunked))
-                               throw new ProtocolViolationException ("ContentLength can't be set for non-write operations.");
-#endif
-
                        string transferEncoding = TransferEncoding;
                        if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
                                throw new ProtocolViolationException ("SendChunked should be true.");
@@ -895,11 +853,8 @@ namespace System.Net
                        GetObjectData (serializationInfo, streamingContext);
                }
 
-#if NET_2_0
-               protected override
-#endif
-               void GetObjectData (SerializationInfo serializationInfo,
-                                   StreamingContext streamingContext)
+               protected override void GetObjectData (SerializationInfo serializationInfo,
+                       StreamingContext streamingContext)
                {
                        SerializationInfo info = serializationInfo;
 
@@ -954,7 +909,7 @@ namespace System.Net
                                        return false;
                                */
 
-                               contentLength = 0;
+                               contentLength = -1;
                                bodyBufferLength = 0;
                                bodyBuffer = null;
                                method = "GET";
@@ -1038,7 +993,6 @@ namespace System.Net
                                        webHeaders.SetInternal ("Cookie", cookieHeader);
                        }
 
-#if NET_2_0
                        string accept_encoding = null;
                        if ((auto_decomp & DecompressionMethods.GZip) != 0)
                                accept_encoding = "gzip";
@@ -1046,7 +1000,7 @@ namespace System.Net
                                accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
                        if (accept_encoding != null)
                                webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
-#endif
+
                        if (!usedPreAuth && preAuthenticate)
                                DoPreAuthenticate ();
 
@@ -1055,14 +1009,14 @@ namespace System.Net
 
                void DoPreAuthenticate ()
                {
-                       webHeaders.RemoveInternal ("Proxy-Authorization");
-                       webHeaders.RemoveInternal ("Authorization");
                        bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
                        ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
                        Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
                        if (auth == null)
                                return;
 
+                       webHeaders.RemoveInternal ("Proxy-Authorization");
+                       webHeaders.RemoveInternal ("Authorization");
                        string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
                        webHeaders [authHeader] = auth.Message;
                        usedPreAuth = true;
@@ -1226,9 +1180,7 @@ namespace System.Net
                                ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
                                if (creds != null) {
                                        cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
-#if NET_1_1
                                        cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
-#endif
                                }
                        }
                        r.Reset ();
@@ -1309,6 +1261,7 @@ namespace System.Net
                                                        }
                                                        webResponse.Close ();
                                                }
+                                               finished_reading = false;
                                                haveResponse = false;
                                                webResponse = null;
                                                r.Reset ();
index 8eb5b7f84ee646a3d8e8d45fe216c030a3fc2a07..83eef98ca697bca3ce61fcc93f523814d81b2a12 100644 (file)
@@ -36,18 +36,19 @@ using System;
 using System.Collections;
 using System.Globalization;
 using System.IO;
+using System.IO.Compression;
 using System.Net.Sockets;
 using System.Runtime.Serialization;
 using System.Text;
-#if NET_2_0
-using System.IO.Compression;
-#endif
 
 namespace System.Net 
 {
+#if MOONLIGHT
+       internal class HttpWebResponse : WebResponse, ISerializable, IDisposable {
+#else
        [Serializable]
-       public class HttpWebResponse : WebResponse, ISerializable, IDisposable
-       {
+       public class HttpWebResponse : WebResponse, ISerializable, IDisposable {
+#endif
                Uri uri;
                WebHeaderCollection webHeaders;
                CookieCollection cookieCollection;
@@ -77,13 +78,8 @@ namespace System.Net
 
                        try {
                                string cl = webHeaders ["Content-Length"];
-#if NET_2_0
                                if (String.IsNullOrEmpty (cl) || !Int64.TryParse (cl, out contentLength))
                                        contentLength = -1;
-#else
-                               if (cl != null && cl != String.Empty)
-                                       contentLength = (long) UInt64.Parse (cl);
-#endif
                        } catch (Exception) {
                                contentLength = -1;
                        }
@@ -92,18 +88,15 @@ namespace System.Net
                                this.cookie_container = container;      
                                FillCookies ();
                        }
-#if NET_2_0
+
                        string content_encoding = webHeaders ["Content-Encoding"];
                        if (content_encoding == "gzip" && (data.request.AutomaticDecompression & DecompressionMethods.GZip) != 0)
                                stream = new GZipStream (stream, CompressionMode.Decompress);
                        else if (content_encoding == "deflate" && (data.request.AutomaticDecompression & DecompressionMethods.Deflate) != 0)
                                stream = new DeflateStream (stream, CompressionMode.Decompress);
-#endif
                }
 
-#if NET_2_0
                [Obsolete ("Serialization is obsoleted for this type", false)]
-#endif
                protected HttpWebResponse (SerializationInfo serializationInfo, StreamingContext streamingContext)
                {
                        SerializationInfo info = serializationInfo;
@@ -181,14 +174,10 @@ namespace System.Net
                
                public override WebHeaderCollection Headers {           
                        get {
-#if ONLY_1_1
-                               CheckDisposed ();
-#endif
                                return webHeaders; 
                        }
                }
 
-#if NET_2_0
                static Exception GetMustImplement ()
                {
                        return new NotImplementedException ();
@@ -201,7 +190,6 @@ namespace System.Net
                                throw GetMustImplement ();
                        }
                }
-#endif
                
                public DateTime LastModified {
                        get {
@@ -257,12 +245,6 @@ namespace System.Net
                }
 
                // Methods
-#if !NET_2_0
-               public override int GetHashCode ()
-               {
-                       return base.GetHashCode ();
-               }
-#endif
                
                public string GetResponseHeader (string headerName)
                {
@@ -299,11 +281,8 @@ namespace System.Net
                        GetObjectData (serializationInfo, streamingContext);
                }
 
-#if NET_2_0
-               protected override
-#endif
-               void GetObjectData (SerializationInfo serializationInfo,
-                                   StreamingContext streamingContext)
+               protected override void GetObjectData (SerializationInfo serializationInfo,
+                       StreamingContext streamingContext)
                {
                        SerializationInfo info = serializationInfo;
 
@@ -330,9 +309,6 @@ namespace System.Net
                        GC.SuppressFinalize (this);  
                }
 
-#if !NET_2_0
-               protected virtual
-#endif
                void Dispose (bool disposing) 
                {
                        if (this.disposed)
@@ -342,9 +318,6 @@ namespace System.Net
                        if (disposing) {
                                // release managed resources
                                uri = null;
-#if !NET_2_0
-                               webHeaders = null;
-#endif
                                cookieCollection = null;
                                method = null;
                                version = null;
@@ -414,11 +387,9 @@ namespace System.Net
                                        if (cookie.Domain == "")
                                                cookie.Domain = val;
                                        break;
-#if NET_2_0
                                case "HTTPONLY":
                                        cookie.HttpOnly = true;
                                        break;
-#endif
                                case "MAX-AGE": // RFC Style Set-Cookie2
                                        if (cookie.Expires == DateTime.MinValue) {
                                                try {
@@ -485,14 +456,8 @@ namespace System.Net
                                        DateTime cookieExpiresUtc = DateTime.ParseExact (value, cookieExpiresFormats [i], CultureInfo.InvariantCulture);
 
                                        //convert UTC/GMT time to local time
-#if NET_2_0
                                        cookieExpiresUtc = DateTime.SpecifyKind (cookieExpiresUtc, DateTimeKind.Utc);
                                        return TimeZone.CurrentTimeZone.ToLocalTime (cookieExpiresUtc);
-#else
-                                       //DateTime.Kind is only available on .NET 2.0, so do some calculation
-                                       TimeSpan localOffset = TimeZone.CurrentTimeZone.GetUtcOffset (cookieExpiresUtc.Date);
-                                       return cookieExpiresUtc.Add (localOffset);
-#endif
                                } catch {}
                        }
 
index b48e5d5ff85f45fdbba261908e517452db3339ca..76076c03ef3b39df829e0e3d847be530f5a69bb4 100644 (file)
@@ -33,8 +33,11 @@ namespace System.Net {
        // <remarks>
        //   Authentication interface for Web client authentication modules.
        // </remarks>
-       public interface IAuthenticationModule
-       {
+#if MOONLIGHT
+       internal interface IAuthenticationModule {
+#else
+       public interface IAuthenticationModule {
+#endif
                Authorization Authenticate (string challenge, WebRequest request, ICredentials credentials);
                Authorization PreAuthenticate (WebRequest request, ICredentials credentials);
                string AuthenticationType { get; }
index 43cfa91b20d3d77ce6035466e9863f6db844602a..98d8081af14d1e98f6a598d8b4e6acd416fa3f9d 100644 (file)
@@ -30,9 +30,11 @@ using System.Security.Cryptography.X509Certificates;
 
 namespace System.Net {
 
-       // <remarks>
-       // </remarks>
+#if MOONLIGHT
+       internal interface ICertificatePolicy {
+#else
        public interface ICertificatePolicy {
+#endif
                bool CheckValidationResult (
                                ServicePoint srvPoint,
                                X509Certificate certificate,
index 1b1d0070f43d10387276bd80e29d3a0cacad0fa5..a8d37e7d0183a0bd4dccdae0ba1c56b52fd7c30c 100644 (file)
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_0
-
 namespace System.Net {
 
+#if MOONLIGHT
+       internal interface ICredentialPolicy {
+#else
        public interface ICredentialPolicy {
-
+#endif
                bool ShouldSendCredential (Uri challengeUri,
                        WebRequest request,
                        NetworkCredential credential,
@@ -40,4 +41,3 @@ namespace System.Net {
        }
 }
 
-#endif
index af6a24ddf5ba1c4fa600c489042b866f754310fa..d6cd6f493bc7d32b29ab42d25adbb6dff46fcf9e 100644 (file)
 
 namespace System.Net {
 
-       // <remarks>
-       // </remarks>
+#if MOONLIGHT && INSIDE_SYSTEM
+       internal interface IWebRequestCreate {
+#else
        public interface IWebRequestCreate {
+#endif
                WebRequest Create (Uri uri);            
        }
 }
index f50d774ca0e78e23fbd908c96036bbe7a8abe5d7..ea4fecdfedf05af0f805834ae2bc8ef873282de9 100644 (file)
@@ -43,6 +43,8 @@ namespace System.Net
                {
 #if SECURITY_DEP
                        authObject = new Mono.Http.NtlmClient ();
+#else
+                       authObject = null;
 #endif
                }
        
index 740b8402a6b57c8c84cbf5f163049f754fd23bba..c93f36d1bba52b5c28f89ab5f537dc4b602af70c 100644 (file)
@@ -270,7 +270,8 @@ namespace System.Net
                {
                        protocolVersion = version;
                }
-#if MONOTOUCH || (!TARGET_JVM && !NET_2_1)
+
+#if !TARGET_JVM
                WebConnectionGroup GetConnectionGroup (string name)
                {
                        if (name == null)
index 016eee02bb341ce88bad04a6297cf2b682d601d4..3f647fdb95e88510e9ab591fde0dfbca633d4542 100644 (file)
@@ -69,8 +69,11 @@ using MSX = Mono.Security.X509;
 
 namespace System.Net 
 {
-       public class ServicePointManager
-       {
+#if MOONLIGHT
+       internal class ServicePointManager {
+#else
+       public class ServicePointManager {
+#endif
                class SPKey {
                        Uri uri; // schema/host/port
                        bool use_connect;
@@ -130,14 +133,14 @@ namespace System.Net
                public const int DefaultNonPersistentConnectionLimit = 4;
                public const int DefaultPersistentConnectionLimit = 2;
 
-#if !MONOTOUCH
+#if !NET_2_1
                const string configKey = "system.net/connectionManagement";
                static ConnectionManagementData manager;
 #endif
                
                static ServicePointManager ()
                {
-#if !MONOTOUCH
+#if !NET_2_1
 #if NET_2_0 && CONFIGURATION_DEP
                        object cfg = ConfigurationManager.GetSection (configKey);
                        ConnectionManagementSection s = cfg as ConnectionManagementSection;
@@ -326,7 +329,7 @@ namespace System.Net
                                        throw new InvalidOperationException ("maximum number of service points reached");
 
                                string addr = address.ToString ();
-#if MONOTOUCH
+#if NET_2_1
                                int limit = defaultConnectionLimit;
 #else
                                int limit = (int) manager.GetMaxConnections (addr);
@@ -384,6 +387,7 @@ namespace System.Net
                internal class ChainValidationHelper {
                        object sender;
                        string host;
+                       static bool is_macosx = System.IO.File.Exists (MSX.OSX509Certificates.SecurityLibrary);
 
                        public ChainValidationHelper (object sender)
                        {
@@ -422,22 +426,29 @@ namespace System.Net
                                X509Certificate2 leaf = new X509Certificate2 (certs [0].RawData);
                                int status11 = 0; // Error code passed to the obsolete ICertificatePolicy callback
                                SslPolicyErrors errors = 0;
-                               if (!chain.Build (leaf))
-                                       errors |= GetErrorsFromChain (chain);
+                               try {
+                                       if (!chain.Build (leaf))
+                                               errors |= GetErrorsFromChain (chain);
+                               } catch (Exception e) {
+                                       Console.Error.WriteLine ("ERROR building certificate chain: {0}", e);
+                                       Console.Error.WriteLine ("Please, report this problem to the Mono team");
+                                       errors |= SslPolicyErrors.RemoteCertificateChainErrors;
+                               }
+
                                if (!CheckCertificateUsage (leaf)) {
                                        errors |= SslPolicyErrors.RemoteCertificateChainErrors;
                                        status11 = -2146762490; //CERT_E_PURPOSE 0x800B0106
                                }
-                               if (!CheckServerIdentity (leaf, Host)) {
+
+                               if (!CheckServerIdentity (certs [0], Host)) {
                                        errors |= SslPolicyErrors.RemoteCertificateNameMismatch;
                                        status11 = -2146762481; // CERT_E_CN_NO_MATCH 0x800B010F
                                }
 
                                bool result = false;
                                // No certificate root found means no mozroots or monotouch
-                               if (Environment.OSVersion.Platform == PlatformID.MacOSX) {
 #if !MONOTOUCH
-                               if (System.IO.File.Exists (MSX.OSX509Certificates.SecurityLibrary)) {
+                               if (is_macosx) {
 #endif
                                        // Attempt to use OSX certificates
                                        // Ideally we should return the SecTrustResult
@@ -460,7 +471,6 @@ namespace System.Net
 #if !MONOTOUCH
                                }
 #endif
-                               }
 
                                if (policy != null && (!(policy is DefaultCertificatePolicy) || cb == null)) {
                                        ServicePoint sp = null;
@@ -562,37 +572,43 @@ namespace System.Net
                        // DH certificates requires some changes - does anyone use one ?
                        static bool CheckCertificateUsage (X509Certificate2 cert) 
                        {
-                               // certificate extensions are required for this
-                               // we "must" accept older certificates without proofs
-                               if (cert.Version < 3)
-                                       return true;
-
-                               X509KeyUsageExtension kux = (X509KeyUsageExtension) cert.Extensions ["2.5.29.15"];
-                               X509EnhancedKeyUsageExtension eku = (X509EnhancedKeyUsageExtension) cert.Extensions ["2.5.29.37"];
-                               if (kux != null && eku != null) {
-                                       // RFC3280 states that when both KeyUsageExtension and 
-                                       // ExtendedKeyUsageExtension are present then BOTH should
-                                       // be valid
-                                       if ((kux.KeyUsages & s_flags) == 0)
-                                               return false;
-                                       return eku.EnhancedKeyUsages ["1.3.6.1.5.5.7.3.1"] != null ||
-                                               eku.EnhancedKeyUsages ["2.16.840.1.113730.4.1"] != null;
-                               } else if (kux != null) {
-                                       return ((kux.KeyUsages & s_flags) != 0);
-                               } else if (eku != null) {
-                                       // Server Authentication (1.3.6.1.5.5.7.3.1) or
-                                       // Netscape Server Gated Crypto (2.16.840.1.113730.4)
-                                       return eku.EnhancedKeyUsages ["1.3.6.1.5.5.7.3.1"] != null ||
-                                               eku.EnhancedKeyUsages ["2.16.840.1.113730.4.1"] != null;
-                               }
+                               try {
+                                       // certificate extensions are required for this
+                                       // we "must" accept older certificates without proofs
+                                       if (cert.Version < 3)
+                                               return true;
+
+                                       X509KeyUsageExtension kux = (X509KeyUsageExtension) cert.Extensions ["2.5.29.15"];
+                                       X509EnhancedKeyUsageExtension eku = (X509EnhancedKeyUsageExtension) cert.Extensions ["2.5.29.37"];
+                                       if (kux != null && eku != null) {
+                                               // RFC3280 states that when both KeyUsageExtension and 
+                                               // ExtendedKeyUsageExtension are present then BOTH should
+                                               // be valid
+                                               if ((kux.KeyUsages & s_flags) == 0)
+                                                       return false;
+                                               return eku.EnhancedKeyUsages ["1.3.6.1.5.5.7.3.1"] != null ||
+                                                       eku.EnhancedKeyUsages ["2.16.840.1.113730.4.1"] != null;
+                                       } else if (kux != null) {
+                                               return ((kux.KeyUsages & s_flags) != 0);
+                                       } else if (eku != null) {
+                                               // Server Authentication (1.3.6.1.5.5.7.3.1) or
+                                               // Netscape Server Gated Crypto (2.16.840.1.113730.4)
+                                               return eku.EnhancedKeyUsages ["1.3.6.1.5.5.7.3.1"] != null ||
+                                                       eku.EnhancedKeyUsages ["2.16.840.1.113730.4.1"] != null;
+                                       }
 
-                               // last chance - try with older (deprecated) Netscape extensions
-                               X509Extension ext = cert.Extensions ["2.16.840.1.113730.1.1"];
-                               if (ext != null) {
-                                       string text = ext.NetscapeCertType (false);
-                                       return text.IndexOf ("SSL Server Authentication") != -1;
+                                       // last chance - try with older (deprecated) Netscape extensions
+                                       X509Extension ext = cert.Extensions ["2.16.840.1.113730.1.1"];
+                                       if (ext != null) {
+                                               string text = ext.NetscapeCertType (false);
+                                               return text.IndexOf ("SSL Server Authentication") != -1;
+                                       }
+                                       return true;
+                               } catch (Exception e) {
+                                       Console.Error.WriteLine ("ERROR processing certificate: {0}", e);
+                                       Console.Error.WriteLine ("Please, report this problem to the Mono team");
+                                       return false;
                                }
-                               return true;
                        }
 
                        // RFC2818 - HTTP Over TLS, Section 3.1
@@ -605,28 +621,33 @@ namespace System.Net
                        // 2.1.         exact match is required
                        // 3.   Use of the most specific Common Name (CN=) in the Subject
                        // 3.1          Existing practice but DEPRECATED
-                       static bool CheckServerIdentity (X509Certificate2 cert, string targetHost) 
+                       static bool CheckServerIdentity (Mono.Security.X509.X509Certificate cert, string targetHost) 
                        {
-                               X509Extension ext = cert.Extensions ["2.5.29.17"];
-                               // 1. subjectAltName
-                               if (ext != null) {
-                                       ASN1 asn = new ASN1 (ext.RawData);
-                                       SubjectAltNameExtension subjectAltName = new SubjectAltNameExtension (asn);
-                                       // 1.1 - multiple dNSName
-                                       foreach (string dns in subjectAltName.DNSNames) {
-                                               // 1.2 TODO - wildcard support
-                                               if (Match (targetHost, dns))
-                                                       return true;
-                                       }
-                                       // 2. ipAddress
-                                       foreach (string ip in subjectAltName.IPAddresses) {
-                                               // 2.1. Exact match required
-                                               if (ip == targetHost)
-                                                       return true;
+                               try {
+                                       Mono.Security.X509.X509Extension ext = cert.Extensions ["2.5.29.17"];
+                                       // 1. subjectAltName
+                                       if (ext != null) {
+                                               SubjectAltNameExtension subjectAltName = new SubjectAltNameExtension (ext);
+                                               // 1.1 - multiple dNSName
+                                               foreach (string dns in subjectAltName.DNSNames) {
+                                                       // 1.2 TODO - wildcard support
+                                                       if (Match (targetHost, dns))
+                                                               return true;
+                                               }
+                                               // 2. ipAddress
+                                               foreach (string ip in subjectAltName.IPAddresses) {
+                                                       // 2.1. Exact match required
+                                                       if (ip == targetHost)
+                                                               return true;
+                                               }
                                        }
+                                       // 3. Common Name (CN=)
+                                       return CheckDomainName (cert.SubjectName, targetHost);
+                               } catch (Exception e) {
+                                       Console.Error.WriteLine ("ERROR processing certificate: {0}", e);
+                                       Console.Error.WriteLine ("Please, report this problem to the Mono team");
+                                       return false;
                                }
-                               // 3. Common Name (CN=)
-                               return CheckDomainName (cert.SubjectName.Format (false), targetHost);
                        }
 
                        static bool CheckDomainName (string subjectName, string targetHost)
index 8ada916e77a263bb35464a71e50effc0dd154068..598c586b08287a7d5e0768b923178d7d96e42b91 100644 (file)
@@ -66,18 +66,12 @@ using System.Runtime.InteropServices;
 using System.Runtime.Serialization;
 using System.Text;
 using System.Threading;
-#if NET_2_0
 using System.Net.Cache;
-#endif
 
 namespace System.Net 
 {
        [ComVisible(true)]
-       public
-#if !NET_2_0
-       sealed
-#endif
-       class WebClient : Component
+       public class WebClient : Component
        {
                static readonly string urlEncodedCType = "application/x-www-form-urlencoded";
                static byte [] hexBytes;
@@ -88,12 +82,10 @@ namespace System.Net
                string baseString;
                NameValueCollection queryString;
                bool is_busy;
-#if NET_2_0
                bool async;
                Thread async_thread;
                Encoding encoding = Encoding.Default;
                IWebProxy proxy;
-#endif
 
                // Constructors
                static WebClient ()
@@ -133,7 +125,6 @@ namespace System.Net
                        }
                }
 
-#if NET_2_0
                static Exception GetMustImplement ()
                {
                        return new NotImplementedException ();
@@ -160,7 +151,6 @@ namespace System.Net
                                throw GetMustImplement ();
                        }
                }
-#endif
                
                public ICredentials Credentials {
                        get { return credentials; }
@@ -191,7 +181,6 @@ namespace System.Net
                        get { return responseHeaders; }
                }
 
-#if NET_2_0
                public Encoding Encoding {
                        get { return encoding; }
                        set {
@@ -205,18 +194,10 @@ namespace System.Net
                        get { return proxy; }
                        set { proxy = value; }
                }
-#endif
 
-#if NET_2_0
                public bool IsBusy {
                        get { return is_busy; } 
                }
-#else
-               bool IsBusy {
-                       get { return is_busy; }
-               }
-#endif
-
                // Methods
 
                void CheckBusy ()
@@ -237,29 +218,20 @@ namespace System.Net
 
                public byte [] DownloadData (string address)
                {
-#if NET_2_0
                        if (address == null)
                                throw new ArgumentNullException ("address");
-#endif
 
                        return DownloadData (CreateUri (address));
                }
 
-#if NET_2_0
-               public
-#endif
-               byte [] DownloadData (Uri address)
+               public byte [] DownloadData (Uri address)
                {
-#if NET_2_0
                        if (address == null)
                                throw new ArgumentNullException ("address");
-#endif
 
                        try {
                                SetBusy ();
-#if NET_2_0                            
                                async = false;
-#endif                         
                                return DownloadDataCore (address, null);
                        } finally {
                                is_busy = false;
@@ -279,7 +251,7 @@ namespace System.Net
                                if (request != null)
                                        request.Abort ();
                                throw;
-                       } catch (WebException wexc) {
+                       } catch (WebException) {
                                throw;
                        } catch (Exception ex) {
                                throw new WebException ("An error occurred " +
@@ -291,33 +263,24 @@ namespace System.Net
 
                public void DownloadFile (string address, string fileName)
                {
-#if NET_2_0
                        if (address == null)
                                throw new ArgumentNullException ("address");
-#endif
 
                        DownloadFile (CreateUri (address), fileName);
                }
 
-#if NET_2_0
-               public
-#endif
-               void DownloadFile (Uri address, string fileName)
+               public void DownloadFile (Uri address, string fileName)
                {
-#if NET_2_0
                        if (address == null)
                                throw new ArgumentNullException ("address");
                        if (fileName == null)
                                throw new ArgumentNullException ("fileName");
-#endif
 
                        try {
                                SetBusy ();
-#if NET_2_0                            
                                async = false;
-#endif                         
                                DownloadFileCore (address, fileName, null);
-                       } catch (WebException wexc) {
+                       } catch (WebException) {
                                throw;
                        } catch (Exception ex) {
                                throw new WebException ("An error occurred " +
@@ -342,18 +305,14 @@ namespace System.Net
                                        byte [] buffer = new byte [length];
                                        
                                        int nread = 0;
-#if NET_2_0
                                        long notify_total = 0;
-#endif                                 
                                        while ((nread = st.Read (buffer, 0, length)) != 0){
-#if NET_2_0
                                                if (async){
                                                        notify_total += nread;
                                                        OnDownloadProgressChanged (
                                                                new DownloadProgressChangedEventArgs (notify_total, response.ContentLength, userToken));
                                                                                                      
                                                }
-#endif
                                                f.Write (buffer, 0, nread);
                                        }
                                } catch (ThreadInterruptedException){
@@ -368,34 +327,24 @@ namespace System.Net
 
                public Stream OpenRead (string address)
                {
-#if NET_2_0
                        if (address == null)
                                throw new ArgumentNullException ("address");
-#endif
-
                        return OpenRead (CreateUri (address));
                }
 
-#if NET_2_0
-               public
-#endif
-               Stream OpenRead (Uri address)
+               public Stream OpenRead (Uri address)
                {
-#if NET_2_0
                        if (address == null)
                                throw new ArgumentNullException ("address");
-#endif
 
                        WebRequest request = null;
                        try {
                                SetBusy ();
-#if NET_2_0                            
                                async = false;
-#endif                         
                                request = SetupRequest (address);
                                WebResponse response = GetWebResponse (request);
                                return response.GetResponseStream ();
-                       } catch (WebException wexc) {
+                       } catch (WebException) {
                                throw;
                        } catch (Exception ex) {
                                throw new WebException ("An error occurred " +
@@ -409,50 +358,36 @@ namespace System.Net
 
                public Stream OpenWrite (string address)
                {
-#if NET_2_0
                        if (address == null)
                                throw new ArgumentNullException ("address");
-#endif
 
                        return OpenWrite (CreateUri (address));
                }
                
                public Stream OpenWrite (string address, string method)
                {
-#if NET_2_0
                        if (address == null)
                                throw new ArgumentNullException ("address");
-#endif
 
                        return OpenWrite (CreateUri (address), method);
                }
 
-#if NET_2_0
-               public
-#endif
-               Stream OpenWrite (Uri address)
+               public Stream OpenWrite (Uri address)
                {
                        return OpenWrite (address, (string) null);
                }
 
-#if NET_2_0
-               public
-#endif
-               Stream OpenWrite (Uri address, string method)
+               public Stream OpenWrite (Uri address, string method)
                {
-#if NET_2_0
                        if (address == null)
                                throw new ArgumentNullException ("address");
-#endif
 
                        try {
                                SetBusy ();
-#if NET_2_0                            
                                async = false;
-#endif                         
                                WebRequest request = SetupRequest (address, method, true);
                                return request.GetRequestStream ();
-                       } catch (WebException wexc) {
+                       } catch (WebException) {
                                throw;
                        } catch (Exception ex) {
                                throw new WebException ("An error occurred " +
@@ -467,10 +402,9 @@ namespace System.Net
                        if (method != null)
                                return method;
 
-#if NET_2_0
                        if (address.Scheme == Uri.UriSchemeFtp)
                                return (is_upload) ? "STOR" : "RETR";
-#endif
+
                        return (is_upload) ? "POST" : "GET";
                }
 
@@ -478,49 +412,35 @@ namespace System.Net
 
                public byte [] UploadData (string address, byte [] data)
                {
-#if NET_2_0
                        if (address == null)
                                throw new ArgumentNullException ("address");
-#endif
 
                        return UploadData (CreateUri (address), data);
                }
                
                public byte [] UploadData (string address, string method, byte [] data)
                {
-#if NET_2_0
                        if (address == null)
                                throw new ArgumentNullException ("address");
-#endif
 
                        return UploadData (CreateUri (address), method, data);
                }
 
-#if NET_2_0
-               public
-#endif
-               byte [] UploadData (Uri address, byte [] data)
+               public byte [] UploadData (Uri address, byte [] data)
                {
                        return UploadData (address, (string) null, data);
                }
 
-#if NET_2_0
-               public
-#endif
-               byte [] UploadData (Uri address, string method, byte [] data)
+               public byte [] UploadData (Uri address, string method, byte [] data)
                {
-#if NET_2_0
                        if (address == null)
                                throw new ArgumentNullException ("address");
                        if (data == null)
                                throw new ArgumentNullException ("data");
-#endif
 
                        try {
                                SetBusy ();
-#if NET_2_0                            
                                async = false;
-#endif                         
                                return UploadDataCore (address, method, data, null);
                        } catch (WebException) {
                                throw;
@@ -534,13 +454,6 @@ namespace System.Net
 
                byte [] UploadDataCore (Uri address, string method, byte [] data, object userToken)
                {
-#if ONLY_1_1
-                       if (address == null)
-                               throw new ArgumentNullException ("address");
-                       if (data == null)
-                               throw new ArgumentNullException ("data");
-#endif
-
                        WebRequest request = SetupRequest (address, method, true);
                        try {
                                int contentLength = data.Length;
@@ -563,18 +476,13 @@ namespace System.Net
 
                public byte [] UploadFile (string address, string fileName)
                {
-#if NET_2_0
                        if (address == null)
                                throw new ArgumentNullException ("address");
-#endif
 
                        return UploadFile (CreateUri (address), fileName);
                }
 
-#if NET_2_0
-               public
-#endif
-               byte [] UploadFile (Uri address, string fileName)
+               public byte [] UploadFile (Uri address, string fileName)
                {
                        return UploadFile (address, (string) null, fileName);
                }
@@ -584,25 +492,18 @@ namespace System.Net
                        return UploadFile (CreateUri (address), method, fileName);
                }
 
-#if NET_2_0
-               public
-#endif
-               byte [] UploadFile (Uri address, string method, string fileName)
+               public byte [] UploadFile (Uri address, string method, string fileName)
                {
-#if NET_2_0
                        if (address == null)
                                throw new ArgumentNullException ("address");
                        if (fileName == null)
                                throw new ArgumentNullException ("fileName");
-#endif
 
                        try {
                                SetBusy ();
-#if NET_2_0                            
                                async = false;
-#endif                         
                                return UploadFileCore (address, method, fileName, null);
-                       } catch (WebException wexc) {
+                       } catch (WebException) {
                                throw;
                        } catch (Exception ex) {
                                throw new WebException ("An error occurred " +
@@ -614,11 +515,6 @@ namespace System.Net
 
                byte [] UploadFileCore (Uri address, string method, string fileName, object userToken)
                {
-#if ONLY_1_1
-                       if (address == null)
-                               throw new ArgumentNullException ("address");
-#endif
-
                        string fileCType = Headers ["Content-Type"];
                        if (fileCType != null) {
                                string lower = fileCType.ToLower ();
@@ -681,51 +577,36 @@ namespace System.Net
                
                public byte[] UploadValues (string address, NameValueCollection data)
                {
-#if NET_2_0
                        if (address == null)
                                throw new ArgumentNullException ("address");
-#endif
 
                        return UploadValues (CreateUri (address), data);
                }
                
                public byte[] UploadValues (string address, string method, NameValueCollection data)
                {
-#if NET_2_0
                        if (address == null)
                                throw new ArgumentNullException ("address");
-#endif
-
                        return UploadValues (CreateUri (address), method, data);
                }
 
-#if NET_2_0
-               public
-#endif
-               byte[] UploadValues (Uri address, NameValueCollection data)
+               public byte[] UploadValues (Uri address, NameValueCollection data)
                {
                        return UploadValues (address, (string) null, data);
                }
 
-#if NET_2_0
-               public
-#endif
-               byte[] UploadValues (Uri address, string method, NameValueCollection data)
+               public byte[] UploadValues (Uri address, string method, NameValueCollection data)
                {
-#if NET_2_0
                        if (address == null)
                                throw new ArgumentNullException ("address");
                        if (data == null)
                                throw new ArgumentNullException ("data");
-#endif
 
                        try {
                                SetBusy ();
-#if NET_2_0                            
                                async = false;
-#endif                         
                                return UploadValuesCore (address, method, data, null);
-                       } catch (WebException wexc) {
+                       } catch (WebException) {
                                throw;
                        } catch (Exception ex) {
                                throw new WebException ("An error occurred " +
@@ -737,11 +618,6 @@ namespace System.Net
 
                byte[] UploadValuesCore (Uri uri, string method, NameValueCollection data, object userToken)
                {
-#if ONLY_1_1
-                       if (data == null)
-                               throw new ArgumentNullException ("data");
-#endif
-
                        string cType = Headers ["Content-Type"];
                        if (cType != null && String.Compare (cType, urlEncodedCType, true) != 0)
                                throw new WebException ("Content-Type header cannot be changed from its default " +
@@ -780,7 +656,6 @@ namespace System.Net
                        }
                }
 
-#if NET_2_0
                public string DownloadString (string address)
                {
                        if (address == null)
@@ -852,42 +727,40 @@ namespace System.Net
                public event UploadProgressChangedEventHandler UploadProgressChanged;
                public event UploadStringCompletedEventHandler UploadStringCompleted;
                public event UploadValuesCompletedEventHandler UploadValuesCompleted;
-#endif
 
                Uri CreateUri (string address)
                {
-#if ONLY_1_1
+                       Uri uri;
                        try {
-                               return MakeUri (address);
-                       } catch (Exception ex) {
-                               throw new WebException ("An error occurred " +
-                                       "performing a WebClient request.", ex);
+                               if (baseAddress == null)
+                                       uri = new Uri (address);
+                               else
+                                       uri = new Uri (baseAddress, address);
+                               return CreateUri (uri);
+                       } catch {
                        }
-#else
-                       return MakeUri (address);
-#endif
+                       return new Uri (Path.GetFullPath (address));
                }
 
-#if NET_2_0
                Uri CreateUri (Uri address)
                {
-                       string query = address.Query;
+                       Uri result = address;
+                       if (baseAddress != null && !result.IsAbsoluteUri) {
+                               try {
+                                       result = new Uri (baseAddress, result.OriginalString);
+                               } catch {
+                                       return result; // Not much we can do here.
+                               }
+                       }
+
+                       string query = result.Query;
                        if (String.IsNullOrEmpty (query))
                                query = GetQueryString (true);
-
-                       if (baseAddress == null && query == null)
-                               return address;
-
-                       if (baseAddress == null)
-                               return new Uri (address.ToString () + query, (query != null));
-
-                       if (query == null)
-                               return new Uri (baseAddress, address.ToString ());
-
-                       return new Uri (baseAddress, address.ToString () + query, (query != null));
-
+                       UriBuilder builder = new UriBuilder (address);
+                       if (!String.IsNullOrEmpty (query))
+                               builder.Query = query.Substring (1);
+                       return builder.Uri;
                }
-#endif
 
                string GetQueryString (bool add_qmark)
                {
@@ -910,39 +783,11 @@ namespace System.Net
                        return sb.ToString ();
                }
 
-               Uri MakeUri (string path)
-               {
-                       string query = GetQueryString (true);
-                       if (baseAddress == null && query == null) {
-                               try {
-                                       return new Uri (path);
-#if NET_2_0
-                               } catch (ArgumentNullException) {
-                                       path = Path.GetFullPath (path);
-                                       return new Uri ("file://" + path);
-#endif
-                               } catch (UriFormatException) {
-                                       path = Path.GetFullPath (path);
-                                       return new Uri ("file://" + path);
-                               }
-                       }
-
-                       if (baseAddress == null)
-                               return new Uri (path + query, (query != null));
-
-                       if (query == null)
-                               return new Uri (baseAddress, path);
-
-                       return new Uri (baseAddress, path + query, (query != null));
-               }
-               
                WebRequest SetupRequest (Uri uri)
                {
                        WebRequest request = GetWebRequest (uri);
-#if NET_2_0
                        if (Proxy != null)
                                request.Proxy = Proxy;
-#endif
                        request.Credentials = credentials;
 
                        // Special headers. These are properties of HttpWebRequest.
@@ -1013,12 +858,10 @@ namespace System.Net
                                        offset += nread;
                                        size -= nread;
                                }
-#if NET_2_0
                                if (async){
 //                                     total += nread;
                                        OnDownloadProgressChanged (new DownloadProgressChangedEventArgs (nread, length, userToken));
                                }
-#endif
                        }
 
                        if (nolength)
@@ -1081,7 +924,6 @@ namespace System.Net
                        }
                }
 
-#if NET_2_0
                public void CancelAsync ()
                {
                        lock (this){
@@ -1546,20 +1388,13 @@ namespace System.Net
                        responseHeaders = response.Headers;
                        return response;
                }
-#endif
 
-#if NET_2_0
-               protected virtual
-#endif
-               WebRequest GetWebRequest (Uri address)
+               protected virtual WebRequest GetWebRequest (Uri address)
                {
                        return WebRequest.Create (address);
                }
 
-#if NET_2_0
-               protected virtual
-#endif
-               WebResponse GetWebResponse (WebRequest request)
+               protected virtual WebResponse GetWebResponse (WebRequest request)
                {
                        WebResponse response = request.GetResponse ();
                        responseHeaders = response.Headers;
index 5bb638c6a18876906ef85d743501206015c030ac..d197f837de4194afe12b5230902308c9fd7426e7 100644 (file)
@@ -35,7 +35,7 @@ using System.Reflection;
 using System.Security.Cryptography.X509Certificates;
 using System.Text;
 using System.Threading;
-#if (NET_2_0 || MONOTOUCH) && SECURITY_DEP
+#if SECURITY_DEP
 using Mono.Security.Protocol.Tls;
 #endif
 
@@ -73,9 +73,7 @@ namespace System.Net
                HttpWebRequest priority_request;
                NetworkCredential ntlm_credentials;
                bool ntlm_authenticated;
-#if NET_1_1
                bool unsafe_sharing;
-#endif
 
                bool ssl;
                bool certsAvailable;
@@ -164,21 +162,17 @@ namespace System.Net
 #endif
                                }
 
-                               WebConnectionData data = Data;
+                               //WebConnectionData data = Data;
                                foreach (IPAddress address in hostEntry.AddressList) {
                                        socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                                        IPEndPoint remote = new IPEndPoint (address, sPoint.Address.Port);
-#if NET_1_1
                                        socket.SetSocketOption (SocketOptionLevel.Tcp, SocketOptionName.NoDelay, sPoint.UseNagleAlgorithm ? 0 : 1);
-#endif
-#if NET_2_0
                                        socket.NoDelay = !sPoint.UseNagleAlgorithm;
                                        if (!sPoint.CallEndPointDelegate (socket, remote)) {
                                                socket.Close ();
                                                socket = null;
                                                status = WebExceptionStatus.ConnectFailure;
                                        } else {
-#endif
                                                try {
                                                        if (request.Aborted)
                                                                return;
@@ -192,7 +186,7 @@ namespace System.Net
                                                        if (s != null)
                                                                s.Close ();
                                                        return;
-                                               } catch (ObjectDisposedException exc) {
+                                               } catch (ObjectDisposedException) {
                                                        // socket closed from another thread
                                                        return;
                                                } catch (Exception exc) {
@@ -204,9 +198,7 @@ namespace System.Net
                                                                status = WebExceptionStatus.ConnectFailure;
                                                        connect_exception = exc;
                                                }
-#if NET_2_0
                                        }
-#endif
                                }
                        }
                }
@@ -355,7 +347,7 @@ namespace System.Net
                                                                                request.ClientCertificates,
                                                                                request, buffer};
                                                nstream = (Stream) Activator.CreateInstance (sslStream, args);
-#if (NET_2_0 || MONOTOUCH) && SECURITY_DEP
+#if SECURITY_DEP
                                                SslClientStream scs = (SslClientStream) nstream;
                                                var helper = new ServicePointManager.ChainValidationHelper (request);
                                                scs.ServerCertValidation2 += new CertificateValidationCallback2 (helper.ValidateChain);
@@ -1123,12 +1115,10 @@ namespace System.Net
                        set { ntlm_credentials = value; }
                }
 
-#if NET_1_1
                internal bool UnsafeAuthenticatedConnectionSharing {
                        get { return unsafe_sharing; }
                        set { unsafe_sharing = value; }
                }
-#endif
                // -
        }
 }
index f98144db88f122fd0bd1c491ba58be3ee48d4c74..8f0c5aa19499aadb47b382771922ee0012e76940 100644 (file)
@@ -59,7 +59,7 @@ namespace System.Net
                                WeakReference cncRef = null;
 
                                int end = connections.Count;
-                               ArrayList removed = null;
+                               // ArrayList removed = null;
                                for (int i = 0; i < end; i++) {
                                        cncRef = (WeakReference) connections [i];
                                        WebConnection cnc = cncRef.Target as WebConnection;
index be4446b7a0cb7fd971c461aa2559a81e2aca25d5..1e401660db60d6919439cd45b3ab6450e1c4dcde 100644 (file)
@@ -30,9 +30,12 @@ using System.Runtime.Serialization;
 \r
 namespace System.Net \r
 {\r
+#if MOONLIGHT && INSIDE_SYSTEM\r
+       internal class WebException : InvalidOperationException, ISerializable {\r
+#else\r
        [Serializable]\r
-       public class WebException : InvalidOperationException, ISerializable\r
-       {\r
+       public class WebException : InvalidOperationException, ISerializable {\r
+#endif\r
                private WebResponse response;\r
                private WebExceptionStatus status = WebExceptionStatus.UnknownError;\r
 \r
@@ -97,12 +100,10 @@ namespace System.Net
                }\r
 #endif \r
 \r
-#if NET_2_0\r
                public override void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)\r
                {\r
                        base.GetObjectData (serializationInfo,\r
                                            streamingContext);\r
                }\r
-#endif\r
        }\r
 }\r
index ae4598f0383525b608981a9868baba5c4c2fac75..16f77533a40dfc0c95c8c2420a44d110c8f28723 100644 (file)
@@ -33,9 +33,7 @@
 
 using System;
 using System.Collections;
-#if NET_2_0
 using System.Collections.Generic;
-#endif
 using System.Collections.Specialized;
 using System.Runtime.InteropServices;
 using System.Runtime.Serialization;
@@ -45,15 +43,16 @@ using System.Text;
     
 namespace System.Net 
 {
+#if MOONLIGHT
+       internal class WebHeaderCollection : NameValueCollection, ISerializable {
+#else
        [Serializable]
        [ComVisible(true)]
-       public class WebHeaderCollection : NameValueCollection, ISerializable
-       {
+       public class WebHeaderCollection : NameValueCollection, ISerializable {
+#endif
                private static readonly Hashtable restricted;
                private static readonly Hashtable multiValue;
-#if NET_2_0
                static readonly Dictionary<string, bool> restricted_response;
-#endif
                private bool internallyCreated = false;
                
                // Static Initializer
@@ -80,12 +79,11 @@ namespace System.Net
                        restricted.Add ("proxy-connection", true);                      
 
                        //
-#if NET_2_0
                        restricted_response = new Dictionary<string, bool> (StringComparer.InvariantCultureIgnoreCase);
                        restricted_response.Add ("Content-Length", true);
                        restricted_response.Add ("Transfer-Encoding", true);
                        restricted_response.Add ("WWW-Authenticate", true);
-#endif
+
                        // see par 14 of RFC 2068 to see which header names
                        // accept multiple values each separated by a comma
                        multiValue = new Hashtable (CaseInsensitiveHashCodeProvider.DefaultInvariant,
@@ -263,7 +261,6 @@ namespace System.Net
                        return restricted.ContainsKey (headerName);
                }
 
-#if NET_2_0
                public static bool IsRestricted (string headerName, bool response)
                {
                        if (String.IsNullOrEmpty (headerName))
@@ -277,7 +274,6 @@ namespace System.Net
                                return restricted_response.ContainsKey (headerName);
                        return restricted.ContainsKey (headerName);
                }
-#endif
 
                public override void OnDeserialization (object sender)
                {
@@ -380,7 +376,6 @@ namespace System.Net
                        return(base.GetKey (index));
                }
 
-#if NET_2_0
                public void Add (HttpRequestHeader header, string value)
                {
                        Add (RequestHeaderToString (header), value);
@@ -603,7 +598,6 @@ namespace System.Net
                {
                        return(base.GetEnumerator ());
                }
-#endif
 
                // Internal Methods
                
index 43ddcaaffd32e0b1fdb6becee915a409e7c791a8..06f3c72b4dc1e7deb8f15c71fe01b61fba5c7259 100644 (file)
@@ -40,7 +40,7 @@ using System.Net.Cache;
 using System.Security.Principal;
 #endif
 
-#if MONOTOUCH
+#if NET_2_1
 using ConfigurationException = System.ArgumentException;
 
 namespace System.Net.Configuration {
@@ -50,9 +50,12 @@ namespace System.Net.Configuration {
 
 namespace System.Net 
 {
+#if MOONLIGHT
+       internal abstract class WebRequest : ISerializable {
+#else
        [Serializable]
-       public abstract class WebRequest : MarshalByRefObject, ISerializable
-       {
+       public abstract class WebRequest : MarshalByRefObject, ISerializable {
+#endif
                static HybridDictionary prefixes = new HybridDictionary ();
 #if NET_2_0
                static bool isDefaultWebProxySet;
@@ -63,13 +66,15 @@ namespace System.Net
                
                static WebRequest ()
                {
-#if MONOTOUCH
+#if NET_2_1
                        AddPrefix ("http", typeof (HttpRequestCreator));
                        AddPrefix ("https", typeof (HttpRequestCreator));
+       #if MONOTOUCH
                        AddPrefix ("file", typeof (FileWebRequestCreator));
                        AddPrefix ("ftp", typeof (FtpRequestCreator));
+       #endif
 #else
-#if NET_2_0 && CONFIGURATION_DEP
+       #if NET_2_0 && CONFIGURATION_DEP
                        object cfg = ConfigurationManager.GetSection ("system.net/webRequestModules");
                        WebRequestModulesSection s = cfg as WebRequestModulesSection;
                        if (s != null) {
@@ -78,7 +83,7 @@ namespace System.Net
                                        AddPrefix (el.Prefix, el.Type);
                                return;
                        }
-#endif
+       #endif
                        ConfigurationSettings.GetConfig ("system.net/webRequestModules");
 #endif
                }
@@ -161,7 +166,7 @@ namespace System.Net
                        set { throw GetMustImplement (); }
                }
                
-#if NET_2_0
+#if NET_2_0 && !MOONLIGHT
                public TokenImpersonationLevel ImpersonationLevel {
                        get { throw GetMustImplement (); }
                        set { throw GetMustImplement (); }
index ac5fbc2546597e163360737d2ee04792777df5b0..b87d65b40c2e2f3b18c79f2672c4209949d8cdd5 100644 (file)
@@ -32,9 +32,12 @@ using System.Runtime.Serialization;
 \r
 namespace System.Net \r
 {\r
+#if MOONLIGHT\r
+       internal abstract class WebResponse : MarshalByRefObject, ISerializable, IDisposable {\r
+#else\r
        [Serializable]\r
-       public abstract class WebResponse : MarshalByRefObject, ISerializable, IDisposable\r
-       {\r
+       public abstract class WebResponse : MarshalByRefObject, ISerializable, IDisposable {\r
+#endif\r
                // Constructors\r
                \r
                protected WebResponse () { }\r
@@ -60,7 +63,6 @@ namespace System.Net
                        get { throw new NotSupportedException (); }\r
                }\r
 \r
-#if NET_2_0\r
                static Exception GetMustImplement ()\r
                {\r
                        return new NotImplementedException ();\r
@@ -81,7 +83,6 @@ namespace System.Net
                                throw GetMustImplement ();\r
                        }\r
                }\r
-#endif\r
                \r
                public virtual Uri ResponseUri {                \r
                        get { throw new NotSupportedException (); }\r
@@ -114,12 +115,10 @@ namespace System.Net
                        throw new NotSupportedException ();\r
                }\r
 \r
-#if NET_2_0\r
                [MonoTODO]\r
                protected virtual void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)\r
                {\r
                        throw GetMustImplement ();\r
                }\r
-#endif\r
        }\r
 }\r
diff --git a/mcs/class/System/System.Runtime.Versioning/ChangeLog b/mcs/class/System/System.Runtime.Versioning/ChangeLog
new file mode 100644 (file)
index 0000000..873b6e2
--- /dev/null
@@ -0,0 +1,7 @@
+2010-04-08  Jb Evain  <jbevain@novell.com>
+
+       * FrameworkName.cs: add missing Equals override.
+
+2010-04-06  Jb Evain  <jbevain@novell.com>
+
+       * FrameworkName.cs: moved here from corlib where it was pre-RC.
diff --git a/mcs/class/System/System.Runtime.Versioning/FrameworkName.cs b/mcs/class/System/System.Runtime.Versioning/FrameworkName.cs
new file mode 100644 (file)
index 0000000..35253ba
--- /dev/null
@@ -0,0 +1,233 @@
+//
+// System.Runtime.Versioning.FrameworkName class
+//
+// Authors
+//     Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Text;
+
+#if NET_4_0
+namespace System.Runtime.Versioning
+{
+       [Serializable]
+       public sealed class FrameworkName : IEquatable <FrameworkName>
+       {               
+               string fullName;
+               int? hashCode;
+               
+               public string FullName {
+                       get {
+                               if (fullName == null) {
+                                       var sb = new StringBuilder (Identifier);
+                                       sb.Append (",Version=v");
+                                       sb.Append (Version.ToString ());
+
+                                       string profile = Profile;
+                                       if (!String.IsNullOrEmpty (profile)) {
+                                               sb.Append (",Profile=");
+                                               sb.Append (profile);
+                                       }
+
+                                       fullName = sb.ToString ();
+                               }
+
+                               return fullName;
+                       }
+               }
+               
+               public string Identifier {
+                       get; private set;
+               }
+
+               public string Profile {
+                       get; private set;
+               }
+               
+               public Version Version {
+                       get; private set;
+               }
+               
+               public FrameworkName (string frameworkName)
+               {
+                       if (frameworkName == null)
+                               throw new ArgumentNullException ("frameworkName");
+
+                       if (frameworkName.Length == 0)
+                               throw new ArgumentException ("The parameter 'frameworkName' cannot be an empty string.", "frameworkName");
+
+                       this.Profile = String.Empty;
+                       ParseFrameworkName (frameworkName);
+               }
+
+               public FrameworkName (string identifier, Version version)
+                       : this (identifier, version, String.Empty)
+               {
+               }
+
+               public FrameworkName (string identifier, Version version, string profile)
+               {
+                       if (identifier == null)
+                               throw new ArgumentNullException ("identifier");
+
+                       if (version == null)
+                               throw new ArgumentNullException ("version");
+
+                       if (identifier.Length == 0)
+                               throw new ArgumentException ("The parameter 'identifier' cannot be an empty string.", "identifier");
+                       
+                       this.Identifier = identifier;
+                       this.Version = version;
+                       if (profile == null)
+                               this.Profile = String.Empty;
+                       else
+                               this.Profile = profile;
+               }
+
+               public bool Equals (FrameworkName other)
+               {
+                       if (Object.ReferenceEquals (other, null))
+                               return false;
+
+                       return (other.Version == this.Version &&
+                               String.Compare (other.Identifier, this.Identifier, StringComparison.Ordinal) == 0 &&
+                               String.Compare (other.Profile, this.Profile, StringComparison.Ordinal) == 0);
+               }
+
+               public override bool Equals (object obj)
+               {
+                       return Equals (obj as FrameworkName);
+               }
+
+               public override int GetHashCode ()
+               {
+                       if (hashCode == null) {
+                               hashCode = Version.GetHashCode () ^ Identifier.GetHashCode ();
+                               string profile = Profile;
+                               if (profile != null)
+                                       hashCode ^= profile.GetHashCode ();
+                       }
+                       
+                       return (int)hashCode;
+               }
+
+               public override string ToString ()
+               {
+                       return FullName;
+               }
+
+               public static bool operator == (FrameworkName left, FrameworkName right)
+               {
+                       if (((object)left) == null && ((object)right) == null)
+                               return true;
+
+                       if (((object)left) == null || ((object)right) == null)
+                               return false;
+
+                       return left.Equals (right);
+               }
+
+               public static bool operator != (FrameworkName left, FrameworkName right)
+               {
+                       if (((object)left) == null && ((object)right) == null)
+                               return false;
+
+                       if (((object)left) == null || ((object)right) == null)
+                               return true;
+
+                       return !left.Equals (right);
+               }
+               
+               void ParseFrameworkName (string frameworkName)
+               {
+                       string[] parts = frameworkName.Split (',');
+                       int len = parts.Length;
+
+                       if (len < 2 || len > 3)
+                               throw new ArgumentException ("FrameworkName cannot have less than two components or more than three components.");
+
+                       bool invalid = false;
+                       string part;
+                       string[] splitPart;
+                       int splen;
+                       
+                       for (int i = 0; i < len; i++) {
+                               part = parts [i].Trim ();
+                               if (part.Length == 0) {
+                                       invalid = true;
+                                       break;
+                               }
+
+                               splitPart = part.Split ('=');
+                               splen = splitPart.Length;
+                               
+                               if (String.Compare ("version", splitPart [0], StringComparison.OrdinalIgnoreCase) == 0) {
+                                       if (i == 0 || splen != 2) {
+                                               invalid = true;
+                                               break;
+                                       }                                       
+
+                                       try {
+                                               char first = splitPart [1][0];
+                                               if (first == 'v' || first == 'V')
+                                                       splitPart [1] = splitPart [1].Substring (1);
+                                               this.Version = new Version (splitPart [1]);
+                                       } catch (Exception ex) {
+                                               throw new ArgumentException ("FrameworkName version component is invalid.", ex);
+                                       }                                       
+
+                                       continue;
+                               }
+
+                               if (String.Compare ("profile", splitPart [0], StringComparison.OrdinalIgnoreCase) == 0) {
+                                       if (i == 0) {
+                                               invalid = true;
+                                               break;
+                                       }
+
+                                       if (splen > 1)
+                                               Profile = String.Join ("=", splitPart, 1, splen - 1);
+                                       
+                                       continue;
+                               }
+
+                               if (i == 0) {
+                                       Identifier = part;
+                                       continue;
+                               }
+
+                               invalid = true;
+                               break;
+                       }
+
+                       if (invalid)
+                               throw new ArgumentException ("FrameworkName is invalid.");
+
+                       if (Version == null)
+                               throw new ArgumentException ("FrameworkName version component is missing.");
+                       
+               }
+       }
+}
+#endif
\ No newline at end of file
index 81ea79899f9e85099fd421162b34423c0a72ad4f..f84b86149104f17fc17cd45875aeffcfb1c0b61b 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * X509Chain.cs: use MOONLIGHT symbol to disambiguate MonoTouch
+       and Moonlight code.
+
 2010-03-11 Gonzalo Paniagua Javier <gonzalo@novell.com>
 
        * OSX509Certificates.cs: moved here from Mono.Security.
index a8399891d2bb1395ebcff40e264c7a11092f0204..678cb8f9baee41335edf3b0cf230f373ea721050 100644 (file)
@@ -857,7 +857,7 @@ namespace System.Security.Cryptography.X509Certificates {
                }
        }
 }
-#elif NET_2_0 && (!NET_2_1 || MONOTOUCH)
+#elif NET_2_0 && !MOONLIGHT
 namespace System.Security.Cryptography.X509Certificates {
        public class X509Chain {
                public bool Build (X509Certificate2 cert)
index c3a8ba66e6238f7339ff3d10d3b48c8a3e7e96a5..972e2ccf3198af9a0452a5024ab81621f2c4e3ed 100644 (file)
@@ -47,7 +47,7 @@ namespace System.Text.RegularExpressions {
                static FieldInfo fi_stack = typeof (RxInterpreter).GetField ("stack", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
                static FieldInfo fi_mark_start = typeof (Mark).GetField ("Start", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
                static FieldInfo fi_mark_end = typeof (Mark).GetField ("End", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
-               static FieldInfo fi_mark_index = typeof (Mark).GetField ("Index", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
+               //static FieldInfo fi_mark_index = typeof (Mark).GetField ("Index", BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
 
                static MethodInfo mi_stack_get_count, mi_stack_set_count, mi_stack_push, mi_stack_pop;
                static MethodInfo mi_set_start_of_match, mi_is_word_char, mi_reset_groups;
index d706ed3ffb5e4a255bce33d702c5fda577a06312..4850f74212a369dfc2bfb38252aaa0fea496bab3 100644 (file)
@@ -1,3 +1,7 @@
+2010-03-20  Miguel de Icaza  <miguel@novell.com>
+
+       * RxInterpreter.cs: Removed warnings.
+
 2010-02-03  Rodrigo Kumpera  <rkumpera@novell.com>
 
        * BaseMachine.cs (Split): Don't add empty strings if they don't come from
index 945b2634095350677d57b953efb8e5c8814770b4..3f5d987ed91d2484e6908ed635808da94d1c0af5 100644 (file)
@@ -1,6 +1,9 @@
 
 // Based upon interpreter.cs, written by Dan Lewis (dlewis@gmx.co.uk)
-
+//
+// There are a couple of bits flagged with DEAD_CODE which are bits that do
+// not seem to have been completed
+//
 using System;
 using System.Collections;
 using System.Globalization;
@@ -899,7 +902,7 @@ namespace System.Text.RegularExpressions {
                                
                                case RxOp.CategoryAnySingleline:
                                        if (strpos < string_end) {
-                                               char c = str [strpos];
+                                               // char c = str [strpos];
                                                if ((true)) {
                                                        strpos ++;
                                                        if (char_group_end != 0)
@@ -1258,6 +1261,7 @@ namespace System.Text.RegularExpressions {
                                        return false;
                                case RxOp.NoCategoryAnySingleline:
                                        if (strpos < string_end) {
+#if DEAD_CODE
                                                char c = str [strpos];
                                                if (!(true)) {
                                                        pc += 1;
@@ -1268,6 +1272,7 @@ namespace System.Text.RegularExpressions {
                                                        }
                                                        continue;
                                                }
+#endif
                                        }
                                        return false;
                                case RxOp.NoCategoryWord:
@@ -1575,7 +1580,7 @@ namespace System.Text.RegularExpressions {
                                        continue;
                                case RxOp.CategoryAnySinglelineReverse:
                                        if (strpos > 0) {
-                                               char c = str [strpos - 1];
+                                               //char c = str [strpos - 1];
                                                if ((true)) {
                                                        strpos --;
                                                        if (char_group_end != 0)
@@ -1904,6 +1909,7 @@ namespace System.Text.RegularExpressions {
                                        return false;
                                case RxOp.NoCategoryAnySinglelineReverse:
                                        if (strpos > 0) {
+#if DEAD_CODe
                                                char c = str [strpos - 1];
                                                if (!(true)) {
                                                        pc += 1;
@@ -1914,6 +1920,7 @@ namespace System.Text.RegularExpressions {
                                                        }
                                                        continue;
                                                }
+#endif
                                        }
                                        return false;
                                case RxOp.NoCategoryWordReverse:
index 401f7264dc3c3b8a05f135dda991b4929b973d42..8b7efcc3eccc5c360d381a7aa637783191ccccaa 100644 (file)
@@ -1,4 +1,4 @@
-#if NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0
 // 
 // Barrier.cs
 //  
@@ -31,7 +31,7 @@ namespace System.Threading
 {
        public class Barrier : IDisposable
        {
-               const int MAX_PARTICIPANTS = 32767;
+               const int MaxParticipants = 32767;
                Action<Barrier> postPhaseAction;
                
                int participants;
@@ -45,7 +45,7 @@ namespace System.Threading
                
                public Barrier (int participants, Action<Barrier> postPhaseAction)
                {
-                       if (participants < 0 || participants > MAX_PARTICIPANTS)
+                       if (participants < 0 || participants > MaxParticipants)
                                throw new ArgumentOutOfRangeException ("participants");
                        
                        this.participants = participants;
@@ -120,6 +120,7 @@ namespace System.Threading
                        
                        if (cntd.Signal (participantCount))
                                PostPhaseAction (cleaned);
+
                        Interlocked.Add (ref participants, -participantCount);
                }
                
index 4c3c189c1888da36c96f8d71c5f95b0bea9e1719..1a3c6005e14b744d6e29a60de1f08b4bd321f0c1 100644 (file)
@@ -1,3 +1,11 @@
+2010-04-15  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * Barrier.cs: Add BOOTSTRAP_NET_4_0
+
+2010-04-06  Jb Evain  <jbevain@novell.com>
+
+       * SemaphoreFullException.cs: moved to corlib in net_4_0.
+
 2010-03-02  Jérémie Laval  <jeremie.laval@gmail.com>
 
        * Barrier.cs: Remove dead comments
index bb06d1023b53647526479579dbd8fd4bd21c924b..4b8b2376c35b9af734be51a209a0fea45b60590e 100644 (file)
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_0 || (NET_4_0 && INSIDE_CORLIB)
+#if (!NET_4_0 && NET_2_0 && !INSIDE_CORLIB) || ((NET_4_0 || BOOTSTRAP_NET_4_0) && INSIDE_CORLIB)
 
 using System.Runtime.InteropServices;
 using System.Runtime.Serialization;
@@ -34,8 +34,8 @@ using System.Runtime.CompilerServices;
 
 namespace System.Threading {
 
-#if NET_4_0 && INSIDE_CORLIB
-//     [TypeForwardedFrom (Consts.AssemblySystem_2_0)]
+#if (NET_4_0 || BOOTSTRAP_NET_4_0) && INSIDE_CORLIB
+       [TypeForwardedFrom (Consts.AssemblySystem_2_0)]
 #endif
        [ComVisible (false)]
        [Serializable]
@@ -61,6 +61,11 @@ namespace System.Threading {
                {
                }
        }
+
 }
+#elif (NET_4_0 || BOOTSTRAP_NET_4_0) && !INSIDE_CORLIB
+using System.Runtime.CompilerServices;
+using System.Threading;
 
+[assembly: TypeForwardedTo (typeof (SemaphoreFullException))]
 #endif
index 1ef812cbaa43d521b4beb9efd1744bce83d78467..e417d1b4d09cfccd5d88f76e50473c14060b4146 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-19  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * Timer.cs: Removed old NET_2_0 defines and added some new
+       MOONLIGHT defines (needed for the client stack)
+
 2009-09-29  Sebastien Pouliot  <sebastien@ximian.com>
 
        * Timer_2_1.cs: Removed. No longer needed by Moonlight
index fc907a6a8d44a131ac3bed1f4cdee02ab85f970b..6126b9dcb65bebed1aefb130676851099784859e 100644 (file)
@@ -35,10 +35,13 @@ using System.Threading;
 
 namespace System.Timers
 {
+#if MOONLIGHT
+       internal class Timer {
+#else
        [DefaultEventAttribute("Elapsed")]
        [DefaultProperty("Interval")]
-       public class Timer : Component, ISupportInitialize
-       {
+       public class Timer : Component, ISupportInitialize {
+#endif
                double interval;
                bool autoReset;
                System.Threading.Timer timer;
@@ -55,11 +58,9 @@ namespace System.Timers
 
                public Timer (double interval)
                {
-#if NET_2_0
                        // MSBUG: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=296761
                        if (interval > 0x7FFFFFFF)
                                throw new ArgumentException ("Invalid value: " + interval, "interval");
-#endif
 
                        autoReset = true;
                        Interval = interval;
@@ -119,18 +120,17 @@ namespace System.Timers
                        }
                }
 
+#if !MOONLIGHT
                public override ISite Site
                {
                        get { return base.Site; }
                        set { base.Site = value; }
                }
-
+#endif
                [DefaultValue(null)]
                [TimersDescriptionAttribute("The object used to marshal the event handler calls issued " +
                                            "when an interval has elapsed.")]
-#if NET_2_0
                [Browsable (false)]
-#endif
                public ISynchronizeInvoke SynchronizingObject
                {
                        get { return so; }
@@ -162,11 +162,18 @@ namespace System.Timers
                        Enabled = false;
                }
 
+#if MOONLIGHT
+               protected void Dispose (bool disposing)
+               {
+                       Close ();
+               }
+#else
                protected override void Dispose (bool disposing)
                {
                        Close ();
                        base.Dispose (disposing);
                }
+#endif
 
                static void Callback (object state)
                {
index 5427553b03cdb2024d2cabb6643e0261d1fff39d..06e1a5b248e1c4c12e921125c9a4acb58a71b568 100644 (file)
@@ -147,6 +147,7 @@ System.Collections.Generic/RBTree.cs
 System.Collections.Generic/Queue.cs
 System.Collections.Generic/SortedDictionary.cs
 System.Collections.Generic/SortedList.cs
+System.Collections.Generic/SortedSet.cs
 System.Collections.Generic/Stack.cs
 System.Collections.ObjectModel/ObservableCollection.cs
 System.Collections.ObjectModel/ReadOnlyObservableCollection.cs
@@ -566,6 +567,7 @@ System.Diagnostics/TraceSourceInfo.cs
 System.Diagnostics/TraceSwitch.cs
 System.Diagnostics/Win32EventLog.cs
 System.Diagnostics/XmlWriterTraceListener.cs
+System.Diagnostics.CodeAnalysis/ExcludeFromCodeCoverageAttribute.cs
 System/FileStyleUriParser.cs
 System/FtpStyleUriParser.cs
 System/GenericUriParser.cs
@@ -873,6 +875,7 @@ System.Net/WebRequestMethods.cs
 System.Net/WebResponse.cs
 System.Net/WebUtility.cs
 System/NewsStyleUriParser.cs
+System.Runtime.Versioning/FrameworkName.cs
 System.Security.AccessControl/SemaphoreAccessRule.cs
 System.Security.AccessControl/SemaphoreAuditRule.cs
 System.Security.AccessControl/SemaphoreRights.cs
index d5b3fb9ac8fdb804c0a1ad73007b29d4db584a83..3b9dcdc2fedd1565641f33f5fdc9a0acd4ff74f5 100644 (file)
@@ -1,3 +1,24 @@
+2010-04-17  Raja R Harinath  <harinath@hurrynot.org>
+
+       Keep "ftp://a.b/%2fcd" urls unmolested
+       * Uri.cs (CompactEscaped): New.  Check if scheme allows escaped
+       path characters are compacted (list of schemes obtained from MSDN).
+       (Reduce): Add argument that is set if escaped characters need to
+       be compacted.
+
+2010-03-20  Miguel de Icaza  <miguel@novell.com>
+
+       * Uri.cs: Drop pre-2.0 support
+
+2010-03-19  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * Uri.cs: Remove some MOONLIGHT defines
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * Uri.cs, UriTypeConverter.cs: use MOONLIGHT symbol to
+       disambiguate MonoTouch and Moonlight code.
+
 2010-01-27  Carlos Alberto Cortez <calberto.cortez@gmail.com>
 
        * Uri.cs: In IsWellFormedOriginalString(), call to our internal
index f3ccc02bf0adfc34836899011259585bded20cf3..6f435c7fb8e33e1f07e7014d1e74bdff743c5bdb 100644 (file)
@@ -55,12 +55,8 @@ using System.Globalization;
 namespace System {
 
        [Serializable]
-#if NET_2_0
        [TypeConverter (typeof (UriTypeConverter))]
        public class Uri : ISerializable {
-#else
-       public class Uri : MarshalByRefObject, ISerializable {
-#endif
                // NOTES:
                // o  scheme excludes the scheme delimiter
                // o  port is -1 to indicate no port is defined
@@ -106,14 +102,12 @@ namespace System {
                public static readonly string UriSchemeMailto = "mailto";
                public static readonly string UriSchemeNews = "news";
                public static readonly string UriSchemeNntp = "nntp";
-#if NET_2_0
                public static readonly string UriSchemeNetPipe = "net.pipe";
                public static readonly string UriSchemeNetTcp = "net.tcp";
-#endif
 
                // Constructors         
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                public Uri (string uriString) : this (uriString, UriKind.Absolute) 
                {
                }
@@ -128,7 +122,6 @@ namespace System {
                {
                }
 
-#if NET_2_0
                public Uri (string uriString, UriKind uriKind)
                {
                        source = uriString;
@@ -212,17 +205,6 @@ namespace System {
                                throw new UriFormatException("Invalid URI: The format of the URI could not be "
                                        + "determined: " + uriString);
                }
-#else
-               public Uri (string uriString, bool dontEscape) 
-               {
-                       userEscaped = dontEscape;
-                       source = uriString;
-                       Parse ();
-                       if (!isAbsoluteUri)
-                               throw new UriFormatException("Invalid URI: The format of the URI could not be "
-                                       + "determined.");
-               }
-#endif
 
                public Uri (Uri baseUri, string relativeUri) 
                {
@@ -230,9 +212,7 @@ namespace System {
                        // FIXME: this should call UriParser.Resolve
                }
 
-#if NET_2_0
                [Obsolete ("dontEscape is always false")]
-#endif
                public Uri (Uri baseUri, string relativeUri, bool dontEscape) 
                {
                        userEscaped = dontEscape;
@@ -241,27 +221,19 @@ namespace System {
 
                private void Merge (Uri baseUri, string relativeUri)
                {
-#if NET_2_0
                        if (baseUri == null)
                                throw new ArgumentNullException ("baseUri");
                        if (!baseUri.IsAbsoluteUri)
                                throw new ArgumentOutOfRangeException ("baseUri");
                        if (relativeUri == null)
                                relativeUri = String.Empty;
-#else
-                       if (baseUri == null)
-                               throw new NullReferenceException ("baseUri");
-#endif
+
                        // See RFC 2396 Par 5.2 and Appendix C
 
                        // Check Windows UNC (for // it is scheme/host separator)
                        if (relativeUri.Length >= 2 && relativeUri [0] == '\\' && relativeUri [1] == '\\') {
                                source = relativeUri;
-#if NET_2_0
                                ParseUri (UriKind.Absolute);
-#else
-                               Parse ();
-#endif
                                return;
                        }
 
@@ -286,11 +258,7 @@ namespace System {
                                            relativeUri.Length > pos + 1 &&
                                            relativeUri [pos + 1] == '/') {
                                                source = relativeUri;
-#if NET_2_0
                                                ParseUri (UriKind.Absolute);
-#else
-                                               Parse ();
-#endif
                                                return;
                                        }
                                        else
@@ -336,11 +304,7 @@ namespace System {
                        if (relativeUri.Length > 0 && relativeUri [0] == '/') {
                                if (relativeUri.Length > 1 && relativeUri [1] == '/') {
                                        source = scheme + ':' + relativeUri;
-#if NET_2_0
                                        ParseUri (UriKind.Absolute);
-#else
-                                       Parse ();
-#endif
                                        return;
                                } else {
                                        path = relativeUri;
@@ -421,7 +385,6 @@ namespace System {
                
                public string AbsolutePath { 
                        get {
-#if NET_2_0
                                EnsureAbsoluteUri ();
                                switch (Scheme) {
                                case "mailto":
@@ -438,9 +401,6 @@ namespace System {
                                        }
                                        return path;
                                }
-#else
-                               return path;
-#endif
                        }
                }
 
@@ -479,29 +439,22 @@ namespace System {
                                return host; 
                        } 
                }
-#if !NET_2_1 || MONOTOUCH
+
                public UriHostNameType HostNameType { 
                        get {
                                EnsureAbsoluteUri ();
                                UriHostNameType ret = CheckHostName (Host);
                                if (ret != UriHostNameType.Unknown)
                                        return ret;
-#if NET_2_0
                                switch (Scheme) {
                                case "mailto":
                                        return UriHostNameType.Basic;
                                default:
                                        return (IsFile) ? UriHostNameType.Basic : ret;
                                }
-#else
-                               // looks it always returns Basic...
-                               return UriHostNameType.Basic; //.Unknown;
-#endif
                        } 
                }
 
-#endif // NET_2_1
-
                public bool IsDefaultPort { 
                        get {
                                EnsureAbsoluteUri ();
@@ -516,17 +469,12 @@ namespace System {
                        }
                }
 
-#if !NET_2_1 || MONOTOUCH
                public bool IsLoopback { 
                        get {
                                EnsureAbsoluteUri ();
                                
                                if (Host.Length == 0) {
-#if NET_2_0
                                        return IsFile;
-#else
-                                       return false;
-#endif
                                }
 
                                if (host == "loopback" || host == "localhost") 
@@ -547,8 +495,6 @@ namespace System {
                        } 
                }
 
-#endif // NET_2_1
-
                public bool IsUnc {
                        // rule: This should be true only if
                        //   - uri string starts from "\\", or
@@ -592,13 +538,9 @@ namespace System {
                                        else if (System.IO.Path.DirectorySeparatorChar == '\\') {
                                                string h = host;
                                                if (path.Length > 0) {
-#if NET_2_0
                                                        if ((path.Length > 1) || (path[0] != '/')) {
                                                                h += path.Replace ('/', '\\');
                                                        }
-#else
-                                                       h += path.Replace ('/', '\\');
-#endif
                                                }
                                                cachedLocalPath = "\\\\" + Unescape (h);
                                        }  else
@@ -689,7 +631,6 @@ namespace System {
                        }
                }
                
-#if NET_2_0
                [MonoTODO ("add support for IPv6 address")]
                public string DnsSafeHost {
                        get {
@@ -701,18 +642,13 @@ namespace System {
                public bool IsAbsoluteUri {
                        get { return isAbsoluteUri; }
                }
-#endif
+
                // LAMESPEC: source field is supplied in such case that this
                // property makes sense. For such case that source field is
                // not supplied (i.e. .ctor(Uri, string), this property
                // makes no sense. To avoid silly regression it just returns
                // ToString() value now. See bug #78374.
-#if NET_2_0
-               public
-#else
-               internal
-#endif
-               string OriginalString {
+               public string OriginalString {
                        get { return source != null ? source : ToString (); }
                }
 
@@ -749,16 +685,8 @@ namespace System {
                                if (length == 0)
                                        return false;
                                uint number;
-#if NET_2_0
                                if (!UInt32.TryParse (captures [i], out number))
                                        return false;
-#else
-                               try {
-                                       number = UInt32.Parse (captures [i]);
-                               } catch (Exception) {
-                                       return false;
-                               }
-#endif
                                if (number > 255)
                                        return false;
                        }
@@ -788,9 +716,7 @@ namespace System {
                }
 #if !NET_2_1
 
-#if NET_2_0
                [Obsolete("This method does nothing, it has been obsoleted")]
-#endif
                protected virtual void Canonicalize ()
                {
                        //
@@ -800,9 +726,7 @@ namespace System {
                }
 
                [MonoTODO ("Find out what this should do")]
-#if NET_2_0
                [Obsolete]
-#endif
                protected virtual void CheckSecurity ()
                {
                }
@@ -830,15 +754,10 @@ namespace System {
 
                private static bool IsAlpha (char c)
                {
-#if NET_2_0
                        // as defined in rfc2234
                        // %x41-5A / %x61-7A (A-Z / a-z)
                        int i = (int) c;
                        return (((i >= 0x41) && (i <= 0x5A)) || ((i >= 0x61) && (i <= 0x7A)));
-#else
-                       // Fx 1.x got this too large
-                       return Char.IsLetter (c);
-#endif
                }
 
                public override bool Equals (object comparant) 
@@ -860,27 +779,19 @@ namespace System {
                // Assumes: uri != null
                bool InternalEquals (Uri uri)
                {
-#if NET_2_0
                        if (this.isAbsoluteUri != uri.isAbsoluteUri)
                                return false;
                        if (!this.isAbsoluteUri)
                                return this.source == uri.source;
-#endif
 
                        CultureInfo inv = CultureInfo.InvariantCulture;
                        return this.scheme.ToLower (inv) == uri.scheme.ToLower (inv)
                                && this.host.ToLower (inv) == uri.host.ToLower (inv)
                                && this.port == uri.port
-#if NET_2_0
                                && this.query == uri.query
-#else
-                               // Note: MS.NET 1.x has bug - ignores query check altogether
-                               && this.query.ToLower (inv) == uri.query.ToLower (inv)
-#endif
                                && this.path == uri.path;
                }
 
-#if NET_2_0
                public static bool operator == (Uri u1, Uri u2)
                {
                        return object.Equals(u1, u2);
@@ -890,7 +801,6 @@ namespace System {
                {
                        return !(u1 == u2);
                }
-#endif
 
                public override int GetHashCode () 
                {
@@ -900,11 +810,7 @@ namespace System {
                                        cachedHashCode = scheme.ToLower (inv).GetHashCode ()
                                                ^ host.ToLower (inv).GetHashCode ()
                                                ^ port
-#if NET_2_0
                                                ^ query.GetHashCode ()
-#else
-                                               ^ query.ToLower (inv).GetHashCode ()
-#endif
                                                ^ path.GetHashCode ();
                                }
                                else {
@@ -951,19 +857,15 @@ namespace System {
                                        sb.Append (':').Append (port);
 
                                if (path.Length > 0) {
-#if NET_2_0
                                        switch (Scheme) {
                                        case "mailto":
                                        case "news":
                                                sb.Append (path);
                                                break;
                                        default:
-                                               sb.Append (Reduce (path));
+                                               sb.Append (Reduce (path, CompactEscaped (Scheme)));
                                                break;
                                        }
-#else
-                                       sb.Append (path);
-#endif
                                }
                                return sb.ToString ();
                        }
@@ -1029,7 +931,6 @@ namespace System {
                                IsHexDigit (pattern [index]));
                }
 
-#if NET_2_0
                //
                // Implemented by copying most of the MakeRelative code
                //
@@ -1064,7 +965,6 @@ namespace System {
                }
 
                [Obsolete ("Use MakeRelativeUri(Uri uri) instead.")]
-#endif
                public string MakeRelative (Uri toUri) 
                {
                        if ((this.Scheme != toUri.Scheme) ||
@@ -1118,12 +1018,10 @@ namespace System {
                        return cachedToString;
                }
 
-#if NET_2_0
                protected void GetObjectData (SerializationInfo info, StreamingContext context)
                {
                        info.AddValue ("AbsoluteUri", this.AbsoluteUri);
                }
-#endif
 
                void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
                {
@@ -1133,20 +1031,16 @@ namespace System {
 
                // Internal Methods             
 
-#if NET_2_0
                [Obsolete]
-#endif
                protected virtual void Escape ()
                {
                        path = EscapeString (path);
                }
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                static string EscapeString (string str)
 #else
-       #if NET_2_0
                [Obsolete]
-       #endif
                protected static string EscapeString (string str) 
 #endif
                {
@@ -1201,14 +1095,9 @@ namespace System {
                // On .NET 1.x, this method is called from .ctor(). When overriden, we 
                // can avoid the "absolute uri" constraints of the .ctor() by
                // overriding with custom code.
-#if NET_2_0
                [Obsolete("The method has been deprecated. It is not used by the system.")]
-#endif
                protected virtual void Parse ()
                {
-#if !NET_2_0
-                       ParseUri (UriKind.Absolute);
-#endif
                }
 
                private void ParseUri (UriKind kind)
@@ -1229,12 +1118,10 @@ namespace System {
                        }
                }
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                string Unescape (string str)
 #else
-       #if NET_2_0
                [Obsolete]
-       #endif
                protected virtual string Unescape (string str)
 #endif
                {
@@ -1386,7 +1273,7 @@ namespace System {
                        if (uriString [0] == '/' && Path.DirectorySeparatorChar == '/'){
                                //Unix Path
                                ParseAsUnixAbsoluteFilePath (uriString);
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                                isAbsoluteUri = false;
 #else
                                if (kind == UriKind.Relative)
@@ -1535,19 +1422,10 @@ namespace System {
                        if (pos != -1 && pos != endpos - 1) {
                                string portStr = uriString.Substring(pos + 1, endpos - (pos + 1));
                                if (portStr.Length > 0 && portStr[portStr.Length - 1] != ']') {
-#if NET_2_0
                                        if (!Int32.TryParse (portStr, NumberStyles.Integer, CultureInfo.InvariantCulture, out port) ||
                                            port < 0 || port > UInt16.MaxValue)
                                                return "Invalid URI: Invalid port number";
                                        endpos = pos;
-#else
-                                       try {
-                                               port = (int) UInt32.Parse (portStr, CultureInfo.InvariantCulture);
-                                               endpos = pos;
-                                       } catch (Exception) {
-                                               return "Invalid URI: Invalid port number";
-                                       }
-#endif
                                } else {
                                        if (port == -1) {
                                                port = GetDefaultPort (scheme);
@@ -1564,7 +1442,7 @@ namespace System {
                        host = uriString;
 
                        if (unixAbsPath) {
-                               path = Reduce ('/' + uriString);
+                               path = Reduce ('/' + uriString, true);
                                host = String.Empty;
                        } else if (host.Length == 2 && host [1] == ':') {
                                // windows filepath
@@ -1596,7 +1474,6 @@ namespace System {
                                else
                                        badhost = true;
                        }
-#if NET_2_0
                        if (badhost && (Parser is DefaultUriParser || Parser == null))
                                return Locale.GetText ("Invalid URI: The hostname could not be parsed. (" + host + ")");
 
@@ -1605,55 +1482,71 @@ namespace System {
                                Parser.InitializeAndValidate (this, out ex);
                        if (ex != null)
                                return ex.Message;
-#else
-                       if (badhost)
-                               return Locale.GetText ("Invalid URI: The hostname could not be parsed. (" + host + ")");
-#endif
 
                        if ((scheme != Uri.UriSchemeMailto) &&
                                        (scheme != Uri.UriSchemeNews) &&
                                        (scheme != Uri.UriSchemeFile)) {
-                               path = Reduce (path);
+                               path = Reduce (path, CompactEscaped (scheme));
                        }
 
                        return null;
                }
 
-               private static string Reduce (string path)
+               private static bool CompactEscaped (string scheme)
+               {
+                       switch (scheme) {
+                       case "file":
+                       case "http":
+                       case "https":
+                       case "net.pipe":
+                       case "net.tcp":
+                               return true;
+                       }
+                       return false;
+               }
+
+               // This is called "compacting" in the MSDN documentation
+               private static string Reduce (string path, bool compact_escaped)
                {
                        // quick out, allocation-free, for a common case
                        if (path == "/")
                                return path;
 
-                       // replace '\', %5C ('\') and %2f ('/') into '/'
-                       // other escaped values seems to survive this step
                        StringBuilder res = new StringBuilder();
-                       for (int i=0; i < path.Length; i++) {
-                               char c = path [i];
-                               switch (c) {
-                               case '\\':
-                                       res.Append ('/');
-                                       break;
-                               case '%':
-                                       if (i < path.Length - 2) {
-                                               char c1 = path [i + 1];
-                                               char c2 = Char.ToUpper (path [i + 2]);
-                                               if (((c1 == '2') && (c2 == 'F')) || ((c1 == '5') && (c2 == 'C'))) {
-                                                       res.Append ('/');
-                                                       i += 2;
+
+                       if (compact_escaped) {
+                               // replace '\', %5C ('\') and %2f ('/') into '/'
+                               // other escaped values seems to survive this step
+                               for (int i=0; i < path.Length; i++) {
+                                       char c = path [i];
+                                       switch (c) {
+                                       case '\\':
+                                               res.Append ('/');
+                                               break;
+                                       case '%':
+                                               if (i < path.Length - 2) {
+                                                       char c1 = path [i + 1];
+                                                       char c2 = Char.ToUpper (path [i + 2]);
+                                                       if (((c1 == '2') && (c2 == 'F')) || ((c1 == '5') && (c2 == 'C'))) {
+                                                               res.Append ('/');
+                                                               i += 2;
+                                                       } else {
+                                                               res.Append (c);
+                                                       }
                                                } else {
                                                        res.Append (c);
                                                }
-                                       } else {
+                                               break;
+                                       default:
                                                res.Append (c);
+                                               break;
                                        }
-                                       break;
-                               default:
-                                       res.Append (c);
-                                       break;
                                }
+                               path = res.ToString ();
+                       } else {
+                               path = path.Replace ('\\', '/');
                        }
-                       path = res.ToString ();
+
                        ArrayList result = new ArrayList ();
 
                        for (int startpos = 0; startpos < path.Length; ) {
@@ -1666,7 +1559,6 @@ namespace System {
 
                                if (current == "..") {
                                        int resultCount = result.Count;
-#if NET_2_0
                                        // in 2.0 profile, skip leading ".." parts
                                        if (resultCount == 0) {
                                                continue;
@@ -1674,16 +1566,6 @@ namespace System {
 
                                        result.RemoveAt (resultCount - 1);
                                        continue;
-#else
-                                       // in 1.x profile, retain leading ".." parts, and only reduce
-                                       // URI is previous part is not ".."
-                                       if (resultCount > 0) {
-                                               if ((string) result[resultCount - 1] != "..") {
-                                                       result.RemoveAt (resultCount - 1);
-                                                       continue;
-                                               }
-                                       }
-#endif
                                }
 
                                result.Add (current);
@@ -1836,17 +1718,10 @@ namespace System {
                
                internal static int GetDefaultPort (string scheme)
                {
-#if NET_2_0
                        UriParser parser = UriParser.GetParser (scheme);
                        if (parser == null)
                                return -1;
                        return parser.DefaultPort;
-#else
-                       for (int i = 0; i < schemes.Length; i++) 
-                               if (schemes [i].scheme == scheme)
-                                       return schemes [i].defaultPort;
-                       return -1;
-#endif
                }
 
                private string GetOpaqueWiseSchemeDelimiter ()
@@ -1857,9 +1732,7 @@ namespace System {
                                return GetSchemeDelimiter (scheme);
                }
 
-#if NET_2_0
                [Obsolete]
-#endif
                protected virtual bool IsBadFileSystemCharacter (char ch)
                {
                        // It does not always overlap with InvalidPathChars.
@@ -1882,9 +1755,7 @@ namespace System {
                        return false;
                }
 
-#if NET_2_0
                [Obsolete]
-#endif
                protected static bool IsExcludedCharacter (char ch)
                {
                        if (ch <= 32 || ch >= 127)
@@ -1921,19 +1792,15 @@ namespace System {
                        case "gopher":
                        case "mailto":
                        case "news":
-#if NET_2_0
                        case "net.pipe":
                        case "net.tcp":
-#endif
                                return true;
                        default:
                                return false;
                        }
                }
 
-#if NET_2_0
                [Obsolete]
-#endif
                protected virtual bool IsReservedCharacter (char ch)
                {
                        if (ch == '$' || ch == '&' || ch == '+' || ch == ',' ||
@@ -1942,7 +1809,7 @@ namespace System {
                                return true;
                        return false;
                }
-#if NET_2_0
+
                [NonSerialized]
                private UriParser parser;
 
@@ -2231,10 +2098,5 @@ namespace System {
                        if (!IsAbsoluteUri)
                                throw new InvalidOperationException ("This operation is not supported for a relative URI.");
                }
-#else
-               private void EnsureAbsoluteUri ()
-               {
-               }
-#endif
        }
 }
index cbf9446c37ea8c8ca4464cbfd20f696ee9f836d1..ea066b4f1d45146bf74420126d7179f95dae4ca2 100644 (file)
@@ -37,11 +37,12 @@ using System.Reflection;
 
 namespace System {
 
-#if NET_2_1 && !MONOTOUCH
-       public sealed class UriTypeConverter : TypeConverter {
-#else
-       public class UriTypeConverter : TypeConverter {
+       public
+#if MOONLIGHT
+       sealed
 #endif
+       class UriTypeConverter : TypeConverter {
+
                public UriTypeConverter ()
                {
                }
index a830880357f85d9c8d72fe1d4cea7194e8565d74..bf8920af0e6e0c27603b791e818b1a0b9b19fca8 100644 (file)
@@ -98,6 +98,7 @@ System.Collections.Generic/StackTest.cs
 System.Collections.Generic/LinkedListTest.cs
 System.Collections.Generic/SortedDictionaryTest.cs
 System.Collections.Generic/SortedListTest.cs
+System.Collections.Generic/SortedSetTest.cs
 System.Collections.Specialized/BasicOperationsTest.cs
 System.Collections.Specialized/BitVector32Test.cs
 System.Collections.Specialized/HybridDictionaryTest.cs
@@ -251,6 +252,7 @@ System.Net.Mail/SmtpPermissionAttributeTest.cs
 System.Net.Mime/ContentDispositionTest.cs
 System.Net.Mime/ContentTypeTest.cs
 System.Net.NetworkInformation/PhysicalAddressTest.cs
+System.Runtime.Versioning/FrameworkNameTest.cs
 System.Security.Cryptography/AsnEncodedDataTest.cs
 System.Security.Cryptography/OidCollectionTest.cs
 System.Security.Cryptography/OidEnumeratorTest.cs
index 91c184e7d81aa84bbd239bc437e9acd3e4326152..44339c0407ff5cba258f2ae70eead3c50c486acf 100644 (file)
@@ -1,3 +1,8 @@
+2010-04-12  Jonathan Pryor  <jpryor@novell.com>
+
+       * CodeGeneratorFromExpressionTest.cs: Test CodeDefaultValueExpression
+         generation.
+
 2009-06-26  Robert Jordan  <robertj@gmx.net>
 
        * CodeGeneratorIdentifierTest.cs: Upgrade to new NUnit style.
index 857cf9f3b93f7361a0f07a8adc08fb5e4c08fc8c..2bcbb8be1735ce995314f6e585840a2ab9c707bc 100644 (file)
@@ -506,6 +506,20 @@ namespace MonoTests.Microsoft.CSharp
                        }
                }
 
+#if NET_2_0
+               [Test]
+               public void DefaultValueExpressionTest ()
+               {
+                       StringBuilder sb = new StringBuilder ();
+
+                       using (StringWriter sw = new StringWriter (sb)) {
+                               Assert.AreEqual ("default(string)", Generate (new CodeDefaultValueExpression (new CodeTypeReference (typeof(string))), sw), "#0");
+                               sb.Length = 0;
+                               sw.Close ();
+                       }
+               }
+#endif
+
                [Test]
                public void DelegateInvokeTest ()
                {
index c90e43c226cd62cfc0ef772dc53d864a86e5db3b..46e6ca01c6ef56ae05525ab478fb96e46bac90a7 100644 (file)
@@ -1,3 +1,7 @@
+2010-04-13  Jonathan Pryor  <jpryor@novell.com>
+
+       * CodeGeneratorTest.cs: Add some testing for CodeRegionDirectives.
+
 2008-05-09  Gert Driesen  <drieseng@users.sourceforge.net>
 
        * CodeGeneratorFromTypeTestBase.cs: Added tests for
index 88f18da3b3d1b22de1ba47747f7fc3f0da4a9da9..2e4d104b2395b8dcb8ee8b4d6aa45c24febd6a3b 100644 (file)
@@ -91,6 +91,57 @@ namespace CodeGeneratorTest
                                CodeGenerator.IsValidLanguageIndependentIdentifier("a spacein2ndplace"), "#G8");
                }
 
+               [Test]
+               public void CurrentMemberShouldBeClearedBetweenTypes ()
+               {
+                       ICodeGenerator codeGenerator = new MockCodeGenerator ();
+                       var o = new StringWriter () {
+                               NewLine = "\n",
+                       };
+
+                       var t = new CodeTypeDeclaration() {
+                               Name = "Foo",
+                               Members = {
+                                       new CodeMemberField() {
+                                               Name = "f",
+                                       },
+                                       new CodeMemberMethod() {
+                                               Name = "M",
+                                               StartDirectives = {
+                                                       new CodeRegionDirective(CodeRegionMode.Start, "foo..."),
+                                               },
+                                               EndDirectives = {
+                                                       new CodeRegionDirective(CodeRegionMode.End, null),
+                                               },
+                                       }
+                               }
+                       };
+
+                       var opts = new CodeGeneratorOptions () {
+                               IndentString = "\t",
+                       };
+
+                       codeGenerator.GenerateCodeFromType (t, o, opts);
+                       t.Name = "Bar";
+                       codeGenerator.GenerateCodeFromType (t, o, opts);
+
+                       var expected = 
+                               "(type Foo\n" + 
+                               "\t\n" +
+                               "\t(field f (TypeRef System.Void))\n" +
+                               "\t\n" +
+                               "\t(region foo...\n" +
+                               "\t\t(method M)))\n" +
+                               "(type Bar\n" + 
+                               "\t\n" +
+                               "\t(field f (TypeRef System.Void))\n" +
+                               "\t\n" +
+                               "\t(region foo...\n" +
+                               "\t\t(method M)))\n";
+
+                       Assert.AreEqual (expected, o.ToString ());
+               }
+
                private CodeTypeDeclaration GetClassType ()
                {
                        return new CodeTypeDeclaration ();
@@ -132,6 +183,9 @@ namespace CodeGeneratorTest
 
                protected override void OutputType (CodeTypeReference typeRef)
                {
+                       Output.Write ("(TypeRef ");
+                       Output.Write (typeRef.BaseType);
+                       Output.Write (")");
                }
 
                protected override void GenerateArrayCreateExpression (CodeArrayCreateExpression e)
@@ -272,6 +326,12 @@ namespace CodeGeneratorTest
 
                protected override void GenerateField (CodeMemberField e)
                {
+                       Output.WriteLine ();
+                       Output.Write ("(field ");
+                       Output.Write (e.Name);
+                       Output.Write (" ");
+                       OutputType (e.Type);
+                       Output.Write (")");
                }
 
                protected override void GenerateSnippetMember (CodeSnippetTypeMember e)
@@ -284,6 +344,10 @@ namespace CodeGeneratorTest
 
                protected override void GenerateMethod (CodeMemberMethod e, CodeTypeDeclaration c)
                {
+                       Output.WriteLine ();
+                       Output.Write ("(method ");
+                       Output.Write (e.Name);
+                       Output.Write (")");
                }
 
                protected override void GenerateProperty (CodeMemberProperty e, CodeTypeDeclaration c)
@@ -300,10 +364,15 @@ namespace CodeGeneratorTest
 
                protected override void GenerateTypeStart (CodeTypeDeclaration e)
                {
+                       Output.Write ("(type ");
+                       Output.Write (e.Name);
+                       ++Indent;
                }
 
                protected override void GenerateTypeEnd (CodeTypeDeclaration e)
                {
+                       Output.WriteLine (")");
+                       --Indent;
                }
 
                protected override void GenerateNamespaceStart (CodeNamespace e)
@@ -356,6 +425,27 @@ namespace CodeGeneratorTest
                        return value;
                }
 
+#if NET_2_0
+               protected override void GenerateDirectives (CodeDirectiveCollection directives)
+               {
+                       foreach (CodeDirective d in directives) {
+                               var r = d as CodeRegionDirective;
+                               if (r != null) {
+                                       if (r.RegionMode == CodeRegionMode.Start) {
+                                               Output.WriteLine ();
+                                               Output.Write ("(region ");
+                                               Output.Write (r.RegionText);
+                                               ++Indent;
+                                       }
+                                       else if (r.RegionMode == CodeRegionMode.End) {
+                                               Output.Write (")");
+                                               --Indent;
+                                       }
+                               }
+                       }
+               }
+#endif
+
                #endregion Override implementation of CodeGenerator
        }
 }
index cfc942588e1f4489f02db6f80f8ce85361386a41..c9a5829a530d9895589c4c404050dfde73b9e970 100644 (file)
@@ -30,7 +30,7 @@ using System.Collections.Generic;
 
 using NUnit.Framework;
 
-namespace ParallelFxTests
+namespace MonoTests.System.Collections.Concurrent
 {
        [TestFixture()]
        public class BlockingCollectionTests
@@ -139,6 +139,13 @@ namespace ParallelFxTests
                        Assert.IsTrue(defaultCollection.IsCompleted, "#4");
                }
                
+               [TestAttribute]
+               public void IsCompletedEmptyTestCase ()
+               {
+                       defaultCollection.CompleteAdding ();
+                       Assert.IsTrue (defaultCollection.IsCompleted);
+               }
+
                [TestAttribute]
                public void ConsumingEnumerableTestCase()
                {
index 81387908bfe1ad0eccc266be9f261ed229db2c04..1c8ce37a42fad05394fa669b06e79ed1d8abe3c6 100644 (file)
@@ -1,3 +1,8 @@
+2010-04-23  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * BlockingCollectionTests.cs: Add IsCompletedEmptyTestCase,
+       fix namespace name
+
 2009-08-19 Jérémie Laval  <jeremie.laval@gmail.com>
 
        * BlockingCollectionTests.cs: track API changes
index 52a10f534d519e540a616569084ac79ef1033393..e40450494e02e99a4cff2a1583eaf6f2114a5b14 100644 (file)
@@ -1,9 +1,55 @@
+2010-04-09  Raja R Harinath  <harinath@hurrynot.org>
+
+       * SortedSetTest.cs (ViewCount): Test that count reflects changes
+       in underlying set.
+
+2010-04-07  Raja R Harinath  <harinath@hurrynot.org>
+
+       * SortedSetTest.cs: Update to test more view functionality,
+       including set comparison operators.
+
+2010-04-06  Jb Evain  <jbevain@novell.com>
+
+       * SortedSetTest.cs: add test for SortedSubSet.Count.
+
+2010-04-05  Raja R Harinath  <harinath@hurrynot.org>
+
+       * SortedSetTest.cs: Add test for various set comparison operators.
+
+2010-04-04  Raja R Harinath  <harinath@hurrynot.org>
+
+       * SortedSetTest.cs: Add tests for IntersectWith, UnionWith,
+       ExceptWith and SymmetricExceptWith.
+
+2010-04-02  Jb Evain  <jbevain@novell.com>
+
+       * SortedSetTest.cs: add tests for Min and Max on subsets.
+
+2010-04-02  Jb Evain  <jbevain@novell.com>
+
+       * SortedSetTest.cs: add tests for GetViewBetween.
+
+2010-04-02  Jb Evain  <jbevain@novell.com>
+
+       * SortedSetTest.cs: add tests for Min and Max.
+
+2010-04-02  Jb Evain  <jbevain@novell.com>
+
+       * SortedSetTest.cs: add test for RemoveWhere.
+
+2010-04-02  Jb Evain  <jbevain@novell.com>
+
+       * SortedSetTest.cs: add test for Reverse.
+
+2010-04-02  Jb Evain  <jbevain@novell.com>
+
+       * SortedSetTest.cs: add new fixture.
+
 2009-12-01  Jb Evain  <jbevain@novell.com>
 
        * StackTest.cs: add a test ensuring that disposing the stack
        enumerator prevents to iterate further.
 
-
 2009-11-25  Jb Evain  <jbevain@novell.com>
 
        * QueueTest.cs: add test for a specific combination of
diff --git a/mcs/class/System/Test/System.Collections.Generic/SortedSetTest.cs b/mcs/class/System/Test/System.Collections.Generic/SortedSetTest.cs
new file mode 100644 (file)
index 0000000..b6dcc92
--- /dev/null
@@ -0,0 +1,518 @@
+//
+// SortedSetTest.cs
+//
+// Author:
+//     Jb Evain <jbevain@novell.com>
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+#if NET_4_0
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+
+using NUnit.Framework;
+
+namespace MonoTests.System.Collections.Generic
+{
+       [TestFixture]
+       public class SortedSetTest
+       {
+               [Test]
+               public void CtorNullComparer ()
+               {
+                       var set = new SortedSet<int> ((IComparer<int>) null);
+                       Assert.AreEqual (Comparer<int>.Default, set.Comparer);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentNullException))]
+               public void CtorNullCollection ()
+               {
+                       new SortedSet<int> (null as IEnumerable<int>);
+               }
+
+               [Test]
+               public void CtorDefault ()
+               {
+                       var set = new SortedSet<int> ();
+                       Assert.IsNotNull (set.Comparer);
+               }
+
+               [Test]
+               public void Add ()
+               {
+                       var set = new SortedSet<int> ();
+                       Assert.AreEqual (0, set.Count);
+                       Assert.IsTrue (set.Add (2));
+                       Assert.IsTrue (set.Add (4));
+                       Assert.IsTrue (set.Add (3));
+                       Assert.AreEqual (3, set.Count);
+                       Assert.IsFalse (set.Add (2));
+               }
+
+               [Test]
+               public void Remove ()
+               {
+                       var set = new SortedSet<int> ();
+                       Assert.IsTrue (set.Add (2));
+                       Assert.IsTrue (set.Add (4));
+                       Assert.AreEqual (2, set.Count);
+                       Assert.IsTrue (set.Remove (4));
+                       Assert.IsTrue (set.Remove (2));
+                       Assert.AreEqual (0, set.Count);
+                       Assert.IsFalse (set.Remove (4));
+                       Assert.IsFalse (set.Remove (2));
+               }
+
+               [Test]
+               public void Clear ()
+               {
+                       var set = new SortedSet<int> { 2, 3, 4, 5 };
+                       Assert.AreEqual (4, set.Count);
+                       set.Clear ();
+                       Assert.AreEqual (0, set.Count);
+               }
+
+               [Test]
+               public void Contains ()
+               {
+                       var set = new SortedSet<int> { 2, 3, 4, 5 };
+                       Assert.IsTrue (set.Contains (4));
+                       Assert.IsFalse (set.Contains (7));
+               }
+
+               [Test]
+               public void GetEnumerator ()
+               {
+                       var set = new SortedSet<int> { 5, 3, 1, 2, 6, 4  };
+                       Assert.IsTrue (set.SequenceEqual (new [] { 1, 2, 3, 4, 5, 6 }));
+               }
+
+               [Test]
+               public void Reverse ()
+               {
+                       var set = new SortedSet<int> { 5, 3, 1, 2, 6, 4  };
+                       var reversed = set.Reverse ();
+                       Assert.IsTrue (reversed.SequenceEqual (new [] { 6, 5, 4, 3, 2, 1 }));
+               }
+
+               [Test]
+               public void RemoveWhere ()
+               {
+                       var set = new SortedSet<int> { 1, 2, 3, 4, 5, 6 };
+                       Assert.AreEqual (3, set.RemoveWhere (i => i % 2 == 0));
+                       Assert.AreEqual (3, set.Count);
+                       Assert.IsTrue (set.SequenceEqual (new [] { 1, 3, 5 }));
+
+               }
+
+               [Test]
+               public void Max ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 12, 9 };
+                       Assert.AreEqual (12, set.Max);
+               }
+
+               [Test]
+               public void Min ()
+               {
+                       var set = new SortedSet<int> { 2, 3, 1, 9 };
+                       Assert.AreEqual (1, set.Min);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentException))]
+               public void GetViewBetweenLowerBiggerThanUpper ()
+               {
+                       var set = new SortedSet<int> { 1, 2, 3, 4, 5, 6 };
+                       set.GetViewBetween (4, 2);
+               }
+
+               [Test]
+               public void GetView ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7, 9 };
+                       var view = set.GetViewBetween (3, 7);
+
+                       Assert.IsTrue (view.SequenceEqual (new [] { 3, 5, 7 }));
+               }
+
+               [Test]
+               public void ViewAdd ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7 };
+                       var view = set.GetViewBetween (3, 5);
+
+                       Assert.IsTrue (view.Add (4));
+                       Assert.IsTrue (view.Contains (4));
+                       Assert.IsTrue (set.Contains (4));
+
+                       Assert.IsFalse (view.Add (5));
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentOutOfRangeException))]
+               public void ViewAddOutOfRange ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7 };
+                       var view = set.GetViewBetween (3, 5);
+
+                       view.Add (7);
+               }
+
+               [Test]
+               public void ViewContains ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7, 9 };
+                       var view = set.GetViewBetween (3, 7);
+
+                       Assert.IsFalse (view.Contains (4));
+                       Assert.IsTrue (view.Contains (3));
+                       Assert.IsTrue (view.Contains (5));
+               }
+
+               [Test]
+               public void ViewRemove ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7, 9 };
+                       var view = set.GetViewBetween (3, 7);
+
+                       Assert.IsTrue (view.Remove (3));
+                       Assert.IsFalse (view.Contains (3));
+                       Assert.IsFalse (set.Contains (3));
+                       Assert.IsFalse (view.Remove (9));
+                       Assert.IsTrue (set.Contains (9));
+               }
+
+               [Test]
+               public void ViewClear ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7, 9 };
+                       var view = set.GetViewBetween (3, 7);
+
+                       view.Clear ();
+
+                       Assert.AreEqual (0, view.Count);
+                       Assert.IsTrue (set.SequenceEqual (new [] { 1, 9 }));
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentOutOfRangeException))]
+               public void ViewGetViewLowerOutOfRange ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7, 9 };
+                       var view = set.GetViewBetween (3, 7);
+                       view.GetViewBetween (2, 5);
+               }
+
+               [Test]
+               [ExpectedException (typeof (ArgumentOutOfRangeException))]
+               public void ViewGetViewUpperOutOfRange ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7, 9 };
+                       var view = set.GetViewBetween (3, 7);
+                       view.GetViewBetween (5, 9);
+               }
+
+               [Test]
+               public void ViewGetView ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7, 9 };
+                       var view = set.GetViewBetween (3, 7);
+                       view = view.GetViewBetween (4, 6);
+
+                       Assert.IsTrue (view.SequenceEqual (new [] { 5 }));
+               }
+
+               void EmptySubView (SortedSet<int> set)
+               {
+                       var view = set.GetViewBetween (-20, -15);
+                       Assert.AreEqual (0, view.Count);
+                       Assert.AreEqual (0, view.Min);
+                       Assert.AreEqual (0, view.Max);
+
+                       view = set.GetViewBetween (15, 20);
+                       Assert.AreEqual (0, view.Count);
+                       Assert.AreEqual (0, view.Min);
+                       Assert.AreEqual (0, view.Max);
+               }
+
+               [Test]
+               public void EmptySubView ()
+               {
+                       EmptySubView (new SortedSet<int> ());
+                       EmptySubView (new SortedSet<int> { 1, 3, 5, 7, 9 });
+                       EmptySubView (new SortedSet<int> { -40, 40 });
+                       EmptySubView (new SortedSet<int> { -40, -10, 10, 40 });
+               }
+
+               [Test]
+               public void ViewMin ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7, 9 };
+
+                       var view = set.GetViewBetween (4, 8);
+                       Assert.AreEqual (5, view.Min);
+
+                       view = set.GetViewBetween (-2, 4);
+                       Assert.AreEqual (1, view.Min);
+
+                       view = set.GetViewBetween (1, 9);
+                       Assert.AreEqual (1, view.Min);
+               }
+
+               [Test]
+               public void ViewMax ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7, 9 };
+
+                       var view = set.GetViewBetween (4, 8);
+                       Assert.AreEqual (7, view.Max);
+
+                       view = set.GetViewBetween (4, 55);
+                       Assert.AreEqual (9, view.Max);
+
+                       view = set.GetViewBetween (1, 9);
+                       Assert.AreEqual (9, view.Max);
+               }
+
+               [Test]
+               public void ViewCount ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 4, 5, 6, 7, 8, 9 };
+                       var view = set.GetViewBetween (4, 8);
+
+                       Assert.AreEqual (5, view.Count);
+                       set.Remove (5);
+                       Assert.AreEqual (4, view.Count);
+                       set.Add (10);
+                       Assert.AreEqual (4, view.Count);
+                       set.Add (6);
+                       Assert.AreEqual (4, view.Count);
+                       set.Add (5);
+                       Assert.AreEqual (5, view.Count);
+               }
+
+               [Test, ExpectedException (typeof (ArgumentNullException))]
+               public void IntersectWith_Null ()
+               {
+                       var set = new SortedSet<int> ();
+                       set.IntersectWith (null);
+               }
+
+               [Test]
+               public void IntersectWith ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7, 9 };
+                       set.IntersectWith (new [] { 5, 7, 3, 7, 11, 7, 5, 2 });
+                       Assert.IsTrue (set.SequenceEqual (new [] { 3, 5, 7 }));
+               }
+
+               [Test]
+               public void ViewIntersectWith ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7, 9 };
+                       var view = set.GetViewBetween (4, 8);
+                       view.IntersectWith (new [] { 1, 5, 9 });
+                       Assert.IsTrue (view.SequenceEqual (new [] { 5 }));
+                       Assert.IsTrue (set.SequenceEqual (new [] { 1, 3, 5, 9 }));
+                       view.IntersectWith (new [] { 1, 2 });
+                       Assert.IsTrue (view.SequenceEqual (new int [] {}));
+                       Assert.IsTrue (set.SequenceEqual (new [] { 1, 3, 9 }));
+               }
+
+               [Test, ExpectedException (typeof (ArgumentNullException))]
+               public void UnionWith_Null ()
+               {
+                       var set = new SortedSet<int> ();
+                       set.UnionWith (null);
+               }
+
+               [Test]
+               public void UnionWith ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7, 9 };
+                       set.UnionWith (new [] { 5, 7, 3, 7, 11, 7, 5, 2 });
+                       Assert.IsTrue (set.SequenceEqual (new [] { 1, 2, 3, 5, 7, 9, 11 }));
+               }
+
+               [Test]
+               public void ViewUnionWith ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7, 9 };
+                       var view = set.GetViewBetween (4, 8);
+                       view.UnionWith (new [] { 4, 5, 6, 6, 4 });
+                       Assert.IsTrue (view.SequenceEqual (new [] { 4, 5, 6, 7 }));
+                       Assert.IsTrue (set.SequenceEqual (new [] { 1, 3, 4, 5, 6, 7, 9 }));
+               }
+
+               [Test, ExpectedException (typeof (ArgumentOutOfRangeException))]
+               public void ViewUnionWith_oor ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7, 9 };
+                       var view = set.GetViewBetween (4, 8);
+                       view.UnionWith (new [] {1});
+               }
+
+               [Test, ExpectedException (typeof (ArgumentNullException))]
+               public void ExceptWith_Null ()
+               {
+                       var set = new SortedSet<int> ();
+                       set.ExceptWith (null);
+               }
+
+               [Test]
+               public void ExceptWith ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7, 9 };
+                       set.ExceptWith (new [] { 5, 7, 3, 7, 11, 7, 5, 2 });
+                       Assert.IsTrue (set.SequenceEqual (new [] { 1, 9 }));
+               }
+
+               [Test]
+               public void ViewExceptWith ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7, 9 };
+                       var view = set.GetViewBetween (4, 8);
+                       view.ExceptWith (new [] { 4, 5, 6, 6, 4 });
+                       Assert.IsTrue (view.SequenceEqual (new [] { 7 }));
+                       Assert.IsTrue (set.SequenceEqual (new [] { 1, 3, 7, 9 }));
+                       view.ExceptWith (new [] { 1, 2 });
+                       Assert.IsTrue (view.SequenceEqual (new [] { 7 }));
+                       Assert.IsTrue (set.SequenceEqual (new [] { 1, 3, 7, 9 }));
+               }
+
+               [Test, ExpectedException (typeof (ArgumentNullException))]
+               public void SymmetricExceptWith_Null ()
+               {
+                       var set = new SortedSet<int> ();
+                       set.SymmetricExceptWith (null);
+               }
+
+               [Test]
+               public void SymmetricExceptWith ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7, 9 };
+                       set.SymmetricExceptWith (new [] { 5, 7, 3, 7, 11, 7, 5, 2 });
+                       Assert.IsTrue (set.SequenceEqual (new [] { 1, 2, 9, 11 }));
+               }
+
+               [Test]
+               public void ViewSymmetricExceptWith ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7, 9 };
+                       var view = set.GetViewBetween (4, 8);
+                       view.SymmetricExceptWith (new [] { 4, 5, 6, 6, 4 });
+                       Assert.IsTrue (view.SequenceEqual (new [] { 4, 6, 7 }));
+                       Assert.IsTrue (set.SequenceEqual (new [] { 1, 3, 4, 6, 7, 9 }));
+               }
+
+               [Test, ExpectedException (typeof (ArgumentOutOfRangeException))]
+               public void ViewSymmetricExceptWith_oor ()
+               {
+                       var set = new SortedSet<int> { 1, 3, 5, 7, 9 };
+                       var view = set.GetViewBetween (4, 8);
+                       view.SymmetricExceptWith (new [] {2});
+               }
+
+               void do_test_e (SortedSet<int> s1, IEnumerable<int> s2, bool o, bool se = false, bool psb = false, bool psu = false)
+               {
+                       bool sb = false, su = false;
+                       if (se)
+                               sb = su = true;
+                       if (psb)
+                               sb = true;
+                       if (psu)
+                               su = true;
+
+                       Assert.IsTrue (!su || !psb);
+                       Assert.IsTrue (!sb || !psu);
+
+                       // actual tests
+                       Assert.AreEqual (o, s1.Overlaps (s2));
+                       Assert.AreEqual (se, s1.SetEquals (s2));
+                       Assert.AreEqual (sb, s1.IsSubsetOf (s2));
+                       Assert.AreEqual (su, s1.IsSupersetOf (s2));
+                       Assert.AreEqual (psb, s1.IsProperSubsetOf (s2));
+                       Assert.AreEqual (psu, s1.IsProperSupersetOf (s2));
+               }
+
+               void do_test (SortedSet<int> s1, SortedSet<int> s2, bool o = false, bool se = false, bool psb = false, bool psu = false)
+               {
+                       if (s1.Count != 0 && s2.Count != 0 && (se || psb || psu))
+                               o = true;
+                       do_test_e (s1, s2, o, se, psb, psu);
+                       do_test_e (s2, s1, o, se, psu, psb);
+               }
+
+               [Test]
+               public void TestSetCompares ()
+               {
+                       var empty = new SortedSet<int> ();
+                       var zero = new SortedSet<int> { 0 };
+                       var one = new SortedSet<int> { 1 };
+                       var two = new SortedSet<int> { 2 };
+                       var bit = new SortedSet<int> { 0, 1 };
+                       var trit = new SortedSet<int> { 0, 1, 2 };
+                       var odds = new SortedSet<int> { 1, 3, 5, 7, 9 };
+                       var evens = new SortedSet<int> { 2, 4, 6, 8 };
+                       var digits = new SortedSet<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
+                       var squares = new SortedSet<int> { 0, 1, 4, 9 };
+
+                       var non_prime_odd_digit = odds.GetViewBetween (8, 42);
+                       var non_trit = digits.GetViewBetween (3, 42);
+
+                       do_test (empty, empty, se: true);
+                       do_test (empty, zero, psb: true);
+                       do_test (empty, digits, psb: true);
+                       do_test (zero, zero, se: true);
+                       do_test (zero, one);
+                       do_test (zero, bit, psb: true);
+                       do_test (zero, trit, psb: true);
+                       do_test (one, bit, psb: true);
+                       do_test (one, trit, psb: true);
+                       do_test (two, bit);
+                       do_test (two, trit, psb: true);
+                       do_test (odds, squares, o: true);
+                       do_test (evens, squares, o: true);
+                       do_test (odds, digits, psb: true);
+                       do_test (evens, digits, psb: true);
+                       do_test (squares, digits, psb: true);
+                       do_test (digits, digits, se: true);
+                       do_test_e (digits, squares.Concat (evens.Concat (odds)), o: true, se: true);
+                       do_test (non_prime_odd_digit, digits, psb: true);
+                       do_test_e (non_prime_odd_digit, new [] { 9 }, o: true, se: true);
+                       do_test (non_trit, digits, psb: true);
+                       do_test (trit, non_trit);
+                       do_test_e (digits, trit.Concat (non_trit), o: true, se: true);
+                       do_test_e (non_trit, new [] { 3, 4, 5, 6, 7, 8, 9 }, o: true, se: true);
+                       do_test (digits.GetViewBetween (0, 2), trit, se: true);
+               }
+       }
+}
+
+#endif
diff --git a/mcs/class/System/Test/System.Runtime.Versioning/ChangeLog b/mcs/class/System/Test/System.Runtime.Versioning/ChangeLog
new file mode 100644 (file)
index 0000000..5b091b6
--- /dev/null
@@ -0,0 +1,3 @@
+2010-04-06  Jb Evain  <jbevain@novell.com>
+
+       * FrameworkNameTest.cs: moved here from corlib where it was pre-RC.
diff --git a/mcs/class/System/Test/System.Runtime.Versioning/FrameworkNameTest.cs b/mcs/class/System/Test/System.Runtime.Versioning/FrameworkNameTest.cs
new file mode 100644 (file)
index 0000000..df2a5b1
--- /dev/null
@@ -0,0 +1,389 @@
+//
+// System.Runtime.Versioning.FrameworkNameTest class
+//
+// Authors
+//     Marek Habersack <mhabersack@novell.com>
+//
+// Copyright (C) 2009 Novell, Inc (http://novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+using System;
+using System.Runtime.Versioning;
+using System.Text;
+
+using NUnit.Framework;
+
+#if NET_4_0
+namespace MonoTests.System.Runtime.Versioning
+{
+       [TestFixture]
+       public class FrameworkNameTest
+       {
+               void Throws<TEx> (string message, Action code)
+               {
+                       bool failed = false;
+                       Exception exception = null;
+                       try {
+                               code ();
+                               failed = true;
+                       } catch (Exception ex) {
+                               if (ex.GetType () != typeof (TEx)) {
+                                       failed = true;
+                                       exception = ex;
+                               }
+                       }
+
+                       if (failed) {
+                               if (exception != null)
+                                       Assert.Fail ("{0}{1}Expected exception {2}, got {3}",
+                                                       message, Environment.NewLine, typeof (TEx), exception.GetType ());
+                               else
+                                       Assert.Fail ("{0}{1}Expected exception {2}",
+                                               message, Environment.NewLine, typeof (TEx));
+                       }
+               }
+               
+               [Test]
+               public void Constructor_String ()
+               {
+                       FrameworkName fn;
+
+                       Throws <ArgumentNullException> ("#A1", () => {
+                                       fn = new FrameworkName (null);
+                               });
+
+                       Throws<ArgumentException> ("#A1-1", () => {
+                                       fn = new FrameworkName (String.Empty);
+                               });
+
+                       Throws <ArgumentException> ("#A1-2", () => {
+                                       fn = new FrameworkName (".NETFramework");
+                               });
+
+                       Throws <ArgumentException> ("#A1-3", () => {
+                                       fn = new FrameworkName (".NETFramework,Ver=test");
+                               });
+
+                       Throws <ArgumentException> ("#A1-4", () => {
+                                       fn = new FrameworkName (".NETFramework,Version=A");
+                               });
+
+                       Throws <ArgumentException> ("#A1-5", () => {
+                                       fn = new FrameworkName ("Version=1.2,.NETFramework");
+                               });
+
+                       Throws <ArgumentException> ("#A1-6", () => {
+                                       fn = new FrameworkName (".NETFramework,Version=vA");
+                               });
+
+                       Throws <ArgumentException> ("#A1-7", () => {
+                                       fn = new FrameworkName (".NETFramework,Version=A.B");
+                               });
+
+                       Throws <ArgumentException> ("#A1-8", () => {
+                                       fn = new FrameworkName (".NETFramework,Version=vA.B");
+                               });
+
+                       Throws <ArgumentException> ("#A1-9", () => {
+                                       fn = new FrameworkName (".NETFramework,Version=VA.B");
+                               });
+
+                       Throws <ArgumentException> ("#A1-10", () => {
+                                       fn = new FrameworkName (".NETFramework,Version=vA.B.C");
+                               });
+
+                       Throws <ArgumentException> ("#A1-11", () => {
+                                       fn = new FrameworkName (".NETFramework,Version=vA.B.C.D");
+                               });
+
+                       Throws <ArgumentException> ("#A1-12", () => {
+                                       fn = new FrameworkName (".NETFramework,Version=2");
+                               });
+
+                       Throws <ArgumentException> ("#A1-13", () => {
+                                       fn = new FrameworkName (".NETFramework,Version=v2");
+                               });
+
+                       Throws <ArgumentException> ("#A1-14", () => {
+                                       fn = new FrameworkName (".NETFramework,Version=v2.0.1.A");
+                               });
+
+                       Throws <ArgumentException> ("#A1-15", () => {
+                                       fn = new FrameworkName (".NETFramework,Version=v2.0.1.0,Some=value");
+                               });
+
+                       Throws <ArgumentException> ("#A1-16", () => {
+                                       fn = new FrameworkName (".NETFramework,Version=v2.0.1.0,Profile=profile name, Extra=value");
+                               });
+
+                       Throws <ArgumentException> ("#A1-17", () => {
+                                       fn = new FrameworkName (".NETFramework,Profile=profile name");
+                               });
+
+                       Throws <ArgumentException> ("#A1-18", () => {
+                                       fn = new FrameworkName ("Profile=profile name,.NETFramework,Version=v2.0.1.0");
+                               });
+
+                       Throws <ArgumentException> ("#A1-19", () => {
+                                       var n = new FrameworkName (".NETFramework, ,Version=v2.0.1.0");
+                               });
+
+                       Throws <ArgumentException> ("#A1-20", () => {
+                                       fn = new FrameworkName (".NETFramework,Version=v2..0.1.0");
+                               });
+
+                       Throws <ArgumentException> ("#A1-21", () => {
+                                       fn = new FrameworkName (".NETFramework,Version=v.0.1.0");
+                               });
+
+                       Throws <ArgumentException> ("#A1-22", () => {
+                                       fn = new FrameworkName (".NETFramework,Version=v1.-2.1.0");
+                               });
+
+                       Throws <ArgumentException> ("#A1-23", () => {
+                                       fn = new FrameworkName (".NETFramework,Version=v0.0.0.0.0");
+                               });
+
+                       Throws <ArgumentException> ("#A1-24", () => {
+                                       fn = new FrameworkName (".NETFramework,Version=vA.0.0.0,Version=v1.2.3.4");
+                               });
+
+                       Throws <ArgumentException> ("#A1-25", () => {
+                                       fn = new FrameworkName (".NETFramework,Version=v0.0.0.0,Version=vA.2.3.4");
+                               });
+
+                       Throws <ArgumentException> ("#A1-26", () => {
+                                       fn = new FrameworkName ("Version=1.2,profile=test profile");
+                               });
+
+                       Throws<ArgumentException> ("#A1-27", () => {
+                                       fn = new FrameworkName (".NETFramework,Version=");
+                               });
+
+                       fn = new FrameworkName (".NETFramework=test,Version=3.5");
+                       Assert.AreEqual (".NETFramework=test", fn.Identifier, "#A2-1");
+                       Assert.IsTrue (fn.Version == new Version (3, 5), "#A2-2");
+                       Assert.AreEqual (String.Empty, fn.Profile, "#A2-3");
+                       Assert.AreEqual (".NETFramework=test,Version=v3.5", fn.FullName, "#A3-4");
+                       
+                       fn = new FrameworkName (".NETFramework,Version=2.0");
+                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A3-1");
+                       Assert.IsTrue (fn.Version == new Version (2, 0), "#A3-2");
+                       Assert.AreEqual (String.Empty, fn.Profile, "#A3-3");
+                       Assert.AreEqual (".NETFramework,Version=v2.0", fn.FullName, "#A3-4");
+
+                       fn = new FrameworkName (".NETFramework,Version=v2.0");
+                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A4-1");
+                       Assert.IsTrue (fn.Version == new Version (2, 0), "#A4-2");
+                       Assert.AreEqual (String.Empty, fn.Profile, "#A4-3");
+                       Assert.AreEqual (".NETFramework,Version=v2.0", fn.FullName, "#A4-4");
+
+                       fn = new FrameworkName (".NETFramework,Version=v0.1");
+                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A5-1");
+                       Assert.IsTrue (fn.Version == new Version (0, 1), "#A5-2");
+                       Assert.AreEqual (String.Empty, fn.Profile, "#A5-3");
+                       Assert.AreEqual (".NETFramework,Version=v0.1", fn.FullName, "#A5-4");
+
+                       fn = new FrameworkName (".NETFramework,Version=v10.1");
+                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A6-1");
+                       Assert.IsTrue (fn.Version == new Version (10, 1), "#A6-2");
+                       Assert.AreEqual (String.Empty, fn.Profile, "#A6-3");
+                       Assert.AreEqual (".NETFramework,Version=v10.1", fn.FullName, "#A6-4");
+
+                       fn = new FrameworkName (".NETFramework,Version=V2.0");
+                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A7-1");
+                       Assert.IsTrue (fn.Version == new Version (2, 0), "#A7-2");
+                       Assert.AreEqual (String.Empty, fn.Profile, "#A7-3");
+                       Assert.AreEqual (".NETFramework,Version=v2.0", fn.FullName, "#A7-4");
+
+                       fn = new FrameworkName (".NETFramework,Version=v2.0.1");
+                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A8-1");
+                       Assert.IsTrue (fn.Version == new Version (2, 0, 1), "#A8-2");
+                       Assert.AreEqual (String.Empty, fn.Profile, "#A8-3");
+                       Assert.AreEqual (".NETFramework,Version=v2.0.1", fn.FullName, "#A8-4");
+
+                       fn = new FrameworkName (".NETFramework,Version=v2.0.1.0");
+                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A9-1");
+                       Assert.IsTrue (fn.Version == new Version (2, 0, 1, 0), "#A9-2");
+                       Assert.AreEqual (String.Empty, fn.Profile, "#A9-3");
+                       Assert.AreEqual (".NETFramework,Version=v2.0.1.0", fn.FullName, "#A9-4");
+
+                       fn = new FrameworkName (".NETFramework,Version=v2.0.1.0,Profile=profile name");
+                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A10-1");
+                       Assert.IsTrue (fn.Version == new Version (2, 0, 1, 0), "#A10-2");
+                       Assert.AreEqual ("profile name", fn.Profile, "#A10-3");
+                       Assert.AreEqual (".NETFramework,Version=v2.0.1.0,Profile=profile name", fn.FullName, "#A10-4");
+
+                       fn = new FrameworkName (".NETFramework,Version=v2. 0.1.0");
+                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A11-1");
+                       Assert.IsTrue (fn.Version == new Version (2, 0, 1, 0), "#A11-2");
+                       Assert.AreEqual (String.Empty, fn.Profile, "#A11-3");
+                       Assert.AreEqual (".NETFramework,Version=v2.0.1.0", fn.FullName, "#A11-4");
+
+                       fn = new FrameworkName (".NETFramework,Version=v0.0.0.0");
+                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A12-1");
+                       Assert.IsTrue (fn.Version == new Version (0, 0, 0, 0), "#A12-2");
+                       Assert.AreEqual (String.Empty, fn.Profile, "#A12-3");
+                       Assert.AreEqual (".NETFramework,Version=v0.0.0.0", fn.FullName, "#A12-4");
+
+                       fn = new FrameworkName (".NETFramework,Version=v0.0.0.0,Version=v1.2.3.4");
+                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A13-1");
+                       Assert.IsTrue (fn.Version == new Version (1, 2, 3, 4), "#A13-2");
+                       Assert.AreEqual (String.Empty, fn.Profile, "#A13-3");
+                       Assert.AreEqual (".NETFramework,Version=v1.2.3.4", fn.FullName, "#A13-4");
+
+                       fn = new FrameworkName ("identifier,verSION=1.2,PRofiLE=test profile");
+                       Assert.AreEqual ("identifier", fn.Identifier, "#A14-1");
+                       Assert.IsTrue (fn.Version == new Version (1, 2), "#A14-2");
+                       Assert.AreEqual ("test profile", fn.Profile, "#A14-3");
+                       Assert.AreEqual ("identifier,Version=v1.2,Profile=test profile", fn.FullName, "#A14-4");
+
+                       fn = new FrameworkName ("identifier,Version=2.0,Profile=");
+                       Assert.AreEqual ("identifier", fn.Identifier, "#A15-1");
+                       Assert.IsTrue (fn.Version == new Version (2, 0), "#A15-2");
+                       Assert.AreEqual (String.Empty, fn.Profile, "#A15-3");
+                       Assert.AreEqual ("identifier,Version=v2.0", fn.FullName, "#A15-4");
+               }
+
+               [Test]
+               public void Constructor_String_Version ()
+               {
+                       FrameworkName fn;
+
+                       Throws <ArgumentNullException> ("#A1-1", () => {
+                                       fn = new FrameworkName (null, new Version (2, 0));
+                               });
+
+                       Throws <ArgumentNullException> ("#A1-2", () => {
+                                       fn = new FrameworkName ("identifier", null);
+                               });
+
+                       Throws <ArgumentException> ("#A1-3", () => {
+                                       fn = new FrameworkName (String.Empty, new Version (2, 0));
+                               });
+
+                       var v = new Version (1,2,3,4);
+                       fn = new FrameworkName ("identifier", v);
+                       Assert.AreEqual ("identifier", fn.Identifier, "#A2-1");
+                       Assert.IsTrue (fn.Version == v, "#A2-2");
+                       Assert.AreEqual (String.Empty, fn.Profile, "#A2-3");
+                       Assert.AreEqual ("identifier,Version=v1.2.3.4", fn.FullName, "#A2-4");
+
+                       fn = new FrameworkName ("identifier,v2.0", v);
+                       Assert.AreEqual ("identifier,v2.0", fn.Identifier, "#A3-1");
+                       Assert.IsTrue (fn.Version == v, "#A3-2");
+                       Assert.AreEqual (String.Empty, fn.Profile, "#A3-3");
+                       Assert.AreEqual ("identifier,v2.0,Version=v1.2.3.4", fn.FullName, "#A3-4");
+
+                       fn = new FrameworkName ("identifier,Version=v2.0", v);
+                       Assert.AreEqual ("identifier,Version=v2.0", fn.Identifier, "#A4-1");
+                       Assert.IsTrue (fn.Version == v, "#A4-2");
+                       Assert.AreEqual (String.Empty, fn.Profile, "#A4-3");
+                       Assert.AreEqual ("identifier,Version=v2.0,Version=v1.2.3.4", fn.FullName, "#A4-4");
+               }
+
+               [Test]
+               public void Constructor_String_Version_String ()
+               {
+                       FrameworkName fn;
+                       var v = new Version (1, 2, 3, 4);
+
+                       Throws <ArgumentNullException> ("#A1-1", () => {
+                                       fn = new FrameworkName (null, new Version (2, 0), "profile");
+                               });
+
+                       Throws <ArgumentNullException> ("#A1-2", () => {
+                                       fn = new FrameworkName ("identifier", null, "profile");
+                               });
+
+                       Throws <ArgumentException> ("#A1-3", () => {
+                                       fn = new FrameworkName (String.Empty, new Version (2, 0), "profile");
+                               });
+
+                       fn = new FrameworkName ("identifier,Version=v2.0", v, "Profile name");
+                       Assert.AreEqual ("identifier,Version=v2.0", fn.Identifier, "#A2-1");
+                       Assert.IsTrue (fn.Version == v, "#A2-2");
+                       Assert.AreEqual ("Profile name", fn.Profile, "#A2-3");
+                       Assert.AreEqual ("identifier,Version=v2.0,Version=v1.2.3.4,Profile=Profile name", fn.FullName, "#A2-4");
+
+                       fn = new FrameworkName ("identifier,v2.0,profile=test", v, "Profile name");
+                       Assert.AreEqual ("identifier,v2.0,profile=test", fn.Identifier, "#A3-1");
+                       Assert.IsTrue (fn.Version == v, "#A3-2");
+                       Assert.AreEqual ("Profile name", fn.Profile, "#A3-3");
+                       Assert.AreEqual ("identifier,v2.0,profile=test,Version=v1.2.3.4,Profile=Profile name", fn.FullName, "#A3-4");
+
+                       fn = new FrameworkName ("identifier,v2.0,profile=test", v, null);
+                       Assert.AreEqual ("identifier,v2.0,profile=test", fn.Identifier, "#A4-1");
+                       Assert.IsTrue (fn.Version == v, "#A4-2");
+                       Assert.AreEqual (String.Empty, fn.Profile, "#A4-3");
+                       Assert.AreEqual ("identifier,v2.0,profile=test,Version=v1.2.3.4", fn.FullName, "#A4-4");
+
+                       fn = new FrameworkName ("identifier,v2.0,profile=test", v, String.Empty);
+                       Assert.AreEqual ("identifier,v2.0,profile=test", fn.Identifier, "#A5-1");
+                       Assert.IsTrue (fn.Version == v, "#A5-2");
+                       Assert.AreEqual (String.Empty, fn.Profile, "#A5-3");
+                       Assert.AreEqual ("identifier,v2.0,profile=test,Version=v1.2.3.4", fn.FullName, "#A5-4");
+               }
+
+               [Test]
+               public void EqualityOperator ()
+               {
+                       var fn = new FrameworkName ("identifier,Version=v2.0");
+
+                       Assert.IsTrue (fn == new FrameworkName ("identifier,Version=v2.0"), "#A1");
+
+                       FrameworkName fn1 = null;
+                       FrameworkName fn2 = null;
+
+                       Assert.IsTrue (fn1 == fn2, "#A2");
+                       Assert.IsFalse (fn == new FrameworkName ("identifier,Version=v2.1"), "#A3");
+                       Assert.IsFalse (fn == null, "#A4");
+               }
+
+               [Test]
+               public void InequalityOperator ()
+               {
+                       var fn = new FrameworkName ("identifier,Version=v2.0");
+
+                       Assert.IsFalse (fn != new FrameworkName ("identifier,Version=v2.0"), "#A1");
+
+                       FrameworkName fn1 = null;
+                       FrameworkName fn2 = null;
+
+                       Assert.IsFalse (fn1 != fn2, "#A2");
+                       Assert.IsTrue (fn != new FrameworkName ("identifier,Version=v2.1"), "#A3");
+                       Assert.IsTrue (fn != null, "#A4");
+               }
+
+               [Test]
+               public void ToStringTest ()
+               {
+                       var fn = new FrameworkName (".NETFramework,Version=v2.0.1");
+                       Assert.AreEqual (".NETFramework,Version=v2.0.1", fn.FullName, "#A1-1");
+                       Assert.AreEqual (fn.FullName, fn.ToString (), "#A1-2");
+
+                       fn = new FrameworkName (".NETFramework,Version=v2.0.1.0");
+                       Assert.AreEqual (".NETFramework,Version=v2.0.1.0", fn.FullName, "#A2-1");
+                       Assert.AreEqual (fn.FullName, fn.ToString (), "#A2-2");
+               }
+       }
+}
+#endif
index 4728ac5b7b1cb4c4027bea43393e1dfaf5497d12..daae27e1f2b1e1f0582475f2fab9172a54f0db24 100644 (file)
@@ -1,3 +1,8 @@
+2010-04-17  Raja R Harinath  <harinath@hurrynot.org>
+
+       * UriTest.cs (FtpRootPath): New.  Check that ftp root paths are
+       unmolested.
+
 2010-01-27  Carlos Alberto Cortez <calberto.cortez@gmail.com>
 
        * UriTest.cs: added an assertion in the IsWellFormedOriginalString
index 2c5de023b61609bbd5e2c5517416fdfb51830cd2..5f3eb5147d64258670694068efdd2b5fbf0a76dd 100644 (file)
@@ -1714,6 +1714,18 @@ namespace MonoTests.System
                        Console.WriteLine ("");
                }
 
+               [Test]
+               public void FtpRootPath ()
+               {
+                       Uri u = new Uri ("ftp://a.b/%2fabc/def");
+                       string p = u.PathAndQuery;
+                       Assert.AreEqual ("/%2fabc/def", p);
+                       p = Uri.UnescapeDataString (p).Substring (1);
+                       Assert.AreEqual ("/abc/def", p);
+                       u = new Uri (new Uri ("ftp://a.b/c/d/e/f"), p);
+                       Assert.AreEqual ("/abc/def", u.PathAndQuery);
+               }
+
 //BNC#533572
 #if NET_2_0
                [Test]
index 98d578110cce760a909b0beb64132b2c2e82d72b..49798247a7d67fa633b75687cabc1fee60ab90d9 100644 (file)
@@ -1,17 +1,31 @@
-#include net_2_1_raw_System.dll.sources
 ../../build/common/Consts.cs
 ../../build/common/Locale.cs
 ../../build/common/MonoTODOAttribute.cs
-
+../corlib/System.Collections.Generic/CollectionDebuggerView.cs
+../corlib/System.Collections/CollectionDebuggerView.cs
+Assembly/AssemblyInfo.cs
 Mono.Http/NtlmClient.cs
-
 MonoTouch/MonoPInvokeCallbackAttribute.cs
-
+System.CodeDom.Compiler/GeneratedCodeAttribute.cs
+System.Collections.Generic/ISet.cs
+System.Collections.Generic/LinkedList.cs
+System.Collections.Generic/LinkedListNode.cs
+System.Collections.Generic/Queue.cs
+System.Collections.Generic/RBTree.cs
+System.Collections.Generic/SortedDictionary.cs
+System.Collections.Generic/SortedList.cs
+System.Collections.Generic/Stack.cs
+System.Collections.Specialized/BitVector32.cs
+System.Collections.Specialized/CollectionsUtil.cs
+System.Collections.Specialized/HybridDictionary.cs
+System.Collections.Specialized/ListDictionary.cs
 System.Collections.Specialized/NameObjectCollectionBase.cs
 System.Collections.Specialized/NameValueCollection.cs
 System.Collections.Specialized/ProcessStringDictionary.cs
 System.Collections.Specialized/StringCollection.cs
+System.Collections.Specialized/StringDictionary.cs
 System.Collections.Specialized/StringEnumerator.cs
+System.ComponentModel.Design.Serialization/InstanceDescriptor.cs
 System.ComponentModel.Design/CommandID.cs
 System.ComponentModel.Design/ComponentChangedEventArgs.cs
 System.ComponentModel.Design/ComponentChangedEventHandler.cs
@@ -32,26 +46,33 @@ System.ComponentModel.Design/IDesignerHost.cs
 System.ComponentModel.Design/IReferenceService.cs
 System.ComponentModel.Design/IRootDesigner.cs
 System.ComponentModel.Design/IServiceContainer.cs
-System.ComponentModel.Design/ITypeResolutionService.cs
 System.ComponentModel.Design/ITypeDescriptorFilterService.cs
+System.ComponentModel.Design/ITypeResolutionService.cs
 System.ComponentModel.Design/MenuCommand.cs
 System.ComponentModel.Design/ServiceCreatorCallback.cs
 System.ComponentModel.Design/StandardCommands.cs
 System.ComponentModel.Design/ViewTechnology.cs
-System.ComponentModel.Design.Serialization/InstanceDescriptor.cs
 System.ComponentModel/ArrayConverter.cs
+System.ComponentModel/AsyncCompletedEventArgs.cs
+System.ComponentModel/AsyncCompletedEventHandler.cs
+System.ComponentModel/AsyncOperation.cs
+System.ComponentModel/AsyncOperationManager.cs
 System.ComponentModel/AttributeCollection.cs
+System.ComponentModel/BackgroundWorker.cs
 System.ComponentModel/BaseNumberConverter.cs
 System.ComponentModel/BindableSupport.cs
 System.ComponentModel/BooleanConverter.cs
 System.ComponentModel/BrowsableAttribute.cs
 System.ComponentModel/ByteConverter.cs
+System.ComponentModel/CancelEventArgs.cs
+System.ComponentModel/CategoryAttribute.cs
 System.ComponentModel/CharConverter.cs
 System.ComponentModel/CollectionChangeAction.cs
 System.ComponentModel/CollectionChangeEventArgs.cs
 System.ComponentModel/CollectionChangeEventHandler.cs
 System.ComponentModel/CollectionConverter.cs
 System.ComponentModel/Component.cs
+System.ComponentModel/ComponentCollection.cs
 System.ComponentModel/ComponentConverter.cs
 System.ComponentModel/CultureInfoConverter.cs
 System.ComponentModel/CustomTypeDescriptor.cs
@@ -59,15 +80,21 @@ System.ComponentModel/DateTimeConverter.cs
 System.ComponentModel/DecimalConverter.cs
 System.ComponentModel/DefaultEventAttribute.cs
 System.ComponentModel/DefaultPropertyAttribute.cs
+System.ComponentModel/DefaultValueAttribute.cs
+System.ComponentModel/DescriptionAttribute.cs
+System.ComponentModel/DesignOnlyAttribute.cs
+System.ComponentModel/DesignTimeVisibleAttribute.cs
 System.ComponentModel/DesignerAttribute.cs
 System.ComponentModel/DesignerCategoryAttribute.cs
 System.ComponentModel/DesignerSerializationVisibility.cs
 System.ComponentModel/DesignerSerializationVisibilityAttribute.cs
-System.ComponentModel/DesignOnlyAttribute.cs
-System.ComponentModel/DesignTimeVisibleAttribute.cs
 System.ComponentModel/DisplayNameAttribute.cs
+System.ComponentModel/DoWorkEventArgs.cs
+System.ComponentModel/DoWorkEventHandler.cs
 System.ComponentModel/DoubleConverter.cs
 System.ComponentModel/EditorAttribute.cs
+System.ComponentModel/EditorBrowsableAttribute.cs
+System.ComponentModel/EditorBrowsableState.cs
 System.ComponentModel/EnumConverter.cs
 System.ComponentModel/EventDescriptor.cs
 System.ComponentModel/EventDescriptorCollection.cs
@@ -76,19 +103,29 @@ System.ComponentModel/ExpandableObjectConverter.cs
 System.ComponentModel/GuidConverter.cs
 System.ComponentModel/IBindingList.cs
 System.ComponentModel/IBindingListView.cs
+System.ComponentModel/IChangeTracking.cs
 System.ComponentModel/IComNativeDescriptorHandler.cs
 System.ComponentModel/IComponent.cs
+System.ComponentModel/IComponent.cs
+System.ComponentModel/IContainer.cs
 System.ComponentModel/ICustomTypeDescriptor.cs
 System.ComponentModel/IDataErrorInfo.cs
+System.ComponentModel/IDataErrorInfo.cs
+System.ComponentModel/IEditableObject.cs
 System.ComponentModel/IListSource.cs
-System.ComponentModel/Int16Converter.cs
-System.ComponentModel/Int32Converter.cs
-System.ComponentModel/Int64Converter.cs
-System.ComponentModel/InvalidEnumArgumentException.cs
+System.ComponentModel/INotifyPropertyChanged.cs
+System.ComponentModel/IRevertibleChangeTracking.cs
+System.ComponentModel/ISite.cs
 System.ComponentModel/ISupportInitialize.cs
 System.ComponentModel/ISupportInitializeNotification.cs
 System.ComponentModel/ISynchronizeInvoke.cs
+System.ComponentModel/ITypeDescriptorContext.cs
 System.ComponentModel/ITypedList.cs
+System.ComponentModel/Int16Converter.cs
+System.ComponentModel/Int32Converter.cs
+System.ComponentModel/Int64Converter.cs
+System.ComponentModel/InvalidEnumArgumentException.cs
+System.ComponentModel/InvalidEnumArgumentException.cs
 System.ComponentModel/ListBindableAttribute.cs
 System.ComponentModel/ListChangedEventArgs.cs
 System.ComponentModel/ListChangedEventHandler.cs
@@ -96,6 +133,7 @@ System.ComponentModel/ListChangedType.cs
 System.ComponentModel/ListSortDescription.cs
 System.ComponentModel/ListSortDescriptionCollection.cs
 System.ComponentModel/ListSortDirection.cs
+System.ComponentModel/ListSortDirection.cs
 System.ComponentModel/LocalizableAttribute.cs
 System.ComponentModel/MarshalByValueComponent.cs
 System.ComponentModel/MemberDescriptor.cs
@@ -104,9 +142,15 @@ System.ComponentModel/MultilineStringConverter.cs
 System.ComponentModel/NotifyParentPropertyAttribute.cs
 System.ComponentModel/NullableConverter.cs
 System.ComponentModel/PasswordPropertyTextAttribute.cs
+System.ComponentModel/ProgressChangedEventArgs.cs
+System.ComponentModel/ProgressChangedEventHandler.cs
+System.ComponentModel/PropertyChangedEventArgs.cs
+System.ComponentModel/PropertyChangedEventHandler.cs
+System.ComponentModel/PropertyDescriptor.cs
 System.ComponentModel/PropertyDescriptor.cs
 System.ComponentModel/PropertyDescriptorCollection.cs
 System.ComponentModel/ReadOnlyAttribute.cs
+System.ComponentModel/ReadOnlyAttribute.cs
 System.ComponentModel/RecommendedAsConfigurableAttribute.cs
 System.ComponentModel/ReferenceConverter.cs
 System.ComponentModel/ReferenceConverter.cs
@@ -116,6 +160,8 @@ System.ComponentModel/RefreshEventArgs.cs
 System.ComponentModel/RefreshEventHandler.cs
 System.ComponentModel/RefreshProperties.cs
 System.ComponentModel/RefreshPropertiesAttribute.cs
+System.ComponentModel/RunWorkerCompletedEventArgs.cs
+System.ComponentModel/RunWorkerCompletedEventHandler.cs
 System.ComponentModel/SByteConverter.cs
 System.ComponentModel/SingleConverter.cs
 System.ComponentModel/StringConverter.cs
@@ -124,6 +170,8 @@ System.ComponentModel/ToolboxItemAttribute.cs
 System.ComponentModel/ToolboxItemFilterAttribute.cs
 System.ComponentModel/ToolboxItemFilterType.cs
 System.ComponentModel/TypeConverter.cs
+System.ComponentModel/TypeConverterAttribute.cs
+System.ComponentModel/TypeConverter_2_1.cs
 System.ComponentModel/TypeDescriptionProvider.cs
 System.ComponentModel/TypeDescriptor.cs
 System.ComponentModel/TypeListConverter.cs
@@ -135,6 +183,7 @@ System.ComponentModel/WeakObjectWrapperComparer.cs
 System.ComponentModel/Win32Exception.cs
 System.Diagnostics/DataReceivedEventArgs.cs
 System.Diagnostics/DataReceivedEventHandler.cs
+System.Diagnostics/Debug_2_1.cs
 System.Diagnostics/FileVersionInfo.cs
 System.Diagnostics/MonitoringDescriptionAttribute.cs
 System.Diagnostics/Process.cs
@@ -149,95 +198,27 @@ System.Diagnostics/Stopwatch.cs
 System.Diagnostics/ThreadPriorityLevel.cs
 System.Diagnostics/ThreadState.cs
 System.Diagnostics/ThreadWaitReason.cs
-System.IO/MonoSyncFileStream.cs
-System.IO/MonoIO.cs
-System.IO/MonoIOError.cs
-
 System.IO.Compression/CompressionMode.cs
 System.IO.Compression/DeflateStream.cs
 System.IO.Compression/GZipStream.cs
-
-System.Net/AuthenticationManager.cs
-System.Net/AuthenticationSchemes.cs
-System.Net/AuthenticationSchemeSelector.cs
-System.Net/Authorization.cs
-System.Net/BasicClient.cs
-System.Net/BindIPEndPoint.cs
+System.IO/MonoIO.cs
+System.IO/MonoIOError.cs
+System.IO/MonoSyncFileStream.cs
 System.Net.Cache/HttpCacheAgeControl.cs
 System.Net.Cache/HttpRequestCacheLevel.cs
 System.Net.Cache/HttpRequestCachePolicy.cs
 System.Net.Cache/RequestCacheLevel.cs
 System.Net.Cache/RequestCachePolicy.cs
-System.Net/ChunkedInputStream.cs
-System.Net/ChunkStream.cs
-System.Net/ConnectionModes.cs
-System.Net/CookieCollection.cs
-System.Net/CookieContainer.cs
-System.Net/Cookie.cs
-System.Net/CookieException.cs
-System.Net/CredentialCache.cs
-System.Net/DecompressionMethods.cs
-System.Net/DefaultCertificatePolicy.cs
-System.Net/DigestClient.cs
-System.Net/Dns.cs
-
-System.Net/EndPoint.cs
-System.Net/EndPointListener.cs
-System.Net/EndPointManager.cs
-
-System.Net/FileWebRequestCreator.cs
-System.Net/FileWebRequest.cs
-System.Net/FileWebResponse.cs
-System.Net/FtpAsyncResult.cs
-System.Net/FtpDataStream.cs
-System.Net/FtpRequestCreator.cs
-System.Net/FtpStatusCode.cs
-System.Net/FtpWebRequest.cs
-System.Net/FtpStatus.cs
-System.Net/FtpWebResponse.cs
-System.Net/GlobalProxySelection.cs
-System.Net/HttpConnection.cs
-System.Net/HttpContinueDelegate.cs
-System.Net/HttpListenerBasicIdentity.cs
-System.Net/HttpListenerContext.cs
-System.Net/HttpListener.cs
-System.Net/HttpListenerException.cs
-System.Net/HttpListenerPrefixCollection.cs
-System.Net/HttpListenerRequest.cs
-System.Net/HttpListenerResponse.cs
-System.Net/HttpRequestCreator.cs
-System.Net/HttpRequestHeader.cs
-System.Net/HttpResponseHeader.cs
-System.Net/HttpStatusCode.cs
-System.Net/HttpStreamAsyncResult.cs
-System.Net/HttpUtility.cs
-System.Net/HttpVersion.cs
-System.Net/HttpWebRequest.cs
-System.Net/HttpWebResponse.cs
-System.Net/IAuthenticationModule.cs
-System.Net/ICertificatePolicy.cs
-System.Net/ICredentialLookup.cs
-System.Net/ICredentialPolicy.cs
-System.Net/ICredentialsByHost.cs
-System.Net/IPAddress.cs
-System.Net/IPEndPoint.cs
-System.Net/IPHostEntry.cs
-System.Net/IPv6Address.cs
-System.Net/IWebProxy.cs
-System.Net/IWebProxyScript.cs
-System.Net/IWebRequestCreate.cs
-System.Net/ListenerAsyncResult.cs
-System.Net/ListenerPrefix.cs
-System.Net.Mail/AlternateViewCollection.cs
 System.Net.Mail/AlternateView.cs
+System.Net.Mail/AlternateViewCollection.cs
+System.Net.Mail/Attachment.cs
 System.Net.Mail/AttachmentBase.cs
 System.Net.Mail/AttachmentCollection.cs
-System.Net.Mail/Attachment.cs
 System.Net.Mail/DeliveryNotificationOptions.cs
-System.Net.Mail/LinkedResourceCollection.cs
 System.Net.Mail/LinkedResource.cs
-System.Net.Mail/MailAddressCollection.cs
+System.Net.Mail/LinkedResourceCollection.cs
 System.Net.Mail/MailAddress.cs
+System.Net.Mail/MailAddressCollection.cs
 System.Net.Mail/MailMessage.cs
 System.Net.Mail/MailPriority.cs
 System.Net.Mail/SendCompletedEventHandler.cs
@@ -247,25 +228,18 @@ System.Net.Mail/SmtpDeliveryMethod.cs
 System.Net.Mail/SmtpException.cs
 System.Net.Mail/SmtpFailedRecipientException.cs
 System.Net.Mail/SmtpFailedRecipientsException.cs
-
 System.Net.Mail/SmtpStatusCode.cs
 System.Net.Mime/ContentDisposition.cs
 System.Net.Mime/ContentType.cs
 System.Net.Mime/DispositionTypeNames.cs
 System.Net.Mime/MediaTypeNames.cs
 System.Net.Mime/TransferEncoding.cs
-System.Net/MonoHttpDate.cs
-System.Net/NetConfig.cs
-System.Net/NetworkAccess.cs
-System.Net/NetworkCredential.cs
 System.Net.NetworkInformation/DuplicateAddressDetectionState.cs
-System.Net.NetworkInformation/GatewayIPAddressInformationCollection.cs
 System.Net.NetworkInformation/GatewayIPAddressInformation.cs
-System.Net.NetworkInformation/IcmpV4Statistics.cs
-System.Net.NetworkInformation/IcmpV6Statistics.cs
+System.Net.NetworkInformation/GatewayIPAddressInformationCollection.cs
 System.Net.NetworkInformation/IPAddressCollection.cs
-System.Net.NetworkInformation/IPAddressInformationCollection.cs
 System.Net.NetworkInformation/IPAddressInformation.cs
+System.Net.NetworkInformation/IPAddressInformationCollection.cs
 System.Net.NetworkInformation/IPGlobalProperties.cs
 System.Net.NetworkInformation/IPGlobalStatistics.cs
 System.Net.NetworkInformation/IPInterfaceProperties.cs
@@ -273,10 +247,12 @@ System.Net.NetworkInformation/IPStatus.cs
 System.Net.NetworkInformation/IPv4InterfaceProperties.cs
 System.Net.NetworkInformation/IPv4InterfaceStatistics.cs
 System.Net.NetworkInformation/IPv6InterfaceProperties.cs
+System.Net.NetworkInformation/IcmpV4Statistics.cs
+System.Net.NetworkInformation/IcmpV6Statistics.cs
 System.Net.NetworkInformation/LinuxNetworkInterfaceMarshal.cs
 System.Net.NetworkInformation/MacOsNetworkInterfaceMarshal.cs
-System.Net.NetworkInformation/MulticastIPAddressInformationCollection.cs
 System.Net.NetworkInformation/MulticastIPAddressInformation.cs
+System.Net.NetworkInformation/MulticastIPAddressInformationCollection.cs
 System.Net.NetworkInformation/NetBiosNodeType.cs
 System.Net.NetworkInformation/NetworkAddressChangedEventHandler.cs
 System.Net.NetworkInformation/NetworkAvailabilityChangedEventHandler.cs
@@ -284,15 +260,14 @@ System.Net.NetworkInformation/NetworkAvailabilityEventArgs.cs
 System.Net.NetworkInformation/NetworkChange.cs
 System.Net.NetworkInformation/NetworkInformationAccess.cs
 System.Net.NetworkInformation/NetworkInformationException.cs
-
-System.Net.NetworkInformation/NetworkInterfaceComponent.cs
 System.Net.NetworkInformation/NetworkInterface.cs
+System.Net.NetworkInformation/NetworkInterfaceComponent.cs
 System.Net.NetworkInformation/NetworkInterfaceType.cs
 System.Net.NetworkInformation/OperationalStatus.cs
 System.Net.NetworkInformation/PhysicalAddress.cs
+System.Net.NetworkInformation/Ping.cs
 System.Net.NetworkInformation/PingCompletedEventArgs.cs
 System.Net.NetworkInformation/PingCompletedEventHandler.cs
-System.Net.NetworkInformation/Ping.cs
 System.Net.NetworkInformation/PingException.cs
 System.Net.NetworkInformation/PingOptions.cs
 System.Net.NetworkInformation/PingReply.cs
@@ -302,30 +277,22 @@ System.Net.NetworkInformation/TcpConnectionInformation.cs
 System.Net.NetworkInformation/TcpState.cs
 System.Net.NetworkInformation/TcpStatistics.cs
 System.Net.NetworkInformation/UdpStatistics.cs
-System.Net.NetworkInformation/UnicastIPAddressInformationCollection.cs
 System.Net.NetworkInformation/UnicastIPAddressInformation.cs
+System.Net.NetworkInformation/UnicastIPAddressInformationCollection.cs
 System.Net.NetworkInformation/Win32NetworkInterfaceMarshal.cs
-System.Net/NtlmClient.cs
-System/NetPipeStyleUriParser.cs
-System.Net/ProtocolViolationException.cs
-System.Net/RequestStream.cs
-System.Net/ResponseStream.cs
 System.Net.Security/AuthenticatedStream.cs
 System.Net.Security/AuthenticationLevel.cs
 System.Net.Security/LocalCertificateSelectionCallback.cs
 System.Net.Security/NegotiateStream.cs
 System.Net.Security/ProtectionLevel.cs
-System.Net/SecurityProtocolType.cs
 System.Net.Security/RemoteCertificateValidationCallback.cs
-System.Net.Security/SslStream.cs
 System.Net.Security/SslPolicyErrors.cs
-System.Net/ServicePoint.cs
-System.Net/ServicePointManager.cs
-System.Net/SocketAddress.cs
+System.Net.Security/SslStream.cs
+System.Net.Sockets/AddressFamily.cs
 System.Net.Sockets/AddressFamily.cs
 System.Net.Sockets/IOControlCode.cs
-System.Net.Sockets/IPv6MulticastOption.cs
 System.Net.Sockets/IPPacketInformation.cs
+System.Net.Sockets/IPv6MulticastOption.cs
 System.Net.Sockets/LingerOption.cs
 System.Net.Sockets/MulticastOption.cs
 System.Net.Sockets/NetworkStream.cs
@@ -334,7 +301,6 @@ System.Net.Sockets/ProtocolType.cs
 System.Net.Sockets/SelectMode.cs
 System.Net.Sockets/SendPacketsElement.cs
 System.Net.Sockets/Socket.cs
-System.Net.Sockets/Socket_2_1.cs
 System.Net.Sockets/SocketAsyncEventArgs.cs
 System.Net.Sockets/SocketAsyncOperation.cs
 System.Net.Sockets/SocketError.cs
@@ -346,12 +312,110 @@ System.Net.Sockets/SocketOptionLevel.cs
 System.Net.Sockets/SocketOptionName.cs
 System.Net.Sockets/SocketShutdown.cs
 System.Net.Sockets/SocketType.cs
+System.Net.Sockets/Socket_2_1.cs
 System.Net.Sockets/TcpClient.cs
 System.Net.Sockets/TcpListener.cs
 System.Net.Sockets/TransmitFileOptions.cs
 System.Net.Sockets/UdpClient.cs
-System/NetTcpStyleUriParser.cs
+System.Net/AuthenticationManager.cs
+System.Net/AuthenticationSchemeSelector.cs
+System.Net/AuthenticationSchemes.cs
+System.Net/Authorization.cs
+System.Net/BasicClient.cs
+System.Net/BindIPEndPoint.cs
+System.Net/ChunkStream.cs
+System.Net/ChunkedInputStream.cs
+System.Net/ConnectionModes.cs
+System.Net/Cookie.cs
+System.Net/CookieCollection.cs
+System.Net/CookieContainer.cs
+System.Net/CookieException.cs
+System.Net/CredentialCache.cs
+System.Net/DecompressionMethods.cs
+System.Net/DefaultCertificatePolicy.cs
+System.Net/DigestClient.cs
+System.Net/Dns.cs
+System.Net/DownloadDataCompletedEventArgs.cs
+System.Net/DownloadDataCompletedEventHandler.cs
+System.Net/DownloadProgressChangedEventArgs.cs
+System.Net/DownloadProgressChangedEventHandler.cs
+System.Net/DownloadStringCompletedEventArgs.cs
+System.Net/DownloadStringCompletedEventHandler.cs
+System.Net/EndPoint.cs
+System.Net/EndPointListener.cs
+System.Net/EndPointManager.cs
+System.Net/FileWebRequest.cs
+System.Net/FileWebRequestCreator.cs
+System.Net/FileWebResponse.cs
+System.Net/FtpAsyncResult.cs
+System.Net/FtpDataStream.cs
+System.Net/FtpRequestCreator.cs
+System.Net/FtpStatus.cs
+System.Net/FtpStatusCode.cs
+System.Net/FtpWebRequest.cs
+System.Net/FtpWebResponse.cs
+System.Net/GlobalProxySelection.cs
+System.Net/HttpConnection.cs
+System.Net/HttpContinueDelegate.cs
+System.Net/HttpListener.cs
+System.Net/HttpListenerBasicIdentity.cs
+System.Net/HttpListenerContext.cs
+System.Net/HttpListenerException.cs
+System.Net/HttpListenerPrefixCollection.cs
+System.Net/HttpListenerRequest.cs
+System.Net/HttpListenerResponse.cs
+System.Net/HttpRequestCreator.cs
+System.Net/HttpRequestHeader.cs
+System.Net/HttpResponseHeader.cs
+System.Net/HttpStatusCode.cs
+System.Net/HttpStreamAsyncResult.cs
+System.Net/HttpUtility.cs
+System.Net/HttpVersion.cs
+System.Net/HttpWebRequest.cs
+System.Net/HttpWebResponse.cs
+System.Net/IAuthenticationModule.cs
+System.Net/ICertificatePolicy.cs
+System.Net/ICredentialLookup.cs
+System.Net/ICredentialPolicy.cs
+System.Net/ICredentialsByHost.cs
+System.Net/IPAddress.cs
+System.Net/IPAddress.cs
+System.Net/IPEndPoint.cs
+System.Net/IPHostEntry.cs
+System.Net/IPv6Address.cs
+System.Net/IPv6Address.cs
+System.Net/IWebProxy.cs
+System.Net/IWebProxyScript.cs
+System.Net/IWebRequestCreate.cs
+System.Net/ListenerAsyncResult.cs
+System.Net/ListenerPrefix.cs
+System.Net/MonoHttpDate.cs
+System.Net/NetConfig.cs
+System.Net/NetworkAccess.cs
+System.Net/NetworkCredential.cs
+System.Net/NtlmClient.cs
+System.Net/OpenReadCompletedEventArgs.cs
+System.Net/OpenReadCompletedEventHandler.cs
+System.Net/OpenWriteCompletedEventArgs.cs
+System.Net/OpenWriteCompletedEventHandler.cs
+System.Net/ProtocolViolationException.cs
+System.Net/RequestStream.cs
+System.Net/ResponseStream.cs
+System.Net/SecurityProtocolType.cs
+System.Net/ServicePoint.cs
+System.Net/ServicePointManager.cs
+System.Net/SocketAddress.cs
 System.Net/TransportType.cs
+System.Net/UploadDataCompletedEventArgs.cs
+System.Net/UploadDataCompletedEventHandler.cs
+System.Net/UploadFileCompletedEventArgs.cs
+System.Net/UploadFileCompletedEventHandler.cs
+System.Net/UploadProgressChangedEventArgs.cs
+System.Net/UploadProgressChangedEventHandler.cs
+System.Net/UploadStringCompletedEventArgs.cs
+System.Net/UploadStringCompletedEventHandler.cs
+System.Net/UploadValuesCompletedEventArgs.cs
+System.Net/UploadValuesCompletedEventHandler.cs
 System.Net/WebAsyncResult.cs
 System.Net/WebClient.cs
 System.Net/WebConnection.cs
@@ -361,64 +425,44 @@ System.Net/WebConnectionStream.cs
 System.Net/WebException.cs
 System.Net/WebExceptionStatus.cs
 System.Net/WebHeaderCollection.cs
-System.Net/WebPermissionAttribute.cs
 System.Net/WebPermission.cs
+System.Net/WebPermissionAttribute.cs
 System.Net/WebProxy.cs
 System.Net/WebRequest.cs
 System.Net/WebRequestMethods.cs
 System.Net/WebResponse.cs
-System/NewsStyleUriParser.cs
-
-System.Net/UploadDataCompletedEventArgs.cs
-System.Net/UploadFileCompletedEventArgs.cs
-System.Net/UploadFileCompletedEventHandler.cs
-System.Net/UploadProgressChangedEventHandler.cs
-System.Net/OpenReadCompletedEventHandler.cs
-System.Net/DownloadDataCompletedEventHandler.cs
-System.Net/DownloadProgressChangedEventHandler.cs
-System.Net/OpenReadCompletedEventArgs.cs
-System.Net/DownloadStringCompletedEventArgs.cs
-System.Net/DownloadDataCompletedEventArgs.cs
-System.Net/DownloadProgressChangedEventArgs.cs
-System.Net/UploadStringCompletedEventArgs.cs
-System.Net/OpenWriteCompletedEventArgs.cs
-System.Net/UploadProgressChangedEventArgs.cs
-System.Net/OpenWriteCompletedEventHandler.cs
-System.Net/UploadDataCompletedEventHandler.cs
-System.Net/UploadValuesCompletedEventArgs.cs
-System.Net/UploadValuesCompletedEventHandler.cs
-System.Net/UploadStringCompletedEventHandler.cs
-System.Net/DownloadStringCompletedEventHandler.cs
-
-System.Security.Cryptography/AsnEncodedDataCollection.cs
-System.Security.Cryptography/AsnEncodedData.cs
-System.Security.Cryptography/AsnEncodedDataEnumerator.cs
-System.Security.Cryptography/OidCollection.cs
-System.Security.Cryptography/Oid.cs
-System.Security.Cryptography/OidEnumerator.cs
-
-System.Security.Cryptography.X509Certificates/OpenFlags.cs
+System.Security.AccessControl/SemaphoreAccessRule.cs
+System.Security.AccessControl/SemaphoreAuditRule.cs
+System.Security.AccessControl/SemaphoreRights.cs
+System.Security.AccessControl/SemaphoreSecurity.cs
+System.Security.Authentication/AuthenticationException.cs
+System.Security.Authentication/CipherAlgorithmType.cs
+System.Security.Authentication/ExchangeAlgorithmType.cs
+System.Security.Authentication/HashAlgorithmType.cs
+System.Security.Authentication/InvalidCredentialException.cs
+System.Security.Authentication/SslProtocols.cs
 System.Security.Cryptography.X509Certificates/OSX509Certificates.cs
+System.Security.Cryptography.X509Certificates/OpenFlags.cs
 System.Security.Cryptography.X509Certificates/PublicKey.cs
 System.Security.Cryptography.X509Certificates/StoreLocation.cs
 System.Security.Cryptography.X509Certificates/StoreName.cs
 System.Security.Cryptography.X509Certificates/X500DistinguishedName.cs
 System.Security.Cryptography.X509Certificates/X500DistinguishedNameFlags.cs
 System.Security.Cryptography.X509Certificates/X509BasicConstraintsExtension.cs
-System.Security.Cryptography.X509Certificates/X509Certificate2Collection.cs
 System.Security.Cryptography.X509Certificates/X509Certificate2.cs
+System.Security.Cryptography.X509Certificates/X509Certificate2Collection.cs
 System.Security.Cryptography.X509Certificates/X509Certificate2Enumerator.cs
 System.Security.Cryptography.X509Certificates/X509CertificateCollection.cs
 System.Security.Cryptography.X509Certificates/X509Chain.cs
-System.Security.Cryptography.X509Certificates/X509ChainElementCollection.cs
 System.Security.Cryptography.X509Certificates/X509ChainElement.cs
+System.Security.Cryptography.X509Certificates/X509ChainElementCollection.cs
 System.Security.Cryptography.X509Certificates/X509ChainElementEnumerator.cs
 System.Security.Cryptography.X509Certificates/X509ChainPolicy.cs
 System.Security.Cryptography.X509Certificates/X509ChainStatus.cs
 System.Security.Cryptography.X509Certificates/X509ChainStatusFlags.cs
 System.Security.Cryptography.X509Certificates/X509EnhancedKeyUsageExtension.cs
-System.Security.Cryptography.X509Certificates/X509ExtensionCollection.cs
 System.Security.Cryptography.X509Certificates/X509Extension.cs
+System.Security.Cryptography.X509Certificates/X509ExtensionCollection.cs
 System.Security.Cryptography.X509Certificates/X509ExtensionEnumerator.cs
 System.Security.Cryptography.X509Certificates/X509FindType.cs
 System.Security.Cryptography.X509Certificates/X509IncludeOption.cs
@@ -431,26 +475,62 @@ System.Security.Cryptography.X509Certificates/X509Store.cs
 System.Security.Cryptography.X509Certificates/X509SubjectKeyIdentifierExtension.cs
 System.Security.Cryptography.X509Certificates/X509SubjectKeyIdentifierHashAlgorithm.cs
 System.Security.Cryptography.X509Certificates/X509VerificationFlags.cs
-
-System.Security.Authentication/AuthenticationException.cs
-System.Security.Authentication/CipherAlgorithmType.cs
-System.Security.Authentication/ExchangeAlgorithmType.cs
-System.Security.Authentication/HashAlgorithmType.cs
-System.Security.Authentication/SslProtocols.cs
-System.Security.Authentication/InvalidCredentialException.cs
-
+System.Security.Cryptography/AsnEncodedData.cs
+System.Security.Cryptography/AsnEncodedDataCollection.cs
+System.Security.Cryptography/AsnEncodedDataEnumerator.cs
+System.Security.Cryptography/Oid.cs
+System.Security.Cryptography/OidCollection.cs
+System.Security.Cryptography/OidEnumerator.cs
+System.Text.RegularExpressions/BaseMachine.cs
+System.Text.RegularExpressions/Capture.cs
+System.Text.RegularExpressions/CaptureCollection.cs
+System.Text.RegularExpressions/Group.cs
+System.Text.RegularExpressions/GroupCollection.cs
+System.Text.RegularExpressions/Match.cs
+System.Text.RegularExpressions/MatchCollection.cs
+System.Text.RegularExpressions/MatchEvaluator.cs
+System.Text.RegularExpressions/Regex.cs
+System.Text.RegularExpressions/RegexCompilationInfo.cs
+System.Text.RegularExpressions/RegexOptions.cs
+System.Text.RegularExpressions/RxInterpreter.cs
+System.Text.RegularExpressions/RxOp.cs
+System.Text.RegularExpressions/arch.cs
+System.Text.RegularExpressions/cache.cs
+System.Text.RegularExpressions/category.cs
+System.Text.RegularExpressions/compiler.cs
+System.Text.RegularExpressions/debug.cs
+System.Text.RegularExpressions/interpreter.cs
+System.Text.RegularExpressions/interval.cs
+System.Text.RegularExpressions/parser.cs
+System.Text.RegularExpressions/quicksearch.cs
+System.Text.RegularExpressions/replace.cs
+System.Text.RegularExpressions/syntax.cs
 System.Threading/Semaphore.cs
 System.Threading/SemaphoreFullException.cs
 System.Threading/ThreadExceptionEventArgs.cs
 System.Threading/ThreadExceptionEventHandler.cs
-
-System.Security.AccessControl/SemaphoreAccessRule.cs
-System.Security.AccessControl/SemaphoreAuditRule.cs
-System.Security.AccessControl/SemaphoreRights.cs
-System.Security.AccessControl/SemaphoreSecurity.cs
-
 System.Timers/ElapsedEventArgs.cs
 System.Timers/ElapsedEventHandler.cs
 System.Timers/Timer.cs
 System.Timers/TimersDescriptionAttribute.cs
-
+System/DefaultUriParser.cs
+System/FileStyleUriParser.cs
+System/FtpStyleUriParser.cs
+System/GenericUriParser.cs
+System/GenericUriParserOptions.cs
+System/HttpStyleUriParser.cs
+System/NetPipeStyleUriParser.cs
+System/NetTcpStyleUriParser.cs
+System/NewsStyleUriParser.cs
+System/SRDescriptionAttribute.cs
+System/Uri.cs
+System/UriBuilder.cs
+System/UriComponents.cs
+System/UriFormat.cs
+System/UriFormatException.cs
+System/UriHostNameType.cs
+System/UriIdnScope.cs
+System/UriKind.cs
+System/UriParser.cs
+System/UriPartial.cs
+System/UriTypeConverter.cs
diff --git a/mcs/class/System/moonlight_bootstrap_System.dll.sources b/mcs/class/System/moonlight_bootstrap_System.dll.sources
new file mode 100644 (file)
index 0000000..f54a612
--- /dev/null
@@ -0,0 +1,6 @@
+../../build/common/Consts.cs
+../../build/common/Locale.cs
+../../build/common/MonoTODOAttribute.cs
+../corlib/System.Collections/CollectionDebuggerView.cs
+../corlib/System.Collections.Generic/CollectionDebuggerView.cs
+#include moonlight_raw_System.dll.sources
diff --git a/mcs/class/System/moonlight_raw_System.dll.sources b/mcs/class/System/moonlight_raw_System.dll.sources
new file mode 100644 (file)
index 0000000..e824344
--- /dev/null
@@ -0,0 +1,294 @@
+Assembly/AssemblyInfo.cs
+Mono.Http/NtlmClient.cs
+System.CodeDom.Compiler/GeneratedCodeAttribute.cs
+System.Collections.Generic/ISet.cs
+System.Collections.Generic/LinkedList.cs
+System.Collections.Generic/LinkedListNode.cs
+System.Collections.Generic/RBTree.cs
+System.Collections.Generic/Queue.cs
+System.Collections.Generic/SortedDictionary.cs
+System.Collections.Generic/SortedList.cs
+System.Collections.Generic/Stack.cs
+System.Collections.Specialized/BitVector32.cs
+System.Collections.Specialized/CollectionsUtil.cs
+System.Collections.Specialized/IOrderedDictionary.cs
+System.Collections.Specialized/ListDictionary.cs
+System.Collections.Specialized/HybridDictionary.cs
+System.Collections.Specialized/NameObjectCollectionBase.cs
+System.Collections.Specialized/NameValueCollection.cs
+System.Collections.Specialized/OrderedDictionary.cs
+System.Collections.Specialized/StringCollection.cs
+System.Collections.Specialized/StringDictionary.cs
+System.Collections.Specialized/StringEnumerator.cs
+System.ComponentModel/AsyncCompletedEventArgs.cs
+System.ComponentModel/AsyncCompletedEventHandler.cs
+System.ComponentModel/AsyncOperation.cs
+System.ComponentModel/AsyncOperationManager.cs
+System.ComponentModel/BackgroundWorker.cs
+System.ComponentModel/BrowsableAttribute.cs
+System.ComponentModel/BindableAttribute.cs
+System.ComponentModel/BindableSupport.cs
+System.ComponentModel/BindingDirection.cs
+System.ComponentModel/CancelEventArgs.cs
+System.ComponentModel/CategoryAttribute.cs
+System.ComponentModel/ComplexBindingPropertiesAttribute.cs
+System.ComponentModel/ComponentCollection.cs
+System.ComponentModel/DefaultBindingPropertyAttribute.cs
+System.ComponentModel/DefaultEventAttribute.cs
+System.ComponentModel/DefaultPropertyAttribute.cs
+System.ComponentModel/DefaultValueAttribute.cs
+System.ComponentModel/DescriptionAttribute.cs
+System.ComponentModel/DesignTimeVisibleAttribute.cs
+System.ComponentModel/DoWorkEventHandler.cs
+System.ComponentModel/DoWorkEventArgs.cs
+System.ComponentModel/EditorAttribute.cs
+System.ComponentModel/EditorBrowsableAttribute.cs
+System.ComponentModel/EditorBrowsableState.cs
+System.ComponentModel/IChangeTracking.cs
+System.ComponentModel/IContainer.cs
+System.ComponentModel/IComponent.cs
+System.ComponentModel/IDataErrorInfo.cs
+System.ComponentModel/IEditableObject.cs
+System.ComponentModel/INotifyPropertyChanged.cs
+System.ComponentModel/InvalidEnumArgumentException.cs
+System.ComponentModel/IRevertibleChangeTracking.cs
+System.ComponentModel/ISite.cs
+System.ComponentModel/ISynchronizeInvoke.cs
+System.ComponentModel/ISupportInitialize.cs
+System.ComponentModel/ITypeDescriptorContext.cs
+System.ComponentModel/ListSortDirection.cs
+System.ComponentModel/LookupBindingPropertiesAttribute.cs
+System.ComponentModel/ProgressChangedEventHandler.cs
+System.ComponentModel/ProgressChangedEventArgs.cs
+System.ComponentModel/PropertyChangedEventArgs.cs
+System.ComponentModel/PropertyChangedEventHandler.cs
+System.ComponentModel/PropertyDescriptor.cs
+System.ComponentModel/ReadOnlyAttribute.cs
+System.ComponentModel/RecommendedAsConfigurableAttribute.cs
+System.ComponentModel/RunWorkerCompletedEventArgs.cs
+System.ComponentModel/RunWorkerCompletedEventHandler.cs
+System.ComponentModel/TypeConverterAttribute.cs
+System.ComponentModel/TypeConverter_2_1.cs
+System/DefaultUriParser.cs
+System.Diagnostics/Debug_2_1.cs
+System/FileStyleUriParser.cs
+System/FtpStyleUriParser.cs
+System/GenericUriParser.cs
+System/GenericUriParserOptions.cs
+System/GopherStyleUriParser.cs
+System/HttpStyleUriParser.cs
+System/UriIdnScope.cs
+System/UriTypeConverter.cs
+System.IO.Compression/CompressionMode.cs
+System.IO.Compression/DeflateStream.cs
+System.IO.Compression/GZipStream.cs
+System.IO/ErrorEventArgs.cs
+System.IO/ErrorEventHandler.cs
+System.IO/FileAction.cs
+System.IO/FileSystemEventArgs.cs
+System.IO/FileSystemEventHandler.cs
+System.IO/InternalBufferOverflowException.cs
+System.IO/InvalidDataException.cs
+System.IO/IODescriptionAttribute.cs
+System.IO/MonoIO.cs
+System.IO/MonoIOError.cs
+System.IO/MonoSyncFileStream.cs
+System.IO/NotifyFilters.cs
+System.IO/RenamedEventArgs.cs
+System.IO/RenamedEventHandler.cs
+System.IO/SearchPattern.cs
+System.IO/WaitForChangedResult.cs
+System.IO/WatcherChangeTypes.cs
+System/IUriData.cs
+System/LdapStyleUriParser.cs
+System.Net/AuthenticationManager.cs
+System.Net/AuthenticationSchemes.cs
+System.Net/AuthenticationSchemeSelector.cs
+System.Net/Authorization.cs
+System.Net/BasicClient.cs
+System.Net/BindIPEndPoint.cs
+System.Net.Cache/HttpCacheAgeControl.cs
+System.Net.Cache/HttpRequestCacheLevel.cs
+System.Net.Cache/HttpRequestCachePolicy.cs
+System.Net.Cache/RequestCacheLevel.cs
+System.Net.Cache/RequestCachePolicy.cs
+System.Net/ChunkedInputStream.cs
+System.Net/ChunkStream.cs
+System.Net/ConnectionModes.cs
+System.Net/CookieCollection.cs
+System.Net/CookieContainer.cs
+System.Net/Cookie.cs
+System.Net/CookieException.cs
+System.Net/CredentialCache.cs
+System.Net/DecompressionMethods.cs
+System.Net/DefaultCertificatePolicy.cs
+System.Net/DigestClient.cs
+System.Net/Dns.cs
+System.Net/DnsEndPoint.cs
+System.Net/EndPoint.cs
+System.Net/GlobalProxySelection.cs
+System.Net/HttpConnection.cs
+System.Net/HttpContinueDelegate.cs
+System.Net/HttpRequestCreator.cs
+System.Net/HttpRequestHeader.cs
+System.Net/HttpResponseHeader.cs
+System.Net/HttpStatusCode.cs
+System.Net/HttpStreamAsyncResult.cs
+System.Net/HttpUtility.cs
+System.Net/HttpVersion.cs
+System.Net/HttpWebRequest.cs
+System.Net/HttpWebResponse.cs
+System.Net/IAuthenticationModule.cs
+System.Net/ICertificatePolicy.cs
+System.Net/ICredentialLookup.cs
+System.Net/ICredentialPolicy.cs
+System.Net/ICredentialsByHost.cs
+System.Net/IPAddress.cs
+System.Net/IPEndPoint.cs
+System.Net/IPHostEntry.cs
+System.Net/IPv6Address.cs
+System.Net/IWebProxy.cs
+System.Net/IWebProxyScript.cs
+System.Net/IWebRequestCreate.cs
+System.Net/ListenerAsyncResult.cs
+System.Net/ListenerPrefix.cs
+System.Net/MonoHttpDate.cs
+System.Net/NetworkAccess.cs
+System.Net/NetworkCredential.cs
+System.Net/NtlmClient.cs
+System/NetPipeStyleUriParser.cs
+System.Net/ProtocolViolationException.cs
+System.Net/RequestStream.cs
+System.Net/ResponseStream.cs
+System.Net.Security/AuthenticatedStream.cs
+System.Net.Security/AuthenticationLevel.cs
+System.Net.Security/LocalCertificateSelectionCallback.cs
+System.Net.Security/ProtectionLevel.cs
+System.Net/SecurityProtocolType.cs
+System.Net.Security/RemoteCertificateValidationCallback.cs
+System.Net.Security/SslStream.cs
+System.Net.Security/SslPolicyErrors.cs
+System.Net/ServicePoint.cs
+System.Net/ServicePointManager.cs
+System.Net/SocketAddress.cs
+System.Net.Sockets/AddressFamily.cs
+System.Net.Sockets/IOControlCode.cs
+System.Net.Sockets/IPv6MulticastOption.cs
+System.Net.Sockets/IPPacketInformation.cs
+System.Net.Sockets/LingerOption.cs
+System.Net.Sockets/MulticastOption.cs
+System.Net.Sockets/NetworkStream.cs
+System.Net.Sockets/ProtocolFamily.cs
+System.Net.Sockets/ProtocolType.cs
+System.Net.Sockets/SelectMode.cs
+System.Net.Sockets/SendPacketsElement.cs
+System.Net.Sockets/Socket.cs
+System.Net.Sockets/Socket_2_1.cs
+System.Net.Sockets/SocketAsyncEventArgs.cs
+System.Net.Sockets/SocketAsyncOperation.cs
+System.Net.Sockets/SocketError.cs
+../System.Net/System.Net.Sockets/SocketException_2_1.cs
+System.Net.Sockets/SocketFlags.cs
+System.Net.Sockets/SocketInformation.cs
+System.Net.Sockets/SocketInformationOptions.cs
+System.Net.Sockets/SocketOptionLevel.cs
+System.Net.Sockets/SocketOptionName.cs
+System.Net.Sockets/SocketShutdown.cs
+System.Net.Sockets/SocketType.cs
+System.Net.Sockets/TcpClient.cs
+System.Net.Sockets/TcpListener.cs
+System.Net.Sockets/TransmitFileOptions.cs
+System.Net.Sockets/UdpClient.cs
+System/NetTcpStyleUriParser.cs
+System.Net/TransportType.cs
+System.Net/WebAsyncResult.cs
+System.Net/WebConnection.cs
+System.Net/WebConnectionData.cs
+System.Net/WebConnectionGroup.cs
+System.Net/WebConnectionStream.cs
+System.Net/WebException.cs
+System.Net/WebExceptionStatus.cs
+System.Net/WebHeaderCollection.cs
+System.Net/WebProxy.cs
+System.Net/WebRequest.cs
+System.Net/WebRequestMethods.cs
+System.Net/WebResponse.cs
+System/NewsStyleUriParser.cs
+System.Security.Authentication/AuthenticationException.cs
+System.Security.Authentication/CipherAlgorithmType.cs
+System.Security.Authentication/ExchangeAlgorithmType.cs
+System.Security.Authentication/HashAlgorithmType.cs
+System.Security.Authentication/SslProtocols.cs
+System.Security.Authentication/InvalidCredentialException.cs
+System.Security.Cryptography.X509Certificates/OpenFlags.cs
+System.Security.Cryptography.X509Certificates/PublicKey.cs
+System.Security.Cryptography.X509Certificates/StoreLocation.cs
+System.Security.Cryptography.X509Certificates/StoreName.cs
+System.Security.Cryptography.X509Certificates/X500DistinguishedName.cs
+System.Security.Cryptography.X509Certificates/X500DistinguishedNameFlags.cs
+System.Security.Cryptography.X509Certificates/X509BasicConstraintsExtension.cs
+System.Security.Cryptography.X509Certificates/X509Certificate2Collection.cs
+System.Security.Cryptography.X509Certificates/X509Certificate2.cs
+System.Security.Cryptography.X509Certificates/X509Certificate2Enumerator.cs
+System.Security.Cryptography.X509Certificates/X509CertificateCollection.cs
+System.Security.Cryptography.X509Certificates/X509Chain.cs
+System.Security.Cryptography.X509Certificates/X509ChainElementCollection.cs
+System.Security.Cryptography.X509Certificates/X509ChainElement.cs
+System.Security.Cryptography.X509Certificates/X509ChainElementEnumerator.cs
+System.Security.Cryptography.X509Certificates/X509ChainPolicy.cs
+System.Security.Cryptography.X509Certificates/X509ChainStatus.cs
+System.Security.Cryptography.X509Certificates/X509ChainStatusFlags.cs
+System.Security.Cryptography.X509Certificates/X509EnhancedKeyUsageExtension.cs
+System.Security.Cryptography.X509Certificates/X509ExtensionCollection.cs
+System.Security.Cryptography.X509Certificates/X509Extension.cs
+System.Security.Cryptography.X509Certificates/X509ExtensionEnumerator.cs
+System.Security.Cryptography.X509Certificates/X509FindType.cs
+System.Security.Cryptography.X509Certificates/X509IncludeOption.cs
+System.Security.Cryptography.X509Certificates/X509KeyUsageExtension.cs
+System.Security.Cryptography.X509Certificates/X509KeyUsageFlags.cs
+System.Security.Cryptography.X509Certificates/X509NameType.cs
+System.Security.Cryptography.X509Certificates/X509RevocationFlag.cs
+System.Security.Cryptography.X509Certificates/X509RevocationMode.cs
+System.Security.Cryptography.X509Certificates/X509Store.cs
+System.Security.Cryptography.X509Certificates/X509SubjectKeyIdentifierExtension.cs
+System.Security.Cryptography.X509Certificates/X509SubjectKeyIdentifierHashAlgorithm.cs
+System.Security.Cryptography.X509Certificates/X509VerificationFlags.cs
+System/SRDescriptionAttribute.cs
+System.Text.RegularExpressions/arch.cs
+System.Text.RegularExpressions/BaseMachine.cs
+System.Text.RegularExpressions/cache.cs
+System.Text.RegularExpressions/CaptureCollection.cs
+System.Text.RegularExpressions/Capture.cs
+System.Text.RegularExpressions/category.cs
+System.Text.RegularExpressions/compiler.cs
+System.Text.RegularExpressions/debug.cs
+System.Text.RegularExpressions/GroupCollection.cs
+System.Text.RegularExpressions/Group.cs
+System.Text.RegularExpressions/interpreter.cs
+System.Text.RegularExpressions/interval.cs
+System.Text.RegularExpressions/MatchCollection.cs
+System.Text.RegularExpressions/Match.cs
+System.Text.RegularExpressions/MatchEvaluator.cs
+System.Text.RegularExpressions/parser.cs
+System.Text.RegularExpressions/quicksearch.cs
+System.Text.RegularExpressions/RegexCompilationInfo.cs
+System.Text.RegularExpressions/Regex.cs
+System.Text.RegularExpressions/RegexOptions.cs
+System.Text.RegularExpressions/RxInterpreter.cs
+System.Text.RegularExpressions/RxOp.cs
+System.Text.RegularExpressions/replace.cs
+System.Text.RegularExpressions/syntax.cs
+System.Timers/ElapsedEventArgs.cs
+System.Timers/ElapsedEventHandler.cs
+System.Timers/Timer.cs
+System.Timers/TimersDescriptionAttribute.cs
+System/UriBuilder.cs
+System/UriComponents.cs
+System/Uri.cs
+System/UriData.cs
+System/UriFormat.cs
+System/UriFormatException.cs
+System/UriHostNameType.cs
+System/UriKind.cs
+System/UriParser.cs
+System/UriPartial.cs
diff --git a/mcs/class/System/net_2_1_bootstrap_System.dll.sources b/mcs/class/System/net_2_1_bootstrap_System.dll.sources
deleted file mode 100644 (file)
index 5482dc9..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-../../build/common/Consts.cs
-../../build/common/Locale.cs
-../../build/common/MonoTODOAttribute.cs
-#include net_2_1_raw_System.dll.sources
diff --git a/mcs/class/System/net_2_1_raw_System.dll.sources b/mcs/class/System/net_2_1_raw_System.dll.sources
deleted file mode 100644 (file)
index 8f6c217..0000000
+++ /dev/null
@@ -1,99 +0,0 @@
-Assembly/AssemblyInfo.cs
-System.CodeDom.Compiler/GeneratedCodeAttribute.cs
-System.Collections.Generic/ISet.cs
-System.Collections.Generic/LinkedList.cs
-System.Collections.Generic/LinkedListNode.cs
-System.Collections.Generic/RBTree.cs
-System.Collections.Generic/Queue.cs
-System.Collections.Generic/SortedDictionary.cs
-System.Collections.Generic/SortedList.cs
-System.Collections.Generic/Stack.cs
-System.Collections.Specialized/BitVector32.cs
-System.Collections.Specialized/CollectionsUtil.cs
-System.Collections.Specialized/ListDictionary.cs
-System.Collections.Specialized/HybridDictionary.cs
-System.Collections.Specialized/StringDictionary.cs
-System.ComponentModel/AsyncCompletedEventArgs.cs
-System.ComponentModel/AsyncCompletedEventHandler.cs
-System.ComponentModel/AsyncOperation.cs
-System.ComponentModel/AsyncOperationManager.cs
-System.ComponentModel/BackgroundWorker.cs
-System.ComponentModel/CancelEventArgs.cs
-System.ComponentModel/CategoryAttribute.cs
-System.ComponentModel/ComponentCollection.cs
-System.ComponentModel/DefaultValueAttribute.cs
-System.ComponentModel/DescriptionAttribute.cs
-System.ComponentModel/DoWorkEventHandler.cs
-System.ComponentModel/DoWorkEventArgs.cs
-System.ComponentModel/EditorBrowsableAttribute.cs
-System.ComponentModel/EditorBrowsableState.cs
-System.ComponentModel/IChangeTracking.cs
-System.ComponentModel/IContainer.cs
-System.ComponentModel/IComponent.cs
-System.ComponentModel/IDataErrorInfo.cs
-System.ComponentModel/IEditableObject.cs
-System.ComponentModel/INotifyPropertyChanged.cs
-System.ComponentModel/InvalidEnumArgumentException.cs
-System.ComponentModel/IRevertibleChangeTracking.cs
-System.ComponentModel/ISite.cs
-System.ComponentModel/ITypeDescriptorContext.cs
-System.ComponentModel/ListSortDirection.cs
-System.ComponentModel/ProgressChangedEventHandler.cs
-System.ComponentModel/ProgressChangedEventArgs.cs
-System.ComponentModel/PropertyChangedEventArgs.cs
-System.ComponentModel/PropertyChangedEventHandler.cs
-System.ComponentModel/PropertyDescriptor.cs
-System.ComponentModel/ReadOnlyAttribute.cs
-System.ComponentModel/RunWorkerCompletedEventArgs.cs
-System.ComponentModel/RunWorkerCompletedEventHandler.cs
-System.ComponentModel/TypeConverterAttribute.cs
-System.ComponentModel/TypeConverter_2_1.cs
-System/DefaultUriParser.cs
-System.Diagnostics/Debug_2_1.cs
-System/FileStyleUriParser.cs
-System/FtpStyleUriParser.cs
-System/GenericUriParser.cs
-System/GenericUriParserOptions.cs
-System/HttpStyleUriParser.cs
-System/UriIdnScope.cs
-System/UriTypeConverter.cs
-System.Net/IPAddress.cs
-System.Net/IPv6Address.cs
-System.Net.Sockets/AddressFamily.cs
-System/SRDescriptionAttribute.cs
-System.Text.RegularExpressions/arch.cs
-System.Text.RegularExpressions/BaseMachine.cs
-System.Text.RegularExpressions/cache.cs
-System.Text.RegularExpressions/CaptureCollection.cs
-System.Text.RegularExpressions/Capture.cs
-System.Text.RegularExpressions/category.cs
-System.Text.RegularExpressions/compiler.cs
-System.Text.RegularExpressions/debug.cs
-System.Text.RegularExpressions/GroupCollection.cs
-System.Text.RegularExpressions/Group.cs
-System.Text.RegularExpressions/interpreter.cs
-System.Text.RegularExpressions/interval.cs
-System.Text.RegularExpressions/MatchCollection.cs
-System.Text.RegularExpressions/Match.cs
-System.Text.RegularExpressions/MatchEvaluator.cs
-System.Text.RegularExpressions/parser.cs
-System.Text.RegularExpressions/quicksearch.cs
-System.Text.RegularExpressions/RegexCompilationInfo.cs
-System.Text.RegularExpressions/Regex.cs
-System.Text.RegularExpressions/RegexOptions.cs
-System.Text.RegularExpressions/RxInterpreter.cs
-System.Text.RegularExpressions/RxOp.cs
-System.Text.RegularExpressions/replace.cs
-System.Text.RegularExpressions/syntax.cs
-System/UriBuilder.cs
-System/UriComponents.cs
-System/Uri.cs
-System/UriFormat.cs
-System/UriFormatException.cs
-System/UriHostNameType.cs
-System/UriKind.cs
-System/UriParser.cs
-System/UriPartial.cs
-
-../corlib/System.Collections/CollectionDebuggerView.cs
-../corlib/System.Collections.Generic/CollectionDebuggerView.cs
index bc52da976a966b425677e8a03daf84c93227c9db..3b68189f0bdd8973a4a22356d239d0011ca8ccce 100644 (file)
@@ -79,7 +79,7 @@ using System.Runtime.InteropServices;
        [assembly: DefaultDependency (LoadHint.Always)]
        [assembly: StringFreezing]
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
        [assembly: InternalsVisibleTo ("System, PublicKey=00240000048000009400000006020000002400005253413100040000010001008D56C76F9E8649383049F383C44BE0EC204181822A6C31CF5EB7EF486944D032188EA1D3920763712CCB12D75FB77E9811149E6148E5D32FBAAB37611C1878DDC19E20EF135D0CB2CFF2BFEC3D115810C3D9069638FE4BE215DBF795861920E5AB6F7DB2E2CEEF136AC23D5DD2BF031700AEC232F6C6B1C785B4305C123B37AB")]
        [assembly: InternalsVisibleTo ("System.Windows, PublicKey=00240000048000009400000006020000002400005253413100040000010001008D56C76F9E8649383049F383C44BE0EC204181822A6C31CF5EB7EF486944D032188EA1D3920763712CCB12D75FB77E9811149E6148E5D32FBAAB37611C1878DDC19E20EF135D0CB2CFF2BFEC3D115810C3D9069638FE4BE215DBF795861920E5AB6F7DB2E2CEEF136AC23D5DD2BF031700AEC232F6C6B1C785B4305C123B37AB")]
        [assembly: InternalsVisibleTo ("System.Windows.Browser, PublicKey=00240000048000009400000006020000002400005253413100040000010001008D56C76F9E8649383049F383C44BE0EC204181822A6C31CF5EB7EF486944D032188EA1D3920763712CCB12D75FB77E9811149E6148E5D32FBAAB37611C1878DDC19E20EF135D0CB2CFF2BFEC3D115810C3D9069638FE4BE215DBF795861920E5AB6F7DB2E2CEEF136AC23D5DD2BF031700AEC232F6C6B1C785B4305C123B37AB")]
index e35c3ac83f926b1fc499093ac007fece56273922..d1f7178414d0ceef3ed94eba17ae572fdadcc1b6 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * AssemblyInfo.cs: use MOONLIGHT symbol to disambiguate
+       MonoTouch and Moonlight code.
+
 2010-02-09  Sebastien Pouliot  <sebastien@ximian.com>
 
        * AssemblyInfo.cs: Mono.CompilerServices.SymbolWriter does not
index 57e212107bf1206e7e419e003bf788f09f539b90..10504f0fbce6cb3e0631989f6c33c1f3d5944c97 100644 (file)
@@ -1,3 +1,35 @@
+2010-04-23  Rolf Bjarne Kvinge  <RKvinge@novell.com>
+
+       * moonlight_raw_corlib.dll.sources: Don't include Lazy.cs here. It's in
+       System.Core.dll.
+
+2010-04-06  Jb Evain  <jbevain@novell.com>
+
+       * corlib.dll.sources: add System.Threading.SemaphoreFullException
+       from System in net_4_0.
+
+2010-03-30  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * moonlight_raw_corlib.dll.sources: Fix Moonlight since these 
+       types now reside in mscorlib (not System.Coe) for NET_4_0 and
+       also for SL4
+
+2010-03-26  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * moonlight_raw_corlib.dll.sources: Add MonoAssembly to ML build
+       since it contains parts of the Assembly features (partial class)
+
+2010-03-18  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * corlib.dll.sources: Add Aes (for NET_4_0)
+       * moonlight_raw_corlib.dll.sources: Add Aes and System.Runtime.
+       CompilerServices/ReferenceAssemblyAttribute.cs
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * Makefile: rename the net_2_1 profile to moonlight.
+       * net_2_1_*.dll.sources: rename to moonlight_*.dll.sources.
+
 2010-03-11  Sebastien Pouliot  <sebastien@ximian.com>
 
        * net_2_1_raw_corlib.dll.sources: Add System.Diagnostics.Contracts
index 820468c9380fcd1966a8dd8a0276f5b11b206c3e..4206ae2742ab1fd2622d311ab7771fdebe757575 100644 (file)
@@ -75,11 +75,3 @@ $(cmp_makefrag): $(cmp_response)
 
 $(cmp_response) $(cmp_makefrag): Makefile $(depsdir)/.stamp
 endif
-
-#
-# qh21 = Quick Hack for 2.1, to be used by impatient developers to get
-# test builds done quickly
-#
-qh21:
-       make PROFILE=net_2_1_raw
-       (cd ../../tools/tuner; rm tune.stamp; make tune.stamp && make PROFILE=net_2_1 install)
index 242941a55f9a188fda4d108bd7658366c55a85c8..5550f25e66063fbc66dccc53e62c2bf5e6668f36 100644 (file)
@@ -1,3 +1,80 @@
+2010-04-20  Damien Diederen  <dd@crosstwine.com>
+
+       * Normalization.cs: Really apply canonical reordering "recursively."
+
+       Before this, a sequence of code points with the combining
+       classes (22, 33, 11) would be reordered to (22, 11, 33) instead of
+       the correct (11, 22, 33).  This is because the 'i--' would be
+       directly cancelled by the 'i++' in the for loop.
+
+2010-04-20  Damien Diederen  <dd@crosstwine.com>
+
+       * Normalization.cs: The correct "checkType" argument to
+       Decompose() is NKD or NKFD when normalizing to NKC resp. NKFC.
+
+       * StringTest.cs: More NFC test cases.
+
+2010-04-20  Damien Diederen  <dd@crosstwine.com>
+
+       * Normalization.cs: Implement algorithmic Hangul composition.
+       Calling Normalize(NormalizationForm.FormC) on Korean characters
+       now works properly (bnc#480152).
+
+       * StringTest.cs: Add test cases for Hangul composition.
+
+2010-04-20  Damien Diederen  <dd@crosstwine.com>
+
+       * Normalization.cs: Follow the spec when checking composition pairs.
+
+       Figure 7 in section 1.3 of http://unicode.org/reports/tr15/ shows
+       how when doing composition, one has to examine the successive
+       (starter, candidate) pairs, and combine if a matching canonical
+       decomposition exists.
+
+       The original algorithm was, instead, iterating on canonical
+       decompositions, and, for each one, trying to match a sequence
+       of (starter, non-starter, ...).  This, however, does not produce
+       the same results as it is violating some implicit ordering
+       constraints in the Unicode tables.
+
+       E.g., when composing the following sequence of codepoints, the
+       original algorithm was picking:
+
+         03B7 0313 0300 0345
+         ^^^^      ^^^^
+         1F74 0313      0345
+         ^^^^           ^^^^
+         1FC2 0313
+
+       and would stop at 1FC2 0313 as there is no decomposition matching
+       it.  The new algorithm, which follows the guidance of the pretty
+       figure 7, ends up doing:
+
+         03B7 0313 0300 0345
+         ^^^^ ^^^^
+         1F20      0300 0345
+         ^^^^      ^^^^
+         1F22           0345
+         ^^^^           ^^^^
+         1F92
+
+       resulting in the correct 1F92.
+
+2010-04-19  Damien Diederen  <dd@crosstwine.com>
+
+       * Normalization.cs: Recursively apply the Unicode decomposition mapping.
+
+       According to http://www.unicode.org/reports/tr15/tr15-31.html,
+       section 1.3:
+
+       "To transform a Unicode string into a given Unicode Normalization
+       Form, the first step is to fully decompose the string. [...] Full
+       decomposition involves recursive application of the
+       Decomposition_Mapping values, because in some cases a complex
+       composite character may have a Decomposition_Mapping into a
+       sequence of characters, one of which may also have its own
+       non-trivial Decomposition_Mapping value."
+
 2010-02-18  Gabriel Burt  <gabriel.burt@gmail.com>
 
        * Normalization.cs: Implement algorithmic Hangul decomposition; Calling
index 8dd8897b43733378d224787b9f90d53cca77c9aa..4e38590e5f5f56a79bccbc463063fa8014c6a06d 100644 (file)
@@ -38,15 +38,6 @@ namespace Mono.Globalization.Unicode
                        return charMapIndex [NUtil.MapIdx (cp)];
                }
 
-               static int GetNormalizedStringLength (int ch)
-               {
-                       int start = charMapIndex [NUtil.MapIdx (ch)];
-                       int i = start;
-                       while (mappedChars [i] != 0)
-                               i++;
-                       return i - start;
-               }
-
                static byte GetCombiningClass (int c)
                {
                        return combiningClass [NUtil.Combining.ToIndex (c)];
@@ -62,70 +53,11 @@ namespace Mono.Globalization.Unicode
                        return helperIndex [NUtil.Helper.ToIndex (cp)];
                }
 
-               static int GetPrimaryCompositeCharIndex (object chars, int start)
-               {
-                       string s = chars as string;
-                       StringBuilder sb = chars as StringBuilder;
-                       char startCh = s != null ? s [start] : sb [start];
-                       int charsLength = sb != null ? sb.Length : s.Length;
-
-                       int idx = GetPrimaryCompositeHelperIndex ((int) startCh);
-                       if (idx == 0)
-                               return 0;
-                       while (mappedChars [idx] == startCh) {
-                               int prevCB = 0;
-                               int combiningClass = 0;
-                               for (int i = 1, j = 1; ; i++, j++) {
-                                       prevCB = combiningClass;
-
-                                       if (mappedChars [idx + i] == 0)
-                                               // matched
-                                               return idx;
-                                       if (start + i >= charsLength)
-                                               return 0; // didn't match
-
-                                       // handle blocked characters here.
-                                       char curCh;
-                                       bool match = false;
-                                       do {
-                                               curCh = s != null ?
-                                                       s [start + j] :
-                                                       sb [start + j];
-                                               combiningClass = GetCombiningClass (curCh);
-                                               if (mappedChars [idx + i] == curCh) {
-                                                       match = true;
-                                                       break;
-                                               }
-                                               if (combiningClass < prevCB) // blocked. Give up this map entry.
-                                                       break;
-                                               if (++j + start >= charsLength || combiningClass == 0)
-                                                       break;
-                                       } while (true);
-
-                                       if (match)
-                                               continue; // check next character in the current map entry string.
-                                       if (prevCB < combiningClass) {
-                                               j--;
-                                               if (mappedChars [idx + i] == curCh)
-                                                       continue;
-                                               //if (mappedChars [idx + i] > curCh)
-                                               //      return 0; // no match
-                                       }
-                                       // otherwise move idx to next item
-                                       while (mappedChars [i] != 0)
-                                               i++;
-                                       idx += i + 1;
-                                       break;
-                               }
-                       }
-                       // reached to end of entries
-                       return 0;
-               }
-
                private static string Compose (string source, int checkType)
                {
                        StringBuilder sb = null;
-                       Decompose (source, ref sb, checkType);
+                       // Decompose to NFD or NKFD depending on our target
+                       Decompose (source, ref sb, checkType == 2 ? 3 : 1);
                        if (sb == null)
                                sb = Combine (source, 0, checkType);
                        else
@@ -155,57 +87,156 @@ namespace Mono.Globalization.Unicode
                        return (PropValue (i) & IsUnsafe) != 0;
                }
 */
-               private static void Combine (StringBuilder sb, int start, int checkType)
+               private static void Combine (StringBuilder sb, int i, int checkType)
                {
-                       for (int i = start; i < sb.Length; i++) {
-                               if (QuickCheck (sb [i], checkType) == NormalizationCheck.Yes)
-                                       continue;
+                       // Back off one character as we may be looking at a V or T jamo.
+                       CombineHangul (sb, null, i > 0 ? i - 1 : i);
 
-                               int cur = i;
-                               // FIXME: It should check "blocked" too
-                               for (;i > 0; i--) // this loop does not check sb[0], but regardless of the condition below it should not go under 0.
-                                       if (GetCombiningClass ((int) sb [i]) == 0)
-                                               break;
-
-                               int idx = 0; // index to mappedChars
-                               for (; i < cur; i++) {
-                                       idx = GetPrimaryCompositeMapIndex (sb, (int) sb [i], i);
-                                       if (idx > 0)
-                                               break;
-                               }
-                               if (idx == 0) {
-                                       i = cur;
+                       while (i < sb.Length) {
+                               if (QuickCheck (sb [i], checkType) == NormalizationCheck.Yes) {
+                                       i++;
                                        continue;
                                }
 
-                               int prim = GetPrimaryCompositeFromMapIndex (idx);
-                               int len = GetNormalizedStringLength (prim);
-                               if (prim == 0 || len == 0)
-                                       throw new SystemException ("Internal error: should not happen. Input: " + sb);
-                               int removed = 0;
-                               sb.Insert (i++, (char) prim); // always single character
+                               i = TryComposeWithPreviousStarter (sb, null, i);
+                       }
+               }
+
+               private static int CombineHangul (StringBuilder sb, string s, int current)
+               {
+                       int length = sb != null ? sb.Length : s.Length;
+                       int last = Fetch (sb, s, current);
 
-                               // handle blocked characters here.
-                               while (removed < len) {
-                                       if (sb [i] == mappedChars [idx + removed]) {
+                       for (int i = current + 1; i < length; ++i) {
+                               int ch = Fetch (sb, s, i);
+
+                               // 1. check to see if two current characters are L and V
+
+                               int LIndex = last - HangulLBase;
+                               if (0 <= LIndex && LIndex < HangulLCount) {
+                                       int VIndex = ch - HangulVBase;
+                                       if (0 <= VIndex && VIndex < HangulVCount) {
+                                               if (sb == null)
+                                                       return -1;
+
+                                               // make syllable of form LV
+
+                                               last = HangulSBase + (LIndex * HangulVCount + VIndex) * HangulTCount;
+
+                                               sb [i - 1] = (char) last; // reset last
                                                sb.Remove (i, 1);
-                                               removed++;
-                                               // otherwise, skip it.
+                                               i--; length--;
+                                               continue; // discard ch
+                                       }
+                               }
+
+
+                               // 2. check to see if two current characters are LV and T
+
+                               int SIndex = last - HangulSBase;
+                               if (0 <= SIndex && SIndex < HangulSCount && (SIndex % HangulTCount) == 0) {
+                                       int TIndex = ch - HangulTBase;
+                                       if (0 < TIndex && TIndex < HangulTCount) {
+                                               if (sb == null)
+                                                       return -1;
+
+                                               // make syllable of form LVT
+
+                                               last += TIndex;
+
+                                               sb [i - 1] = (char) last; // reset last
+                                               sb.Remove (i, 1);
+                                               i--; length--;
+                                               continue; // discard ch
                                        }
-                                       else
-                                               i++;
                                }
-                               i = cur - 1;
+                               // if neither case was true, just add the character
+                               last = ch;
                        }
+
+                       return length;
                }
 
-               static int GetPrimaryCompositeMapIndex (object o, int cur, int bufferPos)
+               static int Fetch (StringBuilder sb, string s, int i)
                {
-                       if ((PropValue (cur) & FullCompositionExclusion) != 0)
-                               return 0;
-                       if (GetCombiningClass (cur) != 0)
-                               return 0; // not a starter
-                       return GetPrimaryCompositeCharIndex (o, bufferPos);
+                       return (int) (sb != null ? sb [i] : s [i]);
+               }
+
+               // Cf. figure 7, section 1.3 of http://unicode.org/reports/tr15/.
+               static int TryComposeWithPreviousStarter (StringBuilder sb, string s, int current)
+               {
+                       // Backtrack to previous starter.
+                       int i = current - 1;
+                       if (GetCombiningClass (Fetch (sb, s, current)) == 0) {
+                               if (i < 0 || GetCombiningClass (Fetch (sb, s, i)) != 0)
+                                       return current + 1;
+                       } else {
+                               while (i >= 0 && GetCombiningClass (Fetch (sb, s, i)) != 0)
+                                       i--;
+                               if (i < 0)
+                                       return current + 1;
+                       }
+
+                       int starter = Fetch (sb, s, i);
+
+                       // The various decompositions involving starter follow this index.
+                       int comp_idx = GetPrimaryCompositeHelperIndex (starter);
+                       if (comp_idx == 0)
+                               return current + 1;
+
+                       int length = (sb != null ? sb.Length : s.Length);
+                       int prevCombiningClass = -1;
+                       for (int j = i + 1; j < length; j++) {
+                               int candidate = Fetch (sb, s, j);
+
+                               int combiningClass = GetCombiningClass (candidate);
+                               if (combiningClass == prevCombiningClass)
+                                       // We skipped over a guy with the same class, without
+                                       // combining.  Skip this one, too.
+                                       continue;
+
+                               int composed = TryCompose (comp_idx, starter, candidate);
+                               if (composed != 0) {
+                                       if (sb == null)
+                                               // Not normalized, and we are only checking.
+                                               return -1;
+
+                                       // Full Unicode warning: This will break when the underlying
+                                       // tables are extended.
+                                       sb [i] = (char) composed;
+                                       sb.Remove (j, 1);
+
+                                       return current;
+                               }
+
+                               // Gray box.  We're done.
+                               if (combiningClass == 0)
+                                       return j + 1;
+
+                               prevCombiningClass = combiningClass;
+                       }
+
+                       return length;
+               }
+
+               static int TryCompose (int i, int starter, int candidate)
+               {
+                       while (mappedChars [i] == starter) {
+                               if (mappedChars [i + 1] == candidate &&
+                                   mappedChars [i + 2] == 0) {
+                                       int composed = GetPrimaryCompositeFromMapIndex (i);
+
+                                       if ((PropValue (composed) & FullCompositionExclusion) == 0)
+                                               return composed;
+                               }
+
+                               // Skip this entry.
+                               while (mappedChars [i] != 0)
+                                       i++;
+                               i++;
+                       }
+
+                       return 0;
                }
 
                static string Decompose (string source, int checkType)
@@ -223,7 +254,7 @@ namespace Mono.Globalization.Unicode
                        for (int i = 0; i < source.Length; i++)
                                if (QuickCheck (source [i], checkType) == NormalizationCheck.No)
                                        DecomposeChar (ref sb, ref buf, source,
-                                               i, ref start);
+                                               i, checkType, ref start);
                        if (sb != null)
                                sb.Append (source, start, source.Length - start);
                        ReorderCanonical (source, ref sb, 1);
@@ -247,31 +278,32 @@ namespace Mono.Globalization.Unicode
                                return;
                        }
                        // check only with sb
-                       for (int i = start; i < sb.Length; i++) {
+                       for (int i = start; i < sb.Length; ) {
                                int level = GetCombiningClass (sb [i]);
-                               if (level == 0)
+                               if (level == 0 || GetCombiningClass (sb [i - 1]) <= level) {
+                                       i++;
                                        continue;
-                               if (GetCombiningClass (sb [i - 1]) > level) {
-                                       char c = sb [i - 1];
-                                       sb [i - 1] = sb [i];
-                                       sb [i] = c;
-                                       i--; // apply recursively
                                }
+
+                               char c = sb [i - 1];
+                               sb [i - 1] = sb [i];
+                               sb [i] = c;
+                               // Apply recursively.
+                               if (i > 1)
+                                       i--;
                        }
                }
 
                static void DecomposeChar (ref StringBuilder sb,
-                       ref int [] buf, string s, int i, ref int start)
+                       ref int [] buf, string s, int i, int checkType, ref int start)
                {
                        if (sb == null)
                                sb = new StringBuilder (s.Length + 100);
                        sb.Append (s, start, i - start);
                        if (buf == null)
                                buf = new int [19];
-                       GetCanonical (s [i], buf, 0);
-                       for (int x = 0; ; x++) {
-                               if (buf [x] == 0)
-                                       break;
+                       int n = GetCanonical (s [i], buf, 0, checkType);
+                       for (int x = 0; x < n; x++) {
                                if (buf [x] < char.MaxValue)
                                        sb.Append ((char) buf [x]);
                                else { // surrogate
@@ -345,11 +377,11 @@ namespace Mono.Globalization.Unicode
                                  HangulNCount = HangulVCount * HangulTCount,   // 588
                                  HangulSCount = HangulLCount * HangulNCount;   // 11172
 
-               private static bool GetCanonicalHangul (int s, int [] buf, int bufIdx)
+               private static int GetCanonicalHangul (int s, int [] buf, int bufIdx)
                {
                        int idx = s - HangulSBase;
                        if (idx < 0 || idx >= HangulSCount) {
-                               return false;
+                               return bufIdx;
                        }
 
                        int L = HangulLBase + idx / HangulNCount;
@@ -362,28 +394,49 @@ namespace Mono.Globalization.Unicode
                                buf [bufIdx++] = T;
                        }
                        buf [bufIdx] = (char) 0;
-                       return true;
+                       return bufIdx;
                }
 
-               public static void GetCanonical (int c, int [] buf, int bufIdx)
+               static int GetCanonical (int c, int [] buf, int bufIdx, int checkType)
                {
-                       if (!GetCanonicalHangul (c, buf, bufIdx)) {
-                               for (int i = CharMapIdx (c); mappedChars [i] != 0; i++)
-                                       buf [bufIdx++] = mappedChars [i];
-                               buf [bufIdx] = (char) 0;
+                       int newBufIdx = GetCanonicalHangul (c, buf, bufIdx);
+                       if (newBufIdx > bufIdx)
+                               return newBufIdx;
+                       int i = CharMapIdx (c);
+                       if (i == 0 || mappedChars [i] == c)
+                               buf [bufIdx++] = c;
+                       else {
+                               // Character c maps to one or more decomposed chars.
+                               for (; mappedChars [i] != 0; i++) {
+                                       int nth = mappedChars [i];
+
+                                       // http://www.unicode.org/reports/tr15/tr15-31.html, 1.3:
+                                       // Full decomposition involves recursive application of the
+                                       // Decomposition_Mapping values.  Note that QuickCheck does
+                                       // not currently support astral plane codepoints.
+                                       if (nth <= 0xffff && QuickCheck ((char)nth, checkType) == NormalizationCheck.Yes)
+                                               buf [bufIdx++] = nth;
+                                       else
+                                               bufIdx = GetCanonical (nth, buf, bufIdx, checkType);
+                               }
                        }
+
+                       return bufIdx;
                }
 
                public static bool IsNormalized (string source, int type)
                {
                        int prevCC = -1;
-                       for (int i = 0; i < source.Length; i++) {
+                       for (int i = 0; i < source.Length; ) {
                                int cc = GetCombiningClass (source [i]);
                                if (cc != 0 && cc < prevCC)
                                        return false;
                                prevCC = cc;
+
                                switch (QuickCheck (source [i], type)) {
                                case NormalizationCheck.Yes:
+                                       i++;
                                        break;
                                case NormalizationCheck.No:
                                        return false;
@@ -395,18 +448,14 @@ namespace Mono.Globalization.Unicode
                                                return source == Normalize (source, type);
                                        }
                                        // go on...
-                                       
-                                       // partly copied from Combine()
-                                       int cur = i;
-                                       for (;i > 0; i--) // this loop does not check sb[0], but regardless of the condition below it should not go under 0.
-                                               if (GetCombiningClass ((int) source [i]) == 0)
-                                                       break;
-                                       //i++;
-                                       // Now i is the "starter"
-                                       for (; i < cur; i++) {
-                                               if (GetPrimaryCompositeCharIndex (source, i) != 0)
-                                                       return false;
-                                       }
+
+                                       i = CombineHangul (null, source, i > 0 ? i - 1 : i);
+                                       if (i < 0)
+                                               return false;
+
+                                       i = TryComposeWithPreviousStarter (null, source, i);
+                                       if (i < 0)
+                                               return false;
                                        break;
                                }
                        }
index bd7ee4b69c43b67eb070aa43dbd172f6372855e6..c766628f6fcdffe440286567bf94b9e4254f072c 100644 (file)
@@ -27,7 +27,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System;
 using System.IO;
index 389b01ddd7fc993eb492799435b9431917147999..647fd419659486bdc75dda78b5744ecb80505f86 100644 (file)
@@ -27,7 +27,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System;
 using System.IO;
index e1b8d247c02caf1be64bf215cddaf1bfe6fadba7..07ce4c9f149c46f7f9f39a0927d5314df08aeb17 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * AuthenticodeBase.cs, AuthenticodeDeformatter.cs: use MOONLIGHT
+       symbol to disambiguate MonoTouch and Moonlight code.
+
 2009-04-30  Sebastien Pouliot  <sebastien@ximian.com> 
 
        * AuthenticodeBase.cs, AuthenticodeDeformatter.cs: Remove from NET_2_1
index 269daa3f55d069f2847c6f7ea610943a6b34a3f2..6ea278738869ffe05ba612b3585c39460f82e893 100644 (file)
@@ -1,3 +1,9 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * CryptoTools.cs, PKCS1.cs, PKCS8.cs, SymmetricTransform.cs,
+       KeyPairPersistence.cs: use MOONLIGHT symbol to disambiguate
+       MonoTouch and Moonlight code.
+
 2009-09-18  Sebastien Pouliot  <sebastien@ximian.com>
 
        * PKCS1.cs: Fix compiler warning for NET_2_1
index e79dc6f1564cf3efa5aea4aacc56a5f62b61573e..a39cd48f292e2a933727a165df60d3be4fd20b8e 100644 (file)
@@ -48,7 +48,7 @@ namespace Mono.Security.Cryptography {
 
                static RandomNumberGenerator Rng {
                        get {
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                                if (rng == null)
                                        rng = new RNGCryptoServiceProvider ();
 #else
index 9a2cad9ba6c99df20f6897aadfbda34cd156ea10..ac694bb5ef0d1d2721a43743de6e688ef642e00f 100644 (file)
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System;
 using System.Globalization;
index dc2e8389b3038b4dd7556ad6405d8097045b117b..6cf82682f7be2d92c319b1be2931d1a375bfd17d 100644 (file)
@@ -68,7 +68,7 @@ namespace Mono.Security.Cryptography {
        
                private static byte[] emptySHA1   = { 0xda, 0x39, 0xa3, 0xee, 0x5e, 0x6b, 0x4b, 0x0d, 0x32, 0x55, 0xbf, 0xef, 0x95, 0x60, 0x18, 0x90, 0xaf, 0xd8, 0x07, 0x09 };
                private static byte[] emptySHA256 = { 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55 };
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                private static byte[] emptySHA384 = { 0x38, 0xb0, 0x60, 0xa7, 0x51, 0xac, 0x96, 0x38, 0x4c, 0xd9, 0x32, 0x7e, 0xb1, 0xb1, 0xe3, 0x6a, 0x21, 0xfd, 0xb7, 0x11, 0x14, 0xbe, 0x07, 0x43, 0x4c, 0x0c, 0xc7, 0xbf, 0x63, 0xf6, 0xe1, 0xda, 0x27, 0x4e, 0xde, 0xbf, 0xe7, 0x6f, 0x65, 0xfb, 0xd5, 0x1a, 0xd2, 0xf1, 0x48, 0x98, 0xb9, 0x5b };
                private static byte[] emptySHA512 = { 0xcf, 0x83, 0xe1, 0x35, 0x7e, 0xef, 0xb8, 0xbd, 0xf1, 0x54, 0x28, 0x50, 0xd6, 0x6d, 0x80, 0x07, 0xd6, 0x20, 0xe4, 0x05, 0x0b, 0x57, 0x15, 0xdc, 0x83, 0xf4, 0xa9, 0x21, 0xd3, 0x6c, 0xe9, 0xce, 0x47, 0xd0, 0xd1, 0x3c, 0x5d, 0x85, 0xf2, 0xb0, 0xff, 0x83, 0x18, 0xd2, 0x87, 0x7e, 0xec, 0x2f, 0x63, 0xb9, 0x31, 0xbd, 0x47, 0x41, 0x7a, 0x81, 0xa5, 0x38, 0x32, 0x7a, 0xf9, 0x27, 0xda, 0x3e };
 #endif
@@ -79,7 +79,7 @@ namespace Mono.Security.Cryptography {
                                return emptySHA1;
                        else if (hash is SHA256)
                                return emptySHA256;
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        else if (hash is SHA384)
                                return emptySHA384;
                        else if (hash is SHA512)
index 577c8310be29f44daed0e3c9f8e8e2f584914c60..84b830f245835b9db8069e4f126f7261a636fa1f 100644 (file)
@@ -272,7 +272,7 @@ namespace Mono.Security.Cryptography {
                                param.InverseQ = Normalize (privateKey [8].Value, keysize2);
                                param.P = Normalize (privateKey [4].Value, keysize2);
                                param.Q = Normalize (privateKey [5].Value, keysize2);
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                                RSA rsa = RSA.Create ();
                                rsa.ImportParameters (param);
 #else
index 49982ba229ac9ff3886f82a0092af6406123ad5c..bda13d875c517bb0d079b9f005f7b311c332d528 100644 (file)
@@ -50,7 +50,7 @@ namespace Mono.Security.Cryptography {
                private byte[] temp2;
                private byte[] workBuff;
                private byte[] workout;
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                // Silverlight 2.0 does not support any feedback mode
                private int FeedBackByte;
                private int FeedBackIter;
@@ -79,7 +79,7 @@ namespace Mono.Security.Cryptography {
                        temp = new byte [BlockSizeByte];
                        Buffer.BlockCopy (rgbIV, 0, temp, 0, System.Math.Min (BlockSizeByte, rgbIV.Length));
                        temp2 = new byte [BlockSizeByte];
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        FeedBackByte = (algo.FeedbackSize >> 3);
                        if (FeedBackByte != 0)
                                FeedBackIter = (int) BlockSizeByte / FeedBackByte;
@@ -136,7 +136,7 @@ namespace Mono.Security.Cryptography {
                // i.e. Any padding must be done before calling this method
                protected virtual void Transform (byte[] input, byte[] output) 
                {
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        // Silverlight 2.0 only supports CBC
                        CBC (input, output);
 #else
@@ -183,7 +183,7 @@ namespace Mono.Security.Cryptography {
                        }
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                // Cipher-FeedBack (CFB)
                protected virtual void CFB (byte[] input, byte[] output) 
                {
@@ -254,7 +254,7 @@ namespace Mono.Security.Cryptography {
 
                        // ordered to avoid possible integer overflow
                        int len = outputBuffer.Length - inputCount - outputOffset;
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        // only PKCS7 is supported Silverlight 2.0
                        if (KeepLastBlock) {
 #else
@@ -279,7 +279,7 @@ namespace Mono.Security.Cryptography {
 
                private bool KeepLastBlock {
                        get {
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                                // only PKCS7 is supported Silverlight 2.0
                                return !encrypt;
 #else
@@ -334,7 +334,7 @@ namespace Mono.Security.Cryptography {
                        return total;
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                RandomNumberGenerator _rng;
 
                private void Random (byte[] buffer, int start, int length)
@@ -365,7 +365,7 @@ namespace Mono.Security.Cryptography {
                        int rem = inputCount - full;
                        int total = full;
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        // only PKCS7 is supported Silverlight 2.0
                        total += BlockSizeByte;
 #else
@@ -407,7 +407,7 @@ namespace Mono.Security.Cryptography {
 
                        // now we only have a single last block to encrypt
                        byte padding = (byte) (BlockSizeByte - rem);
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        // only PKCS7 is supported Silverlight 2.0
                        for (int i = res.Length; --i >= (res.Length - padding);) 
                                res [i] = padding;
@@ -474,7 +474,7 @@ namespace Mono.Security.Cryptography {
 
                        // total may be 0 (e.g. PaddingMode.None)
                        byte padding = ((total > 0) ? res [total - 1] : (byte) 0);
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        // only PKCS7 is supported Silverlight 2.0
                        if ((padding == 0) || (padding > BlockSizeByte))
                                throw new CryptographicException (Locale.GetText ("Bad padding length."));
index 23e3e27ca28435513fbb3a4d9e81a380d0ca9306..96c08c9e9a5efb34db298e3b77c608b87912d6e5 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * X509Certificate.cs: use MOONLIGHT symbol to disambiguate
+       MonoTouch and Moonlight code.
+
 2009-04-30  Sebastien Pouliot  <sebastien@ximian.com> 
 
        * X509Certificate.cs: Adapt to work with only [DSA|RSA]Managed when
index fd8d8d9164c6580ba7ad0aafa1e540c6d5997a64..e1f5f9b2286423f8f11b15051ef38e4ac971b6b4 100644 (file)
@@ -267,7 +267,7 @@ namespace Mono.Security.X509 {
                                        // BUG: MS BCL 1.0 can't import a key which 
                                        // isn't the same size as the one present in
                                        // the container.
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                                        _dsa = new DSAManaged (dsaParams.Y.Length << 3);
 #else
                                        _dsa = (DSA) new DSACryptoServiceProvider (dsaParams.Y.Length << 3);
@@ -367,7 +367,7 @@ namespace Mono.Security.X509 {
                                        // isn't the same size as the one present in
                                        // the container.
                                        int keySize = (rsaParams.Modulus.Length << 3);
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                                        _rsa = new RSAManaged (keySize);
 #else
                                        _rsa = (RSA) new RSACryptoServiceProvider (keySize);
@@ -544,7 +544,7 @@ namespace Mono.Security.X509 {
 
                public bool CheckSignature (byte[] hash, string hashAlgorithm, byte[] signature) 
                {
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        string hashName = GetHashNameFromOID (hashAlgorithm);
                        HashAlgorithm algo = HashAlgorithm.Create (hashName);
                        return PKCS1.Verify_v15 (RSA, algo, hash, signature);
index c878a999eacc0b5e21d4d57f24694283e50fa37c..3a1cf930183b92155e5fd1b872a803f6496de0e5 100644 (file)
@@ -206,7 +206,7 @@ namespace Mono.Security {
                                        mask = "yyyyMMddHHmmsszzz";
                                        break;
                        }
-                       return DateTime.ParseExact (t, mask, null, DateTimeStyles.AdjustToUniversal);
+                       return DateTime.ParseExact (t, mask, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
                }
        }
 }
index 6f406ac13a5c641de0110bb88736ac3ffe9fa6ef..9fe0c26ef4750b4f93a08b8564784e455552b954 100644 (file)
@@ -1,3 +1,13 @@
+2010-03-24  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * ASN1Convert.cs: Specify CultureInfo.InvariantCulture (instead of 
+       null) to avoid crash on Windows. Patch by Yoni Shalom.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * StrongName.cs: use MOONLIGHT symbol to disambiguate
+       MonoTouch and Moonlight code.
+
 2009-09-22  Sebastien Pouliot  <sebastien@ximian.com> 
 
        * StrongName.cs: Moonlight NET_2_1 cannot depend on machine.config
index 64a1a38092e8d22904e0b0252fe9bb618526e4c9..2905a03c125c4a9302b0249f588504d2d4bae5cd 100644 (file)
@@ -160,7 +160,7 @@ namespace Mono.Security {
                        get {
                                if (rsa == null)
                                        return false;
-#if INSIDE_CORLIB && (!NET_2_1 || MONOTOUCH)
+#if INSIDE_CORLIB && !MOONLIGHT
                                // the easy way
                                if (RSA is RSACryptoServiceProvider) {
                                        // available as internal for corlib
index 953c63fc2a16929915d7de6d2d1401b3be8c06ac..9636fb1bda3ad123e3c4b73a611db16564ae8b25 100644 (file)
@@ -47,19 +47,6 @@ namespace Mono {
                // Format is undefined only for use as a string for reporting
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
                internal static extern string GetDisplayName ();
-
-               /*
-               Create a object without calling any of it's constructors.
-               @h is a pointer to the runtime type handle of that object.              
-               Recomended usage is to emit the following code sequence:
-               ldtoken [mscorlib]System.Object
-               call object [mscorlib]Mono.Runtime::NewObject(intptr)
-
-               This is the only well understood sequence known by the JIT
-               which produces faster code.
-               */
-               [MethodImplAttribute (MethodImplOptions.InternalCall)]
-               internal static extern object NewObject (RuntimeTypeHandle h);
        }
        
 }
index a180eb6fee11b04d78e59ebc6885c4835cd147cc..310e0b3467b47d87cee2c7b805512df6d7571582 100644 (file)
@@ -1,3 +1,29 @@
+2010-04-15  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * ConcurrentDictionary.cs:
+       * ConcurrentSkipList.cs:
+       * OrderablePartitioner.cs:
+       * Partitioner.cs: Add BOOTSTRAP_NET_4_0 define
+
+2010-03-24  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * ConcurrentDictionary.cs: Remove while looping
+
+2010-03-24  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * ConcurrentDictionary.cs: Enable tracking on SpinLock
+       * ConcurrentSkipList.cs: Use Spinlock instead of Monitor and
+       refactor to use a saner lock acquiring scheme.
+
+2010-03-24  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * ConcurrentDictionary.cs: Fix lock releasing
+
+2010-03-24  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * ConcurrentDictionary.cs: Use SpinLock instead of Monitor
+       for basket locking
+
 2010-02-02  Jérémie Laval  <jeremie.laval@gmail.com>
 
        * ConcurrentDictionary.cs:
index 3bc6d5c10577e49ca1eb7c22c6176ba952591a55..fb0774cee2ea84a6e69134fbfa6b13bc0f294fd6 100644 (file)
@@ -1,4 +1,3 @@
-#if NET_4_0
 // ConcurrentSkipList.cs
 //
 // Copyright (c) 2009 Jérémie "Garuma" Laval
@@ -29,118 +28,129 @@ using System.Collections;
 using System.Collections.Generic;
 using System.Runtime.Serialization;
 
+#if NET_4_0 || BOOTSTRAP_NET_4_0
+
 namespace System.Collections.Concurrent
 {
-       public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>, 
-         ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, 
+       public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>,
+         ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>,
          IDictionary, ICollection, IEnumerable
        {
                class Pair
                {
                        public readonly TKey Key;
                        public TValue Value;
-                       
+
                        public Pair (TKey key, TValue value)
                        {
                                Key = key;
                                Value = value;
                        }
-                       
+
                        public override bool Equals (object obj)
                        {
                                Pair rhs = obj as Pair;
                                return rhs == null ? false : Key.Equals (rhs.Key) && Value.Equals (rhs.Value);
                        }
-                       
+
                        public override int GetHashCode ()
                        {
                                return Key.GetHashCode ();
                        }
                }
-               
+
                class Basket: List<Pair>
                {
+                       public SpinLock Lock = new SpinLock (true);
                }
-               
+
                // Assumption: a List<T> is never empty
                ConcurrentSkipList<Basket> container
                        = new ConcurrentSkipList<Basket> ((value) => value[0].GetHashCode ());
                int count;
                IEqualityComparer<TKey> comparer;
-               
+
                public ConcurrentDictionary () : this (EqualityComparer<TKey>.Default)
                {
                }
-               
+
                public ConcurrentDictionary (IEnumerable<KeyValuePair<TKey, TValue>> values)
                        : this (values, EqualityComparer<TKey>.Default)
                {
                        foreach (KeyValuePair<TKey, TValue> pair in values)
                                Add (pair.Key, pair.Value);
                }
-               
+
                public ConcurrentDictionary (IEqualityComparer<TKey> comparer)
                {
                        this.comparer = comparer;
                }
-               
+
                public ConcurrentDictionary (IEnumerable<KeyValuePair<TKey, TValue>> values, IEqualityComparer<TKey> comparer)
                        : this (comparer)
-               {                       
+               {
                        foreach (KeyValuePair<TKey, TValue> pair in values)
                                Add (pair.Key, pair.Value);
                }
-               
+
                // Parameters unused
                public ConcurrentDictionary (int concurrencyLevel, int capacity)
                        : this (EqualityComparer<TKey>.Default)
                {
-                       
+
                }
-               
-               public ConcurrentDictionary (int concurrencyLevel, 
+
+               public ConcurrentDictionary (int concurrencyLevel,
                                             IEnumerable<KeyValuePair<TKey, TValue>> values,
                                             IEqualityComparer<TKey> comparer)
                        : this (values, comparer)
                {
-                       
+
                }
-               
+
                // Parameters unused
                public ConcurrentDictionary (int concurrencyLevel, int capacity, IEqualityComparer<TKey> comparer)
                        : this (comparer)
                {
-                       
+
                }
-               
+
                void Add (TKey key, TValue value)
                {
                        while (!TryAdd (key, value));
                }
-               
+
                void IDictionary<TKey, TValue>.Add (TKey key, TValue value)
                {
                        Add (key, value);
                }
-               
+
                public bool TryAdd (TKey key, TValue value)
-               {                       
+               {
+                       if (key == null)
+                               throw new ArgumentNullException ("key");
                        Basket basket;
+                       bool taken = false;
+
                        // Add a value to an existing basket
                        if (TryGetBasket (key, out basket)) {
-                               // Find a maybe more sexy locking scheme later
-                               lock (basket) {
+                               try {
+                                       basket.Lock.Enter (ref taken);
+
                                        foreach (var p in basket) {
                                                if (comparer.Equals (p.Key, key))
-                                                       throw new ArgumentException ("An element with the same key already exists");
+                                                       return false;
                                        }
                                        basket.Add (new Pair (key, value));
+                               } finally {
+                                       if (taken)
+                                               basket.Lock.Exit ();
                                }
                        } else {
                                // Add a new basket
                                basket = new Basket ();
                                basket.Add (new Pair (key, value));
-                               
+
                                if (container.TryAdd (basket)) {
                                        Interlocked.Increment (ref count);
                                        return true;
@@ -148,41 +158,47 @@ namespace System.Collections.Concurrent
                                        return false;
                                }
                        }
-                       
+
                        Interlocked.Increment (ref count);
-                       
+
                        return true;
                }
-               
+
                void ICollection<KeyValuePair<TKey,TValue>>.Add (KeyValuePair<TKey, TValue> pair)
                {
                        Add (pair.Key, pair.Value);
                }
-               
+
                public TValue AddOrUpdate (TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory)
                {
                        Basket basket;
-                       TValue temp;
-                       
+                       TValue temp = default (TValue);
+                       bool taken = false;
+
                        if (!TryGetBasket (key, out basket)) {
                                Add (key, (temp = addValueFactory (key)));
                        } else {
-                               lock (basket) {
+                               try {
+                                       basket.Lock.Enter (ref taken);
+
                                        Pair pair = basket.Find ((p) => comparer.Equals (p.Key, key));
                                        if (pair == null)
                                                throw new InvalidOperationException ("pair is null, shouldn't be");
                                        pair.Value = (temp = updateValueFactory (key, pair.Value));
+                               } finally {
+                                       if (taken)
+                                               basket.Lock.Exit ();
                                }
                        }
-                       
+
                        return temp;
                }
-               
+
                public TValue AddOrUpdate (TKey key, TValue addValue, Func<TKey, TValue, TValue> updateValueFactory)
                {
                        return AddOrUpdate (key, (_) => addValue, updateValueFactory);
                }
-               
+
                TValue GetValue (TKey key)
                {
                        TValue temp;
@@ -191,98 +207,129 @@ namespace System.Collections.Concurrent
                                throw new ArgumentException ("Not a valid key for this dictionary", "key");
                        return temp;
                }
-               
+
                public bool TryGetValue (TKey key, out TValue value)
                {
                        Basket basket;
                        value = default (TValue);
-                       
+                       bool taken = false;
+
                        if (!TryGetBasket (key, out basket))
                                return false;
-                       
-                       lock (basket) {
+
+                       try {
+                               basket.Lock.Enter (ref taken);
+
                                Pair pair = basket.Find ((p) => comparer.Equals (p.Key, key));
                                if (pair == null)
                                        return false;
                                value = pair.Value;
+                       } finally {
+                               if (taken)
+                                       basket.Lock.Exit ();
                        }
-                       
+
                        return true;
                }
-               
+
                public bool TryUpdate (TKey key, TValue newValue, TValue comparand)
                {
                        Basket basket;
+                       bool taken = false;
+
                        if (!TryGetBasket (key, out basket))
                                return false;
-                       
-                       lock (basket) {
+
+                       try {
+                               basket.Lock.Enter (ref taken);
+
                                Pair pair = basket.Find ((p) => comparer.Equals (p.Key, key));
                                if (pair.Value.Equals (comparand)) {
                                        pair.Value = newValue;
-                                       
+
                                        return true;
                                }
+                       } finally {
+                               if (taken)
+                                       basket.Lock.Exit ();
                        }
-                       
+
                        return false;
                }
-               
+
                public TValue this[TKey key] {
                        get {
                                return GetValue (key);
                        }
                        set {
                                Basket basket;
+                               bool taken = false;
+
                                if (!TryGetBasket (key, out basket)) {
                                        Add (key, value);
                                        return;
                                }
-                               lock (basket) {
+
+                               try {
+                                       basket.Lock.Enter (ref taken);
+
                                        Pair pair = basket.Find ((p) => comparer.Equals (p.Key, key));
                                        if (pair == null)
                                                throw new InvalidOperationException ("pair is null, shouldn't be");
                                        pair.Value = value;
+                               } finally {
+                                       if (taken)
+                                               basket.Lock.Exit ();
                                }
                        }
                }
-               
+
                public TValue GetOrAdd (TKey key, Func<TKey, TValue> valueFactory)
                {
                        Basket basket;
                        TValue temp = default (TValue);
-                       
+
                        if (TryGetBasket (key, out basket)) {
                                Pair pair = null;
-                               lock (basket) {
+                               bool taken = false;
+
+                               try {
+                                       basket.Lock.Enter (ref taken);
+
                                        pair = basket.Find ((p) => comparer.Equals (p.Key, key));
                                        if (pair != null)
                                                temp = pair.Value;
+                               } finally {
+                                       if (taken)
+                                               basket.Lock.Exit ();
                                }
-                               
+
                                if (pair == null)
                                        Add (key, (temp = valueFactory (key)));
                        } else {
                                Add (key, (temp = valueFactory (key)));
                        }
-                       
+
                        return temp;
                }
-               
+
                public TValue GetOrAdd (TKey key, TValue value)
                {
                        return GetOrAdd (key, (_) => value);
                }
-               
+
                public bool TryRemove(TKey key, out TValue value)
                {
                        value = default (TValue);
                        Basket b;
-                       
+                       bool taken = false;
+
                        if (!TryGetBasket (key, out b))
                                return false;
-                       
-                       lock (b) {
+
+                       try {
+                               b.Lock.Enter (ref taken);
+
                                TValue temp = default (TValue);
                                // Should always be == 1 but who know
                                bool result = b.RemoveAll ((p) => {
@@ -291,275 +338,294 @@ namespace System.Collections.Concurrent
                                        return r;
                                }) >= 1;
                                value = temp;
-                               
+
                                if (result)
                                        Interlocked.Decrement (ref count);
-                               
+
                                return result;
+                       } finally {
+                               if (taken)
+                                       b.Lock.Exit ();
                        }
+
+                       return false;
                }
-               
+
                bool Remove (TKey key)
                {
                        TValue dummy;
-                       
+
                        return TryRemove (key, out dummy);
                }
-               
+
                bool IDictionary<TKey, TValue>.Remove (TKey key)
                {
                        return Remove (key);
                }
-               
+
                bool ICollection<KeyValuePair<TKey,TValue>>.Remove (KeyValuePair<TKey,TValue> pair)
                {
                        return Remove (pair.Key);
                }
-               
+
                public bool ContainsKey (TKey key)
                {
                        return container.ContainsFromHash (key.GetHashCode ());
                }
-               
+
                bool IDictionary.Contains (object key)
                {
                        if (!(key is TKey))
                                return false;
-                       
+
                        return ContainsKey ((TKey)key);
                }
-               
+
                void IDictionary.Remove (object key)
                {
                        if (!(key is TKey))
                                return;
-                       
+
                        Remove ((TKey)key);
                }
-               
+
                object IDictionary.this [object key]
                {
                        get {
                                if (!(key is TKey))
                                        throw new ArgumentException ("key isn't of correct type", "key");
-                               
+
                                return this[(TKey)key];
                        }
                        set {
                                if (!(key is TKey) || !(value is TValue))
                                        throw new ArgumentException ("key or value aren't of correct type");
-                               
+
                                this[(TKey)key] = (TValue)value;
                        }
                }
-               
+
                void IDictionary.Add (object key, object value)
                {
                        if (!(key is TKey) || !(value is TValue))
                                throw new ArgumentException ("key or value aren't of correct type");
-                       
+
                        Add ((TKey)key, (TValue)value);
                }
-               
+
                bool ICollection<KeyValuePair<TKey,TValue>>.Contains (KeyValuePair<TKey, TValue> pair)
                {
                        return ContainsKey (pair.Key);
                }
-               
+
                public KeyValuePair<TKey,TValue>[] ToArray ()
                {
                        // This is most certainly not optimum but there is
                        // not a lot of possibilities
-                       
+
                        return new List<KeyValuePair<TKey,TValue>> (this).ToArray ();
                }
-       
+
                public void Clear()
                {
                        // Pronk
                        container = new ConcurrentSkipList<Basket> ((value) => value [0].GetHashCode ());
                }
-               
+
                public int Count {
                        get {
                                return count;
                        }
                }
-               
+
                public bool IsEmpty {
                        get {
                                return count == 0;
                        }
                }
-               
+
                bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly {
                        get {
                                return false;
                        }
                }
-               
+
                bool IDictionary.IsReadOnly {
                        get {
                                return false;
                        }
                }
-               
+
                public ICollection<TKey> Keys {
                        get {
                                return GetPart<TKey> ((kvp) => kvp.Key);
                        }
                }
-               
+
                public ICollection<TValue> Values {
                        get {
                                return GetPart<TValue> ((kvp) => kvp.Value);
                        }
                }
-               
+
                ICollection IDictionary.Keys {
                        get {
                                return (ICollection)Keys;
                        }
                }
-               
+
                ICollection IDictionary.Values {
                        get {
                                return (ICollection)Values;
                        }
                }
-               
+
                ICollection<T> GetPart<T> (Func<KeyValuePair<TKey, TValue>, T> extractor)
                {
                        List<T> temp = new List<T> ();
-                       
+
                        foreach (KeyValuePair<TKey, TValue> kvp in this)
                                temp.Add (extractor (kvp));
-                       
+
                        return temp.AsReadOnly ();
                }
-               
+
                void ICollection.CopyTo (Array array, int startIndex)
                {
                        KeyValuePair<TKey, TValue>[] arr = array as KeyValuePair<TKey, TValue>[];
                        if (arr == null)
                                return;
-                       
+
                        CopyTo (arr, startIndex, count);
                }
-               
+
                void CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex)
                {
                        CopyTo (array, startIndex, count);
                }
-               
+
                void ICollection<KeyValuePair<TKey, TValue>>.CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex)
                {
                        CopyTo (array, startIndex);
                }
-               
+
                void CopyTo (KeyValuePair<TKey, TValue>[] array, int startIndex, int num)
                {
                        // TODO: This is quite unsafe as the count value will likely change during
                        // the copying. Watchout for IndexOutOfRange thingies
                        if (array.Length <= count + startIndex)
                                throw new InvalidOperationException ("The array isn't big enough");
-                       
+
                        int i = startIndex;
-                       
+
                        foreach (Basket b in container) {
-                               lock (b) {
+                               bool taken = false;
+
+                               try {
+                                       b.Lock.Enter (ref taken);
+
                                        foreach (Pair p in b) {
                                                if (i >= num)
                                                        break;
                                                array[i++] = new KeyValuePair<TKey, TValue> (p.Key, p.Value);
                                        }
+                               } finally {
+                                       if (taken)
+                                               b.Lock.Exit ();
                                }
                        }
                }
-               
+
                public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator ()
                {
                        return GetEnumeratorInternal ();
                }
-               
+
                IEnumerator IEnumerable.GetEnumerator ()
                {
                        return (IEnumerator)GetEnumeratorInternal ();
                }
-               
+
                IEnumerator<KeyValuePair<TKey, TValue>> GetEnumeratorInternal ()
-               {       
+               {
                        foreach (Basket b in container) {
-                               lock (b) {
+                               bool taken = false;
+
+                               try {
+                                       b.Lock.Enter (ref taken);
+
                                        foreach (Pair p in b)
                                                yield return new KeyValuePair<TKey, TValue> (p.Key, p.Value);
+                               } finally {
+                                       if (taken)
+                                               b.Lock.Exit ();
                                }
                        }
                }
-               
+
                IDictionaryEnumerator IDictionary.GetEnumerator ()
                {
                        return new ConcurrentDictionaryEnumerator (GetEnumeratorInternal ());
                }
-               
+
                class ConcurrentDictionaryEnumerator : IDictionaryEnumerator
                {
                        IEnumerator<KeyValuePair<TKey, TValue>> internalEnum;
-                       
+
                        public ConcurrentDictionaryEnumerator (IEnumerator<KeyValuePair<TKey, TValue>> internalEnum)
                        {
                                this.internalEnum = internalEnum;
                        }
-                       
+
                        public bool MoveNext ()
                        {
                                return internalEnum.MoveNext ();
                        }
-                       
+
                        public void Reset ()
                        {
                                internalEnum.Reset ();
                        }
-                       
+
                        public object Current {
                                get {
                                        return Entry;
                                }
                        }
-                       
+
                        public DictionaryEntry Entry {
                                get {
                                        KeyValuePair<TKey, TValue> current = internalEnum.Current;
                                        return new DictionaryEntry (current.Key, current.Value);
                                }
                        }
-                       
+
                        public object Key {
                                get {
                                        return internalEnum.Current.Key;
                                }
                        }
-                       
+
                        public object Value {
                                get {
                                        return internalEnum.Current.Value;
                                }
                        }
                }
-               
+
                object ICollection.SyncRoot {
                        get {
                                return this;
                        }
                }
 
-               
+
                bool IDictionary.IsFixedSize {
                        get {
                                return false;
                        }
                }
-               
+
                bool ICollection.IsSynchronized {
                        get { return true; }
                }
@@ -569,7 +635,7 @@ namespace System.Collections.Concurrent
                        basket = null;
                        if (!container.GetFromHash (key.GetHashCode (), out basket))
                                return false;
-                       
+
                        return true;
                }
        }
index 57e267c2ab58fd399f92adc26447cfa84e444365..e8c637f7ebd5d2b46797da33bb0b148c1cda880a 100644 (file)
@@ -1,4 +1,4 @@
-#if NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0
 // ConcurrentSkipList.cs
 //
 // Copyright (c) 2008 Jérémie "Garuma" Laval
@@ -30,22 +30,24 @@ using System.Collections.Generic;
 
 namespace System.Collections.Concurrent
 {
-       
+
        internal class ConcurrentSkipList<T> : IProducerConsumerCollection<T>
        {
                // Used for randomSeed
                [ThreadStatic]
                static Random r;
                // Used in FindNodes and thus most others methods
-               // avoid heavy local array creation at each method call and use 
+               // avoid heavy local array creation at each method call and use
                // for thread locallity ThreadStatic attribute
-               [ThreadStaticAttribute]
-               static Node[] preds;
-               [ThreadStaticAttribute]
-               static Node[] succs;
+               [ThreadStatic]
+               static Node[] precedents;
+               [ThreadStatic]
+               static Node[] succedings;
+               [ThreadStatic]
+               static bool[] takenLocks;
 
                int count = 0;
-               
+
                class Node
                {
                        public readonly int      Key;
@@ -54,7 +56,7 @@ namespace System.Collections.Concurrent
                        public readonly Node[]   Nexts;
                        public volatile bool     Marked;
                        public volatile bool     FullyLinked;
-                       public readonly object   Lock;
+                       public SpinLock  Lock;
 
                        public Node (int key, T value, int heightValue)
                        {
@@ -62,7 +64,7 @@ namespace System.Collections.Concurrent
                                Value = value;
                                TopLayer = heightValue;
                                Nexts = new Node [heightValue + 1];
-                               Lock = new object ();
+                               Lock = new SpinLock (true);
                                Marked = FullyLinked = false;
                        }
                }
@@ -83,7 +85,7 @@ namespace System.Collections.Concurrent
                        : this ((value) => comparer.GetHashCode (value))
                {
                }
-               
+
                public ConcurrentSkipList(Func<T, int> hasher)
                {
                        GetKey = hasher;
@@ -92,11 +94,6 @@ namespace System.Collections.Concurrent
 
                void Init ()
                {
-                       if (succs == null)
-                               succs = new Node [MaxHeight];
-                       if (preds == null)
-                               preds = new Node [MaxHeight];
-                       
                        leftSentinel = new Node (int.MinValue, default (T), MaxHeight);
                        rightSentinel = new Node (int.MaxValue, default (T), MaxHeight);
 
@@ -106,46 +103,46 @@ namespace System.Collections.Concurrent
                        // The or ensures that randomSeed != 0
                        randomSeed = ((uint)Math.Abs (Next())) | 0x0100;
                }
-               
+
                public bool TryAdd (T value)
                {
                        if (value == null)
                                throw new ArgumentNullException ("value");
-                       
+
                        CleanArrays ();
                        int topLayer = GetRandomLevel ();
 
                        int v = GetKey (value);
 
                        while (true) {
-                               int found = FindNode (v, preds, succs);
+                               int found = FindNode (v, precedents, succedings);
                                if (found != -1) {
                                        // A node with the same key already exists
-                                       Node nodeFound = succs [found];
+                                       Node nodeFound = succedings [found];
                                        if (!nodeFound.Marked) {
                                                SpinWait sw = new SpinWait ();
-                                               while (!nodeFound.FullyLinked) {
+                                               while (!nodeFound.FullyLinked)
                                                        sw.SpinOnce ();
-                                               }
+
                                                return false;
                                        }
                                        continue;
                                }
                                int highestLocked = -1;
                                try {
-                                       bool valid = LockNodes (topLayer, ref highestLocked,
+                                       bool valid = LockNodes (topLayer, ref highestLocked, precedents, succedings,
                                                                (layer, pred, succ) => !pred.Marked && !succ.Marked && pred.Nexts [layer] == succ);
                                        if (!valid)
                                                continue;
-                                               
+
                                        Node newNode = new Node (v, value, topLayer);
                                        for (int layer = 0; layer <= topLayer; layer++) {
-                                               newNode.Nexts [layer] = succs [layer];
-                                               preds [layer].Nexts [layer] = newNode;
+                                               newNode.Nexts [layer] = succedings [layer];
+                                               precedents [layer].Nexts [layer] = newNode;
                                        }
                                        newNode.FullyLinked = true;
                                } finally {
-                                       Unlock (preds, highestLocked);
+                                       Unlock (precedents, takenLocks, highestLocked);
                                }
                                Interlocked.Increment (ref count);
                                return true;
@@ -161,7 +158,7 @@ namespace System.Collections.Concurrent
                {
                        int countSnapshot = count;
                        T[] temp = new T [countSnapshot];
-                       
+
                        CopyTo(temp, 0);
 
                        return temp;
@@ -203,7 +200,7 @@ namespace System.Collections.Concurrent
                {
                        if (value == null)
                                throw new ArgumentNullException ("value");
-                       
+
                        CleanArrays();
                        Node toDelete = null;
                        bool isMarked = false;
@@ -211,36 +208,39 @@ namespace System.Collections.Concurrent
                        int v = GetKey (value);
 
                        while (true) {
-                               int found = FindNode (v, preds, succs);
-                               
-                               if (isMarked || (found != -1 && OkToDelete (succs [found], found))) {
+                               int found = FindNode (v, precedents, succedings);
+                               bool taken = false;
+                               int highestLocked = -1;
+
+                               if (isMarked || (found != -1 && OkToDelete (succedings [found], found))) {
                                        // If not marked then logically delete the node
-                                       if (!isMarked) {
-                                               toDelete = succs [found];
-                                               topLayer = toDelete.TopLayer;
-                                               Monitor.Enter (toDelete.Lock);
-                                               // Now that we have the lock, check if the node hasn't already been marked
-                                               if (toDelete.Marked) {
-                                                       Monitor.Exit (toDelete.Lock);
-                                                       return false;
-                                               }
-                                               toDelete.Marked = true;
-                                               isMarked = true;
-                                       }
-                                       int highestLocked = -1;
                                        try {
-                                               bool valid = LockNodes (topLayer, ref highestLocked,
+                                               if (!isMarked) {
+                                                       toDelete = succedings [found];
+                                                       topLayer = toDelete.TopLayer;
+
+                                                       toDelete.Lock.Enter (ref taken);
+                                                       // Now that we have the lock, check if the node hasn't already been marked
+                                                       if (toDelete.Marked)
+                                                               return false;
+
+                                                       toDelete.Marked = true;
+                                                       isMarked = true;
+                                               }
+
+                                               bool valid = LockNodes (topLayer, ref highestLocked, precedents, succedings,
                                                                        (layer, pred, succ) => !pred.Marked && pred.Nexts [layer] == succ);
                                                if (!valid)
                                                        continue;
 
-                                               for (int layer = topLayer; layer >= 0; layer--) {
-                                                       preds [layer].Nexts [layer] = toDelete.Nexts [layer];
-                                               }
-                                               Monitor.Exit (toDelete.Lock);
+                                               for (int layer = topLayer; layer >= 0; layer--)
+                                                       precedents [layer].Nexts [layer] = toDelete.Nexts [layer];
                                        } finally {
-                                               Unlock (preds, highestLocked);
+                                               if (taken)
+                                                       toDelete.Lock.Exit ();
+                                               Unlock (precedents, takenLocks, highestLocked);
                                        }
+
                                        Interlocked.Decrement (ref count);
                                        return true;
                                } else {
@@ -253,38 +253,42 @@ namespace System.Collections.Concurrent
                {
                        if (value == null)
                                throw new ArgumentNullException ("value");
-                       
+
                        return ContainsFromHash (GetKey (value));
                }
-               
+
                internal bool ContainsFromHash (int hash)
                {
                        CleanArrays ();
-                       int found = FindNode (hash, preds, succs);
-                       return found != -1 && succs [found].FullyLinked && !succs [found].Marked;
+                       int found = FindNode (hash, precedents, succedings);
+                       return found != -1 && succedings [found].FullyLinked && !succedings [found].Marked;
                }
-               
+
                internal bool GetFromHash (int hash, out T value)
                {
                        value = default (T);
                        CleanArrays ();
                        // We are blindly supposing that the hash is correct
                        // i.e. I trust myself :-)
-                       int found = FindNode (hash, preds, succs);
+                       int found = FindNode (hash, precedents, succedings);
                        if (found == -1)
                                return false;
-                       
+
+                       bool taken = false;
+                       Node node = succedings [found];
+
                        try {
-                               Monitor.Enter (succs [found].Lock);
-                               Node node = succs [found];
+                               node.Lock.Enter (ref taken);
+
                                if (node.FullyLinked && !node.Marked) {
                                        value = node.Value;
                                        return true;
                                }
                        } finally {
-                               Monitor.Exit (succs [found].Lock);
+                               if (taken)
+                                       node.Lock.Exit ();
                        }
-                       
+
                        return false;
                }
 
@@ -303,7 +307,7 @@ namespace System.Collections.Concurrent
                {
                        return GetInternalEnumerator ();
                }
-               
+
                IEnumerator<T> GetInternalEnumerator ()
                {
                        Node curr = leftSentinel;
@@ -311,34 +315,37 @@ namespace System.Collections.Concurrent
                                // If there is an Add operation ongoing we wait a little
                                // Possible optimization : use a helping scheme
                                SpinWait sw = new SpinWait ();
-                               while (!curr.FullyLinked) {
+                               while (!curr.FullyLinked)
                                        sw.SpinOnce ();
-                               }
+
                                yield return curr.Value;
                        }
                }
 
-               void Unlock(Node[] preds, int highestLocked)
+               void Unlock (Node[] preds, bool[] takenLocks, int highestLocked)
                {
-                       for (int i = 0; i <= highestLocked; i++) {
-                               Monitor.Exit (preds [i].Lock);
-                       }
+                       for (int layer = 0; layer <= highestLocked; layer++)
+                               if (takenLocks [layer])
+                                       preds [layer].Lock.Exit ();
                }
 
-               bool LockNodes (int topLayer, ref int highestLocked, Func<int, Node, Node, bool> validityTest)
+               bool LockNodes (int topLayer, ref int highestLocked, Node[] preds, Node[] succs, Func<int, Node, Node, bool> validityTest)
                {
                        Node pred, succ, prevPred = null;
                        bool valid = true;
-                       
+
                        for (int layer = 0; valid && (layer <= topLayer); layer++) {
                                pred = preds [layer];
                                succ = succs [layer];
+                               takenLocks[layer] = false;
+
                                if (pred != prevPred) {
                                        // Possible optimization : limit topLayer to the first refused lock
-                                       Monitor.Enter (pred.Lock);
+                                       pred.Lock.Enter (ref takenLocks[layer]);
                                        highestLocked = layer;
                                        prevPred = pred;
                                }
+
                                valid = validityTest (layer, pred, succ);
                        }
 
@@ -349,7 +356,7 @@ namespace System.Collections.Concurrent
                {
                        // With preds and succs we record the path we use for searching v
                        if (preds.Length != MaxHeight || succs.Length != MaxHeight)
-                               throw new Exception ("precs or succs don't have the  good length");
+                               throw new Exception ("preds or succs don't have the  good length");
 
                        int found = -1;
                        Node pred = leftSentinel;
@@ -368,7 +375,7 @@ namespace System.Collections.Concurrent
                                preds [layer] = pred;
                                succs [layer] = curr;
                        }
-                       
+
                        return found;
                }
 
@@ -391,18 +398,23 @@ namespace System.Collections.Concurrent
                        while (((x >>= 1) & 1) != 0) ++level;
                        return level;
                }
-               
+
                void CleanArrays ()
                {
-                       if (succs == null)
-                               succs = new Node [MaxHeight];
-                       if (preds == null)
-                               preds = new Node [MaxHeight];
-                       
+                       // If one is null, the others too
+                       if (succedings == null) {
+                               succedings = new Node [MaxHeight];
+                               precedents = new Node [MaxHeight];
+                               takenLocks = new bool [MaxHeight];
+
+                               return;
+                       }
+
                        // Hopefully these are more optimized than a bare for loop
                        // (I suppose it uses memset internally)
-                       Array.Clear (preds, 0, preds.Length);
-                       Array.Clear (succs, 0, succs.Length);
+                       Array.Clear (precedents, 0, precedents.Length);
+                       Array.Clear (succedings, 0, succedings.Length);
+                       Array.Clear (takenLocks, 0, takenLocks.Length);
                }
 
                int Next ()
index 1872c00e1d1279923cb7178eda415bee4902fc4a..9b2c8a41281d822eb68ee9a12db9bb0408aa716e 100644 (file)
@@ -1,4 +1,3 @@
-#if NET_4_0
 // 
 // OrderablePartitioner.cs
 //  
@@ -28,6 +27,8 @@
 using System;
 using System.Collections.Generic;
 
+#if NET_4_0 || BOOTSTRAP_NET_4_0
+
 namespace System.Collections.Concurrent
 {
        public abstract class OrderablePartitioner<TSource> : Partitioner<TSource>
index 24987ae73bc058ad7c15a32bc6e1165a3df1a0b7..03ca175dcb63b574e71146afa3c9c4d19730e404 100644 (file)
@@ -1,4 +1,3 @@
-#if NET_4_0
 // 
 // Partitioner.cs
 //  
@@ -28,6 +27,8 @@
 using System;
 using System.Collections.Generic;
 
+#if NET_4_0 || BOOTSTRAP_NET_4_0
+
 namespace System.Collections.Concurrent
 {
        public static class Partitioner
diff --git a/mcs/class/corlib/System.Collections.Concurrent/Partitioners/ChangeLog b/mcs/class/corlib/System.Collections.Concurrent/Partitioners/ChangeLog
new file mode 100644 (file)
index 0000000..12789a4
--- /dev/null
@@ -0,0 +1,8 @@
+2010-04-15  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * ListPartitioner.cs: Remove playground code
+
+2010-04-15  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * ListPartitioner.cs:
+       * EnumerablePartitioner.cs: Add internal behavior specific to PLinq
index da1166776ac96bb09a9bbf2344c3361c0d560974..23df7f7c760fbb44a3dc13dee60e1b31b60fa632 100644 (file)
@@ -1,5 +1,3 @@
-#if NET_4_0
-#define USE_MONITOR
 // 
 // EnumerablePartitioner.cs
 //  
 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 // THE SOFTWARE.
 
+#if NET_4_0 || BOOTSTRAP_NET_4_0
+
 using System;
+using System.Threading.Tasks;
 using System.Collections.Generic;
 
 namespace System.Collections.Concurrent
 {
+       // Represent a chunk partitioner
        internal class EnumerablePartitioner<T> : OrderablePartitioner<T>
        {
                IEnumerable<T> source;
-#if USE_MONITOR
-               object syncLock = new object ();
-#endif
+               
                const int InitialPartitionSize = 1;
                const int PartitionMultiplier = 2;
                
+               int initialPartitionSize;
+               int partitionMultiplier;
+               
                int index = 0;
+               readonly object syncLock = new object ();
                
-               public EnumerablePartitioner (IEnumerable<T> source) : base (true, false, true)
+               public EnumerablePartitioner (IEnumerable<T> source)
+                       : this (source, InitialPartitionSize, PartitionMultiplier)
+               {
+
+               }
+               
+               // This is used to get striped partitionning (for Take and Skip for instance
+               public EnumerablePartitioner (IEnumerable<T> source, int initialPartitionSize, int partitionMultiplier)
+                        : base (true, false, true)
                {
                        this.source = source;
+                       this.initialPartitionSize = initialPartitionSize;
+                       this.partitionMultiplier = partitionMultiplier;
                }
                
                public override IList<IEnumerator<KeyValuePair<long, T>>> GetOrderablePartitions (int partitionCount)
@@ -66,7 +80,7 @@ namespace System.Collections.Concurrent
                
                IEnumerator<KeyValuePair<long, T>> GetPartitionEnumerator (IEnumerator<T> src)
                {
-                       int count = InitialPartitionSize;
+                       int count = initialPartitionSize;
                        List<T> list = new List<T> ();
                        
                        while (true) {
@@ -89,12 +103,14 @@ namespace System.Collections.Concurrent
                                        }                                       
                                }
                                
+                               
+                               
                                for (int i = 0; i < list.Count; i++)
                                        yield return new KeyValuePair<long, T> (ind + i, list[i]);
                                
-                               count *= PartitionMultiplier;
+                               count *= partitionMultiplier;
                        }
                }                                  
        }
 }
-#endif
\ No newline at end of file
+#endif
index 37b0fdddfc2ae98e2ce96f4cbee572974b2b1a9d..7512b373e4da57a04b200ee319caaf87eb277c03 100644 (file)
@@ -1,4 +1,3 @@
-#if NET_4_0
 // 
 // ListPartitioner.cs
 //  
 using System;
 using System.Collections.Generic;
 
+#if NET_4_0 || BOOTSTRAP_NET_4_0
+
 namespace System.Collections.Concurrent
 {
+       // Represent a Range partitioner
        internal class ListPartitioner<T> : OrderablePartitioner<T>
        {
                IList<T> source;
+               readonly bool chunking = Environment.GetEnvironmentVariable ("PLINQ_PARTITIONING_HINT") == "chunking";
                
                public ListPartitioner (IList<T> source) : base (true, true, true)
                {
@@ -47,9 +50,17 @@ namespace System.Collections.Concurrent
                        IEnumerator<KeyValuePair<long, T>>[] enumerators
                                = new IEnumerator<KeyValuePair<long, T>>[partitionCount];
                        
-                       int count = (source.Count >= partitionCount) ? source.Count / partitionCount : 1;
+                       int count = source.Count / partitionCount;
+                       if (count <= 1)
+                               count = 1;
                        
                        for (int i = 0; i < enumerators.Length; i++) {
+                               if (chunking) {
+                                       const int step = 64;
+                                       enumerators[i] = GetEnumeratorForRange (i * step, enumerators.Length, source.Count, step);
+                                       continue;
+                               }
+                               
                                if (i != enumerators.Length - 1)
                                        enumerators[i] = GetEnumeratorForRange (i * count, i * count + count);
                                else
@@ -66,11 +77,19 @@ namespace System.Collections.Concurrent
                        
                        return GetEnumeratorForRangeInternal (startIndex, lastIndex);
                }
+               
+               IEnumerator<KeyValuePair<long, T>> GetEnumeratorForRange (int startIndex, int stride, int count, int step)
+               {
+                       if (startIndex >= source.Count)
+                         return GetEmpty ();
+                       
+                       return GetEnumeratorForRangeInternal (startIndex, stride, count, step);
+               }
 
                IEnumerator<KeyValuePair<long, T>> GetEmpty ()
-                 {
+               {
                        yield break;
-                 }
+               }
                
                IEnumerator<KeyValuePair<long, T>> GetEnumeratorForRangeInternal (int startIndex, int lastIndex)
                {       
@@ -78,6 +97,15 @@ namespace System.Collections.Concurrent
                                yield return new KeyValuePair<long, T> (i, source[i]);
                        }
                }
+               
+               IEnumerator<KeyValuePair<long, T>> GetEnumeratorForRangeInternal (int startIndex, int stride, int count, int step)
+               {
+                       for (int i = startIndex; i < count; i += stride * step) {
+                               for (int j = i; j < i + step && j < count; j++) {
+                                       yield return new KeyValuePair<long, T> (j, source[j]);
+                               }
+                       }
+               }
        }
 }
-#endif
\ No newline at end of file
+#endif
index 6def189150d3f9aeea352a732efe63ec4aaed240..aa07be9838330f6b323534cd6cd9eee58019dbee 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-19  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * CollectionDebuggerView.cs: Change to internal so we can avoid
+       a duplicating the type in assemblies that have [InternalsVisibleTo]
+
 2010-01-25 Gonzalo Paniagua Javier <gonzalo@novell.com>
 
        * EqualityComparer.cs: (Equals) the arguments are checked to be
index f90dc48a35ad3511be5158c227e3e9dbf3481fdd..8f87050b599c7573f72a33372d3cb6e5813b0c49 100644 (file)
@@ -34,7 +34,7 @@ namespace System.Collections.Generic
        //
        // Custom debugger type proxy to display collections as arrays
        //
-       sealed class CollectionDebuggerView<T>
+       internal sealed class CollectionDebuggerView<T>
        {
                readonly ICollection<T> c;
 
@@ -53,7 +53,7 @@ namespace System.Collections.Generic
                }
        }
        
-       sealed class CollectionDebuggerView<T, U>
+       internal sealed class CollectionDebuggerView<T, U>
        {
                readonly ICollection<KeyValuePair<T, U>> c;
 
index 4af1c69d7c72c8f0a42cbf52ef8fe84c0f67f1a3..49f6156515541f1ef84c491c2fbcf9e870ebb4dc 100644 (file)
@@ -1,3 +1,18 @@
+2010-04-15  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * IStructuralComparable.cs:
+       * IStructuralEquatable.cs: Add BOOTSTRAP_NET_4_0 define
+
+2010-03-19  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * CollectionDebuggerView.cs: Change to internal so we can avoid
+       a duplicating the type in assemblies that have [InternalsVisibleTo]
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * IStructuralComparable.cs, IStructuralEquatable.cs: use
+       MOONLIGHT symbol to disambiguate MonoTouch and Moonlight code.
+
 2010-03-12  Sebastien Pouliot  <sebastien@ximian.com>
 
        * IStructuralComparable.cs, IStructuralEquatable.cs: Add them to
index 4ee8fa26ff4ed25bb20cab7b0af4005377a8c5cd..f8abdd3239e12fc6849d295ec41e165939667296 100644 (file)
@@ -34,7 +34,7 @@ namespace System.Collections
        //
        // Custom debugger type proxy to display collections as arrays
        //
-       sealed class CollectionDebuggerView
+       internal sealed class CollectionDebuggerView
        {
                readonly ICollection c;
 
index beca4a2ae38e4f16841ac5d84ea9b7a4646982cc..4850749e69fb972edf8efc36f100e14b24499617 100644 (file)
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if (NET_2_1 && !MONOTOUCH) || NET_4_0
+#if MOONLIGHT || NET_4_0 || BOOTSTRAP_NET_4_0
 
 using System;
 
index 62d75d44d121e87adfcebedc2b735f1be39ae08b..444d44f8fe70de08965279f940654c7eeb6a0e43 100644 (file)
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if (NET_2_1 && !MONOTOUCH) || NET_4_0
+#if MOONLIGHT || NET_4_0 || BOOTSTRAP_NET_4_0
 
 using System;
 
index 5f89d64130f73e3b037047b7fdaa9f66357fd4ca..e30a01a1843a16044f7c7931e8124d77cfa96690 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * StackFrame.cs: use MOONLIGHT symbol to disambiguate
+       MonoTouch and Moonlight code.
+
 2010-03-07 Rodrigo Kumpera  <rkumpera@novell.com>
 
        * Debugger.cs: Add Obsolete attribute to .ctor().
index 38796071e9e90aaabb7bb192b8e1c160120f2e82..8d9c83f7368a390dda37f18202c0542be5e9605e 100644 (file)
@@ -140,7 +140,7 @@ namespace System.Diagnostics {
                        string filename = "<filename unknown>";
                        if (fileName == null)
                                return filename;
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        try {
                                filename = GetFileName ();
                        }
index ecac0ad277ea14ef7e3d802adee3b4144ed79e9b..e8ec9fb650d7bbe9cefd9f2b6a0d31efdcc14fcb 100644 (file)
@@ -150,6 +150,11 @@ namespace System.Diagnostics {
                [MonoLimitation ("Not possible to create StackTraces from other threads")]
                public StackTrace (Thread targetThread, bool needFileInfo)
                {
+                       if (targetThread == Thread.CurrentThread){
+                               init_frames (METHODS_TO_SKIP, needFileInfo);
+                               return;
+                       }
+                       
                        throw new NotImplementedException ();
                }
 
index 35c1392fe87358fb2e183ea8ccefd1906bea3219..d4d8bb64f11d7873f3cb50ea6b090b48f507bdec 100644 (file)
@@ -128,7 +128,7 @@ public abstract class Calendar : ICloneable
        [NonSerialized]
        bool m_isReadOnly;
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
        [System.Runtime.InteropServices.ComVisible(false)]
        public virtual CalendarAlgorithmType AlgorithmType {
                get {
index 2952608b60df24b4f7bf219b810d0b3b87617b5b..57bb6ececbf205fcac94d9ceaa3f797b70674a7e 100644 (file)
@@ -1,3 +1,13 @@
+2010-04-19  Zoltan Varga  <vargaz@gmail.com>
+
+       * CompareInfo.cs (IndexOf): Return startIndex instead of 0 for empty strings.
+       Fixes #597604.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * CultureInfo.cs, CompareInfo.cs, Calendar.cs: use MOONLIGHT symbol
+       to disambiguate MonoTouch and Moonlight code.
+
 2010-02-28 Gonzalo Paniagua Javier <gonzalo@novell.com>
 
        * CultureNotFoundException.cs: new 4.0 type.
index f72ce7390f680ec729685b8b75f4609b970682f5..c6f1f1cc9941c8008704d79111625aae7d7a1348 100644 (file)
@@ -41,7 +41,7 @@ using Mono.Globalization.Unicode;
 namespace System.Globalization
 {
        [Serializable]
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
        [ComVisible (true)]
        public class CompareInfo : IDeserializationCallback {
 
@@ -149,7 +149,7 @@ namespace System.Globalization
                                        }
                                }
                        } else {
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                                this.icu_name = ci.IcuName;
                                this.construct_compareinfo (icu_name);
 #endif
@@ -158,12 +158,12 @@ namespace System.Globalization
 
                ~CompareInfo ()
                {
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        free_internal_collator ();
 #endif
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                private int internal_compare_managed (string str1, int offset1,
                                                int length1, string str2,
                                                int offset2, int length2,
@@ -409,7 +409,7 @@ namespace System.Globalization
                        case CompareOptions.OrdinalIgnoreCase:
                                throw new ArgumentException ("Now allowed CompareOptions.", "options");
                        }
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        if (UseManagedCollation)
                                return collator.GetSortKey (source, options);
                        SortKey key=new SortKey (culture, source, options);
@@ -498,7 +498,7 @@ namespace System.Globalization
                                        CompareOptions.None));
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                private int internal_index_managed (string s, int sindex,
                        int count, char c, CompareOptions opt,
                        bool first)
@@ -567,7 +567,7 @@ namespace System.Globalization
                        }
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                private int internal_index_managed (string s1, int sindex,
                        int count, string s2, CompareOptions opt,
                        bool first)
@@ -619,7 +619,7 @@ namespace System.Globalization
                        if ((options & ValidCompareOptions_NoStringSort) != options)
                                throw new ArgumentException ("options");
                        if(value.Length==0) {
-                               return(0);
+                               return(startIndex);
                        }
                        if(count==0) {
                                return(-1);
index d4e63c1329603dee81712d55a9541544719f4b5e..438dc0f28ec9a6b2b5196cf685d7b994d76028b8 100644 (file)
@@ -266,7 +266,7 @@ namespace System.Globalization
 
                public virtual string Name {
                        get {
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                                if (m_name == "zh-CHS")
                                        return "zh-Hans";
                                if (m_name == "zh-CHT")
@@ -404,7 +404,7 @@ namespace System.Globalization
                        return false;
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public static CultureInfo[] GetCultures(CultureTypes types)
                {
                        bool neutral=((types & CultureTypes.NeutralCultures)!=0);
@@ -494,7 +494,7 @@ namespace System.Globalization
 
                internal void CheckNeutral ()
                {
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        if (IsNeutralCulture) {
                                throw new NotSupportedException ("Culture \"" + m_name + "\" is " +
                                                "a neutral culture. It can not be used in formatting " +
@@ -619,7 +619,7 @@ namespace System.Globalization
                        // It is sort of hack to get those new pseudo-alias
                        // culture names that are not supported in good old
                        // Windows.
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        if (locale == "zh-chs" || locale == "zh-cht")
                                return false;
 #endif
index f7d405326aba151c006341f961ffe5f5546e240c..e1ab06e62c78b45fe272371f80d1a54414de8ffb 100644 (file)
@@ -1,3 +1,15 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * IsolatedStorageFileEnumerator.cs
+       * MoonIsolatedStorageFileStream.cs
+       * MoonIsolatedStorageFile.cs
+       * MoonIsolatedStorage.cs
+       * IsolatedStorageScope.cs
+       * IsolatedStorageFileStream.cs
+       * IsolatedStorage.cs
+       * IsolatedStorageFile.cs:
+               use MOONLIGHT symbol to disambiguate MonoTouch and Moonlight code.
+
 2009-11-01  Sebastien Pouliot  <sebastien@ximian.com>
 
        * MoonIsolatedStorageFile.cs: Add new CheckSearchPattern 
index 479e723fbabd327de5c483afc478da124ab258af..fcb24c984fdf585c34fbff4644c6ddf569417be1 100644 (file)
@@ -28,7 +28,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 using System.Globalization;
 using System.Reflection;
 using System.Runtime.InteropServices;
@@ -153,5 +153,5 @@ namespace System.IO.IsolatedStorage {
                public abstract void Remove ();
        }
 }
-/* NET_2_1 */
+/* MOONLIGHT */
 #endif 
\ No newline at end of file
index 00f2494f626a82d9e74bc1009ab4b4f97aada5fc..583231ec13d0cad16609437454ab2891522693b8 100644 (file)
@@ -27,7 +27,7 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 using System.Collections;
 using System.Reflection;
 using System.Runtime.InteropServices;
index 25641e2c7a96c9278cedf431fbba737822e13f3b..08457bff978ea0448ab4dfb942520ab3731bc131 100644 (file)
@@ -28,7 +28,7 @@
 
 using System.Collections;
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 namespace System.IO.IsolatedStorage {
 
index 75d5c74b250dd6bef40e9ba28b15c34eedc60566..4479dab7f3dcfafb916dd078b966106011a3821d 100644 (file)
@@ -27,7 +27,7 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 using System.Diagnostics;
 using System.Globalization;
 using System.Reflection;
index 3e17bcb41f32b54d59218466b67bf708e6a7576d..bde8468ccc8f2ee09efbbe4ffc5bd5c8fea5579c 100644 (file)
@@ -41,7 +41,7 @@ namespace System.IO.IsolatedStorage {
 
                None = 0,
                User = 1,
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                // Available in Silverlight
                Application = 32,
 #else
index 9698309fef9bdfe29274d66bb6b3ad07d9d606af..9ea31ee08bb3a9feedc2804596c3b63104be2f86 100644 (file)
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
 
 using System;
 using System.IO;
index af4560d712346ac576ea1f36e970bec992643a8a..0c0fe270416bd8036b89ad985dff5e382d012f1f 100644 (file)
@@ -28,7 +28,7 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
 using System;
 using System.IO;
 using System.Runtime.InteropServices;
index 60d05549487803b1259badd1c0fef72abc6deffd..23b90e52ce774808399a38cd380177afe128ba38 100644 (file)
@@ -28,7 +28,7 @@
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
 using System;
 using System.IO;
 
index 7cec76790ef7111f745cb30bcec1bb1e1e4fd543..9fe7abe6a28c5aae69d33cc06539e4dec1d65a4b 100644 (file)
@@ -1,3 +1,74 @@
+2010-04-21  Sebastien Pouliot  <sebastien@ximian.com> 
+
+       * FileInfo.cs: Ensure elevated trust when calling Delete on 
+       Moonlight.
+       * FileSystemInfo.cs: Ensure elevated trust when calling [Creation
+       |LastAccess|LastWrite]Time setters
+
+2010-04-16  Sebastien Pouliot  <sebastien@ximian.com> 
+
+       * Directory.cs: Ensure elevated trust when calling on 
+       Moonlight.
+       * DirectoryInfo.cs: Ensure elevated trust when calling a .ctor 
+       on Moonlight.
+       * File.cs: Ensure elevated trust when calling a .ctor on 
+       Moonlight.
+       * FileInfo.cs: Ensure elevated trust when calling a .ctor on 
+       Moonlight.
+       * FileStream.cs: Ensure elevated trust when calling a .ctor on 
+       Moonlight. Name property returns "[Unknown]" unless a Moonlight
+       application is executed with elevated trust.
+       * Path.cs: Ensure elevated trust when calling a GetTempPath,
+       GetTempFileName or GetFullPath on Moonlight. Add a shared 
+       internal method to validate paths to reduce code duplication.
+
+2010-04-15  Jb Evain  <jbevain@novell.com>
+
+       * Directory.cs: don't fully qualify name when not it's necessary.
+
+2010-03-29  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * DirectoryInfo.cs, FileInfo.cs: Moonlight needs the default ctor
+       to decorate them with [SecuritySafeCritical] for corclr 
+       inheritance rules
+
+2010-03-25 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * Directory.cs: a directory named ":" is legal in unix.
+       This gets rid of the annoying ":" folder when running
+       corlib tests.
+
+2010-03-22  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * Directory.cs, DirectoryInfo.cs: Disble new NET_4_0 API used in
+       SL4 until we have elevated trust working correctly (since they 
+       are *not* decorated as [SecurityCritical])
+
+2010-03-17 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * StreamReader.cs: if the detected encoding is different from the
+       provided to the constructor, adjust the decoded buffer size if
+       needed. Fixes bug #589236.
+
+2010-03-17  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * Stream.cs: CopyTo methods are part of SL4 too
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * FileStream.cs, File.cs, DirectoryInfo.cs, Directory.cs: use
+       MOONLIGHT symbol to disambiguate MonoTouch and Moonlight code.
+
+2010-03-16  Rolf Bjarne Kvinge  <RKvinge@novell.com>
+
+       * Path.cs:
+       * Directory.cs:
+       * DirectoryInfo.cs: Add some of the 4.0 methods to Moonlight.
+
+2010-03-15  Rolf Bjarne Kvinge  <RKvinge@novell.com>
+
+       * SearchOption.cs: Make public for Moonlight, this type is in SL4.
+
 2010-03-12  Sebastien Pouliot  <sebastien@ximian.com>
 
        * File.cs: Enable some NET_4_0 features in NET_2_1 since they are
index 58a74aea3825f90aeac13b6f68191229fdd89570..69709f060d61821495ba05cbe512c6b6e0cd4e5f 100644 (file)
 //
 
 using System.Collections;
+using System.Collections.Generic;
 using System.Security;
 using System.Security.Permissions;
 using System.Text;
 using System.Runtime.InteropServices;
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 using System.Security.AccessControl;
 #endif
 
@@ -68,18 +69,21 @@ namespace System.IO
                        if (path.Trim ().Length == 0)
                                throw new ArgumentException ("Only blank characters in path");
 
+                       // after validations but before File.Exists to avoid an oracle
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
+
                        if (File.Exists(path))
                                throw new IOException ("Cannot create " + path + " because a file with the same name already exists.");
                        
                        // LAMESPEC: with .net 1.0 version this throw NotSupportedException and msdn says so too
                        // but v1.1 throws ArgumentException.
-                       if (path == ":")
+                       if (Environment.IsRunningOnWindows && path == ":")
                                throw new ArgumentException ("Only ':' In path");
                        
                        return CreateDirectoriesInternal (path);
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                [MonoLimitation ("DirectorySecurity not implemented")]
                public static DirectoryInfo CreateDirectory (string path, DirectorySecurity directorySecurity)
                {
@@ -89,7 +93,7 @@ namespace System.IO
 
                static DirectoryInfo CreateDirectoriesInternal (string path)
                {
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        if (SecurityManager.SecurityEnabled) {
                                new FileIOPermission (FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, path).Demand ();
                        }
@@ -119,21 +123,13 @@ namespace System.IO
                
                public static void Delete (string path)
                {
-                       if (path == null)
-                               throw new ArgumentNullException ("path");
-                       
-                       if (path.Length == 0)
-                               throw new ArgumentException ("Path is empty");
-                       
-                       if (path.IndexOfAny (Path.InvalidPathChars) != -1)
-                               throw new ArgumentException ("Path contains invalid chars");
+                       Path.Validate (path);
 
-                       if (path.Trim().Length == 0)
-                               throw new ArgumentException ("Only blank characters in path");
-
-                       if (path == ":")
+                       if (Environment.IsRunningOnWindows && path == ":")
                                throw new NotSupportedException ("Only ':' In path");
 
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
+
                        MonoIOError error;
                        bool success;
                        
@@ -182,8 +178,9 @@ namespace System.IO
                
                public static void Delete (string path, bool recursive)
                {
-                       CheckPathExceptions (path);
-                       
+                       Path.Validate (path);                   
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
+
                        if (recursive)
                                RecursiveDelete (path);
                        else
@@ -194,6 +191,10 @@ namespace System.IO
                {
                        if (path == null)
                                return false;
+
+                       // on Moonlight this does not throw but returns false
+                       if (!SecurityManager.CheckElevatedPermissions ())
+                               return false;
                                
                        MonoIOError error;
                        bool exists;
@@ -236,11 +237,13 @@ namespace System.IO
                public static string GetCurrentDirectory ()
                {
                        MonoIOError error;
+
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
                                
                        string result = MonoIO.GetCurrentDirectory (out error);
                        if (error != MonoIOError.ERROR_SUCCESS)
                                throw MonoIO.GetException (error);
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        if ((result != null) && (result.Length > 0) && SecurityManager.SecurityEnabled) {
                                new FileIOPermission (FileIOPermissionAccess.PathDiscovery, result).Demand ();
                        }
@@ -258,7 +261,7 @@ namespace System.IO
                        return GetFileSystemEntries (path, searchPattern, FileAttributes.Directory, FileAttributes.Directory);
                }
                
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public static string [] GetDirectories (string path, string searchPattern, SearchOption searchOption)
                {
                        if (searchOption == SearchOption.TopDirectoryOnly)
@@ -278,6 +281,10 @@ namespace System.IO
 
                public static string GetDirectoryRoot (string path)
                {
+                       Path.Validate (path);                   
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
+
+                       // FIXME nice hack but that does not work under windows
                        return new String(Path.DirectorySeparatorChar,1);
                }
                
@@ -291,7 +298,7 @@ namespace System.IO
                        return GetFileSystemEntries (path, searchPattern, FileAttributes.Directory, 0);
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public static string[] GetFiles (string path, string searchPattern, SearchOption searchOption)
                {
                        if (searchOption == SearchOption.TopDirectoryOnly)
@@ -340,12 +347,7 @@ namespace System.IO
 
                public static DirectoryInfo GetParent (string path)
                {
-                       if (path == null)
-                               throw new ArgumentNullException ("path");
-                       if (path.IndexOfAny (Path.InvalidPathChars) != -1)
-                               throw new ArgumentException ("Path contains invalid characters");
-                       if (path.Length == 0)
-                               throw new ArgumentException ("The Path do not have a valid format");
+                       Path.Validate (path);                   
 
                        // return null if the path is the root directory
                        if (IsRootDirectory (path))
@@ -375,6 +377,8 @@ namespace System.IO
                        if (sourceDirName == destDirName)
                                throw new IOException ("Source and destination path must be different.");
 
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
+
                        if (Exists (destDirName))
                                throw new IOException (destDirName + " already exists.");
 
@@ -386,7 +390,7 @@ namespace System.IO
                                throw MonoIO.GetException (error);
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public static void SetAccessControl (string path, DirectorySecurity directorySecurity)
                {
                        throw new NotImplementedException ();
@@ -444,38 +448,15 @@ namespace System.IO
 
                // private
                
-               private static void CheckPathExceptions (string path)
-               {
-                       if (path == null)
-                               throw new System.ArgumentNullException("path");
-                       if (path.Length == 0)
-                               throw new System.ArgumentException("Path is Empty");
-                       if (path.Trim().Length == 0)
-                               throw new ArgumentException ("Only blank characters in path");
-                       if (path.IndexOfAny (Path.InvalidPathChars) != -1)
-                               throw new ArgumentException ("Path contains invalid chars");
-               }
-
                // Does the common validation, searchPattern has already been checked for not-null
                static string ValidateDirectoryListing (string path, string searchPattern, out bool stop)
                {
-                       if (path == null)
-                               throw new ArgumentNullException ("path");
-
-                       if (path.Trim ().Length == 0)
-                               throw new ArgumentException ("The Path does not have a valid format");
+                       Path.Validate (path);
 
                        string wild = Path.Combine (path, searchPattern);
                        string wildpath = Path.GetDirectoryName (wild);
                        if (wildpath.IndexOfAny (Path.InvalidPathChars) != -1)
-                               throw new ArgumentException ("Path contains invalid characters");
-
-                       if (wildpath.IndexOfAny (Path.InvalidPathChars) != -1) {
-                               if (path.IndexOfAny (SearchPattern.InvalidChars) == -1)
-                                       throw new ArgumentException ("Path contains invalid characters", "path");
-
                                throw new ArgumentException ("Pattern contains invalid characters", "pattern");
-                       }
 
                        MonoIOError error;
                        if (!MonoIO.ExistsDirectory (wildpath, out error)) {
@@ -522,24 +503,33 @@ namespace System.IO
                        return result;
                }
 
-#if NET_4_0
+#if NET_4_0 || MOONLIGHT
                public static string[] GetFileSystemEntries (string path, string searchPattern, SearchOption searchOption)
                {
                        // Take the simple way home:
-                       return new System.Collections.Generic.List<string> (EnumerateFileSystemEntries (path, searchPattern, searchOption)).ToArray ();
+                       return new List<string> (EnumerateFileSystemEntries (path, searchPattern, searchOption)).ToArray ();
                }
-                                                      
-               internal static System.Collections.Generic.IEnumerable<string> EnumerateKind (string path, string searchPattern, SearchOption searchOption, FileAttributes kind)
+
+               static void EnumerateCheck (string path, string searchPattern, SearchOption searchOption)
                {
                        if (searchPattern == null)
                                throw new ArgumentNullException ("searchPattern");
 
                        if (searchPattern.Length == 0)
-                               yield break;
+                               return;
 
                        if (searchOption != SearchOption.TopDirectoryOnly && searchOption != SearchOption.AllDirectories)
                                throw new ArgumentOutOfRangeException ("searchoption");
 
+                       Path.Validate (path);
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
+               }
+
+               internal static IEnumerable<string> EnumerateKind (string path, string searchPattern, SearchOption searchOption, FileAttributes kind)
+               {
+                       if (searchPattern.Length == 0)
+                               yield break;
+
                        bool stop;
                        string path_with_pattern = ValidateDirectoryListing (path, searchPattern, out stop);
                        if (stop){
@@ -577,54 +567,66 @@ namespace System.IO
                        }
                }
 
-               public static System.Collections.Generic.IEnumerable<string> EnumerateDirectories (string path, string searchPattern, SearchOption searchOption)
+               public static IEnumerable<string> EnumerateDirectories (string path, string searchPattern, SearchOption searchOption)
                {
+                       EnumerateCheck (path, searchPattern, searchOption);
                        return EnumerateKind (path, searchPattern, searchOption, FileAttributes.Directory);
                }
                
-               public static System.Collections.Generic.IEnumerable<string> EnumerateDirectories (string path, string searchPattern)
+               public static IEnumerable<string> EnumerateDirectories (string path, string searchPattern)
                {
+                       EnumerateCheck (path, searchPattern, SearchOption.TopDirectoryOnly);
                        return EnumerateKind (path, searchPattern, SearchOption.TopDirectoryOnly, FileAttributes.Directory);
                }
 
-               public static System.Collections.Generic.IEnumerable<string> EnumerateDirectories (string path)
+               public static IEnumerable<string> EnumerateDirectories (string path)
                {
+                       Path.Validate (path); // no need for EnumerateCheck since we supply valid arguments
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
                        return EnumerateKind (path, "*", SearchOption.TopDirectoryOnly, FileAttributes.Directory);
                }
 
-               public static System.Collections.Generic.IEnumerable<string> EnumerateFiles (string path, string searchPattern, SearchOption searchOption)
+               public static IEnumerable<string> EnumerateFiles (string path, string searchPattern, SearchOption searchOption)
                {
+                       EnumerateCheck (path, searchPattern, searchOption);
                        return EnumerateKind (path, searchPattern, searchOption, FileAttributes.Normal);
                }
 
-               public static System.Collections.Generic.IEnumerable<string> EnumerateFiles (string path, string searchPattern)
+               public static IEnumerable<string> EnumerateFiles (string path, string searchPattern)
                {
+                       EnumerateCheck (path, searchPattern, SearchOption.TopDirectoryOnly);
                        return EnumerateKind (path, searchPattern, SearchOption.TopDirectoryOnly, FileAttributes.Normal);
                }
 
-               public static System.Collections.Generic.IEnumerable<string> EnumerateFiles (string path)
+               public static IEnumerable<string> EnumerateFiles (string path)
                {
+                       Path.Validate (path); // no need for EnumerateCheck since we supply valid arguments
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
                        return EnumerateKind (path, "*", SearchOption.TopDirectoryOnly, FileAttributes.Normal);
                }
 
-               public static System.Collections.Generic.IEnumerable<string> EnumerateFileSystemEntries (string path, string searchPattern, SearchOption searchOption)
+               public static IEnumerable<string> EnumerateFileSystemEntries (string path, string searchPattern, SearchOption searchOption)
                {
+                       EnumerateCheck (path, searchPattern, searchOption);
                        return EnumerateKind (path, searchPattern, searchOption, FileAttributes.Normal | FileAttributes.Directory);
                }
 
-               public static System.Collections.Generic.IEnumerable<string> EnumerateFileSystemEntries (string path, string searchPattern)
+               public static IEnumerable<string> EnumerateFileSystemEntries (string path, string searchPattern)
                {
+                       EnumerateCheck (path, searchPattern, SearchOption.TopDirectoryOnly);
                        return EnumerateKind (path, searchPattern, SearchOption.TopDirectoryOnly, FileAttributes.Normal | FileAttributes.Directory);
                }
 
-               public static System.Collections.Generic.IEnumerable<string> EnumerateFileSystemEntries (string path)
+               public static IEnumerable<string> EnumerateFileSystemEntries (string path)
                {
+                       Path.Validate (path); // no need for EnumerateCheck since we supply valid arguments
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
                        return EnumerateKind (path, "*", SearchOption.TopDirectoryOnly, FileAttributes.Normal | FileAttributes.Directory);
                }
                
 #endif
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                [MonoNotSupported ("DirectorySecurity isn't implemented")]
                public static DirectorySecurity GetAccessControl (string path, AccessControlSections includeSections)
                {
index 16b6e19dc27a0f5690a083f19d0a40d973863eb3..0e214a0486f59126ce27d8531cabea5803ed07ac 100644 (file)
@@ -35,8 +35,9 @@ using System.Collections;
 using System.Collections.Generic;
 using System.Runtime.InteropServices;
 using System.Runtime.Serialization;
+using System.Security;
 using System.Text;
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 using System.Security.AccessControl;
 #endif
 
@@ -49,6 +50,11 @@ namespace System.IO {
                private string current;
                private string parent;
        
+#if MOONLIGHT
+               internal DirectoryInfo ()
+               {
+               }
+#endif
                public DirectoryInfo (string path) : this (path, false)
                {
                }
@@ -57,6 +63,8 @@ namespace System.IO {
                {
                        CheckPath (path);
 
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
+
                        FullPath = Path.GetFullPath (path);
                        if (simpleOriginalPath)
                                OriginalPath = Path.GetFileName (path);
@@ -262,7 +270,7 @@ namespace System.IO {
                        return OriginalPath;
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public DirectoryInfo[] GetDirectories (string searchPattern, SearchOption searchOption)
                {
                        switch (searchOption) {
@@ -370,7 +378,7 @@ namespace System.IO {
                }
 #endif
 
-#if NET_4_0
+#if NET_4_0 || MOONLIGHT
 
                public IEnumerable<DirectoryInfo> EnumerateDirectories ()
                {
@@ -431,6 +439,8 @@ namespace System.IO {
                        MonoIOError error;
                        FileAttributes rattr;
                        bool subdirs = searchOption == SearchOption.AllDirectories;
+
+                       Path.Validate (full);
                        
                        string s = MonoIO.FindFirst (full, path_with_pattern, out rattr, out error, out handle);
                        if (s == null)
index 3ef678e26ebaa3755e0e5ac0b233831fa3029052..733377e8c640e81a15eae4d9e1d7cb1af3b5405c 100644 (file)
@@ -10,7 +10,7 @@
 //
 // Copyright 2002 Ximian, Inc. http://www.ximian.com
 // Copyright (C) 2001 Moonlight Enterprises, All Rights Reserved
-// Copyright (C) 2004, 2006 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2004, 2006, 2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
 //
 
 using System;
-using System.Text;
 using System.Collections.Generic;
+using System.Diagnostics;
+using System.Security;
+using System.Text;
 using System.Runtime.InteropServices;
 
-#if NET_2_1
-using System.Security;
-#else
+#if !NET_2_1
 using System.Security.AccessControl;
 #endif
 
@@ -48,22 +48,8 @@ namespace System.IO
        [ComVisible (true)]
        public static class File
        {
-               static void ValidatePath (string path)
-               {
-                       if (path == null)
-                               throw new ArgumentNullException ("path");
-                       if (path.Length == 0)
-                               throw new ArgumentException ("path");
-#if NET_2_1 && !MONOTOUCH && !DEBUG
-                       // On Moonlight (SL4+) this is possible, with limitations, in "Elevated Trust"
-                       throw new SecurityException ("we're not ready to enable this SL4 feature yet");
-#endif
-               }
-
                public static void AppendAllText (string path, string contents)
                {
-                       ValidatePath (path);
-
                        using (TextWriter w = new StreamWriter (path, true)) {
                                w.Write (contents);
                        }
@@ -71,8 +57,6 @@ namespace System.IO
 
                public static void AppendAllText (string path, string contents, Encoding encoding)
                {
-                       ValidatePath (path);
-
                        using (TextWriter w = new StreamWriter (path, true, encoding)) {
                                w.Write (contents);
                        }
@@ -105,6 +89,8 @@ namespace System.IO
                        if (destFileName.Trim ().Length == 0 || destFileName.IndexOfAny (Path.InvalidPathChars) != -1)
                                throw new ArgumentException ("The file name is not valid.");
 
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
+
                        if (!MonoIO.Exists (sourceFileName, out error))
                                throw new FileNotFoundException (Locale.GetText ("{0} does not exist", sourceFileName), sourceFileName);
                        if ((GetAttributes (sourceFileName) & FileAttributes.Directory) == FileAttributes.Directory)
@@ -163,10 +149,7 @@ namespace System.IO
 
                public static void Delete (string path)
                {
-                       if (path == null)
-                               throw new ArgumentNullException("path");
-                       if (path.Trim().Length == 0 || path.IndexOfAny(Path.InvalidPathChars) >= 0)
-                               throw new ArgumentException("path");
+                       Path.Validate (path);
                        if (Directory.Exists (path))
                                throw new UnauthorizedAccessException(Locale.GetText ("{0} is a directory", path));
 
@@ -174,6 +157,8 @@ namespace System.IO
                        if (DirName != String.Empty && !Directory.Exists (DirName))
                                throw new DirectoryNotFoundException (Locale.GetText ("Could not find a part of the path \"{0}\".", path));
 
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
+
                        MonoIOError error;
                        
                        if (!MonoIO.DeleteFile (path, out error)){
@@ -189,10 +174,12 @@ namespace System.IO
                        // any problem with the path or permissions.
                        // Minimizes what information can be
                        // discovered by using this method.
-                       if (path == null || path.Trim().Length == 0
-                           || path.IndexOfAny(Path.InvalidPathChars) >= 0) {
+                       if (String.IsNullOrWhiteSpace (path) || path.IndexOfAny(Path.InvalidPathChars) >= 0)
+                               return false;
+
+                       // on Moonlight this does not throw but returns false
+                       if (!SecurityManager.CheckElevatedPermissions ())
                                return false;
-                       }
 
                        MonoIOError error;
                        return MonoIO.ExistsFile (path, out error);
@@ -212,12 +199,8 @@ namespace System.IO
 
                public static FileAttributes GetAttributes (string path)
                {
-                       if (path == null)
-                               throw new ArgumentNullException("path");
-                       if (path.Trim ().Length == 0)
-                               throw new ArgumentException (Locale.GetText ("Path is empty"));
-                       if (path.IndexOfAny (Path.InvalidPathChars) >= 0)
-                               throw new ArgumentException (Locale.GetText ("Path contains invalid chars"));
+                       Path.Validate (path);
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
 
                        MonoIOError error;
                        FileAttributes attrs;
@@ -232,7 +215,8 @@ namespace System.IO
                {
                        MonoIOStat stat;
                        MonoIOError error;
-                       CheckPathExceptions (path);
+                       Path.Validate (path);
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
 
                        if (!MonoIO.GetFileStat (path, out stat, out error)) {
                                if (error == MonoIOError.ERROR_PATH_NOT_FOUND || error == MonoIOError.ERROR_FILE_NOT_FOUND)
@@ -252,7 +236,8 @@ namespace System.IO
                {
                        MonoIOStat stat;
                        MonoIOError error;
-                       CheckPathExceptions (path);
+                       Path.Validate (path);
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
 
                        if (!MonoIO.GetFileStat (path, out stat, out error)) {
                                if (error == MonoIOError.ERROR_PATH_NOT_FOUND || error == MonoIOError.ERROR_FILE_NOT_FOUND)
@@ -272,7 +257,8 @@ namespace System.IO
                {
                        MonoIOStat stat;
                        MonoIOError error;
-                       CheckPathExceptions (path);
+                       Path.Validate (path);
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
 
                        if (!MonoIO.GetFileStat (path, out stat, out error)) {
                                if (error == MonoIOError.ERROR_PATH_NOT_FOUND || error == MonoIOError.ERROR_FILE_NOT_FOUND)
@@ -290,8 +276,6 @@ namespace System.IO
 
                public static void Move (string sourceFileName, string destFileName)
                {
-                       MonoIOError error;
-
                        if (sourceFileName == null)
                                throw new ArgumentNullException ("sourceFileName");
                        if (destFileName == null)
@@ -304,6 +288,10 @@ namespace System.IO
                                throw new ArgumentException ("An empty file name is not valid.", "destFileName");
                        if (destFileName.Trim ().Length == 0 || destFileName.IndexOfAny (Path.InvalidPathChars) != -1)
                                throw new ArgumentException ("The file name is not valid.");
+
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
+
+                       MonoIOError error;
                        if (!MonoIO.Exists (sourceFileName, out error))
                                throw new FileNotFoundException (Locale.GetText ("{0} does not exist", sourceFileName), sourceFileName);
 
@@ -432,7 +420,7 @@ namespace System.IO
                                                  FileAttributes fileAttributes)
                {
                        MonoIOError error;
-                       CheckPathExceptions (path);
+                       Path.Validate (path);
 
                        if (!MonoIO.SetFileAttributes (path, fileAttributes, out error))
                                throw MonoIO.GetException (path, error);
@@ -441,7 +429,7 @@ namespace System.IO
                public static void SetCreationTime (string path, DateTime creationTime)
                {
                        MonoIOError error;
-                       CheckPathExceptions (path);
+                       Path.Validate (path);
                        if (!MonoIO.Exists (path, out error))
                                throw MonoIO.GetException (path, error);
                        if (!MonoIO.SetCreationTime (path, creationTime, out error))
@@ -456,7 +444,7 @@ namespace System.IO
                public static void SetLastAccessTime (string path, DateTime lastAccessTime)
                {
                        MonoIOError error;
-                       CheckPathExceptions (path);
+                       Path.Validate (path);
                        if (!MonoIO.Exists (path, out error))
                                throw MonoIO.GetException (path, error);
                        if (!MonoIO.SetLastAccessTime (path, lastAccessTime, out error))
@@ -472,7 +460,7 @@ namespace System.IO
                                                     DateTime lastWriteTime)
                {
                        MonoIOError error;
-                       CheckPathExceptions (path);
+                       Path.Validate (path);
                        if (!MonoIO.Exists (path, out error))
                                throw MonoIO.GetException (path, error);
                        if (!MonoIO.SetLastWriteTime (path, lastWriteTime, out error))
@@ -485,22 +473,6 @@ namespace System.IO
                        SetLastWriteTime (path, lastWriteTimeUtc.ToLocalTime ());
                }
 
-               #region Private
-
-               private static void CheckPathExceptions (string path)
-               {
-                       if (path == null)
-                               throw new System.ArgumentNullException("path");
-                       if (path.Length == 0)
-                               throw new System.ArgumentException(Locale.GetText ("Path is empty"));
-                       if (path.Trim().Length == 0)
-                               throw new ArgumentException (Locale.GetText ("Path is empty"));
-                       if (path.IndexOfAny (Path.InvalidPathChars) != -1)
-                               throw new ArgumentException (Locale.GetText ("Path contains invalid chars"));
-               }
-
-               #endregion
-
                //
                // The documentation for this method is most likely wrong, it
                // talks about doing a "binary read", but the remarks say
@@ -555,8 +527,6 @@ namespace System.IO
 
                public static string ReadAllText (string path)
                {
-                       ValidatePath (path);
-
                        using (StreamReader sr = new StreamReader (path)) {
                                return sr.ReadToEnd ();
                        }
@@ -564,8 +534,6 @@ namespace System.IO
 
                public static string ReadAllText (string path, Encoding encoding)
                {
-                       ValidatePath (path);
-
                        using (StreamReader sr = new StreamReader (path, encoding)) {
                                return sr.ReadToEnd ();
                        }
@@ -641,11 +609,9 @@ namespace System.IO
                        throw new NotSupportedException (Locale.GetText ("File encryption isn't supported on any file system."));
                }
 
-#if (NET_2_1 && !MONOTOUCH) || NET_4_0
+#if MOONLIGHT || NET_4_0
                public static IEnumerable<string> ReadLines (string path)
                {
-                       ValidatePath (path);
-
                        using (StreamReader reader = File.OpenText (path)) {
                                return ReadLines (reader);
                        }
@@ -653,8 +619,6 @@ namespace System.IO
 
                public static IEnumerable<string> ReadLines (string path, Encoding encoding)
                {
-                       ValidatePath (path);
-
                        using (StreamReader reader = new StreamReader (path, encoding)) {
                                return ReadLines (reader);
                        }
@@ -670,7 +634,7 @@ namespace System.IO
 
                public static void AppendAllLines (string path, IEnumerable<string> contents)
                {
-                       ValidatePath (path);
+                       Path.Validate (path);
 
                        if (contents == null)
                                return;
@@ -683,7 +647,7 @@ namespace System.IO
 
                public static void AppendAllLines (string path, IEnumerable<string> contents, Encoding encoding)
                {
-                       ValidatePath (path);
+                       Path.Validate (path);
 
                        if (contents == null)
                                return;
@@ -696,7 +660,7 @@ namespace System.IO
 
                public static void WriteAllLines (string path, IEnumerable<string> contents)
                {
-                       ValidatePath (path);
+                       Path.Validate (path);
 
                        if (contents == null)
                                return;
@@ -709,7 +673,7 @@ namespace System.IO
 
                public static void WriteAllLines (string path, IEnumerable<string> contents, Encoding encoding)
                {
-                       ValidatePath (path);
+                       Path.Validate (path);
 
                        if (contents == null)
                                return;
index 03d2837639730c32b5b93fc59c8f5e75367fa956..004b145290683635b5d46cacbfef7dfc7d9dc8f5 100644 (file)
@@ -35,6 +35,7 @@
 
 using System.Runtime.InteropServices;
 using System.Runtime.Serialization;
+using System.Security;
 
 #if !NET_2_1
 using System.Security.AccessControl;
@@ -48,12 +49,18 @@ namespace System.IO {
        {
                private bool exists;
 
+#if MOONLIGHT
+               internal FileInfo ()
+               {
+               }
+#endif
                public FileInfo (string fileName)
                {
                        if (fileName == null)
                                throw new ArgumentNullException ("fileName");
 
                        CheckPath (fileName);
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
 
                        OriginalPath = fileName;
                        FullPath = Path.GetFullPath (fileName);
@@ -214,6 +221,8 @@ namespace System.IO {
                {
                        MonoIOError error;
 
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
+
                        if (!MonoIO.Exists (FullPath, out error))
                                // a weird MS.NET behaviour
                                return;
index 04479da45e52c9c227e74800923ea9e6f84cd563..7eae1656a62fee71e4ac6ef48b3f23ac2057e123 100644 (file)
@@ -8,7 +8,7 @@
 //  Marek Safar (marek.safar@gmail.com)
 //
 // (C) 2001-2003 Ximian, Inc.  http://www.ximian.com
-// Copyright (C) 2004-2005, 2008 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2004-2005, 2008, 2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -35,13 +35,13 @@ using System.Globalization;
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
 using System.Runtime.Remoting.Messaging;
+using System.Security;
 using System.Security.Permissions;
 using System.Threading;
 
 using Microsoft.Win32.SafeHandles;
 #if NET_2_1
 using System.IO.IsolatedStorage;
-using System.Security;
 #else
 using System.Security.AccessControl;
 #endif
@@ -98,7 +98,7 @@ namespace System.IO
                        this.access = access;
                        this.owner = ownsHandle;
                        this.async = isAsync;
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        // default the browser to 'all' anonymous files and let other usage (like smcs) with 'normal'
                        // (i.e. non-anonymous except for isolated storage) files and paths
                        this.anonymous = SecurityManager.SecurityEnabled;
@@ -264,6 +264,8 @@ namespace System.IO
                                throw new ArgumentException (string.Format (msg, access, mode));
                        }
 
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
+
                        string dname = Path.GetDirectoryName (path);
                        if (dname.Length > 0) {
                                string fp = Path.GetFullPath (dname);
@@ -369,7 +371,11 @@ namespace System.IO
 
                public string Name {
                        get {
-                               return name; 
+#if MOONLIGHT
+                               return SecurityManager.CheckElevatedPermissions () ? name : "[Unknown]";
+#else
+                               return name;
+#endif
                        }
                }
 
index 574ab1d573c8e14730737a5fd83611c645eadbb5..46f67bdb581744351557e0d23da8c042abfa2906 100644 (file)
@@ -35,6 +35,7 @@
 
 using System.Runtime.InteropServices;
 using System.Runtime.Serialization;
+using System.Security;
 using System.Security.Permissions;
 
 namespace System.IO {
@@ -101,6 +102,8 @@ namespace System.IO {
                        }
 
                        set {
+                               SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
+
                                long filetime = value.ToFileTime ();
                        
                                MonoIOError error;
@@ -131,6 +134,8 @@ namespace System.IO {
                        }
 
                        set {
+                               SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
+
                                long filetime = value.ToFileTime ();
 
                                MonoIOError error;
@@ -163,6 +168,8 @@ namespace System.IO {
                        }
 
                        set {
+                               SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
+
                                long filetime = value.ToFileTime ();
 
                                MonoIOError error;
index 0c78b0350aae11adb712d5d98c9d4eab38cf6dda..1dd4706255704a3b4e12c75dac0b901b66ecb8b6 100644 (file)
@@ -275,6 +275,9 @@ namespace System.IO {
                public static string GetFullPath (string path)
                {
                        string fullpath = InsecureGetFullPath (path);
+
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
+
 #if !NET_2_1
                        if (SecurityManager.SecurityEnabled) {
                                new FileIOPermission (FileIOPermissionAccess.PathDiscovery, fullpath).Demand ();
@@ -437,6 +440,8 @@ namespace System.IO {
                        Random rnd;
                        int num = 0;
 
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
+
                        rnd = new Random ();
                        do {
                                num = rnd.Next ();
@@ -466,6 +471,8 @@ namespace System.IO {
                [EnvironmentPermission (SecurityAction.Demand, Unrestricted = true)]
                public static string GetTempPath ()
                {
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
+
                        string p = get_temp_path ();
                        if (p.Length > 0 && p [p.Length - 1] != DirectorySeparatorChar)
                                return p + DirectorySeparatorChar;
@@ -736,7 +743,7 @@ namespace System.IO {
                        return String.Compare (subset, slast, path, slast, subset.Length - slast) == 0;
                }
 
-#if NET_4_0
+#if NET_4_0 || MOONLIGHT
                public static string Combine (params string [] paths)
                {
                        if (paths == null)
@@ -781,5 +788,25 @@ namespace System.IO {
                        return Combine (new string [] { path1, path2, path3, path4 });
                }
 #endif
+
+               internal static void Validate (string path)
+               {
+                       Validate (path, "path");
+               }
+
+               internal static void Validate (string path, string parameterName)
+               {
+                       if (path == null)
+                               throw new ArgumentNullException (parameterName);
+                       if (String.IsNullOrWhiteSpace (path))
+                               throw new ArgumentException (Locale.GetText ("Path is empty"));
+                       if (path.IndexOfAny (Path.InvalidPathChars) != -1)
+                               throw new ArgumentException (Locale.GetText ("Path contains invalid chars"));
+#if MOONLIGHT
+                       // On Moonlight (SL4+) there are some limitations in "Elevated Trust"
+                       if (SecurityManager.HasElevatedPermissions) {
+                       }
+#endif
+               }
        }
 }
index d77ec7bf58cad5ebe602dad0b208f624fde1f656..9c2bfd341c0ec0a963412da7dc3dc0594414cfd7 100644 (file)
 using System.Runtime.InteropServices;
 
 namespace System.IO {
-#if !NET_2_1 || MONOTOUCH
        [ComVisible (true)]
        [Serializable]
        public
-#endif
        enum SearchOption {
                TopDirectoryOnly = 0,
                AllDirectories = 1
index 2d1f4fb45d090b46b33cf1d24d6c65ca3cd8801b..17c8cc457eb82bc3b2733a00659fb5546c423e09 100644 (file)
@@ -261,7 +261,7 @@ namespace System.IO
                                throw result.Exception;
                }
 
-#if NET_4_0
+#if MOONLIGHT || NET_4_0
                public void CopyTo (Stream destination)
                {
                        CopyTo (destination, 16*1024);
index 9e5f558585cc855ee4d9b226d871e4088cc6be2f..279922b43edb9c6eea0923df3a38070fdaf1864b 100644 (file)
@@ -383,6 +383,10 @@ namespace System.IO {
                                        Encoding old = encoding;
                                        parse_start = DoChecks (cbEncoded);
                                        if (old != encoding){
+                                               int old_decoded_size = old.GetMaxCharCount (buffer_size) + 1;
+                                               int new_decoded_size = encoding.GetMaxCharCount (buffer_size) + 1;
+                                               if (old_decoded_size != new_decoded_size)
+                                                       decoded_buffer = new char [new_decoded_size];
                                                decoder = encoding.GetDecoder ();
                                        }
                                        do_checks = 0;
index 96d4401f4a1cd30f62dee31367eba5f47da323de..903c779b11d802570e17cb5516f07ac5ed186086 100644 (file)
@@ -93,11 +93,16 @@ namespace System.Reflection.Emit
        internal class GenericInstanceKey {
                Type gtd;
                internal Type[] args;
+               int hash_code;
 
                internal GenericInstanceKey (Type gtd, Type[] args)
                {
                        this.gtd = gtd;
                        this.args = args;
+
+                       hash_code = gtd.GetHashCode ();
+                       for (int i = 0; i < args.Length; ++i)
+                               hash_code ^= args [i].GetHashCode ();
                }
 
                static bool IsBoundedVector (Type type) {
@@ -193,10 +198,7 @@ namespace System.Reflection.Emit
 
                public override int GetHashCode ()
                {
-                       int hash = gtd.GetHashCode ();
-                       for (int i = 0; i < args.Length; ++i)
-                               hash ^= args [i].GetHashCode ();
-                       return hash;
+                       return hash_code;
                }
        }
 
@@ -262,7 +264,7 @@ namespace System.Reflection.Emit
                        // remove Mono specific flag to allow enum check to pass
                        access &= ~COMPILER_ACCESS;
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        // only "Run" is supported by Silverlight
                        // however SMCS requires more than this but runs outside the CoreCLR sandbox
                        if (SecurityManager.SecurityEnabled && (access != AssemblyBuilderAccess.Run))
@@ -1197,5 +1199,93 @@ namespace System.Reflection.Emit
                {
                        throw new NotImplementedException ();
                }
+
+#if NET_4_0
+               public override Type GetType (string name, bool throwOnError, bool ignoreCase)
+               {
+                       if (name == null)
+                               throw new ArgumentNullException (name);
+                       if (name.Length == 0)
+                       throw new ArgumentException ("name", "Name cannot be empty");
+
+                       var res = InternalGetType (null, name, throwOnError, ignoreCase);
+                       if (res is TypeBuilder) {
+                               if (throwOnError)
+                                       throw new TypeLoadException (string.Format ("Could not load type '{0}' from assembly '{1}'", name, this.name));
+                               return null;
+                       }
+                       return res;
+               }
+
+               public override Module GetModule (String name)
+               {
+                       if (name == null)
+                               throw new ArgumentNullException ("name");
+                       if (name.Length == 0)
+                               throw new ArgumentException ("Name can't be empty");
+
+                       if (modules == null)
+                               return null;
+
+                       foreach (Module module in modules) {
+                               if (module.ScopeName == name)
+                                       return module;
+                       }
+
+                       return null;
+               }
+
+               public override Module[] GetModules (bool getResourceModules)
+               {
+                       Module[] modules = GetModulesInternal ();
+
+                       if (!getResourceModules) {
+                               ArrayList result = new ArrayList (modules.Length);
+                               foreach (Module m in modules)
+                                       if (!m.IsResource ())
+                                               result.Add (m);
+                               return (Module[])result.ToArray (typeof (Module));
+                       }
+                       return modules;
+               }
+
+               [MonoTODO ("This always returns an empty array")]
+               public override AssemblyName[] GetReferencedAssemblies () {
+                       return GetReferencedAssemblies (this);
+               }
+
+               public override Module[] GetLoadedModules (bool getResourceModules)
+               {
+                       return GetModules (getResourceModules);
+               }
+
+               //FIXME MS has issues loading satelite assemblies from SRE
+               public override Assembly GetSatelliteAssembly (CultureInfo culture)
+               {
+                       return GetSatelliteAssembly (culture, null, true);
+               }
+
+               //FIXME MS has issues loading satelite assemblies from SRE
+               public override Assembly GetSatelliteAssembly (CultureInfo culture, Version version)
+               {
+                       return GetSatelliteAssembly (culture, version, true);
+               }
+
+               public override Module ManifestModule {
+                       get {
+                               return GetManifestModule ();
+                       }
+               }
+
+               public override bool GlobalAssemblyCache {
+                       get {
+                               return false;
+                       }
+               }
+
+               public override bool IsDynamic {
+                       get { return true; }
+               }
+#endif
        }
 }
index 9c88a72a857c2efce198411c956d7740a151d912..e4ee42ee92873151d0e5af2e01a9013adcaeaa3f 100644 (file)
@@ -1,3 +1,147 @@
+2010-04-20 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * TypeBuilder.cs (CreateType): Move default constructor
+       and createTypeCalled assignment to before the parent checks.
+
+       * TypeBuilder.cs (is_created): Return true even if creation
+       fails.
+
+       Fixes #331126
+
+2010-04-09 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * TypeBuilder.cs (IsValueTypeImpl): Don't depend on
+       type_is_subtype_of icall. Fixes corlib compilation.
+
+2010-04-08 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * EnumBuilder.cs:
+       * GenericTypeParameterBuilder.cs:
+       * DerivedTypes.cs:
+       * TypeBuilder.cs: Add ResolveInternal virtual call that
+       resolves a given type to it's concrete type.
+
+       * TypeBuilder.cs (DefineDefaultConstructor): Use
+       ResolveInternal on parent to do the lookup on a
+       finished type.
+
+       Fixes #591225.
+
+2010-04-08 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * AssemblyBuilder.cs (GenericInstanceKey): Precalculate
+       GenericInstanceKey hash code since this can cause infinite
+       recursion when inflating "Foo<T> : Bar<Foo<T>>" parent.
+
+       * TypeBuilder.cs (IsSubclassOf): Don't delegate to base class
+       since the unmanaged information can be out of sync.
+
+       * TypeBuilder.cs (UnderlyingSystemType): Invert the test order
+       since IsEnum now is potentialy more expensive.
+
+       Fixes #594728.
+
+2010-04-06  Marek Safar  <marek.safar@gmail.com>
+
+       * ModuleBuilder.cs: Use Dictionary.
+
+2010-04-01 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * ModuleBuilder.cs: Implement Resolve*.
+
+2010-04-01 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * ModuleBuilder.cs: Implement ModuleVersionId.
+
+2010-04-01 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * ModuleBuilder.cs: Implement ResolveType.
+
+2010-04-01 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * ModuleBuilder.cs: Implement GetMethodImpl.
+
+2010-04-01 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * ModuleBuilder.cs (DefineType): Raise the correct exception
+       when name is null.
+
+2010-04-01 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * ModuleBuilder.cs: Implement IsResource.
+
+2010-04-01 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * ModuleBuilder.cs: Implement ScopedName property.
+
+2010-04-01 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * ModuleBuilder.cs: Implement Name property.
+
+2010-03-31 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * ModuleBuilder.cs: Implement Assembly property.
+
+2010-04-01  Zoltan Varga  <vargaz@gmail.com>
+
+       * TypeBuilder.cs (GetField): Avoid a crash if this is called on a
+       FieldOnTypeBuilderInst. Fixes #586944.
+
+2010-03-30  Zoltan Varga  <vargaz@gmail.com>
+
+       * ModuleBuilder.cs (DefinedType): Lookup inside the name_cache before creating
+       the TypeBuilder since the runtime code can't handle a duplicate type name.
+
+2010-03-30  Zoltan Varga  <vargaz@gmail.com>
+
+       * CustomAttributeType.cs (IsValidType): Implement proper checking for value types
+       as well.
+
+2010-03-30  Zoltan Varga  <vargaz@gmail.com>
+
+       * CustomAttributeBuilder.cs: Fix the calls to IsValidType, some were passing
+       in DeclaringType instead of PropertyType/FieldType.
+
+       * CustomAttributeType.cs (IsValidType): Implement proper checking for reference
+       types. Fixes #591788.
+
+2010-03-30  Zoltan Varga  <vargaz@gmail.com>
+
+       * CustomAttributeBuilder.cs (IsValidType): Call Enum.GetUnderlyingType () for
+       dynamic enums to avoid crashes in the unmanaged code. Fixes #591800.
+
+2010-03-26 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * AssemblyBuilder.cs: Add IsDynamic.
+
+2010-03-26 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * AssemblyBuilder.cs: Implement v4 GetSatelliteAssembly,
+       ManifestModule, GlobalAssemblyCache.
+
+2010-03-26 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * AssemblyBuilder.cs: Implement v4 GetReferencedAssemblies
+       and GetLoadedModules.
+
+2010-03-25 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * AssemblyBuilder.cs: Implement v4 GetModules().
+
+2010-03-25 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * AssemblyBuilder.cs: Implement v4 GetType.
+
+2010-03-23 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * MethodOnTypeBuilderInst.cs (ContainsGenericParameters): Check
+       the base_method first.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * AssemblyBuilder.cs, ModuleBuilder.cs: use MOONLIGHT symbol to
+       disambiguate MonoTouch and Moonlight code.
+
 2010-03-12  Jb Evain  <jbevain@novell.com>
 
        * AssemblyBuilder.cs (AddTypeForwarder): throw if the
index c546800f8e85b4d4bc46c6156cf54314a884f13a..06492edf31c36bc2d098cb78ce03c87920689e48 100644 (file)
@@ -91,6 +91,15 @@ namespace System.Reflection.Emit {
                        /* FIXME: Add more checks */
                        if (t.IsArray && t.GetArrayRank () > 1)
                                return false;
+                       if (t is TypeBuilder && t.IsEnum) {
+                               // Check that the enum is properly constructed, the unmanaged code
+                               // depends on this
+                               Enum.GetUnderlyingType (t);
+                       }
+                       if (t.IsClass && !(t.IsArray || t == typeof (object) || t == typeof (Type) || t == typeof (string) || t.Assembly.GetName ().Name == "mscorlib"))
+                               return false;
+                       if (t.IsValueType && !(t.IsPrimitive || t.IsEnum || ((t.Assembly is AssemblyBuilder) && t.Assembly.GetName ().Name == "mscorlib")))
+                               return false;
                        return true;
                }
 
@@ -143,10 +152,10 @@ namespace System.Reflection.Emit {
                        i = 0;
                        foreach (FieldInfo fi in namedFields) {
                                Type t = fi.DeclaringType;
-                               if (!IsValidType (t))
-                                       throw new ArgumentException ("Field '" + fi.Name + "' does not have a valid type.");
                                if ((atype != t) && (!t.IsSubclassOf (atype)) && (!atype.IsSubclassOf (t)))
                                        throw new ArgumentException ("Field '" + fi.Name + "' does not belong to the same class as the constructor");
+                               if (!IsValidType (fi.FieldType))
+                                       throw new ArgumentException ("Field '" + fi.Name + "' does not have a valid type.");
                                // FIXME: Check enums and TypeBuilders as well
                                if (fieldValues [i] != null)
                                        // IsEnum does not seem to work on TypeBuilders
@@ -166,10 +175,10 @@ namespace System.Reflection.Emit {
                                if (!pi.CanWrite)
                                        throw new ArgumentException ("Property '" + pi.Name + "' does not have a setter.");
                                Type t = pi.DeclaringType;
-                               if (!IsValidType (t))
-                                       throw new ArgumentException ("Property '" + pi.Name + "' does not have a valid type.");
                                if ((atype != t) && (!t.IsSubclassOf (atype)) && (!atype.IsSubclassOf (t)))
                                        throw new ArgumentException ("Property '" + pi.Name + "' does not belong to the same class as the constructor");
+                               if (!IsValidType (pi.PropertyType))
+                                       throw new ArgumentException ("Property '" + pi.Name + "' does not have a valid type.");
                                if (propertyValues [i] != null) {
                                        if (!(pi.PropertyType is TypeBuilder) && !pi.PropertyType.IsEnum && !pi.PropertyType.IsInstanceOfType (propertyValues [i]))
                                                if (!pi.PropertyType.IsArray)
@@ -183,7 +192,7 @@ namespace System.Reflection.Emit {
                                if (pi != null) {
                                        Type paramType = pi.ParameterType;
                                        if (!IsValidType (paramType))
-                                               throw new ArgumentException ("Argument " + i + " does not have a valid type.");
+                                               throw new ArgumentException ("Parameter " + i + " does not have a valid type.");
                                        if (constructorArgs [i] != null) {
                                                if (!(paramType is TypeBuilder) && !paramType.IsEnum && !paramType.IsInstanceOfType (constructorArgs [i]))
                                                        if (!paramType.IsArray)
index 43ff5e6a7aabbbe418f2f42e7bd89c45c9e81755..04e7f3c9d70bad3e9f9b29346ae445e6c632ea1b 100644 (file)
@@ -337,6 +337,14 @@ namespace System.Reflection.Emit
                        return rank;
                }
 
+               internal override Type InternalResolve ()
+               {
+                       Type et = elementType.InternalResolve (); 
+                       if (rank == 0)
+                               return et.MakeArrayType ();                     
+                       return et.MakeArrayType (rank);
+               }
+
                protected override bool IsArrayImpl ()
                {
                        return true;
@@ -380,6 +388,11 @@ namespace System.Reflection.Emit
                {
                }
 
+               internal override Type InternalResolve ()
+               {
+                       return elementType.InternalResolve ().MakeByRefType (); 
+               }
+
                protected override bool IsByRefImpl ()
                {
                        return true;
@@ -424,6 +437,11 @@ namespace System.Reflection.Emit
                {
                }
 
+               internal override Type InternalResolve ()
+               {
+                       return elementType.InternalResolve ().MakePointerType (); 
+               }
+
                protected override bool IsPointerImpl ()
                {
                        return true;
index 8b3c84c42922c18dfa2a4bef45304117d409ffd3..44d4f374665d031a3e0736f551016bd10adecf0d 100644 (file)
@@ -256,6 +256,11 @@ namespace System.Reflection.Emit {
                        }
                        return retval;
                }
+               
+               internal override int GetParameterCount ()
+               {
+                       return parameters == null ? 0 : parameters.Length;
+               }               
 
                /*
                public override object Invoke (object obj, object[] parameters) {
index 8b851bb84beae14affcd925f9600cdaa43d64fed..76402331ca5d2f0d260496fbe1e1a8554f820e00 100644 (file)
@@ -68,6 +68,12 @@ namespace System.Reflection.Emit {
                        }
                }
 
+               internal override Type InternalResolve ()
+               {
+                       return _tb.InternalResolve (); 
+               }
+
+
                public override Assembly Assembly {
                        get {
                                return _tb.Assembly;
index 5e1193c4139fc0936c5acaddd39d4608b15ad282..e32565319c8130964ffa22697a811645ef9cf825 100644 (file)
@@ -88,6 +88,11 @@ namespace System.Reflection.Emit
                        }
                }
 
+               internal override Type InternalResolve ()
+               {
+                       return tbuilder.InternalResolve ().GetGenericArguments () [index]; 
+               }
+
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private extern void initialize ();
 
index 68b5d3ab7dac6157aa2e23349d8385c6cbe82a03..6b976e8a9812f687ae174d48d45d902f9ecc4ed1 100644 (file)
@@ -286,6 +286,8 @@ namespace System.Reflection.Emit
 
                public override bool ContainsGenericParameters {
                        get {
+                               if (base_method.ContainsGenericParameters)
+                                       return true;
                                if (!base_method.IsGenericMethodDefinition)
                                        throw new NotSupportedException ();
                                if (method_arguments == null)
index 672be8b6b6129c6830d81650b440bb8dc32d7280..8033613647b05c858e120c66f8bd54dd4bde8741 100644 (file)
@@ -34,6 +34,7 @@
 using System;
 using System.Reflection;
 using System.Collections;
+using System.Collections.Generic;
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
 using System.Diagnostics.SymbolStore;
@@ -66,7 +67,7 @@ namespace System.Reflection.Emit {
                private TypeBuilder global_type;
                private Type global_type_created;
                Hashtable name_cache;
-               Hashtable us_string_cache = new Hashtable ();
+               Dictionary<string, int> us_string_cache;
                private int[] table_indexes;
                bool transient;
                ModuleBuilderTokenGenerator token_gen;
@@ -89,6 +90,7 @@ namespace System.Reflection.Emit {
                        // guid = Guid.NewGuid().ToByteArray ();
                        table_idx = get_next_table_index (this, 0x00, true);
                        name_cache = new Hashtable ();
+                       us_string_cache = new Dictionary<string, int> (512);
 
                        basic_init (this);
 
@@ -101,7 +103,7 @@ namespace System.Reflection.Emit {
                        }
 
                        if (emitSymbolInfo) {
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                                symbolWriter = new Mono.CompilerServices.SymbolWriter.SymbolWriterImpl (this);
 #else
                                Assembly asm = Assembly.LoadWithPartialName ("Mono.CompilerServices.SymbolWriter");
@@ -264,14 +266,14 @@ namespace System.Reflection.Emit {
                }
 
                private TypeBuilder DefineType (string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, int typesize) {
+                       if (name == null)
+                               throw new ArgumentNullException ("fullname");
+                       if (name_cache.ContainsKey (name))
+                               throw new ArgumentException ("Duplicate type name within an assembly.");
                        TypeBuilder res = new TypeBuilder (this, name, attr, parent, interfaces, packingSize, typesize, null);
                        AddType (res);
-                       
-                       try {
-                               name_cache.Add (name, res);
-                       } catch {
-                               throw new ArgumentException ("Duplicate type name within an assembly.");
-                       }
+
+                       name_cache.Add (name, res);
                        
                        return res;
                }
@@ -660,11 +662,14 @@ namespace System.Reflection.Emit {
                private static extern int getMethodToken (ModuleBuilder mb, MethodInfo method,
                                                          Type[] opt_param_types);
 
-               internal int GetToken (string str) {
-                       if (us_string_cache.Contains (str))
-                               return (int)us_string_cache [str];
-                       int result = getUSIndex (this, str);
-                       us_string_cache [str] = result;
+               internal int GetToken (string str)
+               {
+                       int result;
+                       if (!us_string_cache.TryGetValue (str, out result)) {
+                               result = getUSIndex (this, str);
+                               us_string_cache [str] = result;
+                       }
+                       
                        return result;
                }
 
@@ -815,6 +820,103 @@ namespace System.Reflection.Emit {
                {
                        throw new NotImplementedException ();
                }
+
+#if NET_4_0
+               public override Assembly Assembly {
+                       get { return assemblyb; }
+               }
+
+               public override string Name {
+                       get { return name; }
+               }
+
+               public override string ScopeName {
+                       get { return name; }
+               }
+
+               public override Guid ModuleVersionId {
+                       get {
+                               return GetModuleVersionId ();
+                       }
+               }
+
+               //XXX resource modules can't be defined with ModuleBuilder
+               public override bool IsResource ()
+               {
+                       return false;
+               }
+
+               protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) 
+               {
+                       if (global_type_created == null)
+                               return null;
+                       if (types == null)
+                               return global_type_created.GetMethod (name);
+                       return global_type_created.GetMethod (name, bindingAttr, binder, callConvention, types, modifiers);
+               }
+
+               public override FieldInfo ResolveField (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
+                       ResolveTokenError error;
+
+                       IntPtr handle = ResolveFieldToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
+                       if (handle == IntPtr.Zero)
+                               throw resolve_token_exception (metadataToken, error, "Field");
+                       else
+                               return FieldInfo.GetFieldFromHandle (new RuntimeFieldHandle (handle));
+               }
+
+               public override MemberInfo ResolveMember (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
+
+                       ResolveTokenError error;
+
+                       MemberInfo m = ResolveMemberToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
+                       if (m == null)
+                               throw resolve_token_exception (metadataToken, error, "MemberInfo");
+                       else
+                               return m;
+               }
+
+               public override MethodBase ResolveMethod (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
+                       ResolveTokenError error;
+
+                       IntPtr handle = ResolveMethodToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
+                       if (handle == IntPtr.Zero)
+                               throw resolve_token_exception (metadataToken, error, "MethodBase");
+                       else
+                               return MethodBase.GetMethodFromHandleNoGenericCheck (new RuntimeMethodHandle (handle));
+               }
+
+               public override string ResolveString (int metadataToken) {
+                       ResolveTokenError error;
+
+                       string s = ResolveStringToken (_impl, metadataToken, out error);
+                       if (s == null)
+                               throw resolve_token_exception (metadataToken, error, "string");
+                       else
+                               return s;
+               }
+
+               public override byte[] ResolveSignature (int metadataToken) {
+                       ResolveTokenError error;
+
+                   byte[] res = ResolveSignature (_impl, metadataToken, out error);
+                       if (res == null)
+                               throw resolve_token_exception (metadataToken, error, "signature");
+                       else
+                               return res;
+               }
+
+               public override Type ResolveType (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
+                       ResolveTokenError error;
+
+                       IntPtr handle = ResolveTypeToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
+                       if (handle == IntPtr.Zero)
+                               throw resolve_token_exception (metadataToken, error, "Type");
+                       else
+                               return Type.GetTypeFromHandle (new RuntimeTypeHandle (handle));
+               }
+
+#endif
        }
 
        internal class ModuleBuilderTokenGenerator : TokenGenerator {
index a64112f7c4236c6a3e5ba2c7002d2d63de86939d..2a5f8cc9fdfcc8759774115d808e96b5c252504a 100644 (file)
@@ -80,6 +80,12 @@ namespace System.Reflection {
                public override ParameterInfo[] GetParameters() {
                        return new ParameterInfo [0];
                }
+               
+               [MonoTODO("Not implemented.  Always returns 0")]
+               internal override int GetParameterCount ()
+               {
+                       return 0;
+               }               
 
                [MonoTODO("Not implemented")]
                public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) {
index 2b74fbeeca1a82c70120d9e325f4e60b506c4e27..0a7be28f12e0fdf5cc4146d4913b26bd6bbf5c2e 100644 (file)
@@ -173,7 +173,8 @@ namespace System.Reflection.Emit
                        get { return nesting_type; }
                }
 
-/*             public override bool IsSubclassOf (Type c)
+               [ComVisible (true)]
+               public override bool IsSubclassOf (Type c)
                {
                        Type t;
                        if (c == null)
@@ -187,14 +188,14 @@ namespace System.Reflection.Emit
                                t = t.BaseType;
                        }
                        return false;
-               }*/
+               }
 
                public override Type UnderlyingSystemType {
                        get {
                                if (is_created)
                                        return created.UnderlyingSystemType;
 
-                               if (IsEnum && !IsCompilerContext) {
+                               if (!IsCompilerContext && IsEnum) {
                                        if (underlying_type != null)
                                                return underlying_type;
                                        throw new InvalidOperationException (
@@ -479,6 +480,7 @@ namespace System.Reflection.Emit
                        else
                                parent_type = pmodule.assemblyb.corlib_object_type;
 
+                       parent_type = parent_type.InternalResolve ();
                        ConstructorInfo parent_constructor =
                                parent_type.GetConstructor (
                                        BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
@@ -764,6 +766,15 @@ namespace System.Reflection.Emit
                                }
                        }
 
+                       //
+                       // On classes, define a default constructor if not provided
+                       //
+                       if (!(IsInterface || IsValueType) && (ctors == null) && (tname != "<Module>") && 
+                               (GetAttributeFlagsImpl () & TypeAttributes.Abstract | TypeAttributes.Sealed) != (TypeAttributes.Abstract | TypeAttributes.Sealed) && !has_ctor_method ())
+                               DefineDefaultConstructor (MethodAttributes.Public);
+
+                       createTypeCalled = true;
+
                        if ((parent != null) && parent.IsSealed)
                                throw new TypeLoadException ("Could not load type '" + FullName + "' from assembly '" + Assembly + "' because the parent type is sealed.");
 
@@ -781,19 +792,11 @@ namespace System.Reflection.Emit
                                }
                        }
 
-                       //
-                       // On classes, define a default constructor if not provided
-                       //
-                       if (!(IsInterface || IsValueType) && (ctors == null) && (tname != "<Module>") && 
-                               (GetAttributeFlagsImpl () & TypeAttributes.Abstract | TypeAttributes.Sealed) != (TypeAttributes.Abstract | TypeAttributes.Sealed) && !has_ctor_method ())
-                               DefineDefaultConstructor (MethodAttributes.Public);
-
                        if (ctors != null){
                                foreach (ConstructorBuilder ctor in ctors) 
                                        ctor.fixup ();
                        }
 
-                       createTypeCalled = true;
                        created = create_runtime_class (this);
                        if (created != null)
                                return created;
@@ -1356,9 +1359,15 @@ namespace System.Reflection.Emit
                // FIXME: I doubt just removing this still works.
                protected override bool IsValueTypeImpl ()
                {
-                       return ((type_is_subtype_of (this, pmodule.assemblyb.corlib_value_type, false) || type_is_subtype_of (this, typeof(System.ValueType), false)) &&
-                               this != pmodule.assemblyb.corlib_value_type &&
-                               this != pmodule.assemblyb.corlib_enum_type);
+                       if (this == pmodule.assemblyb.corlib_value_type || this == pmodule.assemblyb.corlib_enum_type)
+                               return false;
+                       Type parent_type = parent;
+                       while (parent_type != null) {
+                               if (parent_type == pmodule.assemblyb.corlib_value_type)
+                                       return true;
+                               parent_type = parent_type.BaseType;
+                       }
+                       return false;
                }
                
                public override Type MakeArrayType ()
@@ -1632,9 +1641,15 @@ namespace System.Reflection.Emit
                        }
                }
 
+               internal override Type InternalResolve ()
+               {
+                       check_created ();
+                       return created;
+               }
+
                internal bool is_created {
                        get {
-                               return created != null;
+                               return createTypeCalled;
                        }
                }
 
@@ -1676,13 +1691,6 @@ namespace System.Reflection.Emit
                        return base.IsAssignableFrom (c);
                }
 
-               [ComVisible (true)]
-               [MonoTODO]
-               public override bool IsSubclassOf (Type c)
-               {
-                       return base.IsSubclassOf (c);
-               }
-
                [MonoTODO ("arrays")]
                internal bool IsAssignableTo (Type c)
                {
@@ -1864,6 +1872,9 @@ namespace System.Reflection.Emit
                        if (type.IsGenericTypeDefinition)
                                throw new ArgumentException ("Type cannot be a generic type definition", "type");
 
+                       if (field is FieldOnTypeBuilderInst)
+                               throw new ArgumentException ("The specified field must be declared on a generic type definition.", "field");
+
                        FieldInfo res = type.GetField (field);
                        if (res == null)
                                throw new System.Exception ("field not found");
index 0a436cf11e2aff3052f26427ac9e62f8640e2a45..d6068ba8cd30ad7165ee1c4e7d4d7256e7d086bd 100644 (file)
@@ -52,11 +52,12 @@ namespace System.Reflection {
        [Serializable]
        [ClassInterface(ClassInterfaceType.None)]
 #if NET_2_1
-       public class Assembly : ICustomAttributeProvider, _Assembly {
+       public partial class Assembly : ICustomAttributeProvider, _Assembly {
+#elif NET_4_0
+       public abstract class Assembly : ICustomAttributeProvider, _Assembly, IEvidenceFactory, ISerializable {
 #else
-       public class Assembly : ICustomAttributeProvider, _Assembly, IEvidenceFactory, ISerializable {
+       public partial class Assembly : ICustomAttributeProvider, _Assembly, IEvidenceFactory, ISerializable {
 #endif
-
                internal class ResolveEventHolder {
                        public event ModuleResolveEventHandler ModuleResolve;
                }
@@ -76,7 +77,12 @@ namespace System.Reflection {
                private bool fromByteArray;
                private string assemblyName;
 
-               internal Assembly () 
+#if NET_4_0
+               protected
+#else
+               internal
+#endif
+               Assembly () 
                {
                        resolve_event_holder = new ResolveEventHolder ();
                }
@@ -146,7 +152,7 @@ namespace System.Reflection {
                        [MethodImplAttribute (MethodImplOptions.InternalCall)]
                        get;
                }
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public virtual Evidence Evidence {
                        [SecurityPermission (SecurityAction.Demand, ControlEvidence = true)]
                        get { return UnprotectedGetEvidence (); }
@@ -166,13 +172,8 @@ namespace System.Reflection {
                }
 
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
-               private extern bool get_global_assembly_cache ();
+               internal extern bool get_global_assembly_cache ();
 
-               public bool GlobalAssemblyCache {
-                       get {
-                               return get_global_assembly_cache ();
-                       }
-               }
 #endif
                internal bool FromByteArray {
                        set { fromByteArray = value; }
@@ -292,7 +293,7 @@ namespace System.Reflection {
 
                                string location = Path.GetDirectoryName (Location);
                                string filename = Path.Combine (location, info.FileName);
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                                // we don't control the content of 'info.FileName' so we want to make sure we keep to ourselves
                                filename = Path.GetFullPath (filename);
                                if (!filename.StartsWith (location))
@@ -363,16 +364,6 @@ namespace System.Reflection {
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
                internal extern Type InternalGetType (Module module, String name, Boolean throwOnError, Boolean ignoreCase);
 
-               public Type GetType (string name, bool throwOnError, bool ignoreCase)
-               {
-                       if (name == null)
-                               throw new ArgumentNullException (name);
-                       if (name.Length == 0)
-                       throw new ArgumentException ("name", "Name cannot be empty");
-
-                       return InternalGetType (null, name, throwOnError, ignoreCase);
-               }
-
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
                internal extern static void InternalGetAssemblyName (string assemblyFile, AssemblyName aname);
 
@@ -429,22 +420,12 @@ namespace System.Reflection {
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
                public static extern Assembly GetEntryAssembly();
 
-               public Assembly GetSatelliteAssembly (CultureInfo culture)
-               {
-                       return GetSatelliteAssembly (culture, null, true);
-               }
-
-               public Assembly GetSatelliteAssembly (CultureInfo culture, Version version)
-               {
-                       return GetSatelliteAssembly (culture, version, true);
-               }
-
                internal Assembly GetSatelliteAssemblyNoThrow (CultureInfo culture, Version version)
                {
                        return GetSatelliteAssembly (culture, version, false);
                }
 
-               private Assembly GetSatelliteAssembly (CultureInfo culture, Version version, bool throwOnError)
+               internal Assembly GetSatelliteAssembly (CultureInfo culture, Version version, bool throwOnError)
                {
                        if (culture == null)
                                throw new ArgumentException ("culture");
@@ -469,7 +450,7 @@ namespace System.Reflection {
                        // Try the assembly directory
                        string location = Path.GetDirectoryName (Location);
                        string fullName = Path.Combine (location, Path.Combine (culture.Name, aname.Name + ".dll"));
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        // it's unlikely that culture.Name or aname.Name could contain stuff like ".." but...
                        fullName = Path.GetFullPath (fullName);
                        if (!fullName.StartsWith (location)) {
@@ -492,6 +473,9 @@ namespace System.Reflection {
                        return LoadFrom (assemblyFile, false);
                }
 
+#if NET_4_0
+               [Obsolete]
+#endif
                public static Assembly LoadFrom (String assemblyFile, Evidence securityEvidence)
                {
                        Assembly a = LoadFrom (assemblyFile, false);
@@ -504,6 +488,9 @@ namespace System.Reflection {
                        return a;
                }
 
+#if NET_4_0
+               [Obsolete]
+#endif
                [MonoTODO("This overload is not currently implemented")]
                // FIXME: What are we missing?
                public static Assembly LoadFrom (String assemblyFile, Evidence securityEvidence, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm)
@@ -515,6 +502,9 @@ namespace System.Reflection {
                        throw new NotImplementedException ();
                }
 
+#if NET_4_0
+               [Obsolete]
+#endif
                public static Assembly LoadFile (String path, Evidence securityEvidence)
                {
                        if (path == null)
@@ -534,7 +524,10 @@ namespace System.Reflection {
                {
                        return AppDomain.CurrentDomain.Load (assemblyString);
                }
-               
+
+#if NET_4_0
+               [Obsolete]
+#endif         
                public static Assembly Load (String assemblyString, Evidence assemblySecurity)
                {
                        return AppDomain.CurrentDomain.Load (assemblyString, assemblySecurity);
@@ -545,6 +538,9 @@ namespace System.Reflection {
                        return AppDomain.CurrentDomain.Load (assemblyRef);
                }
 
+#if NET_4_0
+               [Obsolete]
+#endif
                public static Assembly Load (AssemblyName assemblyRef, Evidence assemblySecurity)
                {
                        return AppDomain.CurrentDomain.Load (assemblyRef, assemblySecurity);
@@ -560,6 +556,9 @@ namespace System.Reflection {
                        return AppDomain.CurrentDomain.Load (rawAssembly, rawSymbolStore);
                }
 
+#if NET_4_0
+               [Obsolete]
+#endif
                public static Assembly Load (Byte[] rawAssembly, Byte[] rawSymbolStore,
                                             Evidence securityEvidence)
                {
@@ -584,6 +583,9 @@ namespace System.Reflection {
                        return LoadFrom (assemblyFile, true);
                }
 
+#if NET_4_0
+               [Obsolete]
+#endif
                public static Assembly LoadWithPartialName (string partialName)
                {
                        return LoadWithPartialName (partialName, null);
@@ -596,7 +598,11 @@ namespace System.Reflection {
                }
 
                [MonoTODO ("Not implemented")]
-               public Module LoadModule (string moduleName, byte [] rawModule, byte [] rawSymbolStore)
+               public
+#if NET_4_0
+               virtual
+#endif
+               Module LoadModule (string moduleName, byte [] rawModule, byte [] rawSymbolStore)
                {
                        throw new NotImplementedException ();
                }
@@ -604,6 +610,9 @@ namespace System.Reflection {
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
                private static extern Assembly load_with_partial_name (string name, Evidence e);
 
+#if NET_4_0
+               [Obsolete]
+#endif
                public static Assembly LoadWithPartialName (string partialName, Evidence securityEvidence)
                {
                        return LoadWithPartialName (partialName, securityEvidence, true);
@@ -646,7 +655,11 @@ namespace System.Reflection {
                        }
                }
 
-               public Object CreateInstance (String typeName, Boolean ignoreCase,
+               public
+#if NET_4_0
+               virtual
+#endif
+               Object CreateInstance (String typeName, Boolean ignoreCase,
                                              BindingFlags bindingAttr, Binder binder,
                                              Object[] args, CultureInfo culture,
                                              Object[] activationAttributes)
@@ -667,49 +680,14 @@ namespace System.Reflection {
                        return GetLoadedModules (false);
                }
 
-               // FIXME: Currently, the two sets of modules are equal
-               public Module[] GetLoadedModules (bool getResourceModules)
-               {
-                       return GetModules (getResourceModules);
-               }
-
                public Module[] GetModules ()
                {
                        return GetModules (false);
                }
 
-               public Module GetModule (String name)
-               {
-                       if (name == null)
-                               throw new ArgumentNullException ("name");
-                       if (name.Length == 0)
-                               throw new ArgumentException ("Name can't be empty");
-
-                       Module[] modules = GetModules (true);
-                       foreach (Module module in modules) {
-                               if (module.ScopeName == name)
-                                       return module;
-                       }
-
-                       return null;
-               }
-
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
                internal virtual extern Module[] GetModulesInternal ();
 
-               public Module[] GetModules (bool getResourceModules) {
-                       Module[] modules = GetModulesInternal ();
-
-                       if (!getResourceModules) {
-                               ArrayList result = new ArrayList (modules.Length);
-                               foreach (Module m in modules)
-                                       if (!m.IsResource ())
-                                               result.Add (m);
-                               return (Module[])result.ToArray (typeof (Module));
-                       }
-                       else
-                               return modules;
-               }
 
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
                internal extern string[] GetNamespaces ();
@@ -724,7 +702,7 @@ namespace System.Reflection {
                public extern static Assembly GetCallingAssembly ();
 
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
-               public extern AssemblyName[] GetReferencedAssemblies ();
+               internal static extern AssemblyName[] GetReferencedAssemblies (Assembly module);
 
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
                private extern bool GetManifestResourceInfoInternal (String name, ManifestResourceInfo info);
@@ -767,16 +745,14 @@ namespace System.Reflection {
 
                [MonoTODO ("Currently it always returns zero")]
                [ComVisible (false)]
-               public long HostContext {
+               public
+#if NET_4_0
+               virtual
+#endif
+               long HostContext {
                        get { return 0; }
                }
 
-               [ComVisible (false)]
-               public Module ManifestModule {
-                       get {
-                               return GetManifestModule ();
-                       }
-               }
 
                internal virtual Module GetManifestModule () {
                        return GetManifestModuleInternal ();
@@ -809,7 +785,7 @@ namespace System.Reflection {
                }
 #endif
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                // Code Access Security
 
                internal void Resolve () 
@@ -891,6 +867,84 @@ namespace System.Reflection {
                        }
                }
 #endif
+
+#if NET_4_0
+               static Exception CreateNIE ()
+               {
+                       return new NotImplementedException ("Derived classes must implement it");
+               }
+
+               public virtual Type GetType (string name, bool throwOnError, bool ignoreCase)
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual Module GetModule (String name)
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual AssemblyName[] GetReferencedAssemblies ()
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual Module[] GetModules (bool getResourceModules)
+               {
+                       throw CreateNIE ();
+               }
+
+               [MonoTODO ("Always returns the same as GetModules")]
+               public virtual Module[] GetLoadedModules (bool getResourceModules)
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual Assembly GetSatelliteAssembly (CultureInfo culture)
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual Assembly GetSatelliteAssembly (CultureInfo culture, Version version)
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual Module ManifestModule {
+                       get { throw CreateNIE (); }
+               }
+
+               public virtual bool GlobalAssemblyCache {
+                       get { throw CreateNIE (); }
+               }
+
+               public virtual bool IsDynamic {
+                       get { return false; }
+               }
+
+               public override int GetHashCode ()
+               {
+                       return base.GetHashCode ();
+               }
+
+               public static bool operator == (Assembly left, Assembly right)
+               {
+                       if ((object)left == (object)right)
+                               return true;
+                       if ((object)left == null ^ (object)right == null)
+                               return false;
+                       return left.Equals (right);
+               }
+
+               public static bool operator != (Assembly left, Assembly right)
+               {
+                       if ((object)left == (object)right)
+                               return false;
+                       if ((object)left == null ^ (object)right == null)
+                               return true;
+                       return !left.Equals (right);
+               }
+#endif
        }
 }
 
index 5095bb8b68635c47c562c3390700bd5b9eccf408..615db74d7936d59b98fa795831711593b1e045b1 100644 (file)
@@ -167,9 +167,41 @@ namespace System.Reflection
                                state = null;
                                if (names != null)
                                        ReorderParameters (names, ref args, selected);
+
+                               if (selected != null) {
+                                       if (args == null)
+                                               args = new object [0];
+       
+                                       AdjustArguments (selected, ref args);
+                               }
+
                                return selected;
                        }
 
+                       // probably belongs in ReorderArgumentArray
+                       static void AdjustArguments (MethodBase selected, ref object [] args)
+                       {
+                               var parameters = selected.GetParameters ();
+                               if (parameters.Length == 0)
+                                       return;
+
+                               var last_parameter = parameters [parameters.Length - 1];
+                               if (!Attribute.IsDefined (last_parameter, typeof (ParamArrayAttribute)))
+                                       return;
+
+                               var adjusted = new object [parameters.Length];
+                               Array.Copy (args, adjusted, parameters.Length - 1);
+
+                               var param_args_count = args.Length + 1 - parameters.Length;
+                               var params_args = Array.CreateInstance (last_parameter.ParameterType.GetElementType (), param_args_count);
+
+                               for (int i = 0; i < param_args_count; i++)
+                                       params_args.SetValue (args [args.Length - param_args_count + i], i);
+
+                               adjusted [adjusted.Length - 1] = params_args;
+                               args = adjusted;
+                       }
+
                        void ReorderParameters (string [] names, ref object [] args, MethodBase selected)
                        {
                                object [] newArgs = new object [args.Length];
@@ -383,6 +415,7 @@ namespace System.Reflection
                                        throw new ArgumentNullException ("match");
 
                                /* first look for an exact match... */
+                               MethodBase exact_match = null;
                                for (i = 0; i < match.Length; ++i) {
                                        m = match [i];
                                        ParameterInfo[] args = m.GetParameters ();
@@ -392,9 +425,17 @@ namespace System.Reflection
                                                if (types [j] != args [j].ParameterType)
                                                        break;
                                        }
-                                       if (j == types.Length)
-                                               return m;
+                                       if (j == types.Length) {
+                                               if (exact_match != null) {
+                                                       exact_match = null;
+                                                       break;
+                                               } else {
+                                                       exact_match = m;
+                                               }
+                                       }
                                }
+                               if (exact_match != null)
+                                       return exact_match;
 
                                /* Try methods with ParamArray attribute */
                                bool isdefParamArray = false;
@@ -402,7 +443,7 @@ namespace System.Reflection
                                for (i = 0; i < match.Length; ++i) {
                                        m = match [i];
                                        ParameterInfo[] args = m.GetParameters ();
-                                       if (args.Length > types.Length)
+                                       if (args.Length > types.Length + 1)
                                                continue;
                                        else if (args.Length == 0)
                                                continue;
@@ -443,13 +484,6 @@ namespace System.Reflection
 
                        MethodBase GetBetterMethod (MethodBase m1, MethodBase m2, Type [] types)
                        {
-                               if (m1.IsGenericMethodDefinition && 
-                                   !m2.IsGenericMethodDefinition)
-                                       return m2;
-                               if (m2.IsGenericMethodDefinition && 
-                                   !m1.IsGenericMethodDefinition)
-                                       return m1;
-
                                ParameterInfo [] pl1 = m1.GetParameters ();
                                ParameterInfo [] pl2 = m2.GetParameters ();
                                int prev = 0;
index fda76e313a03394c5f659057b51fab6d94037ecc..7a5dca0e2ca416733ef52f087d849953118f173e 100644 (file)
@@ -1,3 +1,164 @@
+2010-04-20 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Binder.cs (SelectMethod): Exact matching must check
+       all entries because if two of them match, we must use
+       the slow path.
+
+       * Binder.cs (GetBetterMethod): Don't give generic method
+       definition special treatment.
+
+       Fixes #325306.
+
+2010-04-08 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * MonoGenericClass.cs: Implement ResolveInternal.
+
+2010-04-08 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * MonoField.cs (Get|Set)Value: Check if obj is compatible
+       with field's class.
+
+2010-04-02  Marek Safar  <marek.safar@gmail.com>
+
+       * MethodBase.cs: Made GetParameterCount abstract and implement
+       where missing to avoid redundant allocations.
+
+2010-04-01 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Module.cs (GetMethod): Check for null 'types' argument.
+
+       * MonoModule.cs (GetMethodImpl): Special case when 'types'
+       is null and call Type::GetMethod(string) directly.
+       This is ok since proper checking of the 'types' overload
+       is done by callers.
+
+2010-04-01  Jb Evain  <jbevain@novell.com>
+
+       * Module.cs: make Module abstract on net_4_0.
+
+2010-03-31 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Module.cs:
+       * MonoModule.cs: Implement MetadataToken, FullyQualifiedName,
+       ModuleVersionId, MDStreamVersion, ScopeName,
+       Name, Assembly.
+
+2010-03-31 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Module.cs:
+       * MonoModule.cs: Implement GetSignerCertificate and
+       GetTypes.
+
+2010-03-31 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Module.cs:
+       * MonoModule.cs: Implement ResolveMember, ResolveMethod,
+       ResolveString, ResolveType, ResolveSignature and
+       GetMethods.
+
+2010-03-31 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Module.cs:
+       * MonoModule.cs: Implement GetField, GetFields,
+       GetMethodImpl, GetPEKind, GetType, IsDefined and
+       ResolveField.
+
+2010-03-31 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Module.cs:
+       * MonoModule.cs: Implement GetCustomAttributesData.
+
+2010-03-31 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Module.cs:
+       * MonoModule.cs: Implement GetCustomAttributes.
+
+2010-03-31 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Module.cs:
+       * MonoModule.cs: Implement FindTypes.
+
+2010-03-31 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Assembly.cs: Raise the right exception.
+
+2010-03-31 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Module.cs: Make .ctor protected under v4.
+       * MonoModule.cs: Implement IsResource.
+
+2010-03-31 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Module.cs: Make it a partial class under !v4.
+
+       * MonoModule.cs: New type that exists only under
+       v4. Under v2 it is a part of Module.
+
+       This is the initial setup to make v4 Module an
+       abstract type where all methods raise exceptions.
+
+2010-03-30  Jb Evain  <jbevain@novell.com>
+
+       * MonoAssembly.cs: make MonoAssembly non public.
+
+2010-03-30  Jb Evain  <jbevain@novell.com>
+
+       * Binder.cs (BindToMethod): fix the case where we bind to a method
+       with only one params parameter and that no args are given.
+
+2010-03-30  Jb Evain  <jbevain@novell.com>
+
+       * Binder.cs: when invoking a params method, pack the params
+       arguments before doing the actual invocation.
+
+       Fixes #591877
+
+2010-03-26 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Assembly.cs: Add IsDynamic.
+
+2010-03-26 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * MonoAssembly.cs:
+       * Assembly.cs: Add missing MonoTODO.
+
+2010-03-26 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Assembly.cs: Add v4 ==, != and GetHashCode ()
+
+2010-03-25 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Assembly.cs: Add v4 obsolete attribute.
+
+2010-03-25 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Assembly.cs:
+       * MonoAssembly.cs: Move a dozen methods from Assembly.cs
+       to MonoAssembly.cs, so they can either be the concrete impl
+       on v4 of the only impl on v2.
+       Add to Assembly.cs versions that throws NotImplementedException.
+       Mask Assembly.cs as abstract.
+
+2010-03-24 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Assembly.cs: Make it a partial class under !v4.
+
+       * MonoAssembly.cs: New type that exists only under
+       v4. Under v2 it is a part of Assembly.
+
+       This is the initial setup to make v4 Assembly an
+       abstract type where all methods raise exceptions.
+
+2010-03-24  Rolf Bjarne Kvinge  <RKvinge@novell.com>
+
+       * MethodInfo.cs: Exclude IsGenericMethod* and ContainsGenericParameters
+       from moonlight too.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * Assembly.cs: use MOONLIGHT symbol to
+       disambiguate MonoTouch and Moonlight code.
+
 2010-03-07 Rodrigo Kumpera  <rkumpera@novell.com>
 
        * EventInfo.cs: Some v4 adjustments.
index cc669ab983a5b6733833a237b028a08b00c7d36e..65837022081e55dd8166c74a48e1bbc8fc91f02a 100644 (file)
@@ -87,20 +87,9 @@ namespace System.Reflection {
                //
                internal virtual int GetParameterCount ()
                {
-                       ParameterInfo [] pi = GetParameters ();
-                       if (pi == null)
-                               return 0;
-                       
-                       return pi.Length;
+                       throw new NotImplementedException ("must be implemented");
                }
 
-#if ONLY_1_1
-               public new Type GetType ()
-               {
-                       return base.GetType ();
-               }
-#endif
-
                [DebuggerHidden]
                [DebuggerStepThrough]           
                public Object Invoke(Object obj, Object[] parameters) {
index 3a51d0046d9066ece67ab6672ccd56860fa172ee..13578f3aec8556a077b7953e919bfcb443cd91e8 100644 (file)
@@ -107,7 +107,7 @@ namespace System.Reflection {
                        return Type.EmptyTypes;
                }
 
-#if !NET_4_0
+#if !NET_4_0 && !MOONLIGHT
                public override bool IsGenericMethod {
                        get {
                                return false;
index 33e67b7a1c83b26f1ed8f5336fd5dd8cf449efd9..428c3c319c9477f5320e85d94f8aca1c55a31e57 100644 (file)
@@ -47,13 +47,17 @@ namespace System.Reflection {
        [ComDefaultInterfaceAttribute (typeof (_Module))]
        [Serializable]
        [ClassInterfaceAttribute (ClassInterfaceType.None)]
-       public class Module : ISerializable, ICustomAttributeProvider, _Module {
-       
+
+#if NET_4_0
+       public abstract class Module : ISerializable, ICustomAttributeProvider, _Module {
+#else
+       public partial class Module : ISerializable, ICustomAttributeProvider, _Module {
+#endif
                public static readonly TypeFilter FilterTypeName;
                public static readonly TypeFilter FilterTypeNameIgnoreCase;
        
 #pragma warning disable 649    
-               private IntPtr _impl; /* a pointer to a MonoImage */
+               internal IntPtr _impl; /* a pointer to a MonoImage */
                internal Assembly assembly;
                internal string fqname;
                internal string name;
@@ -70,32 +74,13 @@ namespace System.Reflection {
                        FilterTypeNameIgnoreCase = new TypeFilter (filter_by_type_name_ignore_case);
                }
 
-               internal Module () {
-               }
 
-               public Assembly Assembly {
-                       get { return assembly; }
-               }
-       
-               public virtual string FullyQualifiedName {
-                       get {
-#if !NET_2_1
-                               if (SecurityManager.SecurityEnabled) {
-                                       new FileIOPermission (FileIOPermissionAccess.PathDiscovery, fqname).Demand ();
-                               }
+#if NET_4_0
+               protected
+#else
+               internal
 #endif
-                               return fqname;
-                       }
-               }
-
-               // Note: we do not ask for PathDiscovery because no path is returned here.
-               // However MS Fx requires it (see FDBK23572 for details).
-               public string Name {
-                       get { return name; }
-               }
-       
-               public string ScopeName {
-                       get { return scopename; }
+               Module () {
                }
 
                public ModuleHandle ModuleHandle {
@@ -104,122 +89,44 @@ namespace System.Reflection {
                        }
                }
 
-               public extern int MetadataToken {
-                       [MethodImplAttribute (MethodImplOptions.InternalCall)]
-                       get;
-               }
-
-               public int MDStreamVersion {
-                       get {
-                               if (_impl == IntPtr.Zero)
-                                       throw new NotSupportedException ();
-                               return GetMDStreamVersion (_impl);
-                       }
-               }
-
+               [MethodImplAttribute (MethodImplOptions.InternalCall)]
+               internal static extern int get_MetadataToken (Module module);
+               
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
                internal static extern int GetMDStreamVersion (IntPtr module_handle);
-       
-               public virtual Type[] FindTypes(TypeFilter filter, object filterCriteria) 
-               {
-                       System.Collections.ArrayList filtered = new System.Collections.ArrayList ();
-                       Type[] types = GetTypes ();
-                       foreach (Type t in types)
-                               if (filter (t, filterCriteria))
-                                       filtered.Add (t);
-                       return (Type[])filtered.ToArray (typeof(Type));
-               }
-       
-               public virtual object[] GetCustomAttributes(bool inherit) 
-               {
-                       return MonoCustomAttrs.GetCustomAttributes (this, inherit);
-               }
-       
-               public virtual object[] GetCustomAttributes(Type attributeType, bool inherit) 
-               {
-                       return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
-               }
-       
+
                public FieldInfo GetField (string name) 
                {
-                       if (IsResource ())
-                               return null;
-
-                       Type globalType = GetGlobalType ();
-                       return (globalType != null) ? globalType.GetField (name, BindingFlags.Public | BindingFlags.Static) : null;
+                       return GetField (name, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
                }
-       
-               public FieldInfo GetField (string name, BindingFlags bindingAttr) 
-               {
-                       if (IsResource ())
-                               return null;
 
-                       Type globalType = GetGlobalType ();
-                       return (globalType != null) ? globalType.GetField (name, bindingAttr) : null;
-               }
-       
                public FieldInfo[] GetFields () 
                {
-                       if (IsResource ())
-                               return new FieldInfo [0];
-
-                       Type globalType = GetGlobalType ();
-                       return (globalType != null) ? globalType.GetFields (BindingFlags.Public | BindingFlags.Static) : new FieldInfo [0];
+                       return GetFields (BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
                }
        
                public MethodInfo GetMethod (string name) 
                {
-                       // Can't call the other overloads since they call Type.GetMethod () which does a null check on the 'types' array
-                       if (IsResource ())
-                               return null;
-
-                       Type globalType = GetGlobalType ();
-                       return (globalType != null) ? globalType.GetMethod (name) : null;
+                       return GetMethodImpl (name, defaultBindingFlags, null, CallingConventions.Any, null, null);
                }
        
                public MethodInfo GetMethod (string name, Type[] types) 
                {
+                       if (types == null)
+                               throw new ArgumentNullException ("types");
                        return GetMethodImpl (name, defaultBindingFlags, null, CallingConventions.Any, types, null);
                }
        
                public MethodInfo GetMethod (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) 
                {
+                       if (types == null)
+                               throw new ArgumentNullException ("types");
                        return GetMethodImpl (name, bindingAttr, binder, callConvention, types, modifiers);
                }
        
-               protected virtual MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) 
-               {
-                       if (IsResource ())
-                               return null;
-
-                       Type globalType = GetGlobalType ();
-                       return (globalType != null) ? globalType.GetMethod (name, bindingAttr, binder, callConvention, types, modifiers) : null;
-               }
-       
                public MethodInfo[] GetMethods () 
                {
-                       if (IsResource ())
-                               return new MethodInfo [0];
-
-                       Type globalType = GetGlobalType ();
-                       return (globalType != null) ? globalType.GetMethods () : new MethodInfo [0];
-               }
-
-               public MethodInfo[] GetMethods (BindingFlags bindingFlags) {
-                       if (IsResource ())
-                               return new MethodInfo [0];
-
-                       Type globalType = GetGlobalType ();
-                       return (globalType != null) ? globalType.GetMethods (bindingFlags) : new MethodInfo [0];
-               }
-
-               public FieldInfo[] GetFields (BindingFlags bindingFlags)
-               {
-                       if (IsResource ())
-                               return new FieldInfo [0];
-
-                       Type globalType = GetGlobalType ();
-                       return (globalType != null) ? globalType.GetFields (bindingFlags) : new FieldInfo [0];
+                       return GetMethods (BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
                }
        
                [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
@@ -231,18 +138,6 @@ namespace System.Reflection {
                        UnitySerializationHolder.GetModuleData (this, info, context);
                }
 
-#if !NET_2_1
-               public X509Certificate GetSignerCertificate ()
-               {
-                       try {
-                               return X509Certificate.CreateFromSignedFile (assembly.Location);
-                       }
-                       catch {
-                               return null;
-                       }
-               }
-#endif
-
                [ComVisible (true)]
                public virtual Type GetType(string className) 
                {
@@ -255,33 +150,8 @@ namespace System.Reflection {
                        return GetType (className, false, ignoreCase);
                }
        
-               [ComVisible (true)]
-               public virtual Type GetType(string className, bool throwOnError, bool ignoreCase) 
-               {
-                       if (className == null)
-                               throw new ArgumentNullException ("className");
-                       if (className == String.Empty)
-                               throw new ArgumentException ("Type name can't be empty");
-                       return assembly.InternalGetType (this, className, throwOnError, ignoreCase);
-               }
-
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
-               private extern Type[] InternalGetTypes ();
-       
-               public virtual Type[] GetTypes() 
-               {
-                       return InternalGetTypes ();
-               }
-       
-               public virtual bool IsDefined (Type attributeType, bool inherit) 
-               {
-                       return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
-               }
-       
-               public bool IsResource()
-               {
-                       return is_resource;
-               }
+               internal extern Type[] InternalGetTypes ();
        
                public override string ToString () 
                {
@@ -294,25 +164,14 @@ namespace System.Reflection {
                        }
                }
 
-               public Guid ModuleVersionId {
-                       get {
-                               return GetModuleVersionId ();
-                       }
-               }
-
-               public void GetPEKind (out PortableExecutableKinds peKind, out ImageFileMachine machine) {
-                       ModuleHandle.GetPEKind (out peKind, out machine);
-               }
-               
-
-               private Exception resolve_token_exception (int metadataToken, ResolveTokenError error, string tokenType) {
+               internal Exception resolve_token_exception (int metadataToken, ResolveTokenError error, string tokenType) {
                        if (error == ResolveTokenError.OutOfRange)
                                return new ArgumentOutOfRangeException ("metadataToken", String.Format ("Token 0x{0:x} is not valid in the scope of module {1}", metadataToken, name));
                        else
                                return new ArgumentException (String.Format ("Token 0x{0:x} is not a valid {1} token in the scope of module {2}", metadataToken, tokenType, name), "metadataToken");
                }
 
-               private IntPtr[] ptrs_from_types (Type[] types) {
+               internal IntPtr[] ptrs_from_types (Type[] types) {
                        if (types == null)
                                return null;
                        else {
@@ -330,85 +189,18 @@ namespace System.Reflection {
                        return ResolveField (metadataToken, null, null);
                }
 
-               public FieldInfo ResolveField (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
-                       ResolveTokenError error;
-
-                       IntPtr handle = ResolveFieldToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
-                       if (handle == IntPtr.Zero)
-                               throw resolve_token_exception (metadataToken, error, "Field");
-                       else
-                               return FieldInfo.GetFieldFromHandle (new RuntimeFieldHandle (handle));
-               }
-
                public MemberInfo ResolveMember (int metadataToken) {
                        return ResolveMember (metadataToken, null, null);
                }
 
-               public MemberInfo ResolveMember (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
-
-                       ResolveTokenError error;
-
-                       MemberInfo m = ResolveMemberToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
-                       if (m == null)
-                               throw resolve_token_exception (metadataToken, error, "MemberInfo");
-                       else
-                               return m;
-               }
-
                public MethodBase ResolveMethod (int metadataToken) {
                        return ResolveMethod (metadataToken, null, null);
                }
 
-               public MethodBase ResolveMethod (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
-                       ResolveTokenError error;
-
-                       IntPtr handle = ResolveMethodToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
-                       if (handle == IntPtr.Zero)
-                               throw resolve_token_exception (metadataToken, error, "MethodBase");
-                       else
-                               return MethodBase.GetMethodFromHandleNoGenericCheck (new RuntimeMethodHandle (handle));
-               }
-
-               public string ResolveString (int metadataToken) {
-                       ResolveTokenError error;
-
-                       string s = ResolveStringToken (_impl, metadataToken, out error);
-                       if (s == null)
-                               throw resolve_token_exception (metadataToken, error, "string");
-                       else
-                               return s;
-               }
-
                public Type ResolveType (int metadataToken) {
                        return ResolveType (metadataToken, null, null);
                }
 
-               public Type ResolveType (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
-                       ResolveTokenError error;
-
-                       IntPtr handle = ResolveTypeToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
-                       if (handle == IntPtr.Zero)
-                               throw resolve_token_exception (metadataToken, error, "Type");
-                       else
-                               return Type.GetTypeFromHandle (new RuntimeTypeHandle (handle));
-               }
-
-               public byte[] ResolveSignature (int metadataToken) {
-                       ResolveTokenError error;
-
-                   byte[] res = ResolveSignature (_impl, metadataToken, out error);
-                       if (res == null)
-                               throw resolve_token_exception (metadataToken, error, "signature");
-                       else
-                               return res;
-               }
-
-#if NET_4_0
-               public virtual IList<CustomAttributeData> GetCustomAttributesData () {
-                       return CustomAttributeData.GetCustomAttributes (this);
-               }
-#endif
-
                internal static Type MonoDebugger_ResolveType (Module module, int token)
                {
                        ResolveTokenError error;
@@ -454,7 +246,7 @@ namespace System.Reflection {
                private extern string GetGuidInternal ();
 
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
-               private extern Type GetGlobalType ();
+               internal extern Type GetGlobalType ();
 
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
                internal static extern IntPtr ResolveTypeToken (IntPtr module, int token, IntPtr[] type_args, IntPtr[] method_args, out ResolveTokenError error);
@@ -497,5 +289,143 @@ namespace System.Reflection {
                {
                        throw new NotImplementedException ();
                }
+
+#if NET_4_0
+
+               public virtual Assembly Assembly {
+                       get { throw CreateNIE (); }
+               }
+
+               public virtual string Name {
+                       get { throw CreateNIE (); }
+               }
+       
+               public virtual string ScopeName {
+                       get { throw CreateNIE (); }
+               }
+
+               public virtual int MDStreamVersion {
+                       get { throw CreateNIE (); }
+               }
+
+               public virtual Guid ModuleVersionId {
+                       get { throw CreateNIE (); }
+               }
+
+               public virtual string FullyQualifiedName {
+                       get { throw CreateNIE (); }
+               }
+
+               public virtual int MetadataToken {
+                       get { throw CreateNIE (); }
+               }
+
+               static Exception CreateNIE ()
+               {
+                       return new NotImplementedException ("Derived classes must implement it");
+               }
+
+               public virtual bool IsResource()
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual Type[] FindTypes(TypeFilter filter, object filterCriteria) 
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual object[] GetCustomAttributes(bool inherit)
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual object[] GetCustomAttributes(Type attributeType, bool inherit) 
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual IList<CustomAttributeData> GetCustomAttributesData ()
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual FieldInfo GetField (string name, BindingFlags bindingAttr) 
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual FieldInfo[] GetFields (BindingFlags bindingFlags)
+               {
+                       throw CreateNIE ();
+               }
+
+               protected virtual MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) 
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual MethodInfo[] GetMethods (BindingFlags bindingFlags)
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual void GetPEKind (out PortableExecutableKinds peKind, out ImageFileMachine machine)
+               {
+                       throw CreateNIE ();
+               }
+
+               [ComVisible (true)]
+               public virtual Type GetType(string className, bool throwOnError, bool ignoreCase) 
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual bool IsDefined (Type attributeType, bool inherit) 
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual FieldInfo ResolveField (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments)
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual MemberInfo ResolveMember (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments)
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual MethodBase ResolveMethod (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments)
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual byte[] ResolveSignature (int metadataToken)
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual string ResolveString (int metadataToken)
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual Type ResolveType (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments)
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual X509Certificate GetSignerCertificate ()
+               {
+                       throw CreateNIE ();
+               }
+
+               public virtual Type[] GetTypes() 
+               {
+                       throw CreateNIE ();
+               }
+#endif
+
        }
 }
diff --git a/mcs/class/corlib/System.Reflection/MonoAssembly.cs b/mcs/class/corlib/System.Reflection/MonoAssembly.cs
new file mode 100644 (file)
index 0000000..f15794e
--- /dev/null
@@ -0,0 +1,161 @@
+//
+// System.Reflection/MonoAssembly.cs
+//
+// Author:
+//   Rodrigo Kumpera (rkumpera@novell.com)
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections;
+using System.Globalization;
+using System.Runtime.InteropServices;
+
+
+namespace System.Reflection {
+
+#if NET_4_0
+       [ComVisible (true)]
+       [ComDefaultInterfaceAttribute (typeof (_Assembly))]
+       [Serializable]
+       [ClassInterface(ClassInterfaceType.None)]
+       class MonoAssembly : Assembly {
+#else
+       public partial class Assembly {
+#endif
+               public
+#if NET_4_0
+               override
+#endif
+               Type GetType (string name, bool throwOnError, bool ignoreCase)
+               {
+                       if (name == null)
+                               throw new ArgumentNullException (name);
+                       if (name.Length == 0)
+                       throw new ArgumentException ("name", "Name cannot be empty");
+
+                       return InternalGetType (null, name, throwOnError, ignoreCase);
+               }
+
+               public
+#if NET_4_0
+               override
+#endif
+               Module GetModule (String name)
+               {
+                       if (name == null)
+                               throw new ArgumentNullException ("name");
+                       if (name.Length == 0)
+                               throw new ArgumentException ("Name can't be empty");
+
+                       Module[] modules = GetModules (true);
+                       foreach (Module module in modules) {
+                               if (module.ScopeName == name)
+                                       return module;
+                       }
+
+                       return null;
+               }
+
+               public
+#if NET_4_0
+               override
+#endif
+               AssemblyName[] GetReferencedAssemblies () {
+                       return GetReferencedAssemblies (this);
+               }
+
+               public
+#if NET_4_0
+               override
+#endif
+               Module[] GetModules (bool getResourceModules) {
+                       Module[] modules = GetModulesInternal ();
+
+                       if (!getResourceModules) {
+                               ArrayList result = new ArrayList (modules.Length);
+                               foreach (Module m in modules)
+                                       if (!m.IsResource ())
+                                               result.Add (m);
+                               return (Module[])result.ToArray (typeof (Module));
+                       }
+                       else
+                               return modules;
+               }
+
+               [MonoTODO ("Always returns the same as GetModules")]
+               public
+#if NET_4_0
+               override
+#endif
+               Module[] GetLoadedModules (bool getResourceModules)
+               {
+                       return GetModules (getResourceModules);
+               }
+
+               public
+#if NET_4_0
+               override
+#endif
+               Assembly GetSatelliteAssembly (CultureInfo culture)
+               {
+                       return GetSatelliteAssembly (culture, null, true);
+               }
+
+               public
+#if NET_4_0
+               override
+#endif
+               Assembly GetSatelliteAssembly (CultureInfo culture, Version version)
+               {
+                       return GetSatelliteAssembly (culture, version, true);
+               }
+
+               //FIXME remove GetManifestModule under v4, it's a v2 artifact
+               [ComVisible (false)]
+               public
+#if NET_4_0
+               override
+#endif
+               Module ManifestModule {
+                       get {
+                               return GetManifestModule ();
+                       }
+               }
+
+#if !MOONLIGHT
+               public
+#if NET_4_0
+               override
+#endif
+               bool GlobalAssemblyCache {
+                       get {
+                               return get_global_assembly_cache ();
+                       }
+               }
+#endif
+
+       }
+}
+
+
index 6ef6c8a455471a2ce0d9df2c4add350a5452133e..df0becc0f61dac3dcc642cd7b66ff309d01d63a3 100644 (file)
@@ -104,8 +104,16 @@ namespace System.Reflection {
 
                public override object GetValue (object obj)
                {
-                       if (!IsStatic && obj == null)
-                               throw new TargetException ("Non-static field requires a target");
+                       if (!IsStatic) {
+                               if (obj == null)
+                                       throw new TargetException ("Non-static field requires a target");
+                               if (!DeclaringType.IsAssignableFrom (obj.GetType ()))
+                                       throw new ArgumentException (string.Format (
+                                               "Field {0} defined on type {1} is not a field on the target object which is of type {2}.",
+                                               Name, DeclaringType, obj.GetType ()),
+                                               "obj");
+                       }
+                       
                        if (!IsLiteral)
                                CheckGeneric ();
                        return GetValueInternal (obj);
@@ -120,8 +128,15 @@ namespace System.Reflection {
 
                public override void SetValue (object obj, object val, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
                {
-                       if (!IsStatic && obj == null)
-                               throw new TargetException ("Non-static field requires a target");
+                       if (!IsStatic) {
+                               if (obj == null)
+                                       throw new TargetException ("Non-static field requires a target");
+                               if (!DeclaringType.IsAssignableFrom (obj.GetType ()))
+                                       throw new ArgumentException (string.Format (
+                                               "Field {0} defined on type {1} is not a field on the target object which is of type {2}.",
+                                               Name, DeclaringType, obj.GetType ()),
+                                               "obj");
+                       }
                        if (IsLiteral)
                                throw new FieldAccessException ("Cannot set a constant field");
                        if (binder == null)
index afdd191cb29544514f57ef6b0b73d5b8f810f7ea..5bace9415d48a1ba9bee245e3f7014f9d7eb5d9a 100644 (file)
@@ -87,6 +87,15 @@ namespace System.Reflection
                        }
                }
 
+               internal override Type InternalResolve ()
+               {
+                       Type gtd = generic_type.InternalResolve ();
+                       Type[] args = new Type [type_arguments.Length];
+                       for (int i = 0; i < type_arguments.Length; ++i)
+                               args [i] = type_arguments [i].InternalResolve ();
+                       return gtd.MakeGenericType (args);
+               }
+
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                extern void initialize (MethodInfo[] methods, ConstructorInfo[] ctors, FieldInfo[] fields, PropertyInfo[] properties, EventInfo[] events);
 
index 31d360ed8bfba16e8950d7f2e1ad5e4408bd12b5..c5fab6487317769146e367d2d6be9f9dd4ddaef5 100644 (file)
@@ -168,6 +168,12 @@ namespace System.Reflection {
                        src.CopyTo (res, 0);
                        return res;
                }
+               
+               internal override int GetParameterCount ()
+               {
+                       var pi = MonoMethodInfo.GetParametersInfo (mhandle, this);
+                       return pi == null ? 0 : pi.Length;
+               }
 
                /*
                 * InternalInvoke() receives the parameters correctly converted by the 
@@ -462,6 +468,12 @@ namespace System.Reflection {
                        return MonoMethodInfo.GetParametersInfo (mhandle, this);
                }
 
+               internal override int GetParameterCount ()
+               {
+                       var pi = MonoMethodInfo.GetParametersInfo (mhandle, this);
+                       return pi == null ? 0 : pi.Length;
+               }
+
                /*
                 * InternalInvoke() receives the parameters corretcly converted by the binder
                 * to match the types of the method signature.
diff --git a/mcs/class/corlib/System.Reflection/MonoModule.cs b/mcs/class/corlib/System.Reflection/MonoModule.cs
new file mode 100644 (file)
index 0000000..90b13cf
--- /dev/null
@@ -0,0 +1,377 @@
+//
+// System.Reflection/MonoModule.cs
+//
+// Author:
+//   Rodrigo Kumpera (rkumpera@novell.com)
+//
+// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Security.Cryptography.X509Certificates;
+using System.Security;
+using System.Security.Permissions;
+
+
+namespace System.Reflection {
+
+#if NET_4_0
+       [ComVisible (true)]
+       [ComDefaultInterfaceAttribute (typeof (_Module))]
+       [Serializable]
+       [ClassInterface(ClassInterfaceType.None)]
+       class MonoModule : Module {
+#else
+       public partial class Module {
+#endif
+
+               public
+#if NET_4_0
+               override
+#endif
+               Assembly Assembly {
+                       get { return assembly; }
+               }
+
+               public
+#if NET_4_0
+               override
+#endif
+               // Note: we do not ask for PathDiscovery because no path is returned here.
+               // However MS Fx requires it (see FDBK23572 for details).
+               string Name {
+                       get { return name; }
+               }
+       
+               public
+#if NET_4_0
+               override
+#endif
+               string ScopeName {
+                       get { return scopename; }
+               }
+
+               public
+#if NET_4_0
+               override
+#endif
+               int MDStreamVersion {
+                       get {
+                               if (_impl == IntPtr.Zero)
+                                       throw new NotSupportedException ();
+                               return GetMDStreamVersion (_impl);
+                       }
+               }
+
+               public
+#if NET_4_0
+               override
+#endif
+               Guid ModuleVersionId {
+                       get {
+                               return GetModuleVersionId ();
+                       }
+               }
+
+#if NET_4_0
+               public override
+#else
+               public virtual
+#endif
+               string FullyQualifiedName {
+                       get {
+#if !NET_2_1
+                               if (SecurityManager.SecurityEnabled) {
+                                       new FileIOPermission (FileIOPermissionAccess.PathDiscovery, fqname).Demand ();
+                               }
+#endif
+                               return fqname;
+                       }
+               }
+
+               public
+#if NET_4_0
+               override
+#endif
+               bool IsResource()
+               {
+                       return is_resource;
+               }
+
+#if NET_4_0
+               public override
+#else
+               public virtual
+#endif
+               Type[] FindTypes(TypeFilter filter, object filterCriteria) 
+               {
+                       System.Collections.ArrayList filtered = new System.Collections.ArrayList ();
+                       Type[] types = GetTypes ();
+                       foreach (Type t in types)
+                               if (filter (t, filterCriteria))
+                                       filtered.Add (t);
+                       return (Type[])filtered.ToArray (typeof(Type));
+               }
+
+#if NET_4_0
+               public override
+#else
+               public virtual
+#endif
+               object[] GetCustomAttributes(bool inherit) 
+               {
+                       return MonoCustomAttrs.GetCustomAttributes (this, inherit);
+               }
+
+#if NET_4_0
+               public override
+#else
+               public virtual
+#endif
+               object[] GetCustomAttributes(Type attributeType, bool inherit) 
+               {
+                       return MonoCustomAttrs.GetCustomAttributes (this, attributeType, inherit);
+               }
+
+#if NET_4_0
+               public override
+#else
+               public virtual
+#endif
+               FieldInfo GetField (string name, BindingFlags bindingAttr) 
+               {
+                       if (IsResource ())
+                               return null;
+
+                       Type globalType = GetGlobalType ();
+                       return (globalType != null) ? globalType.GetField (name, bindingAttr) : null;
+               }
+
+#if NET_4_0
+               public override
+#else
+               public virtual
+#endif
+               FieldInfo[] GetFields (BindingFlags bindingFlags)
+               {
+                       if (IsResource ())
+                               return new FieldInfo [0];
+
+                       Type globalType = GetGlobalType ();
+                       return (globalType != null) ? globalType.GetFields (bindingFlags) : new FieldInfo [0];
+               }
+
+#if NET_4_0
+               public override
+#else
+               public virtual
+#endif
+               int MetadataToken {
+                       get { return get_MetadataToken (this); }
+               }
+               protected
+#if NET_4_0
+               override
+#else
+               virtual
+#endif 
+               MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) 
+               {
+                       if (IsResource ())
+                               return null;
+
+                       Type globalType = GetGlobalType ();
+                       if (globalType == null)
+                               return null;
+                       if (types == null)
+                               return globalType.GetMethod (name);
+                       return globalType.GetMethod (name, bindingAttr, binder, callConvention, types, modifiers);
+               }
+
+               public
+#if NET_4_0
+               override
+#endif
+               MethodInfo[] GetMethods (BindingFlags bindingFlags) {
+                       if (IsResource ())
+                               return new MethodInfo [0];
+
+                       Type globalType = GetGlobalType ();
+                       return (globalType != null) ? globalType.GetMethods (bindingFlags) : new MethodInfo [0];
+               }
+
+#if NET_4_0
+               public override
+#else
+               public virtual
+#endif
+               void GetPEKind (out PortableExecutableKinds peKind, out ImageFileMachine machine) {
+                       ModuleHandle.GetPEKind (out peKind, out machine);
+               }
+
+#if NET_4_0
+               public override
+#else
+               public virtual
+#endif
+               Type GetType(string className, bool throwOnError, bool ignoreCase) 
+               {
+                       if (className == null)
+                               throw new ArgumentNullException ("className");
+                       if (className == String.Empty)
+                               throw new ArgumentException ("Type name can't be empty");
+                       return assembly.InternalGetType (this, className, throwOnError, ignoreCase);
+               }
+       
+#if NET_4_0
+               public override
+#else
+               public virtual
+#endif
+               bool IsDefined (Type attributeType, bool inherit) 
+               {
+                       return MonoCustomAttrs.IsDefined (this, attributeType, inherit);
+               }
+
+               public
+#if NET_4_0
+               override
+#endif
+               FieldInfo ResolveField (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
+                       ResolveTokenError error;
+
+                       IntPtr handle = ResolveFieldToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
+                       if (handle == IntPtr.Zero)
+                               throw resolve_token_exception (metadataToken, error, "Field");
+                       else
+                               return FieldInfo.GetFieldFromHandle (new RuntimeFieldHandle (handle));
+               }
+
+               public
+#if NET_4_0
+               override
+#endif
+               MemberInfo ResolveMember (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
+
+                       ResolveTokenError error;
+
+                       MemberInfo m = ResolveMemberToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
+                       if (m == null)
+                               throw resolve_token_exception (metadataToken, error, "MemberInfo");
+                       else
+                               return m;
+               }
+
+               public
+#if NET_4_0
+               override
+#endif
+               MethodBase ResolveMethod (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
+                       ResolveTokenError error;
+
+                       IntPtr handle = ResolveMethodToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
+                       if (handle == IntPtr.Zero)
+                               throw resolve_token_exception (metadataToken, error, "MethodBase");
+                       else
+                               return MethodBase.GetMethodFromHandleNoGenericCheck (new RuntimeMethodHandle (handle));
+               }
+
+               public
+#if NET_4_0
+               override
+#endif
+               string ResolveString (int metadataToken) {
+                       ResolveTokenError error;
+
+                       string s = ResolveStringToken (_impl, metadataToken, out error);
+                       if (s == null)
+                               throw resolve_token_exception (metadataToken, error, "string");
+                       else
+                               return s;
+               }
+
+               public
+#if NET_4_0
+               override
+#endif
+               Type ResolveType (int metadataToken, Type [] genericTypeArguments, Type [] genericMethodArguments) {
+                       ResolveTokenError error;
+
+                       IntPtr handle = ResolveTypeToken (_impl, metadataToken, ptrs_from_types (genericTypeArguments), ptrs_from_types (genericMethodArguments), out error);
+                       if (handle == IntPtr.Zero)
+                               throw resolve_token_exception (metadataToken, error, "Type");
+                       else
+                               return Type.GetTypeFromHandle (new RuntimeTypeHandle (handle));
+               }
+
+               public
+#if NET_4_0
+               override
+#endif
+               byte[] ResolveSignature (int metadataToken) {
+                       ResolveTokenError error;
+
+                   byte[] res = ResolveSignature (_impl, metadataToken, out error);
+                       if (res == null)
+                               throw resolve_token_exception (metadataToken, error, "signature");
+                       else
+                               return res;
+               }
+
+#if !NET_2_1
+
+               public
+#if NET_4_0
+               override
+#endif
+               X509Certificate GetSignerCertificate ()
+               {
+                       try {
+                               return X509Certificate.CreateFromSignedFile (assembly.Location);
+                       }
+                       catch {
+                               return null;
+                       }
+               }
+#endif
+
+#if NET_4_0
+               public override
+#else
+               public virtual
+#endif
+               Type[] GetTypes() 
+               {
+                       return InternalGetTypes ();
+               }
+
+#if NET_4_0
+               public override IList<CustomAttributeData> GetCustomAttributesData () {
+                       return CustomAttributeData.GetCustomAttributes (this);
+               }
+#endif
+       }
+}
index 4b0fe5e655905f39911a7c54ba0d7e73bfd301d8..6027a5bd4fb4a3a95b01be66da85110f666e824c 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * ResourceManager.cs: use MOONLIGHT symbol to disambiguate
+       MonoTouch and Moonlight code.
+
 2010-03-01  Miguel de Icaza  <miguel@novell.com>
 
        * Win32Resources.cs: Prevent infinite loops if the resource that
index 58c87fee00e2967e7800f41328f66e795ff0b378..c0979a045a3e1f1aef4b98b136243d33234c1ac1 100644 (file)
@@ -281,7 +281,7 @@ namespace System.Resources
 
                private string GetResourceFilePath (CultureInfo culture)
                {
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        if (resourceDir != null)
                                return Path.Combine (resourceDir, GetResourceFileName (culture));
                        else
index b7bf33b135195698c2535fe860e4d618188c8ad6..f32d1c8818c438cb19e112eb1a58640306e61694 100644 (file)
@@ -1,3 +1,9 @@
+2010-03-18  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * ConditionalWeakTable.cs:
+       * ReferenceAssemblyAttribute.cs:
+       * TypeForwardedFromAttribute.cs:
+               Build them into Moonlight too (SL4)
 
 Fri Feb 12 19:03:11 CET 2010 Paolo Molaro <lupus@ximian.com>
 
index b9909bb16ca272b20602c2a729e5f37938aca09e..203ab4dc49d401d1214bf57962a7faeefa78ff01 100644 (file)
@@ -11,7 +11,7 @@
        //   "I think our table is weak, but does not do proper compacting"
        //
 
-#if NET_4_0 || BOOTSTRAP_NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0 || MOONLIGHT
 using System;
 using System.Collections;
 using System.Collections.Generic;
index 579e0a7b9d2336cb4e6f8b553814c4933388e5b5..0d1358f66d73df457851f48f1381762559a87a95 100644 (file)
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
+#if NET_4_0 || MOONLIGHT
 
 using System;
 using System.Runtime.InteropServices;
 
-#if NET_4_0
-
 namespace System.Runtime.CompilerServices {
 
        [AttributeUsage (AttributeTargets.Assembly, AllowMultiple=false)] 
index d5b48c6b454c494d974798bad6bed8be71adbb31..8f09155abdfed653d183a9980f7dd8b4a015517b 100644 (file)
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_4_0 || BOOTSTRAP_NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0 || MOONLIGHT
 
 namespace System.Runtime.CompilerServices
 {
index 2bef9444084cb33865c0c1e14ed34d013449e7b2..defb099c802f0837b177fffac4b8be3e25e645d4 100644 (file)
@@ -1,3 +1,21 @@
+2010-04-02  Miguel de Icaza  <miguel@novell.com>
+
+       * SafeHandle.cs: Use refcount == -1 to indicate that the handle
+       had been closed.
+
+       The problem here is that we have no records of why the code that
+       threw a ObjectDisposedException inside the do { } while block on
+       DangerousAddRef was added.   It seems it was added in response to
+       Close() methods being called and the need to throw that exception
+       on further calls to ObjectDisposedException.
+
+       Sadly, we have no test suites for that.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * MarshalAsAttribute.cs, Marshal.cs: use MOONLIGHT symbol to
+       disambiguate MonoTouch and Moonlight code.
+
 2009-12-13  Miguel de Icaza  <miguel@novell.com>
 
        * SafeBuffer.cs: When comparing the end, we only need to compare
index 0fa52fe70889c9b6922bd0206e20722f39823fcd..fa0344c771e185b9b0bf8ce078f780851b8e666d 100644 (file)
@@ -38,11 +38,11 @@ using System.Reflection;
 using System.Threading;
 
 using System.Runtime.ConstrainedExecution;
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 using System.Runtime.InteropServices.ComTypes;
 #endif
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 using Mono.Interop;
 #endif
 
@@ -189,7 +189,7 @@ namespace System.Runtime.InteropServices
                        throw new NotImplementedException ();
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public static object CreateWrapperOfType (object o, Type t)
                {
                        __ComObject co = o as __ComObject;
@@ -272,7 +272,7 @@ namespace System.Runtime.InteropServices
                        FreeHGlobal (s);
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public static Guid GenerateGuidForType (Type type)
                {
                        return type.GUID;
@@ -374,7 +374,7 @@ namespace System.Runtime.InteropServices
                {
                        throw new NotImplementedException ();
                }
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
                private extern static IntPtr GetIDispatchForObjectInternal (object o);
 
@@ -744,7 +744,7 @@ namespace System.Runtime.InteropServices
                        return ReleaseInternal (pUnk);
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
                private extern static int ReleaseComObjectInternal (object co);
 
@@ -833,7 +833,7 @@ namespace System.Runtime.InteropServices
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                public extern static IntPtr StringToHGlobalUni (string s);
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public static IntPtr SecureStringToBSTR (SecureString s)
                {
                        if (s == null)
@@ -1049,7 +1049,7 @@ namespace System.Runtime.InteropServices
                        return null;
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public static int FinalReleaseComObject (object o)
                {
                        while (ReleaseComObject (o) != 0);
index 4b5bd0a02a7ef64ede92af663a3f91034e3d7368..9bb9e9a92576c4320e4cc0437d5218784e0b4215 100644 (file)
@@ -46,7 +46,7 @@ namespace System.Runtime.InteropServices {
                [ComVisible(true)]
                public Type MarshalTypeRef;
                
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public VarEnum SafeArraySubType;
 #endif
 
index 028e8f0b426e4f84cc9b6f18ba1558ad79323467..e1b0a70ffb24ddc408c4b20af7f1c0b81ae2814f 100644 (file)
@@ -90,6 +90,7 @@ namespace System.Runtime.InteropServices
                        if (newcount == 0 && owns_handle && !IsInvalid){
                                ReleaseHandle ();
                                handle = invalid_handle_value;
+                               refcount = -1;
                        }
                }
 
@@ -105,7 +106,7 @@ namespace System.Runtime.InteropServices
                [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
                public void DangerousAddRef (ref bool success)
                {
-                       if (refcount == 0)
+                       if (refcount <= 0)
                                throw new ObjectDisposedException (GetType ().FullName);
 
                        int newcount, current;
@@ -113,7 +114,7 @@ namespace System.Runtime.InteropServices
                                current = refcount;
                                newcount = current + 1;
                                
-                               if (handle == invalid_handle_value || current == 0){
+                               if (current <= 0){
                                        //
                                        // In MS, calling sf.Close () followed by a call
                                        // to P/Invoke with SafeHandles throws this, but
@@ -129,7 +130,7 @@ namespace System.Runtime.InteropServices
                [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
                public IntPtr DangerousGetHandle ()
                {
-                       if (refcount == 0){
+                       if (refcount <= 0){
                                throw new ObjectDisposedException (GetType ().FullName);
                        }
 
@@ -139,7 +140,7 @@ namespace System.Runtime.InteropServices
                [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
                public void DangerousRelease ()
                {
-                       if (refcount == 0)
+                       if (refcount <= 0)
                                throw new ObjectDisposedException (GetType ().FullName);
 
                        int newcount, current;
@@ -198,7 +199,7 @@ namespace System.Runtime.InteropServices
                public bool IsClosed {
                        [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
                        get {
-                               return refcount == 0;
+                               return refcount <= 0;
                        }
                }
 
index 2f00e5ff4069686a93a0444f4b7661d4f347c8c6..033977fb79c17b464cc33647a063830f5c65caca 100644 (file)
@@ -50,7 +50,9 @@ namespace System.Runtime.Remoting.Channels
        {
                // TODO: Add context support
                // Required for .NET compatibility
+#pragma warning disable 0414
                private object _ContextID;
+#pragma warning restore
                private int _DomainID;
                private string _processGuid;
 
index 9f0309eb136b174e3c867f8b229adf0ba58caed2..4b23af65c8e7331619d10118e5267d9c756df94d 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * Context.cs: use MOONLIGHT symbol to disambiguate
+       MonoTouch and Moonlight code.
+
 2009-10-07  Sebastien Pouliot  <sebastien@ximian.com>
 
        * Context.cs: Remove LocalDataStoreSlot-related methods from
index e3766b8cbca4640beba287debb8f6ec1ae96b5ae..ca52953270878766b5b489ab51073759f0430b68 100644 (file)
@@ -346,7 +346,7 @@ namespace System.Runtime.Remoting.Contexts {
                        callback_object.DoCallBack (deleg);
                }
                
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public static LocalDataStoreSlot AllocateDataSlot ()
                {
                        return new LocalDataStoreSlot (false);
index 5f44c6b6fb851d8c2b024ac5837bf24aa430ddf8..21eed42f99a2436a0bb3838f2ce2a185d58b9828 100644 (file)
@@ -51,17 +51,28 @@ public class AsyncResult : IAsyncResult, IMessageSink {
        object async_callback;
        ExecutionContext current;
        ExecutionContext original;
+       long add_time;
 #pragma warning restore 169, 414, 649
 
        // not part of MonoAsyncResult...
        MonoMethodMessage call_message;
+#pragma warning disable 0414
        IMessageCtrl message_ctrl;
+#pragma warning restore
        IMessage reply_message;
        
        internal AsyncResult ()
        {
        }
-       
+
+       internal AsyncResult (WaitCallback cb, object state, bool capture_context)
+       {
+               async_state = state;
+               async_delegate = cb;
+               if (capture_context)
+                       current = ExecutionContext.Capture ();
+       }
+
        public virtual object AsyncState
        {
                get {
index 1c24c712326303ff9e259d66757c5a2b7dabd48d..3ff486ed9c8736fbc333570de9573e02069ee735 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-25 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * AsyncResult.cs: add new constructor used by the threadpool and new
+       field that stores the time that the work item was added to the pool.
+
 2010-03-03  Robert Jordan  <robertj@gmx.net>
 
        * CADMessages.cs (GetMethod): don't continue if the type
index e8338d99d22017e97da8712856473e3a73019e65..ffe5b4320df8081c106ae61ecf9458606173de92 100644 (file)
@@ -81,7 +81,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
 
                        // TimeStamp does not have a TypeCode, so it is managed as a special
                        // case in GetTypeCode()
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        // This environment variable is only for test and benchmarking purposes.
                        // By default, mono will always use IL generated class serializers.
                        string s = Environment.GetEnvironmentVariable("MONO_REFLECTION_SERIALIZER");
index 3975be4a7ecdb09136a9928055521b22384aaf27..510fe781b7ef312ac4e0f104f8c218760aa8fdcd 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * BinaryCommon.cs: use MOONLIGHT symbol to disambiguate
+       MonoTouch and Moonlight code.
+
 2010-02-26  Robert Jordan  <robertj@gmx.net>
 
        * ObjectReader.cs (ReadType, GetDeserializationType):
index 11401a64fed4fcbc7ca946bae00c6bada193afc0..2e92f1c7ca75504b839cd92f82164127a2a2cf01 100644 (file)
@@ -149,6 +149,11 @@ namespace System.Runtime.Serialization
                                return entry.Value;
                }
 
+               internal bool HasKey (string name)
+               {
+                       return serialized [name] != null;
+               }
+               
                public void SetType (Type type)
                {
                        if (type == null)
diff --git a/mcs/class/corlib/System.Runtime.Versioning/FrameworkName.cs b/mcs/class/corlib/System.Runtime.Versioning/FrameworkName.cs
deleted file mode 100644 (file)
index e9b7cb3..0000000
+++ /dev/null
@@ -1,234 +0,0 @@
-//
-// System.Runtime.Versioning.FrameworkName class
-//
-// Authors
-//     Marek Habersack <mhabersack@novell.com>
-//
-// Copyright (C) 2009 Novell, Inc (http://novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-using System;
-using System.Text;
-
-#if NET_4_0
-namespace System.Runtime.Versioning
-{
-       [Serializable]
-       public sealed class FrameworkName : IEquatable <FrameworkName>
-       {
-               static readonly char[] nameSplitChars = {','};
-               static readonly char[] partSplitChars = {'='};
-               
-               string fullName;
-               int? hashCode;
-               
-               public string FullName {
-                       get {
-                               if (fullName == null) {
-                                       var sb = new StringBuilder (Identifier);
-                                       sb.Append (",Version=v");
-                                       sb.Append (Version.ToString ());
-
-                                       string profile = Profile;
-                                       if (!String.IsNullOrEmpty (profile)) {
-                                               sb.Append (",Profile=");
-                                               sb.Append (profile);
-                                       }
-
-                                       fullName = sb.ToString ();
-                               }
-
-                               return fullName;
-                       }
-               }
-               
-               public string Identifier {
-                       get; private set;
-               }
-
-               public string Profile {
-                       get; private set;
-               }
-               
-               public Version Version {
-                       get; private set;
-               }
-               
-               public FrameworkName (string frameworkName)
-               {
-                       if (frameworkName == null)
-                               throw new ArgumentNullException ("frameworkName");
-
-                       if (frameworkName.Length == 0)
-                               throw new ArgumentException ("The parameter 'frameworkName' cannot be an empty string.", "frameworkName");
-
-                       this.Profile = String.Empty;
-                       ParseFrameworkName (frameworkName);
-               }
-
-               public FrameworkName (string identifier, Version version)
-                       : this (identifier, version, String.Empty)
-               {
-               }
-
-               public FrameworkName (string identifier, Version version, string profile)
-               {
-                       if (identifier == null)
-                               throw new ArgumentNullException ("identifier");
-
-                       if (version == null)
-                               throw new ArgumentNullException ("version");
-
-                       if (identifier.Length == 0)
-                               throw new ArgumentException ("The parameter 'identifier' cannot be an empty string.", "identifier");
-                       
-                       this.Identifier = identifier;
-                       this.Version = version;
-                       if (profile == null)
-                               this.Profile = String.Empty;
-                       else
-                               this.Profile = profile;
-               }
-
-               public bool Equals (FrameworkName other)
-               {
-                       return (other.Version == this.Version &&
-                               String.Compare (other.Identifier, this.Identifier, StringComparison.Ordinal) == 0 &&
-                               String.Compare (other.Profile, this.Profile, StringComparison.Ordinal) == 0);
-               }
-
-               public override int GetHashCode ()
-               {
-                       if (hashCode == null) {
-                               hashCode = Version.GetHashCode () ^ Identifier.GetHashCode ();
-                               string profile = Profile;
-                               if (profile != null)
-                                       hashCode ^= profile.GetHashCode ();
-                       }
-                       
-                       return (int)hashCode;
-               }
-
-               public override string ToString ()
-               {
-                       return FullName;
-               }
-
-               public static bool operator == (FrameworkName left, FrameworkName right)
-               {
-                       if (((object)left) == null && ((object)right) == null)
-                               return true;
-
-                       if (((object)left) == null || ((object)right) == null)
-                               return false;
-
-                       return left.Equals (right);
-               }
-
-               public static bool operator != (FrameworkName left, FrameworkName right)
-               {
-                       if (((object)left) == null && ((object)right) == null)
-                               return false;
-
-                       if (((object)left) == null || ((object)right) == null)
-                               return true;
-
-                       return !left.Equals (right);
-               }
-               
-               void ParseFrameworkName (string frameworkName)
-               {
-                       string[] parts = frameworkName.Split (nameSplitChars);
-                       int len = parts.Length;
-
-                       if (len < 2 || len > 3)
-                               throw new ArgumentException ("FrameworkName cannot have less than two components or more than three components.");
-
-                       bool invalid = false;
-                       string part;
-                       string[] splitPart;
-                       int splen;
-                       
-                       Console.WriteLine ("frameworkName == '{0}'", frameworkName);
-                       for (int i = 0; i < len; i++) {
-                               part = parts [i].Trim ();
-                               Console.WriteLine ("\ti == {0}; part == '{1}'", i, part);
-                               if (part.Length == 0) {
-                                       Console.WriteLine ("invalid [1]");
-                                       invalid = true;
-                                       break;
-                               }
-
-                               splitPart = part.Split (partSplitChars);
-                               splen = splitPart.Length;
-                               
-                               if (String.Compare ("version", splitPart [0], StringComparison.OrdinalIgnoreCase) == 0) {
-                                       if (i == 0 || splen != 2) {
-                                               invalid = true;
-                                               Console.WriteLine ("\t\tinvalid [2]");
-                                               break;
-                                       }                                       
-
-                                       try {
-                                               char first = splitPart [1][0];
-                                               if (first == 'v' || first == 'V')
-                                                       splitPart [1] = splitPart [1].Substring (1);
-                                               this.Version = new Version (splitPart [1]);
-                                       } catch (Exception ex) {
-                                               throw new ArgumentException ("FrameworkName version component is invalid.", ex);
-                                       }                                       
-
-                                       continue;
-                               }
-
-                               if (String.Compare ("profile", splitPart [0], StringComparison.OrdinalIgnoreCase) == 0) {
-                                       if (i == 0) {
-                                               invalid = true;
-                                               Console.WriteLine ("\t\tinvalid [3]");
-                                               break;
-                                       }
-
-                                       if (splen > 1)
-                                               Profile = String.Join ("=", splitPart, 1, splen - 1);
-                                       
-                                       continue;
-                               }
-
-                               if (i == 0) {
-                                       Identifier = part;
-                                       continue;
-                               }
-
-                               Console.WriteLine ("\t\tinvalid [4]");
-                               invalid = true;
-                               break;
-                       }
-
-                       if (invalid)
-                               throw new ArgumentException ("FrameworkName is invalid.");
-
-                       if (Version == null)
-                               throw new ArgumentException ("FrameworkName version component is missing.");
-                       
-               }
-       }
-}
-#endif
\ No newline at end of file
index 115cbc6462f7c3f20cd4f47534c5452a0ae9e025..86217bd8cb05bc6b1148253a59084a0fa7f0b2fc 100644 (file)
@@ -1,3 +1,9 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * X509KeyStorageFlags.cs, X509ContentType.cs, X509Certificate.cs
+       X509Certificate20.cs: use MOONLIGHT symbol to disambiguate
+       MonoTouch and Moonlight code.
+
 2009-09-22  Sebastien Pouliot  <sebastien@ximian.com>
 
        * X509Certificate20.cs: Don't depend on SecureString for NET_2_1
index 96d3540ad697ad2bc16119587fb051f3a8af5a78..7830a6b91131af330a332282279f1174bcffa6fd 100644 (file)
@@ -36,7 +36,7 @@ using Mono.Security;
 using Mono.Security.X509;
 
 using System.Runtime.Serialization;
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 using Mono.Security.Authenticode;
 #endif
 
@@ -100,7 +100,7 @@ namespace System.Security.Cryptography.X509Certificates {
                        return new X509Certificate (data);
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                [MonoTODO ("Incomplete - minimal validation in this version")]
                public static X509Certificate CreateFromSignedFile (string filename)
                {
@@ -152,7 +152,7 @@ namespace System.Security.Cryptography.X509Certificates {
 #endif
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
                private void InitFromHandle (IntPtr handle)
                {
index f124684aada413817c7ff8687a7f1ba3b106f1ba..21ff22e3dc48d11e7e9d1b713053ae937c473dd4 100644 (file)
@@ -41,7 +41,7 @@ namespace System.Security.Cryptography.X509Certificates {
 
        [ComVisible (true)]
        [MonoTODO ("X509ContentType.SerializedCert isn't supported (anywhere in the class)")]
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
        public partial class X509Certificate {
 #else
        public partial class X509Certificate : IDeserializationCallback, ISerializable {
@@ -60,7 +60,7 @@ namespace System.Security.Cryptography.X509Certificates {
                        Import (rawData, password, X509KeyStorageFlags.DefaultKeySet);
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                [MonoTODO ("SecureString support is incomplete")]
                public X509Certificate (byte[] rawData, SecureString password)
                {
@@ -73,7 +73,7 @@ namespace System.Security.Cryptography.X509Certificates {
                        Import (rawData, password, keyStorageFlags);
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                [MonoTODO ("SecureString support is incomplete")]
                public X509Certificate (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
                {
@@ -91,7 +91,7 @@ namespace System.Security.Cryptography.X509Certificates {
                        Import (fileName, password, X509KeyStorageFlags.DefaultKeySet);
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                [MonoTODO ("SecureString support is incomplete")]
                public X509Certificate (string fileName, SecureString password)
                {
@@ -104,7 +104,7 @@ namespace System.Security.Cryptography.X509Certificates {
                        Import (fileName, password, keyStorageFlags);
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                [MonoTODO ("SecureString support is incomplete")]
                public X509Certificate (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
                {
@@ -171,7 +171,7 @@ namespace System.Security.Cryptography.X509Certificates {
                        return Export (contentType, pwd);
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                [MonoTODO ("X509ContentType.Pfx/Pkcs12 and SerializedCert are not supported. SecureString support is incomplete.")]
                public virtual byte[] Export (X509ContentType contentType, SecureString password)
                {
@@ -189,7 +189,7 @@ namespace System.Security.Cryptography.X509Certificates {
                                switch (contentType) {
                                case X509ContentType.Cert:
                                        return x509.RawData;
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                                case X509ContentType.Pfx: // this includes Pkcs12
                                        // TODO
                                        throw new NotSupportedException ();
@@ -256,7 +256,7 @@ namespace System.Security.Cryptography.X509Certificates {
                        }
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                [MonoTODO ("SecureString support is incomplete")]
                public virtual void Import (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
                {
@@ -279,7 +279,7 @@ namespace System.Security.Cryptography.X509Certificates {
                        Import (rawData, password, keyStorageFlags);
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                [MonoTODO ("SecureString support is incomplete, missing KeyStorageFlags support")]
                public virtual void Import (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
                {
@@ -288,7 +288,7 @@ namespace System.Security.Cryptography.X509Certificates {
                }
 #endif
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                void IDeserializationCallback.OnDeserialization (object sender)
                {
                }
index e07ae398707ca12e14a1dd5cb180e5db6217d278..e7b0f14a554833a850974cbd370bc7cbdb3276a8 100644 (file)
@@ -37,7 +37,7 @@ namespace System.Security.Cryptography.X509Certificates {
        enum X509ContentType {
                Unknown,
                Cert,
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                // not supported by Silverlight 2.0 (NET_2_1)
                SerializedCert,
                Pfx,
index a36aec8534c24d43fd1e67eaac3b4a012fd1c20b..b7b2d9e62d71eedbcc63bd584102fcf2550edf72 100644 (file)
@@ -35,7 +35,7 @@ namespace System.Security.Cryptography.X509Certificates {
        [ComVisible (true)]
        public enum X509KeyStorageFlags {
                DefaultKeySet = 0,
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                // not supported by Silverlight 2.0 (NET_2_1)
                UserKeySet = 1,
                MachineKeySet = 2,
index 77dde0efef8bfd6581a99a5f284398ed17dd5069..fd63654d727e04e3d33078c9b2e9f1b0b18abb18 100644 (file)
@@ -1,3 +1,33 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * Rijndael.cs
+       * HMACSHA512.cs
+       * RijndaelManagedTransform.cs
+       * HMACSHA384.cs
+       * RijndaelManaged.cs
+       * CryptoConfig.cs
+       * CryptoConfig_2_1.cs
+       * DESCryptoServiceProvider.cs
+       * SHA512Managed.cs
+       * RC2.cs
+       * TripleDES.cs
+       * HMACRIPEMD160.cs
+       * RIPEMD160.cs
+       * RC2CryptoServiceProvider.cs
+       * SymmetricAlgorithm.cs
+       * SHA384Managed.cs
+       * DSACryptoServiceProvider.cs
+       * DES.cs
+       * MACTripleDES.cs
+       * HMACMD5.cs
+       * RSACryptoServiceProvider.cs
+       * RIPEMD160Managed.cs
+       * TripleDESCryptoServiceProvider.cs
+       * SHA1CryptoServiceProvider.cs
+       * SHA512.cs
+       * SHA384.cs:
+               Use MOONLIGHT symbol to disambiguate MonoTouch and Moonlight code.
+
 2010-01-07  Sebastien Pouliot  <sebastien@ximian.com>
 
        * ToBase64Transform.cs: Static-ify some methods to make it easier 
index fab9c67842661d8a79cf67c08c1d10d538f6f666..1d0e78d99ea4e970f7dcb9f13c44744860c2da54 100644 (file)
@@ -29,7 +29,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Collections;
 using System.Globalization;
index d308a8a6f400c57864fbaefc22ee7fce09b2ed12..657c7aa4368ff0085f29607983b418fae532c55d 100644 (file)
@@ -124,7 +124,7 @@ namespace System.Security.Cryptography {
                        }
                        return num;
                }
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                // we need SHA1 support to verify the codecs binary integrity
                public static string MapNameToOID (string name)
                {
index cece541a0ad7c8f698b8d4301e4232af3e51df7e..0a664838bec9f03ca1a7ad5b88f2b29c49cc65c4 100644 (file)
@@ -28,7 +28,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Globalization;
 using System.Runtime.InteropServices;
index f8d410f1fa3148312eab535ca0cb78f760ac3b8d..d1fbf26edd2eca03b57c7f3c2db4b95a52f981c7 100644 (file)
@@ -28,7 +28,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Runtime.InteropServices;
 using Mono.Security.Cryptography;
index fbb5e4fab08f1ca27bdce3afc63e35f5971b5a3b..41951ff66ccf22575abf1a1ddddf321141ed3f34 100644 (file)
@@ -31,7 +31,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.IO;
 using System.Globalization;
index cb5feaf336a2fa7edfb6750958cbfa3349456c38..a84aee8a3d66976e8ef2c38b66d02c7bb40f47ef 100644 (file)
@@ -27,7 +27,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Runtime.InteropServices;
 
index f8a6dc2e4f6b23e04a98f6354f7d5c4012a4f211..0a039c5801be78a0df77851ad7524e24303c5ac1 100644 (file)
@@ -27,7 +27,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Runtime.InteropServices;
 
index e27387ef0b179bbf2f70f77a9894c0c55c572814..007caf5129930014fc1a74c35dc22eaeb458ed00 100644 (file)
@@ -27,7 +27,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Runtime.InteropServices;
 
index d04722104fe6950f8287eff285bfd6b20f454f2b..562d40d6f59580bad385708832796c853f591484 100644 (file)
@@ -27,7 +27,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Runtime.InteropServices;
 
index aebd4b4086f3bc73ffaefe19dae3a8f06543c27d..89089707fdf385ee3e807cde56ef0c4ff9e574b3 100644 (file)
@@ -27,7 +27,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Runtime.InteropServices;
 
index 2b808cb67583c976290deb266cf945dc633efdc1..e7e7ecdf9ca62b70db13f77f1b9a6e464c7eed4e 100644 (file)
@@ -27,7 +27,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Runtime.InteropServices;
 
index 732486edfca7528e85252c210b44335b6310a907..6a5d8461ac051421ff8ee69dedae29570ce6e097 100644 (file)
@@ -28,7 +28,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Globalization;
 using System.Runtime.InteropServices;
index c98781e7b2888859ccd75c00e194abea29f6e53a..2102a480c0f391a341bc99820d8f5494848ab6e2 100644 (file)
@@ -27,7 +27,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Runtime.InteropServices;
 
index c242aabb5c870c7a0da7ed0983ee4da2f81b0269..634d9accbef05d8e954716bacbafc5389ad4abbe 100644 (file)
@@ -30,7 +30,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Runtime.InteropServices;
 
index c254c17e5ba7a2663be01d5bc1d940e550e6802b..ef607bc5fd28b0274dfcca13685009223baf6f17 100644 (file)
@@ -29,7 +29,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.IO;
 using System.Runtime.InteropServices;
index 1ccd1fd3bb71989b5c76700d5a54fcec11713835..a1343db1b853fd960c93c0fa61b8840c34cd0cb6 100644 (file)
@@ -27,7 +27,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 \r
 using System.Runtime.InteropServices;
 \r
index 156b9515f16e1cf0f03fa92b06d56ae3d9efa6d1..f92a6a54f54d962b15b9df9cc7f989b77c679bf5 100644 (file)
@@ -31,7 +31,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Runtime.InteropServices;
 using Mono.Security.Cryptography;
index aa44aed17711a0f5f3bb8260f354f727d22b2e1d..ccc4da333b8d2e36360639019b09d25d5c67775c 100644 (file)
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if  !NET_2_1 || MONOTOUCH
+#if  !MOONLIGHT
 
 using System.Runtime.InteropServices;
 
index c6e8fa60e9acaf218e66b49be322c4a81f842a02..465adc8f35bf358b68c97223b7235b18d9e69c80 100644 (file)
@@ -316,7 +316,7 @@ namespace System.Security.Cryptography {
                }
        }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
        [ComVisible (true)]
        public sealed class SHA1CryptoServiceProvider : SHA1 {
index 6cf037bb988fd83bffe892c02d4e4b025a1b5cbf..2daff34a694ddd48475813c9f7cd2f334d293162 100644 (file)
@@ -29,7 +29,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Runtime.InteropServices;
 \r
index 8b79b5f8ddbc5c7672e7d6d465e026787e9bb9d7..43495bef6b11ed4e70869b0dce3bc1f9305e4eab 100644 (file)
@@ -30,7 +30,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Runtime.InteropServices;
 
index 94d943fe739a5116f63e832c6499a966cff17a60..00baef00d084cc62d6143499109c145893b2798c 100644 (file)
@@ -29,7 +29,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Runtime.InteropServices;
 \r
index 2dc5c1498237938bf7b3d57514f0dfe659579342..190adeb327e4a6bd42677edac659a615f7469e77 100644 (file)
@@ -30,7 +30,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Runtime.InteropServices;
 
index d306b56728f056dbb2c52115b931ba0f82741e91..2ee27a7fabcbdea3b57f808622b05abb2c89b935 100644 (file)
@@ -42,7 +42,7 @@ namespace System.Security.Cryptography {
                protected byte[] KeyValue; 
                protected KeySizes[] LegalBlockSizesValue; 
                protected KeySizes[] LegalKeySizesValue; 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                // Silverlight 2.0 only supports CBC
                internal int FeedbackSizeValue;
                internal CipherMode ModeValue;
@@ -61,7 +61,7 @@ namespace System.Security.Cryptography {
                        m_disposed = false;
                }
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                // No Finalizer or IDisposable.Dispose in Silverlight 2.0
                // Documentation makes it "clear" that Clear MUST BE CALLED to zero out sensitive information
 #else          
index 9af792158e0d60ea0b2346c361e1f5347f7fd7c6..f368f7ca1ca147118a8796d1a429d063fa29976c 100644 (file)
@@ -27,7 +27,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Globalization;
 using System.Runtime.InteropServices;
index 61c2729b77df89d9c05c7bb8d2277b90c26404bf..8a93cb90d2f2e471334a2aa8a0a2b82fd808fe53 100644 (file)
@@ -27,7 +27,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Runtime.InteropServices;
 using Mono.Security.Cryptography;
index a2683cb943ecc28ded7a3da0be1ca9ccd68e924f..86d9705e6966345705e4d25f56bba4c0a30e47d0 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * PublisherIdentityPermissionAttribute.cs: use MOONLIGHT symbol to
+       disambiguate MonoTouch and Moonlight code.
+
 2009-09-22  Sebastien Pouliot  <sebastien@ximian.com>
 
        * PermissionSetAttribute.cs: Don't create a pset for NET_2_1
index 2740291d494cb48f7f846df6c43668de77ed3a89..d5ae1319b1a9e843167d82d26ab50939a9ceea99 100644 (file)
@@ -27,7 +27,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Runtime.InteropServices;
 using SSCX = System.Security.Cryptography.X509Certificates;
index 1a2429495d3c63f685a084971b390dc77216a61e..b1caf8bfd76c1a04c8df7d12ec5fae1a36f6e750 100644 (file)
@@ -1,3 +1,15 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * Zone.cs
+       * Hash.cs
+       * Evidence.cs
+       * PolicyLevel.cs
+       * PolicyLevel_2_1.cs
+       * ZoneMembershipCondition.cs
+       * HashMembershipCondition.cs:
+               Use MOONLIGHT symbol to disambiguate MonoTouch
+               and Moonlight code.
+
 2010-02-27 Rodrigo Kumpera  <rkumpera@novell.com>
 
        * Evidence.cs: Add some v4 bits.
index a876dfd3c9ccd5320c0d3c411903787bbfcd4068..5d932f5259d0fec1b475152154acaa88b9129246 100644 (file)
@@ -39,7 +39,7 @@ using System.Runtime.InteropServices;
 using System.Security.Permissions;
 using System.Security.Cryptography.X509Certificates;
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 using Mono.Security.Authenticode;
 #endif
 
index ce8bb46ba8881a0b9f6e9f1d9dafd72cb9d3c38e..7287b97f31a45757e9a53d162aa3b82130aa14c6 100644 (file)
@@ -29,7 +29,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.IO;
 using System.Reflection;
index 75204b3f40496a8bd2fc653b20455848119e9e86..6918f250f85c6ba3b6e522512d6eface402663fa 100644 (file)
@@ -28,7 +28,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Collections;
 using System.Globalization;
index b13c05154a21298e094e0aea601e88a04a59e9d0..a124af3d3202dd0570c0450508911b6b2d8313ac 100644 (file)
@@ -31,7 +31,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Collections; // for IList
 using System.Globalization;
index dae7c7e5fc76c7c3ec307d249b63d7f932ace504..6582f73a03707940a4893b642b0f9171b367c6f2 100644 (file)
@@ -31,7 +31,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
 
 using System.Reflection;
 
index 88736f0008b2adf341d150aaf37ccbd1c2a60830..6b40975ad0ed55da8af4aaff9fe96038b1ebad93 100644 (file)
@@ -28,7 +28,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.IO;
 using System.Globalization;
index 794b32985f7df6c3328470f21da094793979b03f..d3a831b2814bf141f50c7d34621693915cd64de7 100644 (file)
@@ -28,7 +28,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Collections;
 using System.Globalization;
index 16023fc31ae791a431739ea3029348d3d526d279..50ff478d6e0bbf1b35922ed935b022be7bb02280 100644 (file)
@@ -1,3 +1,26 @@
+2010-04-16  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * SecurityManager.cs: Add stub for new methods (so code compiles
+       correctly under other profiles)
+       * SecurityManager_2_1.cs: Implement [Check|Ensure]ElevatedPermissions
+       for Moonlight Elevated Trust
+
+2010-03-23  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * SecurityManager_2_1.cs: Add an internal HasElevatedPermissions 
+       property to mscorlib since the "real" (i.e. visible) one in 
+       System.Windows.dll is not accessible by most code.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * SecurityTransparentAttribute.cs
+       * SecurityFrame.cs
+       * IPermission.cs
+       * SecurityManager.cs
+       * SecurityManager_2_1.cs
+       * SecuritySafeCriticalAttribute.cs:
+               use MOONLIGHT symbol to disambiguate MonoTouch and Moonlight code.
+
 2009-10-30     Marek Safar  <marek.safar@gmail.com>
 
        * SecurityRuleSet.cs, SecurityRulesAttribute.cs: Implemented.
index 4155b32463d48b8310fbb632a7f064b9e392098d..d045a2a9498daffd67a0e13d49852c6a5e9cd44b 100644 (file)
@@ -32,7 +32,7 @@ using System.Runtime.InteropServices;
 namespace System.Security {
 
        [ComVisible (true)]
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
        public interface IPermission {
 #else
        public interface IPermission : ISecurityEncodable {
index 404ada19995cefa1ede28c034404ace3905772f9..340c8764386c62a6dc3b0e4aa48b85d5a2c48895 100644 (file)
@@ -53,7 +53,7 @@ namespace System.Security {
        }
 #pragma warning restore 649    
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
        internal struct SecurityFrame {
 
                private AppDomain _domain;
index 7040a08128fe7b361fd958c0c49575fae96df782..26da6e305bb0493d4810c97efc59dbb71cc59185 100644 (file)
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
 using System.Collections;
+using System.Diagnostics;
 using System.Globalization;
 using System.IO;
 using System.Reflection;
@@ -88,6 +89,17 @@ namespace System.Security {
                        set;
                }
 
+               internal static bool CheckElevatedPermissions ()
+               {
+                       return true; // always true outside Moonlight
+               }
+
+               [Conditional ("MOONLIGHT")]
+               internal static void EnsureElevatedPermissions ()
+               {
+                       // do nothing outside of Moonlight
+               }
+
                // methods
 
                // NOTE: This method doesn't show in the class library status page because
index 7e726a84bbf0a9a19bbc53e8fbed2e0f1504ea6c..9bd6441fc5fd58111c8528e1cdcd48550e854c26 100644 (file)
@@ -7,7 +7,7 @@
 //
 // (C) Nick Drochak
 // Portions (C) 2004 Motus Technologies Inc. (http://www.motus.com)
-// Copyright (C) 2004-2005, 2009 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2004-2005, 2009-2010 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -29,7 +29,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
 
 using System.Reflection;
 using System.Runtime.CompilerServices;
@@ -47,6 +47,12 @@ namespace System.Security {
 
        internal static class SecurityManager {
 
+               static SecurityManager ()
+               {
+                       // if the security manager (coreclr) is not active then the application has elevated permissions
+                       HasElevatedPermissions = !SecurityEnabled;
+               }
+
                // note: this let us differentiate between running in the browser (w/CoreCLR) and \r
                // running on the desktop (e.g. smcs compiling stuff)\r
                extern public static bool SecurityEnabled {
@@ -54,6 +60,35 @@ namespace System.Security {
                        get;
                }
 
+               internal static bool HasElevatedPermissions {
+                       get; set;
+               }
+
+               extern static bool RequiresElevatedPermissions {
+                       [MethodImplAttribute (MethodImplOptions.InternalCall)]
+                       get;
+               }
+
+               [MethodImpl (MethodImplOptions.NoInlining)]
+               internal static bool CheckElevatedPermissions ()
+               {
+                       if (HasElevatedPermissions)
+                               return true;
+
+                       return !RequiresElevatedPermissions;
+               }
+
+               [MethodImpl (MethodImplOptions.NoInlining)]
+               internal static void EnsureElevatedPermissions ()
+               {
+                       // shortcut (to avoid the stack walk) if we are running with elevated trust
+                       if (HasElevatedPermissions)
+                               return;
+
+                       if (RequiresElevatedPermissions)
+                               throw new SecurityException ("This operation requires elevated permissions");
+               }
+
                internal static IPermission CheckPermissionSet (Assembly a, PermissionSet ps, bool noncas)
                {
                        return null;
index 0b641438a43102eb6bbfc4ae378ae7a1ecc3510e..7524ec55459d9fe6b3b67b679b9e544d992ad77d 100644 (file)
@@ -28,7 +28,7 @@
 
 namespace System.Security {
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
        [MonoTODO ("Only supported by the runtime when CoreCLR is enabled")]
 #endif
        [AttributeUsage (AttributeTargets.All, AllowMultiple=false, Inherited=false)]
index f5190aece2763bfa0d09c69399bda4a5a3d98791..ef89603dbf601ebe43f225e7acfc306d4a00189d 100644 (file)
@@ -28,7 +28,7 @@
 
 namespace System.Security {
 
-#if !NET_2_1 || MONOTOUCH
+#if MOONLIGHT
        [MonoTODO ("Only supported by the runtime when CoreCLR is enabled")]
 #endif
        [AttributeUsage (AttributeTargets.Assembly, AllowMultiple=false, Inherited=false)]
index 8ce7828fc903f988e136737c8882afe23d5da3e5..9bae2a7034915c2f532f7ba129d58f6cabc480ea 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * StringBuilder.cs, Encoding.cs: use MOONLIGHT symbol to
+       disambiguate MonoTouch and Moonlight code.
+
 2010-02-02  Jb Evain  <jbevain@novell.com>
 
        * ASCIIEncoding.cs, Latin1Encoding.cs: remove duplicated code.
index 303b150a7304721c699be7d5bbc4154b1957f8e7..32e2312b45d8419a73118bbfe7ad01bce96521a0 100644 (file)
@@ -444,13 +444,13 @@ public abstract class Encoding : ICloneable
                        case UnicodeEncoding.BIG_UNICODE_CODE_PAGE:
                                return BigEndianUnicode;
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        case Latin1Encoding.ISOLATIN_CODE_PAGE:
                                return ISOLatin1;
 #endif
                        default: break;
                }
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                // Try to obtain a code page handler from the I18N handler.
                Encoding enc = (Encoding)(InvokeI18N ("GetEncoding", codepage));
                if (enc != null) {
@@ -494,7 +494,7 @@ public abstract class Encoding : ICloneable
                return e;
        }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
        public static Encoding GetEncoding (int codepage,
                EncoderFallback encoderFallback, DecoderFallback decoderFallback)
@@ -565,7 +565,7 @@ public abstract class Encoding : ICloneable
                return encoding_infos;
        }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
        [ComVisible (false)]
        public bool IsAlwaysNormalized ()
        {
@@ -610,7 +610,7 @@ public abstract class Encoding : ICloneable
                        UTF32Encoding.BIG_UTF32_CODE_PAGE,
                        "UTF_32BE",
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        Latin1Encoding.ISOLATIN_CODE_PAGE,
                        "iso_8859_1", "latin1"
 #endif // !NET_2_1
@@ -639,7 +639,7 @@ public abstract class Encoding : ICloneable
                        if (converted == ((string)encodings [i]))
                                return GetEncoding (code);
                }
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                // Try to obtain a web encoding handler from the I18N handler.
                Encoding enc = (Encoding)(InvokeI18N ("GetEncoding", name));
                if (enc != null) {
@@ -875,14 +875,14 @@ public abstract class Encoding : ICloneable
                                                                case 3: code_page = UTF8Encoding.UTF8_CODE_PAGE; break;
                                                                case 4: code_page = UnicodeEncoding.UNICODE_CODE_PAGE; break;
                                                                case 5: code_page = UnicodeEncoding.BIG_UNICODE_CODE_PAGE; break;
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                                                                case 6: code_page = Latin1Encoding.ISOLATIN_CODE_PAGE; break;
 #endif
                                                                }
                                                                defaultEncoding = GetEncoding (code_page);
                                                        }
                                                } catch (NotSupportedException) {
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                                                        defaultEncoding = UTF8;
 #else
                                                        // code_page is not supported on underlying platform
@@ -891,7 +891,7 @@ public abstract class Encoding : ICloneable
                                                } catch (ArgumentException) {
                                                        // code_page_name is not a valid code page, or is 
                                                        // not supported by underlying OS
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                                                        defaultEncoding = UTF8;
 #else
                                                        defaultEncoding = UTF8Unmarked;
@@ -906,7 +906,7 @@ public abstract class Encoding : ICloneable
                }
        }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
        // Get the ISO Latin1 encoding object.
        private static Encoding ISOLatin1
index d3033b1b00e34e3da2c3bb35fa92b8ff407889f9..d68cb8939e6fb0de3c6d671ca231a25167ecbbbd 100644 (file)
@@ -536,7 +536,7 @@ namespace System.Text {
                        return this;
                }
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                internal
 #else
                public
@@ -546,7 +546,7 @@ namespace System.Text {
                        return AppendFormat (null, format, new object [] { arg0 });
                }
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                internal
 #else
                public
@@ -556,7 +556,7 @@ namespace System.Text {
                        return AppendFormat (null, format, new object [] { arg0, arg1 });
                }
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                internal
 #else
                public
index 2992cdbb9bb9dc06135f83e53af76a2948c87607..97e61717007e81308cf7a74612f8f6dd2c182d8b 100644 (file)
@@ -1,3 +1,14 @@
+2010-04-15  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * Future.cs:
+       * Task.cs:
+       * TaskCanceledException.cs:
+       * TaskContinuationOptions.cs:
+       * TaskCreationOptions.cs:
+       * TaskFactory.cs:
+       * TaskScheduler.cs:
+       * TaskStatus.cs: Add BOOTSTRAP_NET_4_0 define
+
 2010-03-02  Jérémie Laval  <jeremie.laval@gmail.com>
 
        * Task.cs: If we add a continuation when the Task is already finished
index 8dd142403a8dba2ec26f42d4935a3487138d9808..ecb11b2b868ddb5d98bc135d51836ca38169cf81 100644 (file)
@@ -1,4 +1,4 @@
-#if NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0
 // Future.cs
 //
 // Copyright (c) 2008 Jérémie "Garuma" Laval
diff --git a/mcs/class/corlib/System.Threading.Tasks/Internal/ChangeLog b/mcs/class/corlib/System.Threading.Tasks/Internal/ChangeLog
new file mode 100644 (file)
index 0000000..5f10ffe
--- /dev/null
@@ -0,0 +1,4 @@
+2010-04-19  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * ThreadWorker.cs: Cleanup and refactoring
+
index 66001c7b4e00123f56ad6139dbf05f879bea3844..98ebf3573b1acb9be3f4b3692221f099f49fbde0 100644 (file)
@@ -1,4 +1,4 @@
-#if NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0
 // 
 // CyclicDeque.cs
 //  
@@ -198,4 +198,4 @@ namespace System.Threading.Tasks
                }
        }
 }
-#endif
\ No newline at end of file
+#endif
index 3b205696f1166e55ba276c6df36a47e4d5f9c455..536f368bb3847fdc48e12c47bcf5b0ec96160ec8 100644 (file)
@@ -1,4 +1,4 @@
-#if NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0
 // IScheduler.cs
 //
 // Copyright (c) 2008 Jérémie "Garuma" Laval
index 28d5a0f6fbfeb87b34a630827ee6d1833f6fbfd6..5b65790cec1f9ee85258fa727baedf1e0a67a89f 100644 (file)
@@ -1,4 +1,4 @@
-#if NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0
 // Scheduler.cs
 //
 // Copyright (c) 2008 Jérémie "Garuma" Laval
index cd6307105d6a17c14545a5c080dffe3b54cabf9c..713a61cf7424fea7d1d9b15212f39ba4b17d1aa3 100644 (file)
@@ -1,4 +1,4 @@
-#if NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0
 // 
 // SchedulerProxy.cs
 //  
index cad86d43482e06fb89789785fd5b52416f73170c..f16a05d907c4556e71c522a6e975255a3dc8fa91 100644 (file)
@@ -1,4 +1,4 @@
-#if NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0
 // ThreadWorker.cs
 //
 // Copyright (c) 2008 Jérémie "Garuma" Laval
@@ -48,10 +48,7 @@ namespace System.Threading.Tasks
                readonly int  stealingStart;
                const    int  maxRetry = 5;
                
-               #region Sleep related fields
-               readonly SpinWait wait = new SpinWait ();
                const int sleepThreshold = 100000;
-               #endregion
                
                Action threadInitializer;
                
@@ -100,6 +97,7 @@ namespace System.Threading.Tasks
        
                                this.workerThread.IsBackground = true;
                                this.workerThread.Priority = priority;
+                               this.workerThread.Name = "ParallelFxThreadWorker";
                        };
                        threadInitializer ();
                }
@@ -136,15 +134,13 @@ namespace System.Threading.Tasks
                void WorkerMethodWrapper ()
                {
                        int sleepTime = 0;
+                       SpinWait wait = new SpinWait ();
                        
                        // Main loop
                        while (started == 1) {
                                bool result = false;
-                               try {
-                                       result = WorkerMethod ();
-                               } catch (Exception e) {
-                                       Console.WriteLine (e.ToString ());
-                               }
+
+                               result = WorkerMethod ();
                                
                                // Wait a little and if the Thread has been more sleeping than working shut it down
                                wait.SpinOnce ();
index ae6fb42636341011ffcd846da9bf6fc74f7384b7..acc2b5aa1fd00a12a83c3229be80236635ca751a 100644 (file)
@@ -1,4 +1,3 @@
-#if NET_4_0
 // Task.cs
 //
 // Copyright (c) 2008 Jérémie "Garuma" Laval
@@ -23,6 +22,8 @@
 //
 //
 
+#if NET_4_0 || BOOTSTRAP_NET_4_0
+
 using System;
 using System.Threading;
 using System.Collections.Concurrent;
index e06902099829238be89a3fec8e19d4e3f3b56fb8..23ec35ac2d530d4360ea63d09debbe0d0655d846 100644 (file)
@@ -1,4 +1,4 @@
-#if NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0
 // TaskCanceledException.cs
 //
 // Copyright (c) 2008 Jérémie "Garuma" Laval
index 49d8329577c19f4e209bffc37b8affc630cf57ea..a5205523c7232b5044ce79e8629d36b01a6a6e3e 100644 (file)
@@ -1,4 +1,4 @@
-#if NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0
 // TaskContinuationKind.cs
 //
 // Copyright (c) 2008 Jérémie "Garuma" Laval
index 23d1a7f0256813420a4de64c16b92d44cfddd11f..3af2c965b94a21894d3fba33dca9744affde8405 100644 (file)
@@ -1,4 +1,4 @@
-#if NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0
 // TaskCreationOptions.cs
 //
 // Copyright (c) 2008 Jérémie "Garuma" Laval
index 49fc5574d06d8bd05a31e33df84df93e48fb7aa6..d69c9cd1e8778a3160b3def4e3aa3b72b6d2ebc8 100644 (file)
@@ -1,4 +1,4 @@
-#if NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0
 // 
 // TaskFactory.cs
 //  
index bcef0cd8cef10c64572a897f095efddb3832e493..e836e6e4856c5aa76850bdbe04c40b1636543eac 100644 (file)
@@ -1,4 +1,4 @@
-#if NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0
 // 
 // TaskScheduler.cs
 //  
index 851437013ffccbb3987bc71f5b829564cf316de4..ff9060220874cf1802fe9647c8256a19e421cb67 100644 (file)
@@ -1,4 +1,4 @@
-#if NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0
 // 
 // TaskStatus.cs
 //  
index c91bde8ec16f5650bac2bc459ddbc16ff5cfc9f7..3c76f0925f539044609117c52229c9f4e0bef932 100644 (file)
@@ -1,4 +1,4 @@
-#if NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0
 // AtomicBoolean.cs
 //
 // Copyright (c) 2008 Jérémie "Garuma" Laval
index 41ef999b0324dc039b84704e5b15f64dbe932a3d..d97407c29e13d2d955a00d0c2cd86af8e3f97aa7 100644 (file)
@@ -1,3 +1,27 @@
+2010-04-23  Rolf Bjarne Kvinge  <RKvinge@novell.com>
+
+       * LazyThreadSafetyMode.cs: Include in Moonlight build.
+
+2010-04-15  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * AtomicBoolean.cs:
+       * CountdownEvent.cs:
+       * SpinLock.cs: Add BOOTSTRAP_NET_4_0 define
+
+2010-03-25 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * ThreadPool.cs: add fast path to queue work items in the runtime.
+
+2010-03-23  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * Monitor.cs: Implement new NET_4_0 (and SL4) Enter overload 
+       required to run some DRT tests (e.g. 7007)
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * ThreadPool.cs, Thread.cs, ExecutionContext.cs: use MOONLIGHT
+       symbol to disambiguate MonoTouch and Moonlight code.
+
 2010-03-08  Jérémie Laval  <jeremie.laval@gmail.com>
 
        * SpinLock.cs: Merge algorithm back in SpinLock struct
index 0a53f30e5244c7124dcae24597c67345aba019a3..c12c85ed67c632f7ae45f44c10e0d45630cdf851 100644 (file)
@@ -1,4 +1,3 @@
-#if NET_4_0 || BOOTSTRAP_NET_4_0
 // CountdownEvent.cs
 //
 // Copyright (c) 2008 Jérémie "Garuma" Laval
@@ -25,6 +24,8 @@
 
 using System;
 
+#if NET_4_0 || BOOTSTRAP_NET_4_0
+
 namespace System.Threading
 {      
        public class CountdownEvent : IDisposable
index 6deff9db0e222052e26516008bb8410a77d778a6..684caf0a2e4fc928c72e11a6fe4ae096e2563c71 100644 (file)
@@ -36,7 +36,7 @@ namespace System.Threading {
 
        [Serializable]
        public sealed class ExecutionContext : ISerializable {
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                private SecurityContext _sc;
 #endif
                private bool _suppressFlow;
@@ -48,7 +48,7 @@ namespace System.Threading {
 
                internal ExecutionContext (ExecutionContext ec)
                {
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        if (ec._sc != null)
                                _sc = new SecurityContext (ec._sc);
 #endif
@@ -69,7 +69,7 @@ namespace System.Threading {
                                return null;
 
                        ExecutionContext capture = new ExecutionContext (ec);
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        if (SecurityManager.SecurityEnabled)
                                capture.SecurityContext = SecurityContext.Capture ();
 #endif
@@ -94,7 +94,7 @@ namespace System.Threading {
                }
                
                // internal stuff
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                internal SecurityContext SecurityContext {
                        get {
                                if (_sc == null)
@@ -127,7 +127,7 @@ namespace System.Threading {
                        ec.FlowSuppressed = false;
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                [MonoTODO ("only the SecurityContext is considered")]
                [SecurityPermission (SecurityAction.LinkDemand, Infrastructure = true)]
                public static void Run (ExecutionContext executionContext, ContextCallback callback, object state)
index e8213063200c04b91989011269ebc5e5cf524327..b23ffe7a3ab54481d850a540f5f72ef03ae9d9bf 100644 (file)
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_4_0
+#if NET_4_0 || MOONLIGHT
 
 using System;
 
index ac78672ecb6f93d3cb4df95daa7a717ec0322229..6320b39f5219cb78aa66aa835c35f561e9c7fdf9 100644 (file)
@@ -176,5 +176,19 @@ namespace System.Threading
                                if (exitContext) SynchronizationAttribute.EnterContext ();
                        }
                }
+
+#if NET_4_0 || MOONLIGHT
+               public static void Enter (object obj, ref bool lockTaken)
+               {
+                       if (obj == null)
+                               throw new ArgumentNullException ("obj");
+                       if (lockTaken)
+                               throw new ArgumentException ("lockTaken");
+
+                       Enter (obj);
+                       // if Enter throws then lockTaken will be false
+                       lockTaken = true;
+               }
+#endif
        }
 }
index 92fab359e3611a48ccacb125e95ccc68179de52f..e3fb372dd26551be9327ea5a6349eacb7a0e5eab 100644 (file)
@@ -26,7 +26,7 @@ using System;
 using System.Runtime.ConstrainedExecution;
 using System.Runtime.InteropServices;
 
-#if NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0
 namespace System.Threading
 {
        [StructLayout(LayoutKind.Explicit)]
index 86e797c764815b88fd3bc9ad93a5a3f9d36b8641..60b3871f61559f8ccc348e365bb85e82ff24e3e6 100644 (file)
@@ -197,7 +197,7 @@ namespace System.Threading {
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private extern static byte[] ByteArrayToCurrentDomain (byte[] arr);
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public static IPrincipal CurrentPrincipal {
                        get {
                                Thread th = CurrentThread;
@@ -262,7 +262,7 @@ namespace System.Threading {
                        }
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                // Stores a hash keyed by strings of LocalDataStoreSlot objects
                static Hashtable datastorehash;
                private static object datastore_lock = new object ();
@@ -404,7 +404,7 @@ namespace System.Threading {
                        internal_thread = it;
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
                public ApartmentState ApartmentState {
                        get {
@@ -681,7 +681,7 @@ namespace System.Threading {
                        }
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public ThreadPriority Priority {
                        get {
                                return(ThreadPriority.Lowest);
@@ -708,7 +708,7 @@ namespace System.Threading {
                        Abort_internal (Internal, null);
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
                public void Abort (object stateInfo) 
                {
@@ -746,7 +746,7 @@ namespace System.Threading {
                        return Join_internal (Internal, millisecondsTimeout, Internal.system_thread_handle);
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public bool Join(TimeSpan timeout)
                {
                        long ms = (long) timeout.TotalMilliseconds;
@@ -762,7 +762,7 @@ namespace System.Threading {
                public extern static void MemoryBarrier ();
 #endif
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private extern void Resume_internal();
 
@@ -789,7 +789,7 @@ namespace System.Threading {
                        }
                }
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                private void StartSafe ()
                {
                        current_thread = this;
@@ -847,7 +847,7 @@ namespace System.Threading {
                        Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
 
                        // Thread_internal creates and starts the new thread, 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        if (Thread_internal((ThreadStart) StartSafe) == (IntPtr) 0)
 #else
                        if (Thread_internal((ThreadStart) StartUnsafe) == (IntPtr) 0)
@@ -855,7 +855,7 @@ namespace System.Threading {
                                throw new SystemException ("Thread creation failed.");
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private extern static void Suspend_internal(InternalThread thread);
 
@@ -1049,7 +1049,7 @@ namespace System.Threading {
                        // Managed and native threads are currently bound together.
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public ApartmentState GetApartmentState ()
                {
                        return (ApartmentState)Internal.apartment_state;
@@ -1091,7 +1091,7 @@ namespace System.Threading {
                        Start ();
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                // NOTE: This method doesn't show in the class library status page because
                // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
                // But it's there!
index 21578734bd630329c4d25f9562e242b9d31b8948..7dfee45fc808f18c8f9e64f52a3fc26afed7434b 100644 (file)
@@ -82,15 +82,26 @@ namespace System.Threading {
                        if (callBack == null)
                                throw new ArgumentNullException ("callBack");
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        callBack = MoonlightHandler (callBack);
 #endif
-                       IAsyncResult ar = callBack.BeginInvoke (state, null, null);
-                       if (ar == null)
-                               return false;
+                       if (callBack.IsTransparentProxy ()) {
+                               IAsyncResult ar = callBack.BeginInvoke (state, null, null);
+                               if (ar == null)
+                                       return false;
+                       } else {
+                               if (!callBack.HasSingleTarget)
+                                       throw new Exception ("The delegate must have only one target");
+
+                               AsyncResult ares = new AsyncResult (callBack, state, true);
+                               pool_queue (ares);
+                       }
                        return true;
                }
 
+               [MethodImplAttribute(MethodImplOptions.InternalCall)]
+               static extern void pool_queue (AsyncResult ares);
+
                public static RegisteredWaitHandle RegisterWaitForSingleObject (WaitHandle waitObject,
                                                                                WaitOrTimerCallback callBack,
                                                                                object state,
@@ -155,18 +166,25 @@ namespace System.Threading {
                public static bool UnsafeQueueUserWorkItem (WaitCallback callBack, object state)
                {
                        // no stack propagation here (that's why it's unsafe and requires extra security permissions)
-                       IAsyncResult ar = null;
+                       if (!callBack.IsTransparentProxy ()) {
+                               if (!callBack.HasSingleTarget)
+                                       throw new Exception ("The delegate must have only one target");
+
+                               AsyncResult ares = new AsyncResult (callBack, state, false);
+                               pool_queue (ares);
+                               return true;
+                       }
                        try {
                                if (!ExecutionContext.IsFlowSuppressed ())
                                        ExecutionContext.SuppressFlow (); // on current thread only
-
-                               ar = callBack.BeginInvoke (state, null, null);
-                       }
-                       finally {
+                               IAsyncResult ar = callBack.BeginInvoke (state, null, null);
+                               if (ar == null)
+                                       return false;
+                       finally {
                                if (ExecutionContext.IsFlowSuppressed ())
                                        ExecutionContext.RestoreFlow ();
                        }
-                       return (ar != null);
+                       return true;
                }
                
                [MonoTODO("Not implemented")]
@@ -208,7 +226,7 @@ namespace System.Threading {
 
 #endif
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                static WaitCallback MoonlightHandler (WaitCallback callback)
                {
                        return delegate (object o) {
index b520a9ec0a9f8abfe0c9b1b157dfa77f7563d148..e1edad035eefd311be8c61aced0dbba54ced42c2 100644 (file)
@@ -5,7 +5,7 @@
 //  Ben Maurer (bmaurer@ximian.com)
 //  Marek Safar (marek.safar@gmail.com)
 //
-// Copyright (C) 2004 Novell
+// Copyright (C) 2004, 2010 Novell
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -50,6 +50,15 @@ namespace System
        public delegate void Action <in T1, in T2, in T3, in T4, in T5, in T6> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
        public delegate void Action <in T1, in T2, in T3, in T4, in T5, in T6, in T7> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
        public delegate void Action <in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
+#elif MOONLIGHT
+       [TypeForwardedFrom (Consts.AssemblySystem_Core)]
+       public delegate void Action ();
+
+       public delegate void Action <T> (T obj);
+       public delegate void Action <T1, T2, T3, T4, T5> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
+       public delegate void Action <T1, T2, T3, T4, T5, T6> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
+       public delegate void Action <T1, T2, T3, T4, T5, T6, T7> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
+       public delegate void Action <T1, T2, T3, T4, T5, T6, T7, T8> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
 #else
        public delegate void Action <T> (T obj);
 #endif 
index 06ea67fd6542572017bcd563efd8faaf124f75e6..db61c741a891fa35a9c5dd548c8f20fbc8565f86 100644 (file)
@@ -37,7 +37,7 @@ using System.Security.Permissions;
 using System.Security.Policy;
 using System.Configuration.Assemblies;
 using System.Text;
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 using System.Runtime.Remoting;
 using System.Runtime.Remoting.Activation;
 #endif
@@ -58,7 +58,7 @@ namespace System
                {
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                [MonoTODO ("No COM support")]
                public static ObjectHandle CreateComInstanceFrom (string assemblyName, string typeName)
                {
@@ -253,40 +253,36 @@ namespace System
                        if ((bindingAttr & _accessFlags) == 0)
                                bindingAttr |= BindingFlags.Public | BindingFlags.Instance;
 
-                       int length = 0;
-                       if (args != null)
-                               length = args.Length;
-
-                       Type[] atypes = length == 0 ? Type.EmptyTypes : new Type [length];
-                       for (int i = 0; i < length; ++i)
-                               if (args [i] != null)
-                                       atypes [i] = args [i].GetType ();
-
                        if (binder == null)
                                binder = Binder.DefaultBinder;
 
-                       ConstructorInfo ctor = (ConstructorInfo) binder.SelectMethod (bindingAttr, type.GetConstructors (bindingAttr), atypes, null);
+                       object state;
+                       ConstructorInfo ctor = (ConstructorInfo) binder.BindToMethod (bindingAttr, type.GetConstructors (bindingAttr), ref args, null, null, null, out state);
 
                        if (ctor == null) {
                                // Not sure about this
-                               if (type.IsValueType && atypes.Length == 0) {
+                               if (type.IsValueType && (args == null || args.Length == 0)) {
                                        return CreateInstanceInternal (type);
                                }
 
-                               StringBuilder sb = new StringBuilder ();
-                               foreach (Type t in atypes){
-                                               sb.Append (t != null ? t.ToString () : "(unknown)");
-                                       sb.Append (", ");
+                               var sb = new StringBuilder ();
+                               if (args != null) {
+                                       for (int i = 0; i < args.Length; i++) {
+                                               if (i > 0)
+                                                       sb.Append (", ");
+
+                                               var argument = args [i];
+                                               var arg_type = argument != null ? argument.GetType () : null;
+                                               sb.Append (arg_type != null ? arg_type.ToString () : "(unknown)");
+                                       }
                                }
-                               if (sb.Length > 2)
-                                       sb.Length -= 2;
-                               
+
                                throw new MissingMethodException (String.Format (Locale.GetText ("No constructor found for {0}::.ctor({1})"),
                                                                                 type.FullName, sb));
                        }
 
                        CheckAbstractType (type);
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        if (activationAttributes != null && activationAttributes.Length > 0) {
                                if (!type.IsMarshalByRef) {
                                        string msg = Locale.GetText ("Type '{0}' doesn't derive from MarshalByRefObject.", type.FullName);
@@ -357,7 +353,7 @@ namespace System
                        }
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                [SecurityPermission (SecurityAction.LinkDemand, RemotingConfiguration = true)]
                public static object GetObject (Type type, string url)
                {
index 852bbe9ebefdefadbe77fdfab13001c6020aae32..b2e1e57f46f218ea7b49f2c76761a688db3e972e 100644 (file)
@@ -81,7 +81,7 @@ namespace System {
 
                [ThreadStatic]
                static Hashtable assembly_resolve_in_progress_refonly;
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                // CAS
                private Evidence _evidence;
                private PermissionSet _granted;
@@ -121,7 +121,7 @@ namespace System {
                        get { throw new NotImplementedException (); }
                }
 #endif
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public string BaseDirectory {
                        get {
                                string path = SetupInformationNoCopy.ApplicationBase;
@@ -174,7 +174,7 @@ namespace System {
                                return getFriendlyName ();
                        }
                }
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public Evidence Evidence {
                        get {
                                // if the host (runtime) hasn't provided it's own evidence...
@@ -248,7 +248,7 @@ namespace System {
                        }
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
                [Obsolete ("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead.")]
                [SecurityPermission (SecurityAction.LinkDemand, ControlAppDomain = true)]
@@ -793,7 +793,7 @@ namespace System {
                        assembly.FromByteArray = true;
                        return assembly;
                }
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 #if NET_4_0
                [Obsolete ("AppDomain policy levels are obsolete")]
 #endif
@@ -945,7 +945,7 @@ namespace System {
                        return _process_guid;
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
 
                public static AppDomain CreateDomain (string friendlyName)
                {
@@ -1155,7 +1155,7 @@ namespace System {
 
                public override string ToString ()
                {
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        return getFriendlyName ();
 #else
                        StringBuilder sb = new StringBuilder ("Name:");
@@ -1369,7 +1369,7 @@ namespace System {
                        get { return _domain_manager; }
                }
 
-#if (!NET_2_1 || MONOTOUCH)
+#if (!MOONLIGHT)
 
                public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
 
@@ -1477,9 +1477,9 @@ namespace System {
                {
                        return GetAssemblies (true);
                }
-#endif
 
-#if NET_2_1 && !MONOTOUCH
+#else // MOONLIGHT
+
                public int ExecuteAssemblyByName (string assemblyName)
                {
                        // critical code in SL that we're not calling in ML
@@ -1509,5 +1509,42 @@ namespace System {
                        throw new NotImplementedException ();
                }
 #endif
+
+#if NET_4_0 || MOONLIGHT
+               [MonoTODO ("Currently always returns false")]
+               public bool? IsCompatibilitySwitchSet (string value)
+               {
+                       if (value == null)
+                               throw new ArgumentNullException ("value");
+                       // default (at least for SL4) is to return false for unknown values (can't get a null out of it)
+                       return false;
+               }
+
+               [MonoTODO ("Currently always returns false")]
+               public static bool MonitoringIsEnabled { 
+                       get { return false; }
+                       set { throw new NotImplementedException (); }
+               }
+
+               [MonoTODO]
+               public long MonitoringSurvivedMemorySize {
+                       get { throw new NotImplementedException (); }
+               }
+
+               [MonoTODO]
+               public static long MonitoringSurvivedProcessMemorySize {
+                       get { throw new NotImplementedException (); }
+               }
+
+               [MonoTODO]
+               public long MonitoringTotalAllocatedMemorySize {
+                       get { throw new NotImplementedException (); }
+               }
+
+               [MonoTODO]
+               public TimeSpan MonitoringTotalProcessorTime {
+                       get { throw new NotImplementedException (); }
+               }
+#endif
        }
 }
index 45f2d81395e71911727671248a0e6dc022a6f5a2..bbf4e66b70efcf5423b6b65f7e3d038476ca168e 100644 (file)
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
+using System.Collections.Generic;
 using System.IO;
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
 using System.Security;
 using System.Runtime.Serialization.Formatters.Binary;
 
-#if(!NET_2_1 || MONOTOUCH)
+#if(!MOONLIGHT)
 using System.Runtime.Hosting;
 using System.Security.Policy;
 #endif
@@ -69,7 +70,7 @@ namespace System
                bool disallow_binding_redirects;
                bool disallow_code_downloads;
 
-#if (!NET_2_1 || MONOTOUCH)
+#if (!MOONLIGHT)
                private ActivationArguments _activationArguments;
                AppDomainInitializer domain_initializer;
                [NonSerialized]
@@ -116,7 +117,7 @@ namespace System
                        configuration_bytes = setup.configuration_bytes;
                }
 
-#if (!NET_2_1 || MONOTOUCH)
+#if (!MOONLIGHT)
                public AppDomainSetup (ActivationArguments activationArguments)
                {
                        _activationArguments = activationArguments;
@@ -162,7 +163,7 @@ namespace System
                                application_name = value;
                        }
                }
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public string CachePath {
                        get {
                                return cache_path;
@@ -235,7 +236,7 @@ namespace System
                                loader_optimization = value;
                        }
                }
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public string PrivateBinPath {
                        get {
                                return private_bin_path;
@@ -385,5 +386,11 @@ namespace System
                        serialized_non_primitives = ms.ToArray ();
                }
 #endif // !NET_2_1
+#if NET_4_0 || MOONLIGHT
+               [MonoTODO ("not implemented, does not throw because it's used in testing moonlight")]
+               public void SetCompatibilitySwitches (IEnumerable<string> switches)
+               {
+               }
+#endif
        }
 }
index cf17b9ec04a59070eec1b7b78048245ec21fa414..dc68d3baae0c3c25107171de1295abe91c5df22e 100644 (file)
@@ -2211,7 +2211,8 @@ namespace System
                {
                        if (array == null)
                                throw new ArgumentNullException ("array");
-                       return new ReadOnlyCollection<T> (new ArrayReadOnlyList<T> (array));
+
+                       return new ReadOnlyCollection<T> (array);
                }
 
                public static T Find<T> (T [] array, Predicate<T> match)
@@ -2253,88 +2254,5 @@ namespace System
                {
                        Copy (sourceArray, sourceIndex, destinationArray, destinationIndex, length);
                }
-
-               class ArrayReadOnlyList<T> : IList<T>
-               {
-                       T [] array;
-
-                       public ArrayReadOnlyList (T [] array)
-                       {
-                               this.array = array;
-                       }
-
-                       public T this [int index] {
-                               get {
-                                       if (unchecked ((uint) index) >= unchecked ((uint) array.Length))
-                                               throw new ArgumentOutOfRangeException ("index");
-                                       return array [index];
-                               }
-                               set { throw ReadOnlyError (); }
-                       }
-
-                       public int Count {
-                               get { return array.Length; }
-                       }
-
-                       public bool IsReadOnly {
-                               get { return true; }
-                       }
-
-                       public void Add (T item)
-                       {
-                               throw ReadOnlyError ();
-                       }
-
-                       public void Clear ()
-                       {
-                               throw ReadOnlyError ();
-                       }
-
-                       public bool Contains (T item)
-                       {
-                               return Array.IndexOf<T> (array, item) >= 0;
-                       }
-
-                       public void CopyTo (T [] array, int index)
-                       {
-                               this.array.CopyTo (array, index);
-                       }
-
-                       IEnumerator IEnumerable.GetEnumerator ()
-                       {
-                               return GetEnumerator ();
-                       }
-
-                       public IEnumerator<T> GetEnumerator ()
-                       {
-                               for (int i = 0; i < array.Length; i++)
-                                       yield return array [i];
-                       }
-
-                       public int IndexOf (T item)
-                       {
-                               return Array.IndexOf<T> (array, item);
-                       }
-
-                       public void Insert (int index, T item)
-                       {
-                               throw ReadOnlyError ();
-                       }
-
-                       public bool Remove (T item)
-                       {
-                               throw ReadOnlyError ();
-                       }
-
-                       public void RemoveAt (int index)
-                       {
-                               throw ReadOnlyError ();
-                       }
-
-                       static Exception ReadOnlyError ()
-                       {
-                               return new NotSupportedException ("This collection is read-only.");
-                       }
-               }
        }
 }
index b2c326eb421d62f65207400c528bc371edc893a4..dce79282db5075e7fe9a70cafd23fba2a98aad5a 100644 (file)
@@ -1,3 +1,251 @@
+2010-04-25  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpan.cs: Support custom formats in ToString().
+
+2010-04-23  Rolf Bjarne Kvinge  <RKvinge@novell.com>
+
+       * Lazy.cs: Include in Moonlight build.
+
+2010-04-22  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpan.cs: The final 4.0 release removed the restriction of
+       preceding zeroes when parsing, and it also added 't' and 'T' as valid
+       formats equivalent to 'c' (default).
+
+2010-04-16 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * MonoType.cs (GetInterface): Compare against the name
+       of the generic type definition.
+
+       Fixes #484246.
+
+2010-04-16 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * MonoCustomAttrs.cs (GetBasePropertyDefinition): Use
+       GetBaseMethod instead of GetMethodDefinition otherwise
+       we skip intermediate overloads.
+
+       Fixes #499569.
+
+2010-04-16  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * Environment.cs: Ensure elevated trust when calling
+       GetFolderPath on Moonlight
+
+2010-04-16  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * Action.cs: SL4 moved some Action in mscorlib
+       * Funcs.cs: SL4 moved some Func<> in mscorlib
+       * String.cs: Make IsNullOrWhiteSpace available, internally, 
+       before NET_4_0 (or SL4) since it's proving useful.
+
+2010-04-15  Jb Evain  <jbevain@novell.com>
+
+       * Guid.cs: rework the Guid parser to implement the net_4_0
+       [Try]ParseExact methods.
+
+2010-04-15  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * Tuple.cs:
+       * Tuples.cs: Add BOOTSTRAP_NET_4_0 define
+
+2010-04-13 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * MonoCustomAttrs.cs: Raise an exception if the runtime
+       returned a null cattr.
+
+2010-04-13  Zoltan Varga  <vargaz@gmail.com>
+
+       * Convert.cs (ToInt32): Do a checked cast. Fixes #596339.
+
+2010-04-12  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpan.cs: Implement support for custom formats parsing. This
+       should as well include the bits required to easily implement the same
+       for ToString methods, when the final release fixes the mess we found
+       in the latest beta.
+
+2010-04-08 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Type.cs: Add ResolveInternal virtual call that
+       resolves a given type to it's concrete type.
+
+2010-03-07 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Enum.cs (GetInfo): Don't use isinst tests as they can
+       return true for both signed and unsigned version of a
+       primitive type.
+
+       * Enum.cs (FindPosition): Ditto.
+
+2010-04-06  Marek Safar  <marek.safar@gmail.com>
+
+       * Array.cs: Don't make read-only collection read-only.
+
+2010-03-31  Miguel de Icaza  <miguel@novell.com>
+
+       * UInt32.cs, Int64.cs, UInt64.cs: cope with the case that the
+       IFormatProvider is not a NumberFormatInfo, preventing a crash.
+       This was already handled by Int32.cs, but these other routines
+       were never properly updated. 
+
+       Fixes #588356
+
+       * DateTimeOffset.cs: Add support for format K in DateTimeOffset,
+       fixes bug 589227.
+
+       * DateTime.cs: Add serialization support, fixes #588198.
+
+       Perhaps we should change the format as well since this is the new
+       format serialized anyways (see bug 592221, it saves 4 bytes of
+       memory as well)
+
+2010-03-30  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * InvalidTimeZoneException.cs
+       * TimeZoneNotFoundException.cs:
+               Fix Moonlight since these types now reside in mscorlib
+               (instead of System.Core) for NET_4_0 and also for SL4
+
+2010-03-30  Jb Evain  <jbevain@novell.com>
+
+       * MonoType.cs: let the binder reorder arguments when invoking
+       params methods.
+       * Activator.cs (CreateInstance): use BindToMethod instead of
+       SelectMethod to make sure that params constructors are properly called.
+
+       Fixes #591877
+
+2010-03-29  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpan.cs: Implement all the overloads of both TryParseExact and
+       ParseExact methods, by detecting the specific semantic changes in the
+       parse process, so we can properly re-utilize our new approach. This
+       included indicating our parser its culture sensitiveness, usage of colon as
+       day separator fallback or as a precise separator, and other minor bits.
+       We are only missing composite parsing right now.
+
+2010-03-29  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * AppDomainSetup.cs: Add new (FX4 and SL4) SetCompatibilitySwitches
+       method (empty is good enough for moonlight testing)
+       * Environment.cs: Expose MyVideos in Moonlight build
+
+2010-03-26  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpan.cs: We always give higher precedence to the first found
+       error, but for versions before 4.0 we need to give a higher one to
+       per-element overflow *specifically* (as opposed to int32 overflow,
+       which remains the same). This is not needed for 4.0, so report
+       per-element overflow as a normal error. 
+       This should fix a compatibility case, as well as simplifying the code.
+
+2010-03-25 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * MonoAsyncCall.cs: remove unused field.
+       * Delegate.cs: add new IsTransparentProxy property.
+       * MulticastDelegate.cs: add new HasSingleTarget property.
+       * Environment.cs: bump up corlib version.
+
+2010-03-25  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * AppDomain.cs: Add new properties that are in both FX4 and SL4
+       since Moonlight needs them (for testing purpose).
+       * Environment.cs: FailFast overloads are present in SL4 (and also
+       needed for testing Moonlight)
+
+2010-03-24  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * AppDomain.cs: Change default value from null to false for new
+       (NET_4_0 and SL4) IsCompatibilitySwitchSet. Not sure when (or even
+       if) it can return null (at least not when testing SL4 RC). 
+       Fix DRT198
+
+2010-03-22  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpan.cs: When parsing ticks, we used to only parse
+       the first 7 digits, and more than that would cause a FormatException -
+       starting in 4.0 we need to throw an OverflowException, however. Also,
+       for hours/minutes/seconds, two or more preceding zeroes will cause an
+       OverflowException as well.
+
+2010-03-22  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpan.cs: Create a new Parser.Execute method for 4.0 -and use the
+       previous impl for 2.0-, to handle the new semantics gracefully -
+       specifically the new 'dd:hh:mm:ss' format and related bits, instead of
+       of a ton of #ifdef blocks. Remove any 4.0 bits from the previous
+       version as well, to keep it clean.
+
+2010-03-19  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpan.cs: Move the error detection code to a separate method.
+       This way depending on the version we decide what error takes
+       precedence: OverlowException in 2.0, and FormatException in 4.0. This
+       also lets us keep the Execute() code cleaner and easier to understand.
+
+2010-03-18  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpan.cs: Put the error info in a single field, to make it easier
+       to preserve the very first error we get while parsing, and discard the
+       next ones. This will help us in a pair of cases where we were
+       overriding the previous error and reporting the wrong exception.
+
+2010-03-17  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * String.cs: SL4 includes new IsNullOrWhiteSpace and Concat/Join 
+       overloads.
+
+2010-03-17  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpan.cs: TimeSpan is actually implementing IFormattable.
+
+2010-03-17  Rolf Bjarne Kvinge  <RKvinge@novell.com>
+
+       * AppDomain.cs: Added MonoTODO for IsCompatibilitySwitchSet.
+
+2010-03-16  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpan.cs: In 4.0 the Parse/TryParse methods always try to use its
+       associated CultureInfo.NumberFormat.NumberDecimalSeparator value, as well as
+       providing backwards compatibility by also supporting '.' as the
+       separator.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * AppDomainSetup.cs
+       * Tuple.cs
+       * ChangeLog
+       * Exception.cs
+       * String.cs
+       * Console.cs
+       * Tuples.cs
+       * Activator.cs
+       * AppDomain.cs:
+               Use MOONLIGHT symbol to disambiguate MonoTouch and Moonlight code.
+
+2010-03-16  Rolf Bjarne Kvinge  <RKvinge@novell.com>
+
+       * Enum.cs: Added a few 4.0 api to Moonlight.
+
+2010-03-16  Rolf Bjarne Kvinge  <RKvinge@novell.com>
+
+       * AppDomain.cs: Added IsCompatibilitySwitchSet for .NET 4.0 and Moonlight.
+
+2010-03-15  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpan.cs: In 4.0 if the part parsed as days exceeds the allowed
+       range -this is, 23-, then it is processed as days instead - opposed to
+       2.0, where we are throwing an OverflowException.
+
+2010-03-15  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpan.cs: Make the colon parsing optional -and adjust the name to
+       reflect it-, so we can properly parse the case where we only have the
+       hours and minutes. This subtle bug was hidden before, since a string
+       such "10:12" would be parsed correctly, but "10:12  " (trailing white
+       space) was getting a FormatException.
+
 2010-03-12  Sebastien Pouliot  <sebastien@ximian.com>
 
        * Tuple.cs, Tuples.cs: Add them to NET_2_1 since they are parts
index f4221d7e46c6a05bda37e966effe86fa03fd447b..3da209a3d4f7d3abdeb42a77db361cc5a348421d 100644 (file)
@@ -38,7 +38,7 @@ namespace System
 {
        [Serializable]
        [ComVisible (true)]
-       public sealed class CharEnumerator : IEnumerator, ICloneable, IEnumerator <char>
+       public sealed class CharEnumerator : IEnumerator, ICloneable, IEnumerator<char>
        {
                private string str;
                private int index;
index c2d78fd01b346c95138834a5686901bb98717cab..ea9365e689fae20a2f144e5a859ac854217e1d35 100644 (file)
@@ -152,7 +152,7 @@ namespace System
 
                private static Stream Open (IntPtr handle, FileAccess access, int bufferSize)
                {
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        if (SecurityManager.SecurityEnabled && !Debugger.IsAttached && Environment.GetEnvironmentVariable ("MOONLIGHT_ENABLE_CONSOLE") == null)
                                return new NullStream ();
 #endif
index 85e860b225dbd62120c9b1701002fbd66ecd32a1..1575d803c9449aae72861805b0bd2ef79a6d02dc 100644 (file)
@@ -1207,7 +1207,9 @@ namespace System {
                                        "Value is greater than Int32.MaxValue or less than Int32.MinValue"));
          
                        // Returned Even-Rounded
-                       return (int)(Math.Round (value));         
+                       checked {
+                               return (int)(Math.Round (value));
+                       }
                }
  
                public static int ToInt32 (float value) 
@@ -1218,7 +1220,9 @@ namespace System {
          
                        // Returned Even-Rounded, pass as a double, could just call
                        // Convert.ToInt32 ( (double)value);
-                       return (int)(Math.Round ( (double)value));
+                       checked {
+                               return (int)(Math.Round ( (double)value));
+                       }
                }
 
                public static int ToInt32 (int value) 
index 96466e04e12ab3540f76086294dd483b7123dfe7..94c8a73a63577e7ab524aa04daeba40c501d7734 100644 (file)
@@ -34,6 +34,7 @@ using System.Globalization;
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
 using System.Text;
+using System.Runtime.Serialization;
 
 namespace System
 {
@@ -44,7 +45,7 @@ namespace System
        /// 
        [Serializable]
        [StructLayout (LayoutKind.Auto)]
-       public struct DateTime : IFormattable, IConvertible, IComparable, IComparable<DateTime>, IEquatable <DateTime>
+       public struct DateTime : IFormattable, IConvertible, IComparable, ISerializable, IComparable<DateTime>, IEquatable <DateTime>
        {
 #if MONOTOUCH
                static DateTime () {
@@ -353,8 +354,27 @@ namespace System
                {
                        CheckDateTimeKind (kind);
                        this.kind = kind;
-               }                       
+               }
 
+               //
+               // Not visible, but can be invoked during deserialization
+               //
+               DateTime (SerializationInfo info, StreamingContext context)
+               {
+                       if (info.HasKey ("dateData")){
+                               long dateData = info.GetInt64 ("dateData");
+                               kind = (DateTimeKind) (dateData >> 62);
+                               ticks = new TimeSpan (dateData & 0x3fffffffffffffff);
+                       } else if (info.HasKey ("ticks")){
+                               ticks = new TimeSpan (info.GetInt64 ("ticks"));
+                               kind = DateTimeKind.Unspecified;
+                       } else {
+                               kind = DateTimeKind.Unspecified;
+                               ticks = new TimeSpan (0);
+                       }
+               }
+               
+                             
                /* Properties  */
 
                public DateTime Date 
@@ -2144,5 +2164,15 @@ namespace System
                {
                        throw new InvalidCastException();
                }
+
+               void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
+               {
+                       long t = ticks.Ticks;
+                       info.AddValue ("ticks", t);
+
+                       // This is the new .NET format, encodes the kind on the top bits
+                       info.AddValue ("dateData", t | (((uint)kind) << 62));
+               }
+               
        }
 }
index 8c6b03596b6bd45bb802aec8f7dcc3c5593629b6..1ba389774dd0243dc870162eea82e089d4d02f6e 100644 (file)
@@ -518,12 +518,29 @@ namespace System
                                        } else
                                                ii += ParseNumber (input, ii, tokLen, true, allow_white_spaces, out year);
                                        break;
+
+                                       // The documentation is incorrect, they claim that K is the same as 'zz', but
+                                       // it actually allows the format to contain 4 digits for the offset
+                               case 'K':
+                                       tokLen = 1;
+                                       int off_h, off_m = 0, sign;
+                                       temp_int = 0;
+                                       ii += ParseEnum (input, ii, new string [] {"-", "+"}, allow_white_spaces, out sign);
+                                       ii += ParseNumber (input, ii, 4, false, false, out off_h);
+                                       if (off_h == -1 || off_m == -1 || sign == -1)
+                                               return false;
+
+                                       if (sign == 0)
+                                               sign = -1;
+                                       offset = new TimeSpan (sign * off_h, sign * off_m, 0);
+                                       break;
+                                       
                                case 'z':
                                        tokLen = DateTimeUtils.CountRepeat (format, fi, ch);
                                        if (offset != TimeSpan.MinValue || tokLen > 3)
                                                return false;
 
-                                       int off_h, off_m = 0, sign;
+                                       off_m = 0;
                                        temp_int = 0;
                                        ii += ParseEnum (input, ii, new string [] {"-", "+"}, allow_white_spaces, out sign);
                                        ii += ParseNumber (input, ii, 2, tokLen != 1, false, out off_h);
index 0108b42582f6ca00d3be46de7b5e43f62d0d3342..733eac9a4d3f132eab175fecdeed571364b4145f 100644 (file)
@@ -33,6 +33,7 @@
 //
 
 using System.Reflection;
+using System.Runtime.Remoting;
 using System.Runtime.Serialization;
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
@@ -521,5 +522,10 @@ namespace System
                {
                        return !(d1 == d2);
                }
+
+               internal bool IsTransparentProxy ()
+               {
+                       return RemotingServices.IsTransparentProxy (m_target);
+               }
        }
 }
index 8c050dce7afb4147c0b6b0889e22dd92db65e0a5..5015fa097a4639412d717bcefe3ea9aeaaab6436 100644 (file)
@@ -188,13 +188,14 @@ namespace System
                        get_enum_info (enumType, out info);
 
                        IComparer ic = null;
-                       if (info.values is int [])
+                       Type et = Enum.GetUnderlyingType (enumType);
+                       if (et == typeof (int))
                                ic = int_comparer;
-                       else if (info.values is short [])
+                       else if (et == typeof (short))
                                ic = short_comparer;
-                       else if (info.values is sbyte [])
+                       else if (et == typeof (sbyte))
                                ic = sbyte_comparer;
-                       else if (info.values is long [])
+                       else if (et == typeof (long))
                                ic = long_comparer;
                        
                        Array.Sort (info.values, info.names, ic);
@@ -347,42 +348,45 @@ namespace System
                //
                // It also tries to use the non-boxing version of the various Array.BinarySearch methods
                //
-               static int FindPosition (object value, Array values)
+               static int FindPosition (Type enumType, object value, Array values)
                {
-                       int[] int_array = values as int[];
-                       if (int_array != null)
-                               return Array.BinarySearch (int_array, (int)value, MonoEnumInfo.int_comparer);
+                       switch (Type.GetTypeCode (GetUnderlyingType (enumType))) {
+                       case TypeCode.SByte:
+                               sbyte [] sbyte_array = values as sbyte [];
+                               return Array.BinarySearch (sbyte_array, (sbyte) value,  MonoEnumInfo.sbyte_comparer);
 
-                       uint[] uint_array = values as uint [];
-                       if (uint_array != null)
-                               return Array.BinarySearch (uint_array, (uint)value);
-                       
-                       short [] short_array = values as short [];
-                       if (short_array != null)
+                       case TypeCode.Byte:
+                               byte [] byte_array = values as byte [];
+                               return Array.BinarySearch (byte_array, (byte) value);
+
+                       case TypeCode.Int16:
+                               short [] short_array = values as short [];
                                return Array.BinarySearch (short_array, (short)value, MonoEnumInfo.short_comparer);
 
-                       ushort [] ushort_array = values as ushort [];
-                       if (ushort_array != null)
+                       case TypeCode.UInt16:
+                               ushort [] ushort_array = values as ushort [];
                                return Array.BinarySearch (ushort_array, (ushort)value);
-                                       
-                       sbyte [] sbyte_array = values as sbyte [];
-                       if (sbyte_array != null)
-                               return Array.BinarySearch (sbyte_array, (sbyte) value,  MonoEnumInfo.sbyte_comparer);
-                       
-                       byte [] byte_array = values as byte [];
-                       if (byte_array != null)
-                               return Array.BinarySearch (byte_array, (byte) value);
+               
+                       case TypeCode.Int32:
+                               int[] int_array = values as int[];
+                               return Array.BinarySearch (int_array, (int)value, MonoEnumInfo.int_comparer);
+
+                       case TypeCode.UInt32:
+                               uint[] uint_array = values as uint [];
+                               return Array.BinarySearch (uint_array, (uint)value);                    
                        
-                       long [] long_array = values as long [];
-                       if (long_array != null)
+                       case TypeCode.Int64:
+                               long [] long_array = values as long [];
                                return Array.BinarySearch (long_array, (long) value,  MonoEnumInfo.long_comparer);
 
-                       ulong [] ulong_array = values as ulong [];
-                       if (ulong_array != null)
+                       case TypeCode.UInt64:
+                               ulong [] ulong_array = values as ulong [];
                                return Array.BinarySearch (ulong_array, (ulong) value);
 
-                       // This should never happen
-                       return Array.BinarySearch (values, value);
+                       default:
+                               // This should never happen
+                               return Array.BinarySearch (values, value);
+                       }
                }
        
                [ComVisible (true)]
@@ -400,7 +404,7 @@ namespace System
                        value = ToObject (enumType, value);
                        MonoEnumInfo.GetInfo (enumType, out info);
 
-                       int i = FindPosition (value, info.values);
+                       int i = FindPosition (enumType, value, info.values);
                        return (i >= 0) ? info.names [i] : null;
                }
 
@@ -425,7 +429,7 @@ namespace System
                                value = ToObject (enumType, value);
                                MonoEnumInfo.GetInfo (enumType, out info);
 
-                               return FindPosition (value, info.values) >= 0;
+                               return FindPosition (enumType, value, info.values) >= 0;
                        } else {
                                throw new ArgumentException("The value parameter is not the correct type."
                                        + "It must be type String or the same type as the underlying type"
@@ -615,7 +619,7 @@ namespace System
                        return true;
                }
 
-#if BOOTSTRAP_NET_4_0 || NET_4_0
+#if BOOTSTRAP_NET_4_0 || NET_4_0 || MOONLIGHT
                public static bool TryParse<TEnum> (string value, out TEnum result) where TEnum : struct
                {
                        return TryParse (value, false, out result);
@@ -1005,7 +1009,7 @@ namespace System
                        }
                        return retVal;
                }
-#if NET_4_0
+#if NET_4_0 || MOONLIGHT
                public bool HasFlag (Enum flag)
                {
                        ulong mvalue = Convert.ToUInt64 (get_value (), null);
index 0dc905db1f7c89dab08c53be67175d796f195ef2..91e02d48e58781e6b323b30f1a0728e30f38fe79 100644 (file)
@@ -55,7 +55,7 @@ namespace System {
                 * of icalls, do not require an increment.
                 */
 #pragma warning disable 169
-               private const int mono_corlib_version = 89;
+               private const int mono_corlib_version = 90;
 #pragma warning restore 169
 
                [ComVisible (true)]
@@ -84,8 +84,10 @@ namespace System {
                        ProgramFiles = 0x26,
                        MyPictures = 0x27,
                        CommonProgramFiles = 0x2b,
-#if NET_4_0
+#if NET_4_0 || MOONLIGHT
                        MyVideos = 0x0e,
+#endif
+#if NET_4_0
                        NetworkShortcuts = 0x13,
                        Fonts = 0x14,
                        CommonStartMenu = 0x16,
@@ -450,6 +452,8 @@ namespace System {
 #endif
                static string GetFolderPath(SpecialFolder folder, SpecialFolderOption option)
                {
+                       SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
+
                        string dir = null;
 
                        if (Environment.IsRunningOnWindows) {
@@ -701,20 +705,22 @@ namespace System {
 
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
                internal static extern void InternalSetEnvironmentVariable (string variable, string value);
-
+#endif
                [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode=true)]
                public static void FailFast (string message)
                {
                        throw new NotImplementedException ();
                }
-#endif
-#if NET_4_0
+
+#if NET_4_0 || MOONLIGHT
                [SecurityCritical]
                public static void FailFast (string message, Exception exception)
                {
                        throw new NotImplementedException ();
                }
+#endif
 
+#if NET_4_0
                public static bool Is64BitOperatingSystem {
                        get { return IntPtr.Size == 8; } // FIXME: is this good enough?
                }
index 0f0ea62ce9c905abe5245f7c37083d5eba61744c..b4a2f1ee665cf1c2faf13efd5797fdaf1548e158 100644 (file)
@@ -262,7 +262,7 @@ namespace System
                        info.AddValue ("RemoteStackTraceString", _remoteStackTraceString);
                        info.AddValue ("RemoteStackIndex", remote_stack_index);
                        info.AddValue ("HResult", hresult);
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                        info.AddValue ("Source", Source);
 #else
                        info.AddValue ("Source", null);
index ab5a960b4fb974dfa243ca8365dec2622f386566..2bb29f7c26295d69d1d8d7f95e3320c57f05cd21 100644 (file)
 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 //
 
-#if NET_4_0 || BOOTSTRAP_NET_4_0
-
 using System.Runtime.CompilerServices;
 
-namespace System
-{
+namespace System {
+
+#if NET_4_0 || BOOTSTRAP_NET_4_0
        [TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]     
        public delegate TResult Func<out TResult> ();
        
@@ -50,6 +49,17 @@ namespace System
        public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, out TResult> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
        public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, out TResult> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
        public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, out TResult> (T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
-}
+#elif MOONLIGHT
+       public delegate TResult Func<T1, T2, T3, T4, T5, TResult> (
+               T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
+
+       public delegate TResult Func<T1, T2, T3, T4, T5, T6, TResult> (
+               T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
 
+       public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, TResult> (
+               T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
+
+       public delegate TResult Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult> (
+               T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
 #endif
+}
index 6529a286a84013e5257695db0ac9c903c8a89981..14acb73c0a6d5aed96d6fbc0d8aba7a9d65d779b 100644 (file)
@@ -62,8 +62,16 @@ namespace System {
                private byte _j; //_node4;
                private byte _k; //_node5;
 
-               internal class GuidParser
-               {
+               enum Format {
+                       N, // 00000000000000000000000000000000
+                       D, // 00000000-0000-0000-0000-000000000000
+                       B, // {00000000-0000-0000-0000-000000000000}
+                       P, // (00000000-0000-0000-0000-000000000000)
+                       X, // {0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}
+               }
+
+               class GuidParser {
+
                        private string _src;
                        private int _length;
                        private int _cur;
@@ -74,175 +82,192 @@ namespace System {
                                Reset ();
                        }
 
-                       private void Reset ()
+                       void Reset ()
                        {
                                _cur = 0;
                                _length = _src.Length;
                        }
 
-                       private bool AtEnd ()
-                       {
-                               return _cur >= _length;
+                       bool Eof {
+                               get { return _cur >= _length; }
                        }
 
-                       private void ThrowFormatException ()
+                       static bool HasHyphen (Format format)
                        {
-                               throw new FormatException (Locale.GetText ("Invalid format for Guid.Guid(string)."));
+                               switch (format) {
+                               case Format.D:
+                               case Format.B:
+                               case Format.P:
+                                       return true;
+                               default:
+                                       return false;
+                               }
                        }
 
-                       private ulong ParseHex(int length, bool strictLength)
+                       bool TryParseNDBP (Format format, out Guid guid)
                        {
-                               ulong res = 0;
-                               int i;
-                               bool end = false;
-
-                               for (i=0; (!end) && i<length; ++i) {
-                                       if (AtEnd ()) {
-                                               if (strictLength || i==0) {
-                                                       ThrowFormatException ();
-                                               }
-                                               else {
-                                                       end = true;
-                                               }
-                                       }
-                                       else {
-                                               char c = Char.ToLowerInvariant (_src[_cur]);
-                                               if (Char.IsDigit (c)) {
-                                                       res = res * 16 + c - '0';
-                                                       _cur++;
-                                               }
-                                               else if (c >= 'a' && c <= 'f') {
-                                                       res = res * 16 + c - 'a' + 10;
-                                                       _cur++;
-                                               }
-                                               else {
-                                                       if (strictLength || i==0) {
-                                                               ThrowFormatException ();
-                                                       }
-                                                       else {
-                                                               end = true;
-                                                       }
-                                               }
-                                       }
+                               ulong a, b, c;
+                               guid = new Guid ();
+
+                               if (format == Format.B && !ParseChar ('{'))
+                                       return false;
+
+                               if (format == Format.P && !ParseChar ('('))
+                                       return false;
+
+                               if (!ParseHex (8, true, out a))
+                                       return false;
+
+                               var has_hyphen = HasHyphen (format);
+
+                               if (has_hyphen && !ParseChar ('-'))
+                                       return false;
+
+                               if (!ParseHex (4, true, out b))
+                                       return false;
+
+                               if (has_hyphen && !ParseChar ('-'))
+                                       return false;
+
+                               if (!ParseHex (4, true, out c))
+                                       return false;
+
+                               if (has_hyphen && !ParseChar ('-'))
+                                       return false;
+
+                               var d = new byte [8];
+                               for (int i = 0; i < d.Length; i++) {
+                                       ulong dd;
+                                       if (!ParseHex (2, true, out dd))
+                                               return false;
+
+                                       if (i == 1 && has_hyphen && !ParseChar ('-'))
+                                               return false;
+
+                                       d [i] = (byte) dd;
                                }
-                               return res;
+
+                               if (format == Format.B && !ParseChar ('}'))
+                                       return false;
+
+                               if (format == Format.P && !ParseChar (')'))
+                                       return false;
+
+                               guid = new Guid ((int) a, (short) b, (short) c, d);
+                               return true;
                        }
 
-                       private bool ParseOptChar (char c)
+                       bool TryParseX (out Guid guid)
                        {
-                               if (!AtEnd() && _src[_cur] == c) {
-                                       _cur++;
-                                       return true;
-                               }
-                               else {
+                               ulong a, b, c;
+                               guid = new Guid ();
+
+                               if (!(ParseChar ('{')
+                                       && ParseHexPrefix ()
+                                       && ParseHex (8, false, out a)
+                                       && ParseChar (',')
+                                       && ParseHexPrefix ()
+                                       && ParseHex (4, false, out b)
+                                       && ParseChar (',')
+                                       && ParseHexPrefix ()
+                                       && ParseHex (4, false, out c)
+                                       && ParseChar (',')
+                                       && ParseChar ('{'))) {
+
                                        return false;
                                }
-                       }
 
-                       private void ParseChar (char c)
-                       {
-                               bool b = ParseOptChar (c);
-                               if (!b) {
-                                       ThrowFormatException ();
+                               var d = new byte [8];
+                               for (int i = 0; i < d.Length; ++i) {
+                                       ulong dd;
+
+                                       if (!(ParseHexPrefix () && ParseHex (2, false, out dd)))
+                                               return false;
+
+                                       d [i] = (byte) dd;
+
+                                       if (i != 7 && !ParseChar (','))
+                                               return false;
                                }
+
+                               if (!(ParseChar ('}') && ParseChar ('}')))
+                                       return false;
+
+                               guid = new Guid ((int) a, (short) b, (short) c, d);
+                               return true;
                        }
 
-                       private Guid ParseGuid1 ()
+                       bool ParseHexPrefix ()
                        {
-                               bool openBrace; 
-                               bool groups = true;
-                               char endChar = '}';
-                               int a;
-                               short b;
-                               short c;
-                               byte[] d = new byte[8];
-                               int i;
-
-                               openBrace = ParseOptChar ('{');
-                               if (!openBrace) {
-                                       openBrace = ParseOptChar ('(');
-                                       if (openBrace) endChar = ')';
-                               }
-                               
-                               a = (int) ParseHex(8, true);
-                               
-                               if (openBrace) ParseChar('-');
-                               else groups = ParseOptChar('-');
-                               
-                               b = (short) ParseHex(4, true);
-                               if (groups) ParseChar('-');
-                               
-                               c = (short) ParseHex(4, true);
-                               if (groups) ParseChar('-');
-                               
-                               for (i=0; i<8; ++i) {
-                                       d[i] = (byte) ParseHex(2, true);
-                                       if (i == 1 && groups) {
-                                               ParseChar('-');
-                                       }       
-                               }
-       
-                               if (openBrace && !ParseOptChar(endChar)) {
-                                       ThrowFormatException ();
-                               }
-               
-                               return new Guid(a, b, c, d);
+                               if (!ParseChar ('0'))
+                                       return false;
+
+                               return ParseChar ('x');
                        }
 
-                       private void ParseHexPrefix ()
+                       bool ParseChar (char c)
                        {
-                               ParseChar ('0');
-                               ParseChar ('x');
+                               if (!Eof && _src [_cur] == c) {
+                                       _cur++;
+                                       return true;
+                               }
+
+                               return false;
                        }
 
-                       private Guid ParseGuid2 ()
+                       bool ParseHex (int length, bool strict, out ulong res)
                        {
-                               int a;
-                               short b;
-                               short c;
-                               byte[] d = new byte [8];
-                               int i;
-
-                               ParseChar ('{');
-                               ParseHexPrefix ();
-                               a = (int) ParseHex (8, false);
-                               ParseChar (',');
-                               ParseHexPrefix ();
-                               b = (short) ParseHex (4, false);
-                               ParseChar (',');
-                               ParseHexPrefix ();
-                               c = (short) ParseHex (4, false);
-                               ParseChar (',');
-                               ParseChar ('{');
-                               for (i=0; i<8; ++i) {
-                                       ParseHexPrefix ();
-                                       d[i] = (byte) ParseHex (2, false);
-                                       if (i != 7) {
-                                               ParseChar (',');
+                               res = 0;
+
+                               for (int i = 0; i < length; i++) {
+                                       if (Eof)
+                                               return !(strict && (i + 1 != length));
+
+                                       char c = Char.ToLowerInvariant (_src[_cur]);
+                                       if (Char.IsDigit (c)) {
+                                               res = res * 16 + c - '0';
+                                               _cur++;
+                                       } else if (c >= 'a' && c <= 'f') {
+                                               res = res * 16 + c - 'a' + 10;
+                                               _cur++;
+                                       } else {
+                                               if (!strict)
+                                                       return true;
+
+                                               return !(strict && (i + 1 != length));
                                        }
                                }
-                               ParseChar ('}');
-                               ParseChar ('}');
 
-                               return new Guid (a,b,c,d);
-                               
+                               return true;
                        }
 
-                       public Guid Parse ()
+                       public bool Parse (Format format, out Guid guid)
                        {
-                               Guid g;
+                               if (format == Format.X)
+                                       return TryParseX (out guid);
 
-                               try {
-                                       g  = ParseGuid1 ();
-                               }
-                               catch (FormatException) {
-                                       Reset ();
-                                       g = ParseGuid2 ();
-                               }
-                               if (!AtEnd () ) {
-                                       ThrowFormatException ();
-                               }
-                               return g;
+                               return TryParseNDBP (format, out guid);
+                       }
+
+                       public bool Parse (out Guid guid)
+                       {
+                               if (TryParseNDBP (Format.N, out guid))
+                                       return true;
+
+                               Reset ();
+                               if (TryParseNDBP (Format.D, out guid))
+                                       return true;
+
+                               Reset ();
+                               if (TryParseNDBP (Format.B, out guid))
+                                       return true;
+
+                               Reset ();
+                               if (TryParseNDBP (Format.P, out guid))
+                                       return true;
+
+                               Reset ();
+                               return TryParseX (out guid);
                        }
                }
 
@@ -286,12 +311,19 @@ namespace System {
                {
                        CheckNull (g);
                        g = g.Trim();
-                       GuidParser p = new GuidParser (g);
-                       Guid guid = p.Parse();
-       
+                       var parser = new GuidParser (g);
+                       Guid guid;
+                       if (!parser.Parse (out guid))
+                               throw CreateFormatException (g);
+
                        this = guid;
                }
 
+               static Exception CreateFormatException (string s)
+               {
+                       return new FormatException (string.Format ("Invalid Guid format: {0}", s));
+               }
+
                public Guid (int a, short b, short c, byte[] d)
                {
                        CheckArray (d, 8);
@@ -627,5 +659,66 @@ namespace System {
                {
                        return !( a.Equals (b) );
                }
+
+#if NET_4_0
+               public static Guid Parse (string input)
+               {
+                       Guid guid;
+                       if (!TryParse (input, out guid))
+                               throw CreateFormatException (input);
+
+                       return guid;
+               }
+
+               public static Guid ParseExact (string input, string format)
+               {
+                       Guid guid;
+                       if (!TryParseExact (input, format, out guid))
+                               throw CreateFormatException (input);
+
+                       return guid;
+               }
+
+               public static bool TryParse (string input, out Guid result)
+               {
+                       if (input == null)
+                               throw new ArgumentNullException ("input");
+
+                       var parser = new GuidParser (input);
+                       return parser.Parse (out result);
+               }
+
+               public static bool TryParseExact (string input, string format, out Guid result)
+               {
+                       if (input == null)
+                               throw new ArgumentNullException ("input");
+                       if (format == null)
+                               throw new ArgumentNullException ("format");
+
+                       var parser = new GuidParser (input);
+                       return parser.Parse (ParseFormat (format), out result);
+               }
+
+               static Format ParseFormat (string format)
+               {
+                       if (format.Length != 1)
+                               throw new ArgumentException ("Wrong format");
+
+                       switch (format [0]) {
+                       case 'N':
+                               return Format.N;
+                       case 'D':
+                               return Format.D;
+                       case 'B':
+                               return Format.B;
+                       case 'P':
+                               return Format.P;
+                       case 'X':
+                               return Format.X;
+                       }
+
+                       throw new ArgumentException ("Wrong format");
+               }
+#endif
        }
 }
index 5d8f908d8d832ea3bfe43ac89a40f35fc36862d5..bb06bae7a6431508ec23fbb88cc3afe517a6f3fb 100644 (file)
@@ -205,12 +205,12 @@ namespace System {
                                return false;
                        }
 
-                       NumberFormatInfo nfi;
+                       NumberFormatInfo nfi = null;
                        if (fp != null) {
                                Type typeNFI = typeof (System.Globalization.NumberFormatInfo);
                                nfi = (NumberFormatInfo) fp.GetFormat (typeNFI);
-                       }
-                       else
+                       } 
+                       if (nfi == null)
                                nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
 
                        if (!Int32.CheckStyle (style, tryParse, ref exc))
index 2dd461058cdc8f154f706c7d21ab928e76a222a0..d53141adff94ec8a75efee9b5dfd49467e709076 100644 (file)
  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  */
 
-#if NET_4_0 || BOOTSTRAP_NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0 || MOONLIGHT
 
 using System.Runtime.CompilerServices;
 
 namespace System
 {
        [Serializable]
-       [TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]     
+#if NET_4_0 || BOOTSTRAP_NET_4_0
+       [TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
+#elif MOONLIGHT
+       [TypeForwardedFrom (Consts.AssemblySystem_Core)]
+#endif
        public class InvalidTimeZoneException : Exception
        {
                public InvalidTimeZoneException () : base ()
index e825deb4e0134972f41dd4f527fb4f669f80d301..626bcf27541c015991f6c58974bd07a2646a712d 100644 (file)
@@ -27,7 +27,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if NET_4_0
+#if NET_4_0 || MOONLIGHT
 
 using System;
 using System.Runtime.Serialization;
index 5de35956f3ef5ca4e560a8a436bd7e97b441523f..14ac8d311a33685ceff66bc802778289d91599cb 100644 (file)
@@ -45,7 +45,6 @@ namespace System {
                object     state;
                object     res;
                object     out_args;
-               long       wait_event;
                #endregion
        }
 
index acaa63f4f4a3151be80a93f8783a973fc563bae1..0afe4a487cf5794a7df67b7ceaa249d27f06d35c 100644 (file)
@@ -139,6 +139,9 @@ namespace System
                        // shortcut
                        if (!inherit && res.Length == 1)
                        {
+                               if (res [0] == null)
+                                       throw new CustomAttributeFormatException ("Invalid custom attribute format");
+
                                if (attributeType != null)
                                {
                                        if (attributeType.IsAssignableFrom (res[0].GetType ()))
@@ -184,6 +187,8 @@ namespace System
                                foreach (object attr in res)
                                {
                                        AttributeUsageAttribute usage;
+                                       if (attr == null)
+                                               throw new CustomAttributeFormatException ("Invalid custom attribute format");
 
                                        Type attrType = attr.GetType ();
                                        if (attributeType != null)
@@ -327,7 +332,7 @@ namespace System
                        if (method == null || !method.IsVirtual)
                                return null;
 
-                       MethodInfo baseMethod = method.GetBaseDefinition ();
+                       MethodInfo baseMethod = method.GetBaseMethod ();
                        if (baseMethod != null && baseMethod != method) {
                                ParameterInfo[] parameters = property.GetIndexParameters ();
                                if (parameters != null && parameters.Length > 0) {
index d4a19182c9ef0394ff6cfe36e10c15557d922bc7..fe3bca9630b553fcffe19b47b5b6b7d64d126d1b 100644 (file)
@@ -182,9 +182,12 @@ namespace System
                        Type[] interfaces = GetInterfaces();
 
                        foreach (Type type in interfaces) {
-                               if (String.Compare (type.Name, name, ignoreCase, CultureInfo.InvariantCulture) == 0)
+                               /*We must compare against the generic type definition*/
+                               Type t = type.IsGenericType ? type.GetGenericTypeDefinition () : type;
+
+                               if (String.Compare (t.Name, name, ignoreCase, CultureInfo.InvariantCulture) == 0)
                                        return type;
-                               if (String.Compare (type.FullName, name, ignoreCase, CultureInfo.InvariantCulture) == 0)
+                               if (String.Compare (t.FullName, name, ignoreCase, CultureInfo.InvariantCulture) == 0)
                                        return type;
                        }
 
@@ -425,10 +428,6 @@ namespace System
                                                if (System.Reflection.Missing.Value == args [i] && (parameters [i].Attributes & ParameterAttributes.HasDefault) != ParameterAttributes.HasDefault)
                                                        throw new ArgumentException ("Used Missing.Value for argument without default value", "parameters");
                                        }
-                                       bool hasParamArray = parameters.Length > 0 ? Attribute.IsDefined (parameters [parameters.Length - 1], 
-                                               typeof (ParamArrayAttribute)) : false;
-                                       if (hasParamArray)
-                                               ReorderParamArrayArguments (ref args, m);
                                        object result = m.Invoke (target, invokeAttr, binder, args, culture);
                                        binder.ReorderArgumentArray (ref args, state);
                                        return result;
@@ -475,11 +474,6 @@ namespace System
                                if (m == null) {
                                        throwMissingFieldException = true;
                                } else {
-                                       ParameterInfo[] parameters = m.GetParameters();
-                                       bool hasParamArray = parameters.Length > 0 ? Attribute.IsDefined (parameters [parameters.Length - 1], 
-                                               typeof (ParamArrayAttribute)) : false;
-                                       if (hasParamArray)
-                                               ReorderParamArrayArguments (ref args, m);
                                        object result = m.Invoke (target, invokeAttr, binder, args, culture);
                                        binder.ReorderArgumentArray (ref args, state);
                                        return result;
@@ -503,11 +497,6 @@ namespace System
                                if (m == null) {
                                        throwMissingFieldException = true;
                                } else {
-                                       ParameterInfo[] parameters = m.GetParameters();
-                                       bool hasParamArray = parameters.Length > 0 ? Attribute.IsDefined (parameters [parameters.Length - 1], 
-                                               typeof (ParamArrayAttribute)) : false;
-                                       if (hasParamArray)
-                                               ReorderParamArrayArguments (ref args, m);
                                        object result = m.Invoke (target, invokeAttr, binder, args, culture);
                                        binder.ReorderArgumentArray (ref args, state);
                                        return result;
@@ -717,25 +706,6 @@ namespace System
 #endif
                }
 
-               void ReorderParamArrayArguments(ref object[] args, MethodBase method)
-               {
-                       ParameterInfo[] parameters = method.GetParameters();
-                       object[] newArgs = new object [parameters.Length];
-                       Array paramArray = Array.CreateInstance(parameters[parameters.Length - 1].ParameterType.GetElementType(), 
-                               args.Length - (parameters.Length - 1));
-                       int paramArrayCount = 0;
-                       for (int i = 0; i < args.Length; i++) {
-                               if (i < (parameters.Length - 1))
-                                       newArgs [i] = args [i];
-                               else {
-                                       paramArray.SetValue (args [i], paramArrayCount);
-                                       paramArrayCount ++;
-                               }
-                       }
-                       newArgs [parameters.Length - 1] = paramArray;
-                       args = newArgs;
-               }
-
 #if NET_4_0
                //seclevel { transparent = 0, safe-critical = 1, critical = 2}
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
index 85252bf5394035bcbcf21d5baa6d9650cbdc8035..df7becdea425ed5e4c8ae7e0deabf29e4f4ad6e8 100644 (file)
@@ -69,6 +69,9 @@ namespace System
                        return base.DynamicInvokeImpl (args);
                }
 
+               internal bool HasSingleTarget {
+                       get { return prev == null; }
+               }
                // <remarks>
                //   Equals: two multicast delegates are equal if their base is equal
                //   and their invocations list is equal.
index ff0a8d96e2a019b4e0e0c1d80eae518c05ff5f75..d425ff36292d689f884194dcf57369eb814ed84b 100644 (file)
@@ -1393,7 +1393,7 @@ namespace System
                        return (value == null) || (value.Length == 0);
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                public string Normalize ()
                {
                        return Normalization.Normalize (this, 0);
@@ -2393,68 +2393,66 @@ namespace System
                private static void ParseFormatSpecifier (string str, ref int ptr, out int n, out int width,
                                                          out bool left_align, out string format)
                {
+                       int max = str.Length;
+                       
                        // parses format specifier of form:
                        //   N,[\ +[-]M][:F]}
                        //
                        // where:
-
-                       try {
-                               // N = argument number (non-negative integer)
-
-                               n = ParseDecimal (str, ref ptr);
-                               if (n < 0)
-                                       throw new FormatException ("Input string was not in a correct format.");
-
-                               // M = width (non-negative integer)
-
-                               if (str[ptr] == ',') {
-                                       // White space between ',' and number or sign.
+                       // N = argument number (non-negative integer)
+                       
+                       n = ParseDecimal (str, ref ptr);
+                       if (n < 0)
+                               throw new FormatException ("Input string was not in a correct format.");
+                       
+                       // M = width (non-negative integer)
+                       
+                       if (ptr < max && str[ptr] == ',') {
+                               // White space between ',' and number or sign.
+                               ++ptr;
+                               while (ptr < max && Char.IsWhiteSpace (str [ptr]))
                                        ++ptr;
-                                       while (Char.IsWhiteSpace (str [ptr]))
-                                               ++ptr;
-                                       int start = ptr;
-
-                                       format = str.Substring (start, ptr - start);
-
-                                       left_align = (str [ptr] == '-');
-                                       if (left_align)
-                                               ++ ptr;
-
-                                       width = ParseDecimal (str, ref ptr);
-                                       if (width < 0)
-                                               throw new FormatException ("Input string was not in a correct format.");
-                               }
-                               else {
-                                       width = 0;
-                                       left_align = false;
-                                       format = String.Empty;
-                               }
-
-                               // F = argument format (string)
-
-                               if (str[ptr] == ':') {
-                                       int start = ++ ptr;
-                                       while (str[ptr] != '}')
-                                               ++ ptr;
-
-                                       format += str.Substring (start, ptr - start);
-                               }
-                               else
-                                       format = null;
-
-                               if (str[ptr ++] != '}')
+                               int start = ptr;
+                               
+                               format = str.Substring (start, ptr - start);
+                               
+                               left_align = (ptr < max && str [ptr] == '-');
+                               if (left_align)
+                                       ++ ptr;
+                               
+                               width = ParseDecimal (str, ref ptr);
+                               if (width < 0)
                                        throw new FormatException ("Input string was not in a correct format.");
                        }
-                       catch (IndexOutOfRangeException) {
-                               throw new FormatException ("Input string was not in a correct format.");
+                       else {
+                               width = 0;
+                               left_align = false;
+                               format = String.Empty;
                        }
+                       
+                       // F = argument format (string)
+                       
+                       if (ptr < max && str[ptr] == ':') {
+                               int start = ++ ptr;
+                               while (ptr < max && str[ptr] != '}')
+                                       ++ ptr;
+                               
+                               format += str.Substring (start, ptr - start);
+                       }
+                       else
+                               format = null;
+                       
+                       if ((ptr >= max) || str[ptr ++] != '}')
+                               throw new FormatException ("Input string was not in a correct format.");
                }
 
                private static int ParseDecimal (string str, ref int ptr)
                {
                        int p = ptr;
                        int n = 0;
-                       while (true) {
+                       int max = str.Length;
+                       
+                       while (p < max) {
                                char c = str[p];
                                if (c < '0' || '9' < c)
                                        break;
@@ -2463,7 +2461,7 @@ namespace System
                                ++ p;
                        }
 
-                       if (p == ptr)
+                       if (p == ptr || p == max)
                                return -1;
 
                        ptr = p;
@@ -2519,17 +2517,7 @@ namespace System
                        }
                }
 
-#if NET_4_0
-               public static bool IsNullOrWhiteSpace (string value)
-               {
-                       if (value == null)
-                               return true;
-                       foreach (char c in value)
-                               if (!Char.IsWhiteSpace (c))
-                                       return false;
-                       return true;
-               }
-
+#if MOONLIGHT || NET_4_0
                [ComVisible(false)]
                public static string Concat (IEnumerable<string> values)
                {
@@ -2611,7 +2599,20 @@ namespace System
 
                        return JoinUnchecked (separator, stringList.ToArray (), 0, stringList.Count);
                }
+
+               public static bool IsNullOrWhiteSpace (string value)
+#else
+               internal static bool IsNullOrWhiteSpace (string value)
 #endif
+               {
+                       if ((value == null) || (value.Length == 0))
+                               return true;
+                       foreach (char c in value)
+                               if (!Char.IsWhiteSpace (c))
+                                       return false;
+                       return true;
+               }
+
                internal unsafe int GetCaseInsensitiveHashCode ()
                {
                        fixed (char * c = this) {
index d0ab4c2f78c10837b5d0a402b7dc9fb5a01c9c97..60e8e7b0c9c3665a62bf42cd6a92ca9a5a55250f 100644 (file)
@@ -39,6 +39,9 @@ namespace System
        [Serializable]
        [System.Runtime.InteropServices.ComVisible (true)]
        public struct TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable <TimeSpan>
+#if NET_4_0
+                                , IFormattable
+#endif
        {
 #if MONOTOUCH
                static TimeSpan () {
@@ -378,6 +381,106 @@ namespace System
                        Parser p = new Parser (s, formatProvider);
                        return p.Execute (true, out result);
                }
+
+               public static TimeSpan ParseExact (string input, string format, IFormatProvider formatProvider)
+               {
+                       if (format == null)
+                               throw new ArgumentNullException ("format");
+
+                       return ParseExact (input, new string [] { format }, formatProvider, TimeSpanStyles.None);
+               }
+
+               public static TimeSpan ParseExact (string input, string format, IFormatProvider formatProvider, TimeSpanStyles styles)
+               {
+                       if (format == null)
+                               throw new ArgumentNullException ("format");
+
+                       return ParseExact (input, new string [] { format }, formatProvider, styles);
+               }
+
+               public static TimeSpan ParseExact (string input, string [] formats, IFormatProvider formatProvider)
+               {
+                       return ParseExact (input, formats, formatProvider, TimeSpanStyles.None);
+               }
+
+               public static TimeSpan ParseExact (string input, string [] formats, IFormatProvider formatProvider, TimeSpanStyles styles)
+               {
+                       if (input == null)
+                               throw new ArgumentNullException ("input");
+                       if (formats == null)
+                               throw new ArgumentNullException ("formats");
+
+                       // All the errors found during the parsing process are reported as FormatException.
+                       TimeSpan result;
+                       if (!TryParseExact (input, formats, formatProvider, styles, out result))
+                               throw new FormatException ("Invalid format.");
+
+                       return result;
+               }
+
+               public static bool TryParseExact (string input, string format, IFormatProvider formatProvider, out TimeSpan result)
+               {
+                       return TryParseExact (input, new string [] { format }, formatProvider, TimeSpanStyles.None, out result);
+               }
+
+               public static bool TryParseExact (string input, string format, IFormatProvider formatProvider, TimeSpanStyles styles,
+                               out TimeSpan result)
+               {
+                       return TryParseExact (input, new string [] { format }, formatProvider, styles, out result);
+               }
+
+               public static bool TryParseExact (string input, string [] formats, IFormatProvider formatProvider, out TimeSpan result)
+               {
+                       return TryParseExact (input, formats, formatProvider, TimeSpanStyles.None, out result);
+               }
+
+               public static bool TryParseExact (string input, string [] formats, IFormatProvider formatProvider, TimeSpanStyles styles,
+                       out TimeSpan result)
+               {
+                       result = TimeSpan.Zero;
+
+                       if (formats == null || formats.Length == 0)
+                               return false;
+
+                       Parser p = new Parser (input, formatProvider);
+                       p.Exact = true;
+
+                       foreach (string format in formats) {
+                               if (format == null || format.Length == 0)
+                                       return false; // wrong format, return immediately.
+
+                               switch (format) {
+                                       case "g":
+                                               p.AllMembersRequired = false;
+                                               p.CultureSensitive = true;
+                                               p.UseColonAsDaySeparator = true;
+                                               break;
+                                       case "G":
+                                               p.AllMembersRequired = true;
+                                               p.CultureSensitive = true;
+                                               p.UseColonAsDaySeparator = true;
+                                               break;
+                                       case "c":
+                                               p.AllMembersRequired = false;
+                                               p.CultureSensitive = false;
+                                               p.UseColonAsDaySeparator = false;
+                                               break;
+                                       default:
+                                               // Single letter formats other than the defined ones are not accepted.
+                                               if (format.Length == 1)
+                                                       return false;
+                                               // custom format
+                                               if (p.ExecuteWithFormat (format, styles, true, out result))
+                                                       return true;
+                                               continue;
+                               }
+
+                               if (p.Execute (true, out result))
+                                       return true;
+                       }
+
+                       return false;
+               }
 #endif
 
                public TimeSpan Subtract (TimeSpan ts)
@@ -431,11 +534,12 @@ namespace System
 
                public string ToString (string format, IFormatProvider formatProvider)
                {
-                       if (format == null || format.Length == 0 || format == "c") // Default version
+                       if (format == null || format.Length == 0 || format == "c" ||
+                                       format == "t" || format == "T") // Default version
                                return ToString ();
 
                        if (format != "g" && format != "G")
-                               throw new FormatException ("The format is not recognized.");
+                               return ToStringCustom (format); // custom formats ignore culture/formatProvider
 
                        NumberFormatInfo number_info = null;
                        if (formatProvider != null)
@@ -489,6 +593,67 @@ namespace System
 
                        return sb.ToString ();
                }
+
+               string ToStringCustom (string format)
+               {
+                       // Single char formats are not accepted.
+                       if (format.Length < 2)
+                               throw new FormatException ("The format is not recognized.");
+
+                       FormatParser parser = new FormatParser (format);
+                       FormatElement element;
+                       int value;
+
+                       StringBuilder sb = new StringBuilder (format.Length + 1);
+
+                       for (;;) {
+                               if (parser.AtEnd)
+                                       break;
+
+                               element = parser.GetNextElement ();
+                               switch (element.Type) {
+                                       case FormatElementType.Days:
+                                               value = Math.Abs (Days);
+                                               sb.Append (value.ToString ("D" + element.IntValue));
+                                               break;
+                                       case FormatElementType.Hours:
+                                               value = Math.Abs (Hours);
+                                               sb.Append (value.ToString ("D" + element.IntValue));
+                                               break;
+                                       case FormatElementType.Minutes:
+                                               value = Math.Abs (Minutes);
+                                               sb.Append (value.ToString ("D" + element.IntValue));
+                                               break;
+                                       case FormatElementType.Seconds:
+                                               value = Math.Abs (Seconds);
+                                               sb.Append (value.ToString ("D" + element.IntValue));
+                                               break;
+                                       case FormatElementType.Ticks:
+                                               value = Math.Abs (Milliseconds);
+                                               sb.Append (value.ToString ("D" + element.IntValue));
+                                               break;
+                                       case FormatElementType.TicksUppercase:
+                                               value = Math.Abs (Milliseconds);
+                                               if (value > 0) {
+                                                       int threshold = (int)Math.Pow (10, element.IntValue);
+                                                       while (value >= threshold)
+                                                               value /= 10;
+                                                       sb.Append (value.ToString ());
+                                               }
+                                               break;
+                                       case FormatElementType.EscapedChar:
+                                               sb.Append (element.CharValue);
+                                               break;
+                                       case FormatElementType.Literal:
+                                               sb.Append (element.StringValue);
+                                               break;
+                                       default:
+                                               throw new FormatException ("The format is not recognized.");
+                               }
+                       }
+
+                       return sb.ToString ();
+               }
 #endif
 
                public static TimeSpan operator + (TimeSpan t1, TimeSpan t2)
@@ -541,23 +706,49 @@ namespace System
                        return t;
                }
 
+               enum ParseError {
+                       None,
+                       Format,
+                       Overflow
+               }
+
                // Class Parser implements parser for TimeSpan.Parse
                private class Parser
                {
                        private string _src;
                        private int _cur = 0;
                        private int _length;
-                       private bool formatError;
-                       private bool overflowError;
+                       ParseError parse_error;
+#if NET_4_0
+                       bool parsed_ticks;
+                       NumberFormatInfo number_format;
+                       int parsed_numbers_count;
+                       bool parsed_days_separator;
+
+                       public bool Exact; // no fallback, strict pattern.
+                       public bool AllMembersRequired;
+                       public bool CultureSensitive = true;
+                       public bool UseColonAsDaySeparator = true;
+#endif
 
                        public Parser (string src)
                        {
                                _src = src;
                                _length = _src.Length;
+#if NET_4_0
+                               number_format = GetNumberFormatInfo (null);
+#endif
                        }
 
 #if NET_4_0
-                       NumberFormatInfo number_format;
+                       // Reset state data, so we can execute another parse over the input.
+                       void Reset ()
+                       {
+                               _cur = 0;
+                               parse_error = ParseError.None;
+                               parsed_ticks = parsed_days_separator = false;
+                               parsed_numbers_count = 0;
+                       }
 
                        public Parser (string src, IFormatProvider formatProvider) :
                                this (src)
@@ -615,6 +806,34 @@ namespace System
                                return res;
                        }
 
+#if NET_4_0
+                       // Used for custom formats parsing, where we may need to declare how
+                       // many digits we expect, as well as the maximum allowed.
+                       private int ParseIntExact (int digit_count, int max_digit_count)
+                       {
+                               long res = 0;
+                               int count = 0;
+
+                               // We can have more than one preceding zero here.
+                               while (!AtEnd && Char.IsDigit (_src, _cur)) {
+                                       res = res * 10 + _src [_cur] - '0';
+                                       if (res > Int32.MaxValue) {
+                                               SetParseError (ParseError.Format);
+                                               break;
+                                       }
+                                       _cur++;
+                                       count++;
+                               }
+
+                               // digit_count = 1 means we can use up to maximum count,
+                               if (count == 0 || (digit_count > 1 && digit_count != count) ||
+                                               count > max_digit_count)
+                                       SetParseError (ParseError.Format);
+
+                               return (int)res;
+                       }
+#endif
+
                        // Parse simple int value
                        private int ParseInt (bool optional)
                        {
@@ -627,7 +846,7 @@ namespace System
                                while (!AtEnd && Char.IsDigit (_src, _cur)) {
                                        res = res * 10 + _src[_cur] - '0';
                                        if (res > Int32.MaxValue) {
-                                               overflowError = true;
+                                               SetParseError (ParseError.Overflow);
                                                break;
                                        }
                                        _cur++;
@@ -635,7 +854,11 @@ namespace System
                                }
 
                                if (!optional && (count == 0))
-                                       formatError = true;
+                                       SetParseError (ParseError.Format);
+#if NET_4_0
+                               if (count > 0)
+                                       parsed_numbers_count++;
+#endif
 
                                return (int)res;
                        }
@@ -654,22 +877,57 @@ namespace System
                        }       
 
 #if NET_4_0
+                       // This behaves pretty much like ParseOptDot, but we need to have it
+                       // as a separated routine for both days and decimal separators.
+                       private bool ParseOptDaysSeparator ()
+                       {
+                               if (AtEnd)
+                                       return false;
+
+                               if (_src[_cur] == '.') {
+                                       _cur++;
+                                       parsed_days_separator = true;
+                                       return true;
+                               }
+                               return false;
+                       }
+
                        // Just as ParseOptDot, but for decimal separator
                        private bool ParseOptDecimalSeparator ()
                        {
                                if (AtEnd)
                                        return false;
 
-                               // Use culture information if available.
-                               if (number_format != null) {
-                                       string decimal_separator = number_format.NumberDecimalSeparator;
-                                       if (String.Compare (_src, _cur, decimal_separator, 0, decimal_separator.Length) == 0) {
-                                               _cur += decimal_separator.Length;
+                               // we may need to provide compatibility with old versions using '.'
+                               // for culture insensitve and non exact formats.
+                               if (!Exact || !CultureSensitive)
+                                       if (_src [_cur] == '.') {
+                                               _cur++;
                                                return true;
                                        }
 
-                                       return false;
-                               } else if (_src [_cur] == '.') {
+                               string decimal_separator = number_format.NumberDecimalSeparator;
+                               if (CultureSensitive && String.Compare (_src, _cur, decimal_separator, 0, decimal_separator.Length) == 0) {
+                                       _cur += decimal_separator.Length;
+                                       return true;
+                               }
+
+                               return false;
+                       }
+
+                       private bool ParseLiteral (string value)
+                       {
+                               if (!AtEnd && String.Compare (_src, _cur, value, 0, value.Length) == 0) {
+                                       _cur += value.Length;
+                                       return true;
+                               }
+
+                               return false;
+                       }
+
+                       private bool ParseChar (char c)
+                       {
+                               if (!AtEnd && _src [_cur] == c) {
                                        _cur++;
                                        return true;
                                }
@@ -678,18 +936,18 @@ namespace System
                        }
 #endif
 
-                       // Parse optional (LAMESPEC) colon
-                       private void ParseOptColon ()
+                       private void ParseColon (bool optional)
                        {
                                if (!AtEnd) {
                                        if (_src[_cur] == ':')
                                                _cur++;
-                                       else 
-                                               formatError = true;
+                                       else if (!optional)
+                                               SetParseError (ParseError.Format);
                                }
                        }
 
                        // Parse [1..7] digits, representing fractional seconds (ticks)
+                       // In 4.0 more than 7 digits will cause an OverflowException
                        private long ParseTicks ()
                        {
                                long mag = 1000000;
@@ -704,11 +962,195 @@ namespace System
                                }
 
                                if (!digitseen)
-                                       formatError = true;
+                                       SetParseError (ParseError.Format);
+#if NET_4_0
+                               else if (!AtEnd && Char.IsDigit (_src, _cur))
+                                       SetParseError (ParseError.Overflow);
+
+                               parsed_ticks = true;
+#endif
+
+                               return res;
+                       }
+
+#if NET_4_0
+                       // Used by custom formats parsing
+                       // digits_count = 0 for digits up to max_digits_count (optional), and other value to
+                       // force a precise number of digits.
+                       private long ParseTicksExact (int digits_count, int max_digits_count)
+                       {
+                               long mag = 1000000;
+                               long res = 0;
+                               int count = 0;
+
+                               while (mag > 0 && !AtEnd && Char.IsDigit (_src, _cur)) {
+                                       res = res + (_src [_cur] - '0') * mag;
+                                       _cur++;
+                                       count++;
+                                       mag = mag / 10;
+                               }
+
+                               if ((digits_count > 0 && count != digits_count) ||
+                                               count > max_digits_count)
+                                       SetParseError (ParseError.Format);
 
                                return res;
                        }
+#endif
+
+                       void SetParseError (ParseError error)
+                       {
+                               // We preserve the very first error.
+                               if (parse_error != ParseError.None)
+                                       return;
+
+                               parse_error = error;
+                       }
+
+#if NET_4_0
+                       bool CheckParseSuccess (bool tryParse)
+#else
+                       bool CheckParseSuccess (int hours, int minutes, int seconds, bool tryParse)
+#endif
+                       {
+                               // We always report the first error, but for 2.0 we need to give a higher
+                               // precence to per-element overflow (as opposed to int32 overflow).
+#if NET_4_0
+                               if (parse_error == ParseError.Overflow) {
+#else
+                               if (parse_error == ParseError.Overflow || hours > 23 || minutes > 59 || seconds > 59) {
+#endif
+                                       if (tryParse)
+                                               return false;
+                                       throw new OverflowException (
+                                               Locale.GetText ("Invalid time data."));
+                               }
 
+                               if (parse_error == ParseError.Format) {
+                                       if (tryParse)
+                                               return false;
+                                       throw new FormatException (
+                                               Locale.GetText ("Invalid format for TimeSpan.Parse."));
+                               }
+
+                               return true;
+                       }
+
+#if NET_4_0
+                       // We are using a different parse approach in 4.0, due to some changes in the behaviour
+                       // of the parse routines.
+                       // The input string is documented as:
+                       //      Parse [ws][-][dd.]hh:mm:ss[.ff][ws]
+                       //
+                       // There are some special cases as part of 4.0, however:
+                       // 1. ':' *can* be used as days separator, instead of '.', making valid the format 'dd:hh:mm:ss'
+                       // 2. A input in the format 'hh:mm:ss' will end up assigned as 'dd.hh:mm' if the first int has a value
+                       // exceeding the valid range for hours: 0-23.
+                       // 3. The decimal separator can be retrieved from the current culture, as well as keeping support
+                       // for the '.' value as part of keeping compatibility.
+                       //
+                       // So we take the approach to parse, if possible, 4 integers, and depending on both how many were
+                       // actually parsed and what separators were read, assign the values to days/hours/minutes/seconds.
+                       //
+                       public bool Execute (bool tryParse, out TimeSpan result)
+                       {
+                               bool sign;
+                               int value1, value2, value3, value4;
+                               int days, hours, minutes, seconds;
+                               long ticks = 0;
+
+                               result = TimeSpan.Zero;
+                               value1 = value2 = value3 = value4 = 0;
+                               days = hours = minutes = seconds = 0;
+
+                               Reset ();
+
+                               ParseWhiteSpace ();
+                               sign = ParseSign ();
+
+                               // Parse 4 integers, making only the first one non-optional.
+                               value1 = ParseInt (false);
+                               if (!ParseOptDaysSeparator ()) // Parse either day separator or colon
+                                       ParseColon (false);
+                               value2 = ParseInt (true);
+                               ParseColon (true);
+                               value3 = ParseInt (true);
+                               ParseColon (true);
+                               value4 = ParseInt (true);
+
+                               // We know the precise separator for ticks, so there's no need to guess.
+                               if (ParseOptDecimalSeparator ())
+                                       ticks = ParseTicks ();
+
+                               ParseWhiteSpace ();
+
+                               if (!AtEnd)
+                                       SetParseError (ParseError.Format);
+
+                               if (Exact)
+                                       // In Exact mode we cannot allow both ':' and '.' as day separator.
+                                       if (UseColonAsDaySeparator && parsed_days_separator ||
+                                               AllMembersRequired && (parsed_numbers_count < 4 || !parsed_ticks))
+                                               SetParseError (ParseError.Format);
+
+                               switch (parsed_numbers_count) {
+                                       case 1:
+                                               days = value1;
+                                               break;
+                                       case 2: // Two elements are valid only if they are *exactly* in the format: 'hh:mm'
+                                               if (parsed_days_separator)
+                                                       SetParseError (ParseError.Format);
+                                               else {
+                                                       hours = value1;
+                                                       minutes = value2;
+                                               }
+                                               break;
+                                       case 3: // Assign the first value to days if we parsed a day separator or the value
+                                               // is not in the valid range for hours.
+                                               if (parsed_days_separator || value1 > 23) {
+                                                       days = value1;
+                                                       hours = value2;
+                                                       minutes = value3;
+                                               } else {
+                                                       hours = value1;
+                                                       minutes = value2;
+                                                       seconds = value3;
+                                               }
+                                               break;
+                                       case 4: // We are either on 'dd.hh:mm:ss' or 'dd:hh:mm:ss'
+                                               if (!UseColonAsDaySeparator && !parsed_days_separator)
+                                                       SetParseError (ParseError.Format);
+                                               else {
+                                                       days = value1;
+                                                       hours = value2;
+                                                       minutes = value3;
+                                                       seconds = value4;
+                                               }
+                                               break;
+                               }
+
+                               if (hours > 23 || minutes > 59 || seconds > 59)
+                                       SetParseError (ParseError.Overflow);
+
+                               if (!CheckParseSuccess (tryParse))
+                                       return false;
+
+                               long t;
+                               if (!TimeSpan.CalculateTicks (days, hours, minutes, seconds, 0, false, out t))
+                                       return false;
+
+                               try {
+                                       t = checked ((sign) ? (-t - ticks) : (t + ticks));
+                               } catch (OverflowException) {
+                                       if (tryParse)
+                                               return false;
+                                       throw;
+                               }
+
+                               result = new TimeSpan (t);
+                               return true;
+                       }
+#else
                        public bool Execute (bool tryParse, out TimeSpan result)
                        {
                                bool sign;
@@ -734,15 +1176,12 @@ namespace System
                                        hours = days;
                                        days = 0;
                                }
-                               ParseOptColon();
+                               ParseColon(false);
                                minutes = ParseInt (true);
-                               ParseOptColon ();
+                               ParseColon (true);
                                seconds = ParseInt (true);
-#if NET_4_0
-                               if ( ParseOptDecimalSeparator () ) {
-#else
+
                                if ( ParseOptDot () ) {
-#endif
                                        ticks = ParseTicks ();
                                }
                                else {
@@ -751,28 +1190,124 @@ namespace System
                                ParseWhiteSpace ();
        
                                if (!AtEnd)
-                                       formatError = true;
+                                       SetParseError (ParseError.Format);
+
+                               if (!CheckParseSuccess (hours, minutes, seconds, tryParse))
+                                       return false;
+
+                               long t;
+                               if (!TimeSpan.CalculateTicks (days, hours, minutes, seconds, 0, false, out t))
+                                       return false;
 
-                               // Overflow has presceance over FormatException
-                               if (overflowError || hours > 23 || minutes > 59 || seconds > 59) {
+                               try {
+                                       t = checked ((sign) ? (-t - ticks) : (t + ticks));
+                               } catch (OverflowException) {
                                        if (tryParse)
                                                return false;
-                                       throw new OverflowException (
-                                               Locale.GetText ("Invalid time data."));
+                                       throw;
                                }
-                               else if (formatError) {
-                                       if (tryParse)
-                                               return false;
-                                       throw new FormatException (
-                                               Locale.GetText ("Invalid format for TimeSpan.Parse."));
+
+                               result = new TimeSpan (t);
+                               return true;
+                       }
+#endif
+
+#if NET_4_0
+                       public bool ExecuteWithFormat (string format, TimeSpanStyles style, bool tryParse, out TimeSpan result)
+                       {
+                               int days, hours, minutes, seconds;
+                               long ticks;
+                               FormatElement format_element;
+
+                               days = hours = minutes = seconds = -1;
+                               ticks = -1;
+                               result = TimeSpan.Zero;
+                               Reset ();
+
+                               FormatParser format_parser = new FormatParser (format);
+
+                               for (;;) {
+                                       // We need to continue even if AtEnd == true, since we could have
+                                       // a optional second element.
+                                       if (parse_error != ParseError.None)
+                                               break;
+                                       if (format_parser.AtEnd)
+                                               break;
+
+                                       format_element = format_parser.GetNextElement ();
+                                       switch (format_element.Type) {
+                                               case FormatElementType.Days:
+                                                       if (days != -1)
+                                                               goto case FormatElementType.Error;
+                                                       days = ParseIntExact (format_element.IntValue, 8);
+                                                       break;
+                                               case FormatElementType.Hours:
+                                                       if (hours != -1)
+                                                               goto case FormatElementType.Error;
+                                                       hours = ParseIntExact (format_element.IntValue, 2);
+                                                       break;
+                                               case FormatElementType.Minutes:
+                                                       if (minutes != -1)
+                                                               goto case FormatElementType.Error;
+                                                       minutes = ParseIntExact (format_element.IntValue, 2);
+                                                       break;
+                                               case FormatElementType.Seconds:
+                                                       if (seconds != -1)
+                                                               goto case FormatElementType.Error;
+                                                       seconds = ParseIntExact (format_element.IntValue, 2);
+                                                       break;
+                                               case FormatElementType.Ticks:
+                                                       if (ticks != -1)
+                                                               goto case FormatElementType.Error;
+                                                       ticks = ParseTicksExact (format_element.IntValue,
+                                                                       format_element.IntValue);
+                                                       break;
+                                               case FormatElementType.TicksUppercase:
+                                                       // Similar to Milliseconds, but optional and the
+                                                       // number of F defines the max length, not the required one.
+                                                       if (ticks != -1)
+                                                               goto case FormatElementType.Error;
+                                                       ticks = ParseTicksExact (0, format_element.IntValue);
+                                                       break;
+                                               case FormatElementType.Literal:
+                                                       if (!ParseLiteral (format_element.StringValue))
+                                                               SetParseError (ParseError.Format);
+                                                       break;
+                                               case FormatElementType.EscapedChar:
+                                                       if (!ParseChar (format_element.CharValue))
+                                                               SetParseError (ParseError.Format);
+                                                       break;
+                                               case FormatElementType.Error:
+                                                       SetParseError (ParseError.Format);
+                                                       break;
+                                       }
                                }
 
+                               if (days == -1)
+                                       days = 0;
+                               if (hours == -1)
+                                       hours = 0;
+                               if (minutes == -1)
+                                       minutes = 0;
+                               if (seconds == -1)
+                                       seconds = 0;
+                               if (ticks == -1)
+                                       ticks = 0;
+
+                               if (!AtEnd || !format_parser.AtEnd)
+                                       SetParseError (ParseError.Format);
+                               if (hours > 23 || minutes > 59 || seconds > 59)
+                                       SetParseError (ParseError.Format);
+
+                               if (!CheckParseSuccess (tryParse))
+                                       return false;
+
                                long t;
                                if (!TimeSpan.CalculateTicks (days, hours, minutes, seconds, 0, false, out t))
                                        return false;
 
                                try {
-                                       t = checked ((sign) ? (-t - ticks) : (t + ticks));
+                                       t = checked ((style == TimeSpanStyles.AssumeNegative) ? (-t - ticks) : (t + ticks));
                                } catch (OverflowException) {
                                        if (tryParse)
                                                return false;
@@ -782,6 +1317,192 @@ namespace System
                                result = new TimeSpan (t);
                                return true;
                        }
+#endif
+               }
+#if NET_4_0
+               enum FormatElementType 
+               {
+                       Days,
+                       Hours,
+                       Minutes,
+                       Seconds,
+                       Ticks, // 'f'
+                       TicksUppercase, // 'F'
+                       Literal,
+                       EscapedChar,
+                       Error,
+                       End
+               }
+
+               struct FormatElement
+               {
+                       public FormatElement (FormatElementType type)
+                       {
+                               Type = type;
+                               CharValue = (char)0;
+                               IntValue = 0;
+                               StringValue = null;
+                       }
+
+                       public FormatElementType Type;
+                       public char CharValue; // Used by EscapedChar
+                       public string StringValue; // Used by Literal
+                       public int IntValue; // Used by numerical elements.
+               }
+
+               class FormatParser 
+               {
+                       int cur;
+                       string format;
+
+                       public FormatParser (string format)
+                       {
+                               this.format = format;
+                       }
+
+                       public bool AtEnd {
+                               get {
+                                       return cur >= format.Length;
+                               }
+                       }
+
+                       public FormatElement GetNextElement ()
+                       {
+                               FormatElement element = new FormatElement ();
+
+                               if (AtEnd)
+                                       return new FormatElement (FormatElementType.End);
+
+                               int count = 0;
+                               switch (format [cur]) {
+                                       case 'd':
+                                               count = ParseChar ('d');
+                                               if (count > 8)
+                                                       return new FormatElement (FormatElementType.Error);
+                                               element.Type = FormatElementType.Days;
+                                               element.IntValue = count;
+                                               break;
+                                       case 'h':
+                                               count = ParseChar ('h');
+                                               if (count > 2)
+                                                       return new FormatElement (FormatElementType.Error);
+                                               element.Type = FormatElementType.Hours;
+                                               element.IntValue = count;
+                                               break;
+                                       case 'm':
+                                               count = ParseChar ('m');
+                                               if (count > 2)
+                                                       return new FormatElement (FormatElementType.Error);
+                                               element.Type = FormatElementType.Minutes;
+                                               element.IntValue = count;
+                                               break;
+                                       case 's':
+                                               count = ParseChar ('s');
+                                               if (count > 2)
+                                                       return new FormatElement (FormatElementType.Error);
+                                               element.Type = FormatElementType.Seconds;
+                                               element.IntValue = count;
+                                               break;
+                                       case 'f':
+                                               count = ParseChar ('f');
+                                               if (count > 7)
+                                                       return new FormatElement (FormatElementType.Error);
+                                               element.Type = FormatElementType.Ticks;
+                                               element.IntValue = count;
+                                               break;
+                                       case 'F':
+                                               count = ParseChar ('F');
+                                               if (count > 7)
+                                                       return new FormatElement (FormatElementType.Error);
+                                               element.Type = FormatElementType.TicksUppercase;
+                                               element.IntValue = count;
+                                               break;
+                                       case '%':
+                                               cur++;
+                                               if (AtEnd)
+                                                       return new FormatElement (FormatElementType.Error);
+                                               if (format [cur] == 'd')
+                                                       goto case 'd';
+                                               else if (format [cur] == 'h')
+                                                       goto case 'h';
+                                               else if (format [cur] == 'm')
+                                                       goto case 'm';
+                                               else if (format [cur] == 's')
+                                                       goto case 's';
+                                               else if (format [cur] == 'f')
+                                                       goto case 'f';
+                                               else if (format [cur] == 'F')
+                                                       goto case 'F';
+
+                                               return new FormatElement (FormatElementType.Error);
+                                       case '\'':
+                                               string literal = ParseLiteral ();
+                                               if (literal == null)
+                                                       return new FormatElement (FormatElementType.Error);
+                                               element.Type = FormatElementType.Literal;
+                                               element.StringValue = literal;
+                                               break;
+                                       case '\\':
+                                               char escaped_char = ParseEscapedChar ();
+                                               if ((int)escaped_char == 0)
+                                                       return new FormatElement (FormatElementType.Error);
+                                               element.Type = FormatElementType.EscapedChar;
+                                               element.CharValue = escaped_char;
+                                               break;
+                                       default:
+                                               return new FormatElement (FormatElementType.Error);
+                               }
+
+                               return element;
+                       }
+
+                       int ParseChar (char c)
+                       {
+                               int count = 0;
+
+                               while (!AtEnd && format [cur] == c) {
+                                       cur++;
+                                       count++;
+                               }
+
+                               return count;
+                       }
+
+                       char ParseEscapedChar ()
+                       {
+                               if (AtEnd || format [cur] != '\\')
+                                       return (char)0;
+
+                               cur++;
+                               if (AtEnd)
+                                       return (char)0;
+
+                               return format [cur++];
+                       }
+
+                       string ParseLiteral ()
+                       {
+                               int start;
+                               int count = 0;
+
+                               if (AtEnd || format [cur] != '\'')
+                                       return null;
+
+                               start = ++cur;
+                               while (!AtEnd && format [cur] != '\'') {
+                                       cur++;
+                                       count++;
+                               }
+
+                               if (!AtEnd && format [cur] == '\'') {
+                                       cur++;
+                                       return format.Substring (start, count);
+                               }
+
+                               return null;
+                       }
                }
+#endif
+
        }
 }
index 40aa50587af4f9155f863938657b615efbbf3ddc..3dd922f035d89af5e673e30c900d9cfed0076441 100644 (file)
  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  */
 
-#if NET_4_0 || BOOTSTRAP_NET_4_0
+#if NET_4_0 || BOOTSTRAP_NET_4_0 || MOONLIGHT
 
 using System.Runtime.CompilerServices;
 
 namespace System
 {
        [Serializable]
-       [TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]     
+#if NET_4_0 || BOOTSTRAP_NET_4_0
+       [TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
+#elif MOONLIGHT
+       [TypeForwardedFrom (Consts.AssemblySystem_Core)]
+#endif
        public class TimeZoneNotFoundException : Exception
        {
                public TimeZoneNotFoundException () : base ()
index 078669e1cafb3311df9090ff71e6dd84cd537818..b535413c12ddb56cb241d97707da23764f5ea203 100644 (file)
@@ -26,7 +26,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if (NET_2_1 && !MONOTOUCH) || NET_4_0
+#if MOONLIGHT || NET_4_0 || BOOTSTRAP_NET_4_0
 
 using System;
 
index a00e5384082cb7c33f7f0b8a899b0a1b0361dc05..e5e8f6ec2199da93443b365eaecda01fafe6bbfb 100644 (file)
@@ -27,7 +27,7 @@
 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 //
 
-#if (NET_2_1 && !MONOTOUCH) || NET_4_0
+#if MOONLIGHT || NET_4_0 || BOOTSTRAP_NET_4_0
 
 using System;
 using System.Collections;
index 43bdd391be1ace5e8990d40e83f5da8718d8bc18..a6d6f0d52f16dee34450ef32c1939198ccc7d6b1 100644 (file)
@@ -1346,6 +1346,11 @@ namespace System {
                        }
                }
 
+               internal virtual Type InternalResolve ()
+               {
+                       return UnderlyingSystemType;
+               }
+
                internal bool IsSystemType {
                        get {
                                return _impl.Value != IntPtr.Zero;
index fa38bc49db32229e771aa0a759755e9051a0e4f5..950f1e8ea69fdcd0ad299fcb89d77ba8170216c0 100644 (file)
@@ -178,12 +178,12 @@ namespace System
                                return false;
                        }
 
-                       NumberFormatInfo nfi;
+                       NumberFormatInfo nfi = null;
                        if (provider != null) {
                                Type typeNFI = typeof (NumberFormatInfo);
                                nfi = (NumberFormatInfo) provider.GetFormat (typeNFI);
                        }
-                       else
+                       if (nfi == null)
                                nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
 
                        if (!Int32.CheckStyle (style, tryParse, ref exc))
index 5691f2abad1fecd41fbf533e128d6ef6cbffdf01..8f138197b259353032f708b6affbcec3f68cdc38 100644 (file)
@@ -201,12 +201,12 @@ namespace System
                                return false;
                        }
 
-                       NumberFormatInfo nfi;
+                       NumberFormatInfo nfi = null;
                        if (provider != null) {
                                Type typeNFI = typeof (NumberFormatInfo);
                                nfi = (NumberFormatInfo) provider.GetFormat (typeNFI);
                        }
-                       else
+                       if (nfi == null)
                                nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
 
                        if (!Int32.CheckStyle (style, tryParse, ref exc))
index 7749106d2f57be16fa7f4fc68f582fc903a95fa5..c81fae3d0aab161bdc58fc4d0cc069366e458f31 100644 (file)
@@ -1,3 +1,12 @@
+2010-03-24  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * ConcurrentDictionaryTests.cs: Renaming in Assert
+
+2010-03-24  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * ConcurrentDictionaryTests.cs: Update behavior of TryAddDuplicateTest
+       The method returns false and doesn't throw exception anymore
+
 2010-02-02  Jérémie Laval  <jeremie.laval@gmail.com>
 
        * CollectionStressTestHelper.cs:
index be1e22760cfe0961975bd2cbc784bcda156f7687..4f1ad64ce2f2af1628dcae9fd7be5773de7ac1b2 100644 (file)
@@ -47,7 +47,7 @@ namespace MonoTests.System.Collections.Concurrent
                
                void AddStuff ()
                {
-                 map.TryAdd ("foo", 1);
+                       map.TryAdd ("foo", 1);
                        map.TryAdd ("bar", 2);
                        map.TryAdd ("foobar", 3);
                }
@@ -82,16 +82,16 @@ namespace MonoTests.System.Collections.Concurrent
                                int value;
                                
                                Assert.IsTrue (map.TryGetValue ("monkey1", out value), "#1");
-                               Assert.AreEqual (3, value, "#1");
+                               Assert.AreEqual (3, value, "#1b");
                                
                                Assert.IsTrue (map.TryGetValue ("monkey2", out value), "#2");
-                               Assert.AreEqual (3, value, "#2");
+                               Assert.AreEqual (3, value, "#2b");
                                
                                Assert.IsTrue (map.TryGetValue ("monkey3", out value), "#3");
-                               Assert.AreEqual (3, value, "#3");
+                               Assert.AreEqual (3, value, "#3b");
                                
                                Assert.IsTrue (map.TryGetValue ("monkey4", out value), "#4");
-                               Assert.AreEqual (3, value, "#4");
+                               Assert.AreEqual (3, value, "#4b");
                        });
                }
                
@@ -132,16 +132,16 @@ namespace MonoTests.System.Collections.Concurrent
                        });
                }
                
-               [Test, ExpectedException(typeof(ArgumentException))]
+               [Test]
                public void AddWithDuplicate()
                {
-                       map.TryAdd("foo", 6);
+                       Assert.IsFalse (map.TryAdd("foo", 6));
                }
                
                [Test]
                public void GetValueTest()
                {
-                 Assert.AreEqual(1, map["foo"], "#1");
+                       Assert.AreEqual(1, map["foo"], "#1");
                        Assert.AreEqual(2, map["bar"], "#2");
                        Assert.AreEqual(3, map.Count, "#3");
                }
index 109bcbf84d430235fabf08c9af196d8c6452080d..4edfd00b08c3668128b71b71714714647f5ffb1c 100644 (file)
@@ -277,7 +277,7 @@ public class HashtableTest {
 \r
 #if NET_2_0\r
        public class MyEqualityComparer : IEqualityComparer {\r
-               public bool Equals (object x, object y) { return x == y; }\r
+               bool IEqualityComparer.Equals (object x, object y) { return x == y; }\r
                public int GetHashCode (object obj) { return 1; }\r
        }\r
 \r
index 3e40dfb98116470187c892a12fc0677a948cd332..397926c9a6b9b3ffdecdf54a6eee009a7530e0ac 100644 (file)
@@ -19,7 +19,6 @@ namespace MonoTests.System.Collections
        public class StackTest
        {
                 private Stack stack1;
-                private Stack stack2;
                 private Stack stackInt;
 
                [Test]
@@ -411,7 +410,6 @@ namespace MonoTests.System.Collections
                 protected  void SetUp()
                 {
                         stack1 = new Stack();
-                        stack2 = new Stack();
 
                         stackInt = new Stack();
     
index 0d05bd8c7fa67cd0b23da462cec4931d4862a52c..c1fd0abda355a209819eb60af741d1da9341e7d0 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-17 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * StreamReaderTest.cs: test for bug 589236. The detected encoding is
+       different from the one provided in the ctor.
+
 2010-02-22  Carlos Alberto Cortez <calberto.cortez@gmail.com>
 
        * MemoryStreamTest.cs: Add a new test for Capacity.
index f83dc905e97eaed99278378bc5021d1ea9f61c4b..18d8fc6cc435fa3dd34edff0eb2c9ee73bdf2a16 100644 (file)
@@ -59,6 +59,7 @@ public class DirectoryTest
                }\r
        }\r
        \r
+       /* Commented out: a directory named ":" is legal in unix\r
        [Test]\r
        public void CreateDirectoryNotSupportedException ()\r
        {\r
@@ -75,6 +76,7 @@ public class DirectoryTest
                }\r
                DeleteDirectory (":");\r
        }\r
+       */\r
 \r
        [Test]\r
        public void CreateDirectory_Path_Null ()\r
index db6108060a9c2867daec65d2f07a8e3005041a1c..51b70cd2b68068d38f135046cc15310ba413ba1d 100644 (file)
@@ -815,6 +815,28 @@ public class StreamReaderTest
                string str = reader.ReadToEnd ();
                Assert.AreEqual ("bc", str);
        }
+
+       [Test]
+       public void EncodingChangedAuto ()
+       {
+               int testlines = 2048; // all data should larger than stream reader default buffer size
+               string testdata = "test";
+               MemoryStream ms = new MemoryStream();
+               // write utf8 encoding data.
+               using (StreamWriter sw = new StreamWriter (ms, Encoding.UTF8)) {
+                       for (int i = 0; i < testlines; i++)
+                               sw.WriteLine (testdata);
+               }
+
+               MemoryStream readms = new MemoryStream (ms.GetBuffer());
+               using (StreamReader sr = new StreamReader(readms, Encoding.Unicode, true)) {
+                       for (int i = 0; i < testlines; i++) {
+                               string line = sr.ReadLine ();
+                               if (line != testdata)
+                                       Assert.Fail ("Wrong line content");
+                       }
+               }
+       }
 }
 
 class MyStream : Stream {
index 02aabcd241f92b6f967a6f79962287bab02cc8a1..0740d69f8a531ab83b06927d2ce803d5da279b63 100644 (file)
@@ -1684,11 +1684,10 @@ public class AssemblyBuilderTest
        }
 
        [Test]
-       [Category ("NotDotNet")]
        public void GetType_IgnoreCase ()
        {
                TypeBuilder tb = mb.DefineType ("Foo.Test2", TypeAttributes.Public, typeof (object));
-               // the previous line throws a TypeLoadException under MS 1.1 SP1
+               tb.CreateType ();
 
                Type t;
 
@@ -1702,6 +1701,66 @@ public class AssemblyBuilderTest
                Assert.AreEqual ("Test2", t.Name, "#3");
        }
 
+
+       [Test]
+       public void TestGetType ()
+       {
+               TypeBuilder tb = mb.DefineType ("Test", TypeAttributes.Public);
+
+               Assert.IsNull (ab.GetType ("Test", false, true), "#1");
+               try {
+                       ab.GetType ("Test", true, true);
+                       Assert.Fail ("#2");
+               } catch (TypeLoadException) { }
+
+               var res = tb.CreateType ();
+
+               Assert.AreSame (res, ab.GetType ("Test", false, true), "#3");
+       }
+
+       [Test]
+       public void GetModule ()
+       {
+               var ab = genAssembly ();
+               Assert.IsNull (ab.GetModule ("Foo"), "#1");
+
+               var modA = ab.DefineDynamicModule ("Foo");
+               var modB = ab.DefineDynamicModule ("Bar");
+
+               Assert.AreSame (modA, ab.GetModule ("Foo"), "#2"); 
+               Assert.AreSame (modB, ab.GetModule ("Bar"), "#3"); 
+               Assert.IsNull (ab.GetModule ("FooBar"), "#4");
+       }
+       
+       [Test]
+       public void GetModules2 ()
+       {
+               //XXX this is not the v4 behavior since it returns
+               //the manifest module in the place of the first one
+               var ab = genAssembly ();
+               var modA = ab.DefineDynamicModule ("Foo");
+               var modB = ab.DefineDynamicModule ("Bar");
+               Assert.AreEqual (2, ab.GetModules ().Length, "#1");
+               Assert.AreSame (modA, ab.GetModules () [0], "#2");
+               Assert.AreSame (modB, ab.GetModules () [1], "#3");
+       }
+
+       [Test]
+       [Category ("NotDotNet")] // MS returns the real deal
+       public void GetReferencedAssemblies_Trivial ()
+       {
+               Assert.IsNotNull (ab.GetReferencedAssemblies (), "#1");
+       }
+       
+       [Test]
+       public void GetLoadedModules ()
+       {
+               var res = ab.GetLoadedModules (true);
+               Assert.IsNotNull (res, "#1");
+               Assert.AreEqual (1, res.Length, "#2");
+               Assert.AreEqual (mb, res [0], "#3");
+       }
+
        [ExpectedException (typeof (TypeLoadException))]
        public void GetCustomAttributes_NotCreated ()
        {
index b2e7ad4f2048259058c35092c20aa69b70d20dfd..bfb8fd0767daf1b16ae68ac8ef6574d443774e7f 100644 (file)
@@ -1,3 +1,53 @@
+2010-04-20 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * TypeBuilderTest.cs: Enable a bunch of asserts.
+       They regression test #331126.
+
+2010-04-20 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * TypeBuilderTest.cs: Slay all 1.0 code.
+
+2010-04-13 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * TypeBuilderTest.cs: Regression test for #422113.
+
+2010-04-09 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * MethodBuilderTest.cs: Regression test for #591226.
+
+2010-04-08 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * TypeBuilderTest.cs: Regression test for #591225.
+
+2010-04-08 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * TypeBuilderTest.cs: Regression test for #594728.
+
+2010-04-01 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * ModuleBuilderTest.cs (TestGlobalMethods): Improve test.
+
+2010-03-30  Zoltan Varga  <vargaz@gmail.com>
+
+       * ModuleBuilderTest.cs: Add a test for #592215.
+
+2010-03-26 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * AssemblyBuilderTest.cs: Test GetReferencedAssemblies
+       and GetLoadedModules.
+
+2010-03-25 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * AssemblyBuilderTest.cs: Add test for v4 GetModule(s).
+
+2010-03-24 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * DerivedTypesTests.cs: Fix some tests under v4.
+
+2010-03-23 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * MethodOnTypeBuilderInstTest.cs: Add Test for ContainsGenericParameters.
+
 2010-03-11 Rodrigo Kumpera  <rkumpera@novell.com>
 
        * TypeBuilderTest.cs: New tests for GetMethod, GetConstructor and GetField.
index 3425623f13de61f5a3c8a45404de0276d33c9938..17912b4fd4c1c22d877a476699e44a6090c3d2b6 100644 (file)
@@ -526,10 +526,14 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.IsFalse (ptr.IsGenericType, "#9");
                        Assert.IsFalse (ptr.IsGenericTypeDefinition, "#10");
 
+#if NET_4_0
+                       Assert.AreEqual (TypeAttributes.Public, ptr.Attributes, "#11");
+#else
                        try {
-                               var x = ptr.Attributes; 
+                               var x = ptr.Attributes; //This is because GenericTypeParameterBuilder doesn't support Attributes 
                                Assert.Fail ("#11");
                        } catch (NotSupportedException) {}
+#endif
 
                        Assert.IsTrue (ptr.HasElementType, "#12");
                        Assert.IsTrue (ptr.IsPointer, "#13");
@@ -1030,10 +1034,15 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.IsFalse (byref.IsGenericType, "#9");
                        Assert.IsFalse (byref.IsGenericTypeDefinition, "#10");
 
+
+#if NET_4_0
+                       Assert.AreEqual (TypeAttributes.Public, byref.Attributes, "#11");
+#else
                        try {
-                               var x = byref.Attributes; 
+                               var x = byref.Attributes; //This is because GenericTypeParameterBuilder doesn't support Attributes 
                                Assert.Fail ("#11");
                        } catch (NotSupportedException) {}
+#endif
 
                        Assert.IsTrue (byref.HasElementType, "#12");
                        Assert.IsTrue (byref.IsByRef, "#13");
@@ -1653,10 +1662,14 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.IsFalse (arr.IsGenericType, "#9");
                        Assert.IsFalse (arr.IsGenericTypeDefinition, "#10");
 
+#if NET_4_0
+                       Assert.AreEqual (TypeAttributes.Public, arr.Attributes, "#11");
+#else
                        try {
                                var x = arr.Attributes; //This is because GenericTypeParameterBuilder doesn't support Attributes 
                                Assert.Fail ("#11");
                        } catch (NotSupportedException) {}
+#endif
 
                        Assert.IsTrue (arr.HasElementType, "#12");
                        Assert.IsTrue (arr.IsArray, "#13");
index 31efc1d6ba8d854c2d46a763e25c6936785c8b48..9fe0cb5c7289aa85a794891e43b6f1c8688ecad8 100644 (file)
@@ -761,7 +761,6 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.AreEqual ("foo", pi [1].DefaultValue, "#B1");
                }
 
-#if NET_2_0
                [Test]
                public void SetCustomAttribute_DllImport1 ()
                {
@@ -964,6 +963,8 @@ namespace MonoTests.System.Reflection.Emit
                        }
                }
 
+
+
                [Test]
                public void DefineGenericParameters_Names_Null ()
                {
@@ -990,6 +991,34 @@ namespace MonoTests.System.Reflection.Emit
                                Assert.AreEqual ("names", ex.ParamName, "#B5");
                        }
                }
-#endif
+
+
+               public static int Foo<T> (T a, T b) {
+                       return 99;
+               }
+
+               [Test]//bug #591226
+               public void GenericMethodIsProperlyInflated ()
+               {
+                       var tb = module.DefineType ("foo");
+                       var met = typeof (MethodBuilderTest).GetMethod ("Foo");
+
+                       var mb = tb.DefineMethod ("myFunc", MethodAttributes.Public | MethodAttributes.Static, typeof (int), Type.EmptyTypes);
+                       var garg = mb.DefineGenericParameters ("a") [0];
+                       mb.SetParameters (garg, garg);
+
+                       var ilgen = mb.GetILGenerator ();
+                       ilgen.Emit (OpCodes.Ldarg_0);
+                       ilgen.Emit (OpCodes.Ldarg_1);
+                       ilgen.Emit (OpCodes.Call, met.MakeGenericMethod (garg));
+                       ilgen.Emit (OpCodes.Ret);
+
+                       var res = tb.CreateType ();
+                       var mm = res.GetMethod ("myFunc").MakeGenericMethod (typeof (int));
+
+                       var rt = mm.Invoke (null, new object[] { 10, 20 });
+                       Assert.AreEqual (99, rt, "#1");
+               }
+
        }
 }
index ee80a484d72677162de2f4447ef8c0056a0ed17e..6c558448030ba51691d8ae7673f7516d158c95ea 100644 (file)
@@ -29,6 +29,7 @@
 #if NET_2_0
 
 using System;
+using System.Collections.Generic;
 using System.Globalization;
 using System.IO;
 using System.Reflection;
@@ -684,6 +685,21 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.AreEqual (typeof (int), minst.GetParameters ()[0].ParameterType, "#5");
                        Assert.AreEqual (typeof (int[]), minst.GetParameters ()[1].ParameterType, "#6");
                }
+
+               [Test]
+               public void PropertiesOfANonGenericMethodOnGenericType ()
+               {
+                       Type t = typeof (List<>);
+                       Type a = t.GetGenericArguments () [0];
+                       MethodInfo m = t.GetMethod ("IndexOf", new Type [] { a });
+       
+                       var tb = module.DefineType ("foo.type");
+                       Type ttt = t.MakeGenericType (tb);
+                       MethodInfo mm = TypeBuilder.GetMethod (ttt, m);
+                       Assert.IsTrue (mm.GetGenericMethodDefinition ().ContainsGenericParameters, "#1");
+                       Assert.IsTrue (mm.ContainsGenericParameters, "#2");
+               }
+
        }
 }
 
index 21cf8ec2f1bb015c0caff5e6598a9ddd2937b71f..9a442b7a73182b4f2a673f66ede79818377d98d9 100644 (file)
@@ -126,9 +126,12 @@ namespace MonoTests.System.Reflection.Emit
                                                                                                                          CharSet.Auto);
                        method.SetImplementationFlags (MethodImplAttributes.PreserveSig |
                                                                                   method.GetMethodImplementationFlags ());
+
+                       Assert.IsNull (module.GetMethod ("printf"), "#1");
+
                        module.CreateGlobalFunctions ();
 
-                       Assert.IsNotNull (module.GetMethod ("printf"));
+                       Assert.IsNotNull (module.GetMethod ("printf"), "#2");
                }
 
                [Test]
@@ -241,6 +244,21 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.AreEqual (typeof (ICollection), tb.BaseType, "#2");
                }
 
+               [Test]
+               [ExpectedException (typeof (ArgumentException))]
+               public void DuplicateTypeName () {
+                       AssemblyBuilder ab = genAssembly ();
+                       ModuleBuilder module = ab.DefineDynamicModule ("foo.dll", "foo.dll", true);
+
+                       var itb = module.DefineType ("TBase", TypeAttributes.Public);
+
+                       itb.SetParent (typeof(ValueType));        
+
+                       var ptb = module.DefineType ("TBase", TypeAttributes.Public);
+
+                       ptb.SetParent (typeof(Enum));
+               }
+
                [Test]
                public void DuplicateSymbolDocument ()
                {
index 8f75a5e34f1ba8b40a6d8fae822a53f4f9ea8a64..36c67a9cf1bf89f98138a5a8606d0caf9ce23395 100644 (file)
@@ -25,9 +25,7 @@ using System.Runtime.InteropServices;
 using NUnit.Framework;
 using System.Runtime.CompilerServices;
 
-#if NET_2_0
 using System.Collections.Generic;
-#endif
 
 namespace MonoTests.System.Reflection.Emit
 {
@@ -47,11 +45,9 @@ namespace MonoTests.System.Reflection.Emit
        {
        }
 
-#if NET_2_0
        public class Gen<T> {
                public static T field = default(T);
        }
-#endif
 
        [TestFixture]
        public class TypeBuilderTest
@@ -95,13 +91,11 @@ namespace MonoTests.System.Reflection.Emit
                public interface IDestroyable
                {
                }
-#if NET_2_0
 
                public class Tuple <A,B> {
                        A a;
                        B b;
                }
-#endif
 
                private AssemblyBuilder assembly;
 
@@ -273,46 +267,17 @@ namespace MonoTests.System.Reflection.Emit
                        // According to the MSDN docs, this member works, but in reality, it
                        // returns a NotSupportedException
                        TypeBuilder tb = module.DefineType (genTypeName ());
-#if NET_2_0
                        Assert.IsFalse (tb.HasElementType);
-#else
-                       try {
-                               bool b = tb.HasElementType;
-                               Assert.Fail ("#1: " + b);
-                       } catch (NotSupportedException ex) {
-                               // The invoked member is not supported in a
-                               // dynamic module
-                               Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
-                               Assert.IsNull (ex.InnerException, "#3");
-                               Assert.IsNotNull (ex.Message, "#4");
-                       }
-#endif
                }
 
                [Test]
-#if ONLY_1_1
-               [Category ("NotWorking")]
-#endif
                public void TestHasElementType_Complete ()
                {
                        // According to the MSDN docs, this member works, but in reality, it
                        // returns a NotSupportedException
                        TypeBuilder tb = module.DefineType (genTypeName ());
                        tb.CreateType ();
-#if NET_2_0
                        Assert.IsFalse (tb.HasElementType);
-#else
-                       try {
-                               bool b = tb.HasElementType;
-                               Assert.Fail ("#1: " + b);
-                       } catch (NotSupportedException ex) {
-                               // The invoked member is not supported in a
-                               // dynamic module
-                               Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
-                               Assert.IsNull (ex.InnerException, "#3");
-                               Assert.IsNotNull (ex.Message, "#4");
-                       }
-#endif
                }
 
                [Test] // bug #324692
@@ -328,15 +293,10 @@ namespace MonoTests.System.Reflection.Emit
                        } catch (TypeLoadException) {
                        }
 
-#if NET_2_0
-                       //Assert.IsTrue (tb.IsCreated (), "#2");
-#endif
+                       Assert.IsTrue (tb.IsCreated (), "#2");
                }
 
                [Test] // bug #324692
-#if ONLY_1_1
-               [Category ("NotWorking")] // we do not throw IOE when repeatedly invoking CreateType
-#endif
                public void TestCreateTypeReturnsNullOnSecondCallForBadType ()
                {
                        TypeBuilder tb = module.DefineType (genTypeName (),
@@ -352,21 +312,9 @@ namespace MonoTests.System.Reflection.Emit
                                Assert.IsNotNull (ex.Message, "#A4");
                        }
 
-#if NET_2_0
-                       //Assert.IsTrue (tb.IsCreated (), "#B1");
+                       Assert.IsTrue (tb.IsCreated (), "#B1");
                        Assert.IsNull (tb.CreateType (), "#B2");
-                       //Assert.IsTrue (tb.IsCreated (), "#B3");
-#else
-                       try {
-                               tb.CreateType ();
-                               Assert.Fail ("#B1");
-                       } catch (InvalidOperationException ex) {
-                               // Unable to change after type has been created
-                               Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2");
-                               Assert.IsNull (ex.InnerException, "#B3");
-                               Assert.IsNotNull (ex.Message, "#B4");
-                       }
-#endif
+                       Assert.IsTrue (tb.IsCreated (), "#B3");
                }
 
                [Test]
@@ -386,9 +334,7 @@ namespace MonoTests.System.Reflection.Emit
                                Assert.Fail ("#1: must build enum type ok");
                        }
 
-#if NET_2_0
                        Assert.IsTrue (tb.IsCreated (), "#2");
-#endif
                }
 
                [Test]
@@ -409,9 +355,7 @@ namespace MonoTests.System.Reflection.Emit
                        } catch (TypeLoadException) {
                        }
 
-#if NET_2_0
                        Assert.IsTrue (tb.IsCreated (), "#2");
-#endif
                }
 
                [Test]
@@ -430,9 +374,7 @@ namespace MonoTests.System.Reflection.Emit
                        } catch (TypeLoadException) {
                        }
 
-#if NET_2_0
                        Assert.IsTrue (tb.IsCreated (), "#2");
-#endif
                }
 
                [Test]
@@ -450,9 +392,7 @@ namespace MonoTests.System.Reflection.Emit
                        } catch (TypeLoadException) {
                        }
 
-#if NET_2_0
-                       //Assert.IsTrue (tb.IsCreated (), "#2");
-#endif
+                       Assert.IsTrue (tb.IsCreated (), "#2");
                }
 
                [Test]
@@ -470,9 +410,7 @@ namespace MonoTests.System.Reflection.Emit
                        } catch (TypeLoadException) {
                        }
 
-#if NET_2_0
-                       //Assert.IsTrue (tb.IsCreated (), "#2");
-#endif
+                       Assert.IsTrue (tb.IsCreated (), "#2");
                }
 
                [Test]
@@ -496,9 +434,7 @@ namespace MonoTests.System.Reflection.Emit
                        } catch (TypeLoadException) {
                        }
 
-#if NET_2_0
-                       //Assert.IsTrue (tb.IsCreated (), "#2");
-#endif
+                       Assert.IsTrue (tb.IsCreated (), "#2");
                }
 
                [Test]
@@ -523,9 +459,7 @@ namespace MonoTests.System.Reflection.Emit
                                } catch (TypeLoadException) {
                                }
 
-#if NET_2_0
-                               //Assert.IsTrue (tb.IsCreated (), "#2");
-#endif
+                               Assert.IsTrue (tb.IsCreated (), "#2");
                        }
                }
 
@@ -572,9 +506,7 @@ namespace MonoTests.System.Reflection.Emit
                        } catch (TypeLoadException) {
                        }
 
-#if NET_2_0
-                       //Assert.IsTrue (tb.IsCreated (), "#2");
-#endif
+                       Assert.IsTrue (tb.IsCreated (), "#2");
                }
 
                [Test]
@@ -962,39 +894,14 @@ namespace MonoTests.System.Reflection.Emit
                {
                        TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Class,
                                typeof (Attribute));
-#if NET_2_0
                        tb.SetParent (null);
                        Assert.AreEqual (typeof (object), tb.BaseType, "#A1");
-#else
-                       try {
-                               tb.SetParent (null);
-                               Assert.Fail ("#A1");
-                       } catch (ArgumentNullException ex) {
-                               Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#A2");
-                               Assert.IsNull (ex.InnerException, "#A3");
-                               Assert.IsNotNull (ex.Message, "#A4");
-                               Assert.AreEqual ("parent", ex.ParamName, "#A5");
-                       }
-#endif
 
                        tb = module.DefineType (genTypeName (), TypeAttributes.Interface |
                                TypeAttributes.Abstract);
-#if NET_2_0
                        tb.SetParent (null);
                        Assert.IsNull (tb.BaseType, "#B1");
-#else
-                       try {
-                               tb.SetParent (null);
-                               Assert.Fail ("#B1");
-                       } catch (ArgumentNullException ex) {
-                               Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#B2");
-                               Assert.IsNull (ex.InnerException, "#B3");
-                               Assert.IsNotNull (ex.Message, "#B4");
-                               Assert.AreEqual ("parent", ex.ParamName, "#B5");
-                       }
-#endif
 
-#if NET_2_0
                        tb = module.DefineType (genTypeName (), TypeAttributes.Interface |
                                TypeAttributes.Abstract, typeof (ICloneable));
                        Assert.AreEqual (typeof (ICloneable), tb.BaseType, "#C1");
@@ -1012,7 +919,6 @@ namespace MonoTests.System.Reflection.Emit
                                Assert.IsNull (ex.InnerException, "#D3");
                                Assert.IsNotNull (ex.Message, "#D4");
                        }
-#endif
                }
 
                [Test]
@@ -1039,7 +945,6 @@ namespace MonoTests.System.Reflection.Emit
                        tb.SetParent (typeof (IDisposable));
                        Assert.AreEqual (typeof (IDisposable), tb.BaseType, "#3");
 
-#if NET_2_0
                        tb = module.DefineType (genTypeName (), TypeAttributes.Interface |
                                TypeAttributes.Abstract, typeof (IDisposable));
                        tb.SetParent (typeof (ICloneable));
@@ -1049,7 +954,6 @@ namespace MonoTests.System.Reflection.Emit
                                TypeAttributes.Abstract, typeof (IDisposable));
                        tb.SetParent (typeof (ICloneable));
                        Assert.AreEqual (typeof (ICloneable), tb.BaseType, "#5");
-#endif
                }
 
                [Test]
@@ -1223,37 +1127,19 @@ namespace MonoTests.System.Reflection.Emit
                }
 
                [Test]
-#if ONLY_1_1
-               [Category ("NotWorking")] // we allow CreateType to be invoked multiple times
-#endif
                public void TestCreateType_Created ()
                {
                        TypeBuilder tb = module.DefineType (genTypeName ());
-#if NET_2_0
                        Assert.IsFalse (tb.IsCreated (), "#A1");
-#endif
+
                        Type emittedType1 = tb.CreateType ();
-#if NET_2_0
                        Assert.IsTrue (tb.IsCreated (), "#A2");
-#endif
                        Assert.IsNotNull (emittedType1, "#A3");
 
-#if NET_2_0
                        Type emittedType2 = tb.CreateType ();
                        Assert.IsNotNull (emittedType2, "#B1");
                        Assert.IsTrue (tb.IsCreated (), "#B2");
                        Assert.AreSame (emittedType1, emittedType2, "#B3");
-#else
-                       try {
-                               tb.CreateType ();
-                               Assert.Fail ("#B1");
-                       } catch (InvalidOperationException ex) {
-                               // Unable to change after type has been created
-                               Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2");
-                               Assert.IsNull (ex.InnerException, "#B3");
-                               Assert.IsNotNull (ex.Message, "#B4");
-                       }
-#endif
                }
 
                [Test]
@@ -1532,7 +1418,6 @@ namespace MonoTests.System.Reflection.Emit
                        }
                }
 
-#if NET_2_0
                [Test] // DefineField (String, Type, Type [], Type [], FieldAttributes)
                public void DefineField2_Type_Null ()
                {
@@ -1549,7 +1434,6 @@ namespace MonoTests.System.Reflection.Emit
                                Assert.AreEqual ("type", ex.ParamName, "#5");
                        }
                }
-#endif
 
                [Test]
                public void TestDefineInitializedData ()
@@ -4926,7 +4810,6 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.AreEqual ("Sex", fields [0].Name, "#A2");
                        Assert.AreEqual ("MALE", fields [1].Name, "#A3");
 
-#if NET_2_0
                        tb = module.DefineType (genTypeName ());
                        GenericTypeParameterBuilder [] typeParams = tb.DefineGenericParameters ("K", "V");
                        tb.DefineField ("First", typeParams [0], FieldAttributes.Public);
@@ -4941,7 +4824,6 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.AreEqual ("Second", fields [1].Name, "#B3");
                        Assert.AreEqual ("Sex", fields [2].Name, "#B4");
                        Assert.AreEqual ("MALE", fields [3].Name, "#B5");
-#endif
                }
 
                [Test]
@@ -4969,7 +4851,6 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.AreEqual (4, dynamicFields [0].GetValue (value), "#B4");
                }
 
-#if NET_2_0
                [Test] // bug #82625 / 325292
                public void TestGetFieldsComplete_Generic ()
                {
@@ -5013,7 +4894,6 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.AreEqual ("Sex", emittedFields [2].Name, "#D8");
                        Assert.AreEqual ("MALE", emittedFields [3].Name, "#D9");
                }
-#endif
 
                [Test]
                [Category ("NotWorking")] // mcs depends on this
@@ -6131,11 +6011,7 @@ namespace MonoTests.System.Reflection.Emit
                        flags = BindingFlags.Instance | BindingFlags.NonPublic;
                        props = greenType.GetProperties (flags);
 
-#if NET_2_0
                        Assert.AreEqual (13, props.Length, "#A1");
-#else
-                       Assert.AreEqual (11, props.Length, "#A1");
-#endif
                        Assert.AreEqual ("PrivateInstanceGreen", props [0].Name, "#A2");
                        Assert.AreEqual ("FamilyInstanceGreen", props [1].Name, "#A3");
                        Assert.AreEqual ("FamANDAssemInstanceGreen", props [2].Name, "#A4");
@@ -6144,17 +6020,11 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.AreEqual ("FamilyInstanceRed", props [5].Name, "#A7");
                        Assert.AreEqual ("FamANDAssemInstanceRed", props [6].Name, "#A8");
                        Assert.AreEqual ("FamORAssemInstanceRed", props [7].Name, "#A9");
-#if NET_2_0
                        Assert.AreEqual ("AssemblyInstanceRed", props [8].Name, "#A10");
                        Assert.AreEqual ("FamilyInstanceBlue", props [9].Name, "#A11");
                        Assert.AreEqual ("FamANDAssemInstanceBlue", props [10].Name, "#A12");
                        Assert.AreEqual ("FamORAssemInstanceBlue", props [11].Name, "#A13");
                        Assert.AreEqual ("AssemblyInstanceBlue", props [12].Name, "#A15");
-#else
-                       Assert.AreEqual ("FamilyInstanceBlue", props [8].Name, "#A10");
-                       Assert.AreEqual ("FamANDAssemInstanceBlue", props [9].Name, "#A11");
-                       Assert.AreEqual ("FamORAssemInstanceBlue", props [10].Name, "#A12");
-#endif
 
                        flags = BindingFlags.Instance | BindingFlags.Public;
                        props = greenType.GetProperties (flags);
@@ -6184,11 +6054,7 @@ namespace MonoTests.System.Reflection.Emit
                                BindingFlags.FlattenHierarchy;
                        props = greenType.GetProperties (flags);
 
-#if NET_2_0
                        Assert.AreEqual (13, props.Length, "#E1");
-#else
-                       Assert.AreEqual (11, props.Length, "#E1");
-#endif
                        Assert.AreEqual ("PrivateInstanceGreen", props [0].Name, "#E2");
                        Assert.AreEqual ("FamilyInstanceGreen", props [1].Name, "#E3");
                        Assert.AreEqual ("FamANDAssemInstanceGreen", props [2].Name, "#E4");
@@ -6197,17 +6063,11 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.AreEqual ("FamilyInstanceRed", props [5].Name, "#E7");
                        Assert.AreEqual ("FamANDAssemInstanceRed", props [6].Name, "#E8");
                        Assert.AreEqual ("FamORAssemInstanceRed", props [7].Name, "#E9");
-#if NET_2_0
                        Assert.AreEqual ("AssemblyInstanceRed", props [8].Name, "#E10");
                        Assert.AreEqual ("FamilyInstanceBlue", props [9].Name, "#E11");
                        Assert.AreEqual ("FamANDAssemInstanceBlue", props [10].Name, "#E12");
                        Assert.AreEqual ("FamORAssemInstanceBlue", props [11].Name, "#E13");
                        Assert.AreEqual ("AssemblyInstanceBlue", props [12].Name, "#E14");
-#else
-                       Assert.AreEqual ("FamilyInstanceBlue", props [8].Name, "#E10");
-                       Assert.AreEqual ("FamANDAssemInstanceBlue", props [9].Name, "#E11");
-                       Assert.AreEqual ("FamORAssemInstanceBlue", props [10].Name, "#E12");
-#endif
 
                        flags = BindingFlags.Instance | BindingFlags.Public |
                                BindingFlags.FlattenHierarchy;
@@ -6231,11 +6091,7 @@ namespace MonoTests.System.Reflection.Emit
                                BindingFlags.FlattenHierarchy;
                        props = greenType.GetProperties (flags);
 
-#if NET_2_0
                        Assert.AreEqual (13, props.Length, "#H1");
-#else
-                       Assert.AreEqual (11, props.Length, "#H1");
-#endif
                        Assert.AreEqual ("PrivateStaticGreen", props [0].Name, "#H2");
                        Assert.AreEqual ("FamilyStaticGreen", props [1].Name, "#H3");
                        Assert.AreEqual ("FamANDAssemStaticGreen", props [2].Name, "#H4");
@@ -6244,17 +6100,11 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.AreEqual ("FamilyStaticRed", props [5].Name, "#H7");
                        Assert.AreEqual ("FamANDAssemStaticRed", props [6].Name, "#H8");
                        Assert.AreEqual ("FamORAssemStaticRed", props [7].Name, "#H9");
-#if NET_2_0
                        Assert.AreEqual ("AssemblyStaticRed", props [8].Name, "#H10");
                        Assert.AreEqual ("FamilyStaticBlue", props [9].Name, "#H11");
                        Assert.AreEqual ("FamANDAssemStaticBlue", props [10].Name, "#H12");
                        Assert.AreEqual ("FamORAssemStaticBlue", props [11].Name, "#H13");
                        Assert.AreEqual ("AssemblyStaticBlue", props [12].Name, "#H14");
-#else
-                       Assert.AreEqual ("FamilyStaticBlue", props [8].Name, "#H10");
-                       Assert.AreEqual ("FamANDAssemStaticBlue", props [9].Name, "#H11");
-                       Assert.AreEqual ("FamORAssemStaticBlue", props [10].Name, "#H12");
-#endif
 
                        flags = BindingFlags.Instance | BindingFlags.NonPublic |
                                BindingFlags.DeclaredOnly;
@@ -6296,11 +6146,7 @@ namespace MonoTests.System.Reflection.Emit
                                BindingFlags.Public;
                        props = greenType.GetProperties (flags);
 
-#if NET_2_0
                        Assert.AreEqual (16, props.Length, "#M1");
-#else
-                       Assert.AreEqual (14, props.Length, "#M1");
-#endif
                        Assert.AreEqual ("PrivateInstanceGreen", props [0].Name, "#M2");
                        Assert.AreEqual ("FamilyInstanceGreen", props [1].Name, "#M3");
                        Assert.AreEqual ("FamANDAssemInstanceGreen", props [2].Name, "#M4");
@@ -6311,19 +6157,12 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.AreEqual ("FamANDAssemInstanceRed", props [7].Name, "#M9");
                        Assert.AreEqual ("FamORAssemInstanceRed", props [8].Name, "#M10");
                        Assert.AreEqual ("PublicInstanceRed", props [9].Name, "#M11");
-#if NET_2_0
                        Assert.AreEqual ("AssemblyInstanceRed", props [10].Name, "#M12");
                        Assert.AreEqual ("FamilyInstanceBlue", props [11].Name, "#M13");
                        Assert.AreEqual ("FamANDAssemInstanceBlue", props [12].Name, "#M14");
                        Assert.AreEqual ("FamORAssemInstanceBlue", props [13].Name, "#M15");
                        Assert.AreEqual ("PublicInstanceBlue", props [14].Name, "#M16");
                        Assert.AreEqual ("AssemblyInstanceBlue", props [15].Name, "#M17");
-#else
-                       Assert.AreEqual ("FamilyInstanceBlue", props [10].Name, "#M12");
-                       Assert.AreEqual ("FamANDAssemInstanceBlue", props [11].Name, "#M13");
-                       Assert.AreEqual ("FamORAssemInstanceBlue", props [12].Name, "#M14");
-                       Assert.AreEqual ("PublicInstanceBlue", props [13].Name, "#M15");
-#endif
 
                        flags = BindingFlags.Static | BindingFlags.NonPublic |
                                BindingFlags.Public;
@@ -6444,21 +6283,13 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.IsNotNull (greenType.GetMethod ("GetFamANDAssemInstanceBlue", flags), "#A3");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamORAssemInstanceBlue", flags), "#A4");
                        Assert.IsNull (greenType.GetMethod ("GetPublicInstanceBlue", flags), "#A5");
-#if NET_2_0
                        Assert.IsNotNull (greenType.GetMethod ("GetAssemblyInstanceBlue", flags), "#A6");
-#else
-                       Assert.IsNull (greenType.GetMethod ("GetAssemblyInstanceBlue", flags), "#A6");
-#endif
                        Assert.IsNull (greenType.GetMethod ("GetPrivateInstanceRed", flags), "#A7");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamilyInstanceRed", flags), "#A8");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamANDAssemInstanceRed", flags), "#A9");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamORAssemInstanceRed", flags), "#A10");
                        Assert.IsNull (greenType.GetMethod ("GetPublicInstanceRed", flags), "#A11");
-#if NET_2_0
                        Assert.IsNotNull (greenType.GetMethod ("GetAssemblyInstanceRed", flags), "#A12");
-#else
-                       Assert.IsNull (greenType.GetMethod ("GetAssemblyInstanceRed", flags), "#A12");
-#endif
                        Assert.IsNotNull (greenType.GetMethod ("GetPrivateInstanceGreen", flags), "#A13");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamilyInstanceGreen", flags), "#A14");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamANDAssemInstanceGreen", flags), "#A15");
@@ -6609,21 +6440,13 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.IsNotNull (greenType.GetMethod ("GetFamANDAssemInstanceBlue", flags), "#E3");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamORAssemInstanceBlue", flags), "#E4");
                        Assert.IsNull (greenType.GetMethod ("GetPublicInstanceBlue", flags), "#E5");
-#if NET_2_0
                        Assert.IsNotNull (greenType.GetMethod ("GetAssemblyInstanceBlue", flags), "#E6");
-#else
-                       Assert.IsNull (greenType.GetMethod ("GetAssemblyInstanceBlue", flags), "#E6");
-#endif
                        Assert.IsNull (greenType.GetMethod ("GetPrivateInstanceRed", flags), "#E7");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamilyInstanceRed", flags), "#E8");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamANDAssemInstanceRed", flags), "#E9");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamORAssemInstanceRed", flags), "#E10");
                        Assert.IsNull (greenType.GetMethod ("GetPublicInstanceRed", flags), "#E11");
-#if NET_2_0
                        Assert.IsNotNull (greenType.GetMethod ("GetAssemblyInstanceRed", flags), "#E12");
-#else
-                       Assert.IsNull (greenType.GetMethod ("GetAssemblyInstanceRed", flags), "#E12");
-#endif
                        Assert.IsNotNull (greenType.GetMethod ("GetPrivateInstanceGreen", flags), "#E13");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamilyInstanceGreen", flags), "#E14");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamANDAssemInstanceGreen", flags), "#E15");
@@ -6755,21 +6578,13 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.IsNotNull (greenType.GetMethod ("GetFamANDAssemStaticBlue", flags), "#H21");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamORAssemStaticBlue", flags), "#H22");
                        Assert.IsNull (greenType.GetMethod ("GetPublicStaticBlue", flags), "#H23");
-#if NET_2_0
                        Assert.IsNotNull (greenType.GetMethod ("GetAssemblyStaticBlue", flags), "#H24");
-#else
-                       Assert.IsNull (greenType.GetMethod ("GetAssemblyStaticBlue", flags), "#H24");
-#endif
                        Assert.IsNull (greenType.GetMethod ("GetPrivateStaticRed", flags), "#H25");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamilyStaticRed", flags), "#H26");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamANDAssemStaticRed", flags), "#H27");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamORAssemStaticRed", flags), "#H28");
                        Assert.IsNull (greenType.GetMethod ("GetPublicStaticRed", flags), "#H29");
-#if NET_2_0
                        Assert.IsNotNull (greenType.GetMethod ("GetAssemblyStaticRed", flags), "#H30");
-#else
-                       Assert.IsNull (greenType.GetMethod ("GetAssemblyStaticRed", flags), "#H30");
-#endif
                        Assert.IsNotNull (greenType.GetMethod ("GetPrivateStaticGreen", flags), "#H31");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamilyStaticGreen", flags), "#H32");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamANDAssemStaticGreen", flags), "#H33");
@@ -6945,21 +6760,13 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.IsNotNull (greenType.GetMethod ("GetFamANDAssemInstanceBlue", flags), "#M3");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamORAssemInstanceBlue", flags), "#M4");
                        Assert.IsNotNull (greenType.GetMethod ("GetPublicInstanceBlue", flags), "#M5");
-#if NET_2_0
                        Assert.IsNotNull (greenType.GetMethod ("GetAssemblyInstanceBlue", flags), "#M6");
-#else
-                       Assert.IsNull (greenType.GetMethod ("GetAssemblyInstanceBlue", flags), "#M6");
-#endif
                        Assert.IsNull (greenType.GetMethod ("GetPrivateInstanceRed", flags), "#M7");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamilyInstanceRed", flags), "#M8");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamANDAssemInstanceRed", flags), "#M9");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamORAssemInstanceRed", flags), "#M10");
                        Assert.IsNotNull (greenType.GetMethod ("GetPublicInstanceRed", flags), "#M11");
-#if NET_2_0
                        Assert.IsNotNull (greenType.GetMethod ("GetAssemblyInstanceRed", flags), "#M12");
-#else
-                       Assert.IsNull (greenType.GetMethod ("GetAssemblyInstanceRed", flags), "#M12");
-#endif
                        Assert.IsNotNull (greenType.GetMethod ("GetPrivateInstanceGreen", flags), "#M13");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamilyInstanceGreen", flags), "#M14");
                        Assert.IsNotNull (greenType.GetMethod ("GetFamANDAssemInstanceGreen", flags), "#M15");
@@ -7229,21 +7036,13 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemInstanceBlue"), "#A3");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamORAssemInstanceBlue"), "#A4");
                        Assert.IsNull (GetMethodByName (methods, "GetPublicInstanceBlue"), "#A5");
-#if NET_2_0
                        Assert.IsNotNull (GetMethodByName (methods, "GetAssemblyInstanceBlue"), "#A6");
-#else
-                       Assert.IsNull (GetMethodByName (methods, "GetAssemblyInstanceBlue"), "#A6");
-#endif
                        Assert.IsNull (GetMethodByName (methods, "GetPrivateInstanceRed"), "#A7");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamilyInstanceRed"), "#A8");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemInstanceRed"), "#A9");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamORAssemInstanceRed"), "#A10");
                        Assert.IsNull (GetMethodByName (methods, "GetPublicInstanceRed"), "#A11");
-#if NET_2_0
                        Assert.IsNotNull (GetMethodByName (methods, "GetAssemblyInstanceRed"), "#A12");
-#else
-                       Assert.IsNull (GetMethodByName (methods, "GetAssemblyInstanceRed"), "#A12");
-#endif
                        Assert.IsNotNull (GetMethodByName (methods, "GetPrivateInstanceGreen"), "#A13");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamilyInstanceGreen"), "#A14");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemInstanceGreen"), "#A15");
@@ -7398,21 +7197,13 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemInstanceBlue"), "#E3");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamORAssemInstanceBlue"), "#E4");
                        Assert.IsNull (GetMethodByName (methods, "GetPublicInstanceBlue"), "#E5");
-#if NET_2_0
                        Assert.IsNotNull (GetMethodByName (methods, "GetAssemblyInstanceBlue"), "#E6");
-#else
-                       Assert.IsNull (GetMethodByName (methods, "GetAssemblyInstanceBlue"), "#E6");
-#endif
                        Assert.IsNull (GetMethodByName (methods, "GetPrivateInstanceRed"), "#E7");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamilyInstanceRed"), "#E8");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemInstanceRed"), "#E9");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamORAssemInstanceRed"), "#E10");
                        Assert.IsNull (GetMethodByName (methods, "GetPublicInstanceRed"), "#E11");
-#if NET_2_0
                        Assert.IsNotNull (GetMethodByName (methods, "GetAssemblyInstanceRed"), "#E12");
-#else
-                       Assert.IsNull (GetMethodByName (methods, "GetAssemblyInstanceRed"), "#E12");
-#endif
                        Assert.IsNotNull (GetMethodByName (methods, "GetPrivateInstanceGreen"), "#E13");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamilyInstanceGreen"), "#E14");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemInstanceGreen"), "#E15");
@@ -7547,21 +7338,13 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemStaticBlue"), "#H21");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamORAssemStaticBlue"), "#H22");
                        Assert.IsNull (GetMethodByName (methods, "GetPublicStaticBlue"), "#H23");
-#if NET_2_0
                        Assert.IsNotNull (GetMethodByName (methods, "GetAssemblyStaticBlue"), "#H24");
-#else
-                       Assert.IsNull (GetMethodByName (methods, "GetAssemblyStaticBlue"), "#H24");
-#endif
                        Assert.IsNull (GetMethodByName (methods, "GetPrivateStaticRed"), "#H25");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamilyStaticRed"), "#H26");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemStaticRed"), "#H27");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamORAssemStaticRed"), "#H28");
                        Assert.IsNull (GetMethodByName (methods, "GetPublicStaticRed"), "#H29");
-#if NET_2_0
                        Assert.IsNotNull (GetMethodByName (methods, "GetAssemblyStaticRed"), "#H30");
-#else
-                       Assert.IsNull (GetMethodByName (methods, "GetAssemblyStaticRed"), "#H30");
-#endif
                        Assert.IsNotNull (GetMethodByName (methods, "GetPrivateStaticGreen"), "#H31");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamilyStaticGreen"), "#H32");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemStaticGreen"), "#H33");
@@ -7742,21 +7525,13 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemInstanceBlue"), "#M3");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamORAssemInstanceBlue"), "#M4");
                        Assert.IsNotNull (GetMethodByName (methods, "GetPublicInstanceBlue"), "#M5");
-#if NET_2_0
                        Assert.IsNotNull (GetMethodByName (methods, "GetAssemblyInstanceBlue"), "#M6");
-#else
-                       Assert.IsNull (GetMethodByName (methods, "GetAssemblyInstanceBlue"), "#M6");
-#endif
                        Assert.IsNull (GetMethodByName (methods, "GetPrivateInstanceRed"), "#M7");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamilyInstanceRed"), "#M8");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemInstanceRed"), "#M9");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamORAssemInstanceRed"), "#M10");
                        Assert.IsNotNull (GetMethodByName (methods, "GetPublicInstanceRed"), "#M11");
-#if NET_2_0
                        Assert.IsNotNull (GetMethodByName (methods, "GetAssemblyInstanceRed"), "#M12");
-#else
-                       Assert.IsNull (GetMethodByName (methods, "GetAssemblyInstanceRed"), "#M12");
-#endif
                        Assert.IsNotNull (GetMethodByName (methods, "GetPrivateInstanceGreen"), "#M13");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamilyInstanceGreen"), "#M14");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemInstanceGreen"), "#M15");
@@ -7979,21 +7754,13 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemInstanceBlue"), "#A3");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamORAssemInstanceBlue"), "#A4");
                        Assert.IsNull (GetMethodByName (methods, "GetPublicInstanceBlue"), "#A5");
-#if NET_2_0
                        Assert.IsNotNull (GetMethodByName (methods, "GetAssemblyInstanceBlue"), "#A6");
-#else
-                       Assert.IsNull (GetMethodByName (methods, "GetAssemblyInstanceBlue"), "#A6");
-#endif
                        Assert.IsNull (GetMethodByName (methods, "GetPrivateInstanceRed"), "#A7");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamilyInstanceRed"), "#A8");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemInstanceRed"), "#A9");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamORAssemInstanceRed"), "#A10");
                        Assert.IsNull (GetMethodByName (methods, "GetPublicInstanceRed"), "#A11");
-#if NET_2_0
                        Assert.IsNotNull (GetMethodByName (methods, "GetAssemblyInstanceRed"), "#A12");
-#else
-                       Assert.IsNull (GetMethodByName (methods, "GetAssemblyInstanceRed"), "#A12");
-#endif
                        Assert.IsNotNull (GetMethodByName (methods, "GetPrivateInstanceGreen"), "#A13");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamilyInstanceGreen"), "#A14");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemInstanceGreen"), "#A15");
@@ -8148,21 +7915,13 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemInstanceBlue"), "#E3");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamORAssemInstanceBlue"), "#E4");
                        Assert.IsNull (GetMethodByName (methods, "GetPublicInstanceBlue"), "#E5");
-#if NET_2_0
                        Assert.IsNotNull (GetMethodByName (methods, "GetAssemblyInstanceBlue"), "#E6");
-#else
-                       Assert.IsNull (GetMethodByName (methods, "GetAssemblyInstanceBlue"), "#E6");
-#endif
                        Assert.IsNull (GetMethodByName (methods, "GetPrivateInstanceRed"), "#E7");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamilyInstanceRed"), "#E8");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemInstanceRed"), "#E9");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamORAssemInstanceRed"), "#E10");
                        Assert.IsNull (GetMethodByName (methods, "GetPublicInstanceRed"), "#E11");
-#if NET_2_0
                        Assert.IsNotNull (GetMethodByName (methods, "GetAssemblyInstanceRed"), "#E12");
-#else
-                       Assert.IsNull (GetMethodByName (methods, "GetAssemblyInstanceRed"), "#E12");
-#endif
                        Assert.IsNotNull (GetMethodByName (methods, "GetPrivateInstanceGreen"), "#E13");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamilyInstanceGreen"), "#E14");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemInstanceGreen"), "#E15");
@@ -8297,21 +8056,13 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemStaticBlue"), "#H21");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamORAssemStaticBlue"), "#H22");
                        Assert.IsNull (GetMethodByName (methods, "GetPublicStaticBlue"), "#H23");
-#if NET_2_0
                        Assert.IsNotNull (GetMethodByName (methods, "GetAssemblyStaticBlue"), "#H24");
-#else
-                       Assert.IsNull (GetMethodByName (methods, "GetAssemblyStaticBlue"), "#H24");
-#endif
                        Assert.IsNull (GetMethodByName (methods, "GetPrivateStaticRed"), "#H25");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamilyStaticRed"), "#H26");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemStaticRed"), "#H27");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamORAssemStaticRed"), "#H28");
                        Assert.IsNull (GetMethodByName (methods, "GetPublicStaticRed"), "#H29");
-#if NET_2_0
                        Assert.IsNotNull (GetMethodByName (methods, "GetAssemblyStaticRed"), "#H30");
-#else
-                       Assert.IsNull (GetMethodByName (methods, "GetAssemblyStaticRed"), "#H30");
-#endif
                        Assert.IsNotNull (GetMethodByName (methods, "GetPrivateStaticGreen"), "#H31");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamilyStaticGreen"), "#H32");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemStaticGreen"), "#H33");
@@ -8492,21 +8243,13 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemInstanceBlue"), "#M3");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamORAssemInstanceBlue"), "#M4");
                        Assert.IsNotNull (GetMethodByName (methods, "GetPublicInstanceBlue"), "#M5");
-#if NET_2_0
                        Assert.IsNotNull (GetMethodByName (methods, "GetAssemblyInstanceBlue"), "#M6");
-#else
-                       Assert.IsNull (GetMethodByName (methods, "GetAssemblyInstanceBlue"), "#M6");
-#endif
                        Assert.IsNull (GetMethodByName (methods, "GetPrivateInstanceRed"), "#M7");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamilyInstanceRed"), "#M8");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemInstanceRed"), "#M9");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamORAssemInstanceRed"), "#M10");
                        Assert.IsNotNull (GetMethodByName (methods, "GetPublicInstanceRed"), "#M11");
-#if NET_2_0
                        Assert.IsNotNull (GetMethodByName (methods, "GetAssemblyInstanceRed"), "#M12");
-#else
-                       Assert.IsNull (GetMethodByName (methods, "GetAssemblyInstanceRed"), "#M12");
-#endif
                        Assert.IsNotNull (GetMethodByName (methods, "GetPrivateInstanceGreen"), "#M13");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamilyInstanceGreen"), "#M14");
                        Assert.IsNotNull (GetMethodByName (methods, "GetFamANDAssemInstanceGreen"), "#M15");
@@ -8822,19 +8565,8 @@ namespace MonoTests.System.Reflection.Emit
                                // Could not load type '...' from assembly
                                // 'MonoTests.System.Reflection.Emit.TypeBuilderTest, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
                        }
-#if NET_2_0
                        Assert.IsTrue (typeBuilder.IsCreated (), "#2");
                        Assert.IsNull (typeBuilder.CreateType (), "#3");
-#else
-                       try {
-                               typeBuilder.CreateType ();
-                       } catch (InvalidOperationException ex) {
-                               // Unable to change after type has been created
-                               Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2");
-                               Assert.IsNull (ex.InnerException, "#B3");
-                               Assert.IsNotNull (ex.Message, "#B4");
-                       }
-#endif
                }
 
                [Test]
@@ -9185,7 +8917,6 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.IsFalse (typeof (Baz []).IsAssignableFrom (module.GetType (
                                tb3.FullName + "[]")), "#R3");
 
-#if NET_2_0
                        TypeBuilder tb4 = module.DefineType (genTypeName (),
                                TypeAttributes.Public, null,
                                new Type [] { typeof (IWater) });
@@ -9196,7 +8927,6 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.IsFalse (typeof (IComparable).IsAssignableFrom (inst));
                        // This returns True if CreateType () is called _before_ MakeGenericType...
                        //Assert.IsFalse (typeof (IWater).IsAssignableFrom (inst));
-#endif
                }
 
                [Test]
@@ -9439,9 +9169,6 @@ namespace MonoTests.System.Reflection.Emit
                }
 
                [Test]
-#if ONLY_1_1
-               [Category ("NotDotNet")] // Parent type was not extensible by the given type
-#endif
                [Category ("NotWorking")]
                public void CreateType_Interface_ParentInvalid ()
                {
@@ -9537,7 +9264,6 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.IsNull (emitted_type.BaseType, "#B2");
                }
 
-#if NET_2_0
                [Test]
                [Category ("NotWorking")]
                public void DefineGenericParameters_AlreadyDefined ()
@@ -10013,7 +9739,6 @@ namespace MonoTests.System.Reflection.Emit
                        int[] res = (int[])t.GetMethod ("Test").Invoke (null, new object[0]);
                        //Console.WriteLine (res[0]);
                }
-#endif
 
                public interface IDelegateFactory
                {
@@ -10075,7 +9800,6 @@ namespace MonoTests.System.Reflection.Emit
                        Assert.IsTrue (typeof (EmptyInterface).IsAssignableFrom (t2));
                }
 
-#if NET_2_0
 
                [Test] //bug #430508
                public void MakeGenericTypeRespectBaseType ()
@@ -10251,7 +9975,6 @@ namespace MonoTests.System.Reflection.Emit
 
                        Assert.AreEqual (0, result, "#1");
                }
-#endif
 
                static MethodInfo GetMethodByName (MethodInfo [] methods, string name)
                {
@@ -10667,7 +10390,6 @@ namespace MonoTests.System.Reflection.Emit
                        eb.SetAddOnMethod (mb);
                }
 
-#if NET_2_0
                static TypeBuilder Resolve1_Tb;
                static bool Resolve1_Called;
 
@@ -10702,7 +10424,6 @@ namespace MonoTests.System.Reflection.Emit
 
                        Assert.IsTrue (Resolve1_Called);
                }
-#endif
 
                [Test]
                public void CreateConcreteTypeWithAbstractMethod ()
@@ -10746,7 +10467,7 @@ namespace MonoTests.System.Reflection.Emit
 
                        Assert.AreNotSame (arg0, gps [0], "#1");
                }
-#if NET_2_0
+
                [Test]
                public void DeclaringMethodReturnsNull ()
                {
@@ -10901,9 +10622,49 @@ namespace MonoTests.System.Reflection.Emit
                        tb.CreateType ();
                        Assert.IsNotNull (tb.IsDefined (typeof (string), true), "#2");
                }
-#endif
-#if NET_2_0
-#if !WINDOWS
+
+               [Test] //Bug #594728
+               public void IsSubclassOfWorksIfSetParentIsCalledOnParent ()
+               {
+                       var tb_a = module.DefineType ("A", TypeAttributes.Public);
+                       var tb_b = module.DefineType ("B", TypeAttributes.Public);
+       
+                       tb_b.SetParent (tb_a);
+                       tb_a.SetParent (typeof (Attribute));
+       
+                       Assert.IsTrue (tb_b.IsSubclassOf (tb_a), "#1");
+                       Assert.IsTrue (tb_b.IsSubclassOf (typeof (Attribute)), "#2");
+                       Assert.IsFalse (tb_a.IsSubclassOf (tb_b), "#3");
+       
+       
+                       var a = tb_a.CreateType ();
+                       var b = tb_b.CreateType ();
+       
+                       Assert.IsTrue (b.IsSubclassOf (a), "#4");
+                       Assert.IsTrue (b.IsSubclassOf (typeof (Attribute)), "#5");
+                       Assert.IsFalse (a.IsSubclassOf (b), "#6");
+               }
+
+               [Test]
+               public void DefinedDefaultConstructorWorksWithGenericBaseType ()
+               {
+                       AssemblyName assemblyName = new AssemblyName ("a");
+                       AssemblyBuilder ass = AppDomain.CurrentDomain.DefineDynamicAssembly (assemblyName, AssemblyBuilderAccess.RunAndSave);
+                       var mb = ass.DefineDynamicModule ("a.dll");
+
+                       var tb = mb.DefineType ("Base");
+                       tb.DefineGenericParameters ("F");
+
+                       var inst = tb.MakeGenericType (typeof (int));
+                       var tb2 = mb.DefineType ("Child", TypeAttributes.Public, inst);
+
+                       tb.CreateType ();
+                       var res = tb2.CreateType ();
+
+                       Assert.IsNotNull (res, "#1");
+                       Assert.AreEqual (1, res.GetConstructors ().Length, "#2");
+               }
+
                /* 
                 * Tests for passing user types to Ref.Emit. Currently these only test
                 * whenever the runtime code can handle them without crashing, since we
@@ -10911,6 +10672,7 @@ namespace MonoTests.System.Reflection.Emit
                 * These tests are disabled for windows since the MS runtime trips on them.
                 */
                [Test]
+               [Category ("NotDotNet")] //Proper UT handling is a mono extension to SRE bugginess
                public void UserTypes () {
                        TypeDelegator t = new TypeDelegator (typeof (int));
 
@@ -10943,7 +10705,6 @@ namespace MonoTests.System.Reflection.Emit
                        } catch {
                        }
 
-#if !WINDOWS
                        try {
                                /* This is mono only */
                                UnmanagedMarshal m = UnmanagedMarshal.DefineCustom (t, "foo", "bar", Guid.Empty);
@@ -10953,7 +10714,6 @@ namespace MonoTests.System.Reflection.Emit
                                tb.CreateType ();
                        } catch {
                        }
-#endif
 
                        try {
                                /* Properties */
@@ -11105,8 +10865,6 @@ namespace MonoTests.System.Reflection.Emit
                        } catch {
                        }
                }
-#endif
-#endif
 
                //Test for #572660
         [Test]
@@ -11120,5 +10878,16 @@ namespace MonoTests.System.Reflection.Emit
                        var fooType = typeBuilder.CreateType();
                        Assert.AreSame(fooType.MakeArrayType(), fooType.GetField("Foos").FieldType);
         }
+
+
+               [Test] //Test for #422113
+               [ExpectedException (typeof (TypeLoadException))]
+               public void CreateInstanceOfIncompleteType ()
+               {
+                       TypeBuilder tb = module.DefineType (genTypeName (), TypeAttributes.Class, null, new Type[] { typeof (IComparable) });
+                       Type proxyType = tb.CreateType();
+                       Activator.CreateInstance(proxyType);
+               }
+
        }
 }
index 80e11fad53678bf596757a6b9c96e2279bf28466..b826aec74367c815853802fe406a968fd77535f1 100644 (file)
@@ -98,7 +98,9 @@ public class AssemblyNameTest {
                0x1A, 0x56, 0x76, 0x43, 0xDB, 0x64, 0x86, 0x41, 0x64, 0x8D,
                0x4C, 0x91, 0x83, 0x4E, 0xF5, 0x6C };
 
+#if !NET_2_0
        static byte [] kp_token = { 0xff, 0xef, 0x94, 0x53, 0x67, 0x69, 0xda, 0x06 };
+#endif
 
        static byte [] publicKey1 = {
                0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00,
@@ -138,7 +140,9 @@ public class AssemblyNameTest {
                0x50, 0xa4, 0x4d, 0x8b, 0x8a, 0x58, 0x17, 0x70, 0xa4, 0x53,
                0xe4, 0xdc, 0x73, 0x5d, 0x8c, 0x4e, 0xb8, 0xd3, 0xa9, 0xbf };
 
+#if !NET_2_0
        static byte [] pk_token2 = { 0x22, 0x7c, 0x9c, 0x2c, 0x3c, 0x00, 0x63, 0xe9 };
+#endif
 
        static byte [] publicKey3 = {
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00,
index afcb4c996a90e94feef1ed864e837bf5e0c45543..4237469a18a082fa9229f7cc401194c7800474e5 100644 (file)
@@ -218,7 +218,7 @@ namespace MonoTests.System.Reflection
                        Assert.IsTrue (corlib_test.GetReferencedAssemblies ().Length > 0, "GetReferencedAssemblies");
                        Assert.AreEqual (0, corlib_test.HostContext, "HostContext");
 #if NET_4_0
-                       Assert.AreEqual ("v4.0.21006", corlib_test.ImageRuntimeVersion, "ImageRuntimeVersion");
+                       Assert.AreEqual ("v4.0.30128", corlib_test.ImageRuntimeVersion, "ImageRuntimeVersion");
 #else
                        Assert.AreEqual ("v2.0.50727", corlib_test.ImageRuntimeVersion, "ImageRuntimeVersion");
 #endif
@@ -421,7 +421,7 @@ namespace MonoTests.System.Reflection
                [Test]
                public void LoadWithPartialName ()
                {
-                       string [] names = { "corlib_test_net_1_1", "corlib_test_net_2_0", "corlib_plattest" };
+                       string [] names = { "corlib_test_net_1_1", "corlib_test_net_2_0", "corlib_test_net_4_0", "corlib_plattest" };
 
                        foreach (string s in names)
                                if (Assembly.LoadWithPartialName (s) != null)
@@ -1089,21 +1089,26 @@ namespace MonoTests.System.Reflection
                }
 #endif // TARGET_JVM
 
-#if NET_2_0
                [Test]
                public void ManifestModule ()
                {
                        Assembly assembly = typeof (int).Assembly;
                        Module module = assembly.ManifestModule;
                        Assert.IsNotNull (module, "#1");
+
+#if NET_4_0
+                       Assert.AreEqual ("MonoModule", module.GetType ().Name, "#2");
+#else
                        Assert.AreEqual (typeof (Module), module.GetType (), "#2");
+#endif
+
                        Assert.AreEqual ("mscorlib.dll", module.Name, "#3");
                        Assert.IsFalse (module.IsResource (), "#4");
                        Assert.IsTrue (assembly.GetModules ().Length > 0, "#5");
                        Assert.AreSame (module, assembly.GetModules () [0], "#6");
                        Assert.AreSame (module, assembly.ManifestModule, "#7");
                }
-#endif
+
 
                [Serializable ()]
                private class AssemblyResolveHandler
index 222af6bf688cb4dfb39e43027f17bb4fef7d5213..a602169aee39cc912fea5591118d9a5ea1fff71b 100644 (file)
@@ -1309,5 +1309,28 @@ namespace MonoTests.System.Reflection
                        MethodInfo method = typeof (Foo).GetMethod ("Add");
                        method.Invoke((new Foo ()), 0, new Int32Binder (), new object [] {1, "2"}, null);
                }
+
+               public void Bug325306<T> (int a) {}
+               public void Bug325306_ (int a) {}
+
+               [Test] //bug 325306
+               [ExpectedException (typeof (AmbiguousMatchException))]
+               public void SelectMethodWithExactAndAmbiguousMethods ()
+               {
+                       var m = typeof (BinderTest).GetMethod ("Bug325306_");
+               BindingFlags flags = BindingFlags.Instance | BindingFlags.Public;
+                       AssertingBinder.Instance.SelectMethod (flags, new MethodBase [] {m, m}, new Type[] { typeof (int) }, null);
+               }
+
+               [Test] //bug 325306
+               [ExpectedException (typeof (AmbiguousMatchException))]
+               public void SelectMethodWithGmdAmbiguity ()
+               {
+                       var m0 = typeof (BinderTest).GetMethod ("Bug325306");
+                       var m1 = typeof (BinderTest).GetMethod ("Bug325306_");
+               BindingFlags flags = BindingFlags.Instance | BindingFlags.Public;
+       
+                       AssertingBinder.Instance.SelectMethod (flags, new MethodBase [] {m0, m1}, new Type[] { typeof (int) }, null);
+               }
        }
 }
index 70a0e519fbcabaee4c3e9192859b0ab019fe3429..7678814045a0cb87ecce16293ab305b1d0da48ad 100644 (file)
@@ -1,3 +1,27 @@
+2010-04-20 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * BinderTest.cs: Add tests for #325306.
+
+2010-04-19  Zoltan Varga  <vargaz@gmail.com>
+
+       * *.cs: Fix warnings.
+
+2010-04-08 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * FieldInfoTest.cs: Add tests for #594942.
+
+2010-04-01 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * AssemblyTest.cs: Fix one more tests under v4.
+
+2010-03-25 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       *AssemblyTest.cs: Fix one more tests under v4.
+
+2010-03-24 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       *AssemblyTest.cs: Fix some tests under v4.
+
 2010-03-11 Rodrigo Kumpera  <rkumpera@novell.com>
 
        * FieldInfoTest.cs: Remove invalid assert.
index 56bdf551dd5338b5e3dfe9d9aea2b965c0e1d894..5bc090f9565418bd23fa58d8944f5a7d04dbfad2 100644 (file)
@@ -457,7 +457,6 @@ namespace MonoTests.System.Reflection
                        typeof (FieldInfoTest).GetField ("non_const_field").GetRawConstantValue ();
                }
 
-#if NET_2_0
                [Test]
                [ExpectedException (typeof (InvalidOperationException))]
                public void GetValueOpenGeneric ()
@@ -476,14 +475,23 @@ namespace MonoTests.System.Reflection
                public void GetValueOnConstantOfOpenGeneric ()
                {
                        Assert.AreEqual (10, typeof(Foo<>).GetField ("constant").GetValue (null), "#1");
+                       Assert.AreEqual ("waa", typeof(Foo<>).GetField ("sconstant").GetValue (null), "#2");
+                       Assert.AreEqual (IntEnum.Third, typeof(Foo<>).GetField ("econstant").GetValue (null), "#3");
                }
 
                public class Foo<T>
                {
+                        /*
+                       The whole point of this field is to make sure we don't create the vtable layout
+                       when loading the value of constants for Foo<>. See bug #594942.
+
+                       */
+                       public T dummy;
                        public static int field;
                        public const int constant = 10;
+                       public const string sconstant = "waa";
+                       public const IntEnum econstant = IntEnum.Third;
                }
-#endif
 
                public enum IntEnum {
                        First = 1,
index 6f4c341b500cff60c69b351c9b2a2e5caef2c0a9..17b1b2896cc991a074685315ce524e14afd56eac 100644 (file)
@@ -20,10 +20,6 @@ using System.Runtime.InteropServices;
 using NUnit.Framework;
 using System.Runtime.CompilerServices;
 
-#if NET_2_0
-using System.Collections.Generic;
-#endif
-
 namespace MonoTests.System.Reflection.Emit
 {
 #if NET_2_0
index f7399ef8360c4f30f03e1a0866a390cff3ef73a4..3c274e7022ccd4dc0021d071ea927355371dfeb0 100644 (file)
@@ -1013,15 +1013,15 @@ namespace MonoTests.System.Resources
                        {
                        }
 
-                       public new string BaseNameField {
+                       public string BaseNameField {
                                get { return base.BaseNameField; }
                        }
 
-                       public new Assembly MainAssembly {
+                       public Assembly MainAssembly {
                                get { return base.MainAssembly; }
                        }
 
-                       public new Hashtable ResourceSets {
+                       public Hashtable ResourceSets {
                                get { return base.ResourceSets; }
                        }
 
index 9cedc70de8d81bbec892b1cc013752953cd07bbe..cc2488a647cd9a3f127a5a9491549966298c46ba 100644 (file)
@@ -87,6 +87,42 @@ namespace MonoTests.System.Runtime.InteropServices
                        ((IDisposable) sf).Dispose ();
                        Assert.AreEqual (sf.released, false, "r3");
                }
+
+               //
+               // This test does a DangerousAddRef on a new instance
+               // of a custom user Safe Handle, and it just happens
+               // that the default value for the handle is an invalid
+               // handle.
+               //
+               // .NET does not throw an exception in this case, so
+               // we should not either
+               //
+               [Test]
+               public void DangerousAddRefOnNewInstance ()
+               {
+                       var h = new IntPtrSafe ();
+                       var success = false;
+                       h.DangerousAddRef (ref success);
+                       Assert.AreEqual (success, true, "daroni");
+               }
+               
+               public class IntPtrSafe : SafeHandle {
+                       public IntPtrSafe() : base(IntPtr.Zero, true)
+                       {
+                       }
+
+                       protected override bool ReleaseHandle()
+                       {
+                               return true;
+                       }
+
+                       public IntPtr Handle { get; set; }
+
+                       public override bool IsInvalid
+                       {
+                               get { return Handle == IntPtr.Zero; }
+                       }
+               }
        }
 }
 
diff --git a/mcs/class/corlib/Test/System.Runtime.Versioning/FrameworkNameTest.cs b/mcs/class/corlib/Test/System.Runtime.Versioning/FrameworkNameTest.cs
deleted file mode 100644 (file)
index df2a5b1..0000000
+++ /dev/null
@@ -1,389 +0,0 @@
-//
-// System.Runtime.Versioning.FrameworkNameTest class
-//
-// Authors
-//     Marek Habersack <mhabersack@novell.com>
-//
-// Copyright (C) 2009 Novell, Inc (http://novell.com)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-// 
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-// 
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-//
-using System;
-using System.Runtime.Versioning;
-using System.Text;
-
-using NUnit.Framework;
-
-#if NET_4_0
-namespace MonoTests.System.Runtime.Versioning
-{
-       [TestFixture]
-       public class FrameworkNameTest
-       {
-               void Throws<TEx> (string message, Action code)
-               {
-                       bool failed = false;
-                       Exception exception = null;
-                       try {
-                               code ();
-                               failed = true;
-                       } catch (Exception ex) {
-                               if (ex.GetType () != typeof (TEx)) {
-                                       failed = true;
-                                       exception = ex;
-                               }
-                       }
-
-                       if (failed) {
-                               if (exception != null)
-                                       Assert.Fail ("{0}{1}Expected exception {2}, got {3}",
-                                                       message, Environment.NewLine, typeof (TEx), exception.GetType ());
-                               else
-                                       Assert.Fail ("{0}{1}Expected exception {2}",
-                                               message, Environment.NewLine, typeof (TEx));
-                       }
-               }
-               
-               [Test]
-               public void Constructor_String ()
-               {
-                       FrameworkName fn;
-
-                       Throws <ArgumentNullException> ("#A1", () => {
-                                       fn = new FrameworkName (null);
-                               });
-
-                       Throws<ArgumentException> ("#A1-1", () => {
-                                       fn = new FrameworkName (String.Empty);
-                               });
-
-                       Throws <ArgumentException> ("#A1-2", () => {
-                                       fn = new FrameworkName (".NETFramework");
-                               });
-
-                       Throws <ArgumentException> ("#A1-3", () => {
-                                       fn = new FrameworkName (".NETFramework,Ver=test");
-                               });
-
-                       Throws <ArgumentException> ("#A1-4", () => {
-                                       fn = new FrameworkName (".NETFramework,Version=A");
-                               });
-
-                       Throws <ArgumentException> ("#A1-5", () => {
-                                       fn = new FrameworkName ("Version=1.2,.NETFramework");
-                               });
-
-                       Throws <ArgumentException> ("#A1-6", () => {
-                                       fn = new FrameworkName (".NETFramework,Version=vA");
-                               });
-
-                       Throws <ArgumentException> ("#A1-7", () => {
-                                       fn = new FrameworkName (".NETFramework,Version=A.B");
-                               });
-
-                       Throws <ArgumentException> ("#A1-8", () => {
-                                       fn = new FrameworkName (".NETFramework,Version=vA.B");
-                               });
-
-                       Throws <ArgumentException> ("#A1-9", () => {
-                                       fn = new FrameworkName (".NETFramework,Version=VA.B");
-                               });
-
-                       Throws <ArgumentException> ("#A1-10", () => {
-                                       fn = new FrameworkName (".NETFramework,Version=vA.B.C");
-                               });
-
-                       Throws <ArgumentException> ("#A1-11", () => {
-                                       fn = new FrameworkName (".NETFramework,Version=vA.B.C.D");
-                               });
-
-                       Throws <ArgumentException> ("#A1-12", () => {
-                                       fn = new FrameworkName (".NETFramework,Version=2");
-                               });
-
-                       Throws <ArgumentException> ("#A1-13", () => {
-                                       fn = new FrameworkName (".NETFramework,Version=v2");
-                               });
-
-                       Throws <ArgumentException> ("#A1-14", () => {
-                                       fn = new FrameworkName (".NETFramework,Version=v2.0.1.A");
-                               });
-
-                       Throws <ArgumentException> ("#A1-15", () => {
-                                       fn = new FrameworkName (".NETFramework,Version=v2.0.1.0,Some=value");
-                               });
-
-                       Throws <ArgumentException> ("#A1-16", () => {
-                                       fn = new FrameworkName (".NETFramework,Version=v2.0.1.0,Profile=profile name, Extra=value");
-                               });
-
-                       Throws <ArgumentException> ("#A1-17", () => {
-                                       fn = new FrameworkName (".NETFramework,Profile=profile name");
-                               });
-
-                       Throws <ArgumentException> ("#A1-18", () => {
-                                       fn = new FrameworkName ("Profile=profile name,.NETFramework,Version=v2.0.1.0");
-                               });
-
-                       Throws <ArgumentException> ("#A1-19", () => {
-                                       var n = new FrameworkName (".NETFramework, ,Version=v2.0.1.0");
-                               });
-
-                       Throws <ArgumentException> ("#A1-20", () => {
-                                       fn = new FrameworkName (".NETFramework,Version=v2..0.1.0");
-                               });
-
-                       Throws <ArgumentException> ("#A1-21", () => {
-                                       fn = new FrameworkName (".NETFramework,Version=v.0.1.0");
-                               });
-
-                       Throws <ArgumentException> ("#A1-22", () => {
-                                       fn = new FrameworkName (".NETFramework,Version=v1.-2.1.0");
-                               });
-
-                       Throws <ArgumentException> ("#A1-23", () => {
-                                       fn = new FrameworkName (".NETFramework,Version=v0.0.0.0.0");
-                               });
-
-                       Throws <ArgumentException> ("#A1-24", () => {
-                                       fn = new FrameworkName (".NETFramework,Version=vA.0.0.0,Version=v1.2.3.4");
-                               });
-
-                       Throws <ArgumentException> ("#A1-25", () => {
-                                       fn = new FrameworkName (".NETFramework,Version=v0.0.0.0,Version=vA.2.3.4");
-                               });
-
-                       Throws <ArgumentException> ("#A1-26", () => {
-                                       fn = new FrameworkName ("Version=1.2,profile=test profile");
-                               });
-
-                       Throws<ArgumentException> ("#A1-27", () => {
-                                       fn = new FrameworkName (".NETFramework,Version=");
-                               });
-
-                       fn = new FrameworkName (".NETFramework=test,Version=3.5");
-                       Assert.AreEqual (".NETFramework=test", fn.Identifier, "#A2-1");
-                       Assert.IsTrue (fn.Version == new Version (3, 5), "#A2-2");
-                       Assert.AreEqual (String.Empty, fn.Profile, "#A2-3");
-                       Assert.AreEqual (".NETFramework=test,Version=v3.5", fn.FullName, "#A3-4");
-                       
-                       fn = new FrameworkName (".NETFramework,Version=2.0");
-                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A3-1");
-                       Assert.IsTrue (fn.Version == new Version (2, 0), "#A3-2");
-                       Assert.AreEqual (String.Empty, fn.Profile, "#A3-3");
-                       Assert.AreEqual (".NETFramework,Version=v2.0", fn.FullName, "#A3-4");
-
-                       fn = new FrameworkName (".NETFramework,Version=v2.0");
-                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A4-1");
-                       Assert.IsTrue (fn.Version == new Version (2, 0), "#A4-2");
-                       Assert.AreEqual (String.Empty, fn.Profile, "#A4-3");
-                       Assert.AreEqual (".NETFramework,Version=v2.0", fn.FullName, "#A4-4");
-
-                       fn = new FrameworkName (".NETFramework,Version=v0.1");
-                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A5-1");
-                       Assert.IsTrue (fn.Version == new Version (0, 1), "#A5-2");
-                       Assert.AreEqual (String.Empty, fn.Profile, "#A5-3");
-                       Assert.AreEqual (".NETFramework,Version=v0.1", fn.FullName, "#A5-4");
-
-                       fn = new FrameworkName (".NETFramework,Version=v10.1");
-                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A6-1");
-                       Assert.IsTrue (fn.Version == new Version (10, 1), "#A6-2");
-                       Assert.AreEqual (String.Empty, fn.Profile, "#A6-3");
-                       Assert.AreEqual (".NETFramework,Version=v10.1", fn.FullName, "#A6-4");
-
-                       fn = new FrameworkName (".NETFramework,Version=V2.0");
-                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A7-1");
-                       Assert.IsTrue (fn.Version == new Version (2, 0), "#A7-2");
-                       Assert.AreEqual (String.Empty, fn.Profile, "#A7-3");
-                       Assert.AreEqual (".NETFramework,Version=v2.0", fn.FullName, "#A7-4");
-
-                       fn = new FrameworkName (".NETFramework,Version=v2.0.1");
-                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A8-1");
-                       Assert.IsTrue (fn.Version == new Version (2, 0, 1), "#A8-2");
-                       Assert.AreEqual (String.Empty, fn.Profile, "#A8-3");
-                       Assert.AreEqual (".NETFramework,Version=v2.0.1", fn.FullName, "#A8-4");
-
-                       fn = new FrameworkName (".NETFramework,Version=v2.0.1.0");
-                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A9-1");
-                       Assert.IsTrue (fn.Version == new Version (2, 0, 1, 0), "#A9-2");
-                       Assert.AreEqual (String.Empty, fn.Profile, "#A9-3");
-                       Assert.AreEqual (".NETFramework,Version=v2.0.1.0", fn.FullName, "#A9-4");
-
-                       fn = new FrameworkName (".NETFramework,Version=v2.0.1.0,Profile=profile name");
-                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A10-1");
-                       Assert.IsTrue (fn.Version == new Version (2, 0, 1, 0), "#A10-2");
-                       Assert.AreEqual ("profile name", fn.Profile, "#A10-3");
-                       Assert.AreEqual (".NETFramework,Version=v2.0.1.0,Profile=profile name", fn.FullName, "#A10-4");
-
-                       fn = new FrameworkName (".NETFramework,Version=v2. 0.1.0");
-                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A11-1");
-                       Assert.IsTrue (fn.Version == new Version (2, 0, 1, 0), "#A11-2");
-                       Assert.AreEqual (String.Empty, fn.Profile, "#A11-3");
-                       Assert.AreEqual (".NETFramework,Version=v2.0.1.0", fn.FullName, "#A11-4");
-
-                       fn = new FrameworkName (".NETFramework,Version=v0.0.0.0");
-                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A12-1");
-                       Assert.IsTrue (fn.Version == new Version (0, 0, 0, 0), "#A12-2");
-                       Assert.AreEqual (String.Empty, fn.Profile, "#A12-3");
-                       Assert.AreEqual (".NETFramework,Version=v0.0.0.0", fn.FullName, "#A12-4");
-
-                       fn = new FrameworkName (".NETFramework,Version=v0.0.0.0,Version=v1.2.3.4");
-                       Assert.AreEqual (".NETFramework", fn.Identifier, "#A13-1");
-                       Assert.IsTrue (fn.Version == new Version (1, 2, 3, 4), "#A13-2");
-                       Assert.AreEqual (String.Empty, fn.Profile, "#A13-3");
-                       Assert.AreEqual (".NETFramework,Version=v1.2.3.4", fn.FullName, "#A13-4");
-
-                       fn = new FrameworkName ("identifier,verSION=1.2,PRofiLE=test profile");
-                       Assert.AreEqual ("identifier", fn.Identifier, "#A14-1");
-                       Assert.IsTrue (fn.Version == new Version (1, 2), "#A14-2");
-                       Assert.AreEqual ("test profile", fn.Profile, "#A14-3");
-                       Assert.AreEqual ("identifier,Version=v1.2,Profile=test profile", fn.FullName, "#A14-4");
-
-                       fn = new FrameworkName ("identifier,Version=2.0,Profile=");
-                       Assert.AreEqual ("identifier", fn.Identifier, "#A15-1");
-                       Assert.IsTrue (fn.Version == new Version (2, 0), "#A15-2");
-                       Assert.AreEqual (String.Empty, fn.Profile, "#A15-3");
-                       Assert.AreEqual ("identifier,Version=v2.0", fn.FullName, "#A15-4");
-               }
-
-               [Test]
-               public void Constructor_String_Version ()
-               {
-                       FrameworkName fn;
-
-                       Throws <ArgumentNullException> ("#A1-1", () => {
-                                       fn = new FrameworkName (null, new Version (2, 0));
-                               });
-
-                       Throws <ArgumentNullException> ("#A1-2", () => {
-                                       fn = new FrameworkName ("identifier", null);
-                               });
-
-                       Throws <ArgumentException> ("#A1-3", () => {
-                                       fn = new FrameworkName (String.Empty, new Version (2, 0));
-                               });
-
-                       var v = new Version (1,2,3,4);
-                       fn = new FrameworkName ("identifier", v);
-                       Assert.AreEqual ("identifier", fn.Identifier, "#A2-1");
-                       Assert.IsTrue (fn.Version == v, "#A2-2");
-                       Assert.AreEqual (String.Empty, fn.Profile, "#A2-3");
-                       Assert.AreEqual ("identifier,Version=v1.2.3.4", fn.FullName, "#A2-4");
-
-                       fn = new FrameworkName ("identifier,v2.0", v);
-                       Assert.AreEqual ("identifier,v2.0", fn.Identifier, "#A3-1");
-                       Assert.IsTrue (fn.Version == v, "#A3-2");
-                       Assert.AreEqual (String.Empty, fn.Profile, "#A3-3");
-                       Assert.AreEqual ("identifier,v2.0,Version=v1.2.3.4", fn.FullName, "#A3-4");
-
-                       fn = new FrameworkName ("identifier,Version=v2.0", v);
-                       Assert.AreEqual ("identifier,Version=v2.0", fn.Identifier, "#A4-1");
-                       Assert.IsTrue (fn.Version == v, "#A4-2");
-                       Assert.AreEqual (String.Empty, fn.Profile, "#A4-3");
-                       Assert.AreEqual ("identifier,Version=v2.0,Version=v1.2.3.4", fn.FullName, "#A4-4");
-               }
-
-               [Test]
-               public void Constructor_String_Version_String ()
-               {
-                       FrameworkName fn;
-                       var v = new Version (1, 2, 3, 4);
-
-                       Throws <ArgumentNullException> ("#A1-1", () => {
-                                       fn = new FrameworkName (null, new Version (2, 0), "profile");
-                               });
-
-                       Throws <ArgumentNullException> ("#A1-2", () => {
-                                       fn = new FrameworkName ("identifier", null, "profile");
-                               });
-
-                       Throws <ArgumentException> ("#A1-3", () => {
-                                       fn = new FrameworkName (String.Empty, new Version (2, 0), "profile");
-                               });
-
-                       fn = new FrameworkName ("identifier,Version=v2.0", v, "Profile name");
-                       Assert.AreEqual ("identifier,Version=v2.0", fn.Identifier, "#A2-1");
-                       Assert.IsTrue (fn.Version == v, "#A2-2");
-                       Assert.AreEqual ("Profile name", fn.Profile, "#A2-3");
-                       Assert.AreEqual ("identifier,Version=v2.0,Version=v1.2.3.4,Profile=Profile name", fn.FullName, "#A2-4");
-
-                       fn = new FrameworkName ("identifier,v2.0,profile=test", v, "Profile name");
-                       Assert.AreEqual ("identifier,v2.0,profile=test", fn.Identifier, "#A3-1");
-                       Assert.IsTrue (fn.Version == v, "#A3-2");
-                       Assert.AreEqual ("Profile name", fn.Profile, "#A3-3");
-                       Assert.AreEqual ("identifier,v2.0,profile=test,Version=v1.2.3.4,Profile=Profile name", fn.FullName, "#A3-4");
-
-                       fn = new FrameworkName ("identifier,v2.0,profile=test", v, null);
-                       Assert.AreEqual ("identifier,v2.0,profile=test", fn.Identifier, "#A4-1");
-                       Assert.IsTrue (fn.Version == v, "#A4-2");
-                       Assert.AreEqual (String.Empty, fn.Profile, "#A4-3");
-                       Assert.AreEqual ("identifier,v2.0,profile=test,Version=v1.2.3.4", fn.FullName, "#A4-4");
-
-                       fn = new FrameworkName ("identifier,v2.0,profile=test", v, String.Empty);
-                       Assert.AreEqual ("identifier,v2.0,profile=test", fn.Identifier, "#A5-1");
-                       Assert.IsTrue (fn.Version == v, "#A5-2");
-                       Assert.AreEqual (String.Empty, fn.Profile, "#A5-3");
-                       Assert.AreEqual ("identifier,v2.0,profile=test,Version=v1.2.3.4", fn.FullName, "#A5-4");
-               }
-
-               [Test]
-               public void EqualityOperator ()
-               {
-                       var fn = new FrameworkName ("identifier,Version=v2.0");
-
-                       Assert.IsTrue (fn == new FrameworkName ("identifier,Version=v2.0"), "#A1");
-
-                       FrameworkName fn1 = null;
-                       FrameworkName fn2 = null;
-
-                       Assert.IsTrue (fn1 == fn2, "#A2");
-                       Assert.IsFalse (fn == new FrameworkName ("identifier,Version=v2.1"), "#A3");
-                       Assert.IsFalse (fn == null, "#A4");
-               }
-
-               [Test]
-               public void InequalityOperator ()
-               {
-                       var fn = new FrameworkName ("identifier,Version=v2.0");
-
-                       Assert.IsFalse (fn != new FrameworkName ("identifier,Version=v2.0"), "#A1");
-
-                       FrameworkName fn1 = null;
-                       FrameworkName fn2 = null;
-
-                       Assert.IsFalse (fn1 != fn2, "#A2");
-                       Assert.IsTrue (fn != new FrameworkName ("identifier,Version=v2.1"), "#A3");
-                       Assert.IsTrue (fn != null, "#A4");
-               }
-
-               [Test]
-               public void ToStringTest ()
-               {
-                       var fn = new FrameworkName (".NETFramework,Version=v2.0.1");
-                       Assert.AreEqual (".NETFramework,Version=v2.0.1", fn.FullName, "#A1-1");
-                       Assert.AreEqual (fn.FullName, fn.ToString (), "#A1-2");
-
-                       fn = new FrameworkName (".NETFramework,Version=v2.0.1.0");
-                       Assert.AreEqual (".NETFramework,Version=v2.0.1.0", fn.FullName, "#A2-1");
-                       Assert.AreEqual (fn.FullName, fn.ToString (), "#A2-2");
-               }
-       }
-}
-#endif
index 988631ffa60fbfddc7fffc4bf14eee24c5f99a92..271d3cc1b370dd895a23b51de5ef44903a192e3b 100644 (file)
@@ -1,3 +1,7 @@
+2010-03-24  Jérémie Laval  <jeremie.laval@gmail.com>
+
+       * SpinLockTests.cs: Add a correctness check unit test
+
 2010-03-08  Jérémie Laval  <jeremie.laval@gmail.com>
 
        * SpinLockTests.cs: Added unit tests for SpinLock
index 48149a3ddc1cf88c1997c32b8861106f15031b23..a7ef1cad00b5594e65a632fe8439cc1287f88942 100644 (file)
@@ -1,22 +1,22 @@
 #if NET_4_0
-// 
+//
 // SpinLockTests.cs
-//  
+//
 // Author:
 //       Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
-// 
+//
 // Copyright (c) 2010 Jérémie "Garuma" Laval
-// 
+//
 // Permission is hereby granted, free of charge, to any person obtaining a copy
 // of this software and associated documentation files (the "Software"), to deal
 // in the Software without restriction, including without limitation the rights
 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 // copies of the Software, and to permit persons to whom the Software is
 // furnished to do so, subject to the following conditions:
-// 
+//
 // The above copyright notice and this permission notice shall be included in
 // all copies or substantial portions of the Software.
-// 
+//
 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -30,35 +30,37 @@ using System.Threading;
 
 using NUnit.Framework;
 
+using MonoTests.System.Threading.Tasks;
+
 namespace MonoTests.System.Threading
 {
        [TestFixture]
        public class SpinLockTests
        {
                SpinLock sl;
-               
+
                [SetUp]
                public void Setup ()
                {
-                       sl = new SpinLock (false);
+                       sl = new SpinLock (true);
                }
-               
+
                [Test, ExpectedException (typeof (LockRecursionException))]
                public void RecursionExceptionTest ()
                {
                        sl = new SpinLock (true);
                        bool taken = false, taken2 = false;
-                       
+
                        sl.Enter (ref taken);
                        Assert.IsTrue (taken, "#1");
                        sl.Enter (ref taken2);
                }
-               
+
                [Test]
                public void SimpleEnterExitSchemeTest ()
                {
                        bool taken = false;
-                       
+
                        for (int i = 0; i < 50000; i++) {
                                sl.Enter (ref taken);
                                Assert.IsTrue (taken, "#" + i.ToString ());
@@ -66,51 +68,85 @@ namespace MonoTests.System.Threading
                                taken = false;
                        }
                }
-               
+
                [Test]
                public void SemanticCorrectnessTest ()
                {
+                       sl = new SpinLock (false);
+
                        bool taken = false;
                        bool taken2 = false;
-                       
+
                        sl.Enter (ref taken);
                        Assert.IsTrue (taken, "#1");
                        sl.TryEnter (ref taken2);
                        Assert.IsFalse (taken2, "#2");
                        sl.Exit ();
-                       
+
                        sl.TryEnter (ref taken2);
                        Assert.IsTrue (taken2, "#3");
                }
-               
+
                [Test, ExpectedException (typeof (ArgumentException))]
                public void FirstTakenParameterTest ()
                {
                        bool taken = true;
-                       
+
                        sl.Enter (ref taken);
                }
-               
+
                [Test, ExpectedException (typeof (ArgumentException))]
                public void SecondTakenParameterTest ()
                {
                        bool taken = true;
-                       
+
                        sl.TryEnter (ref taken);
                }
-               
+
+               internal class SpinLockWrapper
+               {
+                       public SpinLock Lock = new SpinLock (false);
+               }
+
+               [Test]
+               public void LockUnicityTest ()
+               {
+                       ParallelTestHelper.Repeat (delegate {
+                               int currentCount = 0;
+                               bool fail = false;
+                               SpinLockWrapper wrapper = new SpinLockWrapper ();
+
+                               ParallelTestHelper.ParallelStressTest (wrapper, delegate {
+                                       bool taken = false;
+                                       wrapper.Lock.Enter (ref taken);
+                                       int current = currentCount++;
+                                       if (current != 0)
+                                               fail = true;
+
+                                       SpinWait sw = new SpinWait ();
+                                       for (int i = 0; i < 200; i++)
+                                               sw.SpinOnce ();
+                                       currentCount -= 1;
+
+                                       wrapper.Lock.Exit ();
+                               }, 4);
+
+                               Assert.IsFalse (fail);
+                       }, 200);
+               }
+
                [Test]
                public void IsHeldByCurrentThreadTest ()
                {
                        bool lockTaken = false;
-                       
+
                        sl.Enter (ref lockTaken);
                        Assert.IsTrue (lockTaken, "#1");
                        Assert.IsTrue (sl.IsHeldByCurrentThread, "#2");
-                       
+
                        lockTaken = false;
                        sl = new SpinLock (true);
-                       
+
                        sl.Enter (ref lockTaken);
                        Assert.IsTrue (lockTaken, "#3");
                        Assert.IsTrue (sl.IsHeldByCurrentThread, "#4");
index f700fef53191160e28a820051cabacc40393ae1b..d6676e5c2b4e26b1e95b5c0b6099b1af5ead0e21 100644 (file)
@@ -64,7 +64,6 @@ namespace MonoTests.System {
        [TestFixture]
        public class ActivatorTest {
 
-               private string corlibLocation = typeof (string).Assembly.Location;
                private string testLocation = typeof (ActivatorTest).Assembly.Location;
 
                [Test]
@@ -379,5 +378,91 @@ namespace MonoTests.System {
                                                  BindingFlags.Public | BindingFlags.Instance, null, null, null,
                                                  new object [] {ModuleHandle.EmptyHandle}, null);
                }
+
+               public class ParamsConstructor {
+
+                       public int A;
+                       public string X;
+                       public string Y;
+
+                       public ParamsConstructor (int a, params string [] s)
+                       {
+                               A = a;
+
+                               Assert.IsNotNull (s);
+
+                               if (s.Length == 0)
+                                       return;
+
+                               X = s [0];
+
+                               if (s.Length == 1)
+                                       return;
+
+                               Y = s [1];
+                       }
+               }
+
+               [Test]
+               public void CreateInstanceParamsConstructor ()
+               {
+                       var a = (ParamsConstructor) Activator.CreateInstance (
+                               typeof (ParamsConstructor), new object [] { 42, "foo", "bar" });
+
+                       Assert.AreEqual (42, a.A);
+                       Assert.AreEqual ("foo", a.X);
+                       Assert.AreEqual ("bar", a.Y);
+
+                       a = (ParamsConstructor) Activator.CreateInstance (
+                               typeof (ParamsConstructor), new object [] { 42, "foo" });
+
+                       Assert.AreEqual (42, a.A);
+                       Assert.AreEqual ("foo", a.X);
+                       Assert.AreEqual (null, a.Y);
+
+                       a = (ParamsConstructor) Activator.CreateInstance (
+                               typeof (ParamsConstructor), new object [] { 42 });
+
+                       Assert.AreEqual (42, a.A);
+                       Assert.AreEqual (null, a.X);
+                       Assert.AreEqual (null, a.Y);
+               }
+
+               class SimpleParamsConstructor {
+
+                       public string X;
+                       public string Y;
+
+                       public SimpleParamsConstructor (params string [] s)
+                       {
+                               Assert.IsNotNull (s);
+
+                               if (s.Length == 0)
+                                       return;
+
+                               X = s [0];
+
+                               if (s.Length == 1)
+                                       return;
+
+                               Y = s [1];
+                       }
+               }
+
+               [Test]
+               public void CreateInstanceSimpleParamsConstructor ()
+               {
+                       var a = (SimpleParamsConstructor) Activator.CreateInstance (
+                               typeof (SimpleParamsConstructor), new object [] { "foo", "bar" });
+
+                       Assert.AreEqual ("foo", a.X);
+                       Assert.AreEqual ("bar", a.Y);
+
+                       a = (SimpleParamsConstructor) Activator.CreateInstance (
+                               typeof (SimpleParamsConstructor), new object [0]);
+
+                       Assert.AreEqual (null, a.X);
+                       Assert.AreEqual (null, a.Y);
+               }
        }
 }
index 14c67e4469fba87f6ff7d892124bb1d344e7b336..d40128416be9fb3ada3d529b5105bb0a789d59c2 100644 (file)
@@ -49,6 +49,11 @@ namespace MonoTests.System
                {
                        return true;
                }
+
+               public override int GetHashCode ()
+               {
+                       return 0;
+               }
        }
                
        //End Auxiliary Things
index da399cde42f64483132ebd22623cc19392dc2c03..9a4271672375875f4b5818b2e8e5bbca2542931d 100644 (file)
@@ -726,7 +726,6 @@ namespace MonoTests.System
                        Assert.IsFalse (a.Equals (null), "#8");
                }
 
-#if NET_2_0
                class UserType : TypeDelegator {
                        public int GetCattr1;
                        public int GetCattr2;
@@ -863,8 +862,44 @@ namespace MonoTests.System
                                Assert.Fail ("#1");
                        } catch (NotSupportedException) {}
                }
-#endif
 
+               [Test] //Regression test for #499569
+               public void GetCattrOnPropertyAndInheritance ()
+               {
+                       var m = typeof(Sub).GetProperty ("Name");
+                       var res = Attribute.GetCustomAttributes (m, typeof(MyAttribute), true);
+                       Assert.AreEqual (1, res.Length, "#1");
+               }
+
+               abstract class Abs
+               {
+                       public abstract string Name { get; set; }
+               }
+               
+               class Base: Abs
+               {
+                       [MyAttribute]
+                       public override string Name {
+                               get { return ""; }
+                               set {}
+                       }
+               }
+               
+               class Sub: Base
+               {
+                       public override string Name {
+                               get { return ""; }
+                               set {}
+                       }
+               }
+               
+               class MySubAttribute: MyAttribute
+               {
+               }
+               
+               class MyAttribute: Attribute
+               {
+               }
 
                private int GetAttributeCount (object[] attributes, Type attributeType)
                {
index b06c3fecf8b93908cb7bdf9365a39a85d069cd82..9d4fbb209a1fd7e7c6e9c4dff3bd5387edcd602b 100644 (file)
@@ -19,7 +19,6 @@ namespace MonoTests.System {
 
                const int SIZE = 10;
                byte [] byteArray  = new byte [SIZE];   // 8-bits unsigned integer array
-               float [] floatArray = new float [SIZE];
                
                [Test]
                public void BlockCopy ()
index 79b9842990bd6d08245252ad8fdc26ad8cae6a99..09b7bf5c8ff99aa473a5bb7454e15e5a9d839246 100644 (file)
@@ -1,3 +1,101 @@
+2010-04-25  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpanTest.cs: New test for ToString using custom formats.
+
+2010-04-22  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpanTest.cs: Update our test after the 4.0 release.
+
+2010-04-20 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * TypeTest.cs: Add tests for #331126.
+
+2010-04-20 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * TypeTest.cs: Fix the test suite.
+
+2010-04-19 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * TypeTest.cs: Add regression test for #473289.
+
+2010-04-19  Zoltan Varga  <vargaz@gmail.com>
+
+       * *.cs: Fix warnings.
+
+2010-04-19  Zoltan Varga  <vargaz@gmail.com>
+
+       * StringTest.cs: Add a test for #597604.
+
+2010-04-18  Zoltan Varga  <vargaz@gmail.com>
+
+       * CharTest.cs: Add missing [TestFixture] attribute.
+
+2010-04-16 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * TypeTest.cs: Add regression test for #484246.
+
+2010-04-16 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * AttributeTest.cs: Add regression test for #499569.
+
+2010-04-15  Jb Evain  <jbevain@novell.com>
+
+       * GuidTest.cs: add tests for net_4_0 ParseExact methods.
+
+2010-04-13  Zoltan Varga  <vargaz@gmail.com>
+
+       * ConvertTest.cs: Add a test for #596339.
+
+2010-04-12  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpanTest.cs: Remove "NotWorking" from our custom formats parse
+       methods, as well as augmenting the test with some new assertions, and
+       changing a pair to properly reflect what they are testing.
+
+2010-04-06  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpanTest.cs: Augment our ParseExactCustomFormats test - still
+       marked as NotWorking for now, but committing now in order to have the
+       tests ready.
+
+2010-04-01 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * TypeTest.cs: Fix test for v4 Equals behavior.
+
+2010-03-30  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpanTest.cs: New test for TryParseExact.
+
+2010-03-30  Jb Evain  <jbevain@novell.com>
+
+       * ActivatorTest.cs: add more tests to CreateInstance constructors
+       with params arrays.
+
+2010-03-30  Jb Evain  <jbevain@novell.com>
+
+       * ActivatorTest.cs: add tests for #591877.
+
+2010-03-29  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpan.cs: New test for ParseExact/TryParseExact.
+
+2010-03-26  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpanTest.cs: New assertion in our exception order test, to
+       assert that int32 overflow error has higher precedence in both 2.0 and
+       4.0 profiles.
+
+2010-03-23  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpan.cs: Add some new assertions for old/new stuff in
+       TimeSpan.
+
+2010-03-22  Carlos Alberto Cortez <calberto.cortez@gmail.com>
+
+       * TimeSpanTest.cs: It seems somebody forgot to actually mark the
+       TestParse method with TestAttribute. Also, add a bunch of asserions
+       to reflect the new behaviour for 4.0 in the needed test cases.
+
 2010-03-08  Carlos Alberto Cortez <calberto.cortez@gmail.com>
 
        * TimeSpanTest.cs: New tests for the 4.0 ToString overloads.
index 771c3ab52d7d065ef372fbeb7928e9e6ae2f62ac..30d9cd7f4bc94fe4b133cc74fca04e8c1ebe372e 100644 (file)
@@ -21,8 +21,6 @@ namespace MonoTests.System
        [TestFixture]
        public class CharCategoryTest 
        {
-               static char DSC = Path.DirectorySeparatorChar;
-
                delegate bool ComparisonMethod (char c);
 
                private void CompareWithDump (ComparisonMethod cm, string dump, bool testTrue)
index 6247d105352309c9be4fe97a10fa9d73f0ef7846..86a13812d726f575cb5f69f4da01b705a33bc5ae 100644 (file)
@@ -12,7 +12,7 @@ using System.Globalization;
 
 namespace MonoTests.System
 {
-
+[TestFixture]
 public class CharTest
 {
        [Test]
index 0598692b65bac280623c211efb2c47aa1b1e8973..7ba22472e9db4e3ff7868e1bfc03a4bebbfa1164 100644 (file)
@@ -4688,6 +4688,13 @@ namespace MonoTests.System {
                {
                        Convert.ChangeType ("this-is-a-string", typeof (Foo));
                }
+
+               [Test]
+               [ExpectedException (typeof (OverflowException))]
+               public void ToInt32_NaN ()
+               {
+                       Convert.ToInt32 (Double.NaN);
+               }
        }
 
        public class Image
index 8f0990c95caf35d4758772cd4847ad8de662ca94..b142eeb1969f7d95180e81de58d509a96781af7f 100644 (file)
@@ -7,7 +7,6 @@
 // Copyright (C) 2007 Novell, Inc (http://www.novell.com)
 //
 
-#if NET_2_0
 using System.Globalization;
 using NUnit.Framework;
 using System;
@@ -243,6 +242,17 @@ namespace MonoTests.System {
                                        Assert.AreEqual (dto, DateTimeOffset.ParseExact (serialized, format, fp), format);
                                }
                }
+
+               //
+               // Tests that we can parse the K format specifier which is a 4 digit offset
+               // see bug 589227
+               //
+               [Test]
+               public void ParseExactWithKFormat ()
+               {
+                       DateTimeOffset o = DateTimeOffset.ParseExact ("Wed Mar 17 22:25:08 +0000 2010", "ddd MMM d H:m:ss K yyyy", null);
+               }
+               
                [Test]
                public void ParseExactYearFormat ()
                {
@@ -638,5 +648,4 @@ namespace MonoTests.System {
                }
        }
 }
-#endif
 
index 51c1a225c2476c09a10fd0e8c50d8eb6c43cbfbc..245ed727877a5b5c3d48ca645848c9a5f8f74fe3 100644 (file)
@@ -289,5 +289,53 @@ namespace MonoTests.System {
                {
                        new Guid (0x00010203, 0x0405, 0x0607, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f).ToString ("This is invalid");
                }
+
+#if NET_4_0
+
+               /*
+                       N = new Guid ("000102030405060708090a0b0c0d0e0f"); 
+                       D = new Guid ("00010203-0405-0607-0809-0a0b0c0d0e0f"); 
+                       B = new Guid ("{00010203-0405-0607-0809-0A0B0C0D0E0F}"); 
+                       P = new Guid ("(00010203-0405-0607-0809-0A0B0C0D0E0F)");
+                       X = new Guid ("{0x00010203,0x0405,0x0607,{0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f}}");
+
+                       string expected = "00010203-0405-0607-0809-0a0b0c0d0e0f";
+               */
+
+               [Test]
+               public void ParseExact ()
+               {
+                       const string expected = "00010203-0405-0607-0809-0a0b0c0d0e0f";
+
+                       var guid = Guid.ParseExact ("000102030405060708090a0b0c0d0e0f", "N");
+                       Assert.AreEqual (expected, guid.ToString ());
+
+                       guid = Guid.ParseExact ("00010203-0405-0607-0809-0a0b0c0d0e0f", "D");
+                       Assert.AreEqual (expected, guid.ToString ());
+
+                       guid = Guid.ParseExact ("{00010203-0405-0607-0809-0A0B0C0D0E0F}", "B");
+                       Assert.AreEqual (expected, guid.ToString ());
+
+                       guid = Guid.ParseExact ("(00010203-0405-0607-0809-0A0B0C0D0E0F)", "P");
+                       Assert.AreEqual (expected, guid.ToString ());
+
+                       guid = Guid.ParseExact ("{0x00010203,0x0405,0x0607,{0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f}}", "X");
+                       Assert.AreEqual (expected, guid.ToString ());
+               }
+
+               [Test]
+               [ExpectedException (typeof (FormatException))]
+               public void ParseExactN ()
+               {
+                       Guid.ParseExact ("00010203-0405-0607-0809-0a0b0c0d0e0f", "N");
+               }
+
+               [Test]
+               [ExpectedException (typeof (FormatException))]
+               public void ParseExactD ()
+               {
+                       Guid.ParseExact ("{0x00010203,0x0405,0x0607,{0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f}}", "D");
+               }
+#endif
        }
 }
index c2038d20c7f80c85ec86d1a9b6ca9998d9d7625e..24b6566025493c84cac6e495e5e4f0c651b049d1 100644 (file)
@@ -310,6 +310,11 @@ public class Int64Test
                Assert.IsTrue(typeof(OverflowException) == e.GetType(), "#20");
        }
 
+       // Pass a DateTimeFormatInfo, it is unable to format
+       // numbers, but we should not crash
+       
+       Int64.Parse ("123", new DateTimeFormatInfo ());
+       
        Assert.AreEqual (734561, Int64.Parse ("734561\0"), "#21");
        Assert.AreEqual (734561, Int64.Parse ("734561\0\0\0    \0"), "#22");
        Assert.AreEqual (734561, Int64.Parse ("734561\0\0\0    "), "#23");
index 4f280d50b2211e10f8a90dd087c932c9ffd738de..d8f51a3b9995bd802bc1674fe0961846dc0fef82 100644 (file)
@@ -1,4 +1,4 @@
-// StringTest.cs - NUnit Test Cases for the System.String class
+// StringTest.cs - NUnit Test Cases for the System.String class
 //
 // Authors:
 //   Jeffrey Stedfast <fejj@ximian.com>
@@ -1595,6 +1595,12 @@ public class StringTest
                "Mono".IndexOf ("no", 1, 5, StringComparison.OrdinalIgnoreCase);
        }
 
+       [Test]
+       public void IndexOfStringComparisonCurrentCulture_Empty ()
+       {
+               Assert.AreEqual (1, "Mono".IndexOf ("", 1, StringComparison.CurrentCultureIgnoreCase));
+       }
+
        [Test]
        public void IndexOfStringComparison ()
        {
@@ -4260,6 +4266,56 @@ public class StringTest
                Assert.AreEqual (formKD, s.Normalize (NormalizationForm.FormKD), "#3");
                Assert.AreEqual (formKC, s.Normalize (NormalizationForm.FormKC), "#4");
        }
+
+       [Test] // bug #480152, test cases by David Mitchell
+       public void NormalizeFormD ()
+       {
+               Assert.AreEqual ("\u212B".Normalize (NormalizationForm.FormD), "\u0041\u030A", "#1");
+               Assert.AreEqual ("\u1E69".Normalize (NormalizationForm.FormD), "\u0073\u0323\u0307", "#2");
+               Assert.AreEqual ("\u1e4e".Normalize (NormalizationForm.FormD), "\u004f\u0303\u0308", "#3");
+               Assert.AreEqual ("\u1e2f".Normalize (NormalizationForm.FormD), "\u0069\u0308\u0301", "#4");
+       }
+
+       [Test] // bug #480152, test cases by David Mitchell
+       public void NormalizeFormC ()
+       {
+               Assert.AreEqual ("\u0041\u030a\u0061\u030a".Normalize (NormalizationForm.FormC), "\u00c5\u00e5", "#1");
+               Assert.AreEqual ("\u006E\u0303".Normalize (NormalizationForm.FormC), "\u00F1", "#2");
+               Assert.AreEqual ("\u03B7\u0313\u0300\u0345".Normalize (NormalizationForm.FormC), "\u1F92", "#3");
+       }
+
+        [Test] // bug #480152, test cases by Tom Philpot
+        public void NormalizeFormCCrashers ()
+        {
+               string[][] entries = new string[][] {
+                       new string[] { "\u05d0\u0307\u05dc", "#1" },
+                       new string[] { "\u05d0\u0307\u05dc\u05d9\u05d9\u05df", "#2" },
+                       new string[] { "\u05d4\u05d0\u0307\u05dc\u0307\u05d9\u0307\u05df\u0307", "#3" },
+                       new string[] { "\u05d9\u05e9\u05de\u05e2\u0307\u05d0\u0307\u05dc\u0307", "#4" },
+                       new string[] { "\u05d9\u05e9\u05e8\u05d0\u0307\u05dc\u0307", "#5" },
+               };
+
+               foreach (string[] entry in entries)
+                       entry [0].Normalize (NormalizationForm.FormC);
+       }
+
+       [Test]
+       public void NormalizeFormCHangul ()
+       {
+               Assert.AreEqual ("\u1100\u116C".Normalize (NormalizationForm.FormC), "\uAD34", "#1");
+               Assert.AreEqual ("\u1100\u116B\u11C2".Normalize (NormalizationForm.FormC), "\uAD33", "#2");
+               Assert.AreEqual ("\u1100!".Normalize (NormalizationForm.FormC), "\u1100!", "#3");
+               Assert.AreEqual ("\u1100\u116B!".Normalize (NormalizationForm.FormC), "\uAD18\u0021", "#4");
+               Assert.AreEqual ("!\u116C".Normalize (NormalizationForm.FormC), "!\u116C", "#5");
+               Assert.AreEqual ("!\u116B\u11C2".Normalize (NormalizationForm.FormC), "!\u116B\u11C2", "#6");
+       }
+
+       [Test]
+       public void MoreNormalizeFormC ()
+       {
+               Assert.AreEqual ("\u1E0A\u0323".Normalize (NormalizationForm.FormC), "\u1E0C\u0307", "#1");
+               Assert.AreEqual ("\u0044\u0323\u0307".Normalize (NormalizationForm.FormC), "\u1E0C\u0307", "#2");
+       }
 #endif
        [Test]
        public void Emptiness ()
index eb0b18acedde47e528db31016ef79d9d5f7906c0..41aa3dea6eaeb941f519ec96214013dc7ef7abd8 100644 (file)
@@ -12,6 +12,7 @@
 using NUnit.Framework;
 using System;
 using System.Globalization;
+using System.Threading;
 
 namespace MonoTests.System
 {
@@ -779,29 +780,65 @@ public class TimeSpanTest {
                catch (FormatException) {
                        formatException = true;
                }
-               Assert.AreEqual (expectFormat, formatException, "A1");
-               Assert.AreEqual (expectOverflow, overflowException, "A2");
+               Assert.AreEqual (expectFormat, formatException, "A1 [" + s + "]");
+               Assert.AreEqual (expectOverflow, overflowException, "A2 " + s + "]");
 
                if (!expectOverflow && !expectFormat) {
-                       Assert.AreEqual (expect, result, "A3");
+                       Assert.AreEqual (expect, result, "A3 [" + s + "]");
                }
        }
 
+       [Test]
        public void TestParse ()
        {
                ParseHelper (" 13:45:15 ",false, false, "13:45:15");
                ParseHelper (" -1:2:3 ", false, false, "-01:02:03");
 
+#if NET_4_0
+               // In 4.0 when the first part is out of range, it parses it as day.
+               ParseHelper (" 25:11:12 ", false, false, "25.11:12:00");
+               ParseHelper (" 24:11:12 ", false, false, "24.11:12:00");
+               ParseHelper (" 23:11:12 ", false, false, "23:11:12");
+#else
                ParseHelper (" 25:0:0 ",false, true, "dontcare");
-               ParseHelper ("aaa", true, false, "dontcare");
+#endif
 
                ParseHelper ("-21.23:59:59.9999999", false, false, "-21.23:59:59.9999999");
+               ParseHelper ("10:12  ", false, false, "10:12:00");
+               ParseHelper ("aaa", true, false, "dontcare");
 
                ParseHelper ("100000000000000.1:1:1", false, true, "dontcare");
                ParseHelper ("24:60:60", false, true, "dontcare");
                ParseHelper ("0001:0002:0003.12     ", false, false, "01:02:03.1200000");
 
+#if NET_4_0
+               // In 4.0 when a section has more than 7 digits an OverflowException is thrown.
+               ParseHelper (" 1:2:3:12345678 ", false, true, "dontcare");
+#else
                ParseHelper (" 1:2:3:12345678 ", true, false, "dontcare"); 
+#endif
+
+#if NET_4_0            
+               ParseHelper ("10:11:12:13", false, false, "10.11:12:13"); // Days using : instead of . as separator
+               ParseHelper ("10.11", true, false, "dontcare"); // days+hours is invalid
+
+               // Force the use of french culture -which is using a non common NumberDecimalSeparator-
+               // as current culture, to show that the Parse method is *actually* being culture sensitive
+               // *and* also keeping the compatibility with '.'
+               CultureInfo french_culture = CultureInfo.GetCultureInfo ("fr-FR");
+               CultureInfo prev_culture = CultureInfo.CurrentCulture;
+               try {
+                       Thread.CurrentThread.CurrentCulture = french_culture;
+                       ParseHelper ("10:10:10,006", false, false, "10:10:10.0060000");
+                       ParseHelper ("10:10:10.006", false, false, "10:10:10.0060000");
+               } finally {
+                       // restore culture
+                       Thread.CurrentThread.CurrentCulture = prev_culture;
+               }
+#endif
+
+               ParseHelper ("00:00:00", false, false, "00:00:00");
+               ParseHelper ("00:10:00", false, false, "00:10:00");
        }
 
        // LAMESPEC: timespan in documentation is wrong - hh:mm:ss isn't mandatory
@@ -853,11 +890,28 @@ public class TimeSpanTest {
        }
 
        [Test]
-       [ExpectedException (typeof (OverflowException))]
        public void Parse_InvalidValuesAndFormat_ExceptionOrder () 
        {
                // hours should be between 0 and 23 but format is also invalid (too many dots)
-               TimeSpan.Parse ("0.99.99.0");
+               // In 2.0 overflow as precedence over format, but not in 4.0
+#if NET_4_0
+               try {
+                       TimeSpan.Parse ("0.99.99.0");
+                       Assert.Fail ("#A1");
+               } catch (FormatException) {
+               }
+#else
+               try {
+                       TimeSpan.Parse ("0.99.99.0");
+                       Assert.Fail ("#A1");
+               } catch (OverflowException) {
+               }
+#endif
+               try {
+                       TimeSpan.Parse ("0.999999999999.99.0");
+                       Assert.Fail ("#A2");
+               } catch (OverflowException) {
+               }
        }
 
        [Test]
@@ -912,7 +966,6 @@ public class TimeSpanTest {
                Assert.AreEqual (true, TimeSpan.TryParse (" -1:2:3 ", out result), "#B1");
                Assert.AreEqual ("-01:02:03", result.ToString (), "#B2");
 
-               Assert.AreEqual (false, TimeSpan.TryParse (" 25:0:0 ", out result), "#C1");
                Assert.AreEqual (false, TimeSpan.TryParse ("aaa", out result), "#C2");
 
                Assert.AreEqual (true, TimeSpan.TryParse ("-21.23:59:59.9999999", out result), "#D1");
@@ -921,9 +974,12 @@ public class TimeSpanTest {
                Assert.AreEqual (false, TimeSpan.TryParse ("100000000000000.1:1:1", out result), "#E1");
                Assert.AreEqual (false, TimeSpan.TryParse ("24:60:60", out result), "#E2");
 
-               ParseHelper ("0001:0002:0003.12     ", false, false, "01:02:03.1200000");
+#if NET_4_0
+               Assert.AreEqual (true, TimeSpan.TryParse ("0001:0002:0003.12     ", out result), "#F1");
+#else
                Assert.AreEqual (true, TimeSpan.TryParse ("0001:0002:0003.12     ", out result), "#F1");
                Assert.AreEqual ("01:02:03.1200000", result.ToString (), "#F2");
+#endif
 
                Assert.AreEqual (false, TimeSpan.TryParse (" 1:2:3:12345678 ", out result), "#G1");
 
@@ -932,6 +988,22 @@ public class TimeSpanTest {
                Assert.AreEqual (TimeSpan.MaxValue, result, "MaxValue#2");
                Assert.AreEqual (true, TimeSpan.TryParse ("-10675199.02:48:05.4775808", out result), "MinValue#1");
                Assert.AreEqual (TimeSpan.MinValue, result, "MinValue#2");
+
+#if NET_4_0
+               // Force the use of french culture -which is using a non common NumberDecimalSeparator-
+               // as current culture, to show that the Parse method is *actually* being culture sensitive
+               CultureInfo french_culture = CultureInfo.GetCultureInfo ("fr-FR");
+               CultureInfo prev_culture = CultureInfo.CurrentCulture;
+               result = new TimeSpan (0, 10, 10, 10, 6);
+               try {
+                       Thread.CurrentThread.CurrentCulture = french_culture;
+                       Assert.AreEqual (true, TimeSpan.TryParse ("10:10:10,006", out result), "#CultureSensitive1");
+                       Assert.AreEqual ("10:10:10.0060000", result.ToString (), "#CultureSensitive2");
+               } finally {
+                       // restore culture
+                       Thread.CurrentThread.CurrentCulture = prev_culture;
+               }
+#endif
        }
 
        [Test]
@@ -945,6 +1017,341 @@ public class TimeSpanTest {
        }
 
 #if NET_4_0
+       [Test]
+       public void TryParseOverloads ()
+       { 
+               TimeSpan result;
+
+               // We use fr-FR culture since its NumericDecimalSeparator is not the same used by
+               // most cultures - including the invariant one.
+               CultureInfo french_culture = CultureInfo.GetCultureInfo ("fr-FR");
+               Assert.AreEqual (true, TimeSpan.TryParse ("11:50:50,006", french_culture, out result), "#A1");
+
+               // LAMESPEC - msdn states that an instance of DateTimeFormatInfo is retrieved to
+               // obtain culture sensitive information, but at least in the betas that's false
+               DateTimeFormatInfo format_info = new DateTimeFormatInfo ();
+               format_info.TimeSeparator = ";";
+               Assert.AreEqual (false, TimeSpan.TryParse ("11;50;50", format_info, out result), "#B1");
+               Assert.AreEqual (true, TimeSpan.TryParse ("11:50:50", format_info, out result), "#B2");
+       }
+
+       [Test]
+       public void ParseExact ()
+       {
+               CultureInfo french_culture = CultureInfo.GetCultureInfo ("fr-FR");
+               CultureInfo us_culture = CultureInfo.GetCultureInfo ("en-US");
+
+               // At this point we are only missing the style bites and then we are
+               // pretty much done with the standard formats.
+
+               //
+               // 'g' format - this is the short and culture sensitive format
+               //
+               string [] g_format = new string [] { "g" };
+               ParseExactHelper ("12", g_format, false, false, "12.00:00:00");
+               ParseExactHelper ("11:12", g_format, false, false, "11:12:00");
+               ParseExactHelper ("-11:12", g_format, false, false, "-11:12:00");
+               ParseExactHelper ("25:13", g_format, true, false, "dontcare");
+               ParseExactHelper ("11:66", g_format, true, false, "dontcare"); // I'd have expected OverflowExc here
+               ParseExactHelper ("11:12:13", g_format, false, false, "11:12:13");
+               ParseExactHelper ("-11:12:13", g_format, false, false, "-11:12:13");
+               ParseExactHelper ("10.11:12:13", g_format, true, false, "dontcare"); // this should work as well
+               ParseExactHelper ("10.11:12:13", g_format, true, false, "dontcare", us_culture);
+               ParseExactHelper ("10.11:12:13", g_format, true, false, "dontcare", CultureInfo.InvariantCulture);
+               ParseExactHelper ("10:11:12:66", g_format, true, false, "dontcare");
+               ParseExactHelper ("10:11:12:13", g_format, false, false, "10.11:12:13");
+               ParseExactHelper ("11:12:13.6", g_format, false, false, "11:12:13.6000000", CultureInfo.InvariantCulture);
+               ParseExactHelper ("11:12:13,6", g_format, false, false, "11:12:13.6000000", french_culture);
+               ParseExactHelper ("10:11:12:13.6", g_format, false, false, "10.11:12:13.6000000", us_culture);
+               ParseExactHelper (" 10:11:12:13.6 ", g_format, false, false, "10.11:12:13.6000000", us_culture);
+               ParseExactHelper ("10:11", g_format, false, false, "10:11:00", null, TimeSpanStyles.None);
+               ParseExactHelper ("10:11", g_format, false, false, "10:11:00", null, TimeSpanStyles.AssumeNegative); // no effect
+
+               // 
+               // G format
+               //
+               string [] G_format = new string [] { "G" };
+               ParseExactHelper ("9:10:12", G_format, true, false, "dontcare");
+               ParseExactHelper ("9:10:12.6", G_format, true, false, "dontcare");
+               ParseExactHelper ("3.9:10:12", G_format, true, false, "dontcare");
+               ParseExactHelper ("3.9:10:12.153", G_format, true, false, "dontcare"); // this should be valid...
+               ParseExactHelper ("3:9:10:12.153", G_format, false, false, "3.09:10:12.1530000", us_culture);
+               ParseExactHelper ("0:9:10:12.153", G_format, false, false, "09:10:12.1530000", us_culture);
+               ParseExactHelper ("03:09:10:12.153", G_format, false, false, "3.09:10:12.1530000", us_culture);
+               ParseExactHelper ("003:009:0010:0012.00153", G_format, false, false, "3.09:10:12.0015300", us_culture);
+               ParseExactHelper ("3:9:10:66.153", G_format, true, false, "dontcare"); // seconds out of range
+               ParseExactHelper ("3:9:10:12.153", G_format, true, false, "dontcare", french_culture); // fr-FR uses ',' as decimal separator
+               ParseExactHelper ("3:9:10:12,153", G_format, false, false, "3.09:10:12.1530000", french_culture);
+               ParseExactHelper ("  3:9:10:12.153  ", G_format, false, false, "3.09:10:12.1530000", us_culture);
+               ParseExactHelper ("3:9:10:13.153", G_format, false, false, "3.09:10:13.1530000", us_culture, TimeSpanStyles.AssumeNegative);
+
+               // c format
+               string [] c_format = new string [] { "c" };
+               ParseExactHelper ("12", c_format, false, false, "12.00:00:00");
+               ParseExactHelper ("12:11", c_format, false, false, "12:11:00");
+               ParseExactHelper ("12:66", c_format, true, false, "dontcare");
+               ParseExactHelper ("10.11:12", c_format, false, false, "10.11:12:00");
+               ParseExactHelper ("10.11:12:13", c_format, false, false, "10.11:12:13");
+               ParseExactHelper ("10:11:12:13", c_format, true, false, "dontcare"); // this is normally accepted in the Parse method
+               ParseExactHelper ("10.11:12:13.6", c_format, false, false, "10.11:12:13.6000000");
+               ParseExactHelper ("10:11:12,6", c_format, true, false, "dontcare");
+               ParseExactHelper ("10:11:12,6", c_format, true, false, "dontcare", french_culture);
+               ParseExactHelper ("  10:11:12.6  ", c_format, false, false, "10:11:12.6000000");
+               ParseExactHelper ("10:12", c_format, false, false, "10:12:00", null, TimeSpanStyles.AssumeNegative);
+               ParseExactHelper ("10:123456789999", c_format, true, false, "dontcare");
+
+               ParseExactHelper ("10:12", new string [0], true, false, "dontcare");
+               ParseExactHelper ("10:12", new string [] { String.Empty }, true, false, "dontcare");
+               ParseExactHelper ("10:12", new string [] { null }, true, false, "dontcare");
+       }
+
+       [Test]
+       public void ParseExactMultipleFormats ()
+       {
+               ParseExactHelper ("10:12", new string [] { "G", "g" }, false, false, "10:12:00");
+               ParseExactHelper ("10:12", new string [] { "g", "G" }, false, false, "10:12:00");
+               ParseExactHelper ("7.8:9:10", new string [] { "G", "g" }, true, false, "dontcare");
+               ParseExactHelper ("7.8:9:10", new string [] { "G", "g", "c" }, false, false, "7.08:09:10");
+               ParseExactHelper ("7:8:9:10", new string [] { "c", "g" }, false, false, "7.08:09:10");
+               ParseExactHelper ("7:8:9:10", new string [] { "c", "G" }, true, false, "dontcare");
+               ParseExactHelper ("7.123456789:1", new string [] { "c", "G", "g" }, true, false, "dontcare");
+               ParseExactHelper ("7.123456789:1", new string [] { "G", "g", "c" }, true, false, "dontcare");
+               ParseExactHelper ("1234567890123456", new string [] { "c", "g" }, true, false, "dontcare"); // I'd expect an OverflowException
+               ParseExactHelper ("10:12", new string [] { null, "c", "g" }, true, false, "10:12:00");
+               ParseExactHelper ("10:12", new string [] { String.Empty, "c", "g" }, true, false, "10:12:00");
+       }
+
+       [Test]
+       public void ParseExactCustomFormats ()
+       {
+               // Days
+               ParseExactHelper ("33", new string [] { "%d" }, false, false, "33.00:00:00");
+               ParseExactHelper ("00", new string [] { "%d" }, false, false, "00:00:00");
+               ParseExactHelper ("33", new string [] { "%dd" }, false, false, "33.00:00:00");
+               ParseExactHelper ("3333", new string [] { "%d" }, false, false, "3333.00:00:00");
+               ParseExactHelper ("3333", new string [] { "%ddd" }, true, false, "3333.00:00:00"); // 'dd' mismatch the digit count
+               ParseExactHelper ("3333", new string [] { "%dddd" }, false, false, "3333.00:00:00");
+               ParseExactHelper ("00033", new string [] { "%ddddd" }, false, false, "33.00:00:00");
+               ParseExactHelper ("00033", new string [] { "%d" }, false, false, "33.00:00:00");
+               ParseExactHelper ("00000003", new string [] { "%dddddddd" }, false, false, "3.00:00:00"); // up to 8 'd'
+               ParseExactHelper ("000000003", new string [] { "%ddddddddd" }, true, false, "dontcare");
+               ParseExactHelper ("33", new string [] { "d" }, true, false, "33.00:00:00"); // This is sort of weird.
+               ParseExactHelper ("33", new string [] { "dd" }, false, false, "33.00:00:00");
+               ParseExactHelper ("-33", new string [] { "%d" }, true, false, "dontcare");
+               ParseExactHelper ("33", new string [] { "%d" }, false, false, "-33.00:00:00", null, TimeSpanStyles.AssumeNegative);
+
+               // Hours
+               ParseExactHelper ("12", new string [] { "%h" }, false, false, "12:00:00");
+               ParseExactHelper ("00", new string [] { "%h" }, false, false, "00:00:00");
+               ParseExactHelper ("012", new string [] { "%h" }, true, false, "dontcare"); // more than 2 digits
+               ParseExactHelper ("00012", new string [] { "%hhhhh" }, true, false, "dontcare");
+               ParseExactHelper ("15", new string [] { "%h" }, false, false, "15:00:00");
+               ParseExactHelper ("24", new string [] { "%h" }, true, false, "dontcare");
+               ParseExactHelper ("15", new string [] { "%hh" }, false, false, "15:00:00");
+               ParseExactHelper ("1", new string [] { "%hh" }, true, false, "dontcare"); // 'hh' but a single digit
+               ParseExactHelper ("01", new string [] { "%hh" }, false, false, "01:00:00");
+               ParseExactHelper ("015", new string [] { "%hhh" }, true, false, "dontcare"); // Too many 'h'
+               ParseExactHelper ("12", new string [] { "h" }, true, false, "dontcare");
+               ParseExactHelper ("12", new string [] { "hh" }, false, false, "12:00:00");
+               ParseExactHelper ("-15", new string [] {"%h"}, true, false, "dontcare"); // Explicit - not accepted
+               ParseExactHelper ("15", new string [] { "%h" }, false, false, "-15:00:00", null, TimeSpanStyles.AssumeNegative);
+               ParseExactHelper ("15", new string [] { "%H" }, true, false, "dontcare"); // Uppercase is not accepted
+
+               // Minutes
+               ParseExactHelper ("12", new string [] { "%m" }, false, false, "00:12:00");
+               ParseExactHelper ("00", new string [] { "%m" }, false, false, "00:00:00");
+               ParseExactHelper ("60", new string [] { "%m" }, true, false, "dontcare");
+               ParseExactHelper ("12", new string [] { "%mm" }, false, false, "00:12:00");
+               ParseExactHelper ("1", new string [] { "%mm" }, true, false, "dontcare");
+               ParseExactHelper ("12", new string [] { "%mmm" }, true, false, "dontcare");
+               ParseExactHelper ("12", new string [] { "m" }, true, false, "dontcare");
+               ParseExactHelper ("12", new string [] { "mm" }, false, false, "00:12:00");
+               ParseExactHelper ("-12", new string [] { "%m" }, true, false, "dontcare");
+               ParseExactHelper ("12", new string [] { "%m" }, false, false, "-00:12:00", null, TimeSpanStyles.AssumeNegative);
+               ParseExactHelper ("12", new string [] { "%M" }, true, false, "dontcare");
+
+               // Seconds
+               ParseExactHelper ("12", new string [] { "%s" }, false, false, "00:00:12");
+               ParseExactHelper ("00", new string [] { "%s" }, false, false, "00:00:00");
+               ParseExactHelper ("000", new string [] { "%s" }, true, false, "dontcare");
+               ParseExactHelper ("12", new string [] { "%ss" }, false, false, "00:00:12");
+               ParseExactHelper ("12", new string [] { "%sss" }, true, false, "dontcare");
+               ParseExactHelper ("60", new string [] { "%s" }, true, false, "dontcare");
+               ParseExactHelper ("-12", new string [] { "%s" }, true, false, "dontcare");
+               ParseExactHelper ("12", new string [] { "%s" }, false, false, "-00:00:12", null, TimeSpanStyles.AssumeNegative);
+
+               // Fractions of seconds - f
+               ParseExactHelper ("3", new string [] { "%f" }, false, false, "00:00:00.3000000");
+               ParseExactHelper ("0", new string [] { "%f" }, false, false, "00:00:00");
+               ParseExactHelper ("03", new string [] { "%f" }, true, false, "dontcare"); // This would work for other elements
+               ParseExactHelper ("10", new string [] { "%f" }, true, false, "dontcare"); // Only a digit is accepted with '%f'
+               ParseExactHelper ("3", new string [] { "%ff" }, true, false, "dontcare");
+               ParseExactHelper ("12", new string [] { "%ff" }, false, false, "00:00:00.1200000");
+               ParseExactHelper ("123", new string [] { "%ff" }, true, false, "dontcare");
+               ParseExactHelper ("123", new string [] { "%fff" }, false, false, "00:00:00.1230000");
+               ParseExactHelper ("1234", new string [] { "%ffff" }, false, false, "00:00:00.1234000");
+               ParseExactHelper ("1234567", new string [] { "%fffffff" }, false, false, "00:00:00.1234567");
+               ParseExactHelper ("1234567", new string [] { "%FfFFFFF" }, true, false, "dontcare"); // Mixed f and M
+               ParseExactHelper ("12345678", new string [] { "%ffffffff" }, true, false, "dontcare");
+               ParseExactHelper ("0000000", new string [] { "%fffffff" }, false, false, "00:00:00");
+
+               // Fractions of second - F
+               ParseExactHelper ("3", new string [] { "%F" }, false, false, "00:00:00.3000000");
+               ParseExactHelper ("333", new string [] { "%FFFFF" }, false, false, "00:00:00.3330000");
+               ParseExactHelper ("1234567", new string [] { "%FFFFFFF" }, false, false, "00:00:00.1234567");
+
+               // Multiple symbols
+               ParseExactHelper ("9:10", new string [] { @"h\:m" }, false, false, "09:10:00");
+               ParseExactHelper ("9;10", new string [] { @"h\;m" }, false, false, "09:10:00");
+               ParseExactHelper ("10:9", new string [] { @"m\:h" }, false, false, "09:10:00");
+               ParseExactHelper ("10:9", new string [] { @"%m\:%h" }, false, false, "09:10:00");
+               ParseExactHelper ("9 10", new string [] { @"h\ m" }, false, false, "09:10:00");
+               ParseExactHelper ("9   10", new string [] { @"h\ \ \ m" }, false, false, "09:10:00");
+               ParseExactHelper (" 9:10 ", new string [] { @"h\:m" }, true, false, "dontcare");
+               ParseExactHelper ("9:10:11", new string [] { @"h\:m\:s" }, false, false, "09:10:11");
+               ParseExactHelper ("9:10:11:6", new string [] { @"h\:m\:s\:f" }, false, false, "09:10:11.6000000");
+               ParseExactHelper ("9:10:11:666", new string [] { @"h\:m\:s\:f" }, true, false, "dontcare"); // fff with 1 digit
+               ParseExactHelper ("9:10:11:", new string [] { @"h\:m\:s\:F" }, false, false, "09:10:11"); // optional frac of seconds
+               ParseExactHelper ("9:10:11:", new string [] { @"h\:m\:s\:FF" }, false, false, "09:10:11");
+               ParseExactHelper ("9:10:11::", new string [] { @"h\:m\:s\:F\:" }, false, false, "09:10:11");
+               ParseExactHelper ("8:9:10:11:6666666", new string [] { @"d\:h\:m\:s\:fffffff" }, false, false, "8.09:10:11.6666666");
+               ParseExactHelper ("8:9:10:11:6666666", new string [] { @"d\:h\:m\:s\:fffffff" }, false, false, "-8.09:10:11.6666666", 
+                               null, TimeSpanStyles.AssumeNegative);
+               ParseExactHelper ("9:10", new string [] { @"h\:h" }, true, false, "dontcare"); // Repeated element
+
+               // Misc
+               ParseExactHelper (" 0 ", new string [] { "%d" }, true, false, "dontcare");
+               ParseExactHelper (" 0 ", new string [] { " %d " }, true, false, "dontcare");
+               ParseExactHelper ("0", new string [] { " %d " }, true, false, "dontcare");
+               ParseExactHelper ("::", new string [] { @"\:\:" }, false, false, "00:00:00"); // funny
+               ParseExactHelper ("::", new string [] { @"\:\:" }, false, false, "00:00:00", null, TimeSpanStyles.AssumeNegative);
+               ParseExactHelper (" 0", new string [] { @"\ d" }, false, false, "00:00:00");
+               ParseExactHelper ("Interval = 12:13:14", new string [] { @"'Interval = 'h\:m\:s" }, false, false, "12:13:14");
+       }
+
+       void ParseExactHelper (string input, string [] formats, bool format_error, bool overflow_error, string expected, 
+        IFormatProvider formatProvider = null, TimeSpanStyles timeSpanStyles = TimeSpanStyles.None)
+       {
+               bool overflow_exc = false;
+               bool format_exc = false;
+               TimeSpan result = TimeSpan.Zero;
+
+               try {
+                       result = TimeSpan.ParseExact (input, formats, formatProvider, timeSpanStyles);
+               } catch (OverflowException) {
+                       overflow_exc = true;
+               } catch (FormatException) {
+                       format_exc = true;
+               }
+
+               Assert.AreEqual (format_error, format_exc, "A1");
+               Assert.AreEqual (overflow_error, overflow_exc, "A2");
+               if (!overflow_exc && !format_exc)
+                       Assert.AreEqual (expected, result.ToString ());
+       }
+
+       // 'Ported' the ParseExact test to use TryParseExact instead.
+       [Test]
+       public void TryParseExact ()
+       {
+               CultureInfo french_culture = CultureInfo.GetCultureInfo ("fr-FR");
+               CultureInfo us_culture = CultureInfo.GetCultureInfo ("en-US");
+
+               //
+               // 'g' format - this is the short and culture sensitive format
+               //
+               string [] g_format = new string [] { "g" };
+               TryParseExactHelper ("12", g_format, false, "12.00:00:00");
+               TryParseExactHelper ("11:12", g_format, false, "11:12:00");
+               TryParseExactHelper ("-11:12", g_format, false, "-11:12:00");
+               TryParseExactHelper ("25:13", g_format, true, "dontcare");
+               TryParseExactHelper ("11:66", g_format, true, "dontcare"); // I'd have expected OverflowExc here
+               TryParseExactHelper ("11:12:13", g_format, false, "11:12:13");
+               TryParseExactHelper ("-11:12:13", g_format, false, "-11:12:13");
+               TryParseExactHelper ("10.11:12:13", g_format, true, "dontcare"); // this should work as well
+               TryParseExactHelper ("10.11:12:13", g_format, true, "dontcare", us_culture);
+               TryParseExactHelper ("10.11:12:13", g_format, true, "dontcare", CultureInfo.InvariantCulture);
+               TryParseExactHelper ("10:11:12:66", g_format, true, "dontcare");
+               TryParseExactHelper ("10:11:12:13", g_format, false, "10.11:12:13");
+               TryParseExactHelper ("11:12:13.6", g_format, false, "11:12:13.6000000", CultureInfo.InvariantCulture);
+               TryParseExactHelper ("11:12:13,6", g_format, false, "11:12:13.6000000", french_culture);
+               TryParseExactHelper ("10:11:12:13.6", g_format, false, "10.11:12:13.6000000", us_culture);
+               TryParseExactHelper (" 10:11:12:13.6 ", g_format, false, "10.11:12:13.6000000", us_culture);
+               TryParseExactHelper ("10:11", g_format, false, "10:11:00", null, TimeSpanStyles.None);
+               TryParseExactHelper ("10:11", g_format, false, "10:11:00", null, TimeSpanStyles.AssumeNegative); // no effect
+
+               // 
+               // G format
+               //
+               string [] G_format = new string [] { "G" };
+               TryParseExactHelper ("9:10:12", G_format, true, "dontcare");
+               TryParseExactHelper ("9:10:12.6", G_format, true, "dontcare");
+               TryParseExactHelper ("3.9:10:12", G_format, true, "dontcare");
+               TryParseExactHelper ("3.9:10:12.153", G_format, true, "dontcare"); // this should be valid...
+               TryParseExactHelper ("3:9:10:12.153", G_format, false, "3.09:10:12.1530000", us_culture);
+               TryParseExactHelper ("0:9:10:12.153", G_format, false, "09:10:12.1530000", us_culture);
+               TryParseExactHelper ("03:09:10:12.153", G_format, false, "3.09:10:12.1530000", us_culture);
+               TryParseExactHelper ("003:009:0010:0012.00153", G_format, false, "3.09:10:12.0015300", us_culture);
+               TryParseExactHelper ("3:9:10:66.153", G_format, true, "dontcare"); // seconds out of range
+               TryParseExactHelper ("3:9:10:12.153", G_format, true, "dontcare", french_culture); // fr-FR uses ',' as decimal separator
+               TryParseExactHelper ("3:9:10:12,153", G_format, false, "3.09:10:12.1530000", french_culture);
+               TryParseExactHelper ("  3:9:10:12.153  ", G_format, false, "3.09:10:12.1530000", us_culture);
+               TryParseExactHelper ("3:9:10:13.153", G_format, false, "3.09:10:13.1530000", us_culture, TimeSpanStyles.AssumeNegative);
+
+               // c format
+               string [] c_format = new string [] { "c" };
+               TryParseExactHelper ("12", c_format, false, "12.00:00:00");
+               TryParseExactHelper ("12:11", c_format, false, "12:11:00");
+               TryParseExactHelper ("12:66", c_format, true, "dontcare");
+               TryParseExactHelper ("10.11:12", c_format, false, "10.11:12:00");
+               TryParseExactHelper ("10.11:12:13", c_format, false, "10.11:12:13");
+               TryParseExactHelper ("10:11:12:13", c_format, true, "dontcare"); // this is normally accepted in the Parse method
+               TryParseExactHelper ("10.11:12:13.6", c_format, false, "10.11:12:13.6000000");
+               TryParseExactHelper ("10:11:12,6", c_format, true, "dontcare");
+               TryParseExactHelper ("10:11:12,6", c_format, true, "dontcare", french_culture);
+               TryParseExactHelper ("  10:11:12.6  ", c_format, false, "10:11:12.6000000");
+               TryParseExactHelper ("10:12", c_format, false, "10:12:00", null, TimeSpanStyles.AssumeNegative);
+               TryParseExactHelper ("10:123456789999", c_format, true, "dontcare");
+
+               TryParseExactHelper ("10:12", new string [0], true, "dontcare");
+               TryParseExactHelper ("10:12", new string [] { String.Empty }, true, "dontcare");
+               TryParseExactHelper ("10:12", new string [] { null }, true, "dontcare");
+       }
+
+       void TryParseExactHelper (string input, string [] formats, bool error, string expected, IFormatProvider formatProvider = null,
+                       TimeSpanStyles styles = TimeSpanStyles.None)
+       {
+               TimeSpan result;
+               bool success;
+
+               success = TimeSpan.TryParseExact (input, formats, formatProvider, styles, out result);
+               Assert.AreEqual (!error, success);
+               if (!error)
+                       Assert.AreEqual (expected, result.ToString ());
+       }
+
+       [Test]
+       public void ParseExactExceptions ()
+       {
+               try {
+                       TimeSpan.ParseExact (null, "g", null);
+                       Assert.Fail ("#A1");
+               } catch (ArgumentNullException) {
+               }
+
+               try {
+                       TimeSpan.ParseExact ("10:12", (string)null, null);
+                       Assert.Fail ("#A2");
+               } catch (ArgumentNullException) {
+               }
+
+               try {
+                       TimeSpan.ParseExact ("10:12", (string [])null, null);
+                       Assert.Fail ("#A3");
+               } catch (ArgumentNullException) {
+               }
+       }
+
        [Test]
        public void ToStringOverloads ()
        {
@@ -965,12 +1372,54 @@ public class TimeSpanTest {
                Assert.AreEqual ("1:2:03:04,006", ts.ToString ("g", culture), "#B1");
                Assert.AreEqual ("1:02:03:04,0060000", ts.ToString ("G", culture), "#B2");
                Assert.AreEqual ("1.02:03:04.0060000", ts.ToString ("c", culture), "#B3"); // 'c' format ignores CultureInfo
+               Assert.AreEqual ("1.02:03:04.0060000", ts.ToString ("t", culture), "#B4"); // 't' and 'T' are the same as 'c'
+               Assert.AreEqual("1.02:03:04.0060000", ts.ToString("T", culture), "#B5");
 
                ts = new TimeSpan (4, 5, 6);
                Assert.AreEqual ("4:05:06", ts.ToString ("g", culture), "#C1");
                Assert.AreEqual ("0:04:05:06,0000000", ts.ToString ("G", culture), "#C2");
        }
 
+       [Test]
+       public void ToStringCustomFormats ()
+       {
+               TimeSpan ts = new TimeSpan (1, 3, 5, 7);
+
+               Assert.AreEqual ("1", ts.ToString ("%d"), "#A0");
+               Assert.AreEqual ("3", ts.ToString ("%h"), "#A1");
+               Assert.AreEqual ("5", ts.ToString ("%m"), "#A2");
+               Assert.AreEqual ("7", ts.ToString ("%s"), "#A3");
+               Assert.AreEqual ("0", ts.ToString ("%f"), "#A4");
+               Assert.AreEqual (String.Empty, ts.ToString ("%F"), "#A5"); // Nothing to display
+
+               Assert.AreEqual ("01", ts.ToString ("dd"), "#B0");
+               Assert.AreEqual ("00000001", ts.ToString ("dddddddd"), "#B1");
+               Assert.AreEqual ("03", ts.ToString ("hh"), "#B2");
+               Assert.AreEqual ("05", ts.ToString ("mm"), "#B3");
+               Assert.AreEqual ("07", ts.ToString ("ss"), "#B4");
+               Assert.AreEqual ("00", ts.ToString ("ff"), "#B5");
+               Assert.AreEqual ("0000000", ts.ToString ("fffffff"), "#B6");
+               Assert.AreEqual (String.Empty, ts.ToString ("FF"), "#B7");
+
+               Assert.AreEqual ("01;03;05", ts.ToString (@"dd\;hh\;mm"), "#C0");
+               Assert.AreEqual ("05 07", ts.ToString (@"mm\ ss"), "#C1");
+               Assert.AreEqual ("05 07 ", ts.ToString (@"mm\ ss\ FF"), "#C2");
+               Assert.AreEqual ("Result = 3 hours with 5 minutes and 7 seconds",
+                               ts.ToString (@"'Result = 'h' hours with 'm' minutes and 's' seconds'"), "#C3");
+               Assert.AreEqual ("  ", ts.ToString (@"\ \ "), "#C4");
+
+               ts = new TimeSpan (1, 3, 5, 7, 153);
+               Assert.AreEqual ("1", ts.ToString ("%F"), "#D0");
+               Assert.AreEqual ("15", ts.ToString ("FF"), "#D1"); // Don't use %, as the parser gets confused here
+               Assert.AreEqual ("153", ts.ToString ("FFFFFFF"), "#D2");
+
+               // Negative values are shown without sign
+               ts = new TimeSpan (-1, -3, -5);
+               Assert.AreEqual ("1", ts.ToString ("%h"), "#E0");
+               Assert.AreEqual ("3", ts.ToString ("%m"), "#E1");
+               Assert.AreEqual ("5", ts.ToString ("%s"), "#E2");
+       }
+
        [Test]
        public void ToStringOverloadsErrors ()
        {
@@ -989,12 +1438,44 @@ public class TimeSpanTest {
                } catch (FormatException) {
                }
 
-               // This is suppoused to work, but the docs are wrong.
-               try {
-                       result = ts.ToString ("t");
+               try
+               {
+                       ts.ToString ("m");
                        Assert.Fail ("#3");
                } catch (FormatException) {
                }
+
+               try
+               {
+                       ts.ToString ("d"); // Missing % for single char
+                       Assert.Fail ("#4");
+               } catch (FormatException)
+               {
+               }
+
+               try
+               {
+                       ts.ToString ("ddddddddd");
+                       Assert.Fail ("#5");
+               } catch (FormatException)
+               {
+               }
+
+               try
+               {
+                       ts.ToString ("hhh");
+                       Assert.Fail ("#5");
+               } catch (FormatException)
+               {
+               }
+
+               try
+               {
+                       ts.ToString ("ffffffff");
+                       Assert.Fail ("6");
+               } catch (FormatException)
+               {
+               }
        }
 #endif
 }
index 144ee977234640ac753b3adcc8d168a898cb0a58..dc3b50836dc05f82d837c57f9a08b3dc053d07ba 100644 (file)
@@ -3227,7 +3227,99 @@ PublicKeyToken=b77a5c561934e089"));
                        Assert.AreEqual (0, typeof (Bar).GetMember ("PrivInstBase", flags).Length);
                        Assert.AreEqual (1, typeof (Foo).GetMember ("PrivInstBase", flags).Length);
                }
+
+               [Test] // Bug #484246
+               public void GetInterfaceCompareAgainstGTDNames ()
+               {
+                       var t = typeof (Dictionary<string,string>);
+                       var iface = typeof (IDictionary<string,string>);
+
+                       Assert.AreSame (iface, t.GetInterface ("System.Collections.Generic.IDictionary`2"), "#1");
+
+                       string name = "System.Collections.Generic.IDictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]";
+
+                       Assert.IsNull (t.GetInterface (name), "#2");
+               } 
+
+               [Test]
+               public void RuntimeCorrectlyNormalizeGenericTypes ()
+               {
+                       Type lst = typeof (MList<>);
+                       Type arg = lst.GetGenericArguments ()[0];
+
+                       Type sup = lst.BaseType;
+                       Type sa0 = sup.GetGenericArguments ()[0];
+                       Type sa1 = sup.GetGenericArguments ()[1];
+
+                       Assert.IsTrue (sa1 == lst, "#1");
+                       Assert.IsTrue (sa0 == arg, "#2");
+
+                       Type inst = typeof (Cons<,>).MakeGenericType (arg, lst.MakeGenericType (arg));
+                       Assert.IsTrue (inst == sup, "#3");
+               }
+
+               class Cons<T,U>
+               {
+
+               }
+
+               class MList<A> : Cons<A, MList<A>>
+               {
+
+               }
+
+               [Test] // Bug #331126
+               public void IsAssignableFromWorksCorrectlyWithByRefs ()
+               {
+                       Type int_byref = typeof (int).MakeByRefType ();
+                       Type obj_byref = typeof (object).MakeByRefType ();
+                       Type long_byref = typeof (long).MakeByRefType ();
+                       Type enum1_byref = typeof (AttributeTargets).MakeByRefType ();
+                       Type enum2_byref = typeof (PlatformID).MakeByRefType ();
+                       Type uint_byref = typeof (uint).MakeByRefType ();
+                       Type string_byref = typeof (object).MakeByRefType ();
+                       Type struct0_byref = typeof (Size4).MakeByRefType ();
+                       Type struct1_byref = typeof (Size4b).MakeByRefType ();
+                       Type mvar0_byref = typeof (TypeTest).GetMethod ("Bug331126").GetGenericArguments ()[0].MakeByRefType ();
+                       Type mvar1_byref = typeof (TypeTest).GetMethod ("Bug331126").GetGenericArguments ()[1].MakeByRefType ();
+
+                       Assert.IsFalse (typeof (int).IsAssignableFrom (int_byref), "#1");
+                       Assert.IsFalse (int_byref.IsAssignableFrom (typeof (int)), "#2");
+                       Assert.IsFalse (obj_byref.IsAssignableFrom (long_byref), "#3");
+                       Assert.IsFalse (long_byref.IsAssignableFrom (obj_byref), "#4");
+                       Assert.IsTrue (enum1_byref.IsAssignableFrom (enum2_byref), "#5");
+                       Assert.IsTrue (enum2_byref.IsAssignableFrom (enum1_byref), "#6");
+                       Assert.IsTrue (int_byref.IsAssignableFrom (enum2_byref), "#7");
+                       Assert.IsTrue (enum2_byref.IsAssignableFrom (int_byref), "#8");
+                       Assert.IsTrue (enum2_byref.IsAssignableFrom (uint_byref), "#9");
+                       Assert.IsTrue (uint_byref.IsAssignableFrom (enum2_byref), "#10");
+                       Assert.IsTrue (int_byref.IsAssignableFrom (uint_byref), "#11");
+                       Assert.IsTrue (uint_byref.IsAssignableFrom (int_byref), "#12");
+
+                       Assert.IsTrue (typeof (object).IsAssignableFrom (typeof (long)), "#13");
+
+                       Assert.IsTrue (obj_byref.IsAssignableFrom (string_byref), "#14");
+                       Assert.IsTrue (string_byref.IsAssignableFrom (obj_byref), "#15");
+
+                       Assert.IsFalse (uint_byref.IsAssignableFrom (struct0_byref), "#16");
+                       Assert.IsFalse (struct0_byref.IsAssignableFrom (int_byref), "#17");
+                       Assert.IsFalse (struct0_byref.IsAssignableFrom (struct1_byref), "#18");
+
+                       Assert.IsFalse (obj_byref.IsAssignableFrom (mvar0_byref), "#19");
+                       Assert.IsFalse (mvar0_byref.IsAssignableFrom (mvar1_byref), "#20");
+                       Assert.IsTrue (mvar0_byref.IsAssignableFrom (mvar0_byref), "#21");
+                       Assert.IsFalse (mvar0_byref.IsAssignableFrom (obj_byref), "#22");
+               }
+
+               public void Bug331126<T,K> () {}
+
+               public struct Size4 {
+                       public int field;
+               }
+
+               public struct Size4b {
+                       public int field;
+               }
 
 #if NET_4_0
                interface IGetInterfaceMap<in T>
@@ -3281,10 +3373,10 @@ PublicKeyToken=b77a5c561934e089"));
 
                        a.Equals (a);
                        Assert.AreEqual (1, ta.eq, "#1");
-                       Assert.AreEqual (2, ta.ust, "#2");
+                       Assert.AreEqual (0, ta.ust, "#2");
                        a.Equals (b);
                        Assert.AreEqual (2, ta.eq, "#3");
-                       Assert.AreEqual (3, ta.ust, "#4");
+                       Assert.AreEqual (1, ta.ust, "#4");
                        Assert.AreEqual (0, tb.eq, "#5");
                        Assert.AreEqual (1, tb.ust, "#6");
                }
index f7326ce6c3d740c6a6eebfd2e422c8d43a2f71e3..46ea2675c625128d57ff6a4bc86b5a0a237da9cf 100644 (file)
@@ -187,6 +187,10 @@ public class UInt32Test
                catch (Exception e) {
                        Assert.IsTrue(typeof(FormatException) == e.GetType());
                }
+               // Pass a DateTimeFormatInfo, it is unable to format
+               // numbers, but we should not crash
+               
+               UInt32.Parse ("123", new DateTimeFormatInfo ());
        }
        
        public void TestToString()
index e93f54cf7e9f51ca98c14c4fa2fec627e7857b07..0e2591e0fb25e324cd24b6b8b87cfe996824ce73 100644 (file)
@@ -176,6 +176,11 @@ public class UInt64Test
                catch (Exception e) {
                        Assert.IsTrue(typeof(FormatException) == e.GetType());
                }
+
+               // Pass a DateTimeFormatInfo, it is unable to format
+               // numbers, but we should not crash
+               
+               UInt64.Parse ("123", new DateTimeFormatInfo ());
        }
        
        public void TestToString()
index 20f46d9ba80299b16620db9fb791d87328fdc5f6..3d1585b2fe484c95003d1842d2f39c690fe73fc2 100644 (file)
@@ -506,11 +506,13 @@ System.Reflection/MethodInfo.cs
 System.Reflection/Missing.cs
 System.Reflection/Module.cs
 System.Reflection/ModuleResolveEventHandler.cs
+System.Reflection/MonoAssembly.cs
 System.Reflection/MonoGenericClass.cs
 System.Reflection/MonoGenericMethod.cs
 System.Reflection/MonoEvent.cs
 System.Reflection/MonoField.cs
 System.Reflection/MonoMethod.cs
+System.Reflection/MonoModule.cs
 System.Reflection/MonoProperty.cs
 System.Reflection/ObfuscateAssemblyAttribute.cs
 System.Reflection/ObfuscationAttribute.cs
@@ -1102,7 +1104,6 @@ System.Runtime.Serialization.Formatters.Binary/CodeGenerator.cs
 System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs
 System.Runtime.Serialization.Formatters.Binary/ObjectWriter.cs
 System.Runtime.Serialization.Formatters.Binary/MessageFormatter.cs
-System.Runtime.Versioning/FrameworkName.cs
 System.Runtime.Versioning/ResourceConsumptionAttribute.cs
 System.Runtime.Versioning/ResourceExposureAttribute.cs
 System.Runtime.Versioning/ResourceScope.cs
@@ -1207,6 +1208,7 @@ System.Security.AccessControl/RegistrySecurity.cs
 System.Security.AccessControl/ResourceType.cs
 System.Security.AccessControl/SecurityInfos.cs
 System.Security.AccessControl/SystemAcl.cs
+../System.Core/System.Security.Cryptography/Aes.cs
 System.Security.Cryptography/AsymmetricAlgorithm.cs
 System.Security.Cryptography/AsymmetricKeyExchangeDeformatter.cs
 System.Security.Cryptography/AsymmetricKeyExchangeFormatter.cs
@@ -1469,6 +1471,7 @@ System.Threading/ParameterizedThreadStart.cs
 System.Threading/ReaderWriterLock.cs
 System.Threading/RegisteredWaitHandle.cs
 System.Threading/SendOrPostCallback.cs
+../System/System.Threading/SemaphoreFullException.cs
 System.Threading/SynchronizationContext.cs
 System.Threading/SynchronizationLockException.cs
 System.Threading/Thread.cs
index 9bbfb60b7d64a093fc47595905fb0152f295499f..02dbe74c2f1affe33b60cf35f608fc59b01a858e 100644 (file)
@@ -181,7 +181,6 @@ System.Runtime.Serialization/SerializationCallbackTest.cs
 System.Runtime.Serialization/ArraySerializationTest.cs
 System.Runtime.Serialization/ObjectManagerTest.cs
 System.Runtime.Serialization.Formatters.Binary/BinaryFormatterTest.cs
-System.Runtime.Versioning/FrameworkNameTest.cs
 System.Runtime.Versioning/ResourceConsumptionAttributeTest.cs
 System.Runtime.Versioning/ResourceExposureAttributeTest.cs
 System.Runtime.Versioning/TargetFrameworkAttributeTest.cs
diff --git a/mcs/class/corlib/moonlight_bootstrap_corlib.dll.sources b/mcs/class/corlib/moonlight_bootstrap_corlib.dll.sources
new file mode 100644 (file)
index 0000000..346a842
--- /dev/null
@@ -0,0 +1,2 @@
+#include moonlight_raw_corlib.dll.sources
+
diff --git a/mcs/class/corlib/moonlight_raw_corlib.dll.sources b/mcs/class/corlib/moonlight_raw_corlib.dll.sources
new file mode 100644 (file)
index 0000000..61d8bed
--- /dev/null
@@ -0,0 +1,1039 @@
+Assembly/AssemblyInfo.cs
+../../build/common/Consts.cs
+../../build/common/Locale.cs
+Microsoft.Win32.SafeHandles/CriticalHandleMinusOneIsInvalid.cs
+Microsoft.Win32.SafeHandles/SafeHandleZeroOrMinusOneIsInvalid.cs
+Microsoft.Win32.SafeHandles/SafeHandleMinusOneIsInvalid.cs
+Microsoft.Win32.SafeHandles/SafeFileHandle.cs
+Microsoft.Win32.SafeHandles/SafeWaitHandle.cs
+Mono.Globalization.Unicode/CodePointIndexer.cs
+Mono.Globalization.Unicode/MSCompatUnicodeTable.cs
+Mono.Globalization.Unicode/MSCompatUnicodeTableUtil.cs
+Mono.Globalization.Unicode/SimpleCollator.cs
+Mono.Globalization.Unicode/SortKey.cs
+Mono.Globalization.Unicode/SortKeyBuffer.cs
+Mono/Runtime.cs
+Mono/DataConverter.cs
+Mono.Math/BigInteger.cs
+Mono.Math.Prime/ConfidenceFactor.cs
+Mono.Math.Prime/PrimalityTests.cs
+Mono.Math.Prime.Generator/NextPrimeFinder.cs
+Mono.Math.Prime.Generator/PrimeGeneratorBase.cs
+Mono.Math.Prime.Generator/SequentialSearchPrimeGeneratorBase.cs
+Mono.Security/ASN1.cs
+Mono.Security/ASN1Convert.cs
+Mono.Security/BitConverterLE.cs
+Mono.Security/PKCS7.cs
+Mono.Security/StrongName.cs
+Mono.Security/StrongNameManager_2_1.cs
+Mono.Security/Uri.cs
+Mono.Security.Cryptography/CryptoConvert.cs
+Mono.Security.Cryptography/CryptoTools.cs
+Mono.Security.Cryptography/DSAManaged.cs
+Mono.Security.Cryptography/KeyPairPersistence.cs
+Mono.Security.Cryptography/PKCS1.cs
+Mono.Security.Cryptography/PKCS8.cs
+Mono.Security.Cryptography/HMACAlgorithm.cs
+Mono.Security.Cryptography/SymmetricTransform.cs
+Mono.Security.Cryptography/RSAManaged.cs
+Mono.Security.X509/PKCS12.cs
+Mono.Security.X509/X501Name.cs
+Mono.Security.X509/X509Certificate.cs
+Mono.Security.X509/X509CertificateCollection.cs
+Mono.Security.X509/X509Chain.cs
+Mono.Security.X509/X509ChainStatusFlags.cs
+Mono.Security.X509/X509CRL.cs
+Mono.Security.X509/X509Extension.cs
+Mono.Security.X509/X509Extensions.cs
+Mono.Security.X509/X509Store.cs
+Mono.Security.X509/X509Stores.cs
+Mono.Security.X509/X509StoreManager.cs
+Mono.Security.X509/X520Attributes.cs
+Mono.Security.X509.Extensions/BasicConstraintsExtension.cs
+Mono.Security.X509.Extensions/KeyUsageExtension.cs
+Mono.Security.X509.Extensions/SubjectKeyIdentifierExtension.cs
+Mono.Xml/SmallXmlParser.cs
+System/AccessViolationException.cs
+System/Activator.cs
+System/AppDomain.cs
+System/AppDomainInitializer.cs
+System/AppDomainManager_2_1.cs
+System/AppDomainSetup.cs
+System/AppDomainUnloadedException.cs
+System/ApplicationException.cs
+System/ArgIterator.cs
+System/ArgumentException.cs
+System/ArgumentNullException.cs
+System/ArgumentOutOfRangeException.cs
+System/ArithmeticException.cs
+System/Array.cs
+System/ArrayTypeMismatchException.cs
+System/AssemblyLoadEventArgs.cs
+System/AssemblyLoadEventHandler.cs
+System/AsyncCallback.cs
+System/Attribute.cs
+System/AttributeTargets.cs
+System/AttributeUsageAttribute.cs
+System/BadImageFormatException.cs
+System/Base64FormattingOptions.cs
+System/BitConverter.cs
+System/Boolean.cs
+System/Buffer.cs
+System/Byte.cs
+System/CannotUnloadAppDomainException.cs
+System/Char.cs
+System/CharEnumerator.cs
+System/CLSCompliantAttribute.cs
+System/CStreamReader.cs
+System/CStreamWriter.cs
+System/Console.cs
+System/ConsoleCancelEventArgs.cs
+System/ConsoleCancelEventHandler.cs
+System/ConsoleColor.cs
+System/ConsoleDriver.cs
+System/ConsoleKey.cs
+System/ConsoleKeyInfo.cs
+System/ConsoleModifiers.cs
+System/ConsoleSpecialKey.cs
+System/ContextBoundObject.cs
+System/ContextMarshalException.cs
+System/ContextStaticAttribute.cs
+System/ControlCharacters.cs
+System/Convert.cs
+System/CrossAppDomainDelegate.cs
+System/DataMisalignedException.cs
+System/DateTime.cs
+System/DateTimeKind.cs
+System/DateTimeOffset.cs
+System/DateTimeUtils.cs
+System/DayOfWeek.cs
+System/DBNull.cs
+System/Decimal.cs
+System/Delegate.cs
+System/DelegateSerializationHolder.cs
+System/DivideByZeroException.cs
+System/DllNotFoundException.cs
+System/DomainManagerInitializationFlags.cs
+System/Double.cs
+System/DuplicateWaitObjectException.cs
+System/EntryPointNotFoundException.cs
+System/Enum.cs
+System/Environment.cs
+System/EnvironmentVariableTarget.cs
+System/EventArgs.cs
+System/EventHandler.cs
+System/Exception.cs
+System/ExecutionEngineException.cs
+System/FieldAccessException.cs
+System/FlagsAttribute.cs
+System/FormatException.cs
+System/Funcs.cs
+System/GC.cs
+System/GCCollectionMode.cs
+System/GCNotificationStatus.cs
+System/Guid.cs
+System/IAppDomainSetup.cs
+System/IAsyncResult.cs
+System/ICloneable.cs
+System/IComparable.cs
+System/IEquatable.cs
+System/IConsoleDriver.cs
+System/IConvertible.cs
+System/ICustomFormatter.cs
+System/IDisposable.cs
+System/IFormatProvider.cs
+System/IFormattable.cs
+System/IndexOutOfRangeException.cs
+System/InsufficientMemoryException.cs
+System/Int16.cs
+System/Int32.cs
+System/Int64.cs
+System/IntPtr.cs
+System/InvalidCastException.cs
+System/InvalidOperationException.cs
+System/InvalidProgramException.cs
+System/InvalidTimeZoneException.cs
+System/IServiceProvider.cs
+System/KnownTerminals.cs
+System/LoaderOptimization.cs
+System/LoaderOptimizationAttribute.cs
+System/MarshalByRefObject.cs
+System/Math.cs
+System/MemberAccessException.cs
+System/MethodAccessException.cs
+System/MidpointRounding.cs
+System/MissingFieldException.cs
+System/MissingMemberException.cs
+System/MissingMethodException.cs
+System/MonoAsyncCall.cs
+System/MonoCustomAttrs.cs
+System/MonoListItem.cs
+System/MonoType.cs
+System/MTAThreadAttribute.cs
+System/MulticastDelegate.cs
+System/MulticastNotSupportedException.cs
+System/NonSerializedAttribute.cs
+System/NotFiniteNumberException.cs
+System/NotImplementedException.cs
+System/NotSupportedException.cs
+System/NullConsoleDriver.cs
+System/Nullable.cs
+System/NullReferenceException.cs
+System/NumberFormatter.cs
+System/Object.cs
+System/ObjectDisposedException.cs
+System/ObsoleteAttribute.cs
+System/OperatingSystem.cs
+System/OperationCanceledException.cs
+System/OutOfMemoryException.cs
+System/OverflowException.cs
+System/ParamArrayAttribute.cs
+System/PlatformID.cs
+System/PlatformNotSupportedException.cs
+System/Random.cs
+System/RankException.cs
+System/ResolveEventArgs.cs
+System/ResolveEventHandler.cs
+System/RuntimeArgumentHandle.cs
+System/RuntimeFieldHandle.cs
+System/RuntimeMethodHandle.cs
+System/RuntimeTypeHandle.cs
+System/ModuleHandle.cs
+System/SByte.cs
+System/SerializableAttribute.cs
+System/Single.cs
+System/StackOverflowException.cs
+System/STAThreadAttribute.cs
+System/String.cs
+System/StringSplitOptions.cs
+System/StringComparer.cs
+System/StringComparison.cs
+System/SystemException.cs
+System/TermInfoBooleans.cs
+System/TermInfoDriver.cs
+System/TermInfoNumbers.cs
+System/TermInfoReader.cs
+System/TermInfoStrings.cs
+System/ThreadStaticAttribute.cs
+System/TimeSpan.cs
+System/TimeZone.cs
+System/TimeZoneNotFoundException.cs
+System/TimeoutException.cs
+../../build/common/MonoTODOAttribute.cs
+System/Type.cs
+System/TypeCode.cs
+System/TypedReference.cs
+System/TypeInitializationException.cs
+System/TypeLoadException.cs
+System/TypeUnloadedException.cs
+System/Tuple.cs
+System/Tuples.cs
+System/UInt16.cs
+System/UInt32.cs
+System/UInt64.cs
+System/UIntPtr.cs
+System/UnauthorizedAccessException.cs
+System/UnhandledExceptionEventArgs.cs
+System/UnhandledExceptionEventHandler.cs
+System/UnitySerializationHolder.cs
+System/ValueType.cs
+System/Version.cs
+System/Void.cs
+System/WeakReference.cs
+System/WindowsConsoleDriver.cs
+System.Collections/ArrayList.cs
+System.Collections/BitArray.cs
+System.Collections/CaseInsensitiveComparer.cs
+System.Collections/CaseInsensitiveHashCodeProvider.cs
+System.Collections/CollectionBase.cs
+System.Collections/Comparer.cs
+System.Collections/CollectionDebuggerView.cs
+System.Collections/DictionaryBase.cs
+System.Collections/DictionaryEntry.cs
+System.Collections/Hashtable.cs
+System.Collections/ICollection.cs
+System.Collections/IComparer.cs
+System.Collections/IDictionary.cs
+System.Collections/IDictionaryEnumerator.cs
+System.Collections/IEnumerable.cs
+System.Collections/IEnumerator.cs
+System.Collections/IEqualityComparer.cs
+System.Collections/IHashCodeProvider.cs
+System.Collections/IList.cs
+System.Collections/IStructuralComparable.cs
+System.Collections/IStructuralEquatable.cs
+System.Collections/Queue.cs
+System.Collections/ReadOnlyCollectionBase.cs
+System.Collections/SortedList.cs
+System.Collections/Stack.cs
+System.Configuration.Assemblies/AssemblyHashAlgorithm.cs
+System.Configuration.Assemblies/AssemblyVersionCompatibility.cs
+System.Diagnostics/ConditionalAttribute.cs
+System.Diagnostics/DebuggableAttribute.cs
+System.Diagnostics/Debugger.cs
+System.Diagnostics/DebuggerBrowsableState.cs
+System.Diagnostics/DebuggerBrowsableAttribute.cs
+System.Diagnostics/DebuggerDisplayAttribute.cs
+System.Diagnostics/DebuggerHiddenAttribute.cs
+System.Diagnostics/DebuggerNonUserCodeAttribute.cs
+System.Diagnostics/DebuggerStepThroughAttribute.cs
+System.Diagnostics/DebuggerTypeProxyAttribute.cs
+System.Diagnostics/StackFrame.cs
+System.Diagnostics/StackTrace.cs
+System.Diagnostics.CodeAnalysis/SuppressMessageAttribute.cs
+System.Diagnostics.Contracts/Contract.cs
+System.Diagnostics.Contracts/ContractClassAttribute.cs
+System.Diagnostics.Contracts/ContractClassForAttribute.cs
+System.Diagnostics.Contracts/ContractFailedEventArgs.cs
+System.Diagnostics.Contracts/ContractFailureKind.cs
+System.Diagnostics.Contracts/ContractInvariantMethodAttribute.cs
+System.Diagnostics.Contracts/ContractPublicPropertyNameAttribute.cs
+System.Diagnostics.Contracts/ContractReferenceAssemblyAttribute.cs
+System.Diagnostics.Contracts/ContractRuntimeIgnoredAttribute.cs
+System.Diagnostics.Contracts/ContractVerificationAttribute.cs
+System.Diagnostics.Contracts/PureAttribute.cs
+System.Diagnostics.SymbolStore/ISymbolBinder.cs
+System.Diagnostics.SymbolStore/ISymbolBinder1.cs
+System.Diagnostics.SymbolStore/ISymbolDocument.cs
+System.Diagnostics.SymbolStore/ISymbolDocumentWriter.cs
+System.Diagnostics.SymbolStore/ISymbolMethod.cs
+System.Diagnostics.SymbolStore/ISymbolNamespace.cs
+System.Diagnostics.SymbolStore/ISymbolReader.cs
+System.Diagnostics.SymbolStore/ISymbolScope.cs
+System.Diagnostics.SymbolStore/ISymbolVariable.cs
+System.Diagnostics.SymbolStore/ISymbolWriter.cs
+System.Diagnostics.SymbolStore/SymAddressKind.cs
+System.Diagnostics.SymbolStore/SymbolToken.cs
+System.Diagnostics.SymbolStore/SymDocumentType.cs
+System.Diagnostics.SymbolStore/SymLanguageType.cs
+System.Diagnostics.SymbolStore/SymLanguageVendor.cs
+System.Globalization/Calendar.cs
+System.Globalization/CalendarWeekRule.cs
+System.Globalization/CalendricalCalculations.cs
+System.Globalization/CharUnicodeInfo.cs
+System.Globalization/CompareInfo.cs
+System.Globalization/CompareOptions.cs
+System.Globalization/CultureInfo.cs
+System.Globalization/DateTimeFormatInfo.cs
+System.Globalization/DateTimeStyles.cs
+System.Globalization/DaylightTime.cs
+System.Globalization/GregorianCalendar.cs
+System.Globalization/GregorianCalendarTypes.cs
+System.Globalization/HebrewCalendar.cs
+System.Globalization/HijriCalendar.cs
+System.Globalization/JapaneseCalendar.cs
+System.Globalization/KoreanCalendar.cs
+System.Globalization/NumberFormatInfo.cs
+System.Globalization/NumberStyles.cs
+System.Globalization/RegionInfo.cs
+System.Globalization/StringInfo.cs
+System.Globalization/TaiwanCalendar.cs
+System.Globalization/TextElementEnumerator.cs
+System.Globalization/TextInfo.cs
+System.Globalization/ThaiBuddhistCalendar.cs
+System.Globalization/UmAlQuraCalendar.cs
+System.Globalization/UnicodeCategory.cs
+System.IO/BinaryReader.cs
+System.IO/BinaryWriter.cs
+System.IO/BufferedStream.cs
+System.IO/Directory.cs
+System.IO/DirectoryInfo.cs
+System.IO/DirectoryNotFoundException.cs
+System.IO/EndOfStreamException.cs
+System.IO/File.cs
+System.IO/FileAccess.cs
+System.IO/FileAttributes.cs
+System.IO/FileInfo.cs
+System.IO/FileLoadException.cs
+System.IO/FileMode.cs
+System.IO/FileNotFoundException.cs
+System.IO/FileOptions.cs
+System.IO/FileShare.cs
+System.IO/FileStream.cs
+System.IO/FileStreamAsyncResult.cs
+System.IO/FileSystemInfo.cs
+System.IO/IOException.cs
+System.IO/MemoryStream.cs
+System.IO/MonoIO.cs
+System.IO/MonoIOError.cs
+System.IO/MonoFileType.cs
+System.IO/MonoIOStat.cs
+System.IO/Path.cs
+System.IO/PathTooLongException.cs
+System.IO/SearchOption.cs
+System.IO/SearchPattern.cs
+System.IO/SeekOrigin.cs
+System.IO/Stream.cs
+System.IO/StreamAsyncResult.cs
+System.IO/StreamReader.cs
+System.IO/StreamWriter.cs
+System.IO/StringReader.cs
+System.IO/StringWriter.cs
+System.IO/TextReader.cs
+System.IO/TextWriter.cs
+System.IO/UnexceptionalStreamReader.cs
+System.IO/UnexceptionalStreamWriter.cs
+System.IO/UnmanagedMemoryAccessor.cs
+System.IO/UnmanagedMemoryStream.cs
+System.IO.IsolatedStorage/MoonIsolatedStorage.cs
+System.IO.IsolatedStorage/MoonIsolatedStorageFile.cs
+System.IO.IsolatedStorage/MoonIsolatedStorageFileStream.cs
+System.IO.IsolatedStorage/IsolatedStorageException.cs
+System.Reflection/AmbiguousMatchException.cs
+System.Reflection/Assembly.cs
+System.Reflection/AssemblyAlgorithmIdAttribute.cs
+System.Reflection/AssemblyCompanyAttribute.cs
+System.Reflection/AssemblyConfigurationAttribute.cs
+System.Reflection/AssemblyCopyrightAttribute.cs
+System.Reflection/AssemblyCultureAttribute.cs
+System.Reflection/AssemblyDefaultAliasAttribute.cs
+System.Reflection/AssemblyDelaySignAttribute.cs
+System.Reflection/AssemblyDescriptionAttribute.cs
+System.Reflection/AssemblyFileVersionAttribute.cs
+System.Reflection/AssemblyFlagsAttribute.cs
+System.Reflection/AssemblyInformationalVersionAttribute.cs
+System.Reflection/AssemblyKeyFileAttribute.cs
+System.Reflection/AssemblyKeyNameAttribute.cs
+System.Reflection/AssemblyName.cs
+System.Reflection/AssemblyNameFlags.cs
+System.Reflection/AssemblyNameProxy.cs
+System.Reflection/AssemblyProductAttribute.cs
+System.Reflection/AssemblyTitleAttribute.cs
+System.Reflection/AssemblyTradeMarkAttribute.cs
+System.Reflection/AssemblyVersionAttribute.cs
+System.Reflection/Binder.cs
+System.Reflection/BindingFlags.cs
+System.Reflection/CallingConventions.cs
+System.Reflection/ConstructorInfo.cs
+System.Reflection/CustomAttributeData.cs
+System.Reflection/CustomAttributeFormatException.cs
+System.Reflection/CustomAttributeNamedArgument.cs
+System.Reflection/CustomAttributeTypedArgument.cs
+System.Reflection/DefaultMemberAttribute.cs
+System.Reflection/EventAttributes.cs
+System.Reflection/EventInfo.cs
+System.Reflection/ExceptionHandlingClause.cs
+System.Reflection/ExceptionHandlingClauseOptions.cs
+System.Reflection/FieldAttributes.cs
+System.Reflection/FieldInfo.cs
+System.Reflection/GenericParameterAttributes.cs
+System.Reflection/ICustomAttributeProvider.cs
+System.Reflection/ImageFileMachine.cs
+System.Reflection/InterfaceMapping.cs
+System.Reflection/IReflect.cs
+System.Reflection/LocalVariableInfo.cs
+System.Reflection/ManifestResourceInfo.cs
+System.Reflection/MemberFilter.cs
+System.Reflection/MemberInfo.cs
+System.Reflection/MemberInfoSerializationHolder.cs
+System.Reflection/MemberTypes.cs
+System.Reflection/MethodAttributes.cs
+System.Reflection/MethodBase.cs
+System.Reflection/MethodBody.cs
+System.Reflection/MethodImplAttributes.cs
+System.Reflection/MethodInfo.cs
+System.Reflection/Missing.cs
+System.Reflection/Module.cs
+System.Reflection/ModuleResolveEventHandler.cs
+System.Reflection/MonoAssembly.cs
+System.Reflection/MonoGenericClass.cs
+System.Reflection/MonoGenericMethod.cs
+System.Reflection/MonoEvent.cs
+System.Reflection/MonoField.cs
+System.Reflection/MonoMethod.cs
+System.Reflection/MonoModule.cs
+System.Reflection/MonoProperty.cs
+System.Reflection/ObfuscateAssemblyAttribute.cs
+System.Reflection/ObfuscationAttribute.cs
+System.Reflection/ParameterAttributes.cs
+System.Reflection/ParameterInfo.cs
+System.Reflection/ParameterModifier.cs
+System.Reflection/Pointer.cs
+System.Reflection/PortableExecutableKinds.cs
+System.Reflection/ProcessorArchitecture.cs
+System.Reflection/PropertyAttributes.cs
+System.Reflection/PropertyInfo.cs
+System.Reflection/ReflectionTypeLoadException.cs
+System.Reflection/ResourceAttributes.cs
+System.Reflection/ResourceLocation.cs
+System.Reflection/StrongNameKeyPair.cs
+System.Reflection/TargetException.cs
+System.Reflection/TargetInvocationException.cs
+System.Reflection/TargetParameterCountException.cs
+System.Reflection/TypeAttributes.cs
+System.Reflection/TypeDelegator.cs
+System.Reflection/TypeFilter.cs
+System.Reflection.Emit/AssemblyBuilder.cs
+System.Reflection.Emit/AssemblyBuilderAccess.cs
+System.Reflection.Emit/ConstructorBuilder.cs
+System.Reflection.Emit/ConstructorOnTypeBuilderInst.cs
+System.Reflection.Emit/CustomAttributeBuilder.cs
+System.Reflection.Emit/DerivedTypes.cs
+System.Reflection.Emit/DynamicILInfo.cs
+System.Reflection.Emit/DynamicMethod.cs
+System.Reflection.Emit/EnumBuilder.cs
+System.Reflection.Emit/EventBuilder.cs
+System.Reflection.Emit/EventOnTypeBuilderInst.cs
+System.Reflection.Emit/EventToken.cs
+System.Reflection.Emit/FieldBuilder.cs
+System.Reflection.Emit/FieldOnTypeBuilderInst.cs
+System.Reflection.Emit/FieldToken.cs
+System.Reflection.Emit/FlowControl.cs
+System.Reflection.Emit/GenericTypeParameterBuilder.cs
+System.Reflection.Emit/ILGenerator.cs
+System.Reflection.Emit/Label.cs
+System.Reflection.Emit/LocalBuilder.cs
+System.Reflection.Emit/MethodBuilder.cs
+System.Reflection.Emit/MethodOnTypeBuilderInst.cs
+System.Reflection.Emit/MethodToken.cs
+System.Reflection.Emit/MethodRental.cs
+System.Reflection.Emit/ModuleBuilder.cs
+System.Reflection.Emit/MonoArrayMethod.cs
+System.Reflection.Emit/OpCodeNames.cs
+System.Reflection.Emit/OpCode.cs
+System.Reflection.Emit/OpCodes.cs
+System.Reflection.Emit/OpCodeType.cs
+System.Reflection.Emit/OperandType.cs
+System.Reflection.Emit/PackingSize.cs
+System.Reflection.Emit/ParameterBuilder.cs
+System.Reflection.Emit/ParameterToken.cs
+System.Reflection.Emit/PEFileKinds.cs
+System.Reflection.Emit/PropertyBuilder.cs
+System.Reflection.Emit/PropertyOnTypeBuilderInst.cs
+System.Reflection.Emit/PropertyToken.cs
+System.Reflection.Emit/SignatureHelper.cs
+System.Reflection.Emit/SignatureToken.cs
+System.Reflection.Emit/StackBehaviour.cs
+System.Reflection.Emit/StringToken.cs
+System.Reflection.Emit/TypeBuilder.cs
+System.Reflection.Emit/TypeToken.cs
+System.Reflection.Emit/UnmanagedMarshal.cs
+System.Resources/IResourceReader.cs
+System.Resources/IResourceWriter.cs
+System.Resources/MissingManifestResourceException.cs
+System.Resources/NeutralResourcesLanguageAttribute.cs
+System.Resources/ResourceManager.cs
+System.Resources/ResourceReader.cs
+System.Resources/ResourceSet.cs
+System.Resources/ResourceWriter.cs
+System.Resources/RuntimeResourceSet.cs
+System.Resources/SatelliteContractVersionAttribute.cs
+System.Resources/UltimateResourceFallbackLocation.cs
+System.Resources/Win32Resources.cs
+System.Runtime.CompilerServices/AccessedThroughPropertyAttribute.cs
+System.Runtime.CompilerServices/CallConvCdecl.cs
+System.Runtime.CompilerServices/CallConvFastcall.cs
+System.Runtime.CompilerServices/CallConvThiscall.cs
+System.Runtime.CompilerServices/CallConvStdcall.cs
+System.Runtime.CompilerServices/CompilationRelaxations.cs
+System.Runtime.CompilerServices/CompilationRelaxationsAttribute.cs
+System.Runtime.CompilerServices/CompilerGeneratedAttribute.cs
+System.Runtime.CompilerServices/CompilerGlobalScopeAttribute.cs
+System.Runtime.CompilerServices/CompilerMarshalOverride.cs
+System.Runtime.CompilerServices/ConditionalWeakTable.cs
+System.Runtime.CompilerServices/CustomConstantAttribute.cs
+System.Runtime.CompilerServices/DateTimeConstantAttribute.cs
+System.Runtime.CompilerServices/DecimalConstantAttribute.cs
+System.Runtime.CompilerServices/DefaultDependencyAttribute.cs
+System.Runtime.CompilerServices/DependencyAttribute.cs
+System.Runtime.CompilerServices/DiscardableAttribute.cs
+System.Runtime.CompilerServices/FixedAddressValueTypeAttribute.cs
+System.Runtime.CompilerServices/FixedBufferAttribute.cs
+System.Runtime.CompilerServices/HasCopySemanticsAttribute.cs
+System.Runtime.CompilerServices/IDispatchConstantAttribute.cs
+System.Runtime.CompilerServices/IUnknownConstantAttribute.cs
+System.Runtime.CompilerServices/IndexerNameAttribute.cs
+System.Runtime.CompilerServices/InternalsVisibleToAttribute.cs
+System.Runtime.CompilerServices/IsBoxed.cs
+System.Runtime.CompilerServices/IsByValue.cs
+System.Runtime.CompilerServices/IsConst.cs
+System.Runtime.CompilerServices/IsCopyConstructed.cs
+System.Runtime.CompilerServices/IsExplicitlyDereferenced.cs
+System.Runtime.CompilerServices/IsImplicitlyDereferenced.cs
+System.Runtime.CompilerServices/IsJitIntrinsic.cs
+System.Runtime.CompilerServices/IsLong.cs
+System.Runtime.CompilerServices/IsPinned.cs
+System.Runtime.CompilerServices/IsSignUnspecifiedByte.cs
+System.Runtime.CompilerServices/IsUdtReturn.cs
+System.Runtime.CompilerServices/IsVolatile.cs
+System.Runtime.CompilerServices/LoadHint.cs
+System.Runtime.CompilerServices/MethodCodeType.cs
+System.Runtime.CompilerServices/MethodImplAttribute.cs
+System.Runtime.CompilerServices/MethodImplOptions.cs
+System.Runtime.CompilerServices/NativeCppClassAttribute.cs
+System.Runtime.CompilerServices/ReferenceAssemblyAttribute.cs
+System.Runtime.CompilerServices/RequiredAttributeAttribute.cs
+System.Runtime.CompilerServices/RuntimeCompatibilityAttribute.cs
+System.Runtime.CompilerServices/RuntimeHelpers.cs
+System.Runtime.CompilerServices/RuntimeWrappedException.cs
+System.Runtime.CompilerServices/SpecialNameAttribute.cs 
+System.Runtime.CompilerServices/ScopelessEnumAttribute.cs
+System.Runtime.CompilerServices/SuppressIldasmAttribute.cs
+System.Runtime.CompilerServices/StringFreezingAttribute.cs 
+System.Runtime.CompilerServices/UnsafeValueTypeAttribute.cs
+System.Runtime.CompilerServices/TypeForwardedFromAttribute.cs
+System.Runtime.CompilerServices/TypeForwardedToAttribute.cs
+System.Runtime.ConstrainedExecution/CriticialFinalizerObject.cs
+System.Runtime.ConstrainedExecution/CER.cs
+System.Runtime.ConstrainedExecution/Consistency.cs
+System.Runtime.ConstrainedExecution/PrePrepareMethodAttribute.cs
+System.Runtime.ConstrainedExecution/ReliabilityContractAttribute.cs
+System.Runtime.InteropServices/_Activator.cs
+System.Runtime.InteropServices/_Assembly.cs
+System.Runtime.InteropServices/_AssemblyBuilder.cs
+System.Runtime.InteropServices/_AssemblyName.cs
+System.Runtime.InteropServices/_Attribute.cs
+System.Runtime.InteropServices/_ConstructorBuilder.cs
+System.Runtime.InteropServices/_ConstructorInfo.cs
+System.Runtime.InteropServices/_CustomAttributeBuilder.cs
+System.Runtime.InteropServices/_EnumBuilder.cs
+System.Runtime.InteropServices/_EventBuilder.cs
+System.Runtime.InteropServices/_EventInfo.cs
+System.Runtime.InteropServices/_Exception.cs
+System.Runtime.InteropServices/_FieldBuilder.cs
+System.Runtime.InteropServices/_FieldInfo.cs
+System.Runtime.InteropServices/_ILGenerator.cs
+System.Runtime.InteropServices/_LocalBuilder.cs
+System.Runtime.InteropServices/_MemberInfo.cs
+System.Runtime.InteropServices/_MethodBase.cs
+System.Runtime.InteropServices/_MethodBuilder.cs
+System.Runtime.InteropServices/_MethodInfo.cs
+System.Runtime.InteropServices/_MethodRental.cs
+System.Runtime.InteropServices/_Module.cs
+System.Runtime.InteropServices/_ModuleBuilder.cs
+System.Runtime.InteropServices/_ParameterBuilder.cs
+System.Runtime.InteropServices/_ParameterInfo.cs
+System.Runtime.InteropServices/_PropertyBuilder.cs
+System.Runtime.InteropServices/_PropertyInfo.cs
+System.Runtime.InteropServices/_SignatureHelper.cs
+System.Runtime.InteropServices/_Thread.cs
+System.Runtime.InteropServices/_Type.cs
+System.Runtime.InteropServices/_TypeBuilder.cs
+System.Runtime.InteropServices/AllowReversePInvokeCallsAttribute.cs
+System.Runtime.InteropServices/CallingConvention.cs
+System.Runtime.InteropServices/CharSet.cs
+System.Runtime.InteropServices/ClassInterfaceAttribute.cs
+System.Runtime.InteropServices/ClassInterfaceType.cs
+System.Runtime.InteropServices/CoClassAttribute.cs
+System.Runtime.InteropServices/ComDefaultInterfaceAttribute.cs
+System.Runtime.InteropServices/COMException.cs
+System.Runtime.InteropServices/ComImportAttribute.cs
+System.Runtime.InteropServices/ComInterfaceType.cs
+System.Runtime.InteropServices/ComVisible.cs
+System.Runtime.InteropServices/CriticalHandle.cs
+System.Runtime.InteropServices/DefaultCharSetAttribute.cs
+System.Runtime.InteropServices/DispIdAttribute.cs
+System.Runtime.InteropServices/DllImportAttribute.cs
+System.Runtime.InteropServices/ExternalException.cs
+System.Runtime.InteropServices/FieldOffsetAttribute.cs
+System.Runtime.InteropServices/GCHandle.cs
+System.Runtime.InteropServices/GCHandleType.cs
+System.Runtime.InteropServices/GuidAttribute.cs
+System.Runtime.InteropServices/HandleRef.cs
+System.Runtime.InteropServices/InAttribute.cs
+System.Runtime.InteropServices/InterfaceTypeAttribute.cs
+System.Runtime.InteropServices/LayoutKind.cs
+System.Runtime.InteropServices/Marshal.cs
+System.Runtime.InteropServices/MarshalAsAttribute.cs
+System.Runtime.InteropServices/MarshalDirectiveException.cs
+System.Runtime.InteropServices/OptionalAttribute.cs
+System.Runtime.InteropServices/OutAttribute.cs
+System.Runtime.InteropServices/PreserveSigAttribute.cs
+System.Runtime.InteropServices/SEHException.cs
+System.Runtime.InteropServices/SafeHandle.cs
+System.Runtime.InteropServices/StructLayoutAttribute.cs
+System.Runtime.InteropServices/TypeLibImportClassAttribute.cs
+System.Runtime.InteropServices/TypeLibVersionAttribute.cs
+System.Runtime.InteropServices/UnmanagedFunctionPointerAttribute.cs
+System.Runtime.InteropServices/UnmanagedType.cs
+System.Runtime.Remoting/ActivatedClientTypeEntry.cs
+System.Runtime.Remoting/ActivatedServiceTypeEntry.cs
+System.Runtime.Remoting/CustomErrorsModes.cs
+System.Runtime.Remoting/EnvoyInfo.cs
+System.Runtime.Remoting/IObjectHandle.cs
+System.Runtime.Remoting/IChannelInfo.cs
+System.Runtime.Remoting/Identity.cs
+System.Runtime.Remoting/InternalRemotingServices.cs
+System.Runtime.Remoting/IEnvoyInfo.cs
+System.Runtime.Remoting/IRemotingTypeInfo.cs
+System.Runtime.Remoting/ObjectHandle.cs
+System.Runtime.Remoting/ObjRef.cs
+System.Runtime.Remoting/RemotingConfiguration.cs
+System.Runtime.Remoting/RemotingException.cs
+System.Runtime.Remoting/RemotingTimeoutException.cs
+System.Runtime.Remoting/RemotingServices.cs
+System.Runtime.Remoting/ServerException.cs
+System.Runtime.Remoting/ServerIdentity.cs
+System.Runtime.Remoting/SoapServices.cs
+System.Runtime.Remoting/TypeEntry.cs
+System.Runtime.Remoting/TypeInfo.cs
+System.Runtime.Remoting/WellKnownObjectMode.cs
+System.Runtime.Remoting/WellKnownClientTypeEntry.cs
+System.Runtime.Remoting/WellKnownServiceTypeEntry.cs
+System.Runtime.Remoting.Activation/ActivationServices.cs
+System.Runtime.Remoting.Activation/ActivatorLevel.cs
+System.Runtime.Remoting.Activation/AppDomainLevelActivator.cs
+System.Runtime.Remoting.Activation/ConstructionLevelActivator.cs
+System.Runtime.Remoting.Activation/ContextLevelActivator.cs
+System.Runtime.Remoting.Activation/IActivator.cs
+System.Runtime.Remoting.Activation/IConstructionCallMessage.cs
+System.Runtime.Remoting.Activation/IConstructionReturnMessage.cs
+System.Runtime.Remoting.Activation/RemoteActivator.cs
+System.Runtime.Remoting.Activation/RemoteActivationAttribute.cs
+System.Runtime.Remoting.Activation/UrlAttribute.cs
+System.Runtime.Remoting.Channels/AggregateDictionary.cs
+System.Runtime.Remoting.Channels/BaseChannelObjectWithProperties.cs
+System.Runtime.Remoting.Channels/BaseChannelSinkWithProperties.cs
+System.Runtime.Remoting.Channels/BaseChannelWithProperties.cs
+System.Runtime.Remoting.Channels/ChannelDataStore.cs
+System.Runtime.Remoting.Channels/ChannelServices.cs
+System.Runtime.Remoting.Channels/ChannelSinkStackEntry.cs
+System.Runtime.Remoting.Channels/ClientChannelSinkStack.cs
+System.Runtime.Remoting.Channels/IChannel.cs
+System.Runtime.Remoting.Channels/IChannelDataStore.cs
+System.Runtime.Remoting.Channels/IChannelReceiver.cs
+System.Runtime.Remoting.Channels/IChannelReceiverHook.cs
+System.Runtime.Remoting.Channels/IChannelSender.cs
+System.Runtime.Remoting.Channels/IChannelSinkBase.cs
+System.Runtime.Remoting.Channels/IClientChannelSink.cs
+System.Runtime.Remoting.Channels/IClientChannelSinkProvider.cs
+System.Runtime.Remoting.Channels/IClientChannelSinkStack.cs
+System.Runtime.Remoting.Channels/IClientFormatterSink.cs
+System.Runtime.Remoting.Channels/IClientFormatterSinkProvider.cs
+System.Runtime.Remoting.Channels/IClientResponseChannelSinkStack.cs
+System.Runtime.Remoting.Channels/ISecurableChannel.cs
+System.Runtime.Remoting.Channels/IServerResponseChannelSinkStack.cs
+System.Runtime.Remoting.Channels/ServerDispatchSink.cs
+System.Runtime.Remoting.Channels/ServerDispatchSinkProvider.cs
+System.Runtime.Remoting.Channels/IServerChannelSink.cs
+System.Runtime.Remoting.Channels/IServerChannelSinkProvider.cs
+System.Runtime.Remoting.Channels/IServerChannelSinkStack.cs
+System.Runtime.Remoting.Channels/IServerFormatterSinkProvider.cs
+System.Runtime.Remoting.Channels/ITransportHeaders.cs
+System.Runtime.Remoting.Channels/ServerChannelSinkStack.cs
+System.Runtime.Remoting.Channels/ServerProcessing.cs
+System.Runtime.Remoting.Channels/SinkProviderData.cs
+System.Runtime.Remoting.Channels/TransportHeaders.cs
+System.Runtime.Remoting.Channels/CrossAppDomainChannel.cs
+System.Runtime.Remoting.Contexts/Context.cs
+System.Runtime.Remoting.Contexts/ContextAttribute.cs
+System.Runtime.Remoting.Contexts/ContextProperty.cs
+System.Runtime.Remoting.Contexts/CrossContextChannel.cs
+System.Runtime.Remoting.Contexts/CrossContextDelegate.cs
+System.Runtime.Remoting.Contexts/IContextAttribute.cs
+System.Runtime.Remoting.Contexts/IContextProperty.cs
+System.Runtime.Remoting.Contexts/IContextPropertyActivator.cs
+System.Runtime.Remoting.Contexts/IContributeClientContextSink.cs
+System.Runtime.Remoting.Contexts/IContributeDynamicSink.cs
+System.Runtime.Remoting.Contexts/IContributeEnvoySink.cs
+System.Runtime.Remoting.Contexts/IContributeObjectSink.cs
+System.Runtime.Remoting.Contexts/IContributeServerContextSink.cs
+System.Runtime.Remoting.Contexts/IDynamicMessageSink.cs
+System.Runtime.Remoting.Contexts/IDynamicProperty.cs
+System.Runtime.Remoting.Contexts/SynchronizationAttribute.cs
+System.Runtime.Remoting.Lifetime/ClientSponsor.cs
+System.Runtime.Remoting.Lifetime/ILease.cs
+System.Runtime.Remoting.Lifetime/ISponsor.cs
+System.Runtime.Remoting.Lifetime/Lease.cs
+System.Runtime.Remoting.Lifetime/LeaseManager.cs
+System.Runtime.Remoting.Lifetime/LeaseSink.cs
+System.Runtime.Remoting.Lifetime/LeaseState.cs
+System.Runtime.Remoting.Lifetime/LifetimeServices.cs
+System.Runtime.Remoting.Messaging/ArgInfo.cs
+System.Runtime.Remoting.Messaging/AsyncResult.cs
+System.Runtime.Remoting.Messaging/CallContext.cs
+System.Runtime.Remoting.Messaging/ClientContextTerminatorSink.cs
+System.Runtime.Remoting.Messaging/ConstructionCall.cs
+System.Runtime.Remoting.Messaging/ConstructionCallDictionary.cs
+System.Runtime.Remoting.Messaging/ConstructionResponse.cs
+System.Runtime.Remoting.Messaging/EnvoyTerminatorSink.cs
+System.Runtime.Remoting.Messaging/Header.cs
+System.Runtime.Remoting.Messaging/HeaderHandler.cs
+System.Runtime.Remoting.Messaging/ErrorMessage.cs
+System.Runtime.Remoting.Messaging/IInternalMessage.cs
+System.Runtime.Remoting.Messaging/IMessage.cs
+System.Runtime.Remoting.Messaging/IMessageCtrl.cs
+System.Runtime.Remoting.Messaging/IMessageSink.cs
+System.Runtime.Remoting.Messaging/IMethodCallMessage.cs
+System.Runtime.Remoting.Messaging/IMethodMessage.cs
+System.Runtime.Remoting.Messaging/IMethodReturnMessage.cs
+System.Runtime.Remoting.Messaging/IRemotingFormatter.cs
+System.Runtime.Remoting.Messaging/InternalMessageWrapper.cs
+System.Runtime.Remoting.Messaging/ISerializationRootObject.cs
+System.Runtime.Remoting.Messaging/LogicalCallContext.cs
+System.Runtime.Remoting.Messaging/MessageSurrogateFilter.cs
+System.Runtime.Remoting.Messaging/MethodCall.cs
+System.Runtime.Remoting.Messaging/MethodCallMessageWrapper.cs
+System.Runtime.Remoting.Messaging/MethodResponse.cs
+System.Runtime.Remoting.Messaging/MethodCallDictionary.cs
+System.Runtime.Remoting.Messaging/MethodDictionary.cs
+System.Runtime.Remoting.Messaging/MethodReturnDictionary.cs
+System.Runtime.Remoting.Messaging/MethodReturnMessageWrapper.cs
+System.Runtime.Remoting.Messaging/MonoMethodMessage.cs
+System.Runtime.Remoting.Messaging/OneWayAttribute.cs
+System.Runtime.Remoting.Messaging/RemotingSurrogateSelector.cs
+System.Runtime.Remoting.Messaging/RemotingSurrogate.cs
+System.Runtime.Remoting.Messaging/ReturnMessage.cs
+System.Runtime.Remoting.Messaging/ServerContextTerminatorSink.cs
+System.Runtime.Remoting.Messaging/ServerObjectTerminatorSink.cs
+System.Runtime.Remoting.Messaging/StackBuilderSink.cs
+System.Runtime.Remoting.Messaging/CADMessages.cs
+System.Runtime.Remoting.Metadata/SoapAttribute.cs
+System.Runtime.Remoting.Metadata/SoapFieldAttribute.cs
+System.Runtime.Remoting.Metadata/SoapMethodAttribute.cs
+System.Runtime.Remoting.Metadata/SoapOption.cs
+System.Runtime.Remoting.Metadata/SoapParameterAttribute.cs
+System.Runtime.Remoting.Metadata/SoapTypeAttribute.cs
+System.Runtime.Remoting.Metadata/XmlFieldOrderOption.cs
+System.Runtime.Remoting.Proxies/RealProxy.cs
+System.Runtime.Remoting.Proxies/RemotingProxy.cs
+System.Runtime.Remoting.Proxies/ProxyAttribute.cs
+System.Runtime.Remoting.Services/EnterpriseServicesHelper.cs
+System.Runtime.Remoting.Services/ITrackingHandler.cs
+System.Runtime.Remoting.Services/TrackingServices.cs
+System.Runtime.Serialization/Formatter.cs
+System.Runtime.Serialization/FormatterConverter.cs
+System.Runtime.Serialization/FormatterServices.cs
+System.Runtime.Serialization/IDeserializationCallback.cs
+System.Runtime.Serialization/IFormatter.cs
+System.Runtime.Serialization/IFormatterConverter.cs
+System.Runtime.Serialization/IObjectReference.cs
+System.Runtime.Serialization/ISerializable.cs
+System.Runtime.Serialization/ISerializationSurrogate.cs
+System.Runtime.Serialization/ISurrogateSelector.cs
+System.Runtime.Serialization/ObjectIDGenerator.cs
+System.Runtime.Serialization/ObjectManager.cs
+System.Runtime.Serialization/OnDeserializedAttribute.cs
+System.Runtime.Serialization/OnDeserializingAttribute.cs
+System.Runtime.Serialization/OnSerializedAttribute.cs
+System.Runtime.Serialization/OnSerializingAttribute.cs
+System.Runtime.Serialization/OptionalFieldAttribute.cs
+System.Runtime.Serialization/SerializationBinder.cs
+System.Runtime.Serialization/SerializationCallbacks.cs
+System.Runtime.Serialization/SerializationEntry.cs
+System.Runtime.Serialization/SerializationException.cs
+System.Runtime.Serialization/SerializationInfo.cs
+System.Runtime.Serialization/SerializationInfoEnumerator.cs
+System.Runtime.Serialization/SerializationObjectManager.cs
+System.Runtime.Serialization/StreamingContext.cs
+System.Runtime.Serialization/StreamingContextStates.cs
+System.Runtime.Serialization/SurrogateSelector.cs
+System.Runtime.Serialization.Formatters/FormatterAssemblyStyle.cs
+System.Runtime.Serialization.Formatters/FormatterTopObjectStyle.cs
+System.Runtime.Serialization.Formatters/FormatterTypeStyle.cs
+System.Runtime.Serialization.Formatters/IFieldInfo.cs
+System.Runtime.Serialization.Formatters/InternalArrayTypeE.cs
+System.Runtime.Serialization.Formatters/InternalElementTypeE.cs
+System.Runtime.Serialization.Formatters/InternalMemberTypeE.cs
+System.Runtime.Serialization.Formatters/InternalMemberValueE.cs
+System.Runtime.Serialization.Formatters/InternalNameSpaceE.cs
+System.Runtime.Serialization.Formatters/InternalObjectPositionE.cs
+System.Runtime.Serialization.Formatters/InternalObjectTypeE.cs
+System.Runtime.Serialization.Formatters/InternalParseStateE.cs
+System.Runtime.Serialization.Formatters/InternalParseTypeE.cs
+System.Runtime.Serialization.Formatters/InternalPrimitiveTypeE.cs
+System.Runtime.Serialization.Formatters/InternalRM.cs
+System.Runtime.Serialization.Formatters/InternalSerializerTypeE.cs
+System.Runtime.Serialization.Formatters/InternalST.cs
+System.Runtime.Serialization.Formatters/ISoapMessage.cs
+System.Runtime.Serialization.Formatters/ServerFault.cs
+System.Runtime.Serialization.Formatters/SoapFault.cs
+System.Runtime.Serialization.Formatters/SoapMessage.cs
+System.Runtime.Serialization.Formatters/TypeFilterLevel.cs
+System.Runtime.Serialization.Formatters.Binary/BinaryFormatter.cs
+System.Runtime.Serialization.Formatters.Binary/BinaryCommon.cs
+System.Runtime.Serialization.Formatters.Binary/CodeGenerator.cs
+System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs
+System.Runtime.Serialization.Formatters.Binary/ObjectWriter.cs
+System.Runtime.Serialization.Formatters.Binary/MessageFormatter.cs
+System.Runtime.Versioning/ResourceExposureAttribute.cs
+System.Runtime.Versioning/ResourceScope.cs
+System.Runtime.Versioning/VersioningHelper.cs
+System.Security/AllowPartiallyTrustedCallersAttribute.cs
+System.Security/CodeAccessPermission_2_1.cs
+System.Security/IPermission.cs
+System.Security/PermissionSet_2_1.cs
+System.Security/SecurityCriticalAttribute.cs
+System.Security/SecurityFrame.cs
+System.Security/SecurityException_2_1.cs
+System.Security/SecurityManager_2_1.cs
+System.Security/SecuritySafeCriticalAttribute.cs
+System.Security/SecurityState.cs
+System.Security/SecurityTransparentAttribute.cs
+System.Security/SuppressUnmanagedCodeSecurityAttribute.cs
+System.Security/UnverifiableCodeAttribute.cs
+System.Security/VerificationException.cs
+../System.Core/System.Security.Cryptography/Aes.cs
+System.Security.Cryptography/AsymmetricAlgorithm.cs
+System.Security.Cryptography/AsymmetricKeyExchangeDeformatter.cs
+System.Security.Cryptography/AsymmetricKeyExchangeFormatter.cs
+System.Security.Cryptography/AsymmetricSignatureDeformatter.cs
+System.Security.Cryptography/AsymmetricSignatureFormatter.cs
+System.Security.Cryptography/Base64Constants.cs
+System.Security.Cryptography/CipherMode.cs
+System.Security.Cryptography/CryptoAPITransform.cs
+System.Security.Cryptography/CryptoConfig_2_1.cs
+System.Security.Cryptography/CryptographicException.cs
+System.Security.Cryptography/CryptographicUnexpectedOperationExcpetion.cs
+System.Security.Cryptography/CryptoStream.cs
+System.Security.Cryptography/CryptoStreamMode.cs
+System.Security.Cryptography/DeriveBytes.cs
+System.Security.Cryptography/DES.cs
+System.Security.Cryptography/DESCryptoServiceProvider.cs
+System.Security.Cryptography/DSA.cs
+System.Security.Cryptography/DSAParameters.cs
+System.Security.Cryptography/DSASignatureDeformatter.cs
+System.Security.Cryptography/DSASignatureFormatter.cs
+System.Security.Cryptography/FromBase64Transform.cs
+System.Security.Cryptography/HashAlgorithm.cs
+System.Security.Cryptography/HMAC.cs
+System.Security.Cryptography/HMACMD5.cs
+System.Security.Cryptography/HMACSHA1.cs
+System.Security.Cryptography/HMACSHA256.cs
+System.Security.Cryptography/ICryptoTransform.cs
+System.Security.Cryptography/KeyedHashAlgorithm.cs
+System.Security.Cryptography/KeyNumber.cs
+System.Security.Cryptography/KeySizes.cs
+System.Security.Cryptography/MaskGenerationMethod.cs
+System.Security.Cryptography/MD5.cs
+System.Security.Cryptography/MD5CryptoServiceProvider.cs
+System.Security.Cryptography/PaddingMode.cs
+System.Security.Cryptography/PKCS1MaskGenerationMethod.cs
+System.Security.Cryptography/RandomNumberGenerator.cs
+System.Security.Cryptography/RC2.cs
+System.Security.Cryptography/RC2CryptoServiceProvider.cs
+System.Security.Cryptography/Rfc2898DeriveBytes.cs
+System.Security.Cryptography/Rijndael.cs
+System.Security.Cryptography/RijndaelManaged.cs
+System.Security.Cryptography/RijndaelManagedTransform.cs
+System.Security.Cryptography/RNGCryptoServiceProvider.cs
+System.Security.Cryptography/RSA.cs
+System.Security.Cryptography/RSAOAEPKeyExchangeDeformatter.cs
+System.Security.Cryptography/RSAOAEPKeyExchangeFormatter.cs
+System.Security.Cryptography/RSAParameters.cs
+System.Security.Cryptography/RSAPKCS1KeyExchangeDeformatter.cs
+System.Security.Cryptography/RSAPKCS1KeyExchangeFormatter.cs
+System.Security.Cryptography/RSAPKCS1SignatureDeformatter.cs
+System.Security.Cryptography/RSAPKCS1SignatureFormatter.cs
+System.Security.Cryptography/SHA1.cs
+System.Security.Cryptography/SHA1CryptoServiceProvider.cs
+System.Security.Cryptography/SHA1Managed.cs
+System.Security.Cryptography/SHA256.cs
+System.Security.Cryptography/SHA256Managed.cs
+System.Security.Cryptography/SHAConstants.cs
+System.Security.Cryptography/SymmetricAlgorithm.cs
+System.Security.Cryptography/ToBase64Transform.cs
+System.Security.Cryptography/TripleDES.cs
+System.Security.Cryptography/TripleDESCryptoServiceProvider.cs
+System.Security.Cryptography.X509Certificates/X509Certificate.cs
+System.Security.Cryptography.X509Certificates/X509Certificate20.cs
+System.Security.Cryptography.X509Certificates/X509ContentType.cs
+System.Security.Cryptography.X509Certificates/X509KeyStorageFlags.cs
+System.Security.Permissions/CodeAccessSecurityAttribute.cs
+System.Security.Permissions/EnvironmentPermissionAccess.cs
+System.Security.Permissions/EnvironmentPermissionAttribute.cs
+System.Security.Permissions/FileIOPermissionAccess.cs
+System.Security.Permissions/FileIOPermissionAttribute.cs
+System.Security.Permissions/HostProtectionAttribute.cs
+System.Security.Permissions/HostProtectionResource.cs
+System.Security.Permissions/PermissionSetAttribute.cs
+System.Security.Permissions/PermissionState.cs
+System.Security.Permissions/ReflectionPermissionAttribute.cs
+System.Security.Permissions/ReflectionPermissionFlag.cs
+System.Security.Permissions/SecurityAction.cs
+System.Security.Permissions/SecurityAttribute.cs
+System.Security.Permissions/SecurityPermissionAttribute.cs
+System.Security.Permissions/SecurityPermissionFlag.cs
+System.Security.Permissions/StrongNamePermissionAttribute.cs
+System.Security.Permissions/StrongNamePublicKeyBlob.cs
+System.Security.Policy/Evidence_2_1.cs
+System.Security.Policy/PolicyLevel_2_1.cs
+System.Security.Principal/IIdentity.cs
+System.Security.Principal/IPrincipal.cs
+System.Text/ASCIIEncoding.cs
+System.Text/Decoder.cs
+System.Text/DecoderExceptionFallback.cs
+System.Text/DecoderExceptionFallbackBuffer.cs
+System.Text/DecoderFallback.cs
+System.Text/DecoderFallbackBuffer.cs
+System.Text/DecoderFallbackException.cs
+System.Text/DecoderReplacementFallback.cs
+System.Text/DecoderReplacementFallbackBuffer.cs
+System.Text/Encoder.cs
+System.Text/EncoderExceptionFallback.cs
+System.Text/EncoderExceptionFallbackBuffer.cs
+System.Text/EncoderFallback.cs
+System.Text/EncoderFallbackBuffer.cs
+System.Text/EncoderFallbackException.cs
+System.Text/EncoderReplacementFallback.cs
+System.Text/EncoderReplacementFallbackBuffer.cs
+System.Text/Encoding.cs
+System.Text/EncodingInfo.cs
+System.Text/StringBuilder.cs
+System.Text/SurrogateEncoder.cs
+System.Text/UnicodeEncoding.cs
+System.Text/UTF7Encoding.cs
+System.Text/UTF8Encoding.cs
+System.Text/UTF32Encoding.cs
+System.Threading/AbandonedMutexException.cs
+System.Threading/AutoResetEvent.cs
+System.Threading/ContextCallback.cs
+System.Threading/EventResetMode.cs
+System.Threading/EventWaitHandle.cs
+System.Threading/ExecutionContext.cs
+System.Threading/Interlocked.cs
+System.Threading/IOCompletionCallback.cs
+System.Threading/ManualResetEvent.cs
+System.Threading/Monitor.cs
+System.Threading/Mutex.cs
+System.Threading/NativeEventCalls.cs
+System.Threading/NativeOverlapped.cs
+System.Threading/Overlapped.cs
+System.Threading/ParameterizedThreadStart.cs
+System.Threading/RegisteredWaitHandle.cs
+System.Threading/SendOrPostCallback.cs
+System.Threading/SynchronizationContext.cs
+System.Threading/SynchronizationLockException.cs
+System.Threading/Thread.cs
+System.Threading/ThreadAbortException.cs
+System.Threading/ThreadInterruptedException.cs
+System.Threading/ThreadPool.cs
+System.Threading/ThreadStart.cs
+System.Threading/ThreadStartException.cs
+System.Threading/ThreadState.cs
+System.Threading/ThreadStateException.cs
+System.Threading/Timeout.cs
+System.Threading/Timer.cs
+System.Threading/TimerCallback.cs
+System.Threading/WaitCallback.cs
+System.Threading/WaitHandle.cs
+System.Threading/WaitOrTimerCallback.cs
+System.Collections.Generic/CollectionDebuggerView.cs
+System.Collections.Generic/Dictionary.cs
+System.Collections.Generic/ICollection.cs
+System.Collections.Generic/IEnumerable.cs
+System.Collections.Generic/IEnumerator.cs
+System.Collections.Generic/IList.cs
+System.Collections.Generic/IComparer.cs
+System.Collections.Generic/IEqualityComparer.cs
+System.Collections.Generic/IDictionary.cs
+System.Collections.Generic/KeyValuePair.cs
+System.Collections.Generic/EqualityComparer.cs
+System.Collections.Generic/KeyNotFoundException.cs
+System.Collections.Generic/List.cs
+System.Collections.ObjectModel/Collection.cs
+System.Collections.ObjectModel/KeyedCollection.cs
+System.Collections.ObjectModel/ReadOnlyCollection.cs
+System/Action.cs
+System/ArraySegment.cs
+System/Comparison.cs
+System/Converter.cs
+System/Predicate.cs
+System.Collections.Generic/Comparer.cs
+../Mono.CompilerServices.SymbolWriter/MonoSymbolWriter.cs
+../Mono.CompilerServices.SymbolWriter/MonoSymbolTable.cs
+../Mono.CompilerServices.SymbolWriter/MonoSymbolFile.cs
+../Mono.CompilerServices.SymbolWriter/SymbolWriterImpl.cs
+../System.Core/System/TimeZoneInfo.AdjustmentRule.cs
+../System.Core/System/TimeZoneInfo.cs
+../System.Core/System/TimeZoneInfo.TransitionTime.cs
diff --git a/mcs/class/corlib/net_2_1_bootstrap_corlib.dll.sources b/mcs/class/corlib/net_2_1_bootstrap_corlib.dll.sources
deleted file mode 100644 (file)
index c2216ab..0000000
+++ /dev/null
@@ -1,2 +0,0 @@
-#include net_2_1_raw_corlib.dll.sources
-
diff --git a/mcs/class/corlib/net_2_1_raw_corlib.dll.sources b/mcs/class/corlib/net_2_1_raw_corlib.dll.sources
deleted file mode 100644 (file)
index 111cace..0000000
+++ /dev/null
@@ -1,1033 +0,0 @@
-Assembly/AssemblyInfo.cs
-../../build/common/Consts.cs
-../../build/common/Locale.cs
-Microsoft.Win32.SafeHandles/CriticalHandleMinusOneIsInvalid.cs
-Microsoft.Win32.SafeHandles/SafeHandleZeroOrMinusOneIsInvalid.cs
-Microsoft.Win32.SafeHandles/SafeHandleMinusOneIsInvalid.cs
-Microsoft.Win32.SafeHandles/SafeFileHandle.cs
-Microsoft.Win32.SafeHandles/SafeWaitHandle.cs
-Mono.Globalization.Unicode/CodePointIndexer.cs
-Mono.Globalization.Unicode/MSCompatUnicodeTable.cs
-Mono.Globalization.Unicode/MSCompatUnicodeTableUtil.cs
-Mono.Globalization.Unicode/SimpleCollator.cs
-Mono.Globalization.Unicode/SortKey.cs
-Mono.Globalization.Unicode/SortKeyBuffer.cs
-Mono/Runtime.cs
-Mono/DataConverter.cs
-Mono.Math/BigInteger.cs
-Mono.Math.Prime/ConfidenceFactor.cs
-Mono.Math.Prime/PrimalityTests.cs
-Mono.Math.Prime.Generator/NextPrimeFinder.cs
-Mono.Math.Prime.Generator/PrimeGeneratorBase.cs
-Mono.Math.Prime.Generator/SequentialSearchPrimeGeneratorBase.cs
-Mono.Security/ASN1.cs
-Mono.Security/ASN1Convert.cs
-Mono.Security/BitConverterLE.cs
-Mono.Security/PKCS7.cs
-Mono.Security/StrongName.cs
-Mono.Security/StrongNameManager_2_1.cs
-Mono.Security/Uri.cs
-Mono.Security.Cryptography/CryptoConvert.cs
-Mono.Security.Cryptography/CryptoTools.cs
-Mono.Security.Cryptography/DSAManaged.cs
-Mono.Security.Cryptography/KeyPairPersistence.cs
-Mono.Security.Cryptography/PKCS1.cs
-Mono.Security.Cryptography/PKCS8.cs
-Mono.Security.Cryptography/HMACAlgorithm.cs
-Mono.Security.Cryptography/SymmetricTransform.cs
-Mono.Security.Cryptography/RSAManaged.cs
-Mono.Security.X509/PKCS12.cs
-Mono.Security.X509/X501Name.cs
-Mono.Security.X509/X509Certificate.cs
-Mono.Security.X509/X509CertificateCollection.cs
-Mono.Security.X509/X509Chain.cs
-Mono.Security.X509/X509ChainStatusFlags.cs
-Mono.Security.X509/X509CRL.cs
-Mono.Security.X509/X509Extension.cs
-Mono.Security.X509/X509Extensions.cs
-Mono.Security.X509/X509Store.cs
-Mono.Security.X509/X509Stores.cs
-Mono.Security.X509/X509StoreManager.cs
-Mono.Security.X509/X520Attributes.cs
-Mono.Security.X509.Extensions/BasicConstraintsExtension.cs
-Mono.Security.X509.Extensions/KeyUsageExtension.cs
-Mono.Security.X509.Extensions/SubjectKeyIdentifierExtension.cs
-Mono.Xml/SmallXmlParser.cs
-System/AccessViolationException.cs
-System/Activator.cs
-System/AppDomain.cs
-System/AppDomainInitializer.cs
-System/AppDomainManager_2_1.cs
-System/AppDomainSetup.cs
-System/AppDomainUnloadedException.cs
-System/ApplicationException.cs
-System/ArgIterator.cs
-System/ArgumentException.cs
-System/ArgumentNullException.cs
-System/ArgumentOutOfRangeException.cs
-System/ArithmeticException.cs
-System/Array.cs
-System/ArrayTypeMismatchException.cs
-System/AssemblyLoadEventArgs.cs
-System/AssemblyLoadEventHandler.cs
-System/AsyncCallback.cs
-System/Attribute.cs
-System/AttributeTargets.cs
-System/AttributeUsageAttribute.cs
-System/BadImageFormatException.cs
-System/Base64FormattingOptions.cs
-System/BitConverter.cs
-System/Boolean.cs
-System/Buffer.cs
-System/Byte.cs
-System/CannotUnloadAppDomainException.cs
-System/Char.cs
-System/CharEnumerator.cs
-System/CLSCompliantAttribute.cs
-System/CStreamReader.cs
-System/CStreamWriter.cs
-System/Console.cs
-System/ConsoleCancelEventArgs.cs
-System/ConsoleCancelEventHandler.cs
-System/ConsoleColor.cs
-System/ConsoleDriver.cs
-System/ConsoleKey.cs
-System/ConsoleKeyInfo.cs
-System/ConsoleModifiers.cs
-System/ConsoleSpecialKey.cs
-System/ContextBoundObject.cs
-System/ContextMarshalException.cs
-System/ContextStaticAttribute.cs
-System/ControlCharacters.cs
-System/Convert.cs
-System/CrossAppDomainDelegate.cs
-System/DataMisalignedException.cs
-System/DateTime.cs
-System/DateTimeKind.cs
-System/DateTimeOffset.cs
-System/DateTimeUtils.cs
-System/DayOfWeek.cs
-System/DBNull.cs
-System/Decimal.cs
-System/Delegate.cs
-System/DelegateSerializationHolder.cs
-System/DivideByZeroException.cs
-System/DllNotFoundException.cs
-System/DomainManagerInitializationFlags.cs
-System/Double.cs
-System/DuplicateWaitObjectException.cs
-System/EntryPointNotFoundException.cs
-System/Enum.cs
-System/Environment.cs
-System/EnvironmentVariableTarget.cs
-System/EventArgs.cs
-System/EventHandler.cs
-System/Exception.cs
-System/ExecutionEngineException.cs
-System/FieldAccessException.cs
-System/FlagsAttribute.cs
-System/FormatException.cs
-System/Funcs.cs
-System/GC.cs
-System/GCCollectionMode.cs
-System/GCNotificationStatus.cs
-System/Guid.cs
-System/IAppDomainSetup.cs
-System/IAsyncResult.cs
-System/ICloneable.cs
-System/IComparable.cs
-System/IEquatable.cs
-System/IConsoleDriver.cs
-System/IConvertible.cs
-System/ICustomFormatter.cs
-System/IDisposable.cs
-System/IFormatProvider.cs
-System/IFormattable.cs
-System/IndexOutOfRangeException.cs
-System/InsufficientMemoryException.cs
-System/Int16.cs
-System/Int32.cs
-System/Int64.cs
-System/IntPtr.cs
-System/InvalidCastException.cs
-System/InvalidOperationException.cs
-System/InvalidProgramException.cs
-System/InvalidTimeZoneException.cs
-System/IServiceProvider.cs
-System/KnownTerminals.cs
-System/Lazy.cs
-System/LoaderOptimization.cs
-System/LoaderOptimizationAttribute.cs
-System/MarshalByRefObject.cs
-System/Math.cs
-System/MemberAccessException.cs
-System/MethodAccessException.cs
-System/MidpointRounding.cs
-System/MissingFieldException.cs
-System/MissingMemberException.cs
-System/MissingMethodException.cs
-System/MonoAsyncCall.cs
-System/MonoCustomAttrs.cs
-System/MonoListItem.cs
-System/MonoType.cs
-System/MTAThreadAttribute.cs
-System/MulticastDelegate.cs
-System/MulticastNotSupportedException.cs
-System/NonSerializedAttribute.cs
-System/NotFiniteNumberException.cs
-System/NotImplementedException.cs
-System/NotSupportedException.cs
-System/NullConsoleDriver.cs
-System/Nullable.cs
-System/NullReferenceException.cs
-System/NumberFormatter.cs
-System/Object.cs
-System/ObjectDisposedException.cs
-System/ObsoleteAttribute.cs
-System/OperatingSystem.cs
-System/OperationCanceledException.cs
-System/OutOfMemoryException.cs
-System/OverflowException.cs
-System/ParamArrayAttribute.cs
-System/PlatformID.cs
-System/PlatformNotSupportedException.cs
-System/Random.cs
-System/RankException.cs
-System/ResolveEventArgs.cs
-System/ResolveEventHandler.cs
-System/RuntimeArgumentHandle.cs
-System/RuntimeFieldHandle.cs
-System/RuntimeMethodHandle.cs
-System/RuntimeTypeHandle.cs
-System/ModuleHandle.cs
-System/SByte.cs
-System/SerializableAttribute.cs
-System/Single.cs
-System/StackOverflowException.cs
-System/STAThreadAttribute.cs
-System/String.cs
-System/StringSplitOptions.cs
-System/StringComparer.cs
-System/StringComparison.cs
-System/SystemException.cs
-System/TermInfoBooleans.cs
-System/TermInfoDriver.cs
-System/TermInfoNumbers.cs
-System/TermInfoReader.cs
-System/TermInfoStrings.cs
-System/ThreadStaticAttribute.cs
-System/TimeSpan.cs
-System/TimeZone.cs
-System/TimeoutException.cs
-../../build/common/MonoTODOAttribute.cs
-System/Type.cs
-System/TypeCode.cs
-System/TypedReference.cs
-System/TypeInitializationException.cs
-System/TypeLoadException.cs
-System/TypeUnloadedException.cs
-System/Tuple.cs
-System/Tuples.cs
-System/UInt16.cs
-System/UInt32.cs
-System/UInt64.cs
-System/UIntPtr.cs
-System/UnauthorizedAccessException.cs
-System/UnhandledExceptionEventArgs.cs
-System/UnhandledExceptionEventHandler.cs
-System/UnitySerializationHolder.cs
-System/ValueType.cs
-System/Version.cs
-System/Void.cs
-System/WeakReference.cs
-System/WindowsConsoleDriver.cs
-System.Collections/ArrayList.cs
-System.Collections/BitArray.cs
-System.Collections/CaseInsensitiveComparer.cs
-System.Collections/CaseInsensitiveHashCodeProvider.cs
-System.Collections/CollectionBase.cs
-System.Collections/Comparer.cs
-System.Collections/CollectionDebuggerView.cs
-System.Collections/DictionaryBase.cs
-System.Collections/DictionaryEntry.cs
-System.Collections/Hashtable.cs
-System.Collections/ICollection.cs
-System.Collections/IComparer.cs
-System.Collections/IDictionary.cs
-System.Collections/IDictionaryEnumerator.cs
-System.Collections/IEnumerable.cs
-System.Collections/IEnumerator.cs
-System.Collections/IEqualityComparer.cs
-System.Collections/IHashCodeProvider.cs
-System.Collections/IList.cs
-System.Collections/IStructuralComparable.cs
-System.Collections/IStructuralEquatable.cs
-System.Collections/Queue.cs
-System.Collections/ReadOnlyCollectionBase.cs
-System.Collections/SortedList.cs
-System.Collections/Stack.cs
-System.Configuration.Assemblies/AssemblyHashAlgorithm.cs
-System.Configuration.Assemblies/AssemblyVersionCompatibility.cs
-System.Diagnostics/ConditionalAttribute.cs
-System.Diagnostics/DebuggableAttribute.cs
-System.Diagnostics/Debugger.cs
-System.Diagnostics/DebuggerBrowsableState.cs
-System.Diagnostics/DebuggerBrowsableAttribute.cs
-System.Diagnostics/DebuggerDisplayAttribute.cs
-System.Diagnostics/DebuggerHiddenAttribute.cs
-System.Diagnostics/DebuggerNonUserCodeAttribute.cs
-System.Diagnostics/DebuggerStepThroughAttribute.cs
-System.Diagnostics/DebuggerTypeProxyAttribute.cs
-System.Diagnostics/StackFrame.cs
-System.Diagnostics/StackTrace.cs
-System.Diagnostics.CodeAnalysis/SuppressMessageAttribute.cs
-System.Diagnostics.Contracts/Contract.cs
-System.Diagnostics.Contracts/ContractClassAttribute.cs
-System.Diagnostics.Contracts/ContractClassForAttribute.cs
-System.Diagnostics.Contracts/ContractFailedEventArgs.cs
-System.Diagnostics.Contracts/ContractFailureKind.cs
-System.Diagnostics.Contracts/ContractInvariantMethodAttribute.cs
-System.Diagnostics.Contracts/ContractPublicPropertyNameAttribute.cs
-System.Diagnostics.Contracts/ContractReferenceAssemblyAttribute.cs
-System.Diagnostics.Contracts/ContractRuntimeIgnoredAttribute.cs
-System.Diagnostics.Contracts/ContractVerificationAttribute.cs
-System.Diagnostics.Contracts/PureAttribute.cs
-System.Diagnostics.SymbolStore/ISymbolBinder.cs
-System.Diagnostics.SymbolStore/ISymbolBinder1.cs
-System.Diagnostics.SymbolStore/ISymbolDocument.cs
-System.Diagnostics.SymbolStore/ISymbolDocumentWriter.cs
-System.Diagnostics.SymbolStore/ISymbolMethod.cs
-System.Diagnostics.SymbolStore/ISymbolNamespace.cs
-System.Diagnostics.SymbolStore/ISymbolReader.cs
-System.Diagnostics.SymbolStore/ISymbolScope.cs
-System.Diagnostics.SymbolStore/ISymbolVariable.cs
-System.Diagnostics.SymbolStore/ISymbolWriter.cs
-System.Diagnostics.SymbolStore/SymAddressKind.cs
-System.Diagnostics.SymbolStore/SymbolToken.cs
-System.Diagnostics.SymbolStore/SymDocumentType.cs
-System.Diagnostics.SymbolStore/SymLanguageType.cs
-System.Diagnostics.SymbolStore/SymLanguageVendor.cs
-System.Globalization/Calendar.cs
-System.Globalization/CalendarWeekRule.cs
-System.Globalization/CalendricalCalculations.cs
-System.Globalization/CharUnicodeInfo.cs
-System.Globalization/CompareInfo.cs
-System.Globalization/CompareOptions.cs
-System.Globalization/CultureInfo.cs
-System.Globalization/DateTimeFormatInfo.cs
-System.Globalization/DateTimeStyles.cs
-System.Globalization/DaylightTime.cs
-System.Globalization/GregorianCalendar.cs
-System.Globalization/GregorianCalendarTypes.cs
-System.Globalization/HebrewCalendar.cs
-System.Globalization/HijriCalendar.cs
-System.Globalization/JapaneseCalendar.cs
-System.Globalization/KoreanCalendar.cs
-System.Globalization/NumberFormatInfo.cs
-System.Globalization/NumberStyles.cs
-System.Globalization/RegionInfo.cs
-System.Globalization/StringInfo.cs
-System.Globalization/TaiwanCalendar.cs
-System.Globalization/TextElementEnumerator.cs
-System.Globalization/TextInfo.cs
-System.Globalization/ThaiBuddhistCalendar.cs
-System.Globalization/UmAlQuraCalendar.cs
-System.Globalization/UnicodeCategory.cs
-System.IO/BinaryReader.cs
-System.IO/BinaryWriter.cs
-System.IO/BufferedStream.cs
-System.IO/Directory.cs
-System.IO/DirectoryInfo.cs
-System.IO/DirectoryNotFoundException.cs
-System.IO/EndOfStreamException.cs
-System.IO/File.cs
-System.IO/FileAccess.cs
-System.IO/FileAttributes.cs
-System.IO/FileInfo.cs
-System.IO/FileLoadException.cs
-System.IO/FileMode.cs
-System.IO/FileNotFoundException.cs
-System.IO/FileOptions.cs
-System.IO/FileShare.cs
-System.IO/FileStream.cs
-System.IO/FileStreamAsyncResult.cs
-System.IO/FileSystemInfo.cs
-System.IO/IOException.cs
-System.IO/MemoryStream.cs
-System.IO/MonoIO.cs
-System.IO/MonoIOError.cs
-System.IO/MonoFileType.cs
-System.IO/MonoIOStat.cs
-System.IO/Path.cs
-System.IO/PathTooLongException.cs
-System.IO/SearchOption.cs
-System.IO/SearchPattern.cs
-System.IO/SeekOrigin.cs
-System.IO/Stream.cs
-System.IO/StreamAsyncResult.cs
-System.IO/StreamReader.cs
-System.IO/StreamWriter.cs
-System.IO/StringReader.cs
-System.IO/StringWriter.cs
-System.IO/TextReader.cs
-System.IO/TextWriter.cs
-System.IO/UnexceptionalStreamReader.cs
-System.IO/UnexceptionalStreamWriter.cs
-System.IO/UnmanagedMemoryAccessor.cs
-System.IO/UnmanagedMemoryStream.cs
-System.IO.IsolatedStorage/MoonIsolatedStorage.cs
-System.IO.IsolatedStorage/MoonIsolatedStorageFile.cs
-System.IO.IsolatedStorage/MoonIsolatedStorageFileStream.cs
-System.IO.IsolatedStorage/IsolatedStorageException.cs
-System.Reflection/AmbiguousMatchException.cs
-System.Reflection/Assembly.cs
-System.Reflection/AssemblyAlgorithmIdAttribute.cs
-System.Reflection/AssemblyCompanyAttribute.cs
-System.Reflection/AssemblyConfigurationAttribute.cs
-System.Reflection/AssemblyCopyrightAttribute.cs
-System.Reflection/AssemblyCultureAttribute.cs
-System.Reflection/AssemblyDefaultAliasAttribute.cs
-System.Reflection/AssemblyDelaySignAttribute.cs
-System.Reflection/AssemblyDescriptionAttribute.cs
-System.Reflection/AssemblyFileVersionAttribute.cs
-System.Reflection/AssemblyFlagsAttribute.cs
-System.Reflection/AssemblyInformationalVersionAttribute.cs
-System.Reflection/AssemblyKeyFileAttribute.cs
-System.Reflection/AssemblyKeyNameAttribute.cs
-System.Reflection/AssemblyName.cs
-System.Reflection/AssemblyNameFlags.cs
-System.Reflection/AssemblyNameProxy.cs
-System.Reflection/AssemblyProductAttribute.cs
-System.Reflection/AssemblyTitleAttribute.cs
-System.Reflection/AssemblyTradeMarkAttribute.cs
-System.Reflection/AssemblyVersionAttribute.cs
-System.Reflection/Binder.cs
-System.Reflection/BindingFlags.cs
-System.Reflection/CallingConventions.cs
-System.Reflection/ConstructorInfo.cs
-System.Reflection/CustomAttributeData.cs
-System.Reflection/CustomAttributeFormatException.cs
-System.Reflection/CustomAttributeNamedArgument.cs
-System.Reflection/CustomAttributeTypedArgument.cs
-System.Reflection/DefaultMemberAttribute.cs
-System.Reflection/EventAttributes.cs
-System.Reflection/EventInfo.cs
-System.Reflection/ExceptionHandlingClause.cs
-System.Reflection/ExceptionHandlingClauseOptions.cs
-System.Reflection/FieldAttributes.cs
-System.Reflection/FieldInfo.cs
-System.Reflection/GenericParameterAttributes.cs
-System.Reflection/ICustomAttributeProvider.cs
-System.Reflection/ImageFileMachine.cs
-System.Reflection/InterfaceMapping.cs
-System.Reflection/IReflect.cs
-System.Reflection/LocalVariableInfo.cs
-System.Reflection/ManifestResourceInfo.cs
-System.Reflection/MemberFilter.cs
-System.Reflection/MemberInfo.cs
-System.Reflection/MemberInfoSerializationHolder.cs
-System.Reflection/MemberTypes.cs
-System.Reflection/MethodAttributes.cs
-System.Reflection/MethodBase.cs
-System.Reflection/MethodBody.cs
-System.Reflection/MethodImplAttributes.cs
-System.Reflection/MethodInfo.cs
-System.Reflection/Missing.cs
-System.Reflection/Module.cs
-System.Reflection/ModuleResolveEventHandler.cs
-System.Reflection/MonoGenericClass.cs
-System.Reflection/MonoGenericMethod.cs
-System.Reflection/MonoEvent.cs
-System.Reflection/MonoField.cs
-System.Reflection/MonoMethod.cs
-System.Reflection/MonoProperty.cs
-System.Reflection/ObfuscateAssemblyAttribute.cs
-System.Reflection/ObfuscationAttribute.cs
-System.Reflection/ParameterAttributes.cs
-System.Reflection/ParameterInfo.cs
-System.Reflection/ParameterModifier.cs
-System.Reflection/Pointer.cs
-System.Reflection/PortableExecutableKinds.cs
-System.Reflection/ProcessorArchitecture.cs
-System.Reflection/PropertyAttributes.cs
-System.Reflection/PropertyInfo.cs
-System.Reflection/ReflectionTypeLoadException.cs
-System.Reflection/ResourceAttributes.cs
-System.Reflection/ResourceLocation.cs
-System.Reflection/StrongNameKeyPair.cs
-System.Reflection/TargetException.cs
-System.Reflection/TargetInvocationException.cs
-System.Reflection/TargetParameterCountException.cs
-System.Reflection/TypeAttributes.cs
-System.Reflection/TypeDelegator.cs
-System.Reflection/TypeFilter.cs
-System.Reflection.Emit/AssemblyBuilder.cs
-System.Reflection.Emit/AssemblyBuilderAccess.cs
-System.Reflection.Emit/ConstructorBuilder.cs
-System.Reflection.Emit/ConstructorOnTypeBuilderInst.cs
-System.Reflection.Emit/CustomAttributeBuilder.cs
-System.Reflection.Emit/DerivedTypes.cs
-System.Reflection.Emit/DynamicILInfo.cs
-System.Reflection.Emit/DynamicMethod.cs
-System.Reflection.Emit/EnumBuilder.cs
-System.Reflection.Emit/EventBuilder.cs
-System.Reflection.Emit/EventOnTypeBuilderInst.cs
-System.Reflection.Emit/EventToken.cs
-System.Reflection.Emit/FieldBuilder.cs
-System.Reflection.Emit/FieldOnTypeBuilderInst.cs
-System.Reflection.Emit/FieldToken.cs
-System.Reflection.Emit/FlowControl.cs
-System.Reflection.Emit/GenericTypeParameterBuilder.cs
-System.Reflection.Emit/ILGenerator.cs
-System.Reflection.Emit/Label.cs
-System.Reflection.Emit/LocalBuilder.cs
-System.Reflection.Emit/MethodBuilder.cs
-System.Reflection.Emit/MethodOnTypeBuilderInst.cs
-System.Reflection.Emit/MethodToken.cs
-System.Reflection.Emit/MethodRental.cs
-System.Reflection.Emit/ModuleBuilder.cs
-System.Reflection.Emit/MonoArrayMethod.cs
-System.Reflection.Emit/OpCodeNames.cs
-System.Reflection.Emit/OpCode.cs
-System.Reflection.Emit/OpCodes.cs
-System.Reflection.Emit/OpCodeType.cs
-System.Reflection.Emit/OperandType.cs
-System.Reflection.Emit/PackingSize.cs
-System.Reflection.Emit/ParameterBuilder.cs
-System.Reflection.Emit/ParameterToken.cs
-System.Reflection.Emit/PEFileKinds.cs
-System.Reflection.Emit/PropertyBuilder.cs
-System.Reflection.Emit/PropertyOnTypeBuilderInst.cs
-System.Reflection.Emit/PropertyToken.cs
-System.Reflection.Emit/SignatureHelper.cs
-System.Reflection.Emit/SignatureToken.cs
-System.Reflection.Emit/StackBehaviour.cs
-System.Reflection.Emit/StringToken.cs
-System.Reflection.Emit/TypeBuilder.cs
-System.Reflection.Emit/TypeToken.cs
-System.Reflection.Emit/UnmanagedMarshal.cs
-System.Resources/IResourceReader.cs
-System.Resources/IResourceWriter.cs
-System.Resources/MissingManifestResourceException.cs
-System.Resources/NeutralResourcesLanguageAttribute.cs
-System.Resources/ResourceManager.cs
-System.Resources/ResourceReader.cs
-System.Resources/ResourceSet.cs
-System.Resources/ResourceWriter.cs
-System.Resources/RuntimeResourceSet.cs
-System.Resources/SatelliteContractVersionAttribute.cs
-System.Resources/UltimateResourceFallbackLocation.cs
-System.Resources/Win32Resources.cs
-System.Runtime.CompilerServices/AccessedThroughPropertyAttribute.cs
-System.Runtime.CompilerServices/CallConvCdecl.cs
-System.Runtime.CompilerServices/CallConvFastcall.cs
-System.Runtime.CompilerServices/CallConvThiscall.cs
-System.Runtime.CompilerServices/CallConvStdcall.cs
-System.Runtime.CompilerServices/CompilationRelaxations.cs
-System.Runtime.CompilerServices/CompilationRelaxationsAttribute.cs
-System.Runtime.CompilerServices/CompilerGeneratedAttribute.cs
-System.Runtime.CompilerServices/CompilerGlobalScopeAttribute.cs
-System.Runtime.CompilerServices/CompilerMarshalOverride.cs
-System.Runtime.CompilerServices/ConditionalWeakTable.cs
-System.Runtime.CompilerServices/CustomConstantAttribute.cs
-System.Runtime.CompilerServices/DateTimeConstantAttribute.cs
-System.Runtime.CompilerServices/DecimalConstantAttribute.cs
-System.Runtime.CompilerServices/DefaultDependencyAttribute.cs
-System.Runtime.CompilerServices/DependencyAttribute.cs
-System.Runtime.CompilerServices/DiscardableAttribute.cs
-System.Runtime.CompilerServices/FixedAddressValueTypeAttribute.cs
-System.Runtime.CompilerServices/FixedBufferAttribute.cs
-System.Runtime.CompilerServices/HasCopySemanticsAttribute.cs
-System.Runtime.CompilerServices/IDispatchConstantAttribute.cs
-System.Runtime.CompilerServices/IUnknownConstantAttribute.cs
-System.Runtime.CompilerServices/IndexerNameAttribute.cs
-System.Runtime.CompilerServices/InternalsVisibleToAttribute.cs
-System.Runtime.CompilerServices/IsBoxed.cs
-System.Runtime.CompilerServices/IsByValue.cs
-System.Runtime.CompilerServices/IsConst.cs
-System.Runtime.CompilerServices/IsCopyConstructed.cs
-System.Runtime.CompilerServices/IsExplicitlyDereferenced.cs
-System.Runtime.CompilerServices/IsImplicitlyDereferenced.cs
-System.Runtime.CompilerServices/IsJitIntrinsic.cs
-System.Runtime.CompilerServices/IsLong.cs
-System.Runtime.CompilerServices/IsPinned.cs
-System.Runtime.CompilerServices/IsSignUnspecifiedByte.cs
-System.Runtime.CompilerServices/IsUdtReturn.cs
-System.Runtime.CompilerServices/IsVolatile.cs
-System.Runtime.CompilerServices/LoadHint.cs
-System.Runtime.CompilerServices/MethodCodeType.cs
-System.Runtime.CompilerServices/MethodImplAttribute.cs
-System.Runtime.CompilerServices/MethodImplOptions.cs
-System.Runtime.CompilerServices/NativeCppClassAttribute.cs
-System.Runtime.CompilerServices/RequiredAttributeAttribute.cs
-System.Runtime.CompilerServices/RuntimeCompatibilityAttribute.cs
-System.Runtime.CompilerServices/RuntimeHelpers.cs
-System.Runtime.CompilerServices/RuntimeWrappedException.cs
-System.Runtime.CompilerServices/SpecialNameAttribute.cs 
-System.Runtime.CompilerServices/ScopelessEnumAttribute.cs
-System.Runtime.CompilerServices/SuppressIldasmAttribute.cs
-System.Runtime.CompilerServices/StringFreezingAttribute.cs 
-System.Runtime.CompilerServices/UnsafeValueTypeAttribute.cs
-System.Runtime.CompilerServices/TypeForwardedFromAttribute.cs
-System.Runtime.CompilerServices/TypeForwardedToAttribute.cs
-System.Runtime.ConstrainedExecution/CriticialFinalizerObject.cs
-System.Runtime.ConstrainedExecution/CER.cs
-System.Runtime.ConstrainedExecution/Consistency.cs
-System.Runtime.ConstrainedExecution/PrePrepareMethodAttribute.cs
-System.Runtime.ConstrainedExecution/ReliabilityContractAttribute.cs
-System.Runtime.InteropServices/_Activator.cs
-System.Runtime.InteropServices/_Assembly.cs
-System.Runtime.InteropServices/_AssemblyBuilder.cs
-System.Runtime.InteropServices/_AssemblyName.cs
-System.Runtime.InteropServices/_Attribute.cs
-System.Runtime.InteropServices/_ConstructorBuilder.cs
-System.Runtime.InteropServices/_ConstructorInfo.cs
-System.Runtime.InteropServices/_CustomAttributeBuilder.cs
-System.Runtime.InteropServices/_EnumBuilder.cs
-System.Runtime.InteropServices/_EventBuilder.cs
-System.Runtime.InteropServices/_EventInfo.cs
-System.Runtime.InteropServices/_Exception.cs
-System.Runtime.InteropServices/_FieldBuilder.cs
-System.Runtime.InteropServices/_FieldInfo.cs
-System.Runtime.InteropServices/_ILGenerator.cs
-System.Runtime.InteropServices/_LocalBuilder.cs
-System.Runtime.InteropServices/_MemberInfo.cs
-System.Runtime.InteropServices/_MethodBase.cs
-System.Runtime.InteropServices/_MethodBuilder.cs
-System.Runtime.InteropServices/_MethodInfo.cs
-System.Runtime.InteropServices/_MethodRental.cs
-System.Runtime.InteropServices/_Module.cs
-System.Runtime.InteropServices/_ModuleBuilder.cs
-System.Runtime.InteropServices/_ParameterBuilder.cs
-System.Runtime.InteropServices/_ParameterInfo.cs
-System.Runtime.InteropServices/_PropertyBuilder.cs
-System.Runtime.InteropServices/_PropertyInfo.cs
-System.Runtime.InteropServices/_SignatureHelper.cs
-System.Runtime.InteropServices/_Thread.cs
-System.Runtime.InteropServices/_Type.cs
-System.Runtime.InteropServices/_TypeBuilder.cs
-System.Runtime.InteropServices/AllowReversePInvokeCallsAttribute.cs
-System.Runtime.InteropServices/CallingConvention.cs
-System.Runtime.InteropServices/CharSet.cs
-System.Runtime.InteropServices/ClassInterfaceAttribute.cs
-System.Runtime.InteropServices/ClassInterfaceType.cs
-System.Runtime.InteropServices/CoClassAttribute.cs
-System.Runtime.InteropServices/ComDefaultInterfaceAttribute.cs
-System.Runtime.InteropServices/COMException.cs
-System.Runtime.InteropServices/ComImportAttribute.cs
-System.Runtime.InteropServices/ComInterfaceType.cs
-System.Runtime.InteropServices/ComVisible.cs
-System.Runtime.InteropServices/CriticalHandle.cs
-System.Runtime.InteropServices/DefaultCharSetAttribute.cs
-System.Runtime.InteropServices/DispIdAttribute.cs
-System.Runtime.InteropServices/DllImportAttribute.cs
-System.Runtime.InteropServices/ExternalException.cs
-System.Runtime.InteropServices/FieldOffsetAttribute.cs
-System.Runtime.InteropServices/GCHandle.cs
-System.Runtime.InteropServices/GCHandleType.cs
-System.Runtime.InteropServices/GuidAttribute.cs
-System.Runtime.InteropServices/HandleRef.cs
-System.Runtime.InteropServices/InAttribute.cs
-System.Runtime.InteropServices/InterfaceTypeAttribute.cs
-System.Runtime.InteropServices/LayoutKind.cs
-System.Runtime.InteropServices/Marshal.cs
-System.Runtime.InteropServices/MarshalAsAttribute.cs
-System.Runtime.InteropServices/MarshalDirectiveException.cs
-System.Runtime.InteropServices/OptionalAttribute.cs
-System.Runtime.InteropServices/OutAttribute.cs
-System.Runtime.InteropServices/PreserveSigAttribute.cs
-System.Runtime.InteropServices/SEHException.cs
-System.Runtime.InteropServices/SafeHandle.cs
-System.Runtime.InteropServices/StructLayoutAttribute.cs
-System.Runtime.InteropServices/TypeLibImportClassAttribute.cs
-System.Runtime.InteropServices/TypeLibVersionAttribute.cs
-System.Runtime.InteropServices/UnmanagedFunctionPointerAttribute.cs
-System.Runtime.InteropServices/UnmanagedType.cs
-System.Runtime.Remoting/ActivatedClientTypeEntry.cs
-System.Runtime.Remoting/ActivatedServiceTypeEntry.cs
-System.Runtime.Remoting/CustomErrorsModes.cs
-System.Runtime.Remoting/EnvoyInfo.cs
-System.Runtime.Remoting/IObjectHandle.cs
-System.Runtime.Remoting/IChannelInfo.cs
-System.Runtime.Remoting/Identity.cs
-System.Runtime.Remoting/InternalRemotingServices.cs
-System.Runtime.Remoting/IEnvoyInfo.cs
-System.Runtime.Remoting/IRemotingTypeInfo.cs
-System.Runtime.Remoting/ObjectHandle.cs
-System.Runtime.Remoting/ObjRef.cs
-System.Runtime.Remoting/RemotingConfiguration.cs
-System.Runtime.Remoting/RemotingException.cs
-System.Runtime.Remoting/RemotingTimeoutException.cs
-System.Runtime.Remoting/RemotingServices.cs
-System.Runtime.Remoting/ServerException.cs
-System.Runtime.Remoting/ServerIdentity.cs
-System.Runtime.Remoting/SoapServices.cs
-System.Runtime.Remoting/TypeEntry.cs
-System.Runtime.Remoting/TypeInfo.cs
-System.Runtime.Remoting/WellKnownObjectMode.cs
-System.Runtime.Remoting/WellKnownClientTypeEntry.cs
-System.Runtime.Remoting/WellKnownServiceTypeEntry.cs
-System.Runtime.Remoting.Activation/ActivationServices.cs
-System.Runtime.Remoting.Activation/ActivatorLevel.cs
-System.Runtime.Remoting.Activation/AppDomainLevelActivator.cs
-System.Runtime.Remoting.Activation/ConstructionLevelActivator.cs
-System.Runtime.Remoting.Activation/ContextLevelActivator.cs
-System.Runtime.Remoting.Activation/IActivator.cs
-System.Runtime.Remoting.Activation/IConstructionCallMessage.cs
-System.Runtime.Remoting.Activation/IConstructionReturnMessage.cs
-System.Runtime.Remoting.Activation/RemoteActivator.cs
-System.Runtime.Remoting.Activation/RemoteActivationAttribute.cs
-System.Runtime.Remoting.Activation/UrlAttribute.cs
-System.Runtime.Remoting.Channels/AggregateDictionary.cs
-System.Runtime.Remoting.Channels/BaseChannelObjectWithProperties.cs
-System.Runtime.Remoting.Channels/BaseChannelSinkWithProperties.cs
-System.Runtime.Remoting.Channels/BaseChannelWithProperties.cs
-System.Runtime.Remoting.Channels/ChannelDataStore.cs
-System.Runtime.Remoting.Channels/ChannelServices.cs
-System.Runtime.Remoting.Channels/ChannelSinkStackEntry.cs
-System.Runtime.Remoting.Channels/ClientChannelSinkStack.cs
-System.Runtime.Remoting.Channels/IChannel.cs
-System.Runtime.Remoting.Channels/IChannelDataStore.cs
-System.Runtime.Remoting.Channels/IChannelReceiver.cs
-System.Runtime.Remoting.Channels/IChannelReceiverHook.cs
-System.Runtime.Remoting.Channels/IChannelSender.cs
-System.Runtime.Remoting.Channels/IChannelSinkBase.cs
-System.Runtime.Remoting.Channels/IClientChannelSink.cs
-System.Runtime.Remoting.Channels/IClientChannelSinkProvider.cs
-System.Runtime.Remoting.Channels/IClientChannelSinkStack.cs
-System.Runtime.Remoting.Channels/IClientFormatterSink.cs
-System.Runtime.Remoting.Channels/IClientFormatterSinkProvider.cs
-System.Runtime.Remoting.Channels/IClientResponseChannelSinkStack.cs
-System.Runtime.Remoting.Channels/ISecurableChannel.cs
-System.Runtime.Remoting.Channels/IServerResponseChannelSinkStack.cs
-System.Runtime.Remoting.Channels/ServerDispatchSink.cs
-System.Runtime.Remoting.Channels/ServerDispatchSinkProvider.cs
-System.Runtime.Remoting.Channels/IServerChannelSink.cs
-System.Runtime.Remoting.Channels/IServerChannelSinkProvider.cs
-System.Runtime.Remoting.Channels/IServerChannelSinkStack.cs
-System.Runtime.Remoting.Channels/IServerFormatterSinkProvider.cs
-System.Runtime.Remoting.Channels/ITransportHeaders.cs
-System.Runtime.Remoting.Channels/ServerChannelSinkStack.cs
-System.Runtime.Remoting.Channels/ServerProcessing.cs
-System.Runtime.Remoting.Channels/SinkProviderData.cs
-System.Runtime.Remoting.Channels/TransportHeaders.cs
-System.Runtime.Remoting.Channels/CrossAppDomainChannel.cs
-System.Runtime.Remoting.Contexts/Context.cs
-System.Runtime.Remoting.Contexts/ContextAttribute.cs
-System.Runtime.Remoting.Contexts/ContextProperty.cs
-System.Runtime.Remoting.Contexts/CrossContextChannel.cs
-System.Runtime.Remoting.Contexts/CrossContextDelegate.cs
-System.Runtime.Remoting.Contexts/IContextAttribute.cs
-System.Runtime.Remoting.Contexts/IContextProperty.cs
-System.Runtime.Remoting.Contexts/IContextPropertyActivator.cs
-System.Runtime.Remoting.Contexts/IContributeClientContextSink.cs
-System.Runtime.Remoting.Contexts/IContributeDynamicSink.cs
-System.Runtime.Remoting.Contexts/IContributeEnvoySink.cs
-System.Runtime.Remoting.Contexts/IContributeObjectSink.cs
-System.Runtime.Remoting.Contexts/IContributeServerContextSink.cs
-System.Runtime.Remoting.Contexts/IDynamicMessageSink.cs
-System.Runtime.Remoting.Contexts/IDynamicProperty.cs
-System.Runtime.Remoting.Contexts/SynchronizationAttribute.cs
-System.Runtime.Remoting.Lifetime/ClientSponsor.cs
-System.Runtime.Remoting.Lifetime/ILease.cs
-System.Runtime.Remoting.Lifetime/ISponsor.cs
-System.Runtime.Remoting.Lifetime/Lease.cs
-System.Runtime.Remoting.Lifetime/LeaseManager.cs
-System.Runtime.Remoting.Lifetime/LeaseSink.cs
-System.Runtime.Remoting.Lifetime/LeaseState.cs
-System.Runtime.Remoting.Lifetime/LifetimeServices.cs
-System.Runtime.Remoting.Messaging/ArgInfo.cs
-System.Runtime.Remoting.Messaging/AsyncResult.cs
-System.Runtime.Remoting.Messaging/CallContext.cs
-System.Runtime.Remoting.Messaging/ClientContextTerminatorSink.cs
-System.Runtime.Remoting.Messaging/ConstructionCall.cs
-System.Runtime.Remoting.Messaging/ConstructionCallDictionary.cs
-System.Runtime.Remoting.Messaging/ConstructionResponse.cs
-System.Runtime.Remoting.Messaging/EnvoyTerminatorSink.cs
-System.Runtime.Remoting.Messaging/Header.cs
-System.Runtime.Remoting.Messaging/HeaderHandler.cs
-System.Runtime.Remoting.Messaging/ErrorMessage.cs
-System.Runtime.Remoting.Messaging/IInternalMessage.cs
-System.Runtime.Remoting.Messaging/IMessage.cs
-System.Runtime.Remoting.Messaging/IMessageCtrl.cs
-System.Runtime.Remoting.Messaging/IMessageSink.cs
-System.Runtime.Remoting.Messaging/IMethodCallMessage.cs
-System.Runtime.Remoting.Messaging/IMethodMessage.cs
-System.Runtime.Remoting.Messaging/IMethodReturnMessage.cs
-System.Runtime.Remoting.Messaging/IRemotingFormatter.cs
-System.Runtime.Remoting.Messaging/InternalMessageWrapper.cs
-System.Runtime.Remoting.Messaging/ISerializationRootObject.cs
-System.Runtime.Remoting.Messaging/LogicalCallContext.cs
-System.Runtime.Remoting.Messaging/MessageSurrogateFilter.cs
-System.Runtime.Remoting.Messaging/MethodCall.cs
-System.Runtime.Remoting.Messaging/MethodCallMessageWrapper.cs
-System.Runtime.Remoting.Messaging/MethodResponse.cs
-System.Runtime.Remoting.Messaging/MethodCallDictionary.cs
-System.Runtime.Remoting.Messaging/MethodDictionary.cs
-System.Runtime.Remoting.Messaging/MethodReturnDictionary.cs
-System.Runtime.Remoting.Messaging/MethodReturnMessageWrapper.cs
-System.Runtime.Remoting.Messaging/MonoMethodMessage.cs
-System.Runtime.Remoting.Messaging/OneWayAttribute.cs
-System.Runtime.Remoting.Messaging/RemotingSurrogateSelector.cs
-System.Runtime.Remoting.Messaging/RemotingSurrogate.cs
-System.Runtime.Remoting.Messaging/ReturnMessage.cs
-System.Runtime.Remoting.Messaging/ServerContextTerminatorSink.cs
-System.Runtime.Remoting.Messaging/ServerObjectTerminatorSink.cs
-System.Runtime.Remoting.Messaging/StackBuilderSink.cs
-System.Runtime.Remoting.Messaging/CADMessages.cs
-System.Runtime.Remoting.Metadata/SoapAttribute.cs
-System.Runtime.Remoting.Metadata/SoapFieldAttribute.cs
-System.Runtime.Remoting.Metadata/SoapMethodAttribute.cs
-System.Runtime.Remoting.Metadata/SoapOption.cs
-System.Runtime.Remoting.Metadata/SoapParameterAttribute.cs
-System.Runtime.Remoting.Metadata/SoapTypeAttribute.cs
-System.Runtime.Remoting.Metadata/XmlFieldOrderOption.cs
-System.Runtime.Remoting.Proxies/RealProxy.cs
-System.Runtime.Remoting.Proxies/RemotingProxy.cs
-System.Runtime.Remoting.Proxies/ProxyAttribute.cs
-System.Runtime.Remoting.Services/EnterpriseServicesHelper.cs
-System.Runtime.Remoting.Services/ITrackingHandler.cs
-System.Runtime.Remoting.Services/TrackingServices.cs
-System.Runtime.Serialization/Formatter.cs
-System.Runtime.Serialization/FormatterConverter.cs
-System.Runtime.Serialization/FormatterServices.cs
-System.Runtime.Serialization/IDeserializationCallback.cs
-System.Runtime.Serialization/IFormatter.cs
-System.Runtime.Serialization/IFormatterConverter.cs
-System.Runtime.Serialization/IObjectReference.cs
-System.Runtime.Serialization/ISerializable.cs
-System.Runtime.Serialization/ISerializationSurrogate.cs
-System.Runtime.Serialization/ISurrogateSelector.cs
-System.Runtime.Serialization/ObjectIDGenerator.cs
-System.Runtime.Serialization/ObjectManager.cs
-System.Runtime.Serialization/OnDeserializedAttribute.cs
-System.Runtime.Serialization/OnDeserializingAttribute.cs
-System.Runtime.Serialization/OnSerializedAttribute.cs
-System.Runtime.Serialization/OnSerializingAttribute.cs
-System.Runtime.Serialization/OptionalFieldAttribute.cs
-System.Runtime.Serialization/SerializationBinder.cs
-System.Runtime.Serialization/SerializationCallbacks.cs
-System.Runtime.Serialization/SerializationEntry.cs
-System.Runtime.Serialization/SerializationException.cs
-System.Runtime.Serialization/SerializationInfo.cs
-System.Runtime.Serialization/SerializationInfoEnumerator.cs
-System.Runtime.Serialization/SerializationObjectManager.cs
-System.Runtime.Serialization/StreamingContext.cs
-System.Runtime.Serialization/StreamingContextStates.cs
-System.Runtime.Serialization/SurrogateSelector.cs
-System.Runtime.Serialization.Formatters/FormatterAssemblyStyle.cs
-System.Runtime.Serialization.Formatters/FormatterTopObjectStyle.cs
-System.Runtime.Serialization.Formatters/FormatterTypeStyle.cs
-System.Runtime.Serialization.Formatters/IFieldInfo.cs
-System.Runtime.Serialization.Formatters/InternalArrayTypeE.cs
-System.Runtime.Serialization.Formatters/InternalElementTypeE.cs
-System.Runtime.Serialization.Formatters/InternalMemberTypeE.cs
-System.Runtime.Serialization.Formatters/InternalMemberValueE.cs
-System.Runtime.Serialization.Formatters/InternalNameSpaceE.cs
-System.Runtime.Serialization.Formatters/InternalObjectPositionE.cs
-System.Runtime.Serialization.Formatters/InternalObjectTypeE.cs
-System.Runtime.Serialization.Formatters/InternalParseStateE.cs
-System.Runtime.Serialization.Formatters/InternalParseTypeE.cs
-System.Runtime.Serialization.Formatters/InternalPrimitiveTypeE.cs
-System.Runtime.Serialization.Formatters/InternalRM.cs
-System.Runtime.Serialization.Formatters/InternalSerializerTypeE.cs
-System.Runtime.Serialization.Formatters/InternalST.cs
-System.Runtime.Serialization.Formatters/ISoapMessage.cs
-System.Runtime.Serialization.Formatters/ServerFault.cs
-System.Runtime.Serialization.Formatters/SoapFault.cs
-System.Runtime.Serialization.Formatters/SoapMessage.cs
-System.Runtime.Serialization.Formatters/TypeFilterLevel.cs
-System.Runtime.Serialization.Formatters.Binary/BinaryFormatter.cs
-System.Runtime.Serialization.Formatters.Binary/BinaryCommon.cs
-System.Runtime.Serialization.Formatters.Binary/CodeGenerator.cs
-System.Runtime.Serialization.Formatters.Binary/ObjectReader.cs
-System.Runtime.Serialization.Formatters.Binary/ObjectWriter.cs
-System.Runtime.Serialization.Formatters.Binary/MessageFormatter.cs
-System.Runtime.Versioning/ResourceExposureAttribute.cs
-System.Runtime.Versioning/ResourceScope.cs
-System.Runtime.Versioning/VersioningHelper.cs
-System.Security/AllowPartiallyTrustedCallersAttribute.cs
-System.Security/CodeAccessPermission_2_1.cs
-System.Security/IPermission.cs
-System.Security/PermissionSet_2_1.cs
-System.Security/SecurityCriticalAttribute.cs
-System.Security/SecurityFrame.cs
-System.Security/SecurityException_2_1.cs
-System.Security/SecurityManager_2_1.cs
-System.Security/SecuritySafeCriticalAttribute.cs
-System.Security/SecurityState.cs
-System.Security/SecurityTransparentAttribute.cs
-System.Security/SuppressUnmanagedCodeSecurityAttribute.cs
-System.Security/UnverifiableCodeAttribute.cs
-System.Security/VerificationException.cs
-System.Security.Cryptography/AsymmetricAlgorithm.cs
-System.Security.Cryptography/AsymmetricKeyExchangeDeformatter.cs
-System.Security.Cryptography/AsymmetricKeyExchangeFormatter.cs
-System.Security.Cryptography/AsymmetricSignatureDeformatter.cs
-System.Security.Cryptography/AsymmetricSignatureFormatter.cs
-System.Security.Cryptography/Base64Constants.cs
-System.Security.Cryptography/CipherMode.cs
-System.Security.Cryptography/CryptoAPITransform.cs
-System.Security.Cryptography/CryptoConfig_2_1.cs
-System.Security.Cryptography/CryptographicException.cs
-System.Security.Cryptography/CryptographicUnexpectedOperationExcpetion.cs
-System.Security.Cryptography/CryptoStream.cs
-System.Security.Cryptography/CryptoStreamMode.cs
-System.Security.Cryptography/DeriveBytes.cs
-System.Security.Cryptography/DES.cs
-System.Security.Cryptography/DESCryptoServiceProvider.cs
-System.Security.Cryptography/DSA.cs
-System.Security.Cryptography/DSAParameters.cs
-System.Security.Cryptography/DSASignatureDeformatter.cs
-System.Security.Cryptography/DSASignatureFormatter.cs
-System.Security.Cryptography/FromBase64Transform.cs
-System.Security.Cryptography/HashAlgorithm.cs
-System.Security.Cryptography/HMAC.cs
-System.Security.Cryptography/HMACMD5.cs
-System.Security.Cryptography/HMACSHA1.cs
-System.Security.Cryptography/HMACSHA256.cs
-System.Security.Cryptography/ICryptoTransform.cs
-System.Security.Cryptography/KeyedHashAlgorithm.cs
-System.Security.Cryptography/KeyNumber.cs
-System.Security.Cryptography/KeySizes.cs
-System.Security.Cryptography/MaskGenerationMethod.cs
-System.Security.Cryptography/MD5.cs
-System.Security.Cryptography/MD5CryptoServiceProvider.cs
-System.Security.Cryptography/PaddingMode.cs
-System.Security.Cryptography/PKCS1MaskGenerationMethod.cs
-System.Security.Cryptography/RandomNumberGenerator.cs
-System.Security.Cryptography/RC2.cs
-System.Security.Cryptography/RC2CryptoServiceProvider.cs
-System.Security.Cryptography/Rfc2898DeriveBytes.cs
-System.Security.Cryptography/Rijndael.cs
-System.Security.Cryptography/RijndaelManaged.cs
-System.Security.Cryptography/RijndaelManagedTransform.cs
-System.Security.Cryptography/RNGCryptoServiceProvider.cs
-System.Security.Cryptography/RSA.cs
-System.Security.Cryptography/RSAOAEPKeyExchangeDeformatter.cs
-System.Security.Cryptography/RSAOAEPKeyExchangeFormatter.cs
-System.Security.Cryptography/RSAParameters.cs
-System.Security.Cryptography/RSAPKCS1KeyExchangeDeformatter.cs
-System.Security.Cryptography/RSAPKCS1KeyExchangeFormatter.cs
-System.Security.Cryptography/RSAPKCS1SignatureDeformatter.cs
-System.Security.Cryptography/RSAPKCS1SignatureFormatter.cs
-System.Security.Cryptography/SHA1.cs
-System.Security.Cryptography/SHA1CryptoServiceProvider.cs
-System.Security.Cryptography/SHA1Managed.cs
-System.Security.Cryptography/SHA256.cs
-System.Security.Cryptography/SHA256Managed.cs
-System.Security.Cryptography/SHAConstants.cs
-System.Security.Cryptography/SymmetricAlgorithm.cs
-System.Security.Cryptography/ToBase64Transform.cs
-System.Security.Cryptography/TripleDES.cs
-System.Security.Cryptography/TripleDESCryptoServiceProvider.cs
-System.Security.Cryptography.X509Certificates/X509Certificate.cs
-System.Security.Cryptography.X509Certificates/X509Certificate20.cs
-System.Security.Cryptography.X509Certificates/X509ContentType.cs
-System.Security.Cryptography.X509Certificates/X509KeyStorageFlags.cs
-System.Security.Permissions/CodeAccessSecurityAttribute.cs
-System.Security.Permissions/EnvironmentPermissionAccess.cs
-System.Security.Permissions/EnvironmentPermissionAttribute.cs
-System.Security.Permissions/FileIOPermissionAccess.cs
-System.Security.Permissions/FileIOPermissionAttribute.cs
-System.Security.Permissions/HostProtectionAttribute.cs
-System.Security.Permissions/HostProtectionResource.cs
-System.Security.Permissions/PermissionSetAttribute.cs
-System.Security.Permissions/PermissionState.cs
-System.Security.Permissions/ReflectionPermissionAttribute.cs
-System.Security.Permissions/ReflectionPermissionFlag.cs
-System.Security.Permissions/SecurityAction.cs
-System.Security.Permissions/SecurityAttribute.cs
-System.Security.Permissions/SecurityPermissionAttribute.cs
-System.Security.Permissions/SecurityPermissionFlag.cs
-System.Security.Permissions/StrongNamePermissionAttribute.cs
-System.Security.Permissions/StrongNamePublicKeyBlob.cs
-System.Security.Policy/Evidence_2_1.cs
-System.Security.Policy/PolicyLevel_2_1.cs
-System.Security.Principal/IIdentity.cs
-System.Security.Principal/IPrincipal.cs
-System.Text/ASCIIEncoding.cs
-System.Text/Decoder.cs
-System.Text/DecoderExceptionFallback.cs
-System.Text/DecoderExceptionFallbackBuffer.cs
-System.Text/DecoderFallback.cs
-System.Text/DecoderFallbackBuffer.cs
-System.Text/DecoderFallbackException.cs
-System.Text/DecoderReplacementFallback.cs
-System.Text/DecoderReplacementFallbackBuffer.cs
-System.Text/Encoder.cs
-System.Text/EncoderExceptionFallback.cs
-System.Text/EncoderExceptionFallbackBuffer.cs
-System.Text/EncoderFallback.cs
-System.Text/EncoderFallbackBuffer.cs
-System.Text/EncoderFallbackException.cs
-System.Text/EncoderReplacementFallback.cs
-System.Text/EncoderReplacementFallbackBuffer.cs
-System.Text/Encoding.cs
-System.Text/EncodingInfo.cs
-System.Text/StringBuilder.cs
-System.Text/SurrogateEncoder.cs
-System.Text/UnicodeEncoding.cs
-System.Text/UTF7Encoding.cs
-System.Text/UTF8Encoding.cs
-System.Text/UTF32Encoding.cs
-System.Threading/AbandonedMutexException.cs
-System.Threading/AutoResetEvent.cs
-System.Threading/ContextCallback.cs
-System.Threading/EventResetMode.cs
-System.Threading/EventWaitHandle.cs
-System.Threading/ExecutionContext.cs
-System.Threading/Interlocked.cs
-System.Threading/IOCompletionCallback.cs
-System.Threading/ManualResetEvent.cs
-System.Threading/Monitor.cs
-System.Threading/Mutex.cs
-System.Threading/NativeEventCalls.cs
-System.Threading/NativeOverlapped.cs
-System.Threading/Overlapped.cs
-System.Threading/ParameterizedThreadStart.cs
-System.Threading/RegisteredWaitHandle.cs
-System.Threading/SendOrPostCallback.cs
-System.Threading/SynchronizationContext.cs
-System.Threading/SynchronizationLockException.cs
-System.Threading/Thread.cs
-System.Threading/ThreadAbortException.cs
-System.Threading/ThreadInterruptedException.cs
-System.Threading/ThreadPool.cs
-System.Threading/ThreadStart.cs
-System.Threading/ThreadStartException.cs
-System.Threading/ThreadState.cs
-System.Threading/ThreadStateException.cs
-System.Threading/Timeout.cs
-System.Threading/Timer.cs
-System.Threading/TimerCallback.cs
-System.Threading/WaitCallback.cs
-System.Threading/WaitHandle.cs
-System.Threading/WaitOrTimerCallback.cs
-System.Collections.Generic/CollectionDebuggerView.cs
-System.Collections.Generic/Dictionary.cs
-System.Collections.Generic/ICollection.cs
-System.Collections.Generic/IEnumerable.cs
-System.Collections.Generic/IEnumerator.cs
-System.Collections.Generic/IList.cs
-System.Collections.Generic/IComparer.cs
-System.Collections.Generic/IEqualityComparer.cs
-System.Collections.Generic/IDictionary.cs
-System.Collections.Generic/KeyValuePair.cs
-System.Collections.Generic/EqualityComparer.cs
-System.Collections.Generic/KeyNotFoundException.cs
-System.Collections.Generic/List.cs
-System.Collections.ObjectModel/Collection.cs
-System.Collections.ObjectModel/KeyedCollection.cs
-System.Collections.ObjectModel/ReadOnlyCollection.cs
-System/Action.cs
-System/ArraySegment.cs
-System/Comparison.cs
-System/Converter.cs
-System/Predicate.cs
-System.Collections.Generic/Comparer.cs
-../Mono.CompilerServices.SymbolWriter/MonoSymbolWriter.cs
-../Mono.CompilerServices.SymbolWriter/MonoSymbolTable.cs
-../Mono.CompilerServices.SymbolWriter/MonoSymbolFile.cs
-../Mono.CompilerServices.SymbolWriter/SymbolWriterImpl.cs
-
index 33c0efe666172e9fc8e32ffe55b3929ef196cadc..0e278310a7caf225108009b88606340b85cd2969 100644 (file)
@@ -1,3 +1,7 @@
+2010-04-06  Marek Safar  <marek.safar@gmail.com>
+
+       * Updated to r46640.
+
 2009-11-26  Marek Safar  <marek.safar@gmail.com>
 
        * Updated to r35702.
index 687efe40f09bad019f9874c222cc886e9863cf65..a4ff6c466571f5276d06f32f294aadcbd676470d 100644 (file)
     <DebugType>pdbonly</DebugType>\r
     <BinPlaceSymbols>false</BinPlaceSymbols> \r
     <WarningLevel>4</WarningLevel>\r
-    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>\r
+    <TreatWarningsAsErrors>false</TreatWarningsAsErrors>\r
     <RunCodeAnalysis>false</RunCodeAnalysis>\r
     <GenerateAssemblyAttribute>false</GenerateAssemblyAttribute>\r
-<OutputPath>$(SolutionDir)\..\Bin\40\</OutputPath>\r
-<AssemblyOriginatorKeyFile>$(SolutionDir)\Runtime\MSSharedLibKey.snk</AssemblyOriginatorKeyFile>\r
+<OutputPath>$(SolutionDir)..\Bin\40\</OutputPath>\r
+<AssemblyOriginatorKeyFile>$(SolutionDir)Runtime\MSSharedLibKey.snk</AssemblyOriginatorKeyFile>\r
     <SignAssembly Condition="'$(SignAssembly)' == '' And Exists('$(AssemblyOriginatorKeyFile)')">true</SignAssembly>\r
     <SignedSym Condition="'$(SignAssembly)' == 'true'">SIGNED</SignedSym>\r
     <DelaySign>true</DelaySign>\r
     <DebugSymbols>true</DebugSymbols>
     <DebugType>full</DebugType>
     <Optimize>false</Optimize>
-    <OutputPath>$(SolutionDir)\..\Bin\40\</OutputPath>
-    <DefineConstants>DEBUG;TRACE;CODEPLEX_40;SYSTEM_CORE</DefineConstants>
+    <OutputPath>$(SolutionDir)..\Bin\40\</OutputPath>
+    <DefineConstants>DEBUG;TRACE;CODEPLEX_40;CLR4;SYSTEM_CORE</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
     <DebugType>pdbonly</DebugType>
     <Optimize>true</Optimize>
-    <OutputPath>$(SolutionDir)\..\Bin\40\</OutputPath>
-    <DefineConstants>TRACE;CODEPLEX_40;SYSTEM_CORE</DefineConstants>
+    <OutputPath>$(SolutionDir)..\Bin\40\</OutputPath>
+    <DefineConstants>TRACE;CODEPLEX_40;CLR4;SYSTEM_CORE</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
   </PropertyGroup>\r
@@ -60,6 +60,7 @@
     <Reference Include="System.Runtime.Remoting" Condition=" $(SilverlightBuild) != 'true' " />\r
     <Reference Include="System.Xml" Condition=" $(SilverlightBuild) != 'true' " />\r
     <ProjectReference Include="..\Microsoft.Scripting\Microsoft.Scripting.Build.csproj">\r
+      <Project>{EB66B766-6354-4208-A3D4-AACBDCB5C3B3}</Project>\r
       <Name>Microsoft.Scripting</Name>\r
     </ProjectReference>\r
   </ItemGroup>\r
@@ -85,7 +86,6 @@
       <Compile Include="Actions\ActionBinder.cs" />\r
       <Compile Include="Actions\Argument.cs" />\r
       <Compile Include="Actions\ArgumentType.cs" />\r
-      <Compile Include="Actions\BinderHelpers.cs" />\r
       <Compile Include="Actions\BoundMemberTracker.cs" />\r
       <Compile Include="Actions\CallSignature.cs" />\r
       <Compile Include="Actions\ComboActionRewriter.cs" />\r
       <Compile Include="Actions\Calls\MethodCandidate.cs" />\r
       <Compile Include="Actions\Calls\NarrowingLevel.cs" />\r
       <Compile Include="Actions\Calls\OutArgBuilder.cs" />\r
+      <Compile Include="Actions\Calls\OverloadInfo.cs" />\r
       <Compile Include="Actions\Calls\OverloadResolver.cs" />\r
       <Compile Include="Actions\Calls\OverloadResolverFactory.cs" />\r
       <Compile Include="Actions\Calls\ParameterMapping.cs" />\r
       <!--                       -->\r
       <Compile Include="Ast\BinaryExpression.cs" />\r
       <Compile Include="Ast\Block.cs" />\r
+      <Compile Include="Ast\BlockBuilder.cs" />\r
       <Compile Include="Ast\ConstantExpression.cs" />\r
       <Compile Include="Ast\DebugStatement.cs" />\r
       <Compile Include="Ast\EmptyStatements.cs" />\r
+      <Compile Include="Ast\ExpressionCollectionBuilder.cs" />\r
       <Compile Include="Ast\FinallyFlowControlExpression.cs" />\r
       <Compile Include="Ast\FlowControlRewriter.cs" />\r
       <Compile Include="Ast\GeneratorExpression.cs" />\r
       <Compile Include="Ast\IfStatementTest.cs" />\r
       <Compile Include="Ast\LambdaBuilder.cs" />\r
       <Compile Include="Ast\LambdaParameterRewriter.cs" />\r
+      <Compile Include="Ast\LightDynamicExpression.cs" />\r
       <Compile Include="Ast\LoopStatement.cs" />\r
       <Compile Include="Ast\MethodCallExpression.cs" />\r
       <Compile Include="Ast\NewArrayExpression.cs" />\r
       <Compile Include="Ast\SymbolConstantExpression.cs" />\r
       <Compile Include="Ast\TryStatementBuilder.cs" />\r
       <Compile Include="Ast\UnaryExpression.cs" />\r
+      <Compile Include="Ast\Utils.cs" />\r
       <Compile Include="Ast\VariableDictionaryExpression.cs" />\r
       <Compile Include="Ast\YieldExpression.cs" />\r
     </ItemGroup>\r
       <Compile Include="Generation\ILGen.cs" />\r
       <Compile Include="Generation\KeyedQueue.cs" />\r
       <Compile Include="Generation\MethodSignatureInfo.cs" />\r
-      <Compile Include="Generation\ParameterInfoWrapper.cs" />\r
       <Compile Include="Generation\Snippets.cs" />\r
       <Compile Include="Generation\ToDiskRewriter.cs" />\r
       <Compile Include="Generation\TypeGen.cs" />\r
       <!--          Interpreter          -->\r
       <!--                               -->\r
       <Compile Include="Interpreter\BranchLabel.cs" />\r
+      <Compile Include="Interpreter\ILightCallSiteBinder.cs" />\r
       <Compile Include="Interpreter\InterpretedFrame.cs" />\r
       <Compile Include="Interpreter\Interpreter.cs" />\r
       <Compile Include="Interpreter\LastFaultingLineExpression.cs" />\r
       <Compile Include="Interpreter\LightLambda.cs" />\r
       <Compile Include="Interpreter\LightLambda.Generated.cs" />\r
       <Compile Include="Interpreter\LightLambdaClosureVisitor.cs" />\r
+      <Compile Include="Interpreter\LocalVariables.cs" />\r
+      <Compile Include="Interpreter\LoopCompiler.cs" />\r
       <Compile Include="Interpreter\RuntimeVariables.cs" />\r
     </ItemGroup>\r
     <ItemGroup>\r
       <Compile Include="Interpreter\Instructions\CallInstruction.cs" />\r
       <Compile Include="Interpreter\Instructions\CallInstruction.Generated.cs" />\r
       <Compile Include="Interpreter\Instructions\ControlFlowInstructions.cs" />\r
+      <Compile Include="Interpreter\Instructions\DivInstruction.cs" />\r
       <Compile Include="Interpreter\Instructions\DynamicInstructionN.cs" />\r
       <Compile Include="Interpreter\Instructions\DynamicInstructions.Generated.cs" />\r
+      <Compile Include="Interpreter\Instructions\DynamicSplatInstruction.cs" />\r
       <Compile Include="Interpreter\Instructions\EqualInstruction.cs" />\r
       <Compile Include="Interpreter\Instructions\FieldOperations.cs" />\r
       <Compile Include="Interpreter\Instructions\GreaterThanInstruction.cs" />\r
       <!--          Runtime          -->\r
       <!--                           -->\r
       <Compile Include="Runtime\AmbiguousFileNameException.cs" />\r
+      <Compile Include="Runtime\ArgumentArray.cs" />\r
       <Compile Include="Runtime\AssemblyTypeNames.cs" />\r
       <Compile Include="Runtime\BaseSymbolDictionary.cs" />\r
       <Compile Include="Runtime\BinderOps.cs" />\r
       <Compile Include="Runtime\CodeDomCodeGen.cs" />\r
       <Compile Include="Runtime\CompilerContext.cs" />\r
       <Compile Include="Runtime\CustomSymbolDictionary.cs" />\r
-      <Compile Include="Runtime\DefaultLanguageContext.cs" />\r
       <Compile Include="Runtime\DelegateInfo.cs" />\r
       <Compile Include="Runtime\DelegateSignatureInfo.cs" />\r
       <Compile Include="Runtime\DlrCachedCodeAttribute.cs" />\r
       <Compile Include="Runtime\DynamicDelegateCreator.cs" />\r
       <Compile Include="Runtime\DynamicLanguageProviderAttribute.cs" />\r
       <Compile Include="Runtime\DynamicNull.cs" />\r
-      <Compile Include="Runtime\DynamicRuntimeHostingProvider.cs" />\r
       <Compile Include="Runtime\DynamicStackFrame.cs" />\r
       <Compile Include="Runtime\ExceptionHelpers.cs" />\r
       <Compile Include="Runtime\ExplicitConversionMethodAttribute.cs" />\r
       <Compile Include="Utils\SynchronizedDictionary.cs" />\r
       <Compile Include="Utils\TextStream.cs" />\r
       <Compile Include="Utils\ThreadLocal.cs" />\r
-      <Compile Include="Utils\TypeExtensions.cs" />\r
       <Compile Include="Utils\TypeUtils.cs" />\r
       <Compile Include="Utils\ValueArray.cs" />\r
       <Compile Include="Utils\WeakCollection.cs" />\r
     <DebugSymbols>true</DebugSymbols>
     <DebugType>full</DebugType>
     <Optimize>false</Optimize>
-    <OutputPath>$(SolutionDir)\..\Bin\40\</OutputPath>
-    <DefineConstants>DEBUG;TRACE;CODEPLEX_40;SYSTEM_CORE</DefineConstants>
+    <OutputPath>$(SolutionDir)..\Bin\40\</OutputPath>
+    <DefineConstants>DEBUG;TRACE;CODEPLEX_40;CLR4;SYSTEM_CORE</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
     <DebugType>pdbonly</DebugType>
     <Optimize>true</Optimize>
-    <OutputPath>$(SolutionDir)\..\Bin\40\</OutputPath>
-    <DefineConstants>TRACE;CODEPLEX_40;SYSTEM_CORE</DefineConstants>
+    <OutputPath>$(SolutionDir)..\Bin\40\</OutputPath>
+    <DefineConstants>TRACE;CODEPLEX_40;CLR4;SYSTEM_CORE</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
   </PropertyGroup>\r
index 27e163520eed0346ca926a420d0c03189605bf24..17b03f9b14fde942d998c39565c3219cd9ca11a5 100644 (file)
@@ -13,7 +13,7 @@
     <AssemblyName>Microsoft.Dynamic</AssemblyName>
     <WarningsNotAsErrors>1685,618,649</WarningsNotAsErrors>
     <NoWarn>1591</NoWarn>
-<AssemblyOriginatorKeyFile>$(SolutionDir)\Runtime\MSSharedLibKey.snk</AssemblyOriginatorKeyFile>
+<AssemblyOriginatorKeyFile>$(SolutionDir)Runtime\MSSharedLibKey.snk</AssemblyOriginatorKeyFile>
     <SignAssembly Condition="'$(SignAssembly)' == '' And Exists('$(AssemblyOriginatorKeyFile)')">true</SignAssembly>
     <SignedSym Condition="'$(SignAssembly)' == 'true'">SIGNED</SignedSym>
     <DelaySign>true</DelaySign>
@@ -28,7 +28,7 @@
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'FxCop|AnyCPU' ">
     <DebugType>pdbonly</DebugType>
     <Optimize>true</Optimize>
-<OutputPath>$(SolutionDir)\..\Bin\fxcop\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\fxcop\</OutputPath>
     <DefineConstants>TRACE;CLR2;$(SignedSym)</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
@@ -40,7 +40,7 @@
     <DebugSymbols>true</DebugSymbols>
     <DebugType>full</DebugType>
     <Optimize>false</Optimize>
-<OutputPath>$(SolutionDir)\..\Bin\Debug\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\Debug\</OutputPath>
 <DocumentationFile>$(OutputPath)\Microsoft.Dynamic.xml</DocumentationFile>
     <DefineConstants>DEBUG;TRACE;CLR2;$(SignedSym)</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
@@ -51,7 +51,7 @@
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
     <DebugType>pdbonly</DebugType>
     <Optimize>true</Optimize>
-<OutputPath>$(SolutionDir)\..\Bin\Release\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\Release\</OutputPath>
 <DocumentationFile>$(OutputPath)\Microsoft.Dynamic.xml</DocumentationFile>
     <DefineConstants>TRACE;CLR2;$(SignedSym)</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
@@ -61,7 +61,7 @@
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Silverlight Debug|AnyCPU' ">
     <DebugSymbols>true</DebugSymbols>
-<OutputPath>$(SolutionDir)\..\Bin\Silverlight Debug\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\Silverlight Debug\</OutputPath>
     <DefineConstants>TRACE;DEBUG;SILVERLIGHT;CLR2;$(SignedSym)</DefineConstants>
     <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
     <DebugType>full</DebugType>
@@ -76,7 +76,7 @@
     <SilverlightPath Condition="'$(SilverlightPath)' == ''">$(Silverlight3Path)</SilverlightPath>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Silverlight Release|AnyCPU' ">
-<OutputPath>$(SolutionDir)\..\Bin\Silverlight Release\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\Silverlight Release\</OutputPath>
     <DefineConstants>TRACE;SILVERLIGHT;CLR2;$(SignedSym)</DefineConstants>
 <DocumentationFile>$(OutputPath)\Microsoft.Dynamic.xml</DocumentationFile>
     <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
@@ -93,7 +93,7 @@
     <DebugSymbols>true</DebugSymbols>
     <DebugType>full</DebugType>
     <Optimize>false</Optimize>
-<OutputPath>$(SolutionDir)\..\Bin\Debug\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\V4 Debug\</OutputPath>
 <DocumentationFile>$(OutputPath)\Microsoft.Dynamic.xml</DocumentationFile>
     <DefineConstants>DEBUG;TRACE;CLR4;$(SignedSym)</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'V4 Release|AnyCPU' ">
     <DebugType>pdbonly</DebugType>
     <Optimize>true</Optimize>
-<OutputPath>$(SolutionDir)\..\Bin\Release\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\V4 Release\</OutputPath>
 <DocumentationFile>$(OutputPath)\Microsoft.Dynamic.xml</DocumentationFile>
     <DefineConstants>TRACE;CLR4;$(SignedSym)</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <DebugSymbols>true</DebugSymbols>
     <DebugType>full</DebugType>
     <Optimize>false</Optimize>
-<OutputPath>$(SolutionDir)\..\Bin\Debug\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\Debug\</OutputPath>
     <DefineConstants>TRACE;DEBUG;SILVERLIGHT;CLR4;$(SignedSym)</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
     <DebugType>pdbonly</DebugType>
     <Optimize>true</Optimize>
     <PlatformTarget>AnyCPU</PlatformTarget>
-<OutputPath>$(SolutionDir)\..\Bin\Release\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\Release\</OutputPath>
     <DefineConstants>TRACE;SILVERLIGHT;CLR4;$(SignedSym)</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
     <Compile Include="Actions\Calls\MethodCandidate.cs" />
     <Compile Include="Actions\Calls\NarrowingLevel.cs" />
     <Compile Include="Actions\Calls\OutArgBuilder.cs" />
+    <Compile Include="Actions\Calls\OverloadInfo.cs" />
     <Compile Include="Actions\Calls\OverloadResolver.cs" />
     <Compile Include="Actions\Calls\OverloadResolverFactory.cs" />
     <Compile Include="Actions\Calls\ParameterMapping.cs" />
     <Compile Include="Actions\MemberRequestKind.cs" />
     <Compile Include="Actions\OperationBinder.cs" />
     <Compile Include="Actions\OperationMetaObject.cs" />
+    <Compile Include="Ast\BlockBuilder.cs" />
+    <Compile Include="Ast\ExpressionCollectionBuilder.cs" />
     <Compile Include="Ast\FinallyFlowControlExpression.cs" />
     <Compile Include="Ast\FlowControlRewriter.cs" />
     <Compile Include="Ast\SourceFileInformation.cs" />
     <Compile Include="Ast\SkipInterpretExpression.cs" />
+    <Compile Include="Ast\LightDynamicExpression.cs" />
+    <Compile Include="Ast\Utils.cs" />
     <Compile Include="Ast\VariableDictionaryExpression.cs" />
     <Compile Include="Ast\NewArrayExpression.cs" />
     <Compile Include="Ast\NewExpression.cs" />
     <Compile Include="Interpreter\Instructions\CallInstruction.cs" />
     <Compile Include="Interpreter\Instructions\CallInstruction.Generated.cs" />
     <Compile Include="Interpreter\Instructions\ControlFlowInstructions.cs" />
+    <Compile Include="Interpreter\Instructions\DivInstruction.cs" />
+    <Compile Include="Interpreter\Instructions\DynamicSplatInstruction.cs" />
     <Compile Include="Interpreter\Instructions\EqualInstruction.cs" />
     <Compile Include="Interpreter\Instructions\FieldOperations.cs" />
     <Compile Include="Interpreter\Instructions\GreaterThanInstruction.cs" />
     <Compile Include="Interpreter\Instructions\NumericConvertInstruction.cs" />
     <Compile Include="Interpreter\Instructions\StackOperations.cs" />
     <Compile Include="Interpreter\Instructions\TypeOperations.cs" />
+    <Compile Include="Interpreter\ILightCallSiteBinder.cs" />
     <Compile Include="Interpreter\LightDelegateCreator.cs" />
     <Compile Include="Interpreter\LightLambda.Generated.cs" />
     <Compile Include="Interpreter\Interpreter.cs" />
     <Compile Include="Interpreter\LightLambda.cs" />
     <Compile Include="Interpreter\Instructions\Instruction.cs" />
     <Compile Include="Interpreter\LightCompiler.cs" />
+    <Compile Include="Interpreter\LocalVariables.cs" />
+    <Compile Include="Interpreter\LoopCompiler.cs" />
     <Compile Include="Interpreter\RuntimeVariables.cs" />
     <Compile Include="Interpreter\InterpretedFrame.cs" />
     <Compile Include="Interpreter\LastFaultingLineExpression.cs" />
     <Compile Include="Math\BigIntegerV2.cs" />
     <Compile Include="Math\BigIntegerV4.cs" />
+    <Compile Include="Runtime\ArgumentArray.cs" />
     <Compile Include="Runtime\BindingRestrictionsHelpers.cs" />
     <Compile Include="Runtime\DynamicDelegateCreator.cs" />
     <Compile Include="Runtime\DynamicNull.cs" />
     <Compile Include="Generation\KeyedQueue.cs" />
     <Compile Include="Generation\Snippets.cs" />
     <Compile Include="Generation\TypeGen.cs" />
-    <Compile Include="Actions\BinderHelpers.cs" />
     <Compile Include="Actions\ComboActionRewriter.cs" />
     <Compile Include="Actions\ComboBinder.cs" />
     <Compile Include="Actions\ConditionalBuilder.cs" />
     <Compile Include="Runtime\Cast.Generated.cs" />
     <Compile Include="Runtime\Cast.cs" />
     <Compile Include="Runtime\CodeDomCodeGen.cs" />
-    <Compile Include="Runtime\DefaultLanguageContext.cs" />
     <Compile Include="Runtime\DelegateInfo.cs" />
     <Compile Include="Runtime\DelegateSignatureInfo.cs" />
     <Compile Include="Runtime\ISlice.cs" />
     <Compile Include="Utils\HashSet.cs" />
     <Compile Include="Utils\SynchronizedDictionary.cs" />
     <Compile Include="Utils\ThreadLocal.cs" />
-    <Compile Include="Utils\TypeExtensions.cs" />
     <Compile Include="Utils\TypeUtils.cs" />
     <Compile Include="Utils\ValueArray.cs" />
     <Compile Include="Utils\WeakCollection.cs" />
     <Compile Include="Ast\IfStatementTest.cs" />
     <Compile Include="Generation\CompilerHelpers.cs" />
     <Compile Include="Generation\IExpressionSerializable.cs" />
-    <Compile Include="Generation\ParameterInfoWrapper.cs" />
     <Compile Include="Generation\ToDiskRewriter.cs" />
     <Compile Include="Runtime\AssemblyTypeNames.cs" />
     <Compile Include="Runtime\BaseSymbolDictionary.cs" />
     <Compile Include="Runtime\CustomSymbolDictionary.cs" />
     <Compile Include="Runtime\DlrCachedCodeAttribute.cs" />
     <Compile Include="Runtime\DocumentationAttribute.cs" />
-    <Compile Include="Runtime\DynamicRuntimeHostingProvider.cs" />
-    <Compile Include="Runtime\DynamicStackFrame.cs" />
     <Compile Include="Runtime\ExceptionHelpers.cs" />
     <Compile Include="Runtime\ExplicitConversionMethodAttribute.cs" />
     <Compile Include="Runtime\Extensible.cs" />
   </ItemGroup>
   <ItemGroup Condition=" '$(SilverlightBuild)' != 'true' ">
     <Reference Include="System" />
+    <Reference Include="System.Xml" />
     <Reference Include="System.Configuration" />
     <Reference Include="System.Numerics" Condition=" '$(TargetFrameworkVersion)' == 'v4.0' " />
     <Reference Include="System.Core" Condition=" '$(TargetFrameworkVersion)' == 'v4.0' " />
+    <Reference Include="System.Data" />
+    <Reference Include="System.Runtime.Remoting" />
   </ItemGroup>
   <ItemGroup Condition=" '$(SilverlightBuild)' == 'true' ">
     <Reference Include="mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e">
       <SpecificVersion>False</SpecificVersion>
       <HintPath>$(SilverlightPath)\System.Core.dll</HintPath>
     </Reference>
+    <Reference Include="System.Numerics, Version=2.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Condition="'$(TargetFrameworkVersion)' == 'v4.0' ">
+      <SpecificVersion>False</SpecificVersion>
+      <HintPath>$(SilverlightPath)\System.Numerics.dll</HintPath>
+    </Reference>
   </ItemGroup>
   <ItemGroup>
     <ProjectReference Include="..\Microsoft.Scripting.Core\Microsoft.Scripting.Core.csproj" Condition="'$(TargetFrameworkVersion)' != 'v4.0'">
       <Project>{02FF0909-F5AD-48CF-A86A-345E721B7E40}</Project>
       <Name>Microsoft.Scripting</Name>
     </ProjectReference>
-    <Reference Include="System.Data" />
-    <Reference Include="System.Runtime.Remoting" Condition=" '$(SilverlightBuild)' != 'true' " />
-    <Reference Include="System.Xml" Condition=" '$(SilverlightBuild)' != 'true' " />
-    <Reference Include="System.Numerics" Condition="'$(TargetFrameworkVersion)' == 'v4.0'" />
   </ItemGroup>
   <ItemGroup>
     <Content Include="Microsoft.Scripting.txt" />
index c6d59800fde9afe243115f8697a1e1ca13394faa..a15dcb547c70b9da4786074941133e52869ad3ad 100644 (file)
@@ -63,11 +63,10 @@ using System.Security.Permissions;
 #endif
 
 #if !SILVERLIGHT
-[assembly: AssemblyVersion("0.9.6.20")]
-[assembly: AssemblyFileVersion("1.0.0.00")]
-[assembly: AssemblyInformationalVersion("1.0")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.1.00")]
+[assembly: AssemblyInformationalVersion("1.0.1")]
 [assembly: AllowPartiallyTrustedCallers]
-#if CODEPLEX_40
-[assembly: SecurityRules(SecurityRuleSet.Level1)]
-#endif
+[assembly: TypeForwardedTo(typeof(Microsoft.Scripting.Runtime.DynamicStackFrame))]
 #endif
+
index 497331e8523a22e1f534ea395ddf80e6a4e6dfc0..8c00a873151c4526f97c19a62eb58d18870039b1 100644 (file)
@@ -265,28 +265,38 @@ namespace System.Dynamic {
             }
 
             public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) {
-                if (IsOverridden("TryInvokeMember")) {
-                    return CallMethodWithResult("TryInvokeMember", binder, GetArgArray(args), (e) => binder.FallbackInvokeMember(this, args, e));
-                } else if (IsOverridden("TryGetMember")) {
-                    // Generate a tree like:
-                    //
-                    // {
-                    //   object result;
-                    //   TryGetMember(payload, out result) ? FallbackInvoke(result) : fallbackResult
-                    // }
-                    //
-                    // Then it calls FallbackInvokeMember with this tree as the
-                    // "error", giving the language the option of using this
-                    // tree or doing .NET binding.
-                    //
-                    return CallMethodWithResult(
-                        "TryGetMember", new GetBinderAdapter(binder), NoArgs,
-                        (e) => binder.FallbackInvokeMember(this, args, e),
+                // Generate a tree like:
+                //
+                // {
+                //   object result;
+                //   TryInvokeMember(payload, out result)
+                //      ? result
+                //      : TryGetMember(payload, out result)
+                //          ? FallbackInvoke(result)
+                //          : fallbackResult
+                // }
+                //
+                // Then it calls FallbackInvokeMember with this tree as the
+                // "error", giving the language the option of using this
+                // tree or doing .NET binding.
+                //
+                Fallback fallback = e => binder.FallbackInvokeMember(this, args, e);
+
+                var call = BuildCallMethodWithResult(
+                    "TryInvokeMember",
+                    binder,
+                    GetArgArray(args),
+                    BuildCallMethodWithResult(
+                        "TryGetMember",
+                        new GetBinderAdapter(binder),
+                        NoArgs,
+                        fallback(null), 
                         (e) => binder.FallbackInvoke(e, args, null)
-                    );
-                }
+                    ),
+                    null
+                );
 
-                return base.BindInvokeMember(binder, args);
+                return fallback(call);
             }
 
 
@@ -398,6 +408,24 @@ namespace System.Dynamic {
                 //
                 DynamicMetaObject fallbackResult = fallback(null);
 
+                var callDynamic = BuildCallMethodWithResult(methodName, binder, args, fallbackResult, fallbackInvoke);
+                
+                //
+                // Now, call fallback again using our new MO as the error
+                // When we do this, one of two things can happen:
+                //   1. Binding will succeed, and it will ignore our call to
+                //      the dynamic method, OR
+                //   2. Binding will fail, and it will use the MO we created
+                //      above.
+                //
+                return fallback(callDynamic);
+            }
+
+            private DynamicMetaObject BuildCallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, DynamicMetaObject fallbackResult, Fallback fallbackInvoke) {
+                if (!IsOverridden(methodName)) {
+                    return fallbackResult;
+                }
+
                 //
                 // Build a new expression like:
                 // {
@@ -445,16 +473,7 @@ namespace System.Dynamic {
                     ),
                     GetRestrictions().Merge(resultMO.Restrictions).Merge(fallbackResult.Restrictions)
                 );
-                
-                //
-                // Now, call fallback again using our new MO as the error
-                // When we do this, one of two things can happen:
-                //   1. Binding will succeed, and it will ignore our call to
-                //      the dynamic method, OR
-                //   2. Binding will fail, and it will use the MO we created
-                //      above.
-                //
-                return fallback(callDynamic);
+                return callDynamic;
             }
 
 
diff --git a/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/IInvokeOnGetBinder.cs b/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Actions/IInvokeOnGetBinder.cs
new file mode 100644 (file)
index 0000000..fd14068
--- /dev/null
@@ -0,0 +1,36 @@
+/* ****************************************************************************
+ *
+ * Copyright (c) Microsoft Corporation. 
+ *
+ * This source code is subject to terms and conditions of the Microsoft Public License. A 
+ * copy of the license can be found in the License.html file at the root of this distribution. If 
+ * you cannot locate the  Microsoft Public License, please send an email to 
+ * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound 
+ * by the terms of the Microsoft Public License.
+ *
+ * You must not remove this notice, or any other, from this software.
+ *
+ *
+ * ***************************************************************************/
+
+namespace System.Dynamic {
+    /// <summary>
+    /// Represents information about a dynamic get member operation, indicating
+    /// if the get member should invoke properties when performing the get.
+    /// </summary>
+    public interface IInvokeOnGetBinder {
+        /// <summary>
+        /// Gets the value indicating if this GetMember should invoke properties
+        /// when performing the get. The default value when this interface is not present
+        /// is true.
+        /// </summary>
+        /// <remarks>
+        /// This property is used by some languages to get a better COM interop experience.
+        /// When the value is set to false, the dynamic COM object won't invoke the object
+        /// but will instead bind to the name, and return an object that can be invoked or
+        /// indexed later. This is useful for indexed properties and languages that don't
+        /// produce InvokeMember call sites.
+        /// </remarks>
+        bool InvokeOnGet { get; }
+    }
+}
index 7ebb43f246256c2ad9e7972ab46038c4b440a3e5..f582eab01ab2199c62401665160e80cfd3a2293e 100644 (file)
@@ -248,6 +248,10 @@ namespace System.Dynamic.Utils {
             if (source.IsInterface || dest.IsInterface) {
                 return true;
             }
+            // Variant delegate conversion
+            if (IsLegalExplicitVariantDelegateConversion(source, dest))
+                return true;
+                
             // Object conversion
             if (source == typeof(object) || dest == typeof(object)) {
                 return true;
@@ -255,6 +259,102 @@ namespace System.Dynamic.Utils {
             return false;
         }
 
+        private static bool IsCovariant(Type t)
+        {
+            Debug.Assert(t != null);
+            return 0 != (t.GenericParameterAttributes & GenericParameterAttributes.Covariant);
+        }
+
+        private static bool IsContravariant(Type t)
+        {
+            Debug.Assert(t != null);
+            return 0 != (t.GenericParameterAttributes & GenericParameterAttributes.Contravariant);
+        }
+
+        private static bool IsInvariant(Type t)
+        {
+            Debug.Assert(t != null);
+            return 0 == (t.GenericParameterAttributes & GenericParameterAttributes.VarianceMask);
+        }
+
+        private static bool IsDelegate(Type t)
+        {
+            Debug.Assert(t != null);
+            return t.IsSubclassOf(typeof(System.Delegate));
+        }
+
+        internal static bool IsLegalExplicitVariantDelegateConversion(Type source, Type dest)
+        {
+            Debug.Assert(source != null && dest != null);
+
+            // There *might* be a legal conversion from a generic delegate type S to generic delegate type  T, 
+            // provided all of the follow are true:
+            //   o Both types are constructed generic types of the same generic delegate type, D<X1,... Xk>.
+            //     That is, S = D<S1...>, T = D<T1...>.
+            //   o If type parameter Xi is declared to be invariant then Si must be identical to Ti.
+            //   o If type parameter Xi is declared to be covariant ("out") then Si must be convertible
+            //     to Ti via an identify conversion,  implicit reference conversion, or explicit reference conversion.
+            //   o If type parameter Xi is declared to be contravariant ("in") then either Si must be identical to Ti, 
+            //     or Si and Ti must both be reference types.
+
+            if (!IsDelegate(source) || !IsDelegate(dest) || !source.IsGenericType || !dest.IsGenericType)
+                return false;
+
+            Type genericDelegate = source.GetGenericTypeDefinition();
+
+            if (dest.GetGenericTypeDefinition() != genericDelegate)
+                return false;
+
+            Type[] genericParameters = genericDelegate.GetGenericArguments();
+            Type[] sourceArguments = source.GetGenericArguments();
+            Type[] destArguments = dest.GetGenericArguments();
+
+            Debug.Assert(genericParameters != null);
+            Debug.Assert(sourceArguments != null);
+            Debug.Assert(destArguments != null);
+            Debug.Assert(genericParameters.Length == sourceArguments.Length);
+            Debug.Assert(genericParameters.Length == destArguments.Length);
+
+            for (int iParam = 0; iParam < genericParameters.Length; ++iParam)
+            {
+                Type sourceArgument = sourceArguments[iParam];
+                Type destArgument = destArguments[iParam];
+
+                Debug.Assert(sourceArgument != null && destArgument != null);
+               
+                // If the arguments are identical then this one is automatically good, so skip it.
+                if (AreEquivalent(sourceArgument, destArgument))
+                {
+                    continue;
+                }
+                
+                Type genericParameter = genericParameters[iParam];
+
+                Debug.Assert(genericParameter != null);
+
+                if (IsInvariant(genericParameter))
+                {
+                    return false;
+                }
+        
+                if (IsCovariant(genericParameter))
+                {
+                    if (!HasReferenceConversion(sourceArgument, destArgument))
+                    {
+                        return false;
+                    }
+                }
+                else if (IsContravariant(genericParameter))
+                {
+                    if (sourceArgument.IsValueType || destArgument.IsValueType)
+                    {
+                        return false;
+                    }
+                }
+            }
+            return true;
+        }
+
         internal static bool IsConvertible(Type type) {
             type = GetNonNullableType(type);
             if (type.IsEnum) {
index 5e3b9e93685a9456fc75e228691b598dc60da768..d632c72b6902100f9b2f8f414b86e72ec5c9551e 100644 (file)
@@ -33,14 +33,8 @@ namespace System.Linq.Expressions {
     internal static class ConstantCheck {
 
         internal static bool IsNull(Expression e) {
-            switch (e.NodeType) {
-                case ExpressionType.Constant:
-                    return ((ConstantExpression)e).Value == null;
-
-                case ExpressionType.TypeAs:
-                    var typeAs = (UnaryExpression)e;
-                    // if the TypeAs check is guarenteed to fail, then its result will be null
-                    return AnalyzeTypeIs(typeAs) == AnalyzeTypeIsResult.KnownFalse;
+            if (e.NodeType == ExpressionType.Constant) {
+                return ((ConstantExpression)e).Value == null;
             }
             return false;
         }
@@ -58,19 +52,6 @@ namespace System.Linq.Expressions {
             return AnalyzeTypeIs(typeIs.Expression, typeIs.TypeOperand);
         }
 
-        /// <summary>
-        /// If the result of a unary TypeAs expression is known statically, this
-        /// returns the result, otherwise it returns null, meaning we'll need
-        /// to perform the IsInst instruction at runtime.
-        /// 
-        /// The result of this function must be equivalent to IsInst, or
-        /// null.
-        /// </summary>
-        internal static AnalyzeTypeIsResult AnalyzeTypeIs(UnaryExpression typeAs) {
-            Debug.Assert(typeAs.NodeType == ExpressionType.TypeAs);
-            return AnalyzeTypeIs(typeAs.Operand, typeAs.Type);
-        }
-
         /// <summary>
         /// If the result of an isinst opcode is known statically, this
         /// returns the result, otherwise it returns null, meaning we'll need
@@ -114,13 +95,9 @@ namespace System.Linq.Expressions {
                 return AnalyzeTypeIsResult.KnownAssignable;
             }
 
-            //
-            // If we couldn't statically assign and the type is sealed, no
-            // value at runtime can make isinst succeed
-            //
-            if (nnOperandType.IsSealed) {
-                return AnalyzeTypeIsResult.KnownFalse;
-            }
+            // We used to have an if IsSealed, return KnownFalse check here.
+            // but that doesn't handle generic types & co/contravariance correctly.
+            // So just use IsInst, which we know always gives us the right answer.
 
             // Otherwise we need a full runtime check
             return AnalyzeTypeIsResult.Unknown;
index 6da45482a7c8505004c18c23050830686a1703c3..348b8d1a556e484dbc1ddc096caaea3384d63622 100644 (file)
@@ -611,7 +611,9 @@ namespace System.Linq.Expressions.Compiler {
             if (typeFrom.IsInterface || // interface cast
                typeTo.IsInterface ||
                typeFrom == typeof(object) || // boxing cast
-               typeTo == typeof(object)) {
+               typeTo == typeof(object) ||
+               TypeUtils.IsLegalExplicitVariantDelegateConversion(typeFrom, typeTo))
+            {
                 il.EmitCastToType(typeFrom, typeTo);
             } else if (isTypeFromNullable || isTypeToNullable) {
                 il.EmitNullableConversion(typeFrom, typeTo, isChecked);
@@ -661,6 +663,7 @@ namespace System.Linq.Expressions.Compiler {
             } else {
                 TypeCode tc = Type.GetTypeCode(typeTo);
                 if (isChecked) {
+                    // Overflow checking needs to know if the source value on the IL stack is unsigned or not.
                     if (isFromUnsigned) {
                         switch (tc) {
                             case TypeCode.SByte:
@@ -723,56 +726,47 @@ namespace System.Linq.Expressions.Compiler {
                         }
                     }
                 } else {
-                    if (isFromUnsigned) {
-                        switch (tc) {
-                            case TypeCode.SByte:
-                            case TypeCode.Byte:
-                                il.Emit(OpCodes.Conv_U1);
-                                break;
-                            case TypeCode.Int16:
-                            case TypeCode.UInt16:
-                            case TypeCode.Char:
-                                il.Emit(OpCodes.Conv_U2);
-                                break;
-                            case TypeCode.Int32:
-                            case TypeCode.UInt32:
-                                il.Emit(OpCodes.Conv_U4);
-                                break;
-                            case TypeCode.Int64:
-                            case TypeCode.UInt64:
+                    switch (tc) {
+                        case TypeCode.SByte:
+                            il.Emit(OpCodes.Conv_I1);
+                            break;
+                        case TypeCode.Byte:
+                            il.Emit(OpCodes.Conv_U1);
+                            break;
+                        case TypeCode.Int16:
+                            il.Emit(OpCodes.Conv_I2);
+                            break;
+                        case TypeCode.UInt16:
+                        case TypeCode.Char:
+                            il.Emit(OpCodes.Conv_U2);
+                            break;
+                        case TypeCode.Int32:
+                            il.Emit(OpCodes.Conv_I4);
+                            break;
+                        case TypeCode.UInt32:
+                            il.Emit(OpCodes.Conv_U4);
+                            break;
+                        case TypeCode.Int64:
+                            if (isFromUnsigned) {
                                 il.Emit(OpCodes.Conv_U8);
-                                break;
-                            default:
-                                throw Error.UnhandledConvert(typeTo);
-                        }
-                    } else {
-                        switch (tc) {
-                            case TypeCode.SByte:
-                            case TypeCode.Byte:
-                                il.Emit(OpCodes.Conv_I1);
-                                break;
-                            case TypeCode.Int16:
-                            case TypeCode.UInt16:
-                            case TypeCode.Char:
-                                il.Emit(OpCodes.Conv_I2);
-                                break;
-                            case TypeCode.Int32:
-                            case TypeCode.UInt32:
-                                il.Emit(OpCodes.Conv_I4);
-                                break;
-                            case TypeCode.Int64:
-                            case TypeCode.UInt64:
+                            } else {
                                 il.Emit(OpCodes.Conv_I8);
-                                break;
-                            default:
-                                throw Error.UnhandledConvert(typeTo);
-                        }
+                            }
+                            break;
+                        case TypeCode.UInt64:
+                            if (isFromUnsigned || isFromFloatingPoint) {
+                                il.Emit(OpCodes.Conv_U8);
+                            } else {
+                                il.Emit(OpCodes.Conv_I8);
+                            }
+                            break;
+                        default:
+                            throw Error.UnhandledConvert(typeTo);
                     }
                 }
             }
         }
 
-
         private static void EmitNullableToNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) {
             Debug.Assert(TypeUtils.IsNullableType(typeFrom));
             Debug.Assert(TypeUtils.IsNullableType(typeTo));
index 4769057e5d524259eb681ded3ccbc667a8fe9d98..69b1f0150ce52fbd8270a18441561d356fe9c98a 100644 (file)
@@ -14,7 +14,7 @@
     <AssemblyName>Microsoft.Scripting.Core</AssemblyName>
 <DocumentationFile>$(OutputPath)\Microsoft.Scripting.Core.XML</DocumentationFile>
     <NoWarn>1591</NoWarn>
-<AssemblyOriginatorKeyFile>$(SolutionDir)\Runtime\MSSharedLibKey.snk</AssemblyOriginatorKeyFile>
+<AssemblyOriginatorKeyFile>$(SolutionDir)Runtime\MSSharedLibKey.snk</AssemblyOriginatorKeyFile>
     <SignAssembly Condition="'$(SignAssembly)' == '' And Exists('$(AssemblyOriginatorKeyFile)')">true</SignAssembly>
     <SignedSym Condition="'$(SignAssembly)' == 'true'">SIGNED</SignedSym>
     <DelaySign>true</DelaySign>
@@ -25,7 +25,7 @@
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'FxCop|AnyCPU' ">
     <DebugType>pdbonly</DebugType>
     <Optimize>true</Optimize>
-<OutputPath>$(SolutionDir)\..\Bin\fxcop\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\fxcop\</OutputPath>
     <DefineConstants>TRACE;$(SignedSym);CLR2</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
@@ -39,7 +39,7 @@
     <DebugSymbols>true</DebugSymbols>
     <DebugType>full</DebugType>
     <Optimize>false</Optimize>
-<OutputPath>$(SolutionDir)\..\Bin\Debug\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\Debug\</OutputPath>
 <DocumentationFile>$(OutputPath)\Microsoft.Scripting.Core.xml</DocumentationFile>
     <DefineConstants>DEBUG;TRACE;$(SignedSym);CLR2</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
@@ -52,7 +52,7 @@
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
     <DebugType>pdbonly</DebugType>
     <Optimize>true</Optimize>
-<OutputPath>$(SolutionDir)\..\Bin\Release\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\Release\</OutputPath>
 <DocumentationFile>$(OutputPath)\Microsoft.Scripting.Core.xml</DocumentationFile>
     <DefineConstants>TRACE;$(SignedSym);CLR2</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
@@ -64,7 +64,7 @@
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Silverlight Debug|AnyCPU' ">
     <DebugSymbols>true</DebugSymbols>
-<OutputPath>$(SolutionDir)\..\Bin\Silverlight Debug\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\Silverlight Debug\</OutputPath>
     <DefineConstants>TRACE;DEBUG;SILVERLIGHT;CLR2</DefineConstants>
     <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
     <DebugType>full</DebugType>
@@ -77,7 +77,7 @@
     <SilverlightBuild>true</SilverlightBuild>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Silverlight Release|AnyCPU' ">
-<OutputPath>$(SolutionDir)\..\Bin\Silverlight Release\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\Silverlight Release\</OutputPath>
     <DefineConstants>TRACE;SILVERLIGHT;CLR2</DefineConstants>
 <DocumentationFile>$(OutputPath)\Microsoft.Scripting.Core.xml</DocumentationFile>
     <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
     </Compile>
     <Compile Include="Actions\CallInfo.cs" />
     <Compile Include="Actions\CallSiteOps.cs" />
+    <Compile Include="Actions\IInvokeOnGetBinder.cs" />
     <Compile Include="Actions\InvokeMemberBinder.cs" />
     <Compile Include="Actions\BinaryOperationBinder.cs" />
     <Compile Include="Actions\CallSite.cs" />
index 936dfe027f7a6e9b2f7c65d0391b5f91f275d96d..27331e551609be1ac27a87240f64ddef297618da 100644 (file)
@@ -11,7 +11,7 @@
     <AppDesignerFolder>Properties</AppDesignerFolder>
     <RootNamespace>Microsoft.Scripting.ExtensionAttribute</RootNamespace>
     <AssemblyName>Microsoft.Scripting.ExtensionAttribute</AssemblyName>
-<AssemblyOriginatorKeyFile>$(SolutionDir)\Runtime\MSSharedLibKey.snk</AssemblyOriginatorKeyFile>
+<AssemblyOriginatorKeyFile>$(SolutionDir)Runtime\MSSharedLibKey.snk</AssemblyOriginatorKeyFile>
     <SignAssembly Condition="'$(SignAssembly)' == '' And Exists('$(AssemblyOriginatorKeyFile)')">true</SignAssembly>
     <SignedSym Condition="'$(SignAssembly)' == 'true'">SIGNED</SignedSym>
     <DelaySign>true</DelaySign>
@@ -22,7 +22,7 @@
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'FxCop|AnyCPU' ">
     <DebugType>pdbonly</DebugType>
     <Optimize>true</Optimize>
-<OutputPath>$(SolutionDir)\..\Bin\fxcop\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\fxcop\</OutputPath>
     <DefineConstants>TRACE;$(SignedSym)</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
@@ -34,7 +34,7 @@
     <DebugSymbols>true</DebugSymbols>
     <DebugType>full</DebugType>
     <Optimize>false</Optimize>
-<OutputPath>$(SolutionDir)\..\Bin\Debug\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\Debug\</OutputPath>
     <DefineConstants>DEBUG;TRACE;$(SignedSym)</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
@@ -44,7 +44,7 @@
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
     <DebugType>pdbonly</DebugType>
     <Optimize>true</Optimize>
-<OutputPath>$(SolutionDir)\..\Bin\Release\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\Release\</OutputPath>
     <DefineConstants>TRACE;$(SignedSym)</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
@@ -54,7 +54,7 @@
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Silverlight Debug|AnyCPU' ">
     <DebugSymbols>true</DebugSymbols>
-<OutputPath>$(SolutionDir)\..\Bin\Silverlight Debug\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\Silverlight Debug\</OutputPath>
     <DefineConstants>TRACE;DEBUG;SILVERLIGHT</DefineConstants>
     <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
     <DebugType>full</DebugType>
@@ -66,7 +66,7 @@
     <SilverlightBuild>true</SilverlightBuild>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Silverlight Release|AnyCPU' ">
-<OutputPath>$(SolutionDir)\..\Bin\Silverlight Release\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\Silverlight Release\</OutputPath>
     <DefineConstants>TRACE;SILVERLIGHT</DefineConstants>
     <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
     <NoWarn>1591,618</NoWarn>
index 4b6bf4e90edb16fe0696d4d3565e6ec16af8e38e..16f747334d14a4d98cd571c3a5fcb4251680770b 100644 (file)
@@ -55,11 +55,8 @@ using System.Security;
 [assembly: System.Resources.NeutralResourcesLanguage("en-US")]
 
 #if !SILVERLIGHT
-[assembly: AssemblyVersion("0.9.6.20")]
-[assembly: AssemblyFileVersion("1.0.0.00")]
-[assembly: AssemblyInformationalVersion("1.0")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.1.00")]
+[assembly: AssemblyInformationalVersion("1.0.1")]
 [assembly: AllowPartiallyTrustedCallers]
-#if CODEPLEX_40
-[assembly: SecurityRules(SecurityRuleSet.Level1)]
-#endif
 #endif
index 071bc56e88d070d70a2b9ff7bb471a2a8eff20ee..bc47e001f31485a73708513de419f899139aaa80 100644 (file)
@@ -56,10 +56,7 @@ using System.Security;
 \r
 #if !SILVERLIGHT\r
 [assembly: AssemblyVersion("2.0.0.0")]  // shouldn't change, this assembly is unchanged.  This is the version it originally shipped as.\r
-[assembly: AssemblyFileVersion("1.0.0.00")]\r
-[assembly: AssemblyInformationalVersion("1.0")]\r
-[assembly: AllowPartiallyTrustedCallers]
-#if CODEPLEX_40
-[assembly: SecurityRules(SecurityRuleSet.Level1)]
-#endif\r
+[assembly: AssemblyFileVersion("1.0.1.00")]\r
+[assembly: AssemblyInformationalVersion("1.0.1")]\r
+[assembly: AllowPartiallyTrustedCallers]\r
 #endif\r
index 22938af0480acd20bb3a2f9c2a725644949eff38..79eebfbd561bd7629b3ce0840edaa05d54e672e5 100644 (file)
@@ -6,18 +6,17 @@
   <PropertyGroup>
     <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
     <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
-    <ProductVersion>9.0.21022</ProductVersion>
+    <ProductVersion>10.0.20624</ProductVersion>
     <SchemaVersion>2.0</SchemaVersion>
     <ProjectGuid>{2AE75F5A-CD1F-4925-9647-AF4D1C282FB4}</ProjectGuid>
     <OutputType>Library</OutputType>
     <AppDesignerFolder>Properties</AppDesignerFolder>
-    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <RootNamespace>System.Scripting</RootNamespace>
     <AssemblyName>System.Core</AssemblyName>
 <DocumentationFile>$(OutputPath)\System.Core.XML</DocumentationFile>
     <NoWarn>1591</NoWarn>
     <OldToolsVersion>2.0</OldToolsVersion>
-<AssemblyOriginatorKeyFile>$(SolutionDir)\Runtime\MSSharedLibKey.snk</AssemblyOriginatorKeyFile>
+<AssemblyOriginatorKeyFile>$(SolutionDir)Runtime\MSSharedLibKey.snk</AssemblyOriginatorKeyFile>
     <SignAssembly Condition="'$(SignAssembly)' == '' And Exists('$(AssemblyOriginatorKeyFile)')">true</SignAssembly>
     <SignedSym Condition="'$(SignAssembly)' == 'true'">SIGNED</SignedSym>
     <DelaySign>true</DelaySign>
@@ -27,7 +26,7 @@
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'FxCop|AnyCPU' ">
     <DebugType>pdbonly</DebugType>
     <Optimize>true</Optimize>
-<OutputPath>$(SolutionDir)\..\Bin\fxcop\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\fxcop\</OutputPath>
     <DefineConstants>TRACE;$(SignedSym)</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
@@ -42,7 +41,7 @@
     <DebugSymbols>true</DebugSymbols>
     <DebugType>full</DebugType>
     <Optimize>false</Optimize>
-<OutputPath>$(SolutionDir)\..\Bin\Debug\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\Debug\</OutputPath>
 <DocumentationFile>$(OutputPath)\System.Core.xml</DocumentationFile>
     <DefineConstants>DEBUG;TRACE;$(SignedSym)</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
@@ -55,7 +54,7 @@
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
     <DebugType>pdbonly</DebugType>
     <Optimize>true</Optimize>
-<OutputPath>$(SolutionDir)\..\Bin\Release\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\Release\</OutputPath>
 <DocumentationFile>$(OutputPath)\System.Scripting.Core.xml</DocumentationFile>
     <DefineConstants>TRACE;$(SignedSym)</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
@@ -67,7 +66,7 @@
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Silverlight Debug|AnyCPU' ">
     <DebugSymbols>true</DebugSymbols>
-<OutputPath>$(SolutionDir)\..\Bin\Silverlight Debug\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\Silverlight Debug\</OutputPath>
     <DefineConstants>TRACE;DEBUG;SILVERLIGHT</DefineConstants>
     <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
     <DebugType>full</DebugType>
@@ -81,7 +80,7 @@
     <SilverlightSdkPath>$(ProgramFiles)\Microsoft Silverlight\2.0.31005.0</SilverlightSdkPath>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Silverlight Release|AnyCPU' ">
-<OutputPath>$(SolutionDir)\..\Bin\Silverlight Release\</OutputPath>
+<OutputPath>$(SolutionDir)..\Bin\Silverlight Release\</OutputPath>
     <DefineConstants>TRACE;SILVERLIGHT</DefineConstants>
 <DocumentationFile>$(OutputPath)\System.Scripting.Core.xml</DocumentationFile>
     <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
     <Compile Include="Actions\BinaryOperationBinder.cs" />
     <Compile Include="Actions\CallSite.cs" />
     <Compile Include="Actions\CallSiteBinder.cs" />
-    <Compile Include="Actions\CallSiteRule.cs" />
     <Compile Include="Actions\CallSiteHelpers.cs" />
     <Compile Include="Actions\ConvertBinder.cs" />
     <Compile Include="Actions\DeleteIndexBinder.cs" />
     <Compile Include="Actions\RuleCache.cs" />
     <Compile Include="Actions\SetIndexBinder.cs" />
     <Compile Include="Actions\SetMemberBinder.cs" />
-    <Compile Include="Actions\SmallRuleSet.cs" />
     <Compile Include="Ast\Expression.DebuggerProxy.cs" />
     <Compile Include="Ast\IArgumentProvider.cs" />
     <Compile Include="Ast\ListArgumentProvider.cs" />
-    <Compile Include="Compiler\ArgumentPrepender.cs" />
     <Compile Include="Actions\UnaryOperationBinder.cs" />
     <Compile Include="Ast\ExpressionStringBuilder.cs" />
     <Compile Include="Compiler\BoundConstants.cs" />
     <Compile Include="Compiler\RuntimeVariableList.cs" />
     <Compile Include="Actions\UpdateDelegates.Generated.cs" />
     <Compile Include="Ast\DynamicExpression.cs" />
-    <Compile Include="Actions\AutoRuleTemplate.cs" />
     <Compile Include="Ast\BinaryExpression.cs" />
     <Compile Include="Ast\BlockExpression.cs" />
     <Compile Include="Ast\CatchBlock.cs" />
     <Compile Include="Ast\ParameterExpression.cs" />
     <Compile Include="Ast\SwitchCase.cs" />
     <Compile Include="Ast\SwitchExpression.cs" />
-    <Compile Include="Ast\TreeComparer.cs" />
     <Compile Include="Ast\TryExpression.cs" />
     <Compile Include="Ast\TypeBinaryExpression.cs" />
     <Compile Include="Ast\TypeUtils.cs" />
     <Compile Include="Compiler\ConstantCheck.cs" />
     <Compile Include="Compiler\ExpressionQuoter.cs" />
     <Compile Include="Ast\ExpressionVisitor.cs" />
-    <Compile Include="Ast\ExpressionWriter.cs" />
+    <Compile Include="Ast\DebugViewWriter.cs" />
     <Compile Include="Compiler\HoistedLocals.cs" />
     <Compile Include="Compiler\KeyedQueue.cs" />
     <Compile Include="Compiler\LambdaCompiler.Address.cs" />
     <Compile Include="Utils\TrueReadOnlyCollection.cs" />
     <Compile Include="Utils\TypeExtensions.cs" />
     <Compile Include="Stubs.cs" />
-    <Compile Include="Utils\WeakUniqueSet.cs" />
   </ItemGroup>
   <ItemGroup>
     <Content Include="..\..\System\Linq\Expressions\System.Linq.Expressions.txt">
index 6362b22582761ba9b2f3ce06991c443e5c0ffb77..98c9c1e06c77a9a6a833adf8d51f84d91ce37ae4 100644 (file)
@@ -1,3 +1,7 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * Makefile: rename the net_2_1 profile to moonlight.
+
 2009-06-18  Raja R Harinath  <harinath@hurrynot.org>
 
        * Makefile (run-test-local): Make parallel-make safe.
index 605731dd5065f4cb0a5207472cedf0a81834f89c..105862568c6489b267e1939b138fec733eb5a8a2 100644 (file)
@@ -35,7 +35,7 @@ TEST_SUPPORT_FILES = \
 # mention all targets
 all-local $(STD_TARGETS:=-local):
 
-VALID_PROFILE := $(filter net_2_0 net_2_1 net_4_0, $(PROFILE))
+VALID_PROFILE := $(filter net_2_0 moonlight net_4_0, $(PROFILE))
 ifdef VALID_PROFILE
 
 check: run-mcs-tests 
@@ -53,7 +53,7 @@ ifeq (net_4_0, $(PROFILE))
 COMPILER_NAME = dmcs
 TEST_PATTERN = 'v4'
 endif
-ifeq (net_2_1, $(PROFILE))
+ifeq (moonlight, $(PROFILE))
 COMPILER_NAME = smcs
 TEST_PATTERN = 'v2'
 LOCAL_RUNTIME_FLAGS = --security=temporary-smcs-hack
diff --git a/mcs/errors/cs0182-10.cs b/mcs/errors/cs0182-10.cs
new file mode 100644 (file)
index 0000000..1ce2d2f
--- /dev/null
@@ -0,0 +1,18 @@
+// CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression
+// Line: 13
+
+using System;
+
+class TestAttribute: Attribute
+{
+       public TestAttribute (int[][] o) {}
+}
+
+public class E
+{
+       [Test (null)]
+       public static void Main ()
+       {
+               System.Reflection.MethodBase.GetCurrentMethod().GetCustomAttributes (true);
+       }
+}
\ No newline at end of file
diff --git a/mcs/errors/cs0182-8.cs b/mcs/errors/cs0182-8.cs
new file mode 100644 (file)
index 0000000..56d98c4
--- /dev/null
@@ -0,0 +1,19 @@
+// CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression
+// Line: 13
+
+using System;
+
+class MyAttribute : Attribute {
+
+       public MyAttribute (string s)
+       {
+       }
+}
+
+[My (null as string)]
+class X {
+
+       static void Main ()
+       {
+       }
+}
diff --git a/mcs/errors/cs0182-9.cs b/mcs/errors/cs0182-9.cs
new file mode 100644 (file)
index 0000000..2fb5cf4
--- /dev/null
@@ -0,0 +1,18 @@
+// CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression
+// Line: 13
+
+using System;
+
+class TestAttribute: Attribute
+{
+       public TestAttribute (object o) {}
+}
+
+public class E
+{
+       [Test (new int[][] { null })]
+       public static void Main ()
+       {
+               System.Reflection.MethodBase.GetCurrentMethod().GetCustomAttributes (true);
+       }
+}
\ No newline at end of file
index 3f524e915797907396f6cfbbd09896a5d09ba4f3..915e8277b263b58b34899571ba547a7e0ca95e99 100644 (file)
@@ -1,4 +1,4 @@
-// cs0415.cs: The `IndexerName' attribute is valid only on an indexer that is not an explicit interface member declaration
+// CS0415: The `System.Runtime.CompilerServices.IndexerNameAttribute' attribute is valid only on an indexer that is not an explicit interface member declaration
 // Line: 11
 
 using System.Runtime.CompilerServices;
@@ -8,7 +8,7 @@ interface A {
 }
 
 class X : A {
-        [IndexerName("Error")]
+       [IndexerName("Error")]
        int A.this [int a] { set {} }
 }
 
diff --git a/mcs/errors/gcs0701-3.cs b/mcs/errors/gcs0701-3.cs
deleted file mode 100644 (file)
index 4522501..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-// CS0703: `string[]' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter\r
-// Line: 4\r
-\r
-public class C<T>  where T : string[]\r
-{\r
-}
\ No newline at end of file
diff --git a/mcs/errors/gcs0706.cs b/mcs/errors/gcs0706.cs
new file mode 100644 (file)
index 0000000..08edb3f
--- /dev/null
@@ -0,0 +1,6 @@
+// CS0706: Invalid constraint type `string[]'\r
+// Line: 4\r
+\r
+public class C<T>  where T : string[]\r
+{\r
+}\r
index e75a2bf8d5799b0989f935ffa5cfefc10af5bb4c..e953c391a571825e46e96d9da3a15ef66a005e16 100644 (file)
@@ -26,3 +26,6 @@ cs1540-9.cs
 # the error message has an assembly version in it
 cs1685.cs
 gcs1685.cs
+
+dcs0121.cs NO ERROR # Bug 593368
+dcs0165.cs NO ERROR # Bug 593369
index 5480e0f957cfec8b8cbbc544108bb553702a52c9..4d3ff33de2f2d8c612d9cca8398cb206333c9a74 100644 (file)
@@ -1,3 +1,11 @@
+2010-03-14  Zoltan Varga  <vargaz@gmail.com>
+
+       * ILParser.jay: Fix the float32(<long>) case in the previous change.
+
+2010-03-14  Zoltan Varga  <vargaz@gmail.com>
+
+       * ILParser.jay: Fix support for hex float literals on big-endian platforms.
+
 2009-04-20  Ankit Jain  <jankit@novell.com>
 
        Fix bug #494221.
index 32247371fefc22465ed8c5e60be600366e836ae9..b94d64121b1a36638fffc5c6fdd68b3f5c57b352 100644 (file)
@@ -3274,7 +3274,7 @@ float64                   : FLOAT64
                           {\r
                                 int i = (int) $3;\r
                                 byte[] intb = BitConverter.GetBytes (i);\r
-                                $$ = (double) BitConverter.ToSingle (intb, BitConverter.IsLittleEndian ? 0 : 4);\r
+                                $$ = (double) BitConverter.ToSingle (intb, 0);\r
                           }\r
                         | K_FLOAT32 OPEN_PARENS INT64 CLOSE_PARENS\r
                           {\r
@@ -3285,12 +3285,12 @@ float64                 : FLOAT64
                        | K_FLOAT64 OPEN_PARENS INT64 CLOSE_PARENS\r
                           {\r
                                 byte[] intb = BitConverter.GetBytes ((long) $3);\r
-                               $$ = BitConverter.ToDouble (intb, BitConverter.IsLittleEndian ? 0 : 4);\r
+                               $$ = BitConverter.ToDouble (intb, 0);\r
                           }\r
                         | K_FLOAT64 OPEN_PARENS INT32 CLOSE_PARENS\r
                           {\r
                                 byte[] intb = BitConverter.GetBytes ((int) $3);\r
-                                $$ = (double) BitConverter.ToSingle (intb, BitConverter.IsLittleEndian ? 0 : 4);\r
+                                $$ = (double) BitConverter.ToSingle (intb, 0);\r
                           }\r
                        ;\r
 \r
index 2d96cc9d174a357e466f5bfdd575f1c8713be5a6..ecef16580ea05277ca70bd130218e30d34e0e958 100644 (file)
@@ -1,3 +1,7 @@
+2010-04-05  Zoltan Varga  <vargaz@gmail.com>
+
+       * defs.h: Quiet warnings which might bother rpm.
+
 2009-11-27  Marek Safar  <marek.safar@gmail.com>
 
        * skeleton.cs: Add global state stacks.
index f3679864735109a25ade32aab48d6574282fe9f6..9e50b38d869a664aa77b8a0fb7d3cabaadb39b7e 100644 (file)
 #include <string.h>
 #include <errno.h>
 
+/* Quiet warnings which might bother rpm */
+#ifdef __GNUC__
+#pragma GCC diagnostic ignored "-Wimplicit-function-declaration"
+#pragma GCC diagnostic ignored "-Wreturn-type"
+#endif
 
 /*  machine-dependent definitions                      */
 /*  the following definitions are for the Tahoe                */
index 32230c2096a6fb84aa4b2a6f4f614af83d55a5b2..35174e6f6bacb7896cc4bf74b55e4a7c3d7e87c5 100644 (file)
@@ -1,3 +1,30 @@
+2010-04-15  Jb Evain  <jbevain@novell.com>
+
+       * dmcs.exe.config: update the runtime version to .net 4.0 RTM.
+
+2010-04-12  Marek Safar  <marek.safar@gmail.com>
+
+       * expression.cs, attribute.cs, parameter.cs: More attribute type
+       checks.
+
+2010-04-12  Marek Safar  <marek.safar@gmail.com>
+
+       A fix for bug #593342
+
+       * generic.cs, parameter.cs, argument.cs, field.cs, property.cs,
+       decl.cs, roottypes.cs, constant.cs, nullable.cs, expression.cs,
+       method.cs, ecore.cs, class.cs, delegate.cs, attribute.cs,
+       codegen.cs: Add custom attribute encoder to deal with unfinished
+       types and easier corlib bootstrap from its own types.
+
+2010-03-26  Marek Safar  <marek.safar@gmail.com>
+
+       * cs-parser.jay: Report invalid constraint types.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * Makefile: rename the net_2_1 profile to moonlight.
+
 2010-03-11  Marek Safar  <marek.safar@gmail.com>
 
        * statement.cs, cs-parser.jay: Use correct location for empty
index 6d496c57f5e2d2146558e4047f81b38aac7b6c78..43a2780851e2951341f0ad3643d120cb53c7de59 100644 (file)
@@ -18,7 +18,7 @@ ifeq (net_2_0, $(PROFILE))
 INTERNAL_GMCS = $(RUNTIME) $(RUNTIME_FLAGS) $(topdir)/class/lib/$(BOOTSTRAP_PROFILE)/gmcs.exe
 endif
 
-ifeq (net_2_1_bootstrap, $(PROFILE))
+ifeq (moonlight_bootstrap, $(PROFILE))
 INTERNAL_GMCS = $(RUNTIME) $(RUNTIME_FLAGS) $(topdir)/class/lib/$(BOOTSTRAP_PROFILE)/gmcs.exe
 endif
 
index 4245c6f67efbe623169a9a689c494ff526bd074a..36a55cc761b4510cbe67e6cd4532c11d2885e049 100644 (file)
@@ -29,22 +29,9 @@ namespace Mono.CSharp {
                {
                }
 
-               protected CompilerGeneratedClass (DeclSpace parent, GenericMethod generic, MemberName name, Modifiers mod)
-                       : this (parent, name, mod)
-               {
-                       if (generic != null) {
-                               var list = new List<Constraints> ();
-                               foreach (TypeParameter tparam in generic.TypeParameters) {
-                                       if (tparam.Constraints != null)
-                                               list.Add (tparam.Constraints.Clone ());
-                               }
-                               SetParameterInfo (list);
-                       }
-               }
-
                protected void CheckMembersDefined ()
                {
-                       if (members_defined)
+                       if (HasMembersDefined)
                                throw new InternalErrorException ("Helper class already defined!");
                }
        }
@@ -82,8 +69,8 @@ namespace Mono.CSharp {
                                        return false;
 
                                AnonymousMethodStorey parent = ((AnonymousMethodStorey) Parent).GetGenericStorey ();
-                               if (parent != null)
-                                       member_type = parent.MutateType (MemberType);
+                               if (parent != null && parent.Mutator != null)
+                                       member_type = parent.Mutator.Mutate (MemberType);
 
                                return true;
                        }
@@ -113,11 +100,6 @@ namespace Mono.CSharp {
                        {
                                // Nothing to clone
                        }
-
-                       public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-                       {
-                               // Nothing to mutate
-                       }
                }
 
                // Unique storey ID
@@ -140,12 +122,22 @@ namespace Mono.CSharp {
                // Local variable which holds this storey instance
                public LocalTemporary Instance;
 
+               TypeParameterMutator mutator;
+
                public AnonymousMethodStorey (Block block, TypeContainer parent, MemberBase host, GenericMethod generic, string name)
-                       : base (parent, generic, MakeMemberName (host, name, generic, block.StartLocation), Modifiers.PRIVATE | Modifiers.SEALED)
+                       : base (parent, MakeMemberName (host, name, generic, block.StartLocation), Modifiers.PRIVATE | Modifiers.SEALED)
                {
                        Parent = parent;
                        OriginalSourceBlock = block;
                        ID = unique_id++;
+
+                       if (generic != null) {
+                               var hoisted_tparams = generic.CurrentTypeParameters;
+                               type_params = new TypeParameter [hoisted_tparams.Length];
+                               for (int i = 0; i < type_params.Length; ++i) {
+                                       type_params[i] = hoisted_tparams[i].CreateHoistedCopy (spec);
+                               }
+                       }
                }
 
                static MemberName MakeMemberName (MemberBase host, string name, GenericMethod generic, Location loc)
@@ -168,9 +160,18 @@ namespace Mono.CSharp {
                        Field f = AddCompilerGeneratedField ("<>f__this", type_expr);
                        f.Define ();
                        hoisted_this = new HoistedThis (this, f);
+
+                       // Inflated type instance has to be updated manually
+                       if (Instance.Type != f.Parent.CurrentType) {
+                               var inflator = new TypeParameterInflator (Instance.Type, TypeParameterSpec.EmptyTypes, TypeSpec.EmptyTypes);
+                               Instance.Type.MemberCache.AddMember (f.Spec.InflateMember (inflator));
+
+                               inflator = new TypeParameterInflator (f.Parent.CurrentType, TypeParameterSpec.EmptyTypes, TypeSpec.EmptyTypes);
+                               f.Parent.CurrentType.MemberCache.AddMember (f.Spec.InflateMember (inflator));
+                       }
                }
 
-               public Field AddCapturedVariable (string name, Type type)
+               public Field AddCapturedVariable (string name, TypeSpec type)
                {
                        CheckMembersDefined ();
 
@@ -208,7 +209,7 @@ namespace Mono.CSharp {
                                children_references.Add (block);
                }
 
-               public void AddParentStoreyReference (AnonymousMethodStorey storey)
+               public void AddParentStoreyReference (EmitContext ec, AnonymousMethodStorey storey)
                {
                        CheckMembersDefined ();
 
@@ -217,7 +218,7 @@ namespace Mono.CSharp {
                        else if (used_parent_storeys.Exists (i => i.Storey == storey))
                                return;
 
-                       TypeExpr type_expr = new TypeExpression (storey.TypeBuilder, Location);
+                       TypeExpr type_expr = storey.CreateStoreyTypeExpression (ec);
                        Field f = AddCompilerGeneratedField ("<>f__ref$" + storey.ID, type_expr);
                        used_parent_storeys.Add (new StoreyFieldPair (storey, f));
                }
@@ -256,28 +257,13 @@ namespace Mono.CSharp {
                        hoisted_params.Add (expr);
                }
 
-               public void ChangeParentStorey (AnonymousMethodStorey parentStorey)
+               TypeExpr CreateStoreyTypeExpression (EmitContext ec)
                {
-                       Parent = parentStorey;
-                       type_params = null;
-               }
-
-               //
-               // Initializes all hoisted variables
-               //
-               public void EmitStoreyInstantiation (EmitContext ec)
-               {
-                       // There can be only one instance variable for each storey type
-                       if (Instance != null)
-                               throw new InternalErrorException ();
-
-                       SymbolWriter.OpenCompilerGeneratedBlock (ec.ig);
-
                        //
                        // Create an instance of storey type
                        //
-                       Expression storey_type_expr;
-                       if (is_generic) {
+                       TypeExpr storey_type_expr;
+                       if (CurrentTypeParameters != null) {
                                //
                                // Use current method type parameter (MVAR) for top level storey only. All
                                // nested storeys use class type parameter (VAR)
@@ -288,21 +274,73 @@ namespace Mono.CSharp {
 
                                TypeArguments targs = new TypeArguments ();
 
-                               if (tparams.Length < CountTypeParameters) {
-                                       TypeParameter[] parent_tparams = ec.MemberContext.CurrentTypeDefinition.TypeParameters;
-                                       for (int i = 0; i < parent_tparams.Length; ++i)
-                                               targs.Add (new TypeParameterExpr (parent_tparams[i], Location));
-                               }
-                               
+                               //
+                               // Use type parameter name instead of resolved type parameter
+                               // specification to resolve to correctly nested type parameters
+                               //
                                for (int i = 0; i < tparams.Length; ++i)
-                                       targs.Add (new TypeParameterExpr (tparams[i], Location));
+                                       targs.Add (new SimpleName (tparams [i].Name, Location)); //  new TypeParameterExpr (tparams[i], Location));
 
-                               storey_type_expr = new GenericTypeExpr (TypeBuilder, targs, Location);
+                               storey_type_expr = new GenericTypeExpr (Definition, targs, Location);
                        } else {
-                               storey_type_expr = new TypeExpression (TypeBuilder, Location);
+                               storey_type_expr = new TypeExpression (CurrentType, Location);
+                       }
+
+                       return storey_type_expr;
+               }
+
+               public void SetNestedStoryParent (AnonymousMethodStorey parentStorey)
+               {
+                       Parent = parentStorey;
+                       type_params = null;
+                       spec.IsGeneric = false;
+                       spec.DeclaringType = parentStorey.CurrentType;
+//                     MemberName.TypeArguments = null;
+               }
+
+               protected override bool DoResolveTypeParameters ()
+               {
+                       // Although any storey can have type parameters they are all clones of method type
+                       // parameters therefore have to mutate MVAR references in any of cloned constraints
+                       if (type_params != null) {
+                               for (int i = 0; i < type_params.Length; ++i) {
+                                       var spec = type_params[i].Type;
+                                       spec.BaseType = mutator.Mutate (spec.BaseType);
+                                       if (spec.Interfaces != null) {
+                                               var mutated = new TypeSpec[spec.Interfaces.Count];
+                                               for (int ii = 0; ii < mutated.Length; ++ii) {
+                                                       mutated [ii] = mutator.Mutate (spec.Interfaces[ii]);
+                                               }
+
+                                               spec.Interfaces = mutated;
+                                       }
+
+                                       if (spec.TypeArguments != null) {
+                                               spec.TypeArguments = mutator.Mutate (spec.TypeArguments);
+                                       }
+                               }
                        }
 
-                       ResolveContext rc = new ResolveContext (this);
+                       return true;
+               }
+
+               //
+               // Initializes all hoisted variables
+               //
+               public void EmitStoreyInstantiation (EmitContext ec)
+               {
+                       // There can be only one instance variable for each storey type
+                       if (Instance != null)
+                               throw new InternalErrorException ();
+
+                       SymbolWriter.OpenCompilerGeneratedBlock (ec);
+
+                       //
+                       // Create an instance of a storey
+                       //
+                       Expression storey_type_expr = CreateStoreyTypeExpression (ec);
+
+                       ResolveContext rc = new ResolveContext (ec.MemberContext);
                        Expression e = new New (storey_type_expr, null, Location).Resolve (rc);
                        e.Emit (ec);
 
@@ -312,7 +350,7 @@ namespace Mono.CSharp {
                        EmitHoistedFieldsInitialization (ec);
 
                        SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
-                       SymbolWriter.CloseCompilerGeneratedBlock (ec.ig);
+                       SymbolWriter.CloseCompilerGeneratedBlock (ec);
                }
 
                void EmitHoistedFieldsInitialization (EmitContext ec)
@@ -321,18 +359,22 @@ namespace Mono.CSharp {
                        // Initialize all storey reference fields by using local or hoisted variables
                        //
                        if (used_parent_storeys != null) {
+                               var rc = new ResolveContext (ec.MemberContext);
+
                                foreach (StoreyFieldPair sf in used_parent_storeys) {
                                        //
-                                       // Setting local field
+                                       // Get instance expression of storey field
                                        //
                                        Expression instace_expr = GetStoreyInstanceExpression (ec);
-                                       FieldExpr f_set_expr = TypeManager.IsGenericType (instace_expr.Type) ?
-                                               new FieldExpr (sf.Field, instace_expr.Type, Location) :
-                                               new FieldExpr (sf.Field, Location);
+                                       var fs = sf.Field.Spec;
+                                       if (TypeManager.IsGenericType (instace_expr.Type))
+                                               fs = MemberCache.GetMember (instace_expr.Type, fs);
+
+                                       FieldExpr f_set_expr = new FieldExpr (fs, Location);
                                        f_set_expr.InstanceExpression = instace_expr;
 
                                        SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
-                                       if (a.Resolve (new ResolveContext (ec.MemberContext)) != null)
+                                       if (a.Resolve (rc) != null)
                                                a.EmitStatement (ec);
                                }
                        }
@@ -441,7 +483,7 @@ namespace Mono.CSharp {
                                        //
                                        // Access inside of same storey (S -> S)
                                        //
-                                       return new CompilerGeneratedThis (TypeBuilder, Location);
+                                       return new CompilerGeneratedThis (CurrentType, Location);
                                }
                                //
                                // External field access
@@ -453,7 +495,7 @@ namespace Mono.CSharp {
                        // Storey was cached to local field
                        //
                        FieldExpr f_ind = new FieldExpr (f, Location);
-                       f_ind.InstanceExpression = new CompilerGeneratedThis (TypeBuilder, Location);
+                       f_ind.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location);
                        return f_ind;
                }
 
@@ -470,128 +512,13 @@ namespace Mono.CSharp {
                        get { return hoisted_this; }
                }
 
-               //
-               // Mutate type dispatcher
-               //
-               public Type MutateType (Type type)
-               {
-                       if (TypeManager.IsGenericType (type))
-                               return MutateGenericType (type);
-
-                       if (TypeManager.IsGenericParameter (type))
-                               return MutateGenericArgument (type);
-
-                       if (type.IsArray)
-                               return MutateArrayType (type);
-                       return type;
-               }
-
-               //
-               // Changes method type arguments (MVAR) to storey (VAR) type arguments
-               //
-               public void MutateGenericMethod (MethodSpec ms)
-               {
-                       var method = (MethodInfo) ms.MetaInfo;
-                       Type [] t_args = TypeManager.GetGenericArguments (method);
-                       if (TypeManager.IsGenericType (method.DeclaringType)) {
-                               Type t = MutateGenericType (method.DeclaringType);
-                               if (t != method.DeclaringType) {
-                                       method = (MethodInfo) TypeManager.DropGenericMethodArguments (method);
-                                       if (TypeManager.IsBeingCompiled (method))
-                                               ms.MetaInfo = TypeBuilder.GetMethod (t, method);
-                                       else
-                                               ms.MetaInfo = MethodInfo.GetMethodFromHandle (method.MethodHandle, t.TypeHandle);
-                               }                               
-                       }
-
-                       if (t_args == null || t_args.Length == 0)
-                               return;
-
-                       for (int i = 0; i < t_args.Length; ++i)
-                               t_args [i] = MutateType (t_args [i]);
-
-                       method = (MethodInfo) ms.MetaInfo;
-                       ms.MetaInfo = method.GetGenericMethodDefinition ().MakeGenericMethod (t_args);
-               }
-
-               public void MutateConstructor (MethodSpec ms)
-               {
-                       var ctor = (ConstructorInfo) ms.MetaInfo;
-                       if (TypeManager.IsGenericType (ctor.DeclaringType)) {
-                               Type t = MutateGenericType (ctor.DeclaringType);
-                               if (t != ctor.DeclaringType) {
-                                       ctor = (ConstructorInfo) TypeManager.DropGenericMethodArguments (ctor);
-                                       if (TypeManager.IsBeingCompiled (ctor))
-                                               ms.MetaInfo = TypeBuilder.GetConstructor (t, ctor);
-                                       else
-                                               ms.MetaInfo = ConstructorInfo.GetMethodFromHandle (ctor.MethodHandle, t.TypeHandle);
-                               }
-                       }
-               }
-               
-               public void MutateField (FieldSpec fs)
-               {
-                       var field = fs.MetaInfo;
-                       if (TypeManager.IsGenericType (field.DeclaringType)) {
-                               Type t = MutateGenericType (field.DeclaringType);
-                               if (t != field.DeclaringType) {
-                                       field = TypeManager.DropGenericTypeArguments (field.DeclaringType).GetField (field.Name, TypeManager.AllMembers);
-                                       
-                                       // HACK: TypeBuilder has to be used when a type is of TypeBuilder* but there is no
-                                       // way how to find out (use type comparison when this becomes an issue)
-                                       if (t.GetType ().FullName == "System.Reflection.MonoGenericClass") {
-                                               fs.MetaInfo = TypeBuilder.GetField (t, field);
-                                       } else {
-                                               fs.MetaInfo = FieldInfo.GetFieldFromHandle (field.FieldHandle, t.TypeHandle);
-                                       }
-                               }
-                       }
-               }               
-
-               protected Type MutateArrayType (Type array)
-               {
-                       Type element = TypeManager.GetElementType (array);
-                       if (element.IsArray) {
-                               element = MutateArrayType (element);
-                       } else if (TypeManager.IsGenericParameter (element)) {
-                               element = MutateGenericArgument (element);
-                       } else if (TypeManager.IsGenericType (element)) {
-                               element = MutateGenericType (element);
-                       } else {
-                               return array;
+               public TypeParameterMutator Mutator {
+                       get {
+                               return mutator;
                        }
-
-                       int rank = array.GetArrayRank ();
-                       if (rank == 1)
-                               return element.MakeArrayType ();
-
-                       return element.MakeArrayType (rank);
-               }
-
-               protected Type MutateGenericType (Type type)
-               {
-                       Type [] t_args = TypeManager.GetTypeArguments (type);
-                       if (t_args == null || t_args.Length == 0)
-                               return type;
-
-                       for (int i = 0; i < t_args.Length; ++i)
-                               t_args [i] = MutateType (t_args [i]);
-
-                       return TypeManager.DropGenericTypeArguments (type).MakeGenericType (t_args);
-               }
-
-               //
-               // Changes method generic argument (MVAR) to type generic argument (VAR)
-               //
-               public Type MutateGenericArgument (Type type)
-               {
-                       if (CurrentTypeParameters != null) {
-                               TypeParameter tp = TypeParameter.FindTypeParameter (CurrentTypeParameters, type.Name);
-                               if (tp != null)
-                                       return tp.Type;
+                       set {
+                               mutator = value;
                        }
-
-                       return type;
                }
 
                public IList<ExplicitBlock> ReferencesFromChildrenBlock {
@@ -648,7 +575,7 @@ namespace Mono.CSharp {
                Dictionary<AnonymousExpression, FieldExpr> cached_inner_access; // TODO: Hashtable is too heavyweight
                FieldExpr cached_outer_access;
 
-               protected HoistedVariable (AnonymousMethodStorey storey, string name, Type type)
+               protected HoistedVariable (AnonymousMethodStorey storey, string name, TypeSpec type)
                        : this (storey, storey.AddCapturedVariable (name, type))
                {
                }
@@ -687,9 +614,12 @@ namespace Mono.CSharp {
                                // When setting top-level hoisted variable in generic storey
                                // change storey generic types to method generic types (VAR -> MVAR)
                                //
-                               cached_outer_access = storey.MemberName.IsGeneric ?
-                                       new FieldExpr (field, storey.Instance.Type, field.Location) :
-                                       new FieldExpr (field, field.Location);
+                               if (storey.MemberName.IsGeneric) {
+                                       var fs = MemberCache.GetMember (storey.Instance.Type, field.Spec);
+                                       cached_outer_access = new FieldExpr (fs, field.Location);
+                               } else {
+                                       cached_outer_access = new FieldExpr (field, field.Location);
+                               }
 
                                cached_outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
                                return cached_outer_access;
@@ -705,10 +635,13 @@ namespace Mono.CSharp {
                        }
 
                        if (inner_access == null) {
-                               inner_access = field.Parent.MemberName.IsGeneric ?
-                                       new FieldExpr (field, field.Parent.CurrentType, field.Location) :
-                                       new FieldExpr (field, field.Location);
-                                                       
+                               if (field.Parent.MemberName.IsGeneric) {
+                                       var fs = MemberCache.GetMember (field.Parent.CurrentType, field.Spec);
+                                       inner_access = new FieldExpr (fs, field.Location);
+                               } else {
+                                       inner_access = new FieldExpr (field, field.Location);
+                               }
+
                                inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
                                cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
                        }
@@ -861,13 +794,13 @@ namespace Mono.CSharp {
                        }
                }
 
-               Dictionary<Type, Expression> compatibles;
+               Dictionary<TypeSpec, Expression> compatibles;
                public ToplevelBlock Block;
 
                public AnonymousMethodExpression (Location loc)
                {
                        this.loc = loc;
-                       this.compatibles = new Dictionary<Type, Expression> ();
+                       this.compatibles = new Dictionary<TypeSpec, Expression> ();
                }
 
                public override string ExprClassName {
@@ -890,7 +823,7 @@ namespace Mono.CSharp {
                // Returns true if the body of lambda expression can be implicitly
                // converted to the delegate of type `delegate_type'
                //
-               public bool ImplicitStandardConversionExists (ResolveContext ec, Type delegate_type)
+               public bool ImplicitStandardConversionExists (ResolveContext ec, TypeSpec delegate_type)
                {
                        using (ec.With (ResolveContext.Options.InferReturnType, false)) {
                                using (ec.Set (ResolveContext.Options.ProbingMode)) {
@@ -899,14 +832,14 @@ namespace Mono.CSharp {
                        }
                }
 
-               protected Type CompatibleChecks (ResolveContext ec, Type delegate_type)
+               protected TypeSpec CompatibleChecks (ResolveContext ec, TypeSpec delegate_type)
                {
-                       if (TypeManager.IsDelegateType (delegate_type))
+                       if (delegate_type.IsDelegate)
                                return delegate_type;
 
-                       if (TypeManager.DropGenericTypeArguments (delegate_type) == TypeManager.expression_type) {
-                               delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
-                               if (TypeManager.IsDelegateType (delegate_type))
+                       if (delegate_type.IsGeneric && delegate_type.GetDefinition () == TypeManager.expression_type) {
+                               delegate_type = delegate_type.TypeArguments [0];
+                               if (delegate_type.IsDelegate)
                                        return delegate_type;
 
                                ec.Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
@@ -919,7 +852,7 @@ namespace Mono.CSharp {
                        return null;
                }
 
-               protected bool VerifyExplicitParameters (ResolveContext ec, Type delegate_type, AParametersCollection parameters)
+               protected bool VerifyExplicitParameters (ResolveContext ec, TypeSpec delegate_type, AParametersCollection parameters)
                {
                        if (VerifyParameterCompatibility (ec, delegate_type, parameters, ec.IsInProbingMode))
                                return true;
@@ -932,7 +865,7 @@ namespace Mono.CSharp {
                        return false;
                }
 
-               protected bool VerifyParameterCompatibility (ResolveContext ec, Type delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
+               protected bool VerifyParameterCompatibility (ResolveContext ec, TypeSpec delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
                {
                        if (Parameters.Count != invoke_pd.Count) {
                                if (ignore_errors)
@@ -964,7 +897,7 @@ namespace Mono.CSharp {
                                if (has_implicit_parameters)
                                        continue;
 
-                               Type type = invoke_pd.Types [i];
+                               TypeSpec type = invoke_pd.Types [i];
                                
                                // We assume that generic parameters are always inflated
                                if (TypeManager.IsGenericParameter (type))
@@ -991,26 +924,26 @@ namespace Mono.CSharp {
                //
                // Infers type arguments based on explicit arguments
                //
-               public bool ExplicitTypeInference (ResolveContext ec, TypeInferenceContext type_inference, Type delegate_type)
+               public bool ExplicitTypeInference (ResolveContext ec, TypeInferenceContext type_inference, TypeSpec delegate_type)
                {
                        if (!HasExplicitParameters)
                                return false;
 
-                       if (!TypeManager.IsDelegateType (delegate_type)) {
-                               if (TypeManager.DropGenericTypeArguments (delegate_type) != TypeManager.expression_type)
+                       if (!delegate_type.IsDelegate) {
+                               if (delegate_type.GetDefinition () != TypeManager.expression_type)
                                        return false;
 
                                delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
-                               if (!TypeManager.IsDelegateType (delegate_type))
+                               if (!delegate_type.IsDelegate)
                                        return false;
                        }
                        
-                       AParametersCollection d_params = TypeManager.GetDelegateParameters (ec, delegate_type);
+                       AParametersCollection d_params = Delegate.GetParameters (ec.Compiler, delegate_type);
                        if (d_params.Count != Parameters.Count)
                                return false;
 
                        for (int i = 0; i < Parameters.Count; ++i) {
-                               Type itype = d_params.Types [i];
+                               TypeSpec itype = d_params.Types [i];
                                if (!TypeManager.IsGenericParameter (itype)) {
                                        if (!TypeManager.HasElementType (itype))
                                                continue;
@@ -1023,7 +956,7 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public Type InferReturnType (ResolveContext ec, TypeInferenceContext tic, Type delegate_type)
+               public TypeSpec InferReturnType (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
                {
                        AnonymousExpression am;
                        using (ec.Set (ResolveContext.Options.ProbingMode | ResolveContext.Options.InferReturnType)) {
@@ -1042,13 +975,13 @@ namespace Mono.CSharp {
                // Returns AnonymousMethod container if this anonymous method
                // expression can be implicitly converted to the delegate type `delegate_type'
                //
-               public Expression Compatible (ResolveContext ec, Type type)
+               public Expression Compatible (ResolveContext ec, TypeSpec type)
                {
                        Expression am;
                        if (compatibles.TryGetValue (type, out am))
                                return am;
 
-                       Type delegate_type = CompatibleChecks (ec, type);
+                       TypeSpec delegate_type = CompatibleChecks (ec, type);
                        if (delegate_type == null)
                                return null;
 
@@ -1057,15 +990,8 @@ namespace Mono.CSharp {
                        // needed for the anonymous method.  We create the method here.
                        //
 
-                       var invoke_mb = Delegate.GetInvokeMethod (ec.Compiler,
-                               ec.CurrentType, delegate_type);
-                       Type return_type = TypeManager.TypeToCoreType (invoke_mb.ReturnType);
-
-#if MS_COMPATIBLE
-                       Type[] g_args = delegate_type.GetGenericArguments ();
-                       if (return_type.IsGenericParameter)
-                               return_type = g_args [return_type.GenericParameterPosition];
-#endif
+                       var invoke_mb = Delegate.GetInvokeMethod (ec.Compiler, delegate_type);
+                       TypeSpec return_type = invoke_mb.ReturnType;
 
                        //
                        // Second: the return type of the delegate must be compatible with 
@@ -1123,7 +1049,7 @@ namespace Mono.CSharp {
                        return am;
                }
 
-               protected virtual Expression CreateExpressionTree (ResolveContext ec, Type delegate_type)
+               protected virtual Expression CreateExpressionTree (ResolveContext ec, TypeSpec delegate_type)
                {
                        return CreateExpressionTree (ec);
                }
@@ -1134,9 +1060,9 @@ namespace Mono.CSharp {
                        return null;
                }
 
-               protected virtual ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, Type delegate_type)
+               protected virtual ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
                {
-                       AParametersCollection delegate_parameters = TypeManager.GetDelegateParameters (ec, delegate_type);
+                       var delegate_parameters = Delegate.GetParameters (ec.Compiler, delegate_type);
 
                        if (Parameters == ParametersCompiled.Undefined) {
                                //
@@ -1218,7 +1144,7 @@ namespace Mono.CSharp {
                        return ExprClassName;
                }
 
-               AnonymousMethodBody CompatibleMethodBody (ResolveContext ec, TypeInferenceContext tic, Type return_type, Type delegate_type)
+               AnonymousMethodBody CompatibleMethodBody (ResolveContext ec, TypeInferenceContext tic, TypeSpec return_type, TypeSpec delegate_type)
                {
                        ParametersCompiled p = ResolveParameters (ec, tic, delegate_type);
                        if (p == null)
@@ -1230,7 +1156,7 @@ namespace Mono.CSharp {
 
                }
 
-               protected virtual AnonymousMethodBody CompatibleMethodFactory (Type return_type, Type delegate_type, ParametersCompiled p, ToplevelBlock b)
+               protected virtual AnonymousMethodBody CompatibleMethodFactory (TypeSpec return_type, TypeSpec delegate_type, ParametersCompiled p, ToplevelBlock b)
                {
                        return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
                }
@@ -1281,22 +1207,24 @@ namespace Mono.CSharp {
                                return ec;
                        }
 
+                       protected override void DefineTypeParameters ()
+                       {
+                               // Type parameters were cloned
+                       }
+
                        protected override bool ResolveMemberType ()
                        {
                                if (!base.ResolveMemberType ())
                                        return false;
 
-                               if (Storey != null && Storey.IsGeneric) {
-                                       AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
-                                       if (gstorey != null) {
-                                               if (!Parameters.IsEmpty) {
-                                                       Type [] ptypes = Parameters.Types;
-                                                       for (int i = 0; i < ptypes.Length; ++i)
-                                                               ptypes [i] = gstorey.MutateType (ptypes [i]);
-                                               }
-
-                                               member_type = gstorey.MutateType (member_type);
+                               if (Storey != null && Storey.Mutator != null) {
+                                       if (!parameters.IsEmpty) {
+                                               var mutated = Storey.Mutator.Mutate (parameters.Types);
+                                               if (mutated != parameters.Types)
+                                                       parameters = ParametersCompiled.CreateFullyResolved ((Parameter[]) parameters.FixedParameters, mutated);
                                        }
+
+                                       member_type = Storey.Mutator.Mutate (member_type);
                                }
 
                                return true;
@@ -1304,17 +1232,6 @@ namespace Mono.CSharp {
 
                        public override void Emit ()
                        {
-                               //
-                               // Before emitting any code we have to change all MVAR references to VAR
-                               // when the method is of generic type and has hoisted variables
-                               //
-                               if (Storey == Parent && Storey.IsGeneric) {
-                                       AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
-                                       if (gstorey != null) {
-                                               block.MutateHoistedGenericType (gstorey);
-                                       }
-                               }
-
                                if (MethodBuilder == null) {
                                        Define ();
                                }
@@ -1330,11 +1247,11 @@ namespace Mono.CSharp {
 
                readonly ToplevelBlock block;
 
-               public Type ReturnType;
+               public TypeSpec ReturnType;
 
                object return_label;
 
-               protected AnonymousExpression (ToplevelBlock block, Type return_type, Location loc)
+               protected AnonymousExpression (ToplevelBlock block, TypeSpec return_type, Location loc)
                {
                        this.ReturnType = return_type;
                        this.block = block;
@@ -1436,7 +1353,7 @@ namespace Mono.CSharp {
                static int unique_id;
 
                public AnonymousMethodBody (ParametersCompiled parameters,
-                                       ToplevelBlock block, Type return_type, Type delegate_type,
+                                       ToplevelBlock block, TypeSpec return_type, TypeSpec delegate_type,
                                        Location loc)
                        : base (block, return_type, loc)
                {
@@ -1499,7 +1416,7 @@ namespace Mono.CSharp {
                                modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
                        }
 
-                       TypeContainer parent = storey != null ? storey : ec.CurrentTypeDefinition;
+                       TypeContainer parent = storey != null ? storey : ec.CurrentTypeDefinition.Parent.PartialContainer;
 
                        MemberCore mc = ec.MemberContext as MemberCore;
                        string name = CompilerGeneratedClass.MakeName (parent != storey ? block_name : null,
@@ -1510,15 +1427,14 @@ namespace Mono.CSharp {
                        if (storey == null && mc.MemberName.TypeArguments != null) {
                                member_name = new MemberName (name, mc.MemberName.TypeArguments.Clone (), Location);
 
-                               generic_method = new GenericMethod (parent.NamespaceEntry, parent, member_name,
-                                       new TypeExpression (ReturnType, Location), parameters);
-
-                               var list = new List<Constraints> ();
-                               foreach (TypeParameter tparam in ec.CurrentTypeParameters) {
-                                       if (tparam.Constraints != null)
-                                               list.Add (tparam.Constraints.Clone ());
+                               var hoisted_tparams = ec.CurrentTypeParameters;
+                               var type_params = new TypeParameter[hoisted_tparams.Length];
+                               for (int i = 0; i < type_params.Length; ++i) {
+                                       type_params[i] = hoisted_tparams[i].CreateHoistedCopy (null);
                                }
-                               generic_method.SetParameterInfo (list);
+
+                               generic_method = new GenericMethod (parent.NamespaceEntry, parent, member_name, type_params,
+                                       new TypeExpression (ReturnType, Location), parameters);
                        } else {
                                member_name = new MemberName (name, Location);
                                generic_method = null;
@@ -1592,12 +1508,11 @@ namespace Mono.CSharp {
                                }
                        }
 
-                       ILGenerator ig = ec.ig;
-                       Label l_initialized = ig.DefineLabel ();
+                       Label l_initialized = ec.DefineLabel ();
 
                        if (am_cache != null) {
-                               ig.Emit (OpCodes.Ldsfld, am_cache.Spec.MetaInfo);
-                               ig.Emit (OpCodes.Brtrue_S, l_initialized);
+                               ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
+                               ec.Emit (OpCodes.Brtrue_S, l_initialized);
                        }
 
                        //
@@ -1605,45 +1520,41 @@ namespace Mono.CSharp {
                        //
 
                        if (is_static) {
-                               ig.Emit (OpCodes.Ldnull);
+                               ec.Emit (OpCodes.Ldnull);
                        } else if (storey != null) {
                                Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (new ResolveContext (ec.MemberContext));
                                if (e != null)
                                        e.Emit (ec);
                        } else {
-                               ig.Emit (OpCodes.Ldarg_0);
+                               ec.Emit (OpCodes.Ldarg_0);
                        }
 
-                       MethodInfo delegate_method = method.MethodBuilder;
+                       var delegate_method = method.Spec;
                        if (storey != null && storey.MemberName.IsGeneric) {
-                               Type t = storey.Instance.Type;
-                               
+                               TypeSpec t = storey.Instance.Type;
+
                                //
                                // Mutate anonymous method instance type if we are in nested
                                // hoisted generic anonymous method storey
                                //
                                if (ec.CurrentAnonymousMethod != null &&
                                        ec.CurrentAnonymousMethod.Storey != null &&
-                                       ec.CurrentAnonymousMethod.Storey.IsGeneric) {
-                                       t = storey.GetGenericStorey ().MutateType (t);
+                                       ec.CurrentAnonymousMethod.Storey.Mutator != null) {
+                                       t = storey.Mutator.Mutate (t);
                                }
 
-                               delegate_method = TypeBuilder.GetMethod (t, delegate_method);
+                               ec.Emit (OpCodes.Ldftn, TypeBuilder.GetMethod (t.GetMetaInfo (), (MethodInfo) delegate_method.GetMetaInfo ()));
+                       } else {
+                               ec.Emit (OpCodes.Ldftn, delegate_method);
                        }
 
-                       ig.Emit (OpCodes.Ldftn, delegate_method);
-
                        var constructor_method = Delegate.GetConstructor (ec.MemberContext.Compiler, ec.CurrentType, type);
-#if MS_COMPATIBLE
-//            if (type.IsGenericType && type is TypeBuilder)
-//                constructor_method = TypeBuilder.GetConstructor (type, constructor_method);
-#endif
-                       ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method.MetaInfo);
+                       ec.Emit (OpCodes.Newobj, constructor_method);
 
                        if (am_cache != null) {
-                               ig.Emit (OpCodes.Stsfld, am_cache.Spec.MetaInfo);
-                               ig.MarkLabel (l_initialized);
-                               ig.Emit (OpCodes.Ldsfld, am_cache.Spec.MetaInfo);
+                               ec.Emit (OpCodes.Stsfld, am_cache.Spec);
+                               ec.MarkLabel (l_initialized);
+                               ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
                        }
                }
 
@@ -1669,11 +1580,6 @@ namespace Mono.CSharp {
                        return TypeManager.CSharpName (type);
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       type = storey.MutateType (type);
-               }
-
                public static void Reset ()
                {
                        unique_id = 0;
@@ -1738,7 +1644,7 @@ namespace Mono.CSharp {
 
                        Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
                                null, new AnonymousParameters (ctx, ctor_params), null, loc);
-                       c.Block = new ToplevelBlock (ctx, c.Parameters, loc);
+                       c.Block = new ToplevelBlock (ctx, c.ParameterInfo, loc);
 
                        // 
                        // Create fields and contructor body with field initialization
@@ -1808,12 +1714,17 @@ namespace Mono.CSharp {
                                Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
                                Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
 
-                       ToplevelBlock equals_block = new ToplevelBlock (Compiler, equals.Parameters, loc);
+                       ToplevelBlock equals_block = new ToplevelBlock (Compiler, equals.ParameterInfo, loc);
                        TypeExpr current_type;
-                       if (IsGeneric)
-                               current_type = new GenericTypeExpr (this, loc);
-                       else
-                               current_type = new TypeExpression (TypeBuilder, loc);
+                       if (type_params != null) {
+                               var targs = new TypeArguments ();
+                               foreach (var type_param in type_params)
+                                       targs.Add (new TypeParameterExpr (type_param, type_param.Location));
+
+                               current_type = new GenericTypeExpr (Definition, targs, loc);
+                       } else {
+                               current_type = new TypeExpression (Definition, loc);
+                       }
 
                        equals_block.AddVariable (current_type, "other", loc);
                        LocalVariableReference other_variable = new LocalVariableReference (equals_block, "other", loc);
@@ -1825,12 +1736,12 @@ namespace Mono.CSharp {
                        Expression string_concat = new StringConstant ("{", loc);
                        Expression rs_hashcode = new IntConstant (-2128831035, loc);
                        for (int i = 0; i < parameters.Count; ++i) {
-                               AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
-                               Field f = (Field) Fields [i];
+                               var p = parameters [i];
+                               var f = Fields [i];
 
                                MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
                                        system_collections_generic, "EqualityComparer",
-                                               new TypeArguments (new SimpleName (TypeParameters [i].Name, loc)), loc),
+                                               new TypeArguments (new SimpleName (CurrentTypeParameters [i].Name, loc)), loc),
                                                "Default", loc);
 
                                Arguments arguments_equal = new Arguments (2);
index 9d6247deb7dbf4003d0fae3379bbfd4e60f2b327..79dc4417ddc37496f15f188c55df4343b78fdc9f 100644 (file)
@@ -47,7 +47,7 @@ namespace Mono.CSharp
                        this.Expr = expr;
                }
 
-               public Type Type {
+               public TypeSpec Type {
                        get { return Expr.Type; }
                }
 
@@ -187,7 +187,7 @@ namespace Mono.CSharp
                        if (IsByRef) {
                                var ml = (IMemoryLocation) Expr;
                                ml.AddressOf (ec, AddressOp.Load);
-                               type = TypeManager.GetReferenceType (type);
+                               type = ReferenceContainer.MakeType (type);
                        } else {
                                Expr.Emit (ec);
                        }
@@ -254,7 +254,7 @@ namespace Mono.CSharp
 
                                var arg_type = a.Expr.Type;
 
-                               if (!TypeManager.IsDynamicType (arg_type)) {
+                               if (arg_type != InternalType.Dynamic) {
                                        MethodGroupExpr mg = a.Expr as MethodGroupExpr;
                                        if (mg != null) {
                                                rc.Report.Error (1976, a.Expr.Location,
@@ -366,7 +366,7 @@ namespace Mono.CSharp
                        foreach (Argument a in args) {
                                a.Emit (ec);
                                if (dup_args) {
-                                       ec.ig.Emit (OpCodes.Dup);
+                                       ec.Emit (OpCodes.Dup);
                                        (temps [i++] = new LocalTemporary (a.Type)).Store (ec);
                                }
                        }
@@ -382,18 +382,6 @@ namespace Mono.CSharp
                        }
                }
 
-               public bool GetAttributableValue (ResolveContext ec, out object[] values)
-               {
-                       values = new object [args.Count];
-                       for (int j = 0; j < values.Length; ++j) {
-                               Argument a = this [j];
-                               if (!a.Expr.GetAttributableValue (ec, a.Type, out values[j]))
-                                       return false;
-                       }
-
-                       return true;
-               }
-
                public IEnumerator<Argument> GetEnumerator ()
                {
                        return args.GetEnumerator ();
@@ -405,7 +393,7 @@ namespace Mono.CSharp
                public bool HasDynamic {
                        get {
                                foreach (Argument a in args) {
-                                       if (TypeManager.IsDynamicType (a.Type))
+                                       if (a.Type == InternalType.Dynamic)
                                                return true;
                                }
                                
@@ -454,16 +442,10 @@ namespace Mono.CSharp
                        dynamic = false;
                        foreach (Argument a in args) {
                                a.Resolve (ec);
-                               dynamic |= TypeManager.IsDynamicType (a.Type);
+                               dynamic |= a.Type == InternalType.Dynamic;
                        }
                }
 
-               public void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       foreach (Argument a in args)
-                               a.Expr.MutateHoistedGenericType (storey);
-               }
-
                public void RemoveAt (int index)
                {
                        args.RemoveAt (index);
index 2022af1d14ef5f1fc5b63934251b7b76273a23bf..befc203eda07436a95ca558573f261297f1a9c38 100644 (file)
@@ -179,13 +179,13 @@ namespace Mono.CSharp {
        public class LocalTemporary : Expression, IMemoryLocation, IAssignMethod {
                LocalBuilder builder;
 
-               public LocalTemporary (Type t)
+               public LocalTemporary (TypeSpec t)
                {
                        type = t;
                        eclass = ExprClass.Value;
                }
 
-               public LocalTemporary (LocalBuilder b, Type t)
+               public LocalTemporary (LocalBuilder b, TypeSpec t)
                        : this (t)
                {
                        builder = b;
@@ -216,12 +216,10 @@ namespace Mono.CSharp {
 
                public override void Emit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-
                        if (builder == null)
                                throw new InternalErrorException ("Emit without Store, or after Release");
 
-                       ig.Emit (OpCodes.Ldloc, builder);
+                       ec.Emit (OpCodes.Ldloc, builder);
                }
 
                #region IAssignMethod Members
@@ -255,11 +253,10 @@ namespace Mono.CSharp {
 
                public void Store (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
                        if (builder == null)
                                builder = ec.GetTemporaryLocal (type);
 
-                       ig.Emit (OpCodes.Stloc, builder);
+                       ec.Emit (OpCodes.Stloc, builder);
                }
 
                public void AddressOf (EmitContext ec, AddressOp mode)
@@ -267,23 +264,16 @@ namespace Mono.CSharp {
                        if (builder == null)
                                builder = ec.GetTemporaryLocal (type);
 
-                       ILGenerator ig = ec.ig;
-
                        if (builder.LocalType.IsByRef) {
                                //
                                // if is_address, than this is just the address anyways,
                                // so we just return this.
                                //
-                               ig.Emit (OpCodes.Ldloc, builder);
+                               ec.Emit (OpCodes.Ldloc, builder);
                        } else {
-                               ig.Emit (OpCodes.Ldloca, builder);
+                               ec.Emit (OpCodes.Ldloca, builder);
                        }
                }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       type = storey.MutateType (type);
-               }
        }
 
        /// <summary>
@@ -329,8 +319,8 @@ namespace Mono.CSharp {
                        if (target == null || !ok)
                                return null;
 
-                       Type target_type = target.Type;
-                       Type source_type = source.Type;
+                       TypeSpec target_type = target.Type;
+                       TypeSpec source_type = source.Type;
 
                        eclass = ExprClass.Value;
                        type = target_type;
@@ -378,14 +368,6 @@ namespace Mono.CSharp {
                        return System.Linq.Expressions.Expression.Assign (target_object, source_object);
                }
 #endif
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       source.MutateHoistedGenericType (storey);
-                       target.MutateHoistedGenericType (storey);
-                       type = storey.MutateType (type);                        
-               }
-
                protected virtual Expression ResolveConversions (ResolveContext ec)
                {
                        source = Convert.ImplicitConversionRequired (ec, source, target.Type, loc);
@@ -693,7 +675,7 @@ namespace Mono.CSharp {
 
                protected override Expression ResolveConversions (ResolveContext ec)
                {
-                       Type target_type = target.Type;
+                       TypeSpec target_type = target.Type;
 
                        //
                        // 1. the return type is implicitly convertible to the type of target
@@ -721,7 +703,7 @@ namespace Mono.CSharp {
                                }
                        }
 
-                       if (TypeManager.IsDynamicType (source.Type)) {
+                       if (source.Type == InternalType.Dynamic) {
                                Arguments arg = new Arguments (1);
                                arg.Add (new Argument (source));
                                return new SimpleAssign (target, new DynamicConversion (target_type, CSharpBinderFlags.ConvertExplicit, arg, loc), loc).Resolve (ec);
index caaad5513bbc523c2d85925cb0c82a09cd5471b4..caef628d329e2f668297c2ba00481ab40fd7d2d9 100644 (file)
@@ -58,7 +58,7 @@ namespace Mono.CSharp {
                /// <summary>
                /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
                /// </summary>
-               public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa);
+               public abstract void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa);
 
                /// <summary>
                /// Returns one AttributeTarget for this element.
@@ -84,6 +84,7 @@ namespace Mono.CSharp {
                Arguments NamedArguments;
 
                bool resolve_error;
+               bool arg_resolved;
                readonly bool nameEscaped;
 
                //
@@ -97,20 +98,14 @@ namespace Mono.CSharp {
                //
                IMemberContext context;
 
-               static readonly AttributeUsageAttribute DefaultUsageAttribute = new AttributeUsageAttribute (AttributeTargets.All);
+               public static readonly AttributeUsageAttribute DefaultUsageAttribute = new AttributeUsageAttribute (AttributeTargets.All);
                static Assembly orig_sec_assembly;
                public static readonly object[] EmptyObject = new object [0];
 
-               // non-null if named args present after Resolve () is called
-               PropertyInfo [] prop_info_arr;
-               FieldInfo [] field_info_arr;
-               object [] field_values_arr;
-               object [] prop_values_arr;
-               object [] pos_values;
+               IList<KeyValuePair<MemberExpr, NamedArgument>> named_values;
 
-               static Dictionary<Type, AttributeUsageAttribute> usage_attr_cache;
                // Cache for parameter-less attributes
-               static Dictionary<Type, CustomAttributeBuilder> att_cache;
+               static Dictionary<TypeSpec, MethodSpec> att_cache;
 
                public Attribute (string target, ATypeNameExpression expr, Arguments[] args, Location loc, bool nameEscaped)
                {
@@ -139,8 +134,7 @@ namespace Mono.CSharp {
 
                public static void Reset ()
                {
-                       usage_attr_cache = new Dictionary<Type, AttributeUsageAttribute> (ReferenceEquality<Type>.Default);
-                       att_cache = new Dictionary<Type, CustomAttributeBuilder> (ReferenceEquality<Type>.Default);
+                       att_cache = new Dictionary<TypeSpec, MethodSpec> ();
                }
 
                //
@@ -184,9 +178,9 @@ namespace Mono.CSharp {
                                name.Name);
                }
 
-               public static void Error_AttributeArgumentNotValid (ResolveContext rc, Location loc)
+               public static void Error_AttributeArgumentNotValid (IMemberContext rc, Location loc)
                {
-                       rc.Report.Error (182, loc,
+                       rc.Compiler.Report.Error (182, loc,
                                      "An attribute argument must be a constant expression, typeof " +
                                      "expression or array creation expression");
                }
@@ -232,14 +226,14 @@ namespace Mono.CSharp {
                        return expr.ResolveAsTypeTerminal (ec, false);
                }
 
-               Type ResolvePossibleAttributeType (ATypeNameExpression expr, ref bool is_attr)
+               TypeSpec ResolvePossibleAttributeType (ATypeNameExpression expr, ref bool is_attr)
                {
                        TypeExpr te = ResolveAsTypeTerminal (expr, context);
                        if (te == null)
                                return null;
 
-                       Type t = te.Type;
-                       if (TypeManager.IsSubclassOf (t, TypeManager.attribute_type)) {
+                       TypeSpec t = te.Type;
+                       if (t.IsAttribute) {
                                is_attr = true;
                        } else {
                                Report.SymbolRelatedToPreviousError (t);
@@ -258,7 +252,7 @@ namespace Mono.CSharp {
 
                        bool t1_is_attr = false;
                        bool t2_is_attr = false;
-                       Type t1, t2;
+                       TypeSpec t1, t2;
                        ATypeNameExpression expanded = null;
 
                        try {
@@ -299,7 +293,7 @@ namespace Mono.CSharp {
                        resolve_error = true;
                }
 
-               public virtual Type ResolveType ()
+               public virtual TypeSpec ResolveType ()
                {
                        if (Type == null && !resolve_error)
                                ResolveAttributeType ();
@@ -326,7 +320,7 @@ namespace Mono.CSharp {
                        return HasSecurityAttribute && IsSecurityActionValid (false);
                }
 
-               static bool IsValidArgumentType (Type t)
+               static bool IsValidArgumentType (TypeSpec t)
                {
                        if (t.IsArray)
                                t = TypeManager.GetElementType (t);
@@ -360,21 +354,23 @@ namespace Mono.CSharp {
                                                return;
                                }
                        }
-                       
+
+                       var char_set = Import.ImportType (typeof (CharSet));
                        NamedArguments.Add (new NamedArgument (CharSetEnumMember, loc,
-                               Constant.CreateConstant (rc, typeof (CharSet), RootContext.ToplevelTypes.DefaultCharSet, Location)));
+                               Constant.CreateConstant (rc, char_set, RootContext.ToplevelTypes.DefaultCharSet, Location)));
                }
 
                public Report Report {
                        get { return context.Compiler.Report; }
                }
 
-               public CustomAttributeBuilder Resolve ()
+               public MethodSpec Resolve ()
                {
                        if (resolve_error)
                                return null;
 
                        resolve_error = true;
+                       arg_resolved = true;
 
                        if (Type == null) {
                                ResolveAttributeType ();
@@ -387,63 +383,34 @@ namespace Mono.CSharp {
                                return null;
                        }
 
-                       ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (Type);
+                       ObsoleteAttribute obsolete_attr = Type.GetAttributeObsolete ();
                        if (obsolete_attr != null) {
                                AttributeTester.Report_ObsoleteMessage (obsolete_attr, TypeManager.CSharpName (Type), Location, Report);
                        }
 
-                       CustomAttributeBuilder cb;
+                       MethodSpec ctor;
+                       // Try if the attribute is simple has been resolved before
                        if (PosArguments == null && NamedArguments == null) {
-                               if (att_cache.TryGetValue (Type, out cb)) {
+                               if (att_cache.TryGetValue (Type, out ctor)) {
                                        resolve_error = false;
-                                       return cb;
+                                       return ctor;
                                }
                        }
 
                        ResolveContext rc = new ResolveContext (context, ResolveContext.Options.ConstantScope);
-                       var ctor = ResolveConstructor (rc);
+                       ctor = ResolveConstructor (rc);
                        if (ctor == null) {
-                               if (Type is TypeBuilder && 
-                                   TypeManager.LookupDeclSpace (Type).MemberCache == null)
-                                       // The attribute type has been DefineType'd, but not Defined.  Let's not treat it as an error.
-                                       // It'll be resolved again when the attached-to entity is emitted.
-                                       resolve_error = false;
                                return null;
                        }
 
                        ApplyModuleCharSet (rc);
 
-                       try {
-                               var ctor_meta = (ConstructorInfo) ctor.MetaInfo;
-                               // SRE does not allow private ctor but we want to report all source code errors
-                               if (ctor.MetaInfo.IsPrivate)
-                                       return null;
-
-                               if (NamedArguments == null) {
-                                       cb = new CustomAttributeBuilder (ctor_meta, pos_values);
-
-                                       if (pos_values.Length == 0)
-                                               att_cache.Add (Type, cb);
-
-                                       resolve_error = false;
-                                       return cb;
-                               }
-
-                               if (!ResolveNamedArguments (rc)) {
-                                       return null;
-                               }
-
-                               cb = new CustomAttributeBuilder (ctor_meta, pos_values,
-                                               prop_info_arr, prop_values_arr,
-                                               field_info_arr, field_values_arr);
-
-                               resolve_error = false;
-                               return cb;
-                       }
-                       catch (Exception) {
-                               Error_AttributeArgumentNotValid (rc, Location);
+                       if (NamedArguments != null && !ResolveNamedArguments (rc)) {
                                return null;
                        }
+
+                       resolve_error = false;
+                       return ctor;
                }
 
                protected virtual MethodSpec ResolveConstructor (ResolveContext ec)
@@ -458,8 +425,8 @@ namespace Mono.CSharp {
                        }
 
                        MethodGroupExpr mg = MemberLookupFinal (ec, ec.CurrentType,
-                               Type, ConstructorInfo.ConstructorName, MemberTypes.Constructor,
-                               BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
+                               Type, ConstructorInfo.ConstructorName, 0, MemberKind.Constructor,
+                               BindingRestriction.AccessibleOnly | BindingRestriction.DeclaredOnly,
                                Location) as MethodGroupExpr;
 
                        if (mg == null)
@@ -470,61 +437,15 @@ namespace Mono.CSharp {
                                return null;
                        
                        var constructor = (MethodSpec) mg;
-                       if (PosArguments == null) {
-                               pos_values = EmptyObject;
-                               return constructor;
-                       }
-
-                       if (!PosArguments.GetAttributableValue (ec, out pos_values))
-                               return null;
-
-                       // Here we do the checks which should be done by corlib or by runtime.
-                       // However Zoltan doesn't like it and every Mono compiler has to do it again.
-                       PredefinedAttributes pa = PredefinedAttributes.Get;
-                       if (Type == pa.Guid) {
-                               try {
-                                       new Guid ((string)pos_values [0]);
-                               }
-                               catch (Exception e) {
-                                       Error_AttributeEmitError (e.Message);
-                                       return null;
-                               }
-                       }
-
-                       if (Type == pa.AttributeUsage && (int)pos_values [0] == 0) {
-                               ec.Report.Error (591, Location, "Invalid value for argument to `System.AttributeUsage' attribute");
-                               return null;
-                       }
-
-                       if (Type == pa.IndexerName || Type == pa.Conditional) {
-                               string v = pos_values [0] as string;
-                               if (!Tokenizer.IsValidIdentifier (v) || Tokenizer.IsKeyword (v)) {
-                                       ec.Report.Error (633, PosArguments [0].Expr.Location,
-                                               "The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
-                                       return null;
-                               }
-                       }
-
-                       if (Type == pa.MethodImpl && pos_values.Length == 1 &&
-                               constructor.Parameters.Types [0] == TypeManager.short_type &&
-                               !System.Enum.IsDefined (typeof (MethodImplOptions), pos_values [0].ToString ())) {
-                               Error_AttributeEmitError ("Incorrect argument value.");
-                               return null;
-                       }
-
                        return constructor;
                }
 
                protected virtual bool ResolveNamedArguments (ResolveContext ec)
                {
                        int named_arg_count = NamedArguments.Count;
-
-                       var field_infos = new List<FieldInfo> (named_arg_count);
-                       var prop_infos  = new List<PropertyInfo> (named_arg_count);
-                       var field_values = new List<object> (named_arg_count);
-                       var prop_values = new List<object> (named_arg_count);
-
                        var seen_names = new List<string> (named_arg_count);
+
+                       named_values = new List<KeyValuePair<MemberExpr, NamedArgument>> (named_arg_count);
                        
                        foreach (NamedArgument a in NamedArguments) {
                                string name = a.Name;
@@ -538,14 +459,14 @@ namespace Mono.CSharp {
                                a.Resolve (ec);
 
                                Expression member = Expression.MemberLookup (ec.Compiler,
-                                       ec.CurrentType, Type, name,
-                                       MemberTypes.All,
-                                       BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static,
+                                       ec.CurrentType, Type, name, 0,
+                                       MemberKind.All,
+                                       BindingRestriction.AccessibleOnly,
                                        Location);
 
                                if (member == null) {
-                                       member = Expression.MemberLookup (ec.Compiler, ec.CurrentType, Type, name,
-                                               MemberTypes.All, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
+                                       member = Expression.MemberLookup (ec.Compiler, ec.CurrentType, Type, name, 0,
+                                               MemberKind.All, BindingRestriction.None,
                                                Location);
 
                                        if (member != null) {
@@ -568,9 +489,9 @@ namespace Mono.CSharp {
                                ObsoleteAttribute obsolete_attr;
 
                                if (member is PropertyExpr) {
-                                       PropertyInfo pi = ((PropertyExpr) member).PropertyInfo;
+                                       var pi = ((PropertyExpr) member).PropertyInfo;
 
-                                       if (!pi.CanWrite || !pi.CanRead || pi.GetGetMethod ().IsStatic) {
+                                       if (!pi.HasSet || !pi.HasGet || pi.IsStatic) {
                                                ec.Report.SymbolRelatedToPreviousError (pi);
                                                Error_InvalidNamedArgument (ec, a);
                                                return false;
@@ -582,19 +503,7 @@ namespace Mono.CSharp {
                                                return false;
                                        }
 
-                                       object value;
-                                       if (!a.Expr.GetAttributableValue (ec, member.Type, out value))
-                                               return false;
-
-                                       PropertyBase pb = TypeManager.GetProperty (pi);
-                                       if (pb != null)
-                                               obsolete_attr = pb.GetObsoleteAttribute ();
-                                       else
-                                               obsolete_attr = AttributeTester.GetMemberObsoleteAttribute (pi);
-
-                                       prop_values.Add (value);
-                                       prop_infos.Add (pi);
-                                       
+                                       obsolete_attr = pi.GetAttributeObsolete ();
                                } else {
                                        var fi = ((FieldExpr) member).Spec;
 
@@ -604,39 +513,24 @@ namespace Mono.CSharp {
                                        }
 
                                        if (!IsValidArgumentType (member.Type)) {
-                                               ec.Report.SymbolRelatedToPreviousError (fi.MetaInfo);
+                                               ec.Report.SymbolRelatedToPreviousError (fi);
                                                Error_InvalidNamedArgumentType (ec, a);
                                                return false;
                                        }
 
-                                       object value;
-                                       if (!a.Expr.GetAttributableValue (ec, member.Type, out value))
-                                               return false;
-
-                                       FieldBase fb = TypeManager.GetField (fi.MetaInfo);
-                                       if (fb != null)
-                                               obsolete_attr = fb.GetObsoleteAttribute ();
-                                       else
-                                               obsolete_attr = AttributeTester.GetMemberObsoleteAttribute (fi.MetaInfo);
-
-                                       field_values.Add (value);
-                                       field_infos.Add (fi.MetaInfo);
+                                       obsolete_attr = fi.GetAttributeObsolete ();
                                }
 
                                if (obsolete_attr != null && !context.IsObsolete)
                                        AttributeTester.Report_ObsoleteMessage (obsolete_attr, member.GetSignatureForError (), member.Location, Report);
-                       }
-
-                       prop_info_arr = new PropertyInfo [prop_infos.Count];
-                       field_info_arr = new FieldInfo [field_infos.Count];
-                       field_values_arr = new object [field_values.Count];
-                       prop_values_arr = new object [prop_values.Count];
 
-                       field_infos.CopyTo  (field_info_arr, 0);
-                       field_values.CopyTo (field_values_arr, 0);
+                               if (a.Type != member.Type) {
+                                       a.Expr = Convert.ImplicitConversionRequired (ec, a.Expr, member.Type, a.Expr.Location);
+                               }
 
-                       prop_values.CopyTo  (prop_values_arr, 0);
-                       prop_infos.CopyTo   (prop_info_arr, 0);
+                               if (a.Expr != null)
+                                       named_values.Add (new KeyValuePair<MemberExpr, NamedArgument> ((MemberExpr) member, a));
+                       }
 
                        return true;
                }
@@ -647,7 +541,7 @@ namespace Mono.CSharp {
                public string GetValidTargets ()
                {
                        StringBuilder sb = new StringBuilder ();
-                       AttributeTargets targets = GetAttributeUsage (Type).ValidOn;
+                       AttributeTargets targets = Type.GetAttributeUsage (PredefinedAttributes.Get.AttributeUsage).ValidOn;
 
                        if ((targets & AttributeTargets.Assembly) != 0)
                                sb.Append ("assembly, ");
@@ -697,48 +591,9 @@ namespace Mono.CSharp {
                        return sb.Remove (sb.Length - 2, 2).ToString ();
                }
 
-               /// <summary>
-               /// Returns AttributeUsage attribute based on types hierarchy
-               /// </summary>
-               static AttributeUsageAttribute GetAttributeUsage (Type type)
-               {
-                       AttributeUsageAttribute ua;
-                       if (usage_attr_cache.TryGetValue (type, out ua))
-                               return ua;
-
-                       Class attr_class = TypeManager.LookupClass (type);
-                       PredefinedAttribute pa = PredefinedAttributes.Get.AttributeUsage;
-
-                       if (attr_class == null) {
-                               if (!pa.IsDefined)
-                                       return new AttributeUsageAttribute (0);
-
-                               object[] usage_attr = type.GetCustomAttributes (pa.Type, true);
-                               ua = (AttributeUsageAttribute)usage_attr [0];
-                               usage_attr_cache.Add (type, ua);
-                               return ua;
-                       }
-
-                       Attribute a = null;
-                       if (attr_class.OptAttributes != null)
-                               a = attr_class.OptAttributes.Search (pa);
-
-                       if (a == null) {
-                               if (attr_class.TypeBuilder.BaseType != TypeManager.attribute_type)
-                                       ua = GetAttributeUsage (attr_class.TypeBuilder.BaseType);
-                               else
-                                       ua = DefaultUsageAttribute;
-                       } else {
-                               ua = a.GetAttributeUsageAttribute ();
-                       }
-
-                       usage_attr_cache.Add (type, ua);
-                       return ua;
-               }
-
-               AttributeUsageAttribute GetAttributeUsageAttribute ()
+               public AttributeUsageAttribute GetAttributeUsageAttribute ()
                {
-                       if (pos_values == null)
+                       if (!arg_resolved)
                                // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
                                // But because a lot of attribute class code must be rewritten will be better to wait...
                                Resolve ();
@@ -746,15 +601,15 @@ namespace Mono.CSharp {
                        if (resolve_error)
                                return DefaultUsageAttribute;
 
-                       AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
+                       AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)((Constant) PosArguments [0].Expr).GetValue ());
 
-                       object field = GetPropertyValue ("AllowMultiple");
+                       var field = GetPropertyValue ("AllowMultiple") as BoolConstant;
                        if (field != null)
-                               usage_attribute.AllowMultiple = (bool)field;
+                               usage_attribute.AllowMultiple = field.Value;
 
-                       field = GetPropertyValue ("Inherited");
+                       field = GetPropertyValue ("Inherited") as BoolConstant;
                        if (field != null)
-                               usage_attribute.Inherited = (bool)field;
+                               usage_attribute.Inherited = field.Value;
 
                        return usage_attribute;
                }
@@ -764,7 +619,7 @@ namespace Mono.CSharp {
                /// </summary>
                public string GetIndexerAttributeValue ()
                {
-                       if (pos_values == null)
+                       if (!arg_resolved)
                                // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
                                // But because a lot of attribute class code must be rewritten will be better to wait...
                                Resolve ();
@@ -772,7 +627,7 @@ namespace Mono.CSharp {
                        if (resolve_error)
                                return null;
 
-                       return pos_values [0] as string;
+                       return ((Constant) PosArguments [0].Expr).GetValue () as string;
                }
 
                /// <summary>
@@ -780,7 +635,7 @@ namespace Mono.CSharp {
                /// </summary>
                public string GetConditionalAttributeValue ()
                {
-                       if (pos_values == null)
+                       if (!arg_resolved)
                                // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
                                // But because a lot of attribute class code must be rewritten will be better to wait...
                                Resolve ();
@@ -788,7 +643,7 @@ namespace Mono.CSharp {
                        if (resolve_error)
                                return null;
 
-                       return (string)pos_values [0];
+                       return ((Constant) PosArguments[0].Expr).GetValue () as string;
                }
 
                /// <summary>
@@ -796,7 +651,7 @@ namespace Mono.CSharp {
                /// </summary>
                public ObsoleteAttribute GetObsoleteAttribute ()
                {
-                       if (pos_values == null)
+                       if (!arg_resolved)
                                // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
                                // But because a lot of attribute class code must be rewritten will be better to wait...
                                Resolve ();
@@ -804,13 +659,14 @@ namespace Mono.CSharp {
                        if (resolve_error)
                                return null;
 
-                       if (pos_values == null || pos_values.Length == 0)
+                       if (PosArguments == null)
                                return new ObsoleteAttribute ();
 
-                       if (pos_values.Length == 1)
-                               return new ObsoleteAttribute ((string)pos_values [0]);
+                       string msg = ((Constant) PosArguments[0].Expr).GetValue () as string;
+                       if (PosArguments.Count == 1)
+                               return new ObsoleteAttribute (msg);
 
-                       return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
+                       return new ObsoleteAttribute (msg, ((BoolConstant) PosArguments[1].Expr).Value);
                }
 
                /// <summary>
@@ -820,7 +676,7 @@ namespace Mono.CSharp {
                /// </summary>
                public bool GetClsCompliantAttributeValue ()
                {
-                       if (pos_values == null)
+                       if (!arg_resolved)
                                // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
                                // But because a lot of attribute class code must be rewritten will be better to wait...
                                Resolve ();
@@ -828,18 +684,18 @@ namespace Mono.CSharp {
                        if (resolve_error)
                                return false;
 
-                       return (bool)pos_values [0];
+                       return ((BoolConstant) PosArguments[0].Expr).Value;
                }
 
-               public Type GetCoClassAttributeValue ()
+               public TypeSpec GetCoClassAttributeValue ()
                {
-                       if (pos_values == null)
+                       if (!arg_resolved)
                                Resolve ();
 
                        if (resolve_error)
                                return null;
 
-                       return (Type)pos_values [0];
+                       return GetArgumentType ();
                }
 
                public bool CheckTarget ()
@@ -909,7 +765,7 @@ namespace Mono.CSharp {
 
                System.Security.Permissions.SecurityAction GetSecurityActionValue ()
                {
-                       return (SecurityAction)pos_values [0];
+                       return (SecurityAction) ((Constant) PosArguments[0].Expr).GetTypedValue ();
                }
 
                /// <summary>
@@ -920,9 +776,9 @@ namespace Mono.CSharp {
                {
                        Type orig_assembly_type = null;
 
-                       if (TypeManager.LookupDeclSpace (Type) != null) {
+                       if (Type.MemberDefinition is TypeContainer) {
                                if (!RootContext.StdLib) {
-                                       orig_assembly_type = Type.GetType (Type.FullName);
+                                       orig_assembly_type = System.Type.GetType (Type.GetMetaInfo ().FullName);
                                } else {
                                        string orig_version_path = Environment.GetEnvironmentVariable ("__SECURITY_BOOTSTRAP_DB");
                                        if (orig_version_path == null) {
@@ -935,7 +791,7 @@ namespace Mono.CSharp {
                                                orig_sec_assembly = Assembly.LoadFile (file);
                                        }
 
-                                       orig_assembly_type = orig_sec_assembly.GetType (Type.FullName, true);
+                                       orig_assembly_type = orig_sec_assembly.GetType (Type.GetMetaInfo ().FullName, true);
                                        if (orig_assembly_type == null) {
                                                Report.Warning (-112, 1, Location, "Self-referenced security attribute `{0}' " +
                                                                "was not found in previous version of assembly");
@@ -945,40 +801,44 @@ namespace Mono.CSharp {
                        }
 
                        SecurityAttribute sa;
+                       object[] args;
+
                        // For all non-selfreferencing security attributes we can avoid all hacks
                        if (orig_assembly_type == null) {
-                               sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
+                               args = new object[PosArguments.Count];
+                               for (int j = 0; j < args.Length; ++j) {
+                                       args[j] = ((Constant) PosArguments[j].Expr).GetTypedValue ();
+                               }
+
+                               sa = (SecurityAttribute) Activator.CreateInstance (Type.GetMetaInfo (), args);
 
-                               if (prop_info_arr != null) {
-                                       for (int i = 0; i < prop_info_arr.Length; ++i) {
-                                               PropertyInfo pi = prop_info_arr [i];
-                                               pi.SetValue (sa, prop_values_arr [i], null);
+                               if (named_values != null) {
+                                       for (int i = 0; i < named_values.Count; ++i) {
+                                               PropertyInfo pi = ((PropertyExpr) named_values[i].Key).PropertyInfo.MetaInfo;
+                                               pi.SetValue (sa, ((Constant) named_values [i].Value.Expr).GetTypedValue (), null);
                                        }
                                }
                        } else {
                                // HACK: All security attributes have same ctor syntax
-                               sa = (SecurityAttribute) Activator.CreateInstance (orig_assembly_type, new object[] { GetSecurityActionValue () } );
+                               args = new object[] { GetSecurityActionValue () };
+                               sa = (SecurityAttribute) Activator.CreateInstance (orig_assembly_type, args);
 
                                // All types are from newly created assembly but for invocation with old one we need to convert them
-                               if (prop_info_arr != null) {
-                                       for (int i = 0; i < prop_info_arr.Length; ++i) {
-                                               PropertyInfo emited_pi = prop_info_arr [i];
+                               if (named_values != null) {
+                                       for (int i = 0; i < named_values.Count; ++i) {
+                                               PropertyInfo emited_pi = ((PropertyExpr) named_values[i].Key).PropertyInfo.MetaInfo;
                                                // FIXME: We are missing return type filter
                                                // TODO: pi can be null
                                                PropertyInfo pi = orig_assembly_type.GetProperty (emited_pi.Name);
 
-                                               object old_instance = TypeManager.IsEnumType (pi.PropertyType) ?
-                                                       System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
-                                                       prop_values_arr [i];
-
-                                               pi.SetValue (sa, old_instance, null);
+                                               pi.SetValue (sa, ((Constant) named_values[i].Value.Expr).GetTypedValue (), null);
                                        }
                                }
                        }
 
                        IPermission perm;
                        perm = sa.CreatePermission ();
-                       SecurityAction action = GetSecurityActionValue ();
+                       SecurityAction action = (SecurityAction) args [0];
 
                        // IS is correct because for corlib we are using an instance from old corlib
                        if (!(perm is System.Security.CodeAccessPermission)) {
@@ -1010,14 +870,14 @@ namespace Mono.CSharp {
                        ps.AddPermission (perm);
                }
 
-               public object GetPropertyValue (string name)
+               public Constant GetPropertyValue (string name)
                {
-                       if (prop_info_arr == null)
+                       if (named_values == null)
                                return null;
 
-                       for (int i = 0; i < prop_info_arr.Length; ++i) {
-                               if (prop_info_arr [i].Name == name)
-                                       return prop_values_arr [i];
+                       for (int i = 0; i < named_values.Count; ++i) {
+                               if (named_values [i].Value.Name == name)
+                                       return named_values [i].Value.Expr as Constant;
                        }
 
                        return null;
@@ -1128,16 +988,16 @@ namespace Mono.CSharp {
 
                public CharSet GetCharSetValue ()
                {
-                       return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
+                       return (CharSet)System.Enum.Parse (typeof (CharSet), ((Constant) PosArguments [0].Expr).GetValue ().ToString ());
                }
 
                public bool HasField (string fieldName)
                {
-                       if (field_info_arr == null)
+                       if (named_values == null)
                                return false;
 
-                       foreach (FieldInfo fi in field_info_arr) {
-                               if (fi.Name == fieldName)
+                       foreach (var na in named_values) {
+                               if (na.Value.Name == fieldName)
                                        return true;
                        }
 
@@ -1150,10 +1010,10 @@ namespace Mono.CSharp {
                                        return false;
 
                                MethodImplOptions options;
-                               if (pos_values[0].GetType () != typeof (MethodImplOptions))
-                                       options = (MethodImplOptions)System.Enum.ToObject (typeof (MethodImplOptions), pos_values[0]);
+                               if (PosArguments[0].Type.GetMetaInfo () != typeof (MethodImplOptions))
+                                       options = (MethodImplOptions) System.Enum.ToObject (typeof (MethodImplOptions), ((Constant) PosArguments[0].Expr).GetValue ());
                                else
-                                       options = (MethodImplOptions)pos_values[0];
+                                       options = (MethodImplOptions) ((Constant) PosArguments [0].Expr).GetValue ();
 
                                return (options & MethodImplOptions.InternalCall) != 0;
                        }
@@ -1161,15 +1021,21 @@ namespace Mono.CSharp {
 
                public LayoutKind GetLayoutKindValue ()
                {
-                       if (!RootContext.StdLib || pos_values [0].GetType () != typeof (LayoutKind))
-                               return (LayoutKind)System.Enum.ToObject (typeof (LayoutKind), pos_values [0]);
+                       if (!RootContext.StdLib || PosArguments[0].Type.GetMetaInfo () != typeof (LayoutKind))
+                               return (LayoutKind) System.Enum.ToObject (typeof (LayoutKind), ((Constant) PosArguments[0].Expr).GetValue ());
 
-                       return (LayoutKind)pos_values [0];
+                       return (LayoutKind) ((Constant) PosArguments[0].Expr).GetValue ();
                }
 
-               public object GetParameterDefaultValue ()
+               public Constant GetParameterDefaultValue (out TypeSpec type)
                {
-                       return pos_values [0];
+                       var expr = PosArguments[0].Expr;
+
+                       if (expr is TypeCast)
+                               expr = ((TypeCast) expr).Child;
+
+                       type = expr.Type;
+                       return expr as Constant;
                }
 
                public override bool Equals (object obj)
@@ -1191,11 +1057,11 @@ namespace Mono.CSharp {
                /// </summary>
                public void Emit (Dictionary<Attribute, List<Attribute>> allEmitted)
                {
-                       CustomAttributeBuilder cb = Resolve ();
-                       if (cb == null)
+                       var ctor = Resolve ();
+                       if (ctor == null)
                                return;
 
-                       AttributeUsageAttribute usage_attr = GetAttributeUsage (Type);
+                       AttributeUsageAttribute usage_attr = Type.GetAttributeUsage (PredefinedAttributes.Get.AttributeUsage);
                        if ((usage_attr.ValidOn & Target) == 0) {
                                Report.Error (592, Location, "The attribute `{0}' is not valid on this declaration type. " +
                                              "It is valid on `{1}' declarations only",
@@ -1205,9 +1071,71 @@ namespace Mono.CSharp {
 
                        var predefined = PredefinedAttributes.Get;
 
+                       AttributeEncoder encoder = new AttributeEncoder (false);
+
+                       if (PosArguments != null) {
+                               var param_types = ctor.Parameters.Types;
+                               for (int j = 0; j < PosArguments.Count; ++j) {
+                                       var pt = param_types[j];
+                                       if (!IsValidArgumentType (pt)) {
+                                               Error_AttributeArgumentNotValid (context, loc);
+                                               return;
+                                       }
+
+                                       var arg_expr = PosArguments[j].Expr;
+                                       if (j == 0) {
+                                               if (Type == predefined.IndexerName || Type == predefined.Conditional) {
+                                                       string v = ((StringConstant) arg_expr).Value;
+                                                       if (!Tokenizer.IsValidIdentifier (v) || Tokenizer.IsKeyword (v)) {
+                                                               context.Compiler.Report.Error (633, arg_expr.Location,
+                                                                       "The argument to the `{0}' attribute must be a valid identifier", GetSignatureForError ());
+                                                       }
+                                               } else if (Type == predefined.Guid) {
+                                                       try {
+                                                               string v = ((StringConstant) arg_expr).Value;
+                                                               new Guid (v);
+                                                       } catch (Exception e) {
+                                                               Error_AttributeEmitError (e.Message);
+                                                               return;
+                                                       }
+                                               } else if (Type == predefined.AttributeUsage) {
+                                                       int v = ((IntConstant)((EnumConstant) arg_expr).Child).Value;
+                                                       if (v == 0) {
+                                                               context.Compiler.Report.Error (591, Location, "Invalid value for argument to `{0}' attribute",
+                                                                       "System.AttributeUsage");
+                                                       }
+                                               } else if (Type == predefined.MethodImpl && pt == TypeManager.short_type &&
+                                                       !System.Enum.IsDefined (typeof (MethodImplOptions), ((Constant) arg_expr).GetValue ().ToString ())) {
+                                                       Error_AttributeEmitError ("Incorrect argument value.");
+                                                       return;
+                                               }
+                                       }
+
+                                       arg_expr.EncodeAttributeValue (context, encoder, pt);
+                               }
+                       }
+
+                       if (named_values != null) {
+                               encoder.Stream.Write ((ushort) named_values.Count);
+                               foreach (var na in named_values) {
+                                       if (na.Key is FieldExpr)
+                                               encoder.Stream.Write ((byte) 0x53);
+                                       else
+                                               encoder.Stream.Write ((byte) 0x54);
+
+                                       encoder.Encode (na.Key.Type);
+                                       encoder.Encode (na.Value.Name);
+                                       na.Value.Expr.EncodeAttributeValue (context, encoder, na.Key.Type);
+                               }
+                       } else {
+                               encoder.Stream.Write ((ushort) 0);
+                       }
+
+                       byte[] cdata = encoder.ToArray ();
+
                        try {
                                foreach (Attributable target in targets)
-                                       target.ApplyAttributeBuilder (this, cb, predefined);
+                                       target.ApplyAttributeBuilder (this, ctor, cdata, predefined);
                        } catch (Exception e) {
                                Error_AttributeEmitError (e.Message);
                                return;
@@ -1265,7 +1193,7 @@ namespace Mono.CSharp {
                        return false;
                }
 
-               public Type GetArgumentType ()
+               public TypeSpec GetArgumentType ()
                {
                        TypeOf e = GetValue () as TypeOf;
                        if (e == null)
@@ -1484,35 +1412,113 @@ namespace Mono.CSharp {
                }
        }
 
-       /// <summary>
-       /// Helper class for attribute verification routine.
-       /// </summary>
-       sealed class AttributeTester
+       public struct AttributeEncoder
        {
-               static Dictionary<Type, bool> analyzed_types;
-               static Dictionary<Type, ObsoleteAttribute> analyzed_types_obsolete;
-               static Dictionary<MemberInfo, ObsoleteAttribute> analyzed_member_obsolete;
-               static Dictionary<MethodBase, bool> analyzed_method_excluded;
-//             static Dictionary<FieldInfo, IFixedBuffer> fixed_buffer_cache;
+               public readonly BinaryWriter Stream;
 
-               static AttributeTester ()
+               public AttributeEncoder (bool empty)
                {
-                       Reset ();
+                       if (empty) {
+                               Stream = null;
+                               return;
+                       }
+
+                       Stream = new BinaryWriter (new MemoryStream ());
+                       const ushort version = 1;
+                       Stream.Write (version);
+               }
+
+               public void Encode (string value)
+               {
+                       if (value == null)
+                               throw new ArgumentNullException ();
+
+                       var buf = Encoding.UTF8.GetBytes(value);
+                       WriteCompressedValue (buf.Length);
+                       Stream.Write (buf);
+               }
+
+               public void Encode (TypeSpec type)
+               {
+                       if (type == TypeManager.bool_type) {
+                               Stream.Write ((byte) 0x02);
+                       } else if (type == TypeManager.char_type) {
+                               Stream.Write ((byte) 0x03);
+                       } else if (type == TypeManager.sbyte_type) {
+                               Stream.Write ((byte) 0x04);
+                       } else if (type == TypeManager.byte_type) {
+                               Stream.Write ((byte) 0x05);
+                       } else if (type == TypeManager.short_type) {
+                               Stream.Write ((byte) 0x06);
+                       } else if (type == TypeManager.ushort_type) {
+                               Stream.Write ((byte) 0x07);
+                       } else if (type == TypeManager.int32_type) {
+                               Stream.Write ((byte) 0x08);
+                       } else if (type == TypeManager.uint32_type) {
+                               Stream.Write ((byte) 0x09);
+                       } else if (type == TypeManager.int64_type) {
+                               Stream.Write ((byte) 0x0A);
+                       } else if (type == TypeManager.uint64_type) {
+                               Stream.Write ((byte) 0x0B);
+                       } else if (type == TypeManager.float_type) {
+                               Stream.Write ((byte) 0x0C);
+                       } else if (type == TypeManager.double_type) {
+                               Stream.Write ((byte) 0x0D);
+                       } else if (type == TypeManager.string_type) {
+                               Stream.Write ((byte) 0x0E);
+                       } else if (type == TypeManager.type_type) {
+                               Stream.Write ((byte) 0x50);
+                       } else if (type == TypeManager.object_type) {
+                               Stream.Write ((byte) 0x51);
+                       } else if (TypeManager.IsEnumType (type)) {
+                               Stream.Write ((byte) 0x55);
+                               EncodeTypeName (type);
+                       } else if (type.IsArray) {
+                               Stream.Write ((byte) 0x1D);
+                               Encode (TypeManager.GetElementType (type));
+                       } else {
+                               throw new NotImplementedException (type.ToString ());
+                       }
                }
 
-               private AttributeTester ()
+               public bool EncodeTypeName (TypeSpec type)
                {
+//                     if (TypeManager.ContainsGenericParameters (type) && !TypeManager.IsGenericTypeDefinition (type))
+//                             return false;
+
+                       var old_type = type.GetMetaInfo ();
+                       Encode (type.MemberDefinition.IsImported ? old_type.AssemblyQualifiedName : old_type.FullName);
+                       return true;
                }
 
-               public static void Reset ()
+               void WriteCompressedValue (int value)
                {
-                       analyzed_types = new Dictionary<Type, bool> (ReferenceEquality<Type>.Default);
-                       analyzed_types_obsolete = new Dictionary<Type, ObsoleteAttribute> (ReferenceEquality<Type>.Default);
-                       analyzed_member_obsolete = new Dictionary<MemberInfo, ObsoleteAttribute> (ReferenceEquality<MemberInfo>.Default);
-                       analyzed_method_excluded = new Dictionary<MethodBase, bool> (ReferenceEquality<MethodBase>.Default);
-//                     fixed_buffer_cache = new Dictionary<FieldInfo, IFixedBuffer> (ReferenceEquality<FieldInfo>.Default);
+                       if (value < 0x80) {
+                               Stream.Write ((byte) value);
+                               return;
+                       }
+
+                       if (value < 0x4000) {
+                               Stream.Write ((byte) (0x80 | (value >> 8)));
+                               Stream.Write ((byte) value);
+                               return;
+                       }
+
+                       Stream.Write (value);
                }
 
+               public byte[] ToArray ()
+               {
+                       return ((MemoryStream) Stream.BaseStream).ToArray ();
+               }
+       }
+
+
+       /// <summary>
+       /// Helper class for attribute verification routine.
+       /// </summary>
+       static class AttributeTester
+       {
                public enum Result {
                        Ok,
                        RefOutArrayError,
@@ -1525,8 +1531,8 @@ namespace Mono.CSharp {
                /// </summary>
                public static Result AreOverloadedMethodParamsClsCompliant (AParametersCollection pa, AParametersCollection pb) 
                {
-                       Type [] types_a = pa.Types;
-                       Type [] types_b = pb.Types;
+                       TypeSpec [] types_a = pa.Types;
+                       TypeSpec [] types_b = pb.Types;
                        if (types_a == null || types_b == null)
                                return Result.Ok;
 
@@ -1535,18 +1541,19 @@ namespace Mono.CSharp {
 
                        Result result = Result.Ok;
                        for (int i = 0; i < types_b.Length; ++i) {
-                               Type aType = types_a [i];
-                               Type bType = types_b [i];
+                               TypeSpec aType = types_a [i];
+                               TypeSpec bType = types_b [i];
 
-                               if (aType.IsArray && bType.IsArray) {
-                                       Type a_el_type = TypeManager.GetElementType (aType);
-                                       Type b_el_type = TypeManager.GetElementType (bType);
-                                       if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
+                               var ac_a = aType as ArrayContainer;
+                               var ac_b = aType as ArrayContainer;
+
+                               if (ac_a != null && ac_b != null) {
+                                       if (ac_a.Rank != ac_b.Rank && ac_a.Element == ac_b.Element) {
                                                result = Result.RefOutArrayError;
                                                continue;
                                        }
 
-                                       if (a_el_type.IsArray || b_el_type.IsArray) {
+                                       if (ac_a.Element.IsArray || ac_b.Element.IsArray) {
                                                result = Result.ArrayArrayError;
                                                continue;
                                        }
@@ -1562,34 +1569,6 @@ namespace Mono.CSharp {
                        return result;
                }
 
-               /// <summary>
-               /// This method tests the CLS compliance of external types. It doesn't test type visibility.
-               /// </summary>
-               public static bool IsClsCompliant (Type type) 
-               {
-                       if (type == null)
-                               return true;
-
-                       bool result;
-                       if (analyzed_types.TryGetValue (type, out result))
-                               return result;
-
-                       if (type.IsPointer) {
-                               analyzed_types.Add (type, false);
-                               return false;
-                       }
-
-                       if (type.IsArray) {
-                               result = IsClsCompliant (TypeManager.GetElementType (type));
-                       } else if (TypeManager.IsNullableType (type)) {
-                               result = IsClsCompliant (TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (type) [0]));
-                       } else {
-                               result = AnalyzeTypeCompliance (type);
-                       }
-                       analyzed_types.Add (type, result);
-                       return result;
-               }        
-
                public static void VerifyModulesClsCompliance (CompilerContext ctx)
                {
                        Module[] modules = GlobalRootNamespace.Instance.Modules;
@@ -1607,26 +1586,9 @@ namespace Mono.CSharp {
                        }
                }
 
-               public static Type GetImportedIgnoreCaseClsType (string name)
-               {
-                       foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
-                               Type t = a.GetType (name, false, true);
-                               if (t == null)
-                                       continue;
-
-                               if (IsClsCompliant (t))
-                                       return t;
-                       }
-                       return null;
-               }
-
                static bool GetClsCompliantAttributeValue (ICustomAttributeProvider attribute_provider, Assembly a) 
                {
-                       PredefinedAttribute pa = PredefinedAttributes.Get.CLSCompliant;
-                       if (!pa.IsDefined)
-                               return false;
-
-                       object[] cls_attr = attribute_provider.GetCustomAttributes (pa.Type, false);
+                       object[] cls_attr = attribute_provider.GetCustomAttributes (typeof (CLSCompliantAttribute), false);
                        if (cls_attr.Length == 0) {
                                if (a == null)
                                        return false;
@@ -1637,101 +1599,6 @@ namespace Mono.CSharp {
                        return ((CLSCompliantAttribute)cls_attr [0]).IsCompliant;
                }
 
-               static bool AnalyzeTypeCompliance (Type type)
-               {
-                       type = TypeManager.DropGenericTypeArguments (type);
-                       DeclSpace ds = TypeManager.LookupDeclSpace (type);
-                       if (ds != null) {
-                               return ds.IsClsComplianceRequired ();
-                       }
-
-                       if (TypeManager.IsGenericParameter (type))
-                               return true;
-
-                       return GetClsCompliantAttributeValue (type, type.Assembly);
-               }
-
-               /// <summary>
-               /// Returns instance of ObsoleteAttribute when type is obsolete
-               /// </summary>
-               public static ObsoleteAttribute GetObsoleteAttribute (Type type)
-               {
-                       ObsoleteAttribute result;
-                       if (analyzed_types_obsolete.TryGetValue (type, out result))
-                               return result;
-
-                       if (TypeManager.HasElementType (type)) {
-                               result = GetObsoleteAttribute (TypeManager.GetElementType (type));
-                       } else if (TypeManager.IsGenericParameter (type))
-                               result = null;  // TODO: throw new NotSupportedException ()
-                       else if (TypeManager.IsGenericType (type) && !TypeManager.IsGenericTypeDefinition (type)) {
-                               return GetObsoleteAttribute (TypeManager.DropGenericTypeArguments (type));
-                       } else {
-                               DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
-
-                               // Type is external, we can get attribute directly
-                               if (type_ds == null) {
-                                       PredefinedAttribute pa = PredefinedAttributes.Get.Obsolete;
-                                       if (pa.IsDefined) {
-                                               object[] attribute = type.GetCustomAttributes (pa.Type, false);
-                                               if (attribute.Length == 1)
-                                                       result = (ObsoleteAttribute) attribute[0];
-                                       }
-                               } else {
-                                       result = type_ds.GetObsoleteAttribute ();
-                               }
-                       }
-
-                       // Cannot use .Add because of corlib bootstrap
-                       analyzed_types_obsolete [type] = result;
-                       return result;
-               }
-
-               /// <summary>
-               /// Returns instance of ObsoleteAttribute when method is obsolete
-               /// </summary>
-               public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
-               {
-                       IMethodData mc = TypeManager.GetMethod (mb);
-                       if (mc != null) 
-                               return mc.GetObsoleteAttribute ();
-
-                       // compiler generated methods are not registered by AddMethod
-                       if (mb.DeclaringType is TypeBuilder)
-                               return null;
-
-                       MemberInfo mi = TypeManager.GetPropertyFromAccessor (mb);
-                       if (mi != null)
-                               return GetMemberObsoleteAttribute (mi);
-
-                       mi = TypeManager.GetEventFromAccessor (mb);
-                       if (mi != null)
-                               return GetMemberObsoleteAttribute (mi);
-
-                       return GetMemberObsoleteAttribute (mb);
-               }
-
-               /// <summary>
-               /// Returns instance of ObsoleteAttribute when member is obsolete
-               /// </summary>
-               public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
-               {
-                       ObsoleteAttribute oa;
-                       if (analyzed_member_obsolete.TryGetValue (mi, out oa))
-                               return oa;
-
-                       if ((mi.DeclaringType is TypeBuilder) || TypeManager.IsGenericType (mi.DeclaringType))
-                               return null;
-
-                       PredefinedAttribute pa = PredefinedAttributes.Get.Obsolete;
-                       if (!pa.IsDefined)
-                               return null;
-
-                       oa = System.Attribute.GetCustomAttribute (mi, pa.Type, false) as ObsoleteAttribute;
-                       analyzed_member_obsolete.Add (mi, oa);
-                       return oa;
-               }
-
                /// <summary>
                /// Common method for Obsolete error/warning reporting.
                /// </summary>
@@ -1748,84 +1615,6 @@ namespace Mono.CSharp {
                        }
                        Report.Warning (618, 2, loc, "`{0}' is obsolete: `{1}'", member, oa.Message);
                }
-
-               public static bool IsConditionalMethodExcluded (MethodBase mb, Location loc)
-               {
-                       bool excluded;
-                       if (analyzed_method_excluded.TryGetValue (mb, out excluded))
-                               return excluded;
-
-                       PredefinedAttribute pa = PredefinedAttributes.Get.Conditional;
-                       if (!pa.IsDefined)
-                               return false;
-
-                       ConditionalAttribute[] attrs = mb.GetCustomAttributes (pa.Type, true)
-                               as ConditionalAttribute[];
-                       if (attrs.Length == 0) {
-                               analyzed_method_excluded.Add (mb, false);
-                               return false;
-                       }
-
-                       foreach (ConditionalAttribute a in attrs) {
-                               if (loc.CompilationUnit.IsConditionalDefined (a.ConditionString)) {
-                                       analyzed_method_excluded.Add (mb, false);
-                                       return false;
-                               }
-                       }
-
-                       analyzed_method_excluded.Add (mb, true);
-                       return true;
-               }
-
-               /// <summary>
-               /// Analyzes class whether it has attribute which has ConditionalAttribute
-               /// and its condition is not defined.
-               /// </summary>
-               public static bool IsAttributeExcluded (Type type, Location loc)
-               {
-                       if (!type.IsClass)
-                               return false;
-
-                       Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
-
-                       // TODO: add caching
-                       // TODO: merge all Type bases attribute caching to one cache to save memory
-                       PredefinedAttribute pa = PredefinedAttributes.Get.Conditional;
-                       if (class_decl == null && pa.IsDefined) {
-                               object[] attributes = type.GetCustomAttributes (pa.Type, false);
-                               foreach (ConditionalAttribute ca in attributes) {
-                                       if (loc.CompilationUnit.IsConditionalDefined (ca.ConditionString))
-                                               return false;
-                               }
-                               return attributes.Length > 0;
-                       }
-
-                       return class_decl.IsExcluded ();
-               }
-
-               public static Type GetCoClassAttribute (Type type)
-               {
-                       TypeContainer tc = TypeManager.LookupInterface (type);
-                       PredefinedAttribute pa = PredefinedAttributes.Get.CoClass;
-                       if (tc == null) {
-                               if (!pa.IsDefined)
-                                       return null;
-
-                               object[] o = type.GetCustomAttributes (pa.Type, false);
-                               if (o.Length < 1)
-                                       return null;
-                               return ((System.Runtime.InteropServices.CoClassAttribute)o[0]).CoClass;
-                       }
-
-                       if (tc.OptAttributes == null)
-                               return null;
-
-                       Attribute a = tc.OptAttributes.Search (pa);
-                       if (a == null)
-                               return null;
-
-                       return a.GetCoClassAttributeValue ();
-               }
        }
 
        public class PredefinedAttributes
@@ -1940,13 +1729,13 @@ namespace Mono.CSharp {
 
        public class PredefinedAttribute
        {
-               Type type;
+               TypeSpec type;
                CustomAttributeBuilder cab;
-               ConstructorInfo ctor;
+               MethodSpec ctor;
                readonly string ns, name;
                CompilerContext compiler;
 
-               static readonly Type NotFound = typeof (PredefinedAttribute);
+               static readonly TypeSpec NotFound = InternalType.Null;
 
                public PredefinedAttribute (string ns, string name)
                {
@@ -1954,18 +1743,18 @@ namespace Mono.CSharp {
                        this.name = name;
                }
 
-               public static bool operator == (Type type, PredefinedAttribute pa)
+               public static bool operator == (TypeSpec type, PredefinedAttribute pa)
                {
                        return type == pa.type;
                }
 
-               public static bool operator != (Type type, PredefinedAttribute pa)
+               public static bool operator != (TypeSpec type, PredefinedAttribute pa)
                {
                        return type != pa.type;
                }
 
                public ConstructorInfo Constructor {
-                       get { return ctor; }
+                       get { return ctor == null ? null : (ConstructorInfo) ctor.GetMetaInfo (); }
                }
 
                public override int GetHashCode ()
@@ -2064,15 +1853,15 @@ namespace Mono.CSharp {
                        if (!Resolve (true))
                                return false;
 
-                       ConstructorInfo ci = TypeManager.GetPredefinedConstructor (type, Location.Null, Type.EmptyTypes);
+                       var ci = TypeManager.GetPredefinedConstructor (type, Location.Null, TypeSpec.EmptyTypes);
                        if (ci == null)
                                return false;
 
-                       cab = new CustomAttributeBuilder (ci, new object[0]);
+                       cab = new CustomAttributeBuilder ((ConstructorInfo) ci.GetMetaInfo (), new object[0]);
                        return true;
                }
 
-               public bool ResolveConstructor (Location loc, params Type[] argType)
+               public bool ResolveConstructor (Location loc, params TypeSpec[] argType)
                {
                        if (ctor != null)
                                throw new InternalErrorException ("Predefined ctor redefined");
@@ -2084,7 +1873,7 @@ namespace Mono.CSharp {
                        return ctor != null;
                }
 
-               public Type Type {
+               public TypeSpec Type {
                        get { return type; }
                }
        }
index a146e02fc1917f84e4fa85237a594f316e3a2ffd..b8b82ffe573f99a60cec30aaf0444ebb22f00810 100644 (file)
@@ -14,9 +14,24 @@ namespace Mono.CSharp {
 
        public class ConstantFold {
 
-               public static readonly Type[] binary_promotions = new Type[] { 
-                       TypeManager.decimal_type, TypeManager.double_type, TypeManager.float_type,
-                       TypeManager.uint64_type, TypeManager.int64_type, TypeManager.uint32_type };
+               static TypeSpec[] binary_promotions;
+
+               public static TypeSpec[] BinaryPromotionsTypes {
+                       get {
+                               if (binary_promotions == null) {
+                                        binary_promotions = new TypeSpec[] { 
+                                               TypeManager.decimal_type, TypeManager.double_type, TypeManager.float_type,
+                                               TypeManager.uint64_type, TypeManager.int64_type, TypeManager.uint32_type };
+                               }
+
+                               return binary_promotions;
+                       }
+               }
+
+               public static void Reset ()
+               {
+                       binary_promotions = null;
+               }
 
                //
                // Performs the numeric promotions on the left and right expresions
@@ -30,10 +45,10 @@ namespace Mono.CSharp {
                //              
                static bool DoBinaryNumericPromotions (ResolveContext rc, ref Constant left, ref Constant right)
                {
-                       Type ltype = left.Type;
-                       Type rtype = right.Type;
+                       TypeSpec ltype = left.Type;
+                       TypeSpec rtype = right.Type;
 
-                       foreach (Type t in binary_promotions) {
+                       foreach (TypeSpec t in BinaryPromotionsTypes) {
                                if (t == ltype)
                                        return t == rtype || ConvertPromotion (rc, ref right, ref left, t);
 
@@ -46,7 +61,7 @@ namespace Mono.CSharp {
                        return left != null && right != null;
                }
 
-               static bool ConvertPromotion (ResolveContext rc, ref Constant prim, ref Constant second, Type type)
+               static bool ConvertPromotion (ResolveContext rc, ref Constant prim, ref Constant second, TypeSpec type)
                {
                        Constant c = prim.ConvertImplicitly (rc, type);
                        if (c != null) {
@@ -99,8 +114,8 @@ namespace Mono.CSharp {
                                return new SideEffectConstant (result, right, loc);
                        }
 
-                       Type lt = left.Type;
-                       Type rt = right.Type;
+                       TypeSpec lt = left.Type;
+                       TypeSpec rt = right.Type;
                        bool bool_res;
 
                        if (lt == TypeManager.bool_type && lt == rt) {
index 9923f91607799cf0cb503fa0c206fc26db0d756d..64b6fa35934019b4ac14ad3ab8d64b5f8305c816 100644 (file)
@@ -20,6 +20,7 @@ using System.Runtime.InteropServices;
 using System.Security;
 using System.Security.Permissions;
 using System.Text;
+using System.Linq;
 
 #if NET_2_1
 using XmlElement = System.Object;
@@ -34,14 +35,14 @@ namespace Mono.CSharp {
        /// <summary>
        ///   This is the base class for structs and classes.  
        /// </summary>
-       public abstract class TypeContainer : DeclSpace, IMemberContainer
+       public abstract class TypeContainer : DeclSpace, ITypeDefinition
        {
                //
                // Different context is needed when resolving type container base
                // types. Type names come from the parent scope but type parameter
                // names from the container scope.
                //
-               struct BaseContext : IMemberContext
+               public struct BaseContext : IMemberContext
                {
                        TypeContainer tc;
 
@@ -56,7 +57,7 @@ namespace Mono.CSharp {
                                get { return tc.Compiler; }
                        }
 
-                       public Type CurrentType {
+                       public TypeSpec CurrentType {
                                get { return tc.Parent.CurrentType; }
                        }
 
@@ -64,8 +65,12 @@ namespace Mono.CSharp {
                                get { return tc.PartialContainer.CurrentTypeParameters; }
                        }
 
-                       public TypeContainer CurrentTypeDefinition {
-                               get { return tc.Parent.CurrentTypeDefinition; }
+                       public MemberCore CurrentMemberDefinition {
+                               get { return tc; }
+                       }
+
+                       public bool HasUnresolvedConstraints {
+                               get { return true; }
                        }
 
                        public bool IsObsolete {
@@ -82,10 +87,10 @@ namespace Mono.CSharp {
 
                        public string GetSignatureForError ()
                        {
-                               throw new NotImplementedException ();
+                               return tc.GetSignatureForError ();
                        }
 
-                       public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
+                       public ExtensionMethodGroupExpr LookupExtensionMethod (TypeSpec extensionType, string name, int arity, Location loc)
                        {
                                return null;
                        }
@@ -95,16 +100,18 @@ namespace Mono.CSharp {
                                return tc.Parent.LookupNamespaceAlias (name);
                        }
 
-                       public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
+                       public FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
                        {
-                               TypeParameter[] tp = CurrentTypeParameters;
-                               if (tp != null) {
-                                       TypeParameter t = TypeParameter.FindTypeParameter (tp, name);
-                                       if (t != null)
-                                               return new TypeParameterExpr (t, loc);
+                               if (arity == 0) {
+                                       TypeParameter[] tp = CurrentTypeParameters;
+                                       if (tp != null) {
+                                               TypeParameter t = TypeParameter.FindTypeParameter (tp, name);
+                                               if (t != null)
+                                                       return new TypeParameterExpr (t, loc);
+                                       }
                                }
 
-                               return tc.Parent.LookupNamespaceOrType (name, loc, ignore_cs0104);
+                               return tc.Parent.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
                        }
 
                        #endregion
@@ -131,14 +138,11 @@ namespace Mono.CSharp {
                // Holds the list of properties
                List<MemberCore> properties;
 
-               // Holds the list of delegates
-               List<TypeContainer> delegates;
-               
                // Holds the list of constructors
-               protected List<MemberCore> instance_constructors;
+               protected List<Constructor> instance_constructors;
 
                // Holds the list of fields
-               protected List<MemberCore> fields;
+               protected List<FieldBase> fields;
 
                // Holds a list of fields that have initializers
                protected List<FieldInitializer> initialized_fields;
@@ -183,30 +187,30 @@ namespace Mono.CSharp {
                // from classes from the arraylist `type_bases' 
                //
                TypeExpr base_type;
-               TypeExpr[] iface_exprs;
-               Type GenericType;
-               GenericTypeParameterBuilder[] nested_gen_params;
+               protected TypeExpr[] iface_exprs;
 
                protected List<FullNamedExpression> type_bases;
 
-               protected bool members_defined;
+               bool members_defined;
                bool members_defined_ok;
+               bool type_defined;
 
-               // The interfaces we implement.
-               protected Type[] ifaces;
+               TypeContainer InTransit;
 
-               // The base member cache and our member cache
-               MemberCache base_cache;
-               protected MemberCache member_cache;
+               GenericTypeParameterBuilder[] all_tp_builders;
 
                public const string DefaultIndexerName = "Item";
 
                private bool seen_normal_indexers = false;
                private string indexer_name = DefaultIndexerName;
                protected bool requires_delayed_unmanagedtype_check;
+               bool error;
 
                private CachedMethods cached_method;
 
+               protected TypeSpec spec;
+               TypeSpec current_type;
+
                List<TypeContainer> partial_parts;
 
                /// <remarks>
@@ -226,12 +230,62 @@ namespace Mono.CSharp {
                        this.PartialContainer = this;
                }
 
+               #region Properties
+
+               public override TypeSpec CurrentType {
+                       get {
+                               if (current_type == null) {
+                                       if (IsGeneric) {
+                                               //
+                                               // Switch to inflated version as it's used by all expressions
+                                               //
+                                               var targs = CurrentTypeParameters == null ? TypeSpec.EmptyTypes : CurrentTypeParameters.Select (l => l.Type).ToArray ();
+                                               current_type = spec.MakeGenericType (targs);
+                                       } else {
+                                               current_type = spec;
+                                       }
+                               }
+
+                               return current_type;
+                       }
+               }
+
+               public override TypeParameter[] CurrentTypeParameters {
+                       get {
+                               return PartialContainer.type_params;
+                       }
+               }
+
+               int CurrentTypeParametersStartIndex {
+                       get {
+                               int total = all_tp_builders.Length;
+                               if (CurrentTypeParameters != null) {
+                                       return total - CurrentTypeParameters.Length;
+                               }
+                               return total;
+                       }
+               }
+
+               public TypeSpec Definition {
+                       get {
+                               return spec;
+                       }
+               }
+
+               public bool HasMembersDefined {
+                       get {
+                               return members_defined;
+                       }
+               }
+
+               #endregion
+
                public bool AddMember (MemberCore symbol)
                {
                        return AddToContainer (symbol, symbol.MemberName.Basename);
                }
 
-               protected virtual bool AddMemberType (DeclSpace ds)
+               protected virtual bool AddMemberType (TypeContainer ds)
                {
                        return AddToContainer (ds, ds.Basename);
                }
@@ -330,13 +384,7 @@ namespace Mono.CSharp {
                
                public void AddDelegate (Delegate d)
                {
-                       if (!AddMemberType (d))
-                               return;
-
-                       if (delegates == null)
-                               delegates = new List<TypeContainer> ();
-
-                       delegates.Add (d);
+                       AddTypeContainer (d);
                }
 
                private void AddMemberToList (MemberCore mc, List<MemberCore> alist, bool isexplicit)
@@ -383,7 +431,7 @@ namespace Mono.CSharp {
                                ConstructorBuilder.ConstructorName : ConstructorBuilder.TypeConstructorName))
                                return;
                        
-                       if (is_static && c.Parameters.IsEmpty){
+                       if (is_static && c.ParameterInfo.IsEmpty){
                                if (default_static_constructor != null) {
                                    Report.SymbolRelatedToPreviousError (default_static_constructor);
                                        Report.Error (111, c.Location,
@@ -394,11 +442,11 @@ namespace Mono.CSharp {
 
                                default_static_constructor = c;
                        } else {
-                               if (c.Parameters.IsEmpty)
+                               if (c.ParameterInfo.IsEmpty)
                                        default_constructor = c;
                                
                                if (instance_constructors == null)
-                                       instance_constructors = new List<MemberCore> ();
+                                       instance_constructors = new List<Constructor> ();
                                
                                instance_constructors.Add (c);
                        }
@@ -410,7 +458,7 @@ namespace Mono.CSharp {
                                return false;
 
                        if (fields == null)
-                               fields = new List<MemberCore> ();
+                               fields = new List<FieldBase> ();
 
                        fields.Add (field);
 
@@ -500,7 +548,7 @@ namespace Mono.CSharp {
                        compiler_generated.Add (c);
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.Type == pa.DefaultMember) {
                                if (Indexers != null) {
@@ -508,8 +556,13 @@ namespace Mono.CSharp {
                                        return;
                                }
                        }
-                       
-                       base.ApplyAttributeBuilder (a, cb, pa);
+
+                       if (a.Type == pa.Required) {
+                               Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
+                               return;
+                       }
+
+                       TypeBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
                } 
 
                public override AttributeTargets AttributeTargets {
@@ -536,19 +589,19 @@ namespace Mono.CSharp {
                        }
                }
 
-               protected virtual Type BaseType {
+               public virtual TypeSpec BaseType {
                        get {
-                               return TypeBuilder.BaseType;
+                               return spec.BaseType;
                        }
                }
 
-               public IList<MemberCore> Fields {
+               public IList<FieldBase> Fields {
                        get {
                                return fields;
                        }
                }
 
-               public IList<MemberCore> InstanceConstructors {
+               public IList<Constructor> InstanceConstructors {
                        get {
                                return instance_constructors;
                        }
@@ -578,12 +631,6 @@ namespace Mono.CSharp {
                        }
                }
 
-               public IList<TypeContainer> Delegates {
-                       get {
-                               return delegates;
-                       }
-               }
-
                public IList<CompilerGeneratedClass> CompilerGeneratedClasses {
                        get {
                                return compiler_generated;
@@ -596,12 +643,24 @@ namespace Mono.CSharp {
                        }
                }
 
-               public string IndexerName {
+               public int TypeParametersCount {
                        get {
-                               return indexers == null ? DefaultIndexerName : indexer_name;
+                               return MemberName.Arity;
                        }
                }
 
+               TypeParameterSpec[] ITypeDefinition.TypeParameters {
+                       get {
+                               // TODO MemberCache: this is going to hurt
+                               return PartialContainer.type_params.Select (l => l.Type).ToArray ();
+                       }
+               }
+
+               public string GetAttributeDefaultMember ()
+               {
+                       return indexers == null ? DefaultIndexerName : indexer_name;
+               }
+
                public bool IsComImport {
                        get {
                                if (OptAttributes == null)
@@ -611,6 +670,12 @@ namespace Mono.CSharp {
                        }
                }
 
+               string ITypeDefinition.Namespace {
+                       get {
+                               return NamespaceEntry.NS.MemberName.GetSignatureForError ();
+                       }
+               }
+
                public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
                {
                        if ((field.ModFlags & Modifiers.STATIC) != 0){
@@ -710,12 +775,33 @@ namespace Mono.CSharp {
                        get { return pending; }
                }
 
-               public override bool GetClsCompliantAttributeValue ()
+               public TypeSpec GetAttributeCoClass ()
                {
-                       if (PartialContainer != this)
-                               return PartialContainer.GetClsCompliantAttributeValue ();
+                       if (OptAttributes == null)
+                               return null;
+
+                       Attribute a = OptAttributes.Search (PredefinedAttributes.Get.CoClass);
+                       if (a == null)
+                               return null;
+
+                       return a.GetCoClassAttributeValue ();
+               }
+
+               public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
+               {
+                       Attribute a = null;
+                       if (OptAttributes != null) {
+                               a = OptAttributes.Search (pa);
+                       }
+
+                       if (a == null) {
+                               if (BaseType != TypeManager.attribute_type)
+                                       return BaseType.GetAttributeUsage (pa);
+
+                               return null;
+                       }
 
-                       return base.GetClsCompliantAttributeValue ();
+                       return a.GetAttributeUsageAttribute ();
                }
 
                public virtual void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
@@ -743,21 +829,16 @@ namespace Mono.CSharp {
 
                        int count = type_bases.Count;
                        TypeExpr [] ifaces = null;
-                       IMemberContext base_context = new BaseContext (this);
+                       var base_context = new BaseContext (this);
                        for (int i = 0, j = 0; i < count; i++){
-                               FullNamedExpression fne = (FullNamedExpression) type_bases [i];
+                               FullNamedExpression fne = type_bases [i];
 
-                               //
-                               // Standard ResolveAsTypeTerminal cannot be used in this case because
-                               // it does ObsoleteAttribute and constraint checks which require
-                               // base type to be set
-                               //
-                               TypeExpr fne_resolved = fne.ResolveAsBaseTerminal (base_context, false);
+                               TypeExpr fne_resolved = fne.ResolveAsTypeTerminal (base_context, false);
                                if (fne_resolved == null)
                                        continue;
 
                                if (i == 0 && Kind == MemberKind.Class && !fne_resolved.Type.IsInterface) {
-                                       if (fne_resolved is DynamicTypeExpr)
+                                       if (fne_resolved.Type == InternalType.Dynamic)
                                                Report.Error (1965, Location, "Class `{0}' cannot derive from the dynamic type",
                                                        GetSignatureForError ());
                                        else
@@ -880,7 +961,7 @@ namespace Mono.CSharp {
                                        if (!TypeManager.IsEqual (o_a.ReturnType, o_b.ReturnType))
                                                continue;
 
-                                       if (!TypeManager.IsEqual (o_a.ParameterTypes, o_b.ParameterTypes))
+                                       if (!TypeSpecComparer.Default.Equals (o_a.ParameterTypes, o_b.ParameterTypes))
                                                continue;
 
                                        operators[i] = null;
@@ -912,93 +993,46 @@ namespace Mono.CSharp {
                                                GetSignatureForError ());
                        }
                }
-
-               bool CheckGenericInterfaces (Type[] ifaces)
+       
+               bool CreateTypeBuilder ()
                {
-                       var already_checked = new List<Type> ();
-
-                       for (int i = 0; i < ifaces.Length; i++) {
-                               Type iface = ifaces [i];
-                               foreach (Type t in already_checked) {
-                                       if (iface == t)
-                                               continue;
-
-                                       Type[] inferred = new Type [CountTypeParameters];
-                                       if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, inferred, null))
-                                               continue;
+                       //
+                       // Sets .size to 1 for structs with no instance fields
+                       //
+                       int type_size = Kind == MemberKind.Struct && first_nonstatic_field == null ? 1 : 0;
 
-                                       Report.Error (695, Location,
-                                               "`{0}' cannot implement both `{1}' and `{2}' " +
-                                               "because they may unify for some type parameter substitutions",
-                                               TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
-                                               TypeManager.CSharpName (t));
+                       if (IsTopLevel) {
+                               if (GlobalRootNamespace.Instance.IsNamespace (Name)) {
+                                       Report.Error (519, Location, "`{0}' clashes with a predefined namespace", Name);
                                        return false;
                                }
 
-                               already_checked.Add (iface);
-                       }
-
-                       return true;
-               }
-
-               bool error = false;
-               
-               bool CreateTypeBuilder ()
-               {
-                       try {
-                               Type default_parent = null;
-                               if (Kind == MemberKind.Struct)
-                                       default_parent = TypeManager.value_type;
-                               else if (Kind == MemberKind.Enum)
-                                       default_parent = TypeManager.enum_type;
-                               else if (Kind == MemberKind.Delegate)
-                                       default_parent = TypeManager.multicast_delegate_type;
-
-                               //
-                               // Sets .size to 1 for structs with no instance fields
-                               //
-                               int type_size = Kind == MemberKind.Struct && first_nonstatic_field == null ? 1 : 0;
-
-                               if (IsTopLevel){
-                                       if (GlobalRootNamespace.Instance.IsNamespace (Name)) {
-                                               Report.Error (519, Location, "`{0}' clashes with a predefined namespace", Name);
-                                               return false;
-                                       }
-
-                                       ModuleBuilder builder = Module.Compiled.Builder;
-                                       TypeBuilder = builder.DefineType (
-                                               Name, TypeAttr, default_parent, type_size);
-                               } else {
-                                       TypeBuilder builder = Parent.TypeBuilder;
+                               ModuleBuilder builder = Module.Compiled.Builder;
+                               TypeBuilder = builder.DefineType (Name, TypeAttr, null, type_size);
+                       } else {
+                               TypeBuilder builder = Parent.TypeBuilder;
 
-                                       TypeBuilder = builder.DefineNestedType (
-                                               Basename, TypeAttr, default_parent, type_size);
-                               }
-                       } catch (ArgumentException) {
-                               Report.RuntimeMissingSupport (Location, "static classes");
-                               return false;
+                               TypeBuilder = builder.DefineNestedType (Basename, TypeAttr, null, type_size);
                        }
 
-                       TypeManager.AddUserType (this);
+                       spec.SetMetaInfo (TypeBuilder);
+                       spec.MemberCache = new MemberCache (this);
+                       spec.DeclaringType = Parent.CurrentType;
+
+                       if (!IsTopLevel)
+                               Parent.MemberCache.AddMember (spec);
 
                        if (IsGeneric) {
-                               string[] param_names = new string [TypeParameters.Length];
+                               string[] param_names = new string[TypeParameters.Length];
                                for (int i = 0; i < TypeParameters.Length; i++)
-                                       param_names [i] = TypeParameters [i].Name;
-
-                               GenericTypeParameterBuilder[] gen_params = TypeBuilder.DefineGenericParameters (param_names);
+                                       param_names [i] = TypeParameters[i].Name;
 
-                               int offset = CountTypeParameters;
-                               if (CurrentTypeParameters != null)
-                                       offset -= CurrentTypeParameters.Length;
+                               all_tp_builders = TypeBuilder.DefineGenericParameters (param_names);
 
-                               if (offset > 0) {
-                                       nested_gen_params = new GenericTypeParameterBuilder [offset];
-                                       Array.Copy (gen_params, nested_gen_params, offset);
+                               int offset = CurrentTypeParametersStartIndex;
+                               for (int i = offset; i < all_tp_builders.Length; i++) {
+                                       CurrentTypeParameters [i - offset].Define (all_tp_builders [i], spec);
                                }
-
-                               for (int i = offset; i < gen_params.Length; i++)
-                                       CurrentTypeParameters [i - offset].Define (gen_params [i]);
                        }
 
                        return true;
@@ -1011,44 +1045,138 @@ namespace Mono.CSharp {
                                iface_exprs = GetNormalPartialBases (ref base_type);
                        }
 
-                       //
-                       // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
-                       // which in turn should have called DefineType()s on base types if necessary.
-                       //
-                       // None of the code below should trigger DefineType()s on classes that we depend on.
-                       // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
-                       //
-                       // Let's do it as soon as possible, since code below can call DefineType() on classes
-                       // that depend on us to be populated before they are.
-                       //
-                       if (!(this is CompilerGeneratedClass) && !(this is Delegate))
-                               RootContext.RegisterOrder (this); 
-
-                       if (!CheckRecursiveDefinition (this))
-                               return false;
+                       var cycle = CheckRecursiveDefinition (this);
+                       if (cycle != null) {
+                               Report.SymbolRelatedToPreviousError (cycle);
+                               if (this is Interface) {
+                                       Report.Error (529, Location,
+                                               "Inherited interface `{0}' causes a cycle in the interface hierarchy of `{1}'",
+                                           GetSignatureForError (), cycle.GetSignatureForError ());
+                               } else {
+                                       Report.Error (146, Location,
+                                               "Circular base class dependency involving `{0}' and `{1}'",
+                                               GetSignatureForError (), cycle.GetSignatureForError ());
+                               }
 
-                       if (base_type != null && base_type.Type != null) {
-                               TypeBuilder.SetParent (base_type.Type);
+                               base_type = null;
                        }
 
-                       // add interfaces that were not added at type creation
                        if (iface_exprs != null) {
-                               ifaces = TypeManager.ExpandInterfaces (iface_exprs);
-                               if (ifaces == null)
-                                       return false;
+                               foreach (TypeExpr iface in iface_exprs) {
+                                       var iface_type = iface.Type;
+
+                                       if (!spec.AddInterface (iface_type))
+                                               continue;
 
-                               foreach (Type itype in ifaces)
-                                       TypeBuilder.AddInterfaceImplementation (itype);
+                                       if (iface_type.IsGeneric && spec.Interfaces != null) {
+                                               foreach (var prev_iface in iface_exprs) {
+                                                       if (prev_iface == iface)
+                                                               break;
 
-                               if (!CheckGenericInterfaces (ifaces))
-                                       return false;
+                                                       if (!TypeSpecComparer.Unify.IsEqual (iface_type, prev_iface.Type))
+                                                               continue;
+
+                                                       Report.Error (695, Location,
+                                                               "`{0}' cannot implement both `{1}' and `{2}' because they may unify for some type parameter substitutions",
+                                                               GetSignatureForError (), prev_iface.GetSignatureForError (), iface_type.GetSignatureForError ());
+                                               }
+                                       }
+
+                                       TypeBuilder.AddInterfaceImplementation (iface_type.GetMetaInfo ());
+
+                                       // Ensure the base is always setup
+                                       var compiled_iface = iface_type.MemberDefinition as Interface;
+                                       if (compiled_iface != null) {
+                                               // TODO: Need DefineBaseType only
+                                               compiled_iface.DefineType ();
+                                       }
+
+                                       if (iface_type.Interfaces != null) {
+                                               var base_ifaces = new List<TypeSpec> (iface_type.Interfaces);
+                                               for (int i = 0; i < base_ifaces.Count; ++i) {
+                                                       var ii_iface_type = base_ifaces[i];
+                                                       if (spec.AddInterface (ii_iface_type)) {
+                                                               TypeBuilder.AddInterfaceImplementation (ii_iface_type.GetMetaInfo ());
+
+                                                               if (ii_iface_type.Interfaces != null)
+                                                                       base_ifaces.AddRange (ii_iface_type.Interfaces);
+                                                       }
+                                               }
+                                       }
+                               }
+                       }
 
-                               TypeManager.RegisterBuilder (TypeBuilder, ifaces);
+                       if (Kind == MemberKind.Interface) {
+                               spec.BaseType = TypeManager.object_type;
+                               return true;
+                       }
+
+                       TypeSpec base_ts;
+                       if (base_type != null)
+                               base_ts = base_type.Type;
+                       else if (spec.IsStruct)
+                               base_ts = TypeManager.value_type;
+                       else if (spec.IsEnum)
+                               base_ts = TypeManager.enum_type;
+                       else if (spec.IsDelegate)
+                               base_ts = TypeManager.multicast_delegate_type;
+                       else
+                               base_ts = null;
+
+                       if (base_ts != null) {
+                               spec.BaseType = base_ts;
+
+                               // Set base type after type creation
+                               TypeBuilder.SetParent (base_ts.GetMetaInfo ());
                        }
 
                        return true;
                }
 
+               public virtual void DefineConstants ()
+               {
+                       if (constants != null) {
+                               foreach (Const c in constants) {
+                                       c.DefineValue ();
+                               }
+                       }
+
+                       if (instance_constructors != null) {
+                               foreach (MethodCore m in instance_constructors) {
+                                       var p = m.ParameterInfo;
+                                       if (!p.IsEmpty && p[p.Count - 1].HasDefaultValue) {
+                                               var rc = new ResolveContext (m);
+                                               p.ResolveDefaultValues (rc);
+                                       }
+                               }
+                       }
+
+                       if (methods != null) {
+                               foreach (MethodCore m in methods) {
+                                       var p = m.ParameterInfo;
+                                       if (!p.IsEmpty && p[p.Count - 1].HasDefaultValue) {
+                                               var rc = new ResolveContext (m);
+                                               p.ResolveDefaultValues (rc);
+                                       }
+                               }
+                       }
+
+                       if (indexers != null) {
+                               foreach (Indexer i in indexers) {
+                                       var p = i.ParameterInfo;
+                                       if (p[p.Count - 1].HasDefaultValue) {
+                                           var rc = new ResolveContext (i);
+                                               p.ResolveDefaultValues (rc);
+                                       }
+                               }
+                       }
+
+                       if (types != null) {
+                               foreach (var t in types)
+                                       t.DefineConstants ();
+                       }
+               }
+
                //
                // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
                //
@@ -1066,8 +1194,11 @@ namespace Mono.CSharp {
                        }
 
                        if (partial_parts != null) {
-                               foreach (TypeContainer part in partial_parts)
+                               foreach (TypeContainer part in partial_parts) {
+                                       part.spec = spec;
+                                       part.current_type = current_type;
                                        part.TypeBuilder = TypeBuilder;
+                               }
                        }
 
                        if (Types != null) {
@@ -1082,8 +1213,6 @@ namespace Mono.CSharp {
                        return TypeBuilder;
                }
 
-               bool type_defined;
-
                public override TypeBuilder DefineType ()
                {
                        if (error)
@@ -1093,11 +1222,6 @@ namespace Mono.CSharp {
 
                        type_defined = true;
 
-                       if (CreateType () == null) {
-                               error = true;
-                               return null;
-                       }
-
                        if (!DefineBaseTypes ()) {
                                error = true;
                                return null;
@@ -1115,10 +1239,10 @@ namespace Mono.CSharp {
                {
                        base.SetParameterInfo (constraints_list);
 
-                       if (!is_generic || PartialContainer == this)
+                       if (PartialContainer.CurrentTypeParameters == null || PartialContainer == this)
                                return;
 
-                       TypeParameter[] tc_names = PartialContainer.TypeParameters;
+                       TypeParameter[] tc_names = PartialContainer.CurrentTypeParameters;
                        for (int i = 0; i < tc_names.Length; ++i) {
                                if (tc_names [i].Name != type_params [i].Name) {
                                        Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
@@ -1136,15 +1260,20 @@ namespace Mono.CSharp {
                        }
                }
 
+               //
+               // Replaces normal spec with predefined one when compiling corlib
+               // and this type container defines predefined type
+               //
+               public void SetPredefinedSpec (PredefinedTypeSpec spec)
+               {
+                       this.spec = spec;
+               }
+
                void UpdateTypeParameterConstraints (TypeContainer part)
                {
                        TypeParameter[] current_params = type_params;
                        for (int i = 0; i < current_params.Length; i++) {
-                               Constraints c = part.type_params [i].Constraints;
-                               if (c == null)
-                                       continue;
-
-                               if (current_params [i].UpdateConstraints (part, c))
+                               if (current_params [i].AddPartialConstraints (part, part.type_params [i]))
                                        continue;
 
                                Report.SymbolRelatedToPreviousError (Location, "");
@@ -1154,69 +1283,47 @@ namespace Mono.CSharp {
                        }
                }
 
-               public bool ResolveType ()
+               public bool ResolveTypeParameters ()
                {
-                       if (!DoResolveType ())
+                       if (!DoResolveTypeParameters ())
                                return false;
 
+                       if (types != null) {
+                               foreach (var type in types)
+                                       if (!type.ResolveTypeParameters ())
+                                               return false;
+                       }
+
                        if (compiler_generated != null) {
                                foreach (CompilerGeneratedClass c in compiler_generated)
-                                       if (!c.ResolveType ())
+                                       if (!c.ResolveTypeParameters ())
                                                return false;
                        }
 
                        return true;
                }
 
-               protected virtual bool DoResolveType ()
+               protected virtual bool DoResolveTypeParameters ()
                {
-                       if (!IsGeneric)
+                       if (CurrentTypeParameters == null)
                                return true;
 
                        if (PartialContainer != this)
                                throw new InternalErrorException ();
 
-                       TypeExpr current_type = null;
-                       if (CurrentTypeParameters != null) {
-                               foreach (TypeParameter type_param in CurrentTypeParameters) {
-                                       if (!type_param.Resolve (this)) {
-                                               error = true;
-                                               return false;
-                                       }
-                               }
-
-                               if (partial_parts != null) {
-                                       foreach (TypeContainer part in partial_parts)
-                                               UpdateTypeParameterConstraints (part);
-                               }
-                       }
-
-                       for (int i = 0; i < TypeParameters.Length; ++i) {
-                               //
-                               // FIXME: Same should be done for delegates
-                               // TODO: Quite ugly way how to propagate constraints to
-                               // nested types
-                               //
-                               if (nested_gen_params != null && i < nested_gen_params.Length) {
-                                       TypeParameters [i].SetConstraints (nested_gen_params [i]);
-                               } else {
-                                       if (!TypeParameters [i].DefineType (this)) {
-                                               error = true;
-                                               return false;
-                                       }
+                       var base_context = new BaseContext (this);
+                       foreach (TypeParameter type_param in CurrentTypeParameters) {
+                               if (!type_param.ResolveConstraints (base_context)) {
+                                       error = true;
+                                       return false;
                                }
                        }
 
-                       // TODO: Very strange, why not simple make generic type from
-                       // current type parameters
-                       current_type = new GenericTypeExpr (this, Location);
-                       current_type = current_type.ResolveAsTypeTerminal (this, false);
-                       if (current_type == null) {
-                               error = true;
-                               return false;
+                       if (partial_parts != null) {
+                               foreach (TypeContainer part in partial_parts)
+                                       UpdateTypeParameterConstraints (part);
                        }
 
-                       currentType = current_type.Type;
                        return true;
                }
 
@@ -1228,63 +1335,35 @@ namespace Mono.CSharp {
                                                return false;
                        }
 
-                       if (Delegates != null) {
-                               foreach (Delegate d in Delegates)
-                                       if (d.DefineType () == null)
-                                               return false;
-                       }
-
                        return true;
                }
 
-               TypeContainer InTransit;
-
-               protected bool CheckRecursiveDefinition (TypeContainer tc)
+               TypeSpec CheckRecursiveDefinition (TypeContainer tc)
                {
-                       if (InTransit != null) {
-                               Report.SymbolRelatedToPreviousError (this);
-                               if (this is Interface)
-                                       Report.Error (
-                                               529, tc.Location, "Inherited interface `{0}' causes a " +
-                                               "cycle in the interface hierarchy of `{1}'",
-                                               GetSignatureForError (), tc.GetSignatureForError ());
-                               else
-                                       Report.Error (
-                                               146, tc.Location, "Circular base class dependency " +
-                                               "involving `{0}' and `{1}'",
-                                               tc.GetSignatureForError (), GetSignatureForError ());
-                               return false;
-                       }
+                       if (InTransit != null)
+                               return spec;
 
                        InTransit = tc;
 
                        if (base_type != null && base_type.Type != null) {
-                               Type t = TypeManager.DropGenericTypeArguments (base_type.Type);
-                               TypeContainer ptc = TypeManager.LookupTypeContainer (t);
-                               if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
-                                       return false;
+                               var ptc = base_type.Type.MemberDefinition as TypeContainer;
+                               if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
+                                       return base_type.Type;
                        }
 
                        if (iface_exprs != null) {
                                foreach (TypeExpr iface in iface_exprs) {
-                                       Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
-                                       TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
-                                       if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
-                                               return false;
+                                       var ptc = iface.Type.MemberDefinition as Interface;
+                                       if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
+                                               return iface.Type;
                                }
                        }
 
-                       if (!IsTopLevel && !Parent.PartialContainer.CheckRecursiveDefinition (this))
-                               return false;
+                       if (!IsTopLevel && Parent.PartialContainer.CheckRecursiveDefinition (this) != null)
+                               return spec;
 
                        InTransit = null;
-                       return true;
-               }
-
-               public override TypeParameter[] CurrentTypeParameters {
-                       get {
-                               return PartialContainer.type_params;
-                       }
+                       return null;
                }
 
                /// <summary>
@@ -1298,6 +1377,11 @@ namespace Mono.CSharp {
                        members_defined_ok = DoDefineMembers ();
                        members_defined = true;
 
+                       if (types != null) {
+                               foreach (var nested in types)
+                                       nested.Define ();
+                       }
+
                        return members_defined_ok;
                }
 
@@ -1305,18 +1389,26 @@ namespace Mono.CSharp {
                {
                        if (iface_exprs != null) {
                                foreach (TypeExpr iface in iface_exprs) {
-                                       ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (iface.Type);
-                                       if ((oa != null) && !IsObsolete)
-                                               AttributeTester.Report_ObsoleteMessage (
-                                                       oa, iface.GetSignatureForError (), Location, Report);
+                                       var iface_type = iface.Type;
+
+                                       // Ensure the base is always setup
+                                       var compiled_iface = iface_type.MemberDefinition as Interface;
+                                       if (compiled_iface != null)
+                                               compiled_iface.Define ();
+
+                                       if (Kind == MemberKind.Interface)
+                                               MemberCache.AddInterface (iface_type);
+
+                                       ObsoleteAttribute oa = iface_type.GetAttributeObsolete ();
+                                       if (oa != null && !IsObsolete)
+                                               AttributeTester.Report_ObsoleteMessage (oa, iface.GetSignatureForError (), Location, Report);
 
                                        GenericTypeExpr ct = iface as GenericTypeExpr;
                                        if (ct != null) {
                                                // TODO: passing `this' is wrong, should be base type iface instead
                                                TypeManager.CheckTypeVariance (ct.Type, Variance.Covariant, this);
 
-                                               if (!ct.CheckConstraints (this))
-                                                       return false;
+                                               ct.CheckConstraints (this);
 
                                                if (ct.HasDynamicArguments ()) {
                                                        Report.Error (1966, iface.Location,
@@ -1329,51 +1421,40 @@ namespace Mono.CSharp {
                        }
 
                        if (base_type != null) {
-                               ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
+                               ObsoleteAttribute obsolete_attr = base_type.Type.GetAttributeObsolete ();
                                if (obsolete_attr != null && !IsObsolete)
                                        AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location, Report);
 
-                               GenericTypeExpr ct = base_type as GenericTypeExpr;
-                               if ((ct != null) && !ct.CheckConstraints (this))
-                                       return false;
-                               
-                               TypeContainer baseContainer = TypeManager.LookupTypeContainer(base_type.Type);
+                               var ct = base_type as GenericTypeExpr;
+                               if (ct != null)
+                                       ct.CheckConstraints (this);
+
+                               var baseContainer = base_type.Type.MemberDefinition as ClassOrStruct;
                                if (baseContainer != null)
-                                       baseContainer.Define();                         
-                               
-                               member_cache = new MemberCache (base_type.Type, this);
-                       } else if (Kind == MemberKind.Interface) {
-                               member_cache = new MemberCache (null, this);
-                               Type [] ifaces = TypeManager.GetInterfaces (TypeBuilder);
-                               for (int i = 0; i < ifaces.Length; ++i)
-                                       member_cache.AddInterface (TypeManager.LookupMemberCache (ifaces [i]));
-                       } else {
-                               member_cache = new MemberCache (null, this);
+                                       baseContainer.Define ();
                        }
 
-                       if (types != null)
-                               foreach (TypeContainer tc in types)
-                                       member_cache.AddNestedType (tc);
-
-                       if (delegates != null)
-                               foreach (Delegate d in delegates)
-                                       member_cache.AddNestedType (d);
-
-                       if (partial_parts != null) {
-                               foreach (TypeContainer part in partial_parts)
-                                       part.member_cache = member_cache;
+                       if (type_params != null) {
+                               foreach (var tp in type_params) {
+                                       tp.CheckGenericConstraints ();
+                               }
                        }
 
                        if (!IsTopLevel) {
-                               MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Basename, false);
-                               if (conflict_symbol == null) {
+                               MemberSpec candidate;
+                               var conflict_symbol = MemberCache.FindBaseMember (this, out candidate);
+                               if (conflict_symbol == null && candidate == null) {
                                        if ((ModFlags & Modifiers.NEW) != 0)
-                                               Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
+                                               Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
+                                                       GetSignatureForError ());
                                } else {
                                        if ((ModFlags & Modifiers.NEW) == 0) {
-                                               Report.SymbolRelatedToPreviousError (conflict_symbol);
+                                               if (candidate == null)
+                                                       candidate = conflict_symbol;
+
+                                               Report.SymbolRelatedToPreviousError (candidate);
                                                Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
-                                                       GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
+                                                       GetSignatureForError (), candidate.GetSignatureForError ());
                                        }
                                }
                        }
@@ -1407,23 +1488,9 @@ namespace Mono.CSharp {
                                CheckPairedOperators ();
                        }
 
-                       DefineContainerMembers (delegates);
-
                        ComputeIndexerName();
                        CheckEqualsAndGetHashCode();
 
-                       if (CurrentType != null) {
-                               GenericType = CurrentType;
-                       }
-
-                       //
-                       // FIXME: This hack is needed because member cache does not work
-                       // with generic types, we rely on runtime to inflate dynamic types.
-                       // TODO: This hack requires member cache refactoring to be removed
-                       //
-                       if (TypeManager.IsGenericType (TypeBuilder))
-                               member_cache = new MemberCache (this);
-
                        return true;
                }
 
@@ -1476,7 +1543,7 @@ namespace Mono.CSharp {
                                indexer_name = class_indexer_name;
                }
 
-               protected virtual void EmitIndexerName ()
+               void EmitIndexerName ()
                {
                        if (!seen_normal_indexers)
                                return;
@@ -1486,7 +1553,7 @@ namespace Mono.CSharp {
                                !pa.ResolveConstructor (Location, TypeManager.string_type))
                                return;
 
-                       CustomAttributeBuilder cb = new CustomAttributeBuilder (pa.Constructor, new string [] { IndexerName });
+                       CustomAttributeBuilder cb = new CustomAttributeBuilder (pa.Constructor, new string [] { GetAttributeDefaultMember () });
                        TypeBuilder.SetCustomAttribute (cb);
                }
 
@@ -1500,94 +1567,6 @@ namespace Mono.CSharp {
                        }
                }
 
-               public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
-               {
-                       return BaseCache == null ? null : BaseCache.FindMemberWithSameName (name, ignore_methods, null);
-               }
-
-               /// <summary>
-               ///   This function is based by a delegate to the FindMembers routine
-               /// </summary>
-               static bool AlwaysAccept (MemberInfo m, object filterCriteria)
-               {
-                       return true;
-               }
-
-               /// <summary>
-               ///   This filter is used by FindMembers, and we just keep
-               ///   a global for the filter to `AlwaysAccept'
-               /// </summary>
-               static MemberFilter accepting_filter;
-
-               
-               static TypeContainer ()
-               {
-                       accepting_filter = new MemberFilter (AlwaysAccept);
-               }
-
-               public MethodInfo[] GetMethods ()
-               {
-                       var members = new List<MethodInfo> ();
-
-                       Define ();
-
-                       if (methods != null) {
-                               int len = methods.Count;
-                               for (int i = 0; i < len; i++) {
-                                       Method m = (Method) methods [i];
-
-                                       members.Add (m.MethodBuilder);
-                               }
-                       }
-
-                       if (operators != null) {
-                               int len = operators.Count;
-                               for (int i = 0; i < len; i++) {
-                                       Operator o = (Operator) operators [i];
-
-                                       members.Add (o.MethodBuilder);
-                               }
-                       }
-
-                       if (properties != null) {
-                               int len = properties.Count;
-                               for (int i = 0; i < len; i++) {
-                                       Property p = (Property) properties [i];
-
-                                       if (p.GetBuilder != null)
-                                               members.Add (p.GetBuilder);
-                                       if (p.SetBuilder != null)
-                                               members.Add (p.SetBuilder);
-                               }
-                       }
-                               
-                       if (indexers != null) {
-                               int len = indexers.Count;
-                               for (int i = 0; i < len; i++) {
-                                       Indexer ix = (Indexer) indexers [i];
-
-                                       if (ix.GetBuilder != null)
-                                               members.Add (ix.GetBuilder);
-                                       if (ix.SetBuilder != null)
-                                               members.Add (ix.SetBuilder);
-                               }
-                       }
-
-                       if (events != null) {
-                               int len = events.Count;
-                               for (int i = 0; i < len; i++) {
-                                       Event e = (Event) events [i];
-
-                                       if (e.AddBuilder != null)
-                                               members.Add (e.AddBuilder);
-                                       if (e.RemoveBuilder != null)
-                                               members.Add (e.RemoveBuilder);
-                               }
-                       }
-
-                       return members.ToArray ();
-               }
-               
                // Indicated whether container has StructLayout attribute set Explicit
                public bool HasExplicitLayout {
                        get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
@@ -1596,447 +1575,13 @@ namespace Mono.CSharp {
 
                public bool HasStructLayout {
                        get { return (caching_flags & Flags.HasStructLayout) != 0; }
-                       set { caching_flags |= Flags.HasStructLayout; }
-               }
-
-               //
-               // Return the nested type with name @name.  Ensures that the nested type
-               // is defined if necessary.  Do _not_ use this when you have a MemberCache handy.
-               //
-               public Type FindNestedType (string name)
-               {
-                       if (PartialContainer != this)
-                               throw new InternalErrorException ("should not happen");
-
-                       var lists = new[] { types, delegates };
-
-                       for (int j = 0; j < lists.Length; ++j) {
-                               var list = lists [j];
-                               if (list == null)
-                                       continue;
-                               
-                               int len = list.Count;
-                               for (int i = 0; i < len; ++i) {
-                                       var ds = list [i];
-                                       if (ds.Basename == name) {
-                                               return ds.DefineType ();
-                                       }
-                               }
-                       }
-
-                       return null;
-               }
-
-               private void FindMembers_NestedTypes (Modifiers modflags,
-                                                     BindingFlags bf, MemberFilter filter, object criteria,
-                                                         ref List<MemberInfo> members)
-               {
-                       var lists = new[] { types, delegates };
-
-                       for (int j = 0; j < lists.Length; ++j) {
-                               var list = lists [j];
-                               if (list == null)
-                                       continue;
-                       
-                               int len = list.Count;
-                               for (int i = 0; i < len; i++) {
-                                       var ds = list [i];
-                                       
-                                       if ((ds.ModFlags & modflags) == 0)
-                                               continue;
-                                       
-                                       TypeBuilder tb = ds.TypeBuilder;
-                                       if (tb == null) {
-                                               if (!(criteria is string) || ds.Basename.Equals (criteria))
-                                                       tb = ds.DefineType ();
-                                       }
-                                       
-                                       if (tb != null && (filter (tb, criteria) == true)) {
-                                               if (members == null)
-                                                       members = new List<MemberInfo> ();
-                                               
-                                               members.Add (tb);
-                                       }
-                               }
-                       }
-               }
-               
-               /// <summary>
-               ///   This method returns the members of this type just like Type.FindMembers would
-               ///   Only, we need to use this for types which are _being_ defined because MS' 
-               ///   implementation can't take care of that.
-               /// </summary>
-               //
-               // FIXME: return an empty static array instead of null, that cleans up
-               // some code and is consistent with some coding conventions I just found
-               // out existed ;-)
-               //
-               //
-               // Notice that in various cases we check if our field is non-null,
-               // something that would normally mean that there was a bug elsewhere.
-               //
-               // The problem happens while we are defining p-invoke methods, as those
-               // will trigger a FindMembers, but this happens before things are defined
-               //
-               // Since the whole process is a no-op, it is fine to check for null here.
-               //
-               // TODO: This approach will be one day completely removed, it's already
-               // used at few places only
-               //
-               //
-               public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
-                                                       MemberFilter filter, object criteria)
-               {
-                       List<MemberInfo> members = null;
-
-                       Modifiers modflags = 0;
-                       if ((bf & BindingFlags.Public) != 0)
-                               modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
-                                       Modifiers.INTERNAL;
-                       if ((bf & BindingFlags.NonPublic) != 0)
-                               modflags |= Modifiers.PRIVATE;
-
-                       Modifiers static_mask = 0, static_flags = 0;
-                       switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
-                       case BindingFlags.Static:
-                               static_mask = static_flags = Modifiers.STATIC;
-                               break;
-
-                       case BindingFlags.Instance:
-                               static_mask = Modifiers.STATIC;
-                               static_flags = 0;
-                               break;
-
-                       default:
-                               static_mask = static_flags = 0;
-                               break;
-                       }
-
-                       Timer.StartTimer (TimerType.TcFindMembers);
-
-                       if (filter == null)
-                               filter = accepting_filter; 
-
-                       if ((mt & MemberTypes.Field) != 0) {
-                               if (fields != null) {
-                                       int len = fields.Count;
-                                       for (int i = 0; i < len; i++) {
-                                               FieldBase f = (FieldBase) fields [i];
-                                               
-                                               if ((f.ModFlags & modflags) == 0)
-                                                       continue;
-                                               if ((f.ModFlags & static_mask) != static_flags)
-                                                       continue;
-
-                                               FieldBuilder fb = f.FieldBuilder;
-                                               if (fb != null && filter (fb, criteria) == true) {
-                                                       if (members == null)
-                                                               members = new List<MemberInfo> ();
-                                                       
-                                                       members.Add (fb);
-                                               }
-                                       }
-                               }
-
-                               if (constants != null) {
-                                       int len = constants.Count;
-                                       for (int i = 0; i < len; i++) {
-                                               Const con = (Const) constants [i];
-                                               
-                                               if ((con.ModFlags & modflags) == 0)
-                                                       continue;
-                                               if ((con.ModFlags & static_mask) != static_flags)
-                                                       continue;
-
-                                               FieldBuilder fb = con.FieldBuilder;
-                                               if (fb == null) {
-                                                       // Define parent and not member, otherwise membercache can be null
-                                                       if (con.Parent.Define ())
-                                                               fb = con.FieldBuilder;
-                                               }
-                                               if (fb != null && filter (fb, criteria) == true) {
-                                                       if (members == null)
-                                                               members = new List<MemberInfo> ();
-                                                       
-                                                       members.Add (fb);
-                                               }
-                                       }
-                               }
-                       }
-
-                       if ((mt & MemberTypes.Method) != 0) {
-                               if (methods != null) {
-                                       int len = methods.Count;
-                                       for (int i = 0; i < len; i++) {
-                                               MethodOrOperator m = (MethodOrOperator) methods [i];
-                                               
-                                               if ((m.ModFlags & modflags) == 0)
-                                                       continue;
-                                               if ((m.ModFlags & static_mask) != static_flags)
-                                                       continue;
-                                               
-                                               MethodBuilder mb = m.MethodBuilder;
-
-                                               if (mb != null && filter (mb, criteria) == true) {
-                                                       if (members == null)
-                                                               members = new List<MemberInfo> ();
-
-                                                       members.Add (mb);
-                                               }
-                                       }
-                               }
-
-                               if (operators != null) {
-                                       int len = operators.Count;
-                                       for (int i = 0; i < len; i++) {
-                                               Operator o = (Operator) operators [i];
-                                               
-                                               if ((o.ModFlags & modflags) == 0)
-                                                       continue;
-                                               if ((o.ModFlags & static_mask) != static_flags)
-                                                       continue;
-                                               
-                                               MethodBuilder ob = o.MethodBuilder;
-                                               if (ob != null && filter (ob, criteria) == true) {
-                                                       if (members == null)
-                                                               members = new List<MemberInfo> ();
-                                                       
-                                                       members.Add (ob);
-                                               }
-                                       }
-                               }
-
-                               if (events != null) {
-                                       foreach (Event e in events) {
-                                               if ((e.ModFlags & modflags) == 0)
-                                                       continue;
-                                               if ((e.ModFlags & static_mask) != static_flags)
-                                                       continue;
-
-                                               MethodBuilder b = e.AddBuilder;
-                                               if (b != null && filter (b, criteria)) {
-                                                       if (members == null)
-                                                               members = new List<MemberInfo> ();
-
-                                                       members.Add (b);
-                                               }
-
-                                               b = e.RemoveBuilder;
-                                               if (b != null && filter (b, criteria)) {
-                                                       if (members == null)
-                                                               members = new List<MemberInfo> ();
-
-                                                       members.Add (b);
-                                               }
-                                       }
-                               }
-
-                               if (properties != null) {
-                                       int len = properties.Count;
-                                       for (int i = 0; i < len; i++) {
-                                               Property p = (Property) properties [i];
-                                               
-                                               if ((p.ModFlags & modflags) == 0)
-                                                       continue;
-                                               if ((p.ModFlags & static_mask) != static_flags)
-                                                       continue;
-                                               
-                                               MethodBuilder b;
-
-                                               b = p.GetBuilder;
-                                               if (b != null && filter (b, criteria) == true) {
-                                                       if (members == null)
-                                                               members = new List<MemberInfo> ();
-                                                       
-                                                       members.Add (b);
-                                               }
-
-                                               b = p.SetBuilder;
-                                               if (b != null && filter (b, criteria) == true) {
-                                                       if (members == null)
-                                                               members = new List<MemberInfo> ();
-                                                       
-                                                       members.Add (b);
-                                               }
-                                       }
-                               }
-                               
-                               if (indexers != null) {
-                                       int len = indexers.Count;
-                                       for (int i = 0; i < len; i++) {
-                                               Indexer ix = (Indexer) indexers [i];
-                                               
-                                               if ((ix.ModFlags & modflags) == 0)
-                                                       continue;
-                                               if ((ix.ModFlags & static_mask) != static_flags)
-                                                       continue;
-                                               
-                                               MethodBuilder b;
-
-                                               b = ix.GetBuilder;
-                                               if (b != null && filter (b, criteria) == true) {
-                                                       if (members == null)
-                                                               members = new List<MemberInfo> ();
-                                                       
-                                                       members.Add (b);
-                                               }
-
-                                               b = ix.SetBuilder;
-                                               if (b != null && filter (b, criteria) == true) {
-                                                       if (members == null)
-                                                               members = new List<MemberInfo> ();
-                                                       
-                                                       members.Add (b);
-                                               }
-                                       }
-                               }
-                       }
-
-                       if ((mt & MemberTypes.Event) != 0) {
-                               if (events != null) {
-                                       int len = events.Count;
-                                       for (int i = 0; i < len; i++) {
-                                               Event e = (Event) events [i];
-                                               
-                                               if ((e.ModFlags & modflags) == 0)
-                                                       continue;
-                                               if ((e.ModFlags & static_mask) != static_flags)
-                                                       continue;
-
-                                               MemberInfo eb = e.EventBuilder;
-                                               if (eb != null && filter (eb, criteria) == true) {
-                                                       if (members == null)
-                                                               members = new List<MemberInfo> ();
-
-                                                       members.Add (e.EventBuilder);
-                                               }
-                                       }
-                               }
-                       }
-                       
-                       if ((mt & MemberTypes.Property) != 0){
-                               if (properties != null) {
-                                       int len = properties.Count;
-                                       for (int i = 0; i < len; i++) {
-                                               Property p = (Property) properties [i];
-                                               
-                                               if ((p.ModFlags & modflags) == 0)
-                                                       continue;
-                                               if ((p.ModFlags & static_mask) != static_flags)
-                                                       continue;
-
-                                               MemberInfo pb = p.PropertyBuilder;
-                                               if (pb != null && filter (pb, criteria) == true) {
-                                                       if (members == null)
-                                                               members = new List<MemberInfo> ();
-                                                       
-                                                       members.Add (p.PropertyBuilder);
-                                               }
-                                       }
-                               }
-
-                               if (indexers != null) {
-                                       int len = indexers.Count;
-                                       for (int i = 0; i < len; i++) {
-                                               Indexer ix = (Indexer) indexers [i];
-                                               
-                                               if ((ix.ModFlags & modflags) == 0)
-                                                       continue;
-                                               if ((ix.ModFlags & static_mask) != static_flags)
-                                                       continue;
-
-                                               MemberInfo ib = ix.PropertyBuilder;
-                                               if (ib != null && filter (ib, criteria) == true) {
-                                                       if (members == null)
-                                                               members = new List<MemberInfo> ();
-                                                       
-                                                       members.Add (ix.PropertyBuilder);
-                                               }
-                                       }
-                               }
-                       }
-                       
-                       if ((mt & MemberTypes.NestedType) != 0)
-                               FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
-
-                       if ((mt & MemberTypes.Constructor) != 0){
-                               if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
-                                       int len = instance_constructors.Count;
-                                       for (int i = 0; i < len; i++) {
-                                               Constructor c = (Constructor) instance_constructors [i];
-                                               
-                                               ConstructorBuilder cb = c.ConstructorBuilder;
-                                               if (cb != null && filter (cb, criteria) == true) {
-                                                       if (members == null)
-                                                               members = new List<MemberInfo> ();
-
-                                                       members.Add (cb);
-                                               }
-                                       }
-                               }
-
-                               if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
-                                       ConstructorBuilder cb =
-                                               default_static_constructor.ConstructorBuilder;
-                                       
-                                       if (cb != null && filter (cb, criteria) == true) {
-                                               if (members == null)
-                                                       members = new List<MemberInfo> ();
-                                               
-                                               members.Add (cb);
-                                       }
-                               }
-                       }
-
-                       //
-                       // Lookup members in base if requested.
-                       //
-                       if ((bf & BindingFlags.DeclaredOnly) == 0) {
-                               if (TypeBuilder.BaseType != null) {
-                                       MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
-                                       if (list.Count > 0) {
-                                               if (members == null)
-                                                       members = new List<MemberInfo> ();
-                                       
-                                               members.AddRange (list);
-                                       }
-                               }
-                       }
-
-                       Timer.StopTimer (TimerType.TcFindMembers);
-
-                       if (members == null)
-                               return MemberList.Empty;
-                       else
-                               return new MemberList (members);
-               }
-
-               public override MemberCache MemberCache {
-                       get {
-                               return member_cache;
-                       }
-               }
-
-               public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
-                                                     MemberFilter filter, object criteria)
-               {
-                       DeclSpace ds = TypeManager.LookupDeclSpace (t);
-
-                       if (ds != null)
-                               return ds.FindMembers (mt, bf, filter, criteria);
-                       else
-                               return new MemberList (t.FindMembers (mt, bf, filter, criteria));
-                }
-
-               /// <summary>
-               ///   Emits the values for the constants
-               /// </summary>
-               public void EmitConstants ()
-               {
-                       if (constants != null)
-                               foreach (Const con in constants)
-                                       con.Emit ();
-                       return;
+                       set { caching_flags |= Flags.HasStructLayout; }
+               }
+
+               public MemberCache MemberCache {
+                       get {
+                               return spec.MemberCache;
+                       }
                }
 
                void CheckMemberUsage (List<MemberCore> al, string member_type)
@@ -2109,13 +1654,32 @@ namespace Mono.CSharp {
                        }
                }
 
+               public override void Emit ()
+               {
+                       if (all_tp_builders != null) {
+                               int current_starts_index = CurrentTypeParametersStartIndex;
+                               for (int i = 0; i < all_tp_builders.Length; i++) {
+                                       if (i < current_starts_index) {
+                                               TypeParameters[i].EmitConstraints (all_tp_builders [i]);
+                                       } else {
+                                               CurrentTypeParameters [i - current_starts_index].Emit ();
+                                       }
+                               }
+                       }
+
+                       if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
+                               PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (TypeBuilder);
+
+                       base.Emit ();
+               }
+
                // TODO: move to ClassOrStruct
                void EmitConstructors ()
                {
                        if (instance_constructors == null)
                                return;
 
-                       if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
+                       if (spec.IsAttribute && IsExposedFromAssembly () && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
                                bool has_compliant_args = false;
 
                                foreach (Constructor c in instance_constructors) {
@@ -2158,10 +1722,9 @@ namespace Mono.CSharp {
 
                        EmitConstructors ();
 
-                       // Can not continue if constants are broken
-                       EmitConstants ();
-                       if (Report.Errors > 0)
-                               return;
+                       if (constants != null)
+                               foreach (Const con in constants)
+                                       con.Emit ();
 
                        if (default_static_constructor != null)
                                default_static_constructor.Emit ();
@@ -2194,10 +1757,9 @@ namespace Mono.CSharp {
                                foreach (FieldBase f in fields)
                                        f.Emit ();
 
-                       if (delegates != null) {
-                               foreach (Delegate d in Delegates) {
-                                       d.Emit ();
-                               }
+                       if (types != null) {
+                               foreach (TypeContainer t in types)
+                                       t.EmitType ();
                        }
 
                        if (pending != null)
@@ -2208,15 +1770,22 @@ namespace Mono.CSharp {
 
                        if (compiler_generated != null) {
                                for (int i = 0; i < compiler_generated.Count; ++i)
-                                       ((CompilerGeneratedClass) compiler_generated [i]).EmitType ();
+                                       compiler_generated [i].EmitType ();
                        }
                }
-               
-               public override void CloseType ()
+
+               public void CloseType ()
                {
                        if ((caching_flags & Flags.CloseTypeCreated) != 0)
                                return;
 
+                       // Close base type container first to avoid TypeLoadException
+                       if (spec.BaseType != null) {
+                               var btype = spec.BaseType.MemberDefinition as TypeContainer;
+                               if (btype != null)
+                                       btype.CloseType ();
+                       }
+
                        try {
                                caching_flags |= Flags.CloseTypeCreated;
                                TypeBuilder.CreateType ();
@@ -2232,26 +1801,14 @@ namespace Mono.CSharp {
                        
                        if (Types != null){
                                foreach (TypeContainer tc in Types)
-                                       if (tc.Kind == MemberKind.Struct)
-                                               tc.CloseType ();
-
-                               foreach (TypeContainer tc in Types)
-                                       if (tc.Kind != MemberKind.Struct)
-                                               tc.CloseType ();
+                                       tc.CloseType ();
                        }
 
-                       if (Delegates != null)
-                               foreach (Delegate d in Delegates)
-                                       d.CloseType ();
-
                        if (compiler_generated != null)
                                foreach (CompilerGeneratedClass c in compiler_generated)
                                        c.CloseType ();
                        
-                       PartialContainer = null;
                        types = null;
-//                     properties = null;
-                       delegates = null;
                        fields = null;
                        initialized_fields = null;
                        initialized_static_fields = null;
@@ -2267,9 +1824,6 @@ namespace Mono.CSharp {
                        default_static_constructor = null;
                        type_bases = null;
                        OptAttributes = null;
-                       ifaces = null;
-                       base_cache = null;
-                       member_cache = null;
                }
 
                //
@@ -2363,59 +1917,20 @@ namespace Mono.CSharp {
                        if (!base.VerifyClsCompliance ())
                                return false;
 
-                       VerifyClsName ();
-
-                       Type base_type = TypeBuilder.BaseType;
-                       if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
-                               Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
-                       }
-                       return true;
-               }
-
-
-               /// <summary>
-               /// Checks whether container name is CLS Compliant
-               /// </summary>
-               void VerifyClsName ()
-               {
-                       Dictionary<string, object> base_members = base_cache == null ?
-                               new Dictionary<string, object> () :
-                               base_cache.GetPublicMembers ();
-                       var this_members = new Dictionary<string, object> ();
-
-                       foreach (var entry in defined_names) {
-                               MemberCore mc = entry.Value;
-                               if (!mc.IsClsComplianceRequired ())
-                                       continue;
-
-                               string name = entry.Key;
-                               string basename = name.Substring (name.LastIndexOf ('.') + 1);
-
-                               string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
-                               object found;
-                               if (!base_members.TryGetValue (lcase, out found)) {
-                                       if (!this_members.TryGetValue (lcase, out found)) {
-                                               this_members.Add (lcase, mc);
-                                               continue;
-                                       }
-                               }
+                       // Check this name against other containers
+                       NamespaceEntry.NS.VerifyClsCompliance ();
 
-                               if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
-                                       continue;                                       
-
-                               if (found is MemberInfo) {
-                                       if (basename == ((MemberInfo) found).Name)
-                                               continue;
-                                       Report.SymbolRelatedToPreviousError ((MemberInfo) found);
-                               } else {
-                                       Report.SymbolRelatedToPreviousError ((MemberCore) found);
-                               }
+                       // Check all container names for user classes
+                       if (Kind != MemberKind.Delegate)
+                               MemberCache.VerifyClsCompliance (Definition, Report);
 
-                               Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
+                       if (BaseType != null && !BaseType.IsCLSCompliant ()) {
+                               Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant",
+                                       GetSignatureForError (), BaseType.GetSignatureForError ());
                        }
+                       return true;
                }
 
-
                /// <summary>
                ///   Performs checks for an explicit interface implementation.  First it
                ///   checks whether the `interface_type' is a base inteface implementation.
@@ -2423,8 +1938,9 @@ namespace Mono.CSharp {
                /// </summary>
                public bool VerifyImplements (InterfaceMemberBase mb)
                {
+                       var ifaces = spec.Interfaces;
                        if (ifaces != null) {
-                               foreach (Type t in ifaces){
+                               foreach (TypeSpec t in ifaces){
                                        if (TypeManager.IsEqual (t, mb.InterfaceType))
                                                return true;
                                }
@@ -2436,20 +1952,30 @@ namespace Mono.CSharp {
                        return false;
                }
 
-               public override Type LookupAnyGeneric (string typeName)
+               //
+               // Used for visiblity checks to tests whether this definition shares
+               // base type baseType, it does member-definition search
+               //
+               public bool IsBaseTypeDefinition (TypeSpec baseType)
                {
-                       if (types != null) {
-                               foreach (TypeContainer tc in types) {
-                                       if (!tc.IsGeneric)
-                                               continue;
+                       // RootContext check
+                       if (TypeBuilder == null)
+                               return false;
 
-                                       int pos = tc.Basename.LastIndexOf ('`');
-                                       if (pos == typeName.Length && String.Compare (typeName, 0, tc.Basename, 0, pos) == 0)
-                                               return tc.TypeBuilder;
-                               }
-                       }
+                       var type = spec;
+                       do {
+                               if (type.MemberDefinition == baseType.MemberDefinition)
+                                       return true;
+
+                               type = type.BaseType;
+                       } while (type != null);
+
+                       return false;
+               }
 
-                       return base.LookupAnyGeneric (typeName);
+               public MemberCache LoadMembers (TypeSpec declaringType)
+               {
+                       throw new NotSupportedException ("Not supported for compiled definition " + GetSignatureForError ());
                }
 
                public void Mark_HasEquals ()
@@ -2492,39 +2018,6 @@ namespace Mono.CSharp {
                        }
                }
 
-               //
-               // IMemberContainer
-               //
-
-               string IMemberContainer.Name {
-                       get {
-                               return Name;
-                       }
-               }
-
-               Type IMemberContainer.Type {
-                       get {
-                               return TypeBuilder;
-                       }
-               }
-
-               bool IMemberContainer.IsInterface {
-                       get {
-                               return Kind == MemberKind.Interface;
-                       }
-               }
-
-               MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
-               {
-                       BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
-
-                       if (GenericType != null)
-                               return TypeManager.FindMembers (GenericType, mt, new_bf,
-                                                               null, null);
-                       else
-                               return FindMembers (mt, new_bf, null, null);
-               }
-
                //
                // Generates xml doc comments (if any), and if required,
                // handle warning report.
@@ -2537,18 +2030,6 @@ namespace Mono.CSharp {
                public override string DocCommentHeader {
                        get { return "T:"; }
                }
-
-               public MemberCache BaseCache {
-                       get {
-                               if (base_cache != null)
-                                       return base_cache;
-                               if (TypeBuilder.BaseType != null)
-                                       base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
-                               if (TypeBuilder.IsInterface)
-                                       base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
-                               return base_cache;
-                       }
-               }
        }
 
        public abstract class ClassOrStruct : TypeContainer
@@ -2597,7 +2078,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.IsValidSecurityAttribute ()) {
                                if (declarative_security == null)
@@ -2619,7 +2100,7 @@ namespace Mono.CSharp {
                                return;
                        }
 
-                       base.ApplyAttributeBuilder (a, cb, pa);
+                       base.ApplyAttributeBuilder (a, ctor, cdata, pa);
                }
 
                /// <summary>
@@ -2675,19 +2156,19 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
+               public override ExtensionMethodGroupExpr LookupExtensionMethod (TypeSpec extensionType, string name, int arity, Location loc)
                {
                        DeclSpace top_level = Parent;
                        if (top_level != null) {
                                while (top_level.Parent != null)
                                        top_level = top_level.Parent;
 
-                               var candidates = NamespaceEntry.NS.LookupExtensionMethod (extensionType, this, name);
+                               var candidates = NamespaceEntry.NS.LookupExtensionMethod (extensionType, this, name, arity);
                                if (candidates != null)
                                        return new ExtensionMethodGroupExpr (candidates, NamespaceEntry, extensionType, loc);
                        }
 
-                       return NamespaceEntry.LookupExtensionMethod (extensionType, name, loc);
+                       return NamespaceEntry.LookupExtensionMethod (extensionType, name, arity, loc);
                }
 
                protected override TypeAttributes TypeAttr {
@@ -2720,8 +2201,9 @@ namespace Mono.CSharp {
                              Attributes attrs)
                        : base (ns, parent, name, attrs, MemberKind.Class)
                {
-                       var accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
+                       var accmods = (Parent == null || Parent.Parent == null) ? Modifiers.INTERNAL : Modifiers.PRIVATE;
                        this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
+                       spec = new TypeSpec (Kind, null, this, null, ModFlags);
 
                        if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
                                Report.FeatureIsNotAvailable (Location, "static classes");
@@ -2736,16 +2218,15 @@ namespace Mono.CSharp {
                        base.AddBasesForPart (part, bases);
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.Type == pa.AttributeUsage) {
-                               if (!TypeManager.IsAttributeType (BaseType) &&
-                                       TypeBuilder.FullName != "System.Attribute") {
+                               if (!BaseType.IsAttribute && spec != TypeManager.attribute_type) {
                                        Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
                                }
                        }
 
-                       if (a.Type == pa.Conditional && !TypeManager.IsAttributeType (BaseType)) {
+                       if (a.Type == pa.Conditional && !BaseType.IsAttribute) {
                                Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
                                return;
                        }
@@ -2760,10 +2241,10 @@ namespace Mono.CSharp {
                                return;
                        }
 
-                       if (AttributeTester.IsAttributeExcluded (a.Type, Location))
+                       if (a.Type.IsConditionallyExcluded (Location))
                                return;
 
-                       base.ApplyAttributeBuilder (a, cb, pa);
+                       base.ApplyAttributeBuilder (a, ctor, cdata, pa);
                }
 
                public override AttributeTargets AttributeTargets {
@@ -2807,7 +2288,7 @@ namespace Mono.CSharp {
                                }
 
                                Method method = m as Method;
-                               if (method != null && method.Parameters.HasExtensionMethodType) {
+                               if (method != null && method.ParameterInfo.HasExtensionMethodType) {
                                        Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
                                        continue;
                                }
@@ -2847,51 +2328,44 @@ namespace Mono.CSharp {
                        TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
 
                        if (base_class == null) {
-                               if (RootContext.StdLib)
-                                       base_class = TypeManager.system_object_expr;
-                               else if (Name != "System.Object")
+                               if (spec != TypeManager.object_type)
                                        base_class = TypeManager.system_object_expr;
                        } else {
-                               if (Kind == MemberKind.Class && TypeManager.IsGenericParameter (base_class.Type)){
-                                       Report.Error (
-                                               689, base_class.Location,
-                                               "Cannot derive from `{0}' because it is a type parameter",
-                                               base_class.GetSignatureForError ());
-                                       return ifaces;
-                               }
+                               var base_type = base_class.Type;
 
-                               if (IsGeneric && TypeManager.IsAttributeType (base_class.Type)) {
+                               if (base_type.IsGenericParameter){
+                                       Report.Error (689, base_class.Location, "`{0}': Cannot derive from type parameter `{1}'",
+                                               GetSignatureForError (), base_type.GetSignatureForError ());
+                               } else if (IsGeneric && base_type.IsAttribute) {
                                        Report.Error (698, base_class.Location,
                                                "A generic type cannot derive from `{0}' because it is an attribute class",
                                                base_class.GetSignatureForError ());
-                               }
-
-                               if (base_class.IsSealed){
+                               } else if (base_type.IsStatic) {
                                        Report.SymbolRelatedToPreviousError (base_class.Type);
-                                       if (base_class.Type.IsAbstract) {
-                                               Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
-                                                       GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
-                                       } else {
-                                               Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
-                                                       GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
-                                       }
-                                       return ifaces;
+                                       Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
+                                               GetSignatureForError (), base_type.GetSignatureForError ());
+                               } else if (base_type.IsSealed){
+                                       Report.SymbolRelatedToPreviousError (base_class.Type);
+                                       Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
+                                               GetSignatureForError (), base_type.GetSignatureForError ());
                                }
 
-                               if (!base_class.CanInheritFrom ()){
+                               if (base_type is PredefinedTypeSpec && !(spec is PredefinedTypeSpec) &&
+                                       (base_type == TypeManager.enum_type || base_type == TypeManager.value_type || base_type == TypeManager.multicast_delegate_type ||
+                                       base_type == TypeManager.delegate_type || base_type == TypeManager.array_type)) {
                                        Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
-                                               GetSignatureForError (), base_class.GetSignatureForError ());
-                                       return ifaces;
+                                               GetSignatureForError (), base_type.GetSignatureForError ());
+                                       base_class = TypeManager.system_object_expr;
                                }
 
-                               if (!IsAccessibleAs (base_class.Type)) {
-                                       Report.SymbolRelatedToPreviousError (base_class.Type);
-                                       Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'", 
-                                               TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
+                               if (!IsAccessibleAs (base_type)) {
+                                       Report.SymbolRelatedToPreviousError (base_type);
+                                       Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
+                                               base_type.GetSignatureForError (), GetSignatureForError ());
                                }
                        }
 
-                       if (PartialContainer.IsStaticClass) {
+                       if (PartialContainer.IsStatic) {
                                if (base_class.Type != TypeManager.object_type) {
                                        Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
                                                GetSignatureForError (), base_class.GetSignatureForError ());
@@ -2910,28 +2384,26 @@ namespace Mono.CSharp {
 
                /// Search for at least one defined condition in ConditionalAttribute of attribute class
                /// Valid only for attribute classes.
-               public bool IsExcluded ()
+               public override string[] ConditionalConditions ()
                {
-                       if ((caching_flags & Flags.Excluded_Undetected) == 0)
-                               return (caching_flags & Flags.Excluded) != 0;
+                       if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
+                               return null;
 
                        caching_flags &= ~Flags.Excluded_Undetected;
 
                        if (OptAttributes == null)
-                               return false;
+                               return null;
 
                        Attribute[] attrs = OptAttributes.SearchMulti (PredefinedAttributes.Get.Conditional);
                        if (attrs == null)
-                               return false;
+                               return null;
 
-                       foreach (Attribute a in attrs) {
-                               string condition = a.GetConditionalAttributeValue ();
-                               if (Location.CompilationUnit.IsConditionalDefined (condition))
-                                       return false;
-                       }
+                       string[] conditions = new string[attrs.Length];
+                       for (int i = 0; i < conditions.Length; ++i)
+                               conditions[i] = attrs[i].GetConditionalAttributeValue ();
 
                        caching_flags |= Flags.Excluded;
-                       return true;
+                       return conditions;
                }
 
                //
@@ -2951,6 +2423,7 @@ namespace Mono.CSharp {
        public sealed class Struct : ClassOrStruct {
 
                bool is_unmanaged, has_unmanaged_check_done;
+               bool InTransit;
 
                // <summary>
                //   Modifiers allowed in a struct declaration
@@ -2967,16 +2440,20 @@ namespace Mono.CSharp {
                               Modifiers mod, Attributes attrs)
                        : base (ns, parent, name, attrs, MemberKind.Struct)
                {
-                       var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
-                       
-                       this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
+                       var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;                   
+                       this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report) | Modifiers.SEALED ;
+                       spec = new TypeSpec (Kind, null, this, null, ModFlags);
+               }
 
-                       this.ModFlags |= Modifiers.SEALED;
+               public override AttributeTargets AttributeTargets {
+                       get {
+                               return AttributeTargets.Struct;
+                       }
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
-                       base.ApplyAttributeBuilder (a, cb, pa);
+                       base.ApplyAttributeBuilder (a, ctor, cdata, pa);
 
                        //
                        // When struct constains fixed fixed and struct layout has explicitly
@@ -2992,10 +2469,61 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override AttributeTargets AttributeTargets {
-                       get {
-                               return AttributeTargets.Struct;
+               bool CheckStructCycles (Struct s)
+               {
+                       if (s.Fields == null)
+                               return true;
+
+                       if (s.InTransit)
+                               return false;
+
+                       s.InTransit = true;
+                       foreach (FieldBase field in s.Fields) {
+                               TypeSpec ftype = field.Spec.MemberType;
+                               if (!ftype.IsStruct)
+                                       continue;
+
+                               if (ftype is PredefinedTypeSpec)
+                                       continue;
+
+                               foreach (var targ in ftype.TypeArguments) {
+                                       if (!CheckFieldTypeCycle (targ)) {
+                                               Report.Error (523, field.Location,
+                                                       "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
+                                                       field.GetSignatureForError (), ftype.GetSignatureForError ());
+                                               break;
+                                       }
+                               }
+
+                               if ((field.IsStatic && !ftype.IsGeneric))
+                                       continue;
+
+                               if (!CheckFieldTypeCycle (ftype)) {
+                                       Report.Error (523, field.Location,
+                                               "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
+                                               field.GetSignatureForError (), ftype.GetSignatureForError ());
+                                       break;
+                               }
                        }
+
+                       s.InTransit = false;
+                       return true;
+               }
+
+               bool CheckFieldTypeCycle (TypeSpec ts)
+               {
+                       var fts = ts.MemberDefinition as Struct;
+                       if (fts == null)
+                               return true;
+
+                       return CheckStructCycles (fts);
+               }
+
+               public override void Emit ()
+               {
+                       CheckStructCycles (this);
+
+                       base.Emit ();
                }
 
                public override bool IsUnmanagedType ()
@@ -3012,12 +2540,12 @@ namespace Mono.CSharp {
                        has_unmanaged_check_done = true;
 
                        foreach (FieldBase f in fields) {
-                               if ((f.ModFlags & Modifiers.STATIC) != 0)
+                               if (f.IsStatic)
                                        continue;
 
                                // It can happen when recursive unmanaged types are defined
                                // struct S { S* s; }
-                               Type mt = f.MemberType;
+                               TypeSpec mt = f.MemberType;
                                if (mt == null) {
                                        has_unmanaged_check_done = false;
                                        requires_delayed_unmanagedtype_check = true;
@@ -3027,8 +2555,14 @@ namespace Mono.CSharp {
                                // TODO: Remove when pointer types are under mcs control
                                while (mt.IsPointer)
                                        mt = TypeManager.GetElementType (mt);
-                               if (TypeManager.IsEqual (mt, TypeBuilder))
+
+                               if (mt.MemberDefinition == this) {
+                                       for (var p = Parent; p != null; p = p.Parent) {
+                                               if (p.Kind == MemberKind.Class)
+                                                       return false;
+                                       }
                                        continue;
+                               }
 
                                if (TypeManager.IsUnmanagedType (mt))
                                        continue;
@@ -3043,26 +2577,10 @@ namespace Mono.CSharp {
                protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
                {
                        TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
-                       //
-                       // If we are compiling our runtime,
-                       // and we are defining ValueType, then our
-                       // base is `System.Object'.
-                       //
-                       if (base_class == null) {
-                               if (!RootContext.StdLib && Name == "System.ValueType")
-                                       base_class = TypeManager.system_object_expr;
-                               else
-                                       base_class = TypeManager.system_valuetype_expr;
-                       }
-
+                       base_class = TypeManager.system_valuetype_expr;
                        return ifaces;
                }
 
-               //
-               // FIXME: Allow the user to specify a different set of attributes
-               // in some cases (Sealed for example is mandatory for a class,
-               // but what SequentialLayout can be changed
-               //
                protected override TypeAttributes TypeAttr {
                        get {
                                const TypeAttributes DefaultTypeAttributes =
@@ -3088,7 +2606,7 @@ namespace Mono.CSharp {
        /// <summary>
        ///   Interfaces
        /// </summary>
-       public sealed class Interface : TypeContainer, IMemberContainer {
+       public sealed class Interface : TypeContainer {
 
                /// <summary>
                ///   Modifiers allowed in a class declaration
@@ -3108,16 +2626,17 @@ namespace Mono.CSharp {
                        var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
 
                        this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, name.Location, Report);
+                       spec = new TypeSpec (Kind, null, this, null, ModFlags);
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
                                a.Error_MissingGuidAttribute ();
                                return;
                        }
 
-                       base.ApplyAttributeBuilder (a, cb, pa);
+                       base.ApplyAttributeBuilder (a, ctor, cdata, pa);
                }
 
 
@@ -3143,14 +2662,14 @@ namespace Mono.CSharp {
                        if (!base.VerifyClsCompliance ())
                                return false;
 
-                       if (ifaces != null) {
-                               foreach (Type t in ifaces) {
-                                       if (AttributeTester.IsClsCompliant (t))
+                       if (iface_exprs != null) {
+                               foreach (var iface in iface_exprs) {
+                                       if (iface.Type.IsCLSCompliant ())
                                                continue;
 
-                                       Report.SymbolRelatedToPreviousError (t);
+                                       Report.SymbolRelatedToPreviousError (iface.Type);
                                        Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
-                                               GetSignatureForError (), TypeManager.CSharpName (t));
+                                               GetSignatureForError (), TypeManager.CSharpName (iface.Type));
                                }
                        }
 
@@ -3174,12 +2693,12 @@ namespace Mono.CSharp {
                //
                // The interface type we are explicitly implementing
                //
-               public Type InterfaceType;
+               public TypeSpec InterfaceType;
 
                //
                // The method we're overriding if this is an override method.
                //
-               protected MethodInfo base_method;
+               protected MethodSpec base_method;
 
                readonly Modifiers explicit_mod_flags;
                public MethodAttributes flags;
@@ -3203,75 +2722,92 @@ namespace Mono.CSharp {
                        if ((caching_flags & Flags.MethodOverloadsExist) != 0)
                                CheckForDuplications ();
                        
-                       if (IsExplicitImpl || this is Destructor)
+                       if (IsExplicitImpl)
                                return true;
 
-                       // Is null for System.Object while compiling corlib and base interfaces
-                       if (Parent.PartialContainer.BaseCache == null) {
-                               if ((ModFlags & Modifiers.NEW) != 0) {
-                                       Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
-                               }
+                       // For System.Object only
+                       if (Parent.BaseType == null)
                                return true;
-                       }
-
-                       Type base_ret_type = null;
-                       base_method = FindOutBaseMethod (ref base_ret_type);
 
-                       // method is override
-                       if (base_method != null) {
-                               if (!CheckMethodAgainstBase (base_ret_type))
-                                       return false;
+                       MemberSpec candidate;
+                       var base_member = FindBaseMember (out candidate);
 
-                               if ((ModFlags & Modifiers.OVERRIDE) != 0) {
-                                       ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
-                                       if (oa != null) {
-                                               if (OptAttributes == null || !OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
-                                                       Report.SymbolRelatedToPreviousError (base_method);
-                                                               Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
-                                                                       GetSignatureForError (), TypeManager.CSharpSignature (base_method));
+                       if ((ModFlags & Modifiers.OVERRIDE) != 0) {
+                               if (base_member == null) {
+                                       if (candidate == null) {
+                                               if (this is Method && ((Method)this).ParameterInfo.IsEmpty && MemberName.Name == Destructor.MetadataName && MemberName.Arity == 0) {
+                                                       Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
+                                                               "object.Finalize()");
+                                               } else {
+                                                       Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
+                                                               GetSignatureForError (), SimpleName.GetMemberType (this));
                                                }
                                        } else {
-                                               if (OptAttributes != null && OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
-                                                       Report.SymbolRelatedToPreviousError (base_method);
-                                                       Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
-                                                               GetSignatureForError (), TypeManager.CSharpSignature (base_method));
-                                               }
+                                               Report.SymbolRelatedToPreviousError (candidate);
+                                               if (this is Event)
+                                                       Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event",
+                                                               GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
+                                               else if (this is PropertyBase)
+                                                       Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property",
+                                                               GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
+                                               else
+                                                       Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method",
+                                                               GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
                                        }
+
+                                       return false;
                                }
-                               return true;
-                       }
 
-                       MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !((this is Event) || (this is Property)));
-                       if ((ModFlags & Modifiers.OVERRIDE) != 0) {
-                               if (conflict_symbol != null) {
-                                       Report.SymbolRelatedToPreviousError (conflict_symbol);
-                                       if (this is Event)
-                                               Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
-                                       else if (this is PropertyBase)
-                                               Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
-                                       else
-                                               Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
+                               if (!CheckOverrideAgainstBase (base_member))
+                                       return false;
+
+                               ObsoleteAttribute oa = base_member.GetAttributeObsolete ();
+                               if (oa != null) {
+                                       if (OptAttributes == null || !OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
+                                               Report.SymbolRelatedToPreviousError (base_member);
+                                               Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
+                                                       GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
+                                       }
                                } else {
-                                       Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
-                                               GetSignatureForError (), SimpleName.GetMemberType (this));
+                                       if (OptAttributes != null && OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
+                                               Report.SymbolRelatedToPreviousError (base_member);
+                                               Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
+                                                       GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
+                                       }
                                }
-                               return false;
-                       }
 
-                       if (conflict_symbol == null) {
-                               if ((ModFlags & Modifiers.NEW) != 0) {
-                                       Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
-                               }
+                               base_method = base_member as MethodSpec;
                                return true;
                        }
 
-                       if ((ModFlags & Modifiers.NEW) == 0) {
-                               if (this is MethodOrOperator && conflict_symbol.MemberType == MemberTypes.Method)
-                                       return true;
+                       if (base_member == null && candidate != null && (!(candidate is IParametersMember) || !(this is IParametersMember)))
+                               base_member = candidate;
+
+                       if (base_member == null) {
+                               if ((ModFlags & Modifiers.NEW) != 0) {
+                                       if (base_member == null) {
+                                               Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
+                                                       GetSignatureForError ());
+                                       }
+                               }
+                       } else {
+                               if ((ModFlags & Modifiers.NEW) == 0) {
+                                       ModFlags |= Modifiers.NEW;
+                                       Report.SymbolRelatedToPreviousError (base_member);
+                                       if (!IsInterface && (base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) {
+                                               Report.Warning (114, 2, Location, "`{0}' hides inherited member `{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword",
+                                                       GetSignatureForError (), base_member.GetSignatureForError ());
+                                       } else {
+                                               Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
+                                                       GetSignatureForError (), base_member.GetSignatureForError ());
+                                       }
+                               }
 
-                               Report.SymbolRelatedToPreviousError (conflict_symbol);
-                               Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
-                                       GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
+                               if (!IsInterface && base_member.IsAbstract) {
+                                       Report.SymbolRelatedToPreviousError (base_member);
+                                       Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
+                                               GetSignatureForError (), base_member.GetSignatureForError ());
+                               }
                        }
 
                        return true;
@@ -3279,124 +2815,87 @@ namespace Mono.CSharp {
 
                protected virtual bool CheckForDuplications ()
                {
-                       return Parent.MemberCache.CheckExistingMembersOverloads (
-                               this, GetFullName (MemberName), ParametersCompiled.EmptyReadOnlyParameters, Report);
+                       return Parent.MemberCache.CheckExistingMembersOverloads (this, ParametersCompiled.EmptyReadOnlyParameters);
                }
 
                //
                // Performs various checks on the MethodInfo `mb' regarding the modifier flags
                // that have been defined.
                //
-               // `name' is the user visible name for reporting errors (this is used to
-               // provide the right name regarding method names and properties)
-               //
-               bool CheckMethodAgainstBase (Type base_method_type)
+               protected virtual bool CheckOverrideAgainstBase (MemberSpec base_member)
                {
                        bool ok = true;
 
-                       if ((ModFlags & Modifiers.OVERRIDE) != 0){
-                               if (!(base_method.IsAbstract || base_method.IsVirtual)){
-                                       Report.SymbolRelatedToPreviousError (base_method);
-                                       Report.Error (506, Location,
-                                               "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
-                                                GetSignatureForError (), TypeManager.CSharpSignature (base_method));
-                                       ok = false;
-                               }
-                               
-                               // Now we check that the overriden method is not final
-                               
-                               if (base_method.IsFinal) {
-                                       Report.SymbolRelatedToPreviousError (base_method);
-                                       Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
-                                                             GetSignatureForError (), TypeManager.CSharpSignature (base_method));
-                                       ok = false;
-                               }
-                               //
-                               // Check that the permissions are not being changed
-                               //
-                               MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
-                               MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
-
-                               if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
-                                       Error_CannotChangeAccessModifiers (Location, base_method, base_classp, null);
-                                       ok = false;
-                               }
+                       if ((base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE | Modifiers.OVERRIDE_UNCHECKED)) == 0) {
+                               Report.SymbolRelatedToPreviousError (base_member);
+                               Report.Error (506, Location,
+                                       "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
+                                        GetSignatureForError (), TypeManager.CSharpSignature (base_member));
+                               ok = false;
+                       }
 
-                               if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_method_type))) {
-                                       Report.SymbolRelatedToPreviousError (base_method);
-                                       if (this is PropertyBasedMember) {
-                                               Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'", 
-                                                       GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
-                                       }
-                                       else {
-                                               Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
-                                                       GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
-                                       }
-                                       ok = false;
-                               }
+                       // Now we check that the overriden method is not final  
+                       if ((base_member.Modifiers & Modifiers.SEALED) != 0) {
+                               Report.SymbolRelatedToPreviousError (base_member);
+                               Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
+                                                         GetSignatureForError (), TypeManager.CSharpSignature (base_member));
+                               ok = false;
                        }
 
-                       if ((ModFlags & Modifiers.NEW) == 0) {
-                               if ((ModFlags & Modifiers.OVERRIDE) == 0) {
-                                       ModFlags |= Modifiers.NEW;
-                                       Report.SymbolRelatedToPreviousError (base_method);
-                                       if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
-                                               Report.Warning (114, 2, Location, "`{0}' hides inherited member `{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword",
-                                                       GetSignatureForError (), TypeManager.CSharpSignature (base_method));
-                                               if (base_method.IsAbstract){
-                                                       Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
-                                                                     GetSignatureForError (), TypeManager.CSharpSignature (base_method));
-                                                       ok = false;
-                                               }
-                                       } else {
-                                               Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
-                                                       GetSignatureForError (), TypeManager.CSharpSignature (base_method));
-                                       }
-                               }
-                       } else {
-                               if (base_method.IsAbstract && !IsInterface) {
-                                       Report.SymbolRelatedToPreviousError (base_method);
-                                       Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
-                                               GetSignatureForError (), TypeManager.CSharpSignature (base_method));
-                                       return ok = false;
+                       var base_member_type = ((IInterfaceMemberSpec) base_member).MemberType;
+                       if (!TypeSpecComparer.Override.IsEqual (MemberType, base_member_type)) {
+                               Report.SymbolRelatedToPreviousError (base_member);
+                               if (this is PropertyBasedMember) {
+                                       Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
+                                               GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
+                               } else {
+                                       Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
+                                               GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
                                }
+                               ok = false;
                        }
 
                        return ok;
                }
-               
-               protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
+
+               protected static bool CheckAccessModifiers (MemberCore this_member, MemberSpec base_member)
                {
-                       if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
+                       var thisp = this_member.ModFlags & Modifiers.AccessibilityMask;
+                       var base_classp = base_member.Modifiers & Modifiers.AccessibilityMask;
+
+                       if ((base_classp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
                                //
                                // when overriding protected internal, the method can be declared
                                // protected internal only within the same assembly or assembly
                                // which has InternalsVisibleTo
                                //
-                               if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
-                                       return TypeManager.IsThisOrFriendAssembly (Parent.Module.Assembly, base_method.DeclaringType.Assembly);
-                               } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
+                               if ((thisp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
+                                       return TypeManager.IsThisOrFriendAssembly (this_member.Assembly, base_member.Assembly);
+                               } 
+                               if ((thisp & Modifiers.PROTECTED) != Modifiers.PROTECTED) {
                                        //
                                        // if it's not "protected internal", it must be "protected"
                                        //
 
                                        return false;
-                               } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
+                               }
+                               if (this_member.Parent.PartialContainer.Module.Assembly == base_member.Assembly) {
                                        //
                                        // protected within the same assembly - an error
                                        //
                                        return false;
-                               } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) != 
-                                          (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
+                               }
+                               if ((thisp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL)) !=
+                                          (base_classp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL))) {
                                        //
                                        // protected ok, but other attributes differ - report an error
                                        //
                                        return false;
                                }
                                return true;
-                       } else {
-                               return (thisp == base_classp);
                        }
+
+                       return thisp == base_classp;
                }
 
                public override bool Define ()
@@ -3417,7 +2916,7 @@ namespace Mono.CSharp {
                        }
 
                        if (IsExplicitImpl) {
-                               TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
+                               TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (Parent, false);
                                if (iface_texpr == null)
                                        return false;
 
@@ -3457,7 +2956,7 @@ namespace Mono.CSharp {
                                if (p.CheckAccessibility (this))
                                        continue;
 
-                               Type t = parameters.Types [i];
+                               TypeSpec t = parameters.Types [i];
                                Report.SymbolRelatedToPreviousError (t);
                                if (this is Indexer)
                                        Report.Error (55, Location,
@@ -3511,37 +3010,36 @@ namespace Mono.CSharp {
                        return IsExplicitImpl;
                }
 
-               protected void Error_CannotChangeAccessModifiers (Location loc, MemberInfo base_method, MethodAttributes ma, string suffix)
+               protected void Error_CannotChangeAccessModifiers (MemberCore member, MemberSpec base_member)
                {
-                       Report.SymbolRelatedToPreviousError (base_method);
-                       string base_name = TypeManager.GetFullNameSignature (base_method);
-                       string this_name = GetSignatureForError ();
-                       if (suffix != null) {
-                               base_name += suffix;
-                               this_name += suffix;
-                       }
-
-                       Report.Error (507, loc, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
-                               this_name, ModifiersExtensions.GetDescription (ma), base_name);
+                       Report.SymbolRelatedToPreviousError (base_member);
+                       Report.Error (507, member.Location,
+                               "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
+                               member.GetSignatureForError (),
+                               ModifiersExtensions.AccessibilityName (base_member.Modifiers),
+                               base_member.GetSignatureForError ());
                }
 
-               protected static string Error722 {
-                       get {
-                               return "`{0}': static types cannot be used as return types";
-                       }
+               protected void Error_StaticReturnType ()
+               {
+                       Report.Error (722, Location,
+                               "`{0}': static types cannot be used as return types",
+                               MemberType.GetSignatureForError ());
                }
 
                /// <summary>
                /// Gets base method and its return type
                /// </summary>
-               protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
+               protected virtual MemberSpec FindBaseMember (out MemberSpec bestCandidate)
+               {
+                       return MemberCache.FindBaseMember (this, out bestCandidate);
+               }
 
                //
                // The "short" name of this property / indexer / event.  This is the
                // name without the explicit interface.
                //
-               public string ShortName 
-               {
+               public string ShortName {
                        get { return MemberName.Name; }
                        set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
                }
@@ -3550,9 +3048,14 @@ namespace Mono.CSharp {
                // Returns full metadata method name
                //
                public string GetFullName (MemberName name)
+               {
+                       return GetFullName (name.Name);
+               }
+
+               public string GetFullName (string name)
                {
                        if (!IsExplicitImpl)
-                               return name.Name;
+                               return name;
 
                        //
                        // When dealing with explicit members a full interface type
@@ -3562,19 +3065,12 @@ namespace Mono.CSharp {
                        // replacing predefined names which saves some space and name
                        // is still unique
                        //
-                       return TypeManager.CSharpName (InterfaceType) + "." + name.Name;
+                       return TypeManager.CSharpName (InterfaceType) + "." + name;
                }
 
                protected override bool VerifyClsCompliance ()
                {
                        if (!base.VerifyClsCompliance ()) {
-                               if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
-                                       Report.Warning (3010, 1, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
-                               }
-
-                               if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
-                                       Report.Warning (3011, 1, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
-                               }
                                return false;
                        }
 
@@ -3593,8 +3089,8 @@ namespace Mono.CSharp {
 
        public abstract class MemberBase : MemberCore
        {
-               protected FullNamedExpression type_name;
-               protected Type member_type;
+               protected FullNamedExpression type_expr;
+               protected TypeSpec member_type;
 
                public readonly DeclSpace ds;
                public readonly GenericMethod GenericMethod;
@@ -3605,7 +3101,7 @@ namespace Mono.CSharp {
                        : base (parent, name, attrs)
                {
                        this.ds = generic != null ? generic : (DeclSpace) parent;
-                       this.type_name = type;
+                       this.type_expr = type;
                        ModFlags = ModifiersExtensions.Check (allowed_mod, mod, def_mod, Location, Report);
                        GenericMethod = generic;
                        if (GenericMethod != null)
@@ -3698,7 +3194,7 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public Type MemberType {
+               public TypeSpec MemberType {
                        get { return member_type; }
                }
 
@@ -3707,14 +3203,14 @@ namespace Mono.CSharp {
                        if (member_type != null)
                                throw new InternalErrorException ("Multi-resolve");
 
-                       TypeExpr te = type_name.ResolveAsTypeTerminal (this, false);
+                       TypeExpr te = type_expr.ResolveAsTypeTerminal (this, false);
                        if (te == null)
                                return false;
                        
                        //
                        // Replace original type name, error reporting can use fully resolved name
                        //
-                       type_name = te;
+                       type_expr = te;
 
                        member_type = te.Type;
                        return true;
index 96bfe1642351850ae25f47a1f246b1621db95a7e..d7c7233499ce1be5c8e656c96c8d2a4aeece2624 100644 (file)
@@ -246,20 +246,21 @@ namespace Mono.CSharp {
        /// </summary>
        public class EmitContext : BuilderContext
        {
+               // TODO: Has to be private
                public ILGenerator ig;
 
                /// <summary>
                ///   The value that is allowed to be returned or NULL if there is no
                ///   return type.
                /// </summary>
-               Type return_type;
+               TypeSpec return_type;
 
                /// <summary>
                ///   Keeps track of the Type to LocalBuilder temporary storage created
                ///   to store structures (used to compute the address of the structure
                ///   value on structure method invocations)
                /// </summary>
-               Dictionary<Type, object> temporary_storage;
+               Dictionary<TypeSpec, object> temporary_storage;
 
                /// <summary>
                ///   The location where we store the return value.
@@ -277,6 +278,22 @@ namespace Mono.CSharp {
                /// </summary>
                public bool HasReturnLabel;
 
+               /// <summary>
+               ///   Current loop begin and end labels.
+               /// </summary>
+               public Label LoopBegin, LoopEnd;
+
+               /// <summary>
+               ///   Default target in a switch statement.   Only valid if
+               ///   InSwitch is true
+               /// </summary>
+               public Label DefaultTarget;
+
+               /// <summary>
+               ///   If this is non-null, points to the current switch statement
+               /// </summary>
+               public Switch Switch;
+
                /// <summary>
                ///  Whether we are inside an anonymous method.
                /// </summary>
@@ -284,7 +301,7 @@ namespace Mono.CSharp {
                
                public readonly IMemberContext MemberContext;
 
-               public EmitContext (IMemberContext rc, ILGenerator ig, Type return_type)
+               public EmitContext (IMemberContext rc, ILGenerator ig, TypeSpec return_type)
                {
                        this.MemberContext = rc;
                        this.ig = ig;
@@ -292,7 +309,9 @@ namespace Mono.CSharp {
                        this.return_type = return_type;
                }
 
-               public Type CurrentType {
+#region Properties
+
+               public TypeSpec CurrentType {
                        get { return MemberContext.CurrentType; }
                }
 
@@ -300,24 +319,33 @@ namespace Mono.CSharp {
                        get { return MemberContext.CurrentTypeParameters; }
                }
 
-               public TypeContainer CurrentTypeDefinition {
-                       get { return MemberContext.CurrentTypeDefinition; }
+               public MemberCore CurrentTypeDefinition {
+                       get { return MemberContext.CurrentMemberDefinition; }
                }
 
                public bool IsStatic {
                        get { return MemberContext.IsStatic; }
                }
 
+               bool IsAnonymousStoreyMutateRequired {
+                       get {
+                               return CurrentAnonymousMethod != null &&
+                                       CurrentAnonymousMethod.Storey != null &&
+                                       CurrentAnonymousMethod.Storey.Mutator != null;
+                       }
+               }
+
                // Has to be used for emitter errors only
                public Report Report {
                        get { return MemberContext.Compiler.Report; }
                }
 
-               public Type ReturnType {
+               public TypeSpec ReturnType {
                        get {
                                return return_type;
                        }
                }
+#endregion
 
                /// <summary>
                ///   This is called immediately before emitting an IL opcode to tell the symbol
@@ -336,23 +364,398 @@ namespace Mono.CSharp {
                        SymbolWriter.DefineLocalVariable (name, builder);
                }
 
+               public void BeginCatchBlock (TypeSpec type)
+               {
+                       ig.BeginCatchBlock (type.GetMetaInfo ());
+               }
+
+               public void BeginExceptionBlock ()
+               {
+                       ig.BeginExceptionBlock ();
+               }
+
+               public void BeginFinallyBlock ()
+               {
+                       ig.BeginFinallyBlock ();
+               }
+
                public void BeginScope ()
                {
                        ig.BeginScope();
                        SymbolWriter.OpenScope(ig);
                }
 
+               public void EndExceptionBlock ()
+               {
+                       ig.EndExceptionBlock ();
+               }
+
                public void EndScope ()
                {
                        ig.EndScope();
                        SymbolWriter.CloseScope(ig);
                }
 
+               public LocalBuilder DeclareLocal (TypeSpec type, bool pinned)
+               {
+                       if (IsAnonymousStoreyMutateRequired)
+                               type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
+
+                       return ig.DeclareLocal (type.GetMetaInfo (), pinned);
+               }
+
+               public Label DefineLabel ()
+               {
+                       return ig.DefineLabel ();
+               }
+
+               public void MarkLabel (Label label)
+               {
+                       ig.MarkLabel (label);
+               }
+
+               public void Emit (OpCode opcode)
+               {
+                       ig.Emit (opcode);
+               }
+
+               public void Emit (OpCode opcode, LocalBuilder local)
+               {
+                       ig.Emit (opcode, local);
+               }
+
+               public void Emit (OpCode opcode, string arg)
+               {
+                       ig.Emit (opcode, arg);
+               }
+
+               public void Emit (OpCode opcode, double arg)
+               {
+                       ig.Emit (opcode, arg);
+               }
+
+               public void Emit (OpCode opcode, float arg)
+               {
+                       ig.Emit (opcode, arg);
+               }
+
+               public void Emit (OpCode opcode, int arg)
+               {
+                       ig.Emit (opcode, arg);
+               }
+
+               public void Emit (OpCode opcode, byte arg)
+               {
+                       ig.Emit (opcode, arg);
+               }
+
+               public void Emit (OpCode opcode, Label label)
+               {
+                       ig.Emit (opcode, label);
+               }
+
+               public void Emit (OpCode opcode, Label[] labels)
+               {
+                       ig.Emit (opcode, labels);
+               }
+
+               public void Emit (OpCode opcode, TypeSpec type)
+               {
+                       if (IsAnonymousStoreyMutateRequired)
+                               type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
+
+                       ig.Emit (opcode, type.GetMetaInfo ());
+               }
+
+               public void Emit (OpCode opcode, FieldSpec field)
+               {
+                       if (IsAnonymousStoreyMutateRequired)
+                               field = field.Mutate (CurrentAnonymousMethod.Storey.Mutator);
+
+                       ig.Emit (opcode, field.GetMetaInfo ());
+               }
+
+               public void Emit (OpCode opcode, MethodSpec method)
+               {
+                       if (IsAnonymousStoreyMutateRequired)
+                               method = method.Mutate (CurrentAnonymousMethod.Storey.Mutator);
+
+                       if (method.IsConstructor)
+                               ig.Emit (opcode, (ConstructorInfo) method.GetMetaInfo ());
+                       else
+                               ig.Emit (opcode, (MethodInfo) method.GetMetaInfo ());
+               }
+
+               // TODO: REMOVE breaks mutator
+               public void Emit (OpCode opcode, MethodInfo method)
+               {
+                       ig.Emit (opcode, method);
+               }
+
+               // TODO: REMOVE breaks mutator
+               public void Emit (OpCode opcode, FieldBuilder field)
+               {
+                       ig.Emit (opcode, field);
+               }
+
+               public void Emit (OpCode opcode, MethodSpec method, Type[] vargs)
+               {
+                       // TODO MemberCache: This should mutate too
+                       ig.EmitCall (opcode, (MethodInfo) method.GetMetaInfo (), vargs);
+               }
+
+               public void EmitArrayNew (ArrayContainer ac)
+               {
+                       if (ac.Rank == 1) {
+                               Emit (OpCodes.Newarr, ac.Element);
+                       } else {
+                               if (IsAnonymousStoreyMutateRequired)
+                                       ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
+
+                               ig.Emit (OpCodes.Newobj, ac.GetConstructor ());
+                       }
+               }
+
+               //
+               // Emits the right opcode to load from an array
+               //
+               public void EmitArrayLoad (ArrayContainer ac)
+               {
+                       if (ac.Rank > 1) {
+                               if (IsAnonymousStoreyMutateRequired)
+                                       ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
+
+                               ig.Emit (OpCodes.Call, ac.GetGetMethod ());
+                               return;
+                       }
+
+                       var type = ac.Element;
+                       if (TypeManager.IsEnumType (type))
+                               type = EnumSpec.GetUnderlyingType (type);
+
+                       if (type == TypeManager.byte_type || type == TypeManager.bool_type)
+                               Emit (OpCodes.Ldelem_U1);
+                       else if (type == TypeManager.sbyte_type)
+                               Emit (OpCodes.Ldelem_I1);
+                       else if (type == TypeManager.short_type)
+                               Emit (OpCodes.Ldelem_I2);
+                       else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
+                               Emit (OpCodes.Ldelem_U2);
+                       else if (type == TypeManager.int32_type)
+                               Emit (OpCodes.Ldelem_I4);
+                       else if (type == TypeManager.uint32_type)
+                               Emit (OpCodes.Ldelem_U4);
+                       else if (type == TypeManager.uint64_type)
+                               Emit (OpCodes.Ldelem_I8);
+                       else if (type == TypeManager.int64_type)
+                               Emit (OpCodes.Ldelem_I8);
+                       else if (type == TypeManager.float_type)
+                               Emit (OpCodes.Ldelem_R4);
+                       else if (type == TypeManager.double_type)
+                               Emit (OpCodes.Ldelem_R8);
+                       else if (type == TypeManager.intptr_type)
+                               Emit (OpCodes.Ldelem_I);
+                       else if (TypeManager.IsStruct (type)) {
+                               Emit (OpCodes.Ldelema, type);
+                               Emit (OpCodes.Ldobj, type);
+                       } else if (type.IsGenericParameter) {
+                               Emit (OpCodes.Ldelem, type);
+                       } else if (type.IsPointer)
+                               Emit (OpCodes.Ldelem_I);
+                       else
+                               Emit (OpCodes.Ldelem_Ref);
+               }
+
+               //
+               // Emits the right opcode to store to an array
+               //
+               public void EmitArrayStore (ArrayContainer ac)
+               {
+                       if (ac.Rank > 1) {
+                               if (IsAnonymousStoreyMutateRequired)
+                                       ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
+
+                               ig.Emit (OpCodes.Call, ac.GetSetMethod ());
+                               return;
+                       }
+
+                       var type = ac.Element;
+
+                       if (type.IsEnum)
+                               type = EnumSpec.GetUnderlyingType (type);
+
+                       if (type == TypeManager.byte_type || type == TypeManager.sbyte_type || type == TypeManager.bool_type)
+                               Emit (OpCodes.Stelem_I1);
+                       else if (type == TypeManager.short_type || type == TypeManager.ushort_type || type == TypeManager.char_type)
+                               Emit (OpCodes.Stelem_I2);
+                       else if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
+                               Emit (OpCodes.Stelem_I4);
+                       else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
+                               Emit (OpCodes.Stelem_I8);
+                       else if (type == TypeManager.float_type)
+                               Emit (OpCodes.Stelem_R4);
+                       else if (type == TypeManager.double_type)
+                               Emit (OpCodes.Stelem_R8);
+                       else if (type == TypeManager.intptr_type)
+                               Emit (OpCodes.Stobj, type);
+                       else if (TypeManager.IsStruct (type))
+                               Emit (OpCodes.Stobj, type);
+                       else if (type.IsGenericParameter)
+                               Emit (OpCodes.Stelem, type);
+                       else if (type.IsPointer)
+                               Emit (OpCodes.Stelem_I);
+                       else
+                               Emit (OpCodes.Stelem_Ref);
+               }
+
+               public void EmitInt (int i)
+               {
+                       switch (i) {
+                       case -1:
+                               ig.Emit (OpCodes.Ldc_I4_M1);
+                               break;
+
+                       case 0:
+                               ig.Emit (OpCodes.Ldc_I4_0);
+                               break;
+
+                       case 1:
+                               ig.Emit (OpCodes.Ldc_I4_1);
+                               break;
+
+                       case 2:
+                               ig.Emit (OpCodes.Ldc_I4_2);
+                               break;
+
+                       case 3:
+                               ig.Emit (OpCodes.Ldc_I4_3);
+                               break;
+
+                       case 4:
+                               ig.Emit (OpCodes.Ldc_I4_4);
+                               break;
+
+                       case 5:
+                               ig.Emit (OpCodes.Ldc_I4_5);
+                               break;
+
+                       case 6:
+                               ig.Emit (OpCodes.Ldc_I4_6);
+                               break;
+
+                       case 7:
+                               ig.Emit (OpCodes.Ldc_I4_7);
+                               break;
+
+                       case 8:
+                               ig.Emit (OpCodes.Ldc_I4_8);
+                               break;
+
+                       default:
+                               if (i >= -128 && i <= 127) {
+                                       ig.Emit (OpCodes.Ldc_I4_S, (sbyte) i);
+                               } else
+                                       ig.Emit (OpCodes.Ldc_I4, i);
+                               break;
+                       }
+               }
+
+               public void EmitLong (long l)
+               {
+                       if (l >= int.MinValue && l <= int.MaxValue) {
+                               EmitInt (unchecked ((int) l));
+                               ig.Emit (OpCodes.Conv_I8);
+                               return;
+                       }
+
+                       if (l >= 0 && l <= uint.MaxValue) {
+                               EmitInt (unchecked ((int) l));
+                               ig.Emit (OpCodes.Conv_U8);
+                               return;
+                       }
+
+                       ig.Emit (OpCodes.Ldc_I8, l);
+               }
+
+               //
+               // Load the object from the pointer.  
+               //
+               public void EmitLoadFromPtr (TypeSpec t)
+               {
+                       if (t == TypeManager.int32_type)
+                               ig.Emit (OpCodes.Ldind_I4);
+                       else if (t == TypeManager.uint32_type)
+                               ig.Emit (OpCodes.Ldind_U4);
+                       else if (t == TypeManager.short_type)
+                               ig.Emit (OpCodes.Ldind_I2);
+                       else if (t == TypeManager.ushort_type)
+                               ig.Emit (OpCodes.Ldind_U2);
+                       else if (t == TypeManager.char_type)
+                               ig.Emit (OpCodes.Ldind_U2);
+                       else if (t == TypeManager.byte_type)
+                               ig.Emit (OpCodes.Ldind_U1);
+                       else if (t == TypeManager.sbyte_type)
+                               ig.Emit (OpCodes.Ldind_I1);
+                       else if (t == TypeManager.uint64_type)
+                               ig.Emit (OpCodes.Ldind_I8);
+                       else if (t == TypeManager.int64_type)
+                               ig.Emit (OpCodes.Ldind_I8);
+                       else if (t == TypeManager.float_type)
+                               ig.Emit (OpCodes.Ldind_R4);
+                       else if (t == TypeManager.double_type)
+                               ig.Emit (OpCodes.Ldind_R8);
+                       else if (t == TypeManager.bool_type)
+                               ig.Emit (OpCodes.Ldind_I1);
+                       else if (t == TypeManager.intptr_type)
+                               ig.Emit (OpCodes.Ldind_I);
+                       else if (t.IsEnum) {
+                               if (t == TypeManager.enum_type)
+                                       ig.Emit (OpCodes.Ldind_Ref);
+                               else
+                                       EmitLoadFromPtr (EnumSpec.GetUnderlyingType (t));
+                       } else if (TypeManager.IsStruct (t) || TypeManager.IsGenericParameter (t))
+                               Emit (OpCodes.Ldobj, t);
+                       else if (t.IsPointer)
+                               ig.Emit (OpCodes.Ldind_I);
+                       else
+                               ig.Emit (OpCodes.Ldind_Ref);
+               }
+
+               //
+               // The stack contains the pointer and the value of type `type'
+               //
+               public void EmitStoreFromPtr (TypeSpec type)
+               {
+                       if (type.IsEnum)
+                               type = EnumSpec.GetUnderlyingType (type);
+
+                       if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
+                               ig.Emit (OpCodes.Stind_I4);
+                       else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
+                               ig.Emit (OpCodes.Stind_I8);
+                       else if (type == TypeManager.char_type || type == TypeManager.short_type ||
+                                type == TypeManager.ushort_type)
+                               ig.Emit (OpCodes.Stind_I2);
+                       else if (type == TypeManager.float_type)
+                               ig.Emit (OpCodes.Stind_R4);
+                       else if (type == TypeManager.double_type)
+                               ig.Emit (OpCodes.Stind_R8);
+                       else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
+                                type == TypeManager.bool_type)
+                               ig.Emit (OpCodes.Stind_I1);
+                       else if (type == TypeManager.intptr_type)
+                               ig.Emit (OpCodes.Stind_I);
+                       else if (TypeManager.IsStruct (type) || TypeManager.IsGenericParameter (type))
+                               ig.Emit (OpCodes.Stobj, type.GetMetaInfo ());
+                       else
+                               ig.Emit (OpCodes.Stind_Ref);
+               }
+
                /// <summary>
                ///   Returns a temporary storage for a variable of type t as 
                ///   a local variable in the current body.
                /// </summary>
-               public LocalBuilder GetTemporaryLocal (Type t)
+               public LocalBuilder GetTemporaryLocal (TypeSpec t)
                {
                        if (temporary_storage != null) {
                                object o;
@@ -367,13 +770,13 @@ namespace Mono.CSharp {
                                if (o != null)
                                        return (LocalBuilder) o;
                        }
-                       return ig.DeclareLocal (TypeManager.TypeToReflectionType (t));
+                       return DeclareLocal (t, false);
                }
 
-               public void FreeTemporaryLocal (LocalBuilder b, Type t)
+               public void FreeTemporaryLocal (LocalBuilder b, TypeSpec t)
                {
                        if (temporary_storage == null) {
-                               temporary_storage = new Dictionary<Type, object> (ReferenceEquality<Type>.Default);
+                               temporary_storage = new Dictionary<TypeSpec, object> (ReferenceEquality<TypeSpec>.Default);
                                temporary_storage.Add (t, b);
                                return;
                        }
@@ -392,22 +795,6 @@ namespace Mono.CSharp {
                        s.Push (b);
                }
 
-               /// <summary>
-               ///   Current loop begin and end labels.
-               /// </summary>
-               public Label LoopBegin, LoopEnd;
-
-               /// <summary>
-               ///   Default target in a switch statement.   Only valid if
-               ///   InSwitch is true
-               /// </summary>
-               public Label DefaultTarget;
-
-               /// <summary>
-               ///   If this is non-null, points to the current switch statement
-               /// </summary>
-               public Switch Switch;
-
                /// <summary>
                ///   ReturnValue creates on demand the LocalBuilder for the
                ///   return value from the function.  By default this is not
@@ -423,9 +810,9 @@ namespace Mono.CSharp {
                public LocalBuilder TemporaryReturn ()
                {
                        if (return_value == null){
-                               return_value = ig.DeclareLocal (return_type);
+                               return_value = DeclareLocal (return_type, false);
                                if (!HasReturnLabel){
-                                       ReturnLabel = ig.DefineLabel ();
+                                       ReturnLabel = DefineLabel ();
                                        HasReturnLabel = true;
                                }
                        }
@@ -471,7 +858,7 @@ namespace Mono.CSharp {
                        get { return RootContext.ToplevelTypes.Compiler; }
                }
 
-               public Type CurrentType {
+               public TypeSpec CurrentType {
                        get { return null; }
                }
 
@@ -479,7 +866,7 @@ namespace Mono.CSharp {
                        get { return null; }
                }
 
-               public TypeContainer CurrentTypeDefinition {
+               public MemberCore CurrentMemberDefinition {
                        get { return RootContext.ToplevelTypes; }
                }
 
@@ -488,6 +875,10 @@ namespace Mono.CSharp {
                        return "<module>";
                }
 
+               public bool HasUnresolvedConstraints {
+                       get { return false; }
+               }
+
                public bool IsObsolete {
                        get { return false; }
                }
@@ -500,14 +891,14 @@ namespace Mono.CSharp {
                        get { return false; }
                }
 
-               public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
+               public ExtensionMethodGroupExpr LookupExtensionMethod (TypeSpec extensionType, string name, int arity, Location loc)
                {
                        throw new NotImplementedException ();
                }
 
-               public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
+               public FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
                {
-                       return RootContext.ToplevelTypes.LookupNamespaceOrType (name, loc, ignore_cs0104);
+                       return RootContext.ToplevelTypes.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
                }
 
                public FullNamedExpression LookupNamespaceAlias (string name)
@@ -530,7 +921,7 @@ namespace Mono.CSharp {
                bool has_extension_method;              
                public AssemblyName Name;
                MethodInfo add_type_forwarder;
-               Dictionary<Type, Attribute> emitted_forwarders;
+               Dictionary<ITypeDefinition, Attribute> emitted_forwarders;
 
                // Module is here just because of error messages
                static string[] attribute_targets = new string [] { "assembly", "module" };
@@ -618,9 +1009,9 @@ namespace Mono.CSharp {
 
                        Attribute a = ResolveAttribute (PredefinedAttributes.Get.RuntimeCompatibility);
                        if (a != null) {
-                               object val = a.GetPropertyValue ("WrapNonExceptionThrows");
+                               var val = a.GetPropertyValue ("WrapNonExceptionThrows") as BoolConstant;
                                if (val != null)
-                                       wrap_non_exception_throws = (bool) val;
+                                       wrap_non_exception_throws = val.Value;
                        }
                }
 
@@ -823,7 +1214,7 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.IsValidSecurityAttribute ()) {
                                if (declarative_security == null)
@@ -861,32 +1252,31 @@ namespace Mono.CSharp {
                                return;
 
                        if (a.Type == pa.TypeForwarder) {
-                               Type t = a.GetArgumentType ();
+                               TypeSpec t = a.GetArgumentType ();
                                if (t == null || TypeManager.HasElementType (t)) {
                                        Report.Error (735, a.Location, "Invalid type specified as an argument for TypeForwardedTo attribute");
                                        return;
                                }
 
-                               t = TypeManager.DropGenericTypeArguments (t);
                                if (emitted_forwarders == null) {
-                                       emitted_forwarders = new Dictionary<Type, Attribute>  ();
-                               } else if (emitted_forwarders.ContainsKey (t)) {
-                                       Report.SymbolRelatedToPreviousError(emitted_forwarders[t].Location, null);
+                                       emitted_forwarders = new Dictionary<ITypeDefinition, Attribute>  ();
+                               } else if (emitted_forwarders.ContainsKey (t.MemberDefinition)) {
+                                       Report.SymbolRelatedToPreviousError(emitted_forwarders[t.MemberDefinition].Location, null);
                                        Report.Error(739, a.Location, "A duplicate type forward of type `{0}'",
                                                TypeManager.CSharpName(t));
                                        return;
                                }
 
-                               emitted_forwarders.Add(t, a);
+                               emitted_forwarders.Add(t.MemberDefinition, a);
 
-                               if (TypeManager.LookupDeclSpace (t) != null) {
+                               if (t.Assembly == Builder) {
                                        Report.SymbolRelatedToPreviousError (t);
                                        Report.Error (729, a.Location, "Cannot forward type `{0}' because it is defined in this assembly",
                                                TypeManager.CSharpName (t));
                                        return;
                                }
 
-                               if (t.DeclaringType != null) {
+                               if (t.IsNested) {
                                        Report.Error (730, a.Location, "Cannot forward type `{0}' because it is a nested type",
                                                TypeManager.CSharpName (t));
                                        return;
@@ -902,7 +1292,7 @@ namespace Mono.CSharp {
                                        }
                                }
 
-                               add_type_forwarder.Invoke (Builder, new object[] { t });
+                               add_type_forwarder.Invoke (Builder, new object[] { t.GetMetaInfo () });
                                return;
                        }
                        
@@ -911,7 +1301,7 @@ namespace Mono.CSharp {
                                return;
                        }
 
-                       Builder.SetCustomAttribute (cb);
+                       Builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
                }
 
                public override void Emit (TypeContainer tc)
@@ -924,14 +1314,13 @@ namespace Mono.CSharp {
                        // FIXME: Does this belong inside SRE.AssemblyBuilder instead?
                        PredefinedAttribute pa = PredefinedAttributes.Get.RuntimeCompatibility;
                        if (pa.IsDefined && (OptAttributes == null || !OptAttributes.Contains (pa))) {
-                               ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
-                                       pa.Type, Location.Null, Type.EmptyTypes);
+                               var ci = TypeManager.GetPredefinedConstructor (pa.Type, Location.Null, TypeSpec.EmptyTypes);
                                PropertyInfo [] pis = new PropertyInfo [1];
                                pis [0] = TypeManager.GetPredefinedProperty (pa.Type,
                                        "WrapNonExceptionThrows", Location.Null, TypeManager.bool_type).MetaInfo;
                                object [] pargs = new object [1];
                                pargs [0] = true;
-                               Builder.SetCustomAttribute (new CustomAttributeBuilder (ci, new object [0], pis, pargs));
+                               Builder.SetCustomAttribute (new CustomAttributeBuilder ((ConstructorInfo) ci.GetMetaInfo (), new object[0], pis, pargs));
                        }
 
                        if (declarative_security != null) {
@@ -942,7 +1331,7 @@ namespace Mono.CSharp {
                                try {
                                        // Microsoft runtime hacking
                                        if (add_permission == null) {
-                                               Type assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
+                                               var assembly_builder = typeof (AssemblyBuilder).Assembly.GetType ("System.Reflection.Emit.AssemblyBuilderData");
                                                add_permission = assembly_builder.GetMethod ("AddPermissionRequests", BindingFlags.Instance | BindingFlags.NonPublic);
 
                                                FieldInfo fi = typeof (AssemblyBuilder).GetField ("m_assemblyData", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
index 36de138c0a78371cb67f92c1908e6576b3bae976..ed2f1ba2a6d369a3e3c6f499b22598285460e034 100644 (file)
@@ -19,6 +19,7 @@ using System.Reflection;
 using System.Reflection.Emit;
 using System.Text;
 using Mono.CSharp.Linq;
+using System.Linq;
 
 namespace Mono.CSharp {
 
@@ -26,7 +27,27 @@ namespace Mono.CSharp {
        // A common base class for Completing expressions, it
        // is just a very simple ExpressionStatement
        //
-       public abstract class CompletingExpression : ExpressionStatement {
+       public abstract class CompletingExpression : ExpressionStatement
+       {
+               public static void AppendResults (List<string> results, string prefix, IEnumerable<string> names)
+               {
+                       foreach (string name in names) {
+                               if (name == null || prefix == null)
+                                       continue;
+
+                               if (!name.StartsWith (prefix))
+                                       continue;
+
+                               if (results.Contains (name))
+                                       continue;
+
+                               if (prefix != null)
+                                       results.Add (name.Substring (prefix.Length));
+                               else
+                                       results.Add (name);
+                       }
+               }
+
                public override void EmitStatement (EmitContext ec)
                {
                        // Do nothing
@@ -51,33 +72,13 @@ namespace Mono.CSharp {
                        this.loc = l;
                        this.Prefix = prefix;
                }
-
-               public static void AppendResults (List<string> results, string prefix, IEnumerable<string> names)
-               {
-                       foreach (string name in names){
-                               if (name == null || prefix == null)
-                                       continue;
-
-                               if (!name.StartsWith (prefix))
-                                       continue;
-
-                               if (results.Contains (name))
-                                       continue;
-
-                               if (prefix != null)
-                                       results.Add (name.Substring (prefix.Length));
-                               else
-                                       results.Add (name);
-                       }
-
-               }
                
                protected override Expression DoResolve (ResolveContext ec)
                {
                        var results = new List<string> ();
 
                        AppendResults (results, Prefix, Evaluator.GetVarNames ());
-                       AppendResults (results, Prefix, ec.CurrentTypeDefinition.NamespaceEntry.CompletionGetTypesStartingWith (Prefix));
+                       AppendResults (results, Prefix, ec.CurrentMemberDefinition.Parent.NamespaceEntry.CompletionGetTypesStartingWith (Prefix));
                        AppendResults (results, Prefix, Evaluator.GetUsingList ());
                        
                        throw new CompletionResult (Prefix, results.ToArray ());
@@ -93,30 +94,6 @@ namespace Mono.CSharp {
                Expression expr;
                string partial_name;
                TypeArguments targs;
-
-               internal static MemberFilter CollectingFilter = new MemberFilter (Match);
-
-               static bool Match (MemberInfo m, object filter_criteria)
-               {
-                       if (m is FieldInfo){
-                               if (((FieldInfo) m).IsSpecialName)
-                                       return false;
-                               
-                       }
-                       if (m is MethodInfo){
-                               if (((MethodInfo) m).IsSpecialName)
-                                       return false;
-                       }
-
-                       if (filter_criteria == null)
-                               return true;
-                       
-                       string n = (string) filter_criteria;
-                       if (m.Name.StartsWith (n))
-                               return true;
-                       
-                       return false;
-               }
                
                public CompletionMemberAccess (Expression e, string partial_name, Location l)
                {
@@ -142,7 +119,7 @@ namespace Mono.CSharp {
                        if (expr_resolved == null)
                                return null;
 
-                       Type expr_type = expr_resolved.Type;
+                       TypeSpec expr_type = expr_resolved.Type;
                        if (expr_type.IsPointer || expr_type == TypeManager.void_type || expr_type == TypeManager.null_type || expr_type == InternalType.AnonymousMethod) {
                                Unary.Error_OperatorCannotBeApplied (ec, loc, ".", expr_type);
                                return null;
@@ -173,28 +150,10 @@ namespace Mono.CSharp {
                                CompletionSimpleName.AppendResults (
                                        results,
                                        partial_name, 
-                                       ec.CurrentTypeDefinition.NamespaceEntry.CompletionGetTypesStartingWith (namespaced_partial));
+                                       ec.CurrentMemberDefinition.Parent.NamespaceEntry.CompletionGetTypesStartingWith (namespaced_partial));
                        } else {
-                               MemberInfo [] result = expr_type.FindMembers (
-                                       MemberTypes.All, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public,
-                                       CollectingFilter, partial_name);
-
-                               foreach (MemberInfo r in result){
-                                       string name;
-                                       
-                                       MethodBase rasb = r as MethodBase;
-                                       if (rasb != null && rasb.IsSpecialName)
-                                               continue;
-                                       
-                                       if (partial_name == null)
-                                               name = r.Name;
-                                       else 
-                                               name = r.Name.Substring (partial_name.Length);
-                                       
-                                       if (results.Contains (name))
-                                               continue;
-                                       results.Add (name);
-                               }
+                               var r = MemberCache.GetCompletitionMembers (expr_type, partial_name).Select (l => l.Name);
+                               AppendResults (results, partial_name, r);
                        }
 
                        throw new CompletionResult (partial_name == null ? "" : partial_name, results.ToArray ());
@@ -222,29 +181,20 @@ namespace Mono.CSharp {
                
                protected override Expression DoResolve (ResolveContext ec)
                {
-                       MemberList members = TypeManager.FindMembers (
-                               ec.CurrentInitializerVariable.Type,
-                               MemberTypes.Field | MemberTypes.Property,
-                               BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public,
-                               CompletionMemberAccess.CollectingFilter, partial_name);
+                       var members = MemberCache.GetCompletitionMembers (ec.CurrentInitializerVariable.Type, partial_name);
 
-                       string [] result = new string [members.Count];
-                       int i = 0;
-                       foreach (MemberInfo mi in members){
-                               string name;
-                               
-                               if (partial_name == null)
-                                       name = mi.Name;
-                               else
-                                       name = mi.Name.Substring (partial_name.Length);
-                               
-                               result [i++] = name;
+// TODO: Does this mean exact match only ?
+//                     if (partial_name != null && results.Count > 0 && result [0] == "")
+//                             throw new CompletionResult ("", new string [] { "=" });
+
+                       var results = members.Where (l => (l.Kind & (MemberKind.Field | MemberKind.Property)) != 0).Select (l => l.Name).ToList ();
+                       if (partial_name != null) {
+                               var temp = new List<string> ();
+                               AppendResults (temp, partial_name, results);
+                               results = temp;
                        }
 
-                       if (partial_name != null && i > 0 && result [0] == "")
-                               throw new CompletionResult ("", new string [] { "=" });
-                       
-                       throw new CompletionResult (partial_name == null ? "" : partial_name, result);
+                       throw new CompletionResult (partial_name == null ? "" : partial_name, results.ToArray ());
                }
 
                protected override void CloneTo (CloneContext clonectx, Expression t)
index f25e56843da5450537ad30fd6f56b044ad265b0f..6b502c04f2b2986eb189a973afd4b72362c157ae 100644 (file)
@@ -17,7 +17,7 @@ namespace Mono.CSharp {
 
        public class Const : FieldBase
        {
-               bool define_called;
+               Constant value;
 
                public const Modifiers AllowedModifiers =
                        Modifiers.NEW |
@@ -37,34 +37,16 @@ namespace Mono.CSharp {
                        ModFlags |= Modifiers.STATIC;
                }
 
-               protected override bool CheckBase ()
-               {
-                       // Constant.Define can be called when the parent type hasn't yet been populated
-                       // and it's base types need not have been populated.  So, we defer this check
-                       // to the second time Define () is called on this member.
-                       if (Parent.PartialContainer.BaseCache == null)
-                               return true;
-                       return base.CheckBase ();
-               }
-
                /// <summary>
                ///   Defines the constant in the @parent
                /// </summary>
                public override bool Define ()
                {
-                       // Because constant define can be called from other class
-                       if (define_called) {
-                               CheckBase ();
-                               return FieldBuilder != null;
-                       }
-
-                       define_called = true;
-
                        if (!base.Define ())
                                return false;
 
-                       Type ttype = MemberType;
-                       if (!IsConstantTypeValid (ttype)) {
+                       TypeSpec ttype = MemberType;
+                       if (!ttype.IsConstantCompatible) {
                                Error_InvalidConstantType (ttype, Location, Report);
                        }
 
@@ -76,11 +58,10 @@ namespace Mono.CSharp {
                                field_attr |= FieldAttributes.Literal;
                        }
 
-                       FieldBuilder = Parent.TypeBuilder.DefineField (Name, MemberType, field_attr);
-                       spec = new ConstSpec (this, FieldBuilder, ModFlags, initializer);
+                       FieldBuilder = Parent.TypeBuilder.DefineField (Name, MemberType.GetMetaInfo (), field_attr);
+                       spec = new ConstSpec (Parent.Definition, this, MemberType, FieldBuilder, ModFlags, initializer);
 
-                       TypeManager.RegisterConstant (FieldBuilder, (ConstSpec) spec);
-                       Parent.MemberCache.AddMember (FieldBuilder, spec);
+                       Parent.MemberCache.AddMember (spec);
 
                        if ((field_attr & FieldAttributes.InitOnly) != 0)
                                Parent.PartialContainer.RegisterFieldForInitialization (this,
@@ -89,15 +70,12 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public static bool IsConstantTypeValid (Type t)
+               public Constant DefineValue ()
                {
-                       if (TypeManager.IsBuiltinOrEnum (t))
-                               return true;
-
-                       if (TypeManager.IsGenericParameter (t) || t.IsPointer)
-                               return false;
+                       if (value == null)
+                               value = initializer.Resolve (new ResolveContext (this)) as Constant;
 
-                       return TypeManager.IsReferenceType (t);
+                       return value;
                }
 
                /// <summary>
@@ -105,10 +83,6 @@ namespace Mono.CSharp {
                /// </summary>
                public override void Emit ()
                {
-                       var value = initializer.Resolve (new ResolveContext (this)) as Constant;
-                       if (value == null || FieldBuilder == null)
-                               return;
-
                        if (value.Type == TypeManager.decimal_type) {
                                FieldBuilder.SetCustomAttribute (CreateDecimalConstantAttribute (value));
                        } else{
@@ -137,9 +111,9 @@ namespace Mono.CSharp {
                        return new CustomAttributeBuilder (pa.Constructor, args);
                }
 
-               public static void Error_InvalidConstantType (Type t, Location loc, Report Report)
+               public static void Error_InvalidConstantType (TypeSpec t, Location loc, Report Report)
                {
-                       if (TypeManager.IsGenericParameter (t)) {
+                       if (t.IsGenericParameter) {
                                Report.Error (1959, loc,
                                        "Type parameter `{0}' cannot be declared const", TypeManager.CSharpName (t));
                        } else {
@@ -153,8 +127,8 @@ namespace Mono.CSharp {
        {
                Expression value;
 
-               public ConstSpec (IMemberDefinition definition, FieldInfo fi, Modifiers mod, Expression value)
-                       : base (definition, fi, mod)
+               public ConstSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, FieldInfo fi, Modifiers mod, Expression value)
+                       : base (declaringType, definition, memberType, fi, mod)
                {
                        this.value = value;
                }
@@ -163,7 +137,7 @@ namespace Mono.CSharp {
                        get {
                                return value;
                        }
-                       set {
+                       private set {
                                this.value = value;
                        }
                }
@@ -242,7 +216,6 @@ namespace Mono.CSharp {
                                expr = expr.Resolve (rc);
                        }
 
-
                        return expr;
                }
        }
index 12c7892d5fe44a39a2d61db05bb1da9427ae4e42..63fe0146a54054d68946e0816d63b52f8529eda4 100644 (file)
@@ -39,23 +39,6 @@ namespace Mono.CSharp {
                        return this.GetType ().Name + " (" + AsString () + ")";
                }
 
-               public override bool GetAttributableValue (ResolveContext ec, Type value_type, out object value)
-               {
-                       if (value_type == TypeManager.object_type) {
-                               value = GetTypedValue ();
-                               return true;
-                       }
-
-                       Constant c = ImplicitConversionRequired (ec, value_type, loc);
-                       if (c == null) {
-                               value = null;
-                               return false;
-                       }
-
-                       value = c.GetTypedValue ();
-                       return true;
-               }
-
                /// <summary>
                ///  This is used to obtain the actual value of the literal
                ///  cast into an object.
@@ -67,7 +50,7 @@ namespace Mono.CSharp {
                        return GetValue ();
                }
 
-               public override void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, Type target, bool expl)
+               public override void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, TypeSpec target, bool expl)
                {
                        if (!expl && IsLiteral && 
                                (TypeManager.IsPrimitiveType (target) || type == TypeManager.decimal_type) &&
@@ -79,7 +62,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               public Constant ImplicitConversionRequired (ResolveContext ec, Type type, Location loc)
+               public Constant ImplicitConversionRequired (ResolveContext ec, TypeSpec type, Location loc)
                {
                        Constant c = ConvertImplicitly (ec, type);
                        if (c == null)
@@ -88,7 +71,7 @@ namespace Mono.CSharp {
                        return c;
                }
 
-               public virtual Constant ConvertImplicitly (ResolveContext rc, Type type)
+               public virtual Constant ConvertImplicitly (ResolveContext rc, TypeSpec type)
                {
                        if (this.type == type)
                                return this;
@@ -113,12 +96,12 @@ namespace Mono.CSharp {
                //
                //  Returns a constant instance based on Type
                //
-               public static Constant CreateConstant (ResolveContext rc, Type t, object v, Location loc)
+               public static Constant CreateConstant (ResolveContext rc, TypeSpec t, object v, Location loc)
                {
                        return CreateConstantFromValue (t, v, loc).Resolve (rc);
                }
 
-               public static Constant CreateConstantFromValue (Type t, object v, Location loc)
+               public static Constant CreateConstantFromValue (TypeSpec t, object v, Location loc)
                {
                        if (t == TypeManager.int32_type)
                                return new IntConstant ((int) v, loc);
@@ -149,7 +132,7 @@ namespace Mono.CSharp {
                        if (t == TypeManager.decimal_type)
                                return new DecimalConstant ((decimal) v, loc);
                        if (TypeManager.IsEnumType (t)) {
-                               Type real_type = TypeManager.GetEnumUnderlyingType (t);
+                               var real_type = EnumSpec.GetUnderlyingType (t);
                                return new EnumConstant (CreateConstantFromValue (real_type, v, loc).Resolve (null), t);
                        }
                        if (v == null) {
@@ -179,12 +162,12 @@ namespace Mono.CSharp {
                /// It throws OverflowException 
                /// </summary>
                // DON'T CALL THIS METHOD DIRECTLY AS IT DOES NOT HANDLE ENUMS
-               public abstract Constant ConvertExplicitly (bool in_checked_context, Type target_type);
+               public abstract Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type);
 
                /// <summary>
                ///   Attempts to do a compile-time folding of a constant cast.
                /// </summary>
-               public Constant TryReduce (ResolveContext ec, Type target_type, Location loc)
+               public Constant TryReduce (ResolveContext ec, TypeSpec target_type, Location loc)
                {
                        try {
                                return TryReduce (ec, target_type);
@@ -201,14 +184,14 @@ namespace Mono.CSharp {
                        }
                }
 
-               Constant TryReduce (ResolveContext ec, Type target_type)
+               Constant TryReduce (ResolveContext ec, TypeSpec target_type)
                {
                        if (Type == target_type)
                                return this;
 
                        Constant c;
                        if (TypeManager.IsEnumType (target_type)) {
-                               c = TryReduce (ec, TypeManager.GetEnumUnderlyingType (target_type));
+                               c = TryReduce (ec, EnumSpec.GetUnderlyingType (target_type));
                                if (c == null)
                                        return null;
 
@@ -226,7 +209,7 @@ namespace Mono.CSharp {
                /// Need to pass type as the constant can require a boxing
                /// and in such case no optimization is possible
                /// </summary>
-               public bool IsDefaultInitializer (Type type)
+               public bool IsDefaultInitializer (TypeSpec type)
                {
                        if (type == Type)
                                return IsDefaultValue;
@@ -273,12 +256,7 @@ namespace Mono.CSharp {
 
                public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
                {
-                       return System.Linq.Expressions.Expression.Constant (GetTypedValue (), type);
-               }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       // A constant cannot be of generic type
+                       return System.Linq.Expressions.Expression.Constant (GetTypedValue (), type.GetMetaInfo ());
                }
 
                public new Constant Resolve (ResolveContext rc)
@@ -309,7 +287,7 @@ namespace Mono.CSharp {
                {
                }
 
-               public override void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, Type target, bool expl)
+               public override void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, TypeSpec target, bool expl)
                {
                        try {
                                ConvertExplicitly (true, target);
@@ -350,13 +328,18 @@ namespace Mono.CSharp {
                {
                        return (object) Value;
                }
+
+               public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
+               {
+                       enc.Stream.Write (Value);
+               }
                
                public override void Emit (EmitContext ec)
                {
                        if (Value)
-                               ec.ig.Emit (OpCodes.Ldc_I4_1);
+                               ec.Emit (OpCodes.Ldc_I4_1);
                        else
-                               ec.ig.Emit (OpCodes.Ldc_I4_0);
+                               ec.Emit (OpCodes.Ldc_I4_0);
                }
 
                public override bool IsDefaultValue {
@@ -375,7 +358,7 @@ namespace Mono.CSharp {
                        get { return Value == false; }
                }
 
-               public override Constant ConvertExplicitly (bool in_checked_context, Type target_type)
+               public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
                {
                        return null;
                }
@@ -391,9 +374,14 @@ namespace Mono.CSharp {
                        Value = v;
                }
 
+               public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
+               {
+                       enc.Stream.Write (Value);
+               }
+
                public override void Emit (EmitContext ec)
                {
-                       IntLiteral.EmitInt (ec.ig, Value);
+                       ec.EmitInt (Value);
                }
 
                public override string AsString ()
@@ -440,7 +428,7 @@ namespace Mono.CSharp {
                        get { return Value == 0; }
                }
 
-               public override Constant ConvertExplicitly (bool in_checked_context, Type target_type)
+               public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
                {
                        if (target_type == TypeManager.sbyte_type) {
                                if (in_checked_context){
@@ -491,9 +479,14 @@ namespace Mono.CSharp {
                        return this;
                }
 
+               public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
+               {
+                       enc.Stream.Write ((ushort) Value);
+               }
+
                public override void Emit (EmitContext ec)
                {
-                       IntLiteral.EmitInt (ec.ig, Value);
+                       ec.EmitInt (Value);
                }
 
                static string descape (char c)
@@ -551,7 +544,7 @@ namespace Mono.CSharp {
                        get { return Value == '\0'; }
                }
 
-               public override Constant ConvertExplicitly (bool in_checked_context, Type target_type)
+               public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
                {
                        if (target_type == TypeManager.byte_type) {
                                if (in_checked_context){
@@ -610,9 +603,14 @@ namespace Mono.CSharp {
                        return this;
                }
 
+               public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
+               {
+                       enc.Stream.Write (Value);
+               }
+
                public override void Emit (EmitContext ec)
                {
-                       IntLiteral.EmitInt (ec.ig, Value);
+                       ec.EmitInt (Value);
                }
 
                public override string AsString ()
@@ -652,7 +650,7 @@ namespace Mono.CSharp {
                        get { return Value == 0; }
                }
 
-               public override Constant ConvertExplicitly (bool in_checked_context, Type target_type)
+               public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
                {
                        if (target_type == TypeManager.byte_type) {
                                if (in_checked_context && Value < 0)
@@ -711,9 +709,14 @@ namespace Mono.CSharp {
                        return this;
                }
 
+               public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
+               {
+                       enc.Stream.Write (Value);
+               }
+
                public override void Emit (EmitContext ec)
                {
-                       IntLiteral.EmitInt (ec.ig, Value);
+                       ec.EmitInt (Value);
                }
 
                public override string AsString ()
@@ -753,7 +756,7 @@ namespace Mono.CSharp {
                        }
                }               
 
-               public override Constant ConvertExplicitly (bool in_checked_context, Type target_type)
+               public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
                {
                        if (target_type == TypeManager.byte_type) {
                                if (in_checked_context){
@@ -824,9 +827,14 @@ namespace Mono.CSharp {
                        return this;
                }
 
+               public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
+               {
+                       enc.Stream.Write (Value);
+               }
+
                public override void Emit (EmitContext ec)
                {
-                       IntLiteral.EmitInt (ec.ig, Value);
+                       ec.EmitInt (Value);
                }
 
                public override string AsString ()
@@ -866,7 +874,7 @@ namespace Mono.CSharp {
                        get { return Value == 0; }
                }
 
-               public override Constant ConvertExplicitly (bool in_checked_context, Type target_type)
+               public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
                {
                        if (target_type == TypeManager.byte_type) {
                                if (in_checked_context){
@@ -931,61 +939,14 @@ namespace Mono.CSharp {
                        return this;
                }
 
-               static public void EmitInt (ILGenerator ig, int i)
+               public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
                {
-                       switch (i){
-                       case -1:
-                               ig.Emit (OpCodes.Ldc_I4_M1);
-                               break;
-                               
-                       case 0:
-                               ig.Emit (OpCodes.Ldc_I4_0);
-                               break;
-                               
-                       case 1:
-                               ig.Emit (OpCodes.Ldc_I4_1);
-                               break;
-                               
-                       case 2:
-                               ig.Emit (OpCodes.Ldc_I4_2);
-                               break;
-                               
-                       case 3:
-                               ig.Emit (OpCodes.Ldc_I4_3);
-                               break;
-                               
-                       case 4:
-                               ig.Emit (OpCodes.Ldc_I4_4);
-                               break;
-                               
-                       case 5:
-                               ig.Emit (OpCodes.Ldc_I4_5);
-                               break;
-                               
-                       case 6:
-                               ig.Emit (OpCodes.Ldc_I4_6);
-                               break;
-                               
-                       case 7:
-                               ig.Emit (OpCodes.Ldc_I4_7);
-                               break;
-                               
-                       case 8:
-                               ig.Emit (OpCodes.Ldc_I4_8);
-                               break;
-
-                       default:
-                               if (i >= -128 && i <= 127){
-                                       ig.Emit (OpCodes.Ldc_I4_S, (sbyte) i);
-                               } else
-                                       ig.Emit (OpCodes.Ldc_I4, i);
-                               break;
-                       }
+                       enc.Stream.Write (Value);
                }
 
                public override void Emit (EmitContext ec)
                {
-                       EmitInt (ec.ig, Value);
+                       ec.EmitInt (Value);
                }
 
                public override string AsString ()
@@ -1025,7 +986,7 @@ namespace Mono.CSharp {
                        get { return Value == 0; }
                }
 
-               public override Constant ConvertExplicitly (bool in_checked_context, Type target_type)
+               public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
                {
                        if (target_type == TypeManager.byte_type) {
                                if (in_checked_context){
@@ -1086,7 +1047,7 @@ namespace Mono.CSharp {
                        return null;
                }
 
-               public override Constant ConvertImplicitly (ResolveContext rc, Type type)
+               public override Constant ConvertImplicitly (ResolveContext rc, TypeSpec type)
                {
                        if (this.type == type)
                                return this;
@@ -1103,7 +1064,7 @@ namespace Mono.CSharp {
                ///   into a different data type using casts (See Implicit Constant
                ///   Expression Conversions)
                /// </summary>
-               Constant TryImplicitIntConversion (Type target_type)
+               Constant TryImplicitIntConversion (TypeSpec target_type)
                {
                        if (target_type == TypeManager.sbyte_type) {
                                if (Value >= SByte.MinValue && Value <= SByte.MaxValue)
@@ -1159,9 +1120,14 @@ namespace Mono.CSharp {
                        return this;
                }
 
+               public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
+               {
+                       enc.Stream.Write (Value);
+               }
+
                public override void Emit (EmitContext ec)
                {
-                       IntLiteral.EmitInt (ec.ig, unchecked ((int) Value));
+                       ec.EmitInt (unchecked ((int) Value));
                }
 
                public override string AsString ()
@@ -1201,7 +1167,7 @@ namespace Mono.CSharp {
                        get { return Value == 0; }
                }
 
-               public override Constant ConvertExplicitly (bool in_checked_context, Type target_type)
+               public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
                {
                        if (target_type == TypeManager.byte_type) {
                                if (in_checked_context){
@@ -1277,26 +1243,14 @@ namespace Mono.CSharp {
                        return this;
                }
 
-               public override void Emit (EmitContext ec)
+               public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
                {
-                       EmitLong (ec.ig, Value);
+                       enc.Stream.Write (Value);
                }
 
-               static public void EmitLong (ILGenerator ig, long l)
+               public override void Emit (EmitContext ec)
                {
-                       if (l >= int.MinValue && l <= int.MaxValue) {
-                               IntLiteral.EmitInt (ig, unchecked ((int) l));
-                               ig.Emit (OpCodes.Conv_I8);
-                               return;
-                       }
-
-                       if (l >= 0 && l <= uint.MaxValue) {
-                               IntLiteral.EmitInt (ig, unchecked ((int) l));
-                               ig.Emit (OpCodes.Conv_U8);
-                               return;
-                       }
-                       
-                       ig.Emit (OpCodes.Ldc_I8, l);
+                       ec.EmitLong (Value);
                }
 
                public override string AsString ()
@@ -1336,7 +1290,7 @@ namespace Mono.CSharp {
                        get { return Value == 0; }
                }
 
-               public override Constant ConvertExplicitly (bool in_checked_context, Type target_type)
+               public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
                {
                        if (target_type == TypeManager.byte_type) {
                                if (in_checked_context){
@@ -1402,7 +1356,7 @@ namespace Mono.CSharp {
                        return null;
                }
 
-               public override Constant ConvertImplicitly (ResolveContext rc, Type type)
+               public override Constant ConvertImplicitly (ResolveContext rc, TypeSpec type)
                {
                        if (Value >= 0 && type == TypeManager.uint64_type) {
                                return new ULongConstant ((ulong) Value, loc).Resolve (rc);
@@ -1428,11 +1382,14 @@ namespace Mono.CSharp {
                        return this;
                }
 
-               public override void Emit (EmitContext ec)
+               public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
                {
-                       ILGenerator ig = ec.ig;
+                       enc.Stream.Write (Value);
+               }
 
-                       LongLiteral.EmitLong (ig, unchecked ((long) Value));
+               public override void Emit (EmitContext ec)
+               {
+                       ec.EmitLong (unchecked ((long) Value));
                }
 
                public override string AsString ()
@@ -1472,7 +1429,7 @@ namespace Mono.CSharp {
                        get { return Value == 0; }
                }
 
-               public override Constant ConvertExplicitly (bool in_checked_context, Type target_type)
+               public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
                {
                        if (target_type == TypeManager.byte_type) {
                                if (in_checked_context && Value > Byte.MaxValue)
@@ -1542,9 +1499,14 @@ namespace Mono.CSharp {
                        return this;
                }
 
+               public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
+               {
+                       enc.Stream.Write (Value);
+               }
+
                public override void Emit (EmitContext ec)
                {
-                       ec.ig.Emit (OpCodes.Ldc_R4, Value);
+                       ec.Emit (OpCodes.Ldc_R4, Value);
                }
 
                public override string AsString ()
@@ -1569,7 +1531,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override Constant ConvertExplicitly (bool in_checked_context, Type target_type)
+               public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
                {
                        if (target_type == TypeManager.byte_type) {
                                if (in_checked_context){
@@ -1660,9 +1622,14 @@ namespace Mono.CSharp {
                        return this;
                }
 
+               public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
+               {
+                       enc.Stream.Write (Value);
+               }
+
                public override void Emit (EmitContext ec)
                {
-                       ec.ig.Emit (OpCodes.Ldc_R8, Value);
+                       ec.Emit (OpCodes.Ldc_R8, Value);
                }
 
                public override string AsString ()
@@ -1687,7 +1654,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override Constant ConvertExplicitly (bool in_checked_context, Type target_type)
+               public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
                {
                        if (target_type == TypeManager.byte_type) {
                                if (in_checked_context){
@@ -1790,8 +1757,6 @@ namespace Mono.CSharp {
 
                public override void Emit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-
                        int [] words = decimal.GetBits (Value);
                        int power = (words [3] >> 16) & 0xff;
 
@@ -1805,8 +1770,8 @@ namespace Mono.CSharp {
                                                        return;
                                        }
 
-                                       IntConstant.EmitInt (ig, (int) Value);
-                                       ig.Emit (OpCodes.Newobj, TypeManager.void_decimal_ctor_int_arg);
+                                       ec.EmitInt ((int) Value);
+                                       ec.Emit (OpCodes.Newobj, TypeManager.void_decimal_ctor_int_arg);
                                        return;
                                }
 
@@ -1819,21 +1784,21 @@ namespace Mono.CSharp {
                                                        return;
                                        }
 
-                                       LongConstant.EmitLong (ig, (long) Value);
-                                       ig.Emit (OpCodes.Newobj, TypeManager.void_decimal_ctor_long_arg);
+                                       ec.EmitLong ((long) Value);
+                                       ec.Emit (OpCodes.Newobj, TypeManager.void_decimal_ctor_long_arg);
                                        return;
                                }
                        }
 
-                       IntConstant.EmitInt (ig, words [0]);
-                       IntConstant.EmitInt (ig, words [1]);
-                       IntConstant.EmitInt (ig, words [2]);
+                       ec.EmitInt (words [0]);
+                       ec.EmitInt (words [1]);
+                       ec.EmitInt (words [2]);
 
                        // sign
-                       IntConstant.EmitInt (ig, words [3] >> 31);
+                       ec.EmitInt (words [3] >> 31);
 
                        // power
-                       IntConstant.EmitInt (ig, power);
+                       ec.EmitInt (power);
 
                        if (TypeManager.void_decimal_ctor_five_args == null) {
                                TypeManager.void_decimal_ctor_five_args = TypeManager.GetPredefinedConstructor (
@@ -1844,7 +1809,7 @@ namespace Mono.CSharp {
                                        return;
                        }
 
-                       ig.Emit (OpCodes.Newobj, TypeManager.void_decimal_ctor_five_args);
+                       ec.Emit (OpCodes.Newobj, TypeManager.void_decimal_ctor_five_args);
                }
 
                public override bool IsDefaultValue {
@@ -1859,7 +1824,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override Constant ConvertExplicitly (bool in_checked_context, Type target_type)
+               public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
                {
                        if (target_type == TypeManager.sbyte_type)
                                return new SByteConstant ((sbyte)Value, loc);
@@ -1919,7 +1884,7 @@ namespace Mono.CSharp {
                public override void Emit (EmitContext ec)
                {
                        if (Value == null) {
-                               ec.ig.Emit (OpCodes.Ldnull);
+                               ec.Emit (OpCodes.Ldnull);
                                return;
                        }
 
@@ -1929,15 +1894,24 @@ namespace Mono.CSharp {
                        //
                        if (Value.Length == 0 && RootContext.Optimize && !TypeManager.IsEqual (ec.CurrentType, TypeManager.string_type)) {
                                if (TypeManager.string_empty == null)
-                                       TypeManager.string_empty = TypeManager.GetPredefinedField (TypeManager.string_type, "Empty", loc);
+                                       TypeManager.string_empty = TypeManager.GetPredefinedField (TypeManager.string_type, "Empty", loc, TypeManager.string_type);
 
                                if (TypeManager.string_empty != null) {
-                                       ec.ig.Emit (OpCodes.Ldsfld, TypeManager.string_empty);
+                                       ec.Emit (OpCodes.Ldsfld, TypeManager.string_empty);
                                        return;
                                }
                        }
 
-                       ec.ig.Emit (OpCodes.Ldstr, Value);
+                       ec.Emit (OpCodes.Ldstr, Value);
+               }
+
+               public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
+               {
+                       // cast to object
+                       if (type != targetType)
+                               enc.Encode (type);
+
+                       enc.Encode (Value);
                }
 
                public override bool IsDefaultValue {
@@ -1958,7 +1932,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override Constant ConvertExplicitly (bool in_checked_context, Type target_type)
+               public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
                {
                        return null;
                }
@@ -1969,7 +1943,7 @@ namespace Mono.CSharp {
        //
        public class NullConstant : Constant
        {
-               public NullConstant (Type type, Location loc)
+               public NullConstant (TypeSpec type, Location loc)
                        : base (loc)
                {
                        eclass = ExprClass.Value;
@@ -1986,13 +1960,30 @@ namespace Mono.CSharp {
                        return this;
                }
 
+               public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
+               {
+                       // Type it as string cast
+                       if (targetType == TypeManager.object_type || targetType == TypeManager.null_type)
+                               enc.Encode (TypeManager.string_type);
+
+                       var ac = targetType as ArrayContainer;
+                       if (ac != null) {
+                               if (ac.Rank != 1)
+                                       base.EncodeAttributeValue (rc, enc, targetType);
+                               else
+                                       enc.Stream.Write (uint.MaxValue);
+                       } else {
+                               enc.Stream.Write (byte.MaxValue);
+                       }
+               }
+
                public override void Emit (EmitContext ec)
                {
-                       ec.ig.Emit (OpCodes.Ldnull);
+                       ec.Emit (OpCodes.Ldnull);
 
                        // Only to make verifier happy
                        if (TypeManager.IsGenericParameter (type))
-                               ec.ig.Emit (OpCodes.Unbox_Any, type);
+                               ec.Emit (OpCodes.Unbox_Any, type);
                }
 
                public override string ExprClassName {
@@ -2006,7 +1997,7 @@ namespace Mono.CSharp {
                        return "null";
                }
 
-               public override Constant ConvertExplicitly (bool inCheckedContext, Type targetType)
+               public override Constant ConvertExplicitly (bool inCheckedContext, TypeSpec targetType)
                {
                        if (targetType.IsPointer) {
                                if (IsLiteral || this is NullPointer)
@@ -2031,7 +2022,7 @@ namespace Mono.CSharp {
                        return null;
                }
 
-               public override Constant ConvertImplicitly (ResolveContext rc, Type targetType)
+               public override Constant ConvertImplicitly (ResolveContext rc, TypeSpec targetType)
                {
                        return ConvertExplicitly (false, targetType);
                }
@@ -2056,11 +2047,6 @@ namespace Mono.CSharp {
                public override bool IsZeroInteger {
                        get { return true; }
                }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       type = storey.MutateType (type);
-               }
        }
 
        /// <summary>
@@ -2123,7 +2109,7 @@ namespace Mono.CSharp {
                        get { return value.IsZeroInteger; }
                }
 
-               public override Constant ConvertExplicitly (bool in_checked_context, Type target_type)
+               public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
                {
                        Constant new_value = value.ConvertExplicitly (in_checked_context, target_type);
                        return new_value == null ? null : new SideEffectConstant (new_value, side_effect, new_value.Location);
index 8a56cdcfb4953552dea7e1a60947d7206f286eb0..006c66cb60cf72a175c595df8cc7b8486bf82c41 100644 (file)
@@ -24,7 +24,7 @@ namespace Mono.CSharp
                //
                // A scope type context, it can be inflated for generic types
                //
-               Type CurrentType { get; }
+               TypeSpec CurrentType { get; }
 
                //
                // A scope type parameters either VAR or MVAR
@@ -32,21 +32,20 @@ namespace Mono.CSharp
                TypeParameter[] CurrentTypeParameters { get; }
 
                //
-               // A type definition of the type context. For partial types definition use
+               // A member definition of the context. For partial types definition use
                // CurrentTypeDefinition.PartialContainer otherwise the context is local
                //
-               // TODO: CurrentType.Definition
-               //
-               TypeContainer CurrentTypeDefinition { get; }
+               MemberCore CurrentMemberDefinition { get; }
 
                bool IsObsolete { get; }
                bool IsUnsafe { get; }
                bool IsStatic { get; }
+               bool HasUnresolvedConstraints { get; }
 
                string GetSignatureForError ();
 
-               ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc);
-               FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104);
+               ExtensionMethodGroupExpr LookupExtensionMethod (TypeSpec extensionType, string name, int arity, Location loc);
+               FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104);
                FullNamedExpression LookupNamespaceAlias (string name);
 
                CompilerContext Compiler { get; }
@@ -61,7 +60,7 @@ namespace Mono.CSharp
 
                public TypeInferenceContext ReturnTypeInference;
 
-               Type return_type;
+               TypeSpec return_type;
 
                /// <summary>
                ///   The location where return has to jump to return the
@@ -74,7 +73,7 @@ namespace Mono.CSharp
                /// </summary>
                public bool HasReturnLabel;
 
-               public BlockContext (IMemberContext mc, ExplicitBlock block, Type returnType)
+               public BlockContext (IMemberContext mc, ExplicitBlock block, TypeSpec returnType)
                        : base (mc)
                {
                        if (returnType == null)
@@ -180,7 +179,7 @@ namespace Mono.CSharp
                                HasReturnLabel = true;
                }
 
-               public Type ReturnType {
+               public TypeSpec ReturnType {
                        get { return return_type; }
                }
        }
@@ -362,7 +361,7 @@ namespace Mono.CSharp
                        get { return CurrentAnonymousMethod as Iterator; }
                }
 
-               public Type CurrentType {
+               public TypeSpec CurrentType {
                        get { return MemberContext.CurrentType; }
                }
 
@@ -370,8 +369,8 @@ namespace Mono.CSharp
                        get { return MemberContext.CurrentTypeParameters; }
                }
 
-               public TypeContainer CurrentTypeDefinition {
-                       get { return MemberContext.CurrentTypeDefinition; }
+               public MemberCore CurrentMemberDefinition {
+                       get { return MemberContext.CurrentMemberDefinition; }
                }
 
                public bool ConstantCheckState {
@@ -382,6 +381,10 @@ namespace Mono.CSharp
                        get { return (flags & Options.DoFlowAnalysis) != 0; }
                }
 
+               public bool HasUnresolvedConstraints {
+                       get { return false; }
+               }
+
                public bool IsInProbingMode {
                        get { return (flags & Options.ProbingMode) != 0; }
                }
@@ -473,14 +476,14 @@ namespace Mono.CSharp
                        get { return HasSet (Options.UnsafeScope) || MemberContext.IsUnsafe; }
                }
 
-               public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
+               public ExtensionMethodGroupExpr LookupExtensionMethod (TypeSpec extensionType, string name, int arity, Location loc)
                {
-                       return MemberContext.LookupExtensionMethod (extensionType, name, loc);
+                       return MemberContext.LookupExtensionMethod (extensionType, name, arity, loc);
                }
 
-               public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
+               public FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
                {
-                       return MemberContext.LookupNamespaceOrType (name, loc, ignore_cs0104);
+                       return MemberContext.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
                }
 
                public FullNamedExpression LookupNamespaceAlias (string name)
index 533f828c4ff0711e234d29a9ec36e87322642295..e719336077543bbb5f3b09b09feb327f50e3bb8d 100644 (file)
@@ -39,184 +39,119 @@ namespace Mono.CSharp {
                        implicit_conv = new DoubleHash (100);
                }
                
-               static Type TypeParam_EffectiveBaseType (GenericConstraints gc)
-               {
-                       var list = new List<Type> ();
-                       list.Add (gc.EffectiveBaseClass);
-                       foreach (Type t in gc.InterfaceConstraints) {
-                               if (!TypeManager.IsGenericParameter (t))
-                                       continue;
-
-                               GenericConstraints new_gc = TypeManager.GetTypeParameterConstraints (t);
-                               if (new_gc != null)
-                                       list.Add (TypeParam_EffectiveBaseType (new_gc));
-                       }
-                       return FindMostEncompassedType (list);
-               }
-
                //
                // From a one-dimensional array-type S[] to System.Collections.IList<T> and base
                // interfaces of this interface, provided there is an implicit reference conversion
                // from S to T.
                //
-               static bool Array_To_IList (Type array, Type list, bool isExplicit)
+               static bool ArrayToIList (ArrayContainer array, TypeSpec list, bool isExplicit)
                {
-                       if ((array.GetArrayRank () != 1) || !TypeManager.IsGenericType (list))
+                       if (array.Rank != 1 || !list.IsGeneric)
                                return false;
 
-                       Type gt = TypeManager.DropGenericTypeArguments (list);
-                       if ((gt != TypeManager.generic_ilist_type) &&
-                           (gt != TypeManager.generic_icollection_type) &&
-                           (gt != TypeManager.generic_ienumerable_type))
+                       var open_version = list.GetDefinition ();
+                       if ((open_version != TypeManager.generic_ilist_type) &&
+                               (open_version != TypeManager.generic_icollection_type) &&
+                               (open_version != TypeManager.generic_ienumerable_type))
                                return false;
 
-                       Type element_type = TypeManager.GetElementType (array);
-                       Type arg_type = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (list) [0]);
-
-                       if (element_type == arg_type)
+                       var arg_type = list.TypeArguments[0];
+                       if (array.Element == arg_type)
                                return true;
 
                        if (isExplicit)
-                               return ExplicitReferenceConversionExists (element_type, arg_type);
+                               return ExplicitReferenceConversionExists (array.Element, arg_type);
 
-                       Type t = TypeManager.GetElementType (array);
                        if (MyEmptyExpr == null)
-                               MyEmptyExpr = new EmptyExpression (t);
+                               MyEmptyExpr = new EmptyExpression (array.Element);
                        else
-                               MyEmptyExpr.SetType (t);
+                               MyEmptyExpr.SetType (array.Element);
 
                        return ImplicitReferenceConversionExists (MyEmptyExpr, arg_type);
                }
                
-               static bool IList_To_Array(Type list, Type array)
+               static bool IList_To_Array(TypeSpec list, ArrayContainer array)
                {
-                       if (!TypeManager.IsGenericType (list) || !array.IsArray || array.GetArrayRank() != 1)
+                       if (array.Rank != 1 || !list.IsGeneric)
                                return false;
-                       
-                       Type gt = TypeManager.DropGenericTypeArguments (list);
-                       if (gt != TypeManager.generic_ilist_type &&
-                               gt != TypeManager.generic_icollection_type &&
-                               gt != TypeManager.generic_ienumerable_type)
+
+                       var open_version = list.GetDefinition ();
+                       if ((open_version != TypeManager.generic_ilist_type) &&
+                               (open_version != TypeManager.generic_icollection_type) &&
+                               (open_version != TypeManager.generic_ienumerable_type))
                                return false;
-                       
-                       Type arg_type = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments(list)[0]);
-                       Type element_type = TypeManager.GetElementType(array);
-                       
-                       if (element_type == arg_type)
+
+                       var arg_type = list.TypeArguments[0];
+                       if (array.Element == arg_type)
                                return true;
                        
                        if (MyEmptyExpr == null)
-                               MyEmptyExpr = new EmptyExpression(element_type);
+                               MyEmptyExpr = new EmptyExpression (array.Element);
                        else
-                               MyEmptyExpr.SetType(element_type);
-                               
-                       return ImplicitReferenceConversionExists(MyEmptyExpr, arg_type) || ExplicitReferenceConversionExists(element_type, arg_type);
+                               MyEmptyExpr.SetType (array.Element);
+
+                       return ImplicitReferenceConversionExists (MyEmptyExpr, arg_type) || ExplicitReferenceConversionExists (array.Element, arg_type);
                }
 
-               static Expression ImplicitTypeParameterConversion (Expression expr,
-                                                                  Type target_type)
+               static Expression ImplicitTypeParameterConversion (Expression expr, TypeSpec target_type)
                {
-                       Type expr_type = expr.Type;
-
-                       GenericConstraints gc = TypeManager.GetTypeParameterConstraints (expr_type);
-
-                       if (gc == null) {
-                               if (target_type == TypeManager.object_type)
+                       var expr_type = (TypeParameterSpec) expr.Type;
+                       //
+                       // From T to a type parameter U
+                       //
+                       var ttype = target_type as TypeParameterSpec;
+                       if (ttype != null) {
+                               if (expr_type.IsReferenceType && !ttype.IsReferenceType)
                                        return new BoxedCast (expr, target_type);
 
-                               return null;
-                       }
-
-                       // We're converting from a type parameter which is known to be a reference type.
-                       Type base_type = TypeParam_EffectiveBaseType (gc);
-
-                       if (TypeManager.IsSubclassOf (base_type, target_type))
                                return new ClassCast (expr, target_type);
-
-                       if (target_type.IsInterface) {
-                               if (TypeManager.ImplementsInterface (base_type, target_type))
-                                       return new ClassCast (expr, target_type);
-
-                               foreach (Type t in gc.InterfaceConstraints) {
-                                       if (TypeManager.IsSubclassOf (t, target_type))
-                                               return new ClassCast (expr, target_type);
-                                       if (TypeManager.ImplementsInterface (t, target_type))
-                                               return new ClassCast (expr, target_type);
-                               }
                        }
 
-                       foreach (Type t in gc.InterfaceConstraints) {
-                               if (!TypeManager.IsGenericParameter (t))
-                                       continue;
-                               if (TypeManager.IsSubclassOf (t, target_type))
-                                       return new ClassCast (expr, target_type);
-                               if (TypeManager.ImplementsInterface (t, target_type))
+                       //
+                       // From T to its effective base class C
+                       // From T to any base class of C
+                       // From T to any interface implemented by C
+                       //
+                       var base_type = expr_type.BaseType;
+                       if (base_type == target_type || TypeManager.IsSubclassOf (base_type, target_type) || base_type.ImplementsInterface (target_type)) {
+                               if (expr_type.IsReferenceType)
                                        return new ClassCast (expr, target_type);
-                       }
-
-                       return null;
-               }
-
-               static bool ImplicitTypeParameterBoxingConversion (Type expr_type, Type target_type,
-                                                                  out bool use_class_cast)
-               {
-                       GenericConstraints gc = TypeManager.GetTypeParameterConstraints (expr_type);
 
-                       if (gc == null) {
-                               use_class_cast = false;
-                               return target_type == TypeManager.object_type;
+                               return new BoxedCast (expr, target_type);
                        }
 
-                       use_class_cast = true;
-
-                       if (!gc.HasReferenceTypeConstraint)
-                               return false;
-
-                       // We're converting from a type parameter which is known to be a reference type.
-                       Type base_type = TypeParam_EffectiveBaseType (gc);
-
-                       if (TypeManager.IsSubclassOf (base_type, target_type))
-                               return true;
+                       base_type = expr_type.GetEffectiveBase ();
 
-                       if (target_type.IsInterface) {
-                               if (TypeManager.ImplementsInterface (base_type, target_type))
-                                       return true;
+                       var effective_ifaces = expr_type.Interfaces;
+                       if (effective_ifaces != null) {
+                               foreach (var t in effective_ifaces) {
+                                       if (t == target_type || t.ImplementsInterface (target_type)) {
+                                               if (expr_type.IsReferenceType)
+                                                       return new ClassCast (expr, target_type);
 
-                               foreach (Type t in gc.InterfaceConstraints) {
-                                       if (TypeManager.IsSubclassOf (t, target_type))
-                                               return true;
-                                       if (TypeManager.ImplementsInterface (t, target_type))
-                                               return true;
+                                               return new BoxedCast (expr, target_type);
+                                       }
                                }
                        }
 
-                       foreach (Type t in gc.InterfaceConstraints) {
-                               if (!TypeManager.IsGenericParameter (t))
-                                       continue;
-                               if (TypeManager.IsSubclassOf (t, target_type))
-                                       return true;
-                               if (TypeManager.ImplementsInterface (t, target_type))
-                                       return true;
-                       }
-
-                       use_class_cast = false;
-                       return false;
+                       return null;
                }
 
-               static Expression ExplicitTypeParameterConversion (Expression source, Type source_type, Type target_type)
+               static Expression ExplicitTypeParameterConversion (Expression source, TypeSpec source_type, TypeSpec target_type)
                {
-                       if (TypeManager.IsGenericParameter (target_type)) {
-                               GenericConstraints gc = TypeManager.GetTypeParameterConstraints (target_type);
-                               if (gc == null)
-                                       return null;
-
-                               foreach (Type iface in gc.InterfaceConstraints) {
-                                       if (!TypeManager.IsGenericParameter (iface))
-                                               continue;
+                       var target_tp = target_type as TypeParameterSpec;
+                       if (target_tp != null) {
+                               if (target_tp.Interfaces != null) {
+                                       foreach (TypeSpec iface in target_tp.Interfaces) {
+                                               if (!TypeManager.IsGenericParameter (iface))
+                                                       continue;
 
-                                       if (TypeManager.IsSubclassOf (source_type, iface))
-                                               return source == null ? EmptyExpression.Null : new ClassCast (source, target_type, true);
+                                               if (TypeManager.IsSubclassOf (source_type, iface))
+                                                       return source == null ? EmptyExpression.Null : new ClassCast (source, target_type, true);
+                                       }
                                }
+
+                               return null;
                        }
 
                        if (target_type.IsInterface)
@@ -225,9 +160,9 @@ namespace Mono.CSharp {
                        return null;
                }
 
-               static Expression ImplicitReferenceConversion (Expression expr, Type target_type, bool explicit_cast)
+               static Expression ImplicitReferenceConversion (Expression expr, TypeSpec target_type, bool explicit_cast)
                {
-                       Type expr_type = expr.Type;
+                       TypeSpec expr_type = expr.Type;
 
                        if (expr_type == null && expr.eclass == ExprClass.MethodGroup){
                                // if we are a method group, emit a warning
@@ -238,7 +173,7 @@ namespace Mono.CSharp {
                        if (expr_type == TypeManager.void_type)
                                return null;
 
-                       if (TypeManager.IsGenericParameter (expr_type))
+                       if (expr_type.Kind == MemberKind.TypeParameter)
                                return ImplicitTypeParameterConversion (expr, target_type);
 
                        //
@@ -273,12 +208,12 @@ namespace Mono.CSharp {
                //
                // 6.1.6 Implicit reference conversions
                //
-               public static bool ImplicitReferenceConversionExists (Expression expr, Type target_type)
+               public static bool ImplicitReferenceConversionExists (Expression expr, TypeSpec target_type)
                {
                        if (TypeManager.IsStruct (target_type))
                                return false;
 
-                       Type expr_type = expr.Type;
+                       TypeSpec expr_type = expr.Type;
 
                        // from the null type to any reference-type.
                        if (expr_type == TypeManager.null_type)
@@ -287,11 +222,23 @@ namespace Mono.CSharp {
                        if (TypeManager.IsGenericParameter (expr_type))
                                return ImplicitTypeParameterConversion (expr, target_type) != null;
 
+                       // This code is kind of mirrored inside ImplicitStandardConversionExists
+                       // with the small distinction that we only probe there
+                       //
+                       // Always ensure that the code here and there is in sync
+
+                       // from any class-type S to any interface-type T.
+                       if (target_type.IsInterface) {
+                               if (expr_type.ImplementsInterface (target_type)){
+                                       return !TypeManager.IsValueType (expr_type);
+                               }
+                       }
+
                        //
                        // notice that it is possible to write "ValueType v = 1", the ValueType here
                        // is an abstract class, and not really a value type, so we apply the same rules.
                        //
-                       if (target_type == TypeManager.object_type || TypeManager.IsDynamicType (target_type)) {
+                       if (target_type == TypeManager.object_type || target_type == InternalType.Dynamic) {
                                //
                                // A pointer type cannot be converted to object
                                //
@@ -301,11 +248,19 @@ namespace Mono.CSharp {
                                if (TypeManager.IsValueType (expr_type))
                                        return false;
 
-                               if (expr_type.IsClass || expr_type.IsInterface || expr_type == TypeManager.enum_type){
+                               if (expr_type.IsClass || expr_type.IsInterface || expr_type == TypeManager.enum_type || expr_type.IsDelegate) {
                                        // No mcs internal types are convertible
-                                       return expr_type.Module != typeof (Convert).Module;
+                                       return true; // expr_type.MetaInfo.Module != typeof (Convert).Module;
                                }
 
+                               // From anything to dynamic
+                               if (target_type == InternalType.Dynamic)
+                                       return true;
+
+                               // From dynamic to object
+                               if (expr_type == InternalType.Dynamic)
+                                       return true;
+
                                return false;
                        } else if (target_type == TypeManager.value_type) {
                                return expr_type == TypeManager.enum_type;
@@ -317,35 +272,31 @@ namespace Mono.CSharp {
                                //
                                if (target_type == TypeManager.enum_type || TypeManager.IsGenericParameter (expr_type))
                                        return false;
-                               
-                               return true;
-                       }
 
-                       // This code is kind of mirrored inside ImplicitStandardConversionExists
-                       // with the small distinction that we only probe there
-                       //
-                       // Always ensure that the code here and there is in sync
+                               if (TypeManager.IsValueType (expr_type))
+                                       return false;
 
-                       // from any class-type S to any interface-type T.
-                       if (target_type.IsInterface) {
-                               if (TypeManager.ImplementsInterface (expr_type, target_type)){
-                                       return !TypeManager.IsGenericParameter (expr_type) &&
-                                               !TypeManager.IsValueType (expr_type);
-                               }
+                               // Array type variance conversion
+                               //if (target_type.IsArray != expr_type.IsArray)
+                               //      return false;
+
+                               return true;
                        }
 
-                       if (expr_type.IsArray) {
+                       var expr_type_array = expr_type as ArrayContainer;
+                       if (expr_type_array != null) {
+                               var target_type_array = target_type as ArrayContainer;
                                // from an array-type S to an array-type of type T
-                               if (target_type.IsArray && expr_type.GetArrayRank () == target_type.GetArrayRank ()) {
+                               if (target_type_array != null && expr_type_array.Rank == target_type_array.Rank) {
 
                                        //
                                        // Both SE and TE are reference-types
                                        //
-                                       Type expr_element_type = TypeManager.GetElementType (expr_type);
+                                       TypeSpec expr_element_type = expr_type_array.Element;
                                        if (!TypeManager.IsReferenceType (expr_element_type))
                                                return false;
 
-                                       Type target_element_type = TypeManager.GetElementType (target_type);
+                                       TypeSpec target_element_type = target_type_array.Element;
                                        if (!TypeManager.IsReferenceType (target_element_type))
                                                return false;
 
@@ -362,23 +313,23 @@ namespace Mono.CSharp {
                                        return true;
 
                                // from an array-type of type T to IList<T>
-                               if (Array_To_IList (expr_type, target_type, false))
+                               if (ArrayToIList (expr_type_array, target_type, false))
                                        return true;
 
                                return false;
                        }
 
-                       if (TypeManager.IsVariantOf (expr_type, target_type))
+                       if (TypeSpecComparer.Variant.IsEqual (expr_type, target_type))
                                return true;
 
                        // from any interface type S to interface-type T.
                        if (expr_type.IsInterface && target_type.IsInterface) {
-                               return TypeManager.ImplementsInterface (expr_type, target_type);
+                               return expr_type.ImplementsInterface (target_type);
                        }
 
                        // from any delegate type to System.Delegate
                        if (target_type == TypeManager.delegate_type &&
-                               (expr_type == TypeManager.delegate_type || TypeManager.IsDelegateType (expr_type)))
+                               (expr_type == TypeManager.delegate_type || expr_type.IsDelegate))
                                return true;
 
                        if (TypeManager.IsEqual (expr_type, target_type))
@@ -387,16 +338,16 @@ namespace Mono.CSharp {
                        return false;
                }
 
-               public static bool ImplicitBoxingConversionExists (Expression expr, Type target_type,
+               public static bool ImplicitBoxingConversionExists (Expression expr, TypeSpec target_type,
                                                                   out bool use_class_cast)
                {
-                       Type expr_type = expr.Type;
+                       TypeSpec expr_type = expr.Type;
                        use_class_cast = false;
                        
                        //
                        // From any value-type to the type object.
                        //
-                       if (target_type == TypeManager.object_type || TypeManager.IsDynamicType (target_type)) {
+                       if (target_type == TypeManager.object_type || target_type == InternalType.Dynamic) {
                                //
                                // A pointer type cannot be converted to object
                                //
@@ -422,7 +373,7 @@ namespace Mono.CSharp {
                                // From any nullable-type with an underlying enum-type to the type System.Enum
                                //
                                if (TypeManager.IsNullableType (expr_type))
-                                       return TypeManager.IsEnumType (TypeManager.GetTypeArguments (expr_type) [0]);
+                                       return TypeManager.IsEnumType (Nullable.NullableInfo.GetUnderlyingType (expr_type));
                        }
 
                        if (TypeManager.IsSubclassOf (expr_type, target_type)) {
@@ -442,21 +393,23 @@ namespace Mono.CSharp {
 
                        // from any class-type S to any interface-type T.
                        if (target_type.IsInterface) {
-                               if (TypeManager.ImplementsInterface (expr_type, target_type))
+                               if (expr_type.ImplementsInterface (target_type))
                                        return TypeManager.IsGenericParameter (expr_type) ||
                                                TypeManager.IsValueType (expr_type);
                        }
 
-                       if (TypeManager.IsGenericParameter (expr_type))
-                               return ImplicitTypeParameterBoxingConversion (
-                                       expr_type, target_type, out use_class_cast);
+                       if (TypeManager.IsGenericParameter (expr_type)) {
+                               return ImplicitTypeParameterConversion (expr, target_type) != null;
+//                             return ImplicitTypeParameterBoxingConversion (
+//                                     expr_type, target_type, out use_class_cast);
+                       }
 
                        return false;
                }
 
-               public static Expression ImplicitNulableConversion (ResolveContext ec, Expression expr, Type target_type)
+               public static Expression ImplicitNulableConversion (ResolveContext ec, Expression expr, TypeSpec target_type)
                {
-                       Type expr_type = expr.Type;
+                       TypeSpec expr_type = expr.Type;
 
                        //
                        // From null to any nullable type
@@ -465,11 +418,11 @@ namespace Mono.CSharp {
                                return ec == null ? EmptyExpression.Null : Nullable.LiftedNull.Create (target_type, expr.Location);
 
                        // S -> T?
-                       Type t_el = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (target_type)[0]);
+                       TypeSpec t_el = TypeManager.GetTypeArguments (target_type)[0];
 
                        // S? -> T?
                        if (TypeManager.IsNullableType (expr_type))
-                               expr_type = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (expr_type)[0]);
+                               expr_type = TypeManager.GetTypeArguments (expr_type)[0];
 
                        //
                        // Predefined implicit identity or implicit numeric conversion
@@ -510,12 +463,12 @@ namespace Mono.CSharp {
                ///   expr is the expression to convert, returns a new expression of type
                ///   target_type or null if an implicit conversion is not possible.
                /// </summary>
-               public static Expression ImplicitNumericConversion (Expression expr, Type target_type)
+               public static Expression ImplicitNumericConversion (Expression expr, TypeSpec target_type)
                {
                        return ImplicitNumericConversion (expr, expr.Type, target_type);
                }
 
-               static Expression ImplicitNumericConversion (Expression expr, Type expr_type, Type target_type)
+               static Expression ImplicitNumericConversion (Expression expr, TypeSpec expr_type, TypeSpec target_type)
                {
                        if (expr_type == TypeManager.sbyte_type){
                                //
@@ -663,14 +616,13 @@ namespace Mono.CSharp {
                ///  Same as ImplicitStandardConversionExists except that it also looks at
                ///  implicit user defined conversions - needed for overload resolution
                /// </summary>
-               public static bool ImplicitConversionExists (ResolveContext ec, Expression expr, Type target_type)
+               public static bool ImplicitConversionExists (ResolveContext ec, Expression expr, TypeSpec target_type)
                {
                        if (ImplicitStandardConversionExists (expr, target_type))
                                return true;
 
                        if (expr.Type == InternalType.AnonymousMethod) {
-                               if (!TypeManager.IsDelegateType (target_type) &&
-                                       TypeManager.DropGenericTypeArguments (target_type) != TypeManager.expression_type)
+                               if (!TypeManager.IsDelegateType (target_type) && target_type.GetDefinition () != TypeManager.expression_type)
                                        return false;
 
                                AnonymousMethodExpression ame = (AnonymousMethodExpression) expr;
@@ -678,7 +630,7 @@ namespace Mono.CSharp {
                        }
                        
                        if (expr.eclass == ExprClass.MethodGroup) {
-                               if (TypeManager.IsDelegateType (target_type) && RootContext.Version != LanguageVersion.ISO_1) {
+                               if (target_type.IsDelegate && RootContext.Version != LanguageVersion.ISO_1) {
                                        MethodGroupExpr mg = expr as MethodGroupExpr;
                                        if (mg != null)
                                                return DelegateCreation.ImplicitStandardConversionExists (ec, mg, target_type);
@@ -696,9 +648,9 @@ namespace Mono.CSharp {
                ///
                ///  ec should point to a real EmitContext if expr.Type is TypeManager.anonymous_method_type.
                /// </summary>
-               public static bool ImplicitStandardConversionExists (Expression expr, Type target_type)
+               public static bool ImplicitStandardConversionExists (Expression expr, TypeSpec target_type)
                {
-                       Type expr_type = expr.Type;
+                       TypeSpec expr_type = expr.Type;
 
                        if (expr_type == TypeManager.null_type) {
                                NullLiteral nl = expr as NullLiteral;
@@ -758,7 +710,7 @@ namespace Mono.CSharp {
                                                return true;
                                }
 
-                               if (value == 0 && TypeManager.IsEnumType (target_type))
+                               if (value == 0 && target_type.IsEnum)
                                        return true;
                        }
 
@@ -777,7 +729,7 @@ namespace Mono.CSharp {
                        // If `expr_type' implements `target_type' (which is an iface)
                        // see TryImplicitIntConversion
                        //
-                       if (target_type.IsInterface && TypeManager.ImplementsInterface (expr_type, target_type))
+                       if (target_type.IsInterface && expr_type.ImplementsInterface (target_type))
                                return true;
 
                        if (target_type == TypeManager.void_ptr_type && expr_type.IsPointer)
@@ -794,19 +746,12 @@ namespace Mono.CSharp {
                ///  Finds "most encompassed type" according to the spec (13.4.2)
                ///  amongst the methods in the MethodGroupExpr
                /// </summary>
-               static Type FindMostEncompassedType (IList<Type> types)
+               public static TypeSpec FindMostEncompassedType (IEnumerable<TypeSpec> types)
                {
-                       Type best = null;
-
-                       if (types.Count == 0)
-                               return null;
-
-                       if (types.Count == 1)
-                               return (Type) types [0];
-
+                       TypeSpec best = null;
                        EmptyExpression expr = EmptyExpression.Grab ();
 
-                       foreach (Type t in types) {
+                       foreach (TypeSpec t in types) {
                                if (best == null) {
                                        best = t;
                                        continue;
@@ -818,7 +763,7 @@ namespace Mono.CSharp {
                        }
 
                        expr.SetType (best);
-                       foreach (Type t in types) {
+                       foreach (TypeSpec t in types) {
                                if (best == t)
                                        continue;
                                if (!ImplicitStandardConversionExists (expr, t)) {
@@ -836,9 +781,9 @@ namespace Mono.CSharp {
                ///  Finds "most encompassing type" according to the spec (13.4.2)
                ///  amongst the types in the given set
                /// </summary>
-               static Type FindMostEncompassingType (IList<Type> types)
+               static TypeSpec FindMostEncompassingType (IList<TypeSpec> types)
                {
-                       Type best = null;
+                       TypeSpec best = null;
 
                        if (types.Count == 0)
                                return null;
@@ -848,7 +793,7 @@ namespace Mono.CSharp {
 
                        EmptyExpression expr = EmptyExpression.Grab ();
 
-                       foreach (Type t in types) {
+                       foreach (TypeSpec t in types) {
                                if (best == null) {
                                        best = t;
                                        continue;
@@ -859,7 +804,7 @@ namespace Mono.CSharp {
                                        best = t;
                        }
 
-                       foreach (Type t in types) {
+                       foreach (TypeSpec t in types) {
                                if (best == t)
                                        continue;
                                expr.SetType (t);
@@ -879,17 +824,17 @@ namespace Mono.CSharp {
                ///   by making use of FindMostEncomp* methods. Applies the correct rules separately
                ///   for explicit and implicit conversion operators.
                /// </summary>
-               static public Type FindMostSpecificSource (IList<MethodSpec> list,
+               static public TypeSpec FindMostSpecificSource (IList<MethodSpec> list,
                                                           Expression source, bool apply_explicit_conv_rules)
                {
-                       var src_types_set = new List<Type> ();
+                       var src_types_set = new List<TypeSpec> ();
 
                        //
                        // If any operator converts from S then Sx = S
                        //
-                       Type source_type = source.Type;
+                       TypeSpec source_type = source.Type;
                        foreach (var mb in list){
-                               Type param_type = mb.Parameters.Types [0];
+                               TypeSpec param_type = mb.Parameters.Types [0];
 
                                if (param_type == source_type)
                                        return param_type;
@@ -901,9 +846,9 @@ namespace Mono.CSharp {
                        // Explicit Conv rules
                        //
                        if (apply_explicit_conv_rules) {
-                               var candidate_set = new List<Type> ();
+                               var candidate_set = new List<TypeSpec> ();
 
-                               foreach (Type param_type in src_types_set){
+                               foreach (TypeSpec param_type in src_types_set){
                                        if (ImplicitStandardConversionExists (source, param_type))
                                                candidate_set.Add (param_type);
                                }
@@ -924,16 +869,16 @@ namespace Mono.CSharp {
                /// <summary>
                ///  Finds the most specific target Tx according to section 13.4.4
                /// </summary>
-               static public Type FindMostSpecificTarget (IList<MethodSpec> list,
-                                                          Type target, bool apply_explicit_conv_rules)
+               static public TypeSpec FindMostSpecificTarget (IList<MethodSpec> list,
+                                                          TypeSpec target, bool apply_explicit_conv_rules)
                {
-                       var tgt_types_set = new List<Type> ();
+                       var tgt_types_set = new List<TypeSpec> ();
 
                        //
                        // If any operator converts to T then Tx = T
                        //
                        foreach (var mi in list){
-                               Type ret_type = TypeManager.TypeToCoreType (mi.ReturnType);
+                               TypeSpec ret_type = mi.ReturnType;
                                if (ret_type == target)
                                        return ret_type;
 
@@ -944,11 +889,11 @@ namespace Mono.CSharp {
                        // Explicit conv rules
                        //
                        if (apply_explicit_conv_rules) {
-                               var candidate_set = new List<Type> ();
+                               var candidate_set = new List<TypeSpec> ();
 
                                EmptyExpression expr = EmptyExpression.Grab ();
 
-                               foreach (Type ret_type in tgt_types_set){
+                               foreach (TypeSpec ret_type in tgt_types_set){
                                        expr.SetType (ret_type);
 
                                        if (ImplicitStandardConversionExists (expr, target))
@@ -974,7 +919,7 @@ namespace Mono.CSharp {
                ///  User-defined Implicit conversions
                /// </summary>
                static public Expression ImplicitUserConversion (ResolveContext ec, Expression source,
-                                                                Type target, Location loc)
+                                                                TypeSpec target, Location loc)
                {
                        return UserDefinedConversion (ec, source, target, loc, false, true);
                }
@@ -983,20 +928,20 @@ namespace Mono.CSharp {
                ///  User-defined Explicit conversions
                /// </summary>
                static Expression ExplicitUserConversion (ResolveContext ec, Expression source,
-                                                                Type target, Location loc)
+                                                                TypeSpec target, Location loc)
                {
                        return UserDefinedConversion (ec, source, target, loc, true, true);
                }
 
                static void AddConversionOperators (List<MethodSpec> list,
-                                                   Expression source, Type target_type,
+                                                   Expression source, TypeSpec target_type,
                                                    bool look_for_explicit,
                                                    MethodGroupExpr mg)
                {
                        if (mg == null)
                                return;
 
-                       Type source_type = source.Type;
+                       TypeSpec source_type = source.Type;
                        EmptyExpression expr = EmptyExpression.Grab ();
 
                        //
@@ -1012,10 +957,10 @@ namespace Mono.CSharp {
                                        target_type = TypeManager.uint64_type;
                        }
 
-                       foreach (var m in mg.Methods) {
+                       foreach (MethodSpec m in mg.Methods) {
                                AParametersCollection pd = m.Parameters;
-                               Type return_type = TypeManager.TypeToCoreType (m.ReturnType);
-                               Type arg_type = pd.Types [0];
+                               TypeSpec return_type = m.ReturnType;
+                               TypeSpec arg_type = pd.Types [0];
 
                                if (source_type != arg_type) {
                                        if (!ImplicitStandardConversionExists (source, arg_type)) {
@@ -1052,47 +997,47 @@ namespace Mono.CSharp {
                ///   Compute the user-defined conversion operator from source_type to target_type.
                ///   `look_for_explicit' controls whether we should also include the list of explicit operators
                /// </summary>
-               static MethodSpec GetConversionOperator (CompilerContext ctx, Type container_type, Expression source, Type target_type, bool look_for_explicit)
+               static MethodSpec GetConversionOperator (CompilerContext ctx, TypeSpec container_type, Expression source, TypeSpec target_type, bool look_for_explicit)
                {
                        var ops = new List<MethodSpec> (4);
 
-                       Type source_type = source.Type;
+                       TypeSpec source_type = source.Type;
 
                        if (source_type != TypeManager.decimal_type) {
                                AddConversionOperators (ops, source, target_type, look_for_explicit,
-                                       Expression.MethodLookup (ctx, container_type, source_type, "op_Implicit", Location.Null) as MethodGroupExpr);
+                                       Expression.MethodLookup (ctx, container_type, source_type, MemberKind.Operator, "op_Implicit", 0, Location.Null));
                                if (look_for_explicit) {
                                        AddConversionOperators (ops, source, target_type, look_for_explicit,
                                                Expression.MethodLookup (ctx,
-                                                       container_type, source_type, "op_Explicit", Location.Null) as MethodGroupExpr);
+                                                       container_type, source_type, MemberKind.Operator, "op_Explicit", 0, Location.Null));
                                }
                        }
 
                        if (target_type != TypeManager.decimal_type) {
                                AddConversionOperators (ops, source, target_type, look_for_explicit,
-                                       Expression.MethodLookup (ctx, container_type, target_type, "op_Implicit", Location.Null) as MethodGroupExpr);
+                                       Expression.MethodLookup (ctx, container_type, target_type, MemberKind.Operator, "op_Implicit", 0, Location.Null));
                                if (look_for_explicit) {
                                        AddConversionOperators (ops, source, target_type, look_for_explicit,
                                                Expression.MethodLookup (ctx,
-                                                       container_type, target_type, "op_Explicit", Location.Null) as MethodGroupExpr);
+                                                       container_type, target_type, MemberKind.Operator, "op_Explicit", 0, Location.Null));
                                }
                        }
 
                        if (ops.Count == 0)
                                return null;
 
-                       Type most_specific_source = FindMostSpecificSource (ops, source, look_for_explicit);
+                       TypeSpec most_specific_source = FindMostSpecificSource (ops, source, look_for_explicit);
                        if (most_specific_source == null)
                                return null;
 
-                       Type most_specific_target = FindMostSpecificTarget (ops, target_type, look_for_explicit);
+                       TypeSpec most_specific_target = FindMostSpecificTarget (ops, target_type, look_for_explicit);
                        if (most_specific_target == null)
                                return null;
 
                        MethodSpec method = null;
 
                        foreach (var m in ops) {
-                               if (TypeManager.TypeToCoreType (m.ReturnType) != most_specific_target)
+                               if (m.ReturnType != most_specific_target)
                                        continue;
                                if (m.Parameters.Types [0] != most_specific_source)
                                        continue;
@@ -1109,10 +1054,10 @@ namespace Mono.CSharp {
                ///   User-defined conversions
                /// </summary>
                public static Expression UserDefinedConversion (ResolveContext ec, Expression source,
-                                                               Type target, Location loc,
+                                                               TypeSpec target, Location loc,
                                                                bool look_for_explicit, bool return_convert)
                {
-                       Type source_type = source.Type;
+                       TypeSpec source_type = source.Type;
                        MethodSpec method = null;
                        Expression expr = null;
 
@@ -1131,14 +1076,14 @@ namespace Mono.CSharp {
                        if (!(source is Constant) && hash.Lookup (source_type, target, out o)) {
                                method = (MethodSpec) o;
                        } else {
-                               if (TypeManager.IsDynamicType (source_type))
+                               if (source_type == InternalType.Dynamic)
                                        return null;
 
                                method = GetConversionOperator (ec.Compiler, null, source, target, look_for_explicit);
                        }
 
                        if (method != null) {
-                               Type most_specific_source = method.Parameters.Types[0];
+                               TypeSpec most_specific_source = method.Parameters.Types[0];
 
                                //
                                // This will do the conversion to the best match that we
@@ -1171,7 +1116,7 @@ namespace Mono.CSharp {
                                        nullable = true;
                                }
 
-                               Type target_underlying;
+                               TypeSpec target_underlying;
                                if (TypeManager.IsNullableType (target)) {
                                        target_underlying = TypeManager.GetTypeArguments (target)[0];
                                        nullable = true;
@@ -1216,7 +1161,7 @@ namespace Mono.CSharp {
                ///   in a context that expects a `target_type'.
                /// </summary>
                static public Expression ImplicitConversion (ResolveContext ec, Expression expr,
-                                                            Type target_type, Location loc)
+                                                            TypeSpec target_type, Location loc)
                {
                        Expression e;
 
@@ -1246,12 +1191,12 @@ namespace Mono.CSharp {
                ///   user defined implicit conversions are excluded.
                /// </summary>
                static public Expression ImplicitConversionStandard (ResolveContext ec, Expression expr,
-                                                                    Type target_type, Location loc)
+                                                                    TypeSpec target_type, Location loc)
                {
                        return ImplicitConversionStandard (ec, expr, target_type, loc, false);
                }
 
-               static Expression ImplicitConversionStandard (ResolveContext ec, Expression expr, Type target_type, Location loc, bool explicit_cast)
+               static Expression ImplicitConversionStandard (ResolveContext ec, Expression expr, TypeSpec target_type, Location loc, bool explicit_cast)
                {
                        if (expr.eclass == ExprClass.MethodGroup){
                                if (!TypeManager.IsDelegateType (target_type)){
@@ -1269,7 +1214,7 @@ namespace Mono.CSharp {
                                }
                        }
 
-                       Type expr_type = expr.Type;
+                       TypeSpec expr_type = expr.Type;
                        Expression e;
 
                        if (expr_type.Equals (target_type)) {
@@ -1278,7 +1223,7 @@ namespace Mono.CSharp {
                                return null;
                        }
 
-                       if (TypeManager.IsVariantOf (expr_type, target_type)) {
+                       if (TypeSpecComparer.Variant.IsEqual (expr_type, target_type)) {
                                return expr;
                        }
 
@@ -1361,13 +1306,13 @@ namespace Mono.CSharp {
                ///   an error is signaled
                /// </summary>
                static public Expression ImplicitConversionRequired (ResolveContext ec, Expression source,
-                                                                    Type target_type, Location loc)
+                                                                    TypeSpec target_type, Location loc)
                {
                        Expression e = ImplicitConversion (ec, source, target_type, loc);
                        if (e != null)
                                return e;
 
-                       if (TypeManager.IsDynamicType (source.Type)) {
+                       if (source.Type == InternalType.Dynamic) {
                                Arguments args = new Arguments (1);
                                args.Add (new Argument (source));
                                return new DynamicConversion (target_type, 0, args, loc).Resolve (ec);
@@ -1398,10 +1343,10 @@ namespace Mono.CSharp {
                ///   Int16->UIntPtr
                ///
                /// </summary>
-               public static Expression ExplicitNumericConversion (Expression expr, Type target_type)
+               public static Expression ExplicitNumericConversion (Expression expr, TypeSpec target_type)
                {
-                       Type expr_type = expr.Type;
-                       Type real_target_type = target_type;
+                       TypeSpec expr_type = expr.Type;
+                       TypeSpec real_target_type = target_type;
 
                        if (expr_type == TypeManager.sbyte_type){
                                //
@@ -1651,7 +1596,7 @@ namespace Mono.CSharp {
                ///  Returns whether an explicit reference conversion can be performed
                ///  from source_type to target_type
                /// </summary>
-               public static bool ExplicitReferenceConversionExists (Type source_type, Type target_type)
+               public static bool ExplicitReferenceConversionExists (TypeSpec source_type, TypeSpec target_type)
                {
                        Expression e = ExplicitReferenceConversion (null, source_type, target_type);
                        if (e == null)
@@ -1666,7 +1611,7 @@ namespace Mono.CSharp {
                /// <summary>
                ///   Implements Explicit Reference conversions
                /// </summary>
-               static Expression ExplicitReferenceConversion (Expression source, Type source_type, Type target_type)
+               static Expression ExplicitReferenceConversion (Expression source, TypeSpec source_type, TypeSpec target_type)
                {
                        bool target_is_value_type = TypeManager.IsStruct (target_type);
 
@@ -1701,21 +1646,12 @@ namespace Mono.CSharp {
                        if (TypeManager.IsSubclassOf (target_type, source_type))
                                return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
 
-                       //
-                       // From any class type S to any interface T, provides S is not sealed
-                       // and provided S does not implement T.
-                       //
-                       if (target_type.IsInterface && !source_type.IsSealed &&
-                               !TypeManager.ImplementsInterface (source_type, target_type)) {
-                               return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
-                       }
-
                        //
                        // From any interface-type S to to any class type T, provided T is not
                        // sealed, or provided T implements S.
                        //
                        if (source_type.IsInterface) {
-                               if (!target_type.IsSealed || TypeManager.ImplementsInterface (target_type, source_type)) {
+                               if (!target_type.IsSealed || target_type.ImplementsInterface (source_type)) {
                                        if (target_type.IsClass)
                                                return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
 
@@ -1727,17 +1663,20 @@ namespace Mono.CSharp {
                                }
 
                                //
-                               // From System.Collecitons.Generic.IList<T> and its base interfaces to a one-dimensional
+                               // From System.Collections.Generic.IList<T> and its base interfaces to a one-dimensional
                                // array type S[], provided there is an implicit or explicit reference conversion from S to T.
                                //
-                               if (IList_To_Array (source_type, target_type))
+                               var target_array = target_type as ArrayContainer;
+                               if (target_array != null && IList_To_Array (source_type, target_array))
                                        return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
 
                                return null;
                        }
 
-                       if (source_type.IsArray) {
-                               if (target_type.IsArray) {
+                       var source_array = source_type as ArrayContainer;
+                       if (source_array != null) {
+                               var target_array = target_type as ArrayContainer;
+                               if (target_array != null) {
                                        //
                                        // From System.Array to any array-type
                                        //
@@ -1752,17 +1691,17 @@ namespace Mono.CSharp {
                                        //     * Both Se and Te are reference types
                                        //     * An explicit reference conversions exist from Se to Te
                                        //
-                                       if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
+                                       if (source_array.Rank == target_array.Rank) {
 
-                                               source_type = TypeManager.GetElementType (source_type);
+                                               source_type = source_array.Element;
                                                if (!TypeManager.IsReferenceType (source_type))
                                                        return null;
 
-                                               Type target_type_element = TypeManager.GetElementType (target_type);
-                                               if (!TypeManager.IsReferenceType (target_type_element))
+                                               var target_element = target_array.Element;
+                                               if (!TypeManager.IsReferenceType (target_element))
                                                        return null;
 
-                                               if (ExplicitReferenceConversionExists (source_type, target_type_element))
+                                               if (ExplicitReferenceConversionExists (source_type, target_element))
                                                        return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
                                                        
                                                return null;
@@ -1773,12 +1712,20 @@ namespace Mono.CSharp {
                                // From a single-dimensional array type S[] to System.Collections.Generic.IList<T> and its base interfaces, 
                                // provided that there is an explicit reference conversion from S to T
                                //
-                               if (Array_To_IList (source_type, target_type, true))
+                               if (ArrayToIList (source_array, target_type, true))
                                        return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
 
                                return null;
                        }
 
+                       //
+                       // From any class type S to any interface T, provides S is not sealed
+                       // and provided S does not implement T.
+                       //
+                       if (target_type.IsInterface && !source_type.IsSealed && !source_type.ImplementsInterface (target_type)) {
+                               return source == null ? EmptyExpression.Null : new ClassCast (source, target_type);
+                       }
+
                        //
                        // From System delegate to any delegate-type
                        //
@@ -1793,9 +1740,9 @@ namespace Mono.CSharp {
                ///   type is expr.Type to `target_type'.
                /// </summary>
                static public Expression ExplicitConversionCore (ResolveContext ec, Expression expr,
-                                                                Type target_type, Location loc)
+                                                                TypeSpec target_type, Location loc)
                {
-                       Type expr_type = expr.Type;
+                       TypeSpec expr_type = expr.Type;
 
                        // Explicit conversion includes implicit conversion and it used for enum underlying types too
                        Expression ne = ImplicitConversionStandard (ec, expr, target_type, loc, true);
@@ -1803,7 +1750,7 @@ namespace Mono.CSharp {
                                return ne;
 
                        if (TypeManager.IsEnumType (expr_type)) {
-                               Expression underlying = EmptyCast.Create (expr, TypeManager.GetEnumUnderlyingType (expr_type));
+                               Expression underlying = EmptyCast.Create (expr, EnumSpec.GetUnderlyingType (expr_type));
                                expr = ExplicitConversionCore (ec, underlying, target_type, loc);
                                if (expr != null)
                                        return expr;
@@ -1818,7 +1765,7 @@ namespace Mono.CSharp {
                                if (expr_type == TypeManager.enum_type)
                                        return new UnboxCast (expr, target_type);
 
-                               Expression ce = ExplicitConversionCore (ec, expr, TypeManager.GetEnumUnderlyingType (target_type), loc);
+                               Expression ce = ExplicitConversionCore (ec, expr, EnumSpec.GetUnderlyingType (target_type), loc);
                                if (ce != null)
                                        return EmptyCast.Create (ce, target_type);
                                
@@ -1826,7 +1773,7 @@ namespace Mono.CSharp {
                                // LAMESPEC: IntPtr and UIntPtr conversion to any Enum is allowed
                                //
                                if (expr_type == TypeManager.intptr_type || expr_type == TypeManager.uintptr_type) {
-                                       ne = ExplicitUserConversion (ec, expr, TypeManager.GetEnumUnderlyingType (target_type), loc);
+                                       ne = ExplicitUserConversion (ec, expr, EnumSpec.GetUnderlyingType (target_type), loc);
                                        if (ne != null)
                                                return ExplicitConversionCore (ec, ne, target_type, loc);
                                }
@@ -1858,9 +1805,9 @@ namespace Mono.CSharp {
                        return null;
                }
 
-               public static Expression ExplicitUnsafe (Expression expr, Type target_type)
+               public static Expression ExplicitUnsafe (Expression expr, TypeSpec target_type)
                {
-                       Type expr_type = expr.Type;
+                       TypeSpec expr_type = expr.Type;
 
                        if (target_type.IsPointer){
                                if (expr_type.IsPointer)
@@ -1908,7 +1855,7 @@ namespace Mono.CSharp {
                ///   Same as ExplicitConversion, only it doesn't include user defined conversions
                /// </summary>
                static public Expression ExplicitConversionStandard (ResolveContext ec, Expression expr,
-                                                                    Type target_type, Location l)
+                                                                    TypeSpec target_type, Location l)
                {
                        int errors = ec.Report.Errors;
                        Expression ne = ImplicitConversionStandard (ec, expr, target_type, l);
@@ -1938,7 +1885,7 @@ namespace Mono.CSharp {
                ///   type is expr.Type to `target_type'.
                /// </summary>
                static public Expression ExplicitConversion (ResolveContext ec, Expression expr,
-                       Type target_type, Location loc)
+                       TypeSpec target_type, Location loc)
                {
                        Expression e = ExplicitConversionCore (ec, expr, target_type, loc);
                        if (e != null) {
@@ -1956,10 +1903,10 @@ namespace Mono.CSharp {
                                return e;
                        }
 
-                       Type expr_type = expr.Type;
+                       TypeSpec expr_type = expr.Type;
                        if (TypeManager.IsNullableType (target_type)) {
                                if (TypeManager.IsNullableType (expr_type)) {
-                                       Type target = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (target_type)[0]);
+                                       TypeSpec target = TypeManager.GetTypeArguments (target_type)[0];
                                        Expression unwrap = Nullable.Unwrap.Create (expr);
                                        e = ExplicitConversion (ec, unwrap, target, expr.Location);
                                        if (e == null)
@@ -1969,7 +1916,7 @@ namespace Mono.CSharp {
                                } else if (expr_type == TypeManager.object_type) {
                                        return new UnboxCast (expr, target_type);
                                } else {
-                                       Type target = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (target_type) [0]);
+                                       TypeSpec target = TypeManager.GetTypeArguments (target_type) [0];
 
                                        e = ExplicitConversionCore (ec, expr, target, loc);
                                        if (e != null)
index c88417f49762b3f2d7b6ef7c38edc7b3a0a9debb..b983dacf0582917c8d058ded794924aa4803c7a8 100644 (file)
@@ -2947,8 +2947,9 @@ type_list
 base_type_name
        : type
          {
-               if ($1 is ComposedCast)
+               if ($1 is ComposedCast) {
                        Report.Error (1521, GetLocation ($1), "Invalid base type `{0}'", ((ComposedCast)$1).GetSignatureForError ());
+               }
                $$ = $1;
          }
        | error
@@ -3007,7 +3008,7 @@ primary_expression_no_array_creation
        | IDENTIFIER opt_type_argument_list
          {
                var lt = (Tokenizer.LocatedToken) $1;
-               $$ = new SimpleName (MemberName.MakeName (lt.Value, (TypeArguments)$2), (TypeArguments)$2, lt.Location);          
+               $$ = new SimpleName (lt.Value, (TypeArguments)$2, lt.Location);   
          }
        | IDENTIFIER GENERATE_COMPLETION {
                var lt = (Tokenizer.LocatedToken) $1;
@@ -3553,7 +3554,7 @@ rank_specifiers
        : rank_specifier
        | rank_specifier rank_specifiers
          {
-               $$ = (string) $2 + (string) $1;
+               $$ = (string) $1 + (string) $2;
          }
        ;
 
@@ -3657,14 +3658,14 @@ unbound_type_name
          {  
                var lt = (Tokenizer.LocatedToken) $1;
 
-               $$ = new SimpleName (MemberName.MakeName (lt.Value, (int)$2), lt.Location);
+               $$ = new SimpleName (lt.Value, (int) $2, lt.Location);
          }
        | qualified_alias_member IDENTIFIER generic_dimension
          {
                var lt1 = (Tokenizer.LocatedToken) $1;
                var lt2 = (Tokenizer.LocatedToken) $2;
 
-               $$ = new QualifiedAliasMember (lt1.Value, MemberName.MakeName (lt2.Value, (int) $3), lt1.Location);
+               $$ = new QualifiedAliasMember (lt1.Value, lt2.Value, (int) $3, lt1.Location);
          }
        | unbound_type_name DOT IDENTIFIER
          {
@@ -3676,14 +3677,14 @@ unbound_type_name
          {
                var lt = (Tokenizer.LocatedToken) $3;
                
-               $$ = new MemberAccess ((Expression) $1, MemberName.MakeName (lt.Value, (int) $4), lt.Location);         
+               $$ = new MemberAccess ((Expression) $1, lt.Value, (int) $4, lt.Location);               
          }
        | namespace_or_type_name DOT IDENTIFIER generic_dimension
          {
                var lt = (Tokenizer.LocatedToken) $3;
                MemberName name = (MemberName) $1;
 
-               $$ = new MemberAccess (name.GetTypeExpression (), MemberName.MakeName (lt.Value, (int) $4), lt.Location);               
+               $$ = new MemberAccess (name.GetTypeExpression (), lt.Value, (int) $4, lt.Location);             
          }
        ;
 
@@ -4348,6 +4349,9 @@ type_parameter_constraints
 type_parameter_constraint
        : type
          {
+               if ($1 is ComposedCast)
+                       Report.Error (706, GetLocation ($1), "Invalid constraint type `{0}'", ((ComposedCast)$1).GetSignatureForError ());
+         
                $$ = $1;
          }
        | NEW OPEN_PARENS CLOSE_PARENS
index 0eacc8239ba7200f0d32fd65e9635f666f8ec968..cba83b950b9d5e66604335b5a4cd69ee7f06458e 100644 (file)
@@ -103,6 +103,12 @@ namespace Mono.CSharp {
                        return GetName (false);
                }
 
+               public int Arity {
+                       get {
+                               return TypeArguments == null ? 0 : TypeArguments.Count;
+                       }
+               }
+
                public bool IsGeneric {
                        get {
                                if (TypeArguments != null)
@@ -127,7 +133,7 @@ namespace Mono.CSharp {
                {
                        if (Left == null) {
                                if (TypeArguments != null)
-                                       return new SimpleName (Basename, TypeArguments, Location);
+                                       return new SimpleName (Name, TypeArguments, Location);
                                
                                return new SimpleName (Name, Location);
                        }
@@ -247,6 +253,7 @@ namespace Mono.CSharp {
        ///   Base representation for members.  This is used to keep track
        ///   of Name, Location and Modifier flags, and handling Attributes.
        /// </summary>
+       [System.Diagnostics.DebuggerDisplay ("{GetSignatureForError()}")]
        public abstract class MemberCore : Attributable, IMemberContext, IMemberDefinition
        {
                /// <summary>
@@ -263,6 +270,12 @@ namespace Mono.CSharp {
                        }
                }
 
+               string IMemberDefinition.Name {
+                       get {
+                               return member_name.Name;
+                       }
+               }
+
                 // Is not readonly because of IndexerName attribute
                private MemberName member_name;
                public MemberName MemberName {
@@ -284,7 +297,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               public /*readonly*/ DeclSpace Parent;
+               public /*readonly*/ TypeContainer Parent;
 
                /// <summary>
                ///   Location where this declaration happens
@@ -313,7 +326,7 @@ namespace Mono.CSharp {
                        CloseTypeCreated = 1 << 4,              // Tracks whether we have Closed the type
                        HasCompliantAttribute_Undetected = 1 << 5,      // Presence of CLSCompliantAttribute has not been detected
                        HasClsCompliantAttribute = 1 << 6,                      // Type has CLSCompliantAttribute
-                       ClsCompliantAttributeTrue = 1 << 7,                     // Type has CLSCompliant (true)
+                       ClsCompliantAttributeFalse = 1 << 7,                    // Member has CLSCompliant(false)
                        Excluded_Undetected = 1 << 8,           // Conditional attribute has not been detected yet
                        Excluded = 1 << 9,                                      // Method is conditional
                        MethodOverloadsExist = 1 << 10,         // Test for duplication must be performed
@@ -331,12 +344,16 @@ namespace Mono.CSharp {
 
                public MemberCore (DeclSpace parent, MemberName name, Attributes attrs)
                {
-                       this.Parent = parent;
+                       this.Parent = parent as TypeContainer;
                        member_name = name;
                        caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
                        AddAttributes (attrs, this);
                }
 
+               public virtual Assembly Assembly {
+                       get { return Parent.Module.Assembly; }
+               }
+
                protected virtual void SetMemberName (MemberName new_name)
                {
                        member_name = new_name;
@@ -439,8 +456,7 @@ namespace Mono.CSharp {
                        if (!RootContext.VerifyClsCompliance)
                                return;
 
-                       if (Report.WarningLevel > 0)
-                               VerifyClsCompliance ();
+                       VerifyClsCompliance ();
                }
 
                public bool IsCompilerGenerated {
@@ -452,6 +468,12 @@ namespace Mono.CSharp {
                        }
                }
 
+               public bool IsImported {
+                       get {
+                               return false;
+                       }
+               }
+
                public virtual bool IsUsed {
                        get { return (caching_flags & Flags.IsUsed) != 0; }
                }
@@ -467,10 +489,15 @@ namespace Mono.CSharp {
                        caching_flags |= Flags.IsUsed;
                }
 
+               public void SetIsAssigned ()
+               {
+                       caching_flags |= Flags.IsAssigned;
+               }
+
                /// <summary>
                /// Returns instance of ObsoleteAttribute for this MemberCore
                /// </summary>
-               public virtual ObsoleteAttribute GetObsoleteAttribute ()
+               public virtual ObsoleteAttribute GetAttributeObsolete ()
                {
                        if ((caching_flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0)
                                return null;
@@ -498,44 +525,15 @@ namespace Mono.CSharp {
                /// </summary>
                public virtual void CheckObsoleteness (Location loc)
                {
-                       ObsoleteAttribute oa = GetObsoleteAttribute ();
+                       ObsoleteAttribute oa = GetAttributeObsolete ();
                        if (oa != null)
                                AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, Report);
                }
 
-               //
-               // Returns the access level for type `t'
-               //
-               static Modifiers GetAccessLevelFromType (Type type)
-               {
-                       var ma = type.Attributes;
-                       Modifiers mod;
-                       switch (ma & TypeAttributes.VisibilityMask) {
-                       case TypeAttributes.Public:
-                       case TypeAttributes.NestedPublic:
-                               mod = Modifiers.PUBLIC;
-                               break;
-                       case TypeAttributes.NestedPrivate:
-                               mod = Modifiers.PRIVATE;
-                               break;
-                       case TypeAttributes.NestedFamily:
-                               mod = Modifiers.PROTECTED;
-                               break;
-                       case TypeAttributes.NestedFamORAssem:
-                               mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
-                               break;
-                       default:
-                               mod = Modifiers.INTERNAL;
-                               break;
-                       }
-
-                       return mod;
-               }
-
                //
                // Checks whether the type P is as accessible as this member
                //
-               public bool IsAccessibleAs (Type p)
+               public bool IsAccessibleAs (TypeSpec p)
                {
                        //
                        // if M is private, its accessibility is the same as this declspace.
@@ -548,19 +546,20 @@ namespace Mono.CSharp {
                        while (TypeManager.HasElementType (p))
                                p = TypeManager.GetElementType (p);
 
-                       if (TypeManager.IsGenericParameter (p))
+                       if (p.IsGenericParameter)
                                return true;
 
-                       if (TypeManager.IsGenericType (p)) {
-                               foreach (Type t in TypeManager.GetTypeArguments (p)) {
-                                       if (!IsAccessibleAs (t))
-                                               return false;
+                       for (TypeSpec p_parent; p != null; p = p_parent) {
+                               p_parent = p.DeclaringType;
+
+                               if (p.IsGeneric) {
+                                       foreach (TypeSpec t in p.TypeArguments) {
+                                               if (!IsAccessibleAs (t))
+                                                       return false;
+                                       }
                                }
-                       }
 
-                       for (Type p_parent = null; p != null; p = p_parent) {
-                               p_parent = p.DeclaringType;
-                               var pAccess = GetAccessLevelFromType (p);
+                               var pAccess = p.Modifiers & Modifiers.AccessibilityMask;
                                if (pAccess == Modifiers.PUBLIC)
                                        continue;
 
@@ -576,7 +575,7 @@ namespace Mono.CSharp {
 
                                        case Modifiers.PROTECTED:
                                                if (al == Modifiers.PROTECTED) {
-                                                       same_access_restrictions = mc.Parent.IsBaseType (p_parent);
+                                                       same_access_restrictions = mc.Parent.IsBaseTypeDefinition (p_parent);
                                                        break;
                                                }
 
@@ -586,7 +585,7 @@ namespace Mono.CSharp {
                                                        // protected type then the type is accessible
                                                        //
                                                        while (mc.Parent != null) {
-                                                               if (mc.Parent.IsBaseType (p_parent))
+                                                               if (mc.Parent.IsBaseTypeDefinition (p_parent))
                                                                        same_access_restrictions = true;
                                                                mc = mc.Parent; 
                                                        }
@@ -598,9 +597,9 @@ namespace Mono.CSharp {
                                                if (al == Modifiers.INTERNAL)
                                                        same_access_restrictions = TypeManager.IsThisOrFriendAssembly (Parent.Module.Assembly, p.Assembly);
                                                else if (al == Modifiers.PROTECTED)
-                                                       same_access_restrictions = mc.Parent.IsBaseType (p_parent);
+                                                       same_access_restrictions = mc.Parent.IsBaseTypeDefinition (p_parent);
                                                else if (al == (Modifiers.PROTECTED | Modifiers.INTERNAL))
-                                                       same_access_restrictions = mc.Parent.IsBaseType (p_parent) &&
+                                                       same_access_restrictions = mc.Parent.IsBaseTypeDefinition (p_parent) &&
                                                                TypeManager.IsThisOrFriendAssembly (Parent.Module.Assembly, p.Assembly);
                                                break;
 
@@ -611,7 +610,7 @@ namespace Mono.CSharp {
                                                if (al == Modifiers.PRIVATE) {
                                                        var decl = mc.Parent;
                                                        do {
-                                                               same_access_restrictions = TypeManager.IsEqual (decl.TypeBuilder, p_parent);
+                                                               same_access_restrictions = decl.CurrentType == p_parent;
                                                        } while (!same_access_restrictions && !decl.IsTopLevel && (decl = decl.Parent) != null);
                                                }
                                                
@@ -637,16 +636,29 @@ namespace Mono.CSharp {
                        if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
                                return (caching_flags & Flags.ClsCompliant) != 0;
 
-                       if (GetClsCompliantAttributeValue () && IsExposedFromAssembly ()) {
-                               caching_flags &= ~Flags.ClsCompliance_Undetected;
+                       caching_flags &= ~Flags.ClsCompliance_Undetected;
+
+                       if (HasClsCompliantAttribute) {
+                               if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0)
+                                       return false;
+
+                               caching_flags |= Flags.ClsCompliant;
+                               return true;
+                       }
+
+                       if (Parent.PartialContainer.IsClsComplianceRequired ()) {
                                caching_flags |= Flags.ClsCompliant;
                                return true;
                        }
 
-                       caching_flags &= ~Flags.ClsCompliance_Undetected;
                        return false;
                }
 
+               public virtual string[] ConditionalConditions ()
+               {
+                       return null;
+               }
+
                /// <summary>
                /// Returns true when MemberCore is exposed from assembly.
                /// </summary>
@@ -664,9 +676,9 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public virtual ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
+               public virtual ExtensionMethodGroupExpr LookupExtensionMethod (TypeSpec extensionType, string name, int arity, Location loc)
                {
-                       return Parent.LookupExtensionMethod (extensionType, name, loc);
+                       return Parent.LookupExtensionMethod (extensionType, name, arity, loc);
                }
 
                public virtual FullNamedExpression LookupNamespaceAlias (string name)
@@ -674,42 +686,34 @@ namespace Mono.CSharp {
                        return Parent.NamespaceEntry.LookupNamespaceAlias (name);
                }
 
-               public virtual FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
+               public virtual FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
                {
-                       return Parent.LookupNamespaceOrType (name, loc, ignore_cs0104);
+                       return Parent.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
                }
 
                /// <summary>
                /// Goes through class hierarchy and gets value of first found CLSCompliantAttribute.
                /// If no is attribute exists then assembly CLSCompliantAttribute is returned.
                /// </summary>
-               public virtual bool GetClsCompliantAttributeValue ()
+               public bool IsNotCLSCompliant ()
                {
                        if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
-                               return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
+                               return (caching_flags & Flags.ClsCompliantAttributeFalse) != 0;
 
                        caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
 
                        if (OptAttributes != null) {
-                               Attribute cls_attribute = OptAttributes.Search (
-                                       PredefinedAttributes.Get.CLSCompliant);
+                               Attribute cls_attribute = OptAttributes.Search (PredefinedAttributes.Get.CLSCompliant);
                                if (cls_attribute != null) {
                                        caching_flags |= Flags.HasClsCompliantAttribute;
-                                       bool value = cls_attribute.GetClsCompliantAttributeValue ();
-                                       if (value)
-                                               caching_flags |= Flags.ClsCompliantAttributeTrue;
-                                       return value;
+                                       if (cls_attribute.GetClsCompliantAttributeValue ())
+                                               return false;
+
+                                       caching_flags |= Flags.ClsCompliantAttributeFalse;
+                                       return true;
                                }
                        }
-                       
-                       // It's null for TypeParameter
-                       if (Parent == null)
-                               return false;                   
 
-                       if (Parent.GetClsCompliantAttributeValue ()) {
-                               caching_flags |= Flags.ClsCompliantAttributeTrue;
-                               return true;
-                       }
                        return false;
                }
 
@@ -719,7 +723,7 @@ namespace Mono.CSharp {
                protected bool HasClsCompliantAttribute {
                        get {
                                if ((caching_flags & Flags.HasCompliantAttribute_Undetected) != 0)
-                                       GetClsCompliantAttributeValue ();
+                                       IsNotCLSCompliant ();
                                
                                return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
                        }
@@ -741,41 +745,55 @@ namespace Mono.CSharp {
                /// </summary>
                protected virtual bool VerifyClsCompliance ()
                {
-                       if (!IsClsComplianceRequired ()) {
-                               if (HasClsCompliantAttribute && Report.WarningLevel >= 2) {
-                                       if (!IsExposedFromAssembly ()) {
-                                               Attribute a = OptAttributes.Search (PredefinedAttributes.Get.CLSCompliant);
-                                               Report.Warning (3019, 2, a.Location, "CLS compliance checking will not be performed on `{0}' because it is not visible from outside this assembly", GetSignatureForError ());
-                                       }
-
-                                       if (!CodeGen.Assembly.IsClsCompliant) {
-                                               Attribute a = OptAttributes.Search (PredefinedAttributes.Get.CLSCompliant);
-                                               Report.Warning (3021, 2, a.Location, "`{0}' does not need a CLSCompliant attribute because the assembly is not marked as CLS-compliant", GetSignatureForError ());
+                       if (HasClsCompliantAttribute) {
+                               if (CodeGen.Assembly.ClsCompliantAttribute == null) {
+                                       Attribute a = OptAttributes.Search (PredefinedAttributes.Get.CLSCompliant);
+                                       if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0) {
+                                               Report.Warning (3021, 2, a.Location,
+                                                       "`{0}' does not need a CLSCompliant attribute because the assembly is not marked as CLS-compliant",
+                                                       GetSignatureForError ());
+                                       } else {
+                                               Report.Warning (3014, 1, a.Location,
+                                                       "`{0}' cannot be marked as CLS-compliant because the assembly is not marked as CLS-compliant",
+                                                       GetSignatureForError ());
                                        }
+                                       return false;
                                }
-                               return false;
-                       }
 
-                       if (HasClsCompliantAttribute) {
-                               if (CodeGen.Assembly.ClsCompliantAttribute == null && !CodeGen.Assembly.IsClsCompliant) {
+                               if (!IsExposedFromAssembly ()) {
                                        Attribute a = OptAttributes.Search (PredefinedAttributes.Get.CLSCompliant);
-                                       Report.Warning (3014, 1, a.Location,
-                                               "`{0}' cannot be marked as CLS-compliant because the assembly is not marked as CLS-compliant",
-                                               GetSignatureForError ());
+                                       Report.Warning (3019, 2, a.Location, "CLS compliance checking will not be performed on `{0}' because it is not visible from outside this assembly", GetSignatureForError ());
+                                       return false;
+                               }
+
+                               if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0) {
+                                       if (Parent.Kind == MemberKind.Interface && Parent.IsClsComplianceRequired ()) {
+                                               Report.Warning (3010, 1, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
+                                       } else if (Parent.Kind == MemberKind.Class && (ModFlags & Modifiers.ABSTRACT) != 0 && Parent.IsClsComplianceRequired ()) {
+                                               Report.Warning (3011, 1, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
+                                       }
+
                                        return false;
                                }
 
-                               if (!Parent.IsClsComplianceRequired ()) {
+                               if (Parent.Parent != null && !Parent.IsClsComplianceRequired ()) {
                                        Attribute a = OptAttributes.Search (PredefinedAttributes.Get.CLSCompliant);
-                                       Report.Warning (3018, 1, a.Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'", 
+                                       Report.Warning (3018, 1, a.Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'",
                                                GetSignatureForError (), Parent.GetSignatureForError ());
                                        return false;
                                }
+                       } else {
+                               if (!IsExposedFromAssembly ())
+                                       return false;
+
+                               if (!Parent.PartialContainer.IsClsComplianceRequired ())
+                                       return false;
                        }
 
                        if (member_name.Name [0] == '_') {
                                Report.Warning (3008, 1, Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError () );
                        }
+
                        return true;
                }
 
@@ -815,24 +833,28 @@ namespace Mono.CSharp {
                #region IMemberContext Members
 
                public virtual CompilerContext Compiler {
-                       get { return Parent.Module.Compiler; }
+                       get { return Parent.Compiler; }
                }
 
-               public virtual Type CurrentType {
+               public virtual TypeSpec CurrentType {
                        get { return Parent.CurrentType; }
                }
 
-               public virtual TypeContainer CurrentTypeDefinition {
-                       get { return Parent.CurrentTypeDefinition; }
+               public MemberCore CurrentMemberDefinition {
+                       get { return this; }
                }
 
                public virtual TypeParameter[] CurrentTypeParameters {
                        get { return null; }
                }
 
+               public virtual bool HasUnresolvedConstraints {
+                       get { return false; }
+               }
+
                public bool IsObsolete {
                        get {
-                               if (GetObsoleteAttribute () != null)
+                               if (GetAttributeObsolete () != null)
                                        return true;
 
                                return Parent == null ? false : Parent.IsObsolete;
@@ -849,7 +871,9 @@ namespace Mono.CSharp {
                }
 
                public bool IsStatic {
-                       get { return (ModFlags & Modifiers.STATIC) != 0; }
+                       get {
+                               return (ModFlags & Modifiers.STATIC) != 0;
+                       }
                }
 
                #endregion
@@ -865,54 +889,210 @@ namespace Mono.CSharp {
                protected enum StateFlags
                {
                        Obsolete_Undetected = 1,        // Obsolete attribute has not been detected yet
-                       Obsolete = 1 << 1                       // Member has obsolete attribute
+                       Obsolete = 1 << 1,                      // Member has obsolete attribute
+                       CLSCompliant_Undetected = 1 << 3,       // CLSCompliant attribute has not been detected yet
+                       CLSCompliant = 1 << 4,          // Member is CLS Compliant
+
+                       IsAccessor = 1 << 9,            // Method is an accessor
+                       IsGeneric = 1 << 10,            // Member contains type arguments
+
+                       PendingMetaInflate = 1 << 12,
+                       PendingMakeMethod = 1 << 13,
+                       PendingMemberCacheMembers = 1 << 14,
+                       PendingBaseTypeInflate = 1 << 15,
+                       InterfacesExpanded = 1 << 16,
+                       IsNotRealProperty = 1 << 17,
                }
 
-               readonly Modifiers modifiers;
-               readonly string name;
+               protected Modifiers modifiers;
                protected StateFlags state;
                protected IMemberDefinition definition;
                public readonly MemberKind Kind;
+               protected TypeSpec declaringType;
+
+#if DEBUG
+               static int counter;
+               public int ID = counter++;
+#endif
 
-               protected MemberSpec (MemberKind kind, IMemberDefinition definition, string name, Modifiers modifiers)
+               protected MemberSpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition definition, Modifiers modifiers)
                {
+                       this.Kind = kind;
+                       this.declaringType = declaringType;
                        this.definition = definition;
-                       this.name = name;
                        this.modifiers = modifiers;
 
-                       state = StateFlags.Obsolete_Undetected;
+                       state = StateFlags.Obsolete_Undetected | StateFlags.CLSCompliant_Undetected;
+               }
+
+               #region Properties
+
+               public Assembly Assembly {
+                       get {
+                               return definition.Assembly;
+                       }
+               }
+
+               public virtual int Arity {
+                       get {
+                               return 0;
+                       }
+               }
+
+               public TypeSpec DeclaringType {
+                       get {
+                               return declaringType;
+                       }
+                       set {
+                               declaringType = value;
+                       }
+               }
+
+               public IMemberDefinition MemberDefinition {
+                       get {
+                               return definition;
+                       }
+               }
+
+               public Modifiers Modifiers {
+                       get {
+                               return modifiers;
+                       }
+                       set {
+                               modifiers = value;
+                       }
+               }
+               
+               public virtual string Name {
+                       get {
+                               return definition.Name;
+                       }
+               }
+
+               public bool IsAbstract {
+                       get { return (modifiers & Modifiers.ABSTRACT) != 0; }
                }
 
-               public abstract Type DeclaringType { get; }
+               public bool IsAccessor {
+                       get {
+                               return (state & StateFlags.IsAccessor) != 0;
+                       }
+                       set {
+                               state = value ? state | StateFlags.IsAccessor : state & ~StateFlags.IsAccessor;
+                       }
+               }
 
-               public ObsoleteAttribute GetObsoleteAttribute ()
+               //
+               // Return true when this member is a generic in C# terms
+               // therefore nested non-generic type of generic type will
+               // return false
+               //
+               public bool IsGeneric {
+                       get {
+                               return (state & StateFlags.IsGeneric) != 0;
+                       }
+                       set {
+                               state = value ? state | StateFlags.IsGeneric : state & ~StateFlags.IsGeneric;
+                       }
+               }
+
+               public bool IsPrivate {
+                       get { return (modifiers & Modifiers.PRIVATE) != 0; }
+               }
+
+               public bool IsStatic {
+                       get { 
+                               return (modifiers & Modifiers.STATIC) != 0;
+                       }
+               }
+
+               #endregion
+
+               public virtual ObsoleteAttribute GetAttributeObsolete ()
                {
                        if ((state & (StateFlags.Obsolete | StateFlags.Obsolete_Undetected)) == 0)
                                return null;
 
                        state &= ~StateFlags.Obsolete_Undetected;
 
-                       var oa = definition.GetObsoleteAttribute ();
+                       var oa = definition.GetAttributeObsolete ();
                        if (oa != null)
                                state |= StateFlags.Obsolete;
 
                        return oa;
                }
 
-               public IMemberDefinition MemberDefinition {
-                       get { return definition; }
+               protected virtual bool IsNotCLSCompliant ()
+               {
+                       return MemberDefinition.IsNotCLSCompliant ();
                }
 
-               public Modifiers Modifiers {
-                       get { return modifiers; }
+               public virtual string GetSignatureForError ()
+               {
+                       var bf = MemberDefinition as Property.BackingField;
+                       var name = bf == null ? Name : bf.OriginalName;
+                       return DeclaringType.GetSignatureForError () + "." + name;
                }
-               
-               public string Name {
-                       get { return name; }
+
+               public virtual MemberSpec InflateMember (TypeParameterInflator inflator)
+               {
+                       var inflated = (MemberSpec) MemberwiseClone ();
+                       inflated.declaringType = inflator.TypeInstance;
+                       inflated.state |= StateFlags.PendingMetaInflate;
+                       return inflated;
                }
 
-               public bool IsStatic {
-                       get { return (modifiers & Modifiers.STATIC) != 0; }
+               //
+               // Returns member CLS compliance based on full member hierarchy
+               //
+               public bool IsCLSCompliant ()
+               {
+                       if ((state & StateFlags.CLSCompliant_Undetected) != 0) {
+                               state &= ~StateFlags.CLSCompliant_Undetected;
+
+                               if (IsNotCLSCompliant ())
+                                       return false;
+
+                               bool compliant;
+                               if (DeclaringType != null) {
+                                       compliant = DeclaringType.IsCLSCompliant ();
+                               } else {
+                                       // TODO: NEED AssemblySpec
+                                       if (MemberDefinition.IsImported) {
+                                               var attr = MemberDefinition.Assembly.GetCustomAttributes (typeof (CLSCompliantAttribute), false);
+                                               compliant = attr.Length > 0 && ((CLSCompliantAttribute) attr[0]).IsCompliant;
+                                       } else {
+                                               compliant = CodeGen.Assembly.IsClsCompliant;
+                                       }
+                               }
+
+                               if (compliant)
+                                       state |= StateFlags.CLSCompliant;
+                       }
+
+                       return (state & StateFlags.CLSCompliant) != 0;
+               }
+
+               public bool IsConditionallyExcluded (Location loc)
+               {
+                       if ((Kind & (MemberKind.Class | MemberKind.Method)) == 0)
+                               return false;
+
+                       var conditions = MemberDefinition.ConditionalConditions ();
+                       if (conditions == null)
+                               return false;
+
+                       foreach (var condition in conditions) {
+                               if (loc.CompilationUnit.IsConditionalDefined (condition))
+                                       return false;
+                       }
+
+                       return true;
+               }
+
+               public override string ToString ()
+               {
+                       return GetSignatureForError ();
                }
        }
 
@@ -922,18 +1102,32 @@ namespace Mono.CSharp {
        //
        public interface IMemberDefinition
        {
-               ObsoleteAttribute GetObsoleteAttribute ();
+               Assembly Assembly { get; }
+               string Name { get; }
+               bool IsImported { get; }
+
+               string[] ConditionalConditions ();
+               ObsoleteAttribute GetAttributeObsolete ();
+               bool IsNotCLSCompliant ();
+               void SetIsAssigned ();
                void SetIsUsed ();
        }
 
-       /// <summary>
-       ///   Base class for structs, classes, enumerations and interfaces.  
-       /// </summary>
-       /// <remarks>
-       ///   They all create new declaration spaces.  This
-       ///   provides the common foundation for managing those name
-       ///   spaces.
-       /// </remarks>
+       public interface IParametersMember : IInterfaceMemberSpec
+       {
+               AParametersCollection Parameters { get; }
+       }
+
+       public interface IInterfaceMemberSpec
+       {
+               TypeSpec MemberType { get; }
+       }
+
+       //
+       // Base type container declaration. It exists to handle partial types
+       // which share same definition (PartialContainer) but have different
+       // resolve scopes
+       //
        public abstract class DeclSpace : MemberCore {
                /// <summary>
                ///   This points to the actual definition that is being
@@ -941,13 +1135,6 @@ namespace Mono.CSharp {
                /// </summary>
                public TypeBuilder TypeBuilder;
 
-               /// <summary>
-               ///   If we are a generic type, this is the type we are
-               ///   currently defining.  We need to lookup members on this
-               ///   instead of the TypeBuilder.
-               /// </summary>
-               protected Type currentType;
-
                //
                // This is the namespace in which this typecontainer
                // was declared.  We use this to resolve names.
@@ -1058,11 +1245,7 @@ namespace Mono.CSharp {
                        defined_names.TryGetValue (name, out mc);
                        return mc;
                }
-
-               public bool IsStaticClass {
-                       get { return (ModFlags & Modifiers.STATIC) != 0; }
-               }
-               
+       
                // 
                // root_types contains all the types.  All TopLevel types
                // hence have a parent that points to `root_types', that is
@@ -1077,27 +1260,6 @@ namespace Mono.CSharp {
                        return false;
                }
 
-               public virtual void CloseType ()
-               {
-                       if ((caching_flags & Flags.CloseTypeCreated) == 0){
-                               try {
-                                       TypeBuilder.CreateType ();
-                               } catch {
-                                       //
-                                       // The try/catch is needed because
-                                       // nested enumerations fail to load when they
-                                       // are defined.
-                                       //
-                                       // Even if this is the right order (enumerations
-                                       // declared after types).
-                                       //
-                                       // Note that this still creates the type and
-                                       // it is possible to save it
-                               }
-                               caching_flags |= Flags.CloseTypeCreated;
-                       }
-               }
-
                protected virtual TypeAttributes TypeAttr {
                        get { return Module.DefaultCharSetType; }
                }
@@ -1114,157 +1276,71 @@ namespace Mono.CSharp {
                                type.GetSignatureForError ());
                }
 
-               public override void Emit ()
-               {
-                       if (type_params != null) {
-                               int offset = count_type_params - type_params.Length;
-                               for (int i = offset; i < type_params.Length; i++)
-                                       CurrentTypeParameters [i - offset].Emit ();
-                       }
-
-                       if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
-                               PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (TypeBuilder);
-
-                       base.Emit ();
-               }
-
                public override string GetSignatureForError ()
-               {       
+               {
                        return MemberName.GetSignatureForError ();
                }
                
-               public bool CheckAccessLevel (Type check_type)
+               public bool CheckAccessLevel (TypeSpec check_type)
                {
-                       Type tb = TypeBuilder;
+                       TypeSpec tb = PartialContainer.Definition;
+                       check_type = check_type.GetDefinition ();
 
-                       if (this is GenericMethod) {
-                               tb = Parent.TypeBuilder;
-
-                               // FIXME: Generic container does not work with nested generic
-                               // anonymous method stories
-                               if (TypeBuilder == null)
-                                       return true;
-                       }
-
-                       check_type = TypeManager.DropGenericTypeArguments (check_type);
-                       if (check_type == tb)
-                               return true;
-
-                       // TODO: When called from LocalUsingAliasEntry tb is null
-                       // because we are in RootDeclSpace
-                       if (tb == null)
-                               tb = typeof (RootDeclSpace);
-
-                       //
-                       // Broken Microsoft runtime, return public for arrays, no matter what 
-                       // the accessibility is for their underlying class, and they return 
-                       // NonPublic visibility for pointers
-                       //
-                       if (TypeManager.HasElementType (check_type))
-                               return CheckAccessLevel (TypeManager.GetElementType (check_type));
-
-                       if (TypeManager.IsGenericParameter (check_type))
-                               return true;
-
-                       TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
+                       var check_attr = check_type.Modifiers & Modifiers.AccessibilityMask;
 
                        switch (check_attr){
-                       case TypeAttributes.Public:
+                       case Modifiers.PUBLIC:
                                return true;
 
-                       case TypeAttributes.NotPublic:
-                               return TypeManager.IsThisOrFriendAssembly (Module.Assembly, check_type.Assembly);
+                       case Modifiers.INTERNAL:
+                               return TypeManager.IsThisOrFriendAssembly (Assembly, check_type.Assembly);
                                
-                       case TypeAttributes.NestedPublic:
-                               return CheckAccessLevel (check_type.DeclaringType);
-
-                       case TypeAttributes.NestedPrivate:
-                               Type declaring = check_type.DeclaringType;
-                               return tb == declaring || TypeManager.IsNestedChildOf (tb, declaring);  
+                       case Modifiers.PRIVATE:
+                               TypeSpec declaring = check_type.DeclaringType;
+                               return tb == declaring.GetDefinition () || TypeManager.IsNestedChildOf (tb, declaring); 
 
-                       case TypeAttributes.NestedFamily:
+                       case Modifiers.PROTECTED:
                                //
                                // Only accessible to methods in current type or any subtypes
                                //
-                               return FamilyAccessible (tb, check_type);
+                               return TypeManager.IsNestedFamilyAccessible (tb, check_type.DeclaringType);
 
-                       case TypeAttributes.NestedFamANDAssem:
-                               return TypeManager.IsThisOrFriendAssembly (Module.Assembly, check_type.Assembly) && 
-                                       FamilyAccessible (tb, check_type);
-
-                       case TypeAttributes.NestedFamORAssem:
-                               return FamilyAccessible (tb, check_type) ||
-                                       TypeManager.IsThisOrFriendAssembly (Module.Assembly, check_type.Assembly);
+                       case Modifiers.PROTECTED | Modifiers.INTERNAL:
+                               if (TypeManager.IsThisOrFriendAssembly (Assembly, check_type.Assembly))
+                                       return true;
 
-                       case TypeAttributes.NestedAssembly:
-                               return TypeManager.IsThisOrFriendAssembly (Module.Assembly, check_type.Assembly);
+                               goto case Modifiers.PROTECTED;
                        }
 
                        throw new NotImplementedException (check_attr.ToString ());
                }
 
-               static bool FamilyAccessible (Type tb, Type check_type)
+               private TypeSpec LookupNestedTypeInHierarchy (string name, int arity)
                {
-                       Type declaring = check_type.DeclaringType;
-                       return TypeManager.IsNestedFamilyAccessible (tb, declaring);
-               }
-
-               public bool IsBaseType (Type baseType)
-               {
-                       // We are called from RootDeclspace
-                       if (TypeBuilder == null)
-                               return false;
-
-                       return TypeManager.IsSubclassOf (TypeBuilder, baseType);
-               }
-
-               private Type LookupNestedTypeInHierarchy (string name)
-               {
-                       Type t = null;
-                       // if the member cache has been created, lets use it.
-                       // the member cache is MUCH faster.
-                       if (MemberCache != null) {
-                               t = MemberCache.FindNestedType (name);
-                               if (t == null)
-                                       return null;
-                       }
-
-                       //
-                       // FIXME: This hack is needed because member cache does not work
-                       // with nested base generic types, it does only type name copy and
-                       // not type construction
-                       //
+                       // TODO: GenericMethod only
+                       if (PartialContainer == null)
+                               return null;
 
-                       // no member cache. Do it the hard way -- reflection
-                       for (Type current_type = TypeBuilder;
-                            current_type != null && current_type != TypeManager.object_type;
-                            current_type = current_type.BaseType) {
-
-                               Type ct = TypeManager.DropGenericTypeArguments (current_type);
-                               if (ct is TypeBuilder) {
-                                       TypeContainer tc = ct == TypeBuilder
-                                               ? PartialContainer : TypeManager.LookupTypeContainer (ct);
-                                       if (tc != null)
-                                               t = tc.FindNestedType (name);
-                               } else {
-                                       t = TypeManager.GetNestedType (ct, name);
-                               }
+                       // Has any nested type
+                       // Does not work, because base type can have
+                       //if (PartialContainer.Types == null)
+                       //      return null;
 
-                               if ((t == null) || !CheckAccessLevel (t))
-                                       continue;
+                       var container = PartialContainer.CurrentType;
 
-                               if (!TypeManager.IsGenericType (current_type))
-                                       return t;
+                       // Is not Root container
+                       if (container == null)
+                               return null;
 
-                               Type[] args = TypeManager.GetTypeArguments (current_type);
-                               Type[] targs = TypeManager.GetTypeArguments (t);
-                               for (int i = 0; i < args.Length; i++)
-                                       targs [i] = TypeManager.TypeToCoreType (args [i]);
+                       var     t = MemberCache.FindNestedType (container, name, arity);
+                       if (t == null)
+                               return null;
 
-                               return t.MakeGenericType (targs);
-                       }
+                       // FIXME: Breaks error reporting
+                       if (!CheckAccessLevel (t))
+                               return null;
 
-                       return null;
+                       return t;
                }
 
                //
@@ -1274,73 +1350,50 @@ namespace Mono.CSharp {
                //
                // Returns: Type or null if they type can not be found.
                //
-               public override FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
+               public override FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
                {
                        FullNamedExpression e;
-                       if (Cache.TryGetValue (name, out e))
+                       if (arity == 0 && Cache.TryGetValue (name, out e))
                                return e;
 
                        e = null;
                        int errors = Report.Errors;
 
-                       TypeParameter[] tp = CurrentTypeParameters;
-                       if (tp != null) {
-                               TypeParameter tparam = TypeParameter.FindTypeParameter (tp, name);
-                               if (tparam != null)
-                                       e = new TypeParameterExpr (tparam, Location.Null);
+                       if (arity == 0) {
+                               TypeParameter[] tp = CurrentTypeParameters;
+                               if (tp != null) {
+                                       TypeParameter tparam = TypeParameter.FindTypeParameter (tp, name);
+                                       if (tparam != null)
+                                               e = new TypeParameterExpr (tparam, Location.Null);
+                               }
                        }
 
                        if (e == null) {
-                               Type t = LookupNestedTypeInHierarchy (name);
+                               TypeSpec t = LookupNestedTypeInHierarchy (name, arity);
 
                                if (t != null)
                                        e = new TypeExpression (t, Location.Null);
                                else if (Parent != null)
-                                       e = Parent.LookupNamespaceOrType (name, loc, ignore_cs0104);
+                                       e = Parent.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
                                else
-                                       e = NamespaceEntry.LookupNamespaceOrType (name, loc, ignore_cs0104);
+                                       e = NamespaceEntry.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
                        }
 
-                       if (errors == Report.Errors)
+                       // TODO MemberCache: How to cache arity stuff ?
+                       if (errors == Report.Errors && arity == 0)
                                Cache [name] = e;
                        
                        return e;
                }
 
-               /// <remarks>
-               ///   This function is broken and not what you're looking for.  It should only
-               ///   be used while the type is still being created since it doesn't use the cache
-               ///   and relies on the filter doing the member name check.
-               /// </remarks>
-               ///
-               // [Obsolete ("Only MemberCache approach should be used")]
-               public virtual MemberList FindMembers (MemberTypes mt, BindingFlags bf,
-                                                       MemberFilter filter, object criteria)
-               {
-                       throw new NotSupportedException ();
-               }
-
-               /// <remarks>
-               ///   If we have a MemberCache, return it.  This property may return null if the
-               ///   class doesn't have a member cache or while it's still being created.
-               /// </remarks>
-               public abstract MemberCache MemberCache {
-                       get;
+               public override Assembly Assembly {
+                       get { return Module.Assembly; }
                }
 
                public virtual ModuleContainer Module {
                        get { return Parent.Module; }
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
-               {
-                       if (a.Type == pa.Required) {
-                               Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
-                               return;
-                       }
-                       TypeBuilder.SetCustomAttribute (cb);
-               }
-
                TypeParameter[] initialize_type_params ()
                {
                        if (type_param_list != null)
@@ -1426,7 +1479,7 @@ namespace Mono.CSharp {
                                }
 
                                type_params [i] = new TypeParameter (
-                                       Parent, this, name.Name, constraints, name.OptAttributes, variance, Location);
+                                       Parent, i, new MemberName (name.Name, Location), constraints, name.OptAttributes, variance);
 
                                AddToContainer (type_params [i], name.Name);
                        }
@@ -1439,7 +1492,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               public TypeParameter[] TypeParameters {
+               protected TypeParameter[] TypeParameters {
                        get {
                                if (!IsGeneric)
                                        throw new InvalidOperationException ();
@@ -1452,26 +1505,12 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override Type CurrentType {
-                       get { return currentType != null ? currentType : TypeBuilder; }
-               }
-
-               public override TypeContainer CurrentTypeDefinition {
-                       get { return PartialContainer; }
-               }
-
                public int CountTypeParameters {
                        get {
                                return count_type_params;
                        }
                }
 
-               // Used for error reporting only
-               public virtual Type LookupAnyGeneric (string typeName)
-               {
-                       return NamespaceEntry.NS.LookForAnyGenericType (typeName);
-               }
-
                public override string[] ValidAttributeTargets {
                        get { return attribute_targets; }
                }
@@ -1484,35 +1523,10 @@ namespace Mono.CSharp {
 
                        if (type_params != null) {
                                foreach (TypeParameter tp in type_params) {
-                                       if (tp.Constraints == null)
-                                               continue;
-
-                                       tp.Constraints.VerifyClsCompliance (Report);
+                                       tp.VerifyClsCompliance ();
                                }
                        }
 
-                       var cache = TypeManager.AllClsTopLevelTypes;
-                       if (cache == null)
-                               return true;
-
-                       string lcase = Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
-                       if (!cache.ContainsKey (lcase)) {
-                               cache.Add (lcase, this);
-                               return true;
-                       }
-
-                       object val = cache [lcase];
-                       if (val == null) {
-                               Type t = AttributeTester.GetImportedIgnoreCaseClsType (lcase);
-                               if (t == null)
-                                       return true;
-                               Report.SymbolRelatedToPreviousError (t);
-                       }
-                       else {
-                               Report.SymbolRelatedToPreviousError ((DeclSpace)val);
-                       }
-
-                       Report.Warning (3005, 1, Location, "Identifier `{0}' differing only in case is not CLS-compliant", GetSignatureForError ());
                        return true;
                }
        }
index a07adb45a44338dd8c645d8b41bd7d942c10f6b6..58bc40b01952a42691ad8e37191f6c265f664d48 100644 (file)
@@ -15,6 +15,7 @@
 using System;
 using System.Reflection;
 using System.Reflection.Emit;
+using System.Collections.Generic;
 
 namespace Mono.CSharp {
 
@@ -24,9 +25,8 @@ namespace Mono.CSharp {
        public class Delegate : TypeContainer
        {
                FullNamedExpression ReturnType;
-               public readonly AParametersCollection Parameters;
+               public readonly ParametersCompiled Parameters;
 
-               // TODO: Maybe I can keep member cache only and not the builders
                Constructor Constructor;
                Method InvokeBuilder;
                Method BeginInvokeBuilder;
@@ -60,19 +60,20 @@ namespace Mono.CSharp {
                                                           IsTopLevel ? Modifiers.INTERNAL :
                                                           Modifiers.PRIVATE, name.Location, Report);
                        Parameters      = param_list;
+                       spec = new TypeSpec (Kind, null, this, null, ModFlags | Modifiers.SEALED);
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.Target == AttributeTargets.ReturnValue) {
                                if (return_attributes == null)
                                        return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
 
-                               return_attributes.ApplyAttributeBuilder (a, cb, pa);
+                               return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
                                return;
                        }
 
-                       base.ApplyAttributeBuilder (a, cb, pa);
+                       base.ApplyAttributeBuilder (a, ctor, cdata, pa);
                }
 
                public override AttributeTargets AttributeTargets {
@@ -81,7 +82,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               protected override Type BaseType {
+               public override TypeSpec BaseType {
                        get {
                                return TypeManager.multicast_delegate_type;
                        }
@@ -89,20 +90,6 @@ namespace Mono.CSharp {
 
                protected override bool DoDefineMembers ()
                {
-                       if (IsGeneric) {
-                               foreach (TypeParameter type_param in TypeParameters) {
-                                       if (!type_param.Resolve (this))
-                                               return false;
-                               }
-
-                               foreach (TypeParameter type_param in TypeParameters) {
-                                       if (!type_param.DefineType (this))
-                                               return false;
-                               }
-                       }
-
-                       member_cache = new MemberCache (BaseType, this);
-
                        var ctor_parameters = ParametersCompiled.CreateFullyResolved (
                                new [] {
                                        new Parameter (new TypeExpression (TypeManager.object_type, Location), "object", Parameter.Modifier.NONE, null, Location),
@@ -124,7 +111,7 @@ namespace Mono.CSharp {
                        // First, call the `out of band' special method for
                        // defining recursively any types we need:
                        //
-                       var p = Parameters.AsCompiled;
+                       var p = Parameters;
 
                        if (!p.Resolve (this))
                                return false;
@@ -231,12 +218,12 @@ namespace Mono.CSharp {
                        }
 
                        if (out_params > 0) {
-                               var end_param_types = new Type [out_params];
+                               var end_param_types = new TypeSpec [out_params];
                                Parameter[] end_params = new Parameter[out_params];
 
                                int param = 0;
                                for (int i = 0; i < Parameters.FixedParameters.Length; ++i) {
-                                       Parameter p = Parameters.AsCompiled [i];
+                                       Parameter p = Parameters [i];
                                        if ((p.ModFlags & Parameter.Modifier.ISBYREF) == 0)
                                                continue;
 
@@ -262,16 +249,24 @@ namespace Mono.CSharp {
                        EndInvokeBuilder.Define ();
                }
 
-               public override void Emit ()
+               public override void DefineConstants ()
+               {
+                       if (!Parameters.IsEmpty && Parameters[Parameters.Count - 1].HasDefaultValue) {
+                               var rc = new ResolveContext (this);
+                               Parameters.ResolveDefaultValues (rc);
+                       }
+               }
+
+               public override void EmitType ()
                {
-                       if (TypeManager.IsDynamicType (ReturnType.Type)) {
+                       if (ReturnType.Type == InternalType.Dynamic) {
                                return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
                                PredefinedAttributes.Get.Dynamic.EmitAttribute (return_attributes.Builder);
                        } else {
                                var trans_flags = TypeManager.HasDynamicTypeUsed (ReturnType.Type);
                                if (trans_flags != null) {
                                        var pa = PredefinedAttributes.Get.DynamicTransform;
-                                       if (pa.Constructor != null || pa.ResolveConstructor (Location, TypeManager.bool_type.MakeArrayType ())) {
+                                       if (pa.Constructor != null || pa.ResolveConstructor (Location, ArrayContainer.MakeType (TypeManager.bool_type))) {
                                                return_attributes = new ReturnParameter (this, InvokeBuilder.MethodBuilder, Location);
                                                return_attributes.Builder.SetCustomAttribute (
                                                        new CustomAttributeBuilder (pa.Constructor, new object [] { trans_flags }));
@@ -279,13 +274,13 @@ namespace Mono.CSharp {
                                }
                        }
 
-                       Parameters.AsCompiled.ApplyAttributes (InvokeBuilder.MethodBuilder);
+                       Parameters.ApplyAttributes (InvokeBuilder.MethodBuilder);
                        
                        Constructor.ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
                        InvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
 
                        if (BeginInvokeBuilder != null) {
-                               BeginInvokeBuilder.Parameters.ApplyAttributes (BeginInvokeBuilder.MethodBuilder);
+                               BeginInvokeBuilder.ParameterInfo.ApplyAttributes (BeginInvokeBuilder.MethodBuilder);
 
                                BeginInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
                                EndInvokeBuilder.MethodBuilder.SetImplementationFlags (MethodImplAttributes.Runtime);
@@ -319,9 +314,9 @@ namespace Mono.CSharp {
                                return false;
                        }
 
-                       Parameters.AsCompiled.VerifyClsCompliance (this);
+                       Parameters.VerifyClsCompliance (this);
 
-                       if (!AttributeTester.IsClsCompliant (ReturnType.Type)) {
+                       if (!ReturnType.Type.IsCLSCompliant ()) {
                                Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
                                        GetSignatureForError ());
                        }
@@ -329,92 +324,34 @@ namespace Mono.CSharp {
                }
 
 
-               public static MethodSpec GetConstructor (CompilerContext ctx, Type container_type, Type delegate_type)
+               public static MethodSpec GetConstructor (CompilerContext ctx, TypeSpec container_type, TypeSpec delType)
                {
-                       Type dt = delegate_type;
-                       Type[] g_args = null;
-                       if (TypeManager.IsGenericType (delegate_type)) {
-                               g_args = TypeManager.GetTypeArguments (delegate_type);
-                               delegate_type = TypeManager.DropGenericTypeArguments (delegate_type);
-                       }
-
-                       Delegate d = TypeManager.LookupDelegate (delegate_type);
-                       if (d != null) {
-                               if (g_args != null)
-                                       return Import.CreateMethod (TypeBuilder.GetConstructor (dt, d.Constructor.ConstructorBuilder));
-
-                               return d.Constructor.Spec;
-                       }
-
-                       Expression ml = Expression.MemberLookup (ctx, container_type,
-                               null, dt, ConstructorInfo.ConstructorName, MemberTypes.Constructor,
-                               BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, Location.Null);
-
-                       MethodGroupExpr mg = ml as MethodGroupExpr;
-                       if (mg == null) {
-                               ctx.Report.Error (-100, Location.Null, "Internal error: could not find delegate constructor!");
-                               // FIXME: null will cause a crash later
-                               return null;
-                       }
-
-                       return mg.Methods[0];
+                       var ctor = MemberCache.FindMember (delType, MemberFilter.Constructor (null), BindingRestriction.DeclaredOnly);
+                       return (MethodSpec) ctor;
                }
 
                //
-               // Returns the MethodBase for "Invoke" from a delegate type, this is used
-               // to extract the signature of a delegate.
+               // Returns the "Invoke" from a delegate type
                //
-               public static MethodSpec GetInvokeMethod (CompilerContext ctx, Type container_type, Type delegate_type)
+               public static MethodSpec GetInvokeMethod (CompilerContext ctx, TypeSpec delType)
                {
-                       Type dt = delegate_type;
-
-                       Type[] g_args = null;
-                       if (TypeManager.IsGenericType (delegate_type)) {
-                               g_args = TypeManager.GetTypeArguments (delegate_type);
-                               delegate_type = TypeManager.DropGenericTypeArguments (delegate_type);
-                       }
-
-                       Delegate d = TypeManager.LookupDelegate (delegate_type);
-                       MethodSpec invoke;
-                       if (d != null) {
-                               if (g_args != null) {
-                                       invoke = Import.CreateMethod (TypeBuilder.GetMethod (dt, d.InvokeBuilder.MethodBuilder));
-#if MS_COMPATIBLE
-//                                     ParametersCompiled p = (ParametersCompiled) d.Parameters.InflateTypes (g_args, g_args);
-//                                     TypeManager.RegisterMethod (invoke, p);
-#endif
-                                       return invoke;
-                               }
-                               return d.InvokeBuilder.Spec;
-                       }
-
-                       Expression ml = Expression.MemberLookup (ctx, container_type, null, dt,
-                               "Invoke", Location.Null);
-
-                       MethodGroupExpr mg = ml as MethodGroupExpr;
-                       if (mg == null) {
-                               ctx.Report.Error (-100, Location.Null, "Internal error: could not find Invoke method!");
-                               // FIXME: null will cause a crash later
-                               return null;
-                       }
+                       var invoke = MemberCache.FindMember (delType,
+                               MemberFilter.Method (InvokeMethodName, 0, null, null),
+                               BindingRestriction.DeclaredOnly);
 
-                       invoke = mg.Methods[0];
-#if MS_COMPATIBLE
-//                     if (g_args != null) {
-//                             AParametersCollection p = TypeManager.GetParameterData (invoke);
-//                             p = p.InflateTypes (g_args, g_args);
-//                             TypeManager.RegisterMethod (invoke, p);
-//                             return invoke;
-//                     }
-#endif
+                       return (MethodSpec) invoke;
+               }
 
-                       return invoke;
+               public static AParametersCollection GetParameters (CompilerContext ctx, TypeSpec delType)
+               {
+                       var invoke_mb = GetInvokeMethod (ctx, delType);
+                       return invoke_mb.Parameters;
                }
 
                //
                // 15.2 Delegate compatibility
                //
-               public static bool IsTypeCovariant (Expression a, Type b)
+               public static bool IsTypeCovariant (Expression a, TypeSpec b)
                {
                        //
                        // For each value parameter (a parameter with no ref or out modifier), an 
@@ -432,7 +369,7 @@ namespace Mono.CSharp {
 
                public static string FullDelegateDesc (MethodSpec invoke_method)
                {
-                       return TypeManager.GetFullNameSignature (invoke_method.MetaInfo).Replace (".Invoke", "");
+                       return TypeManager.GetFullNameSignature (invoke_method).Replace (".Invoke", "");
                }
                
                public Expression InstanceExpression {
@@ -462,7 +399,7 @@ namespace Mono.CSharp {
                        Arguments delegate_arguments = new Arguments (pd.Count);
                        for (int i = 0; i < pd.Count; ++i) {
                                Argument.AType atype_modifier;
-                               Type atype = pd.Types [i];
+                               TypeSpec atype = pd.Types [i];
                                switch (pd.FixedParameters [i].ModFlags) {
                                case Parameter.Modifier.REF:
                                        atype_modifier = Argument.AType.Ref;
@@ -504,7 +441,7 @@ namespace Mono.CSharp {
                {
                        constructor_method = Delegate.GetConstructor (ec.Compiler, ec.CurrentType, type);
 
-                       var invoke_method = Delegate.GetInvokeMethod (ec.Compiler, ec.CurrentType, type);
+                       var invoke_method = Delegate.GetInvokeMethod (ec.Compiler, type);
                        method_group.DelegateType = type;
                        method_group.CustomErrorHandler = this;
 
@@ -517,7 +454,7 @@ namespace Mono.CSharp {
                        
                        if (TypeManager.IsNullableType (delegate_method.DeclaringType)) {
                                ec.Report.Error (1728, loc, "Cannot create delegate from method `{0}' because it is a member of System.Nullable<T> type",
-                                       TypeManager.GetFullNameSignature (delegate_method.MetaInfo));
+                                       TypeManager.GetFullNameSignature (delegate_method));
                                return null;
                        }               
                        
@@ -526,28 +463,28 @@ namespace Mono.CSharp {
                        ExtensionMethodGroupExpr emg = method_group as ExtensionMethodGroupExpr;
                        if (emg != null) {
                                delegate_instance_expression = emg.ExtensionExpression;
-                               Type e_type = delegate_instance_expression.Type;
+                               TypeSpec e_type = delegate_instance_expression.Type;
                                if (TypeManager.IsValueType (e_type)) {
                                        ec.Report.Error (1113, loc, "Extension method `{0}' of value type `{1}' cannot be used to create delegates",
-                                               TypeManager.CSharpSignature (delegate_method.MetaInfo), TypeManager.CSharpName (e_type));
+                                               delegate_method.GetSignatureForError (), TypeManager.CSharpName (e_type));
                                }
                        }
 
-                       Type rt = TypeManager.TypeToCoreType (delegate_method.ReturnType);
+                       TypeSpec rt = delegate_method.ReturnType;
                        Expression ret_expr = new TypeExpression (rt, loc);
-                       if (!Delegate.IsTypeCovariant (ret_expr, (TypeManager.TypeToCoreType (invoke_method.ReturnType)))) {
+                       if (!Delegate.IsTypeCovariant (ret_expr, invoke_method.ReturnType)) {
                                Error_ConversionFailed (ec, delegate_method, ret_expr);
                        }
 
-                       if (Invocation.IsMethodExcluded (delegate_method, loc)) {
-                               ec.Report.SymbolRelatedToPreviousError (delegate_method.MetaInfo);
-                               MethodOrOperator m = TypeManager.GetMethod (delegate_method.MetaInfo) as MethodOrOperator;
+                       if (delegate_method.IsConditionallyExcluded (loc)) {
+                               ec.Report.SymbolRelatedToPreviousError (delegate_method);
+                               MethodOrOperator m = delegate_method.MemberDefinition as MethodOrOperator;
                                if (m != null && m.IsPartialDefinition) {
                                        ec.Report.Error (762, loc, "Cannot create delegate from partial method declaration `{0}'",
-                                               TypeManager.CSharpSignature (delegate_method.MetaInfo));
+                                               delegate_method.GetSignatureForError ());
                                } else {
                                        ec.Report.Error (1618, loc, "Cannot create delegate with `{0}' because it has a Conditional attribute",
-                                               TypeManager.CSharpSignature (delegate_method.MetaInfo));
+                                               TypeManager.CSharpSignature (delegate_method));
                                }
                        }
 
@@ -572,7 +509,7 @@ namespace Mono.CSharp {
                        Expression instance = method_group.InstanceExpression;
                        if (instance != null && instance != EmptyExpression.Null) {
                                delegate_instance_expression = instance;
-                               Type instance_type = delegate_instance_expression.Type;
+                               TypeSpec instance_type = delegate_instance_expression.Type;
                                if (TypeManager.IsValueType (instance_type) || TypeManager.IsGenericParameter (instance_type)) {
                                        delegate_instance_expression = new BoxedCast (
                                                delegate_instance_expression, TypeManager.object_type);
@@ -585,29 +522,30 @@ namespace Mono.CSharp {
                public override void Emit (EmitContext ec)
                {
                        if (delegate_instance_expression == null)
-                               ec.ig.Emit (OpCodes.Ldnull);
+                               ec.Emit (OpCodes.Ldnull);
                        else
                                delegate_instance_expression.Emit (ec);
 
-                       if (!delegate_method.DeclaringType.IsSealed && delegate_method.IsVirtual && !method_group.IsBase) {
-                               ec.ig.Emit (OpCodes.Dup);
-                               ec.ig.Emit (OpCodes.Ldvirtftn, (MethodInfo) delegate_method.MetaInfo);
+                       // Any delegate must be sealed
+                       if (!delegate_method.DeclaringType.IsDelegate && delegate_method.IsVirtual && !method_group.IsBase) {
+                               ec.Emit (OpCodes.Dup);
+                               ec.Emit (OpCodes.Ldvirtftn, delegate_method);
                        } else {
-                               ec.ig.Emit (OpCodes.Ldftn, (MethodInfo) delegate_method.MetaInfo);
+                               ec.Emit (OpCodes.Ldftn, delegate_method);
                        }
 
-                       ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) constructor_method.MetaInfo);
+                       ec.Emit (OpCodes.Newobj, constructor_method);
                }
 
                void Error_ConversionFailed (ResolveContext ec, MethodSpec method, Expression return_type)
                {
-                       var invoke_method = Delegate.GetInvokeMethod (ec.Compiler, ec.CurrentType, type);
+                       var invoke_method = Delegate.GetInvokeMethod (ec.Compiler, type);
                        string member_name = delegate_instance_expression != null ?
                                Delegate.FullDelegateDesc (method) :
-                               TypeManager.GetFullNameSignature (method.MetaInfo);
+                               TypeManager.GetFullNameSignature (method);
 
                        ec.Report.SymbolRelatedToPreviousError (type);
-                       ec.Report.SymbolRelatedToPreviousError (method.MetaInfo);
+                       ec.Report.SymbolRelatedToPreviousError (method);
                        if (RootContext.Version == LanguageVersion.ISO_1) {
                                ec.Report.Error (410, loc, "A method or delegate `{0} {1}' parameters and return type must be same as delegate `{2} {3}' parameters and return type",
                                        TypeManager.CSharpName (method.ReturnType), member_name,
@@ -625,32 +563,23 @@ namespace Mono.CSharp {
                                TypeManager.CSharpName (invoke_method.ReturnType), Delegate.FullDelegateDesc (invoke_method));
                }
 
-               public static bool ImplicitStandardConversionExists (ResolveContext ec, MethodGroupExpr mg, Type target_type)
+               public static bool ImplicitStandardConversionExists (ResolveContext ec, MethodGroupExpr mg, TypeSpec target_type)
                {
                        if (target_type == TypeManager.delegate_type || target_type == TypeManager.multicast_delegate_type)
                                return false;
 
                        mg.DelegateType = target_type;
-                       var invoke = Delegate.GetInvokeMethod (ec.Compiler, null, target_type);
+                       var invoke = Delegate.GetInvokeMethod (ec.Compiler, target_type);
 
                        Arguments arguments = CreateDelegateMethodArguments (invoke.Parameters, mg.Location);
                        return mg.OverloadResolve (ec, ref arguments, true, mg.Location) != null;
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       if (delegate_instance_expression != null)
-                               delegate_instance_expression.MutateHoistedGenericType (storey);
-
-                       storey.MutateGenericMethod (delegate_method);
-                       storey.MutateConstructor (constructor_method);
-               }
-
                #region IErrorHandler Members
 
                public bool NoExactMatch (ResolveContext ec, MethodSpec method)
                {
-                       if (method.IsGenericMethod)
+                       if (method.IsGeneric)
                                return false;
 
                        Error_ConversionFailed (ec, method, null);
@@ -670,7 +599,7 @@ namespace Mono.CSharp {
        //
        public class ImplicitDelegateCreation : DelegateCreation
        {
-               ImplicitDelegateCreation (Type t, MethodGroupExpr mg, Location l)
+               ImplicitDelegateCreation (TypeSpec t, MethodGroupExpr mg, Location l)
                {
                        type = t;
                        this.method_group = mg;
@@ -678,7 +607,7 @@ namespace Mono.CSharp {
                }
 
                static public Expression Create (ResolveContext ec, MethodGroupExpr mge,
-                                                Type target_type, Location loc)
+                                                TypeSpec target_type, Location loc)
                {
                        ImplicitDelegateCreation d = new ImplicitDelegateCreation (target_type, mge, loc);
                        return d.DoResolve (ec);
@@ -695,7 +624,7 @@ namespace Mono.CSharp {
                //
                // This constructor is invoked from the `New' expression
                //
-               public NewDelegate (Type type, Arguments Arguments, Location loc)
+               public NewDelegate (TypeSpec type, Arguments Arguments, Location loc)
                {
                        this.type = type;
                        this.Arguments = Arguments;
@@ -726,9 +655,9 @@ namespace Mono.CSharp {
 
                        method_group = e as MethodGroupExpr;
                        if (method_group == null) {
-                               if (TypeManager.IsDynamicType (e.Type)) {
+                               if (e.Type == InternalType.Dynamic) {
                                        e = Convert.ImplicitConversionRequired (ec, e, type, loc);
-                               } else if (!TypeManager.IsDelegateType (e.Type)) {
+                               } else if (!e.Type.IsDelegate) {
                                        e.Error_UnexpectedKind (ec, ResolveFlags.MethodGroup | ResolveFlags.Type, loc);
                                        return null;
                                }
@@ -737,8 +666,7 @@ namespace Mono.CSharp {
                                // An argument is not a method but another delegate
                                //
                                delegate_instance_expression = e;
-                               method_group = new MethodGroupExpr (new [] { 
-                                       Delegate.GetInvokeMethod (ec.Compiler, ec.CurrentType, e.Type) }, e.Type, loc);
+                               method_group = new MethodGroupExpr (Delegate.GetInvokeMethod (ec.Compiler, e.Type), e.Type, loc);
                        }
 
                        return base.DoResolve (ec);
@@ -776,13 +704,13 @@ namespace Mono.CSharp {
                                return null;
                        }
                        
-                       Type del_type = InstanceExpr.Type;
+                       TypeSpec del_type = InstanceExpr.Type;
                        if (del_type == null)
                                return null;
                        
-                       method = Delegate.GetInvokeMethod (ec.Compiler, ec.CurrentType, del_type);
+                       method = Delegate.GetInvokeMethod (ec.Compiler, del_type);
                        var mb = method;
-                       var me = new MethodGroupExpr (new [] { mb }, del_type, loc);
+                       var me = new MethodGroupExpr (mb, del_type, loc);
                        me.InstanceExpression = InstanceExpr;
 
                        AParametersCollection pd = mb.Parameters;
@@ -804,7 +732,7 @@ namespace Mono.CSharp {
                                        is_params_applicable || (!is_applicable && params_method), false, loc);
                        }
 
-                       type = TypeManager.TypeToCoreType (method.ReturnType);
+                       type = method.ReturnType;
                        eclass = ExprClass.Value;
                        return this;
                }
@@ -825,23 +753,12 @@ namespace Mono.CSharp {
                        // Pop the return value if there is one
                        //
                        if (type != TypeManager.void_type)
-                               ec.ig.Emit (OpCodes.Pop);
+                               ec.Emit (OpCodes.Pop);
                }
 
                public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx)
                {
                        return Invocation.MakeExpression (ctx, InstanceExpr, method, arguments);
                }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       storey.MutateGenericMethod (method);
-                       type = storey.MutateType (type);
-
-                       if (arguments != null)
-                               arguments.MutateHoistedGenericType (storey);
-
-                       InstanceExpr.MutateHoistedGenericType (storey);
-               }
        }
 }
index f3b20963a8c9ea882aaa582d480ab9150a8b76c5..cab6cf8fa57ebbb9ef535529e37800283b267755 100644 (file)
@@ -1,6 +1,6 @@
 <?xml version="1.0"?> 
 <configuration>
        <startup>
-               <supportedRuntime version="v4.0.30128"/>
+               <supportedRuntime version="v4.0.30319"/>
        </startup>
 </configuration>
index 2eb06b554237663998241f48097da9017a656b39..8b8dfeecc8b370a395d21887919c7685440ce554 100644 (file)
@@ -21,6 +21,7 @@ using System.Security;
 using System.Security.Permissions;
 using System.Text;
 using System.Xml;
+using System.Linq;
 
 using Mono.CompilerServices.SymbolWriter;
 
@@ -53,10 +54,6 @@ namespace Mono.CSharp {
                                foreach (TypeContainer tc in t.Types)
                                        tc.GenerateDocComment (t);
 
-                       if (t.Delegates != null)
-                               foreach (Delegate de in t.Delegates)
-                                       de.GenerateDocComment (t);
-
                        if (t.Constants != null)
                                foreach (Const c in t.Constants)
                                        c.GenerateDocComment (t);
@@ -261,7 +258,7 @@ namespace Mono.CSharp {
                // returns a full runtime type name from a name which might
                // be C# specific type name.
                //
-               private static Type FindDocumentedType (MemberCore mc, string name, DeclSpace ds, string cref, Report r)
+               private static TypeSpec FindDocumentedType (MemberCore mc, string name, DeclSpace ds, string cref, Report r)
                {
                        bool is_array = false;
                        string identifier = name;
@@ -272,13 +269,13 @@ namespace Mono.CSharp {
                                        is_array = true;
                                }
                        }
-                       Type t = FindDocumentedTypeNonArray (mc, identifier, ds, cref, r);
+                       TypeSpec t = FindDocumentedTypeNonArray (mc, identifier, ds, cref, r);
                        if (t != null && is_array)
-                               t = Array.CreateInstance (t, 0).GetType ();
+                               t = Import.ImportType (Array.CreateInstance (t.GetMetaInfo (), 0).GetType ());
                        return t;
                }
 
-               private static Type FindDocumentedTypeNonArray (MemberCore mc, 
+               private static TypeSpec FindDocumentedTypeNonArray (MemberCore mc, 
                        string identifier, DeclSpace ds, string cref, Report r)
                {
                        switch (identifier) {
@@ -315,7 +312,7 @@ namespace Mono.CSharp {
                        case "void":
                                return TypeManager.void_type;;
                        }
-                       FullNamedExpression e = ds.LookupNamespaceOrType (identifier, mc.Location, false);
+                       FullNamedExpression e = ds.LookupNamespaceOrType (identifier, 0, mc.Location, false);
                        if (e != null) {
                                if (!(e is TypeExpr))
                                        return null;
@@ -325,152 +322,67 @@ namespace Mono.CSharp {
                        if (index < 0)
                                return null;
                        int warn;
-                       Type parent = FindDocumentedType (mc, identifier.Substring (0, index), ds, cref, r);
+                       TypeSpec parent = FindDocumentedType (mc, identifier.Substring (0, index), ds, cref, r);
                        if (parent == null)
                                return null;
                        // no need to detect warning 419 here
-                       return FindDocumentedMember (mc, parent,
+                       var ts = FindDocumentedMember (mc, parent,
                                identifier.Substring (index + 1),
-                               null, ds, out warn, cref, false, null, r).Member as Type;
-               }
-
-               private static MemberInfo [] empty_member_infos =
-                       new MemberInfo [0];
-
-               private static MemberInfo [] FindMethodBase (Type type,
-                       BindingFlags binding_flags, MethodSignature signature)
-               {
-                       MemberList ml = TypeManager.FindMembers (
-                               type,
-                               MemberTypes.Constructor | MemberTypes.Method | MemberTypes.Property | MemberTypes.Custom,
-                               binding_flags,
-                               MethodSignature.method_signature_filter,
-                               signature);
-                       if (ml == null)
-                               return empty_member_infos;
-
-                       return FilterOverridenMembersOut ((MemberInfo []) ml);
-               }
-
-               static bool IsOverride (PropertyInfo deriv_prop, PropertyInfo base_prop)
-               {
-                       if (!MethodGroupExpr.IsAncestralType (base_prop.DeclaringType, deriv_prop.DeclaringType))
-                               return false;
-
-                       Type [] deriv_pd = TypeManager.GetParameterData (deriv_prop).Types;
-                       Type [] base_pd = TypeManager.GetParameterData (base_prop).Types;
-               
-                       if (deriv_pd.Length != base_pd.Length)
-                               return false;
-
-                       for (int j = 0; j < deriv_pd.Length; ++j) {
-                               if (deriv_pd [j] != base_pd [j])
-                                       return false;
-                               Type ct = TypeManager.TypeToCoreType (deriv_pd [j]);
-                               Type bt = TypeManager.TypeToCoreType (base_pd [j]);
-
-                               if (ct != bt)
-                                       return false;
-                       }
-
-                       return true;
-               }
-
-               private static MemberInfo [] FilterOverridenMembersOut (
-                       MemberInfo [] ml)
-               {
-                       if (ml == null)
-                               return empty_member_infos;
-
-                       var al = new List<MemberInfo> (ml.Length);
-                       for (int i = 0; i < ml.Length; i++) {
-                               MethodBase mx = ml [i] as MethodBase;
-                               PropertyInfo px = ml [i] as PropertyInfo;
-                               if (mx != null || px != null) {
-                                       bool overriden = false;
-                                       for (int j = 0; j < ml.Length; j++) {
-                                               if (j == i)
-                                                       continue;
-                                               MethodBase my = ml [j] as MethodBase;
-                                               if (mx != null && my != null &&
-                                                       MethodGroupExpr.IsOverride (my, mx)) {
-                                                       overriden = true;
-                                                       break;
-                                               }
-                                               else if (mx != null)
-                                                       continue;
-                                               PropertyInfo py = ml [j] as PropertyInfo;
-                                               if (px != null && py != null &&
-                                                       IsOverride (py, px)) {
-                                                       overriden = true;
-                                                       break;
-                                               }
-                                       }
-                                       if (overriden)
-                                               continue;
-                               }
-                               al.Add (ml [i]);
-                       }
-                       return al.ToArray ();
-               }
-
-               struct FoundMember
-               {
-                       public static FoundMember Empty = new FoundMember (true);
-
-                       public bool IsEmpty;
-                       public readonly MemberInfo Member;
-                       public readonly Type Type;
-
-                       public FoundMember (bool regardless_of_this_value_its_empty)
-                       {
-                               IsEmpty = true;
-                               Member = null;
-                               Type = null;
-                       }
-
-                       public FoundMember (Type found_type, MemberInfo member)
-                       {
-                               IsEmpty = false;
-                               Type = found_type;
-                               Member = member;
-                       }
+                               null, ds, out warn, cref, false, null, r) as TypeSpec;
+                       if (ts != null)
+                               return ts;
+                       return null;
                }
 
                //
                // Returns a MemberInfo that is referenced in XML documentation
                // (by "see" or "seealso" elements).
                //
-               private static FoundMember FindDocumentedMember (MemberCore mc,
-                       Type type, string member_name, Type [] param_list, 
+               private static MemberSpec FindDocumentedMember (MemberCore mc,
+                       TypeSpec type, string member_name, AParametersCollection param_list, 
                        DeclSpace ds, out int warning_type, string cref,
                        bool warn419, string name_for_error, Report r)
                {
-                       for (; type != null; type = type.DeclaringType) {
-                               MemberInfo mi = FindDocumentedMemberNoNest (
+//                     for (; type != null; type = type.DeclaringType) {
+                               var mi = FindDocumentedMemberNoNest (
                                        mc, type, member_name, param_list, ds,
                                        out warning_type, cref, warn419,
                                        name_for_error, r);
                                if (mi != null)
-                                       return new FoundMember (type, mi);
-                       }
+                                       return mi; // new FoundMember (type, mi);
+//                     }
                        warning_type = 0;
-                       return FoundMember.Empty;
+                       return null;
                }
 
-               private static MemberInfo FindDocumentedMemberNoNest (
-                       MemberCore mc, Type type, string member_name,
-                       Type [] param_list, DeclSpace ds, out int warning_type, 
+               private static MemberSpec FindDocumentedMemberNoNest (
+                       MemberCore mc, TypeSpec type, string member_name,
+                       AParametersCollection param_list, DeclSpace ds, out int warning_type, 
                        string cref, bool warn419, string name_for_error, Report Report)
                {
                        warning_type = 0;
-                       MemberInfo [] mis;
+                       var filter = new MemberFilter (member_name, 0, MemberKind.All, param_list, null);
+                       IList<MemberSpec> found = null;
+                       while (type != null && found == null) {
+                               found = MemberCache.FindMembers (type, filter, BindingRestriction.None);
+                               type = type.DeclaringType;
+                       }
+
+                       if (found == null)
+                               return null;
 
+                       if (warn419 && found.Count > 1) {
+                               Report419 (mc, name_for_error, found.ToArray (), Report);
+                       }
+
+                       return found [0];
+
+/*
                        if (param_list == null) {
                                // search for fields/events etc.
                                mis = TypeManager.MemberLookup (type, null,
-                                       type, MemberTypes.All,
-                                       BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
+                                       type, MemberKind.All,
+                                       BindingRestriction.None,
                                        member_name, null);
                                mis = FilterOverridenMembersOut (mis);
                                if (mis == null || mis.Length == 0)
@@ -538,14 +450,14 @@ namespace Mono.CSharp {
                                msig);
                        if (mis.Length == 0)
                                return null; // CS1574
-                       MemberInfo mi = mis [0];
-                       Type expected = mi is MethodInfo ?
-                               ((MethodInfo) mi).ReturnType :
-                               mi is PropertyInfo ?
-                               ((PropertyInfo) mi).PropertyType :
+                       var mi = mis [0];
+                       TypeSpec expected = mi is MethodSpec ?
+                               ((MethodSpec) mi).ReturnType :
+                               mi is PropertySpec ?
+                               ((PropertySpec) mi).PropertyType :
                                null;
                        if (return_type_name != null) {
-                               Type returnType = FindDocumentedType (mc, return_type_name, ds, cref, Report);
+                               TypeSpec returnType = FindDocumentedType (mc, return_type_name, ds, cref, Report);
                                if (returnType == null || returnType != expected) {
                                        warning_type = 1581;
                                        Report.Warning (1581, 1, mc.Location, "Invalid return type in XML comment cref attribute `{0}'", cref);
@@ -553,19 +465,7 @@ namespace Mono.CSharp {
                                }
                        }
                        return mis [0];
-               }
-
-               private static bool IsAmbiguous (MemberInfo [] members)
-               {
-                       if (members.Length < 2)
-                               return false;
-                       if (members.Length > 2)
-                               return true;
-                       if (members [0] is EventInfo && members [1] is FieldInfo)
-                               return false;
-                       if (members [1] is EventInfo && members [0] is FieldInfo)
-                               return false;
-                       return true;
+*/ 
                }
 
                //
@@ -638,18 +538,18 @@ namespace Mono.CSharp {
                        }
 
                        // check if parameters are valid
-                       Type [] parameter_types;
+                       AParametersCollection parameter_types;
                        if (parameters == null)
                                parameter_types = null;
                        else if (parameters.Length == 0)
-                               parameter_types = Type.EmptyTypes;
+                               parameter_types = ParametersCompiled.EmptyReadOnlyParameters;
                        else {
                                string [] param_list = parameters.Split (',');
-                               var plist = new List<Type> ();
+                               var plist = new List<TypeSpec> ();
                                for (int i = 0; i < param_list.Length; i++) {
                                        string param_type_name = param_list [i].Trim (wsChars);
                                        Normalize (mc, ref param_type_name, Report);
-                                       Type param_type = FindDocumentedType (mc, param_type_name, ds, cref, Report);
+                                       TypeSpec param_type = FindDocumentedType (mc, param_type_name, ds, cref, Report);
                                        if (param_type == null) {
                                                Report.Warning (1580, 1, mc.Location, "Invalid type for parameter `{0}' in XML comment cref attribute `{1}'",
                                                        (i + 1).ToString (), cref);
@@ -657,13 +557,14 @@ namespace Mono.CSharp {
                                        }
                                        plist.Add (param_type);
                                }
-                               parameter_types = plist.ToArray ();
+
+                               parameter_types = ParametersCompiled.CreateFullyResolved (plist.ToArray ());
                        }
 
-                       Type type = FindDocumentedType (mc, name, ds, cref, Report);
+                       TypeSpec type = FindDocumentedType (mc, name, ds, cref, Report);
                        if (type != null
                                // delegate must not be referenced with args
-                               && (!TypeManager.IsDelegateType (type)
+                               && (!type.IsDelegate
                                || parameter_types == null)) {
                                string result = GetSignatureForDoc (type)
                                        + (brace_pos < 0 ? String.Empty : signature.Substring (brace_pos));
@@ -675,36 +576,36 @@ namespace Mono.CSharp {
                        if (period > 0) {
                                string typeName = name.Substring (0, period);
                                string member_name = name.Substring (period + 1);
+                               string lookup_name = member_name == "this" ? MemberCache.IndexerNameAlias : member_name;
+                               Normalize (mc, ref lookup_name, Report);
                                Normalize (mc, ref member_name, Report);
                                type = FindDocumentedType (mc, typeName, ds, cref, Report);
                                int warn_result;
                                if (type != null) {
-                                       FoundMember fm = FindDocumentedMember (mc, type, member_name, parameter_types, ds, out warn_result, cref, true, name, Report);
+                                       var mi = FindDocumentedMember (mc, type, lookup_name, parameter_types, ds, out warn_result, cref, true, name, Report);
                                        if (warn_result > 0)
                                                return;
-                                       if (!fm.IsEmpty) {
-                                               MemberInfo mi = fm.Member;
+                                       if (mi != null) {
                                                // we cannot use 'type' directly
                                                // to get its name, since mi
                                                // could be from DeclaringType
                                                // for nested types.
-                                               xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + GetSignatureForDoc (fm.Type) + "." + member_name + GetParametersFormatted (mi));
+                                               xref.SetAttribute ("cref", GetMemberDocHead (mi) + GetSignatureForDoc (mi.DeclaringType) + "." + member_name + GetParametersFormatted (mi));
                                                return; // a member of a type
                                        }
                                }
-                       }
-                       else {
+                       } else {
                                int warn_result;
-                               FoundMember fm = FindDocumentedMember (mc, ds.TypeBuilder, name, parameter_types, ds, out warn_result, cref, true, name, Report);
+                               var mi = FindDocumentedMember (mc, ds.PartialContainer.Definition, name, parameter_types, ds, out warn_result, cref, true, name, Report);
+
                                if (warn_result > 0)
                                        return;
-                               if (!fm.IsEmpty) {
-                                       MemberInfo mi = fm.Member;
+                               if (mi != null) {
                                        // we cannot use 'type' directly
                                        // to get its name, since mi
                                        // could be from DeclaringType
                                        // for nested types.
-                                       xref.SetAttribute ("cref", GetMemberDocHead (mi.MemberType) + GetSignatureForDoc (fm.Type) + "." + name + GetParametersFormatted (mi));
+                                       xref.SetAttribute ("cref", GetMemberDocHead (mi) + GetSignatureForDoc (mi.DeclaringType) + "." + name + GetParametersFormatted (mi));
                                        return; // local member name
                                }
                        }
@@ -726,33 +627,25 @@ namespace Mono.CSharp {
                        xref.SetAttribute ("cref", "!:" + name);
                }
 
-               static string GetParametersFormatted (MemberInfo mi)
+               static string GetParametersFormatted (MemberSpec mi)
                {
-                       MethodBase mb = mi as MethodBase;
-                       bool is_setter = false;
-                       PropertyInfo pi = mi as PropertyInfo;
-                       if (pi != null) {
-                               mb = pi.GetGetMethod ();
-                               if (mb == null) {
-                                       is_setter = true;
-                                       mb = pi.GetSetMethod ();
-                               }
-                       }
-                       if (mb == null)
-                               return String.Empty;
+                       var pm = mi as IParametersMember;
+                       if (pm == null || pm.Parameters.IsEmpty)
+                               return string.Empty;
 
-                       AParametersCollection parameters = TypeManager.GetParameterData (mb);
+                       AParametersCollection parameters = pm.Parameters;
+/*
                        if (parameters == null || parameters.Count == 0)
                                return String.Empty;
-
+*/
                        StringBuilder sb = new StringBuilder ();
                        sb.Append ('(');
                        for (int i = 0; i < parameters.Count; i++) {
-                               if (is_setter && i + 1 == parameters.Count)
-                                       break; // skip "value".
+//                             if (is_setter && i + 1 == parameters.Count)
+//                                     break; // skip "value".
                                if (i > 0)
                                        sb.Append (',');
-                               Type t = parameters.Types [i];
+                               TypeSpec t = parameters.Types [i];
                                sb.Append (GetSignatureForDoc (t));
                        }
                        sb.Append (')');
@@ -773,7 +666,7 @@ namespace Mono.CSharp {
                        return identifier;
                }
 
-               static void Report419 (MemberCore mc, string member_name, MemberInfo [] mis, Report Report)
+               static void Report419 (MemberCore mc, string member_name, MemberSpec [] mis, Report Report)
                {
                        Report.Warning (419, 3, mc.Location, 
                                "Ambiguous reference in cref attribute `{0}'. Assuming `{1}' but other overloads including `{2}' have also matched",
@@ -786,22 +679,19 @@ namespace Mono.CSharp {
                // Get a prefix from member type for XML documentation (used
                // to formalize cref target name).
                //
-               static string GetMemberDocHead (MemberTypes type)
+               static string GetMemberDocHead (MemberSpec type)
                {
-                       switch (type) {
-                       case MemberTypes.Constructor:
-                       case MemberTypes.Method:
+                       if (type is FieldSpec)
+                               return "F:";
+                       if (type is MethodSpec)
                                return "M:";
-                       case MemberTypes.Event:
+                       if (type is EventSpec)
                                return "E:";
-                       case MemberTypes.Field:
-                               return "F:";
-                       case MemberTypes.NestedType:
-                       case MemberTypes.TypeInfo:
-                               return "T:";
-                       case MemberTypes.Property:
+                       if (type is PropertySpec)
                                return "P:";
-                       }
+                       if (type is TypeSpec)
+                               return "T:";
+
                        return "!:";
                }
 
@@ -840,32 +730,35 @@ namespace Mono.CSharp {
                                switch (op.OperatorType) {
                                case Operator.OpType.Implicit:
                                case Operator.OpType.Explicit:
-                                       suffix = "~" + GetSignatureForDoc (op.MethodBuilder.ReturnType);
+                                       suffix = "~" + GetSignatureForDoc (op.ReturnType);
                                        break;
                                }
                        }
                        return String.Concat (mc.DocCommentHeader, ds.Name, ".", name, paramSpec, suffix);
                }
 
-               static string GetSignatureForDoc (Type type)
+               static string GetSignatureForDoc (TypeSpec type)
                {
-                       if (TypeManager.IsGenericParameter (type))
-                               return (type.DeclaringMethod != null ? "``" : "`") + TypeManager.GenericParameterPosition (type);
+                       var tp = type as TypeParameterSpec;
+                       if (tp != null) {
+                               var prefix = tp.IsMethodOwned ? "``" : "`";
+                               return prefix + tp.DeclaredPosition;
+                       }
 
                        if (TypeManager.IsGenericType (type)) {
-                               string g = type.Namespace;
+                               string g = type.MemberDefinition.Namespace;
                                if (g != null && g.Length > 0)
                                        g += '.';
                                int idx = type.Name.LastIndexOf ('`');
                                g += (idx < 0 ? type.Name : type.Name.Substring (0, idx)) + '{';
                                int argpos = 0;
-                               foreach (Type t in type.GetGenericArguments ())
+                               foreach (TypeSpec t in TypeManager.GetTypeArguments (type))
                                        g += (argpos++ > 0 ? "," : String.Empty) + GetSignatureForDoc (t);
                                g += '}';
                                return g;
                        }
 
-                       string name = type.FullName != null ? type.FullName : type.Name;
+                       string name = type.GetMetaInfo ().FullName != null ? type.GetMetaInfo ().FullName : type.Name;
                        return name.Replace ("+", ".").Replace ('&', '@');
                }
 
@@ -884,7 +777,7 @@ namespace Mono.CSharp {
                                string xname = pelem.GetAttribute ("name");
                                if (xname.Length == 0)
                                        continue; // really? but MS looks doing so
-                               if (xname != "" && mc.Parameters.GetParameterIndexByName (xname) < 0)
+                               if (xname != "" && mc.ParameterInfo.GetParameterIndexByName (xname) < 0)
                                        Report.Warning (1572, 2, mc.Location, "XML comment on `{0}' has a param tag for `{1}', but there is no parameter by that name",
                                                mc.GetSignatureForError (), xname);
                                else if (paramTags.ContainsKey (xname))
@@ -892,7 +785,7 @@ namespace Mono.CSharp {
                                                mc.GetSignatureForError (), xname);
                                paramTags [xname] = xname;
                        }
-                       IParameterData [] plist = mc.Parameters.FixedParameters;
+                       IParameterData [] plist = mc.ParameterInfo.FixedParameters;
                        foreach (Parameter p in plist) {
                                if (paramTags.Count > 0 && !paramTags.ContainsKey (p.Name))
                                        Report.Warning (1573, 4, mc.Location, "Parameter `{0}' has no matching param tag in the XML comment for `{1}'",
@@ -1009,10 +902,6 @@ namespace Mono.CSharp {
                        if (root.Types != null)
                                foreach (TypeContainer tc in root.Types)
                                        DocUtil.GenerateTypeDocComment (tc, null, r);
-
-                       if (root.Delegates != null)
-                               foreach (Delegate d in root.Delegates) 
-                                       DocUtil.GenerateDocComment (d, null, r);
                }
        }
 }
index 316b0901fd8917ac5bcecfbe540075c44ac7986e..2ec21ee01647a1c28bb7747d10f5d4da2915c7bc 100644 (file)
@@ -1650,6 +1650,8 @@ namespace Mono.CSharp
                {
                        // TODO: Should be passed to parser as an argument
                        RootContext.ToplevelTypes = new ModuleCompiled (ctx, RootContext.Unsafe);
+                       var ctypes = TypeManager.InitCoreTypes ();
+                       TypeManager.InitExpressionTypes ();
 
                        Parse ();
                        if (Report.Errors > 0)
@@ -1702,6 +1704,7 @@ namespace Mono.CSharp
                        if (timestamps)
                                ShowTime ("Loading references");
 
+                       Import.Initialize ();
                        LoadReferences ();
                        
                        if (modules.Count > 0) {
@@ -1712,7 +1715,7 @@ namespace Mono.CSharp
                        if (timestamps)
                                ShowTime ("References loaded");
                        
-                       if (!TypeManager.InitCoreTypes (ctx) || Report.Errors > 0)
+                       if (!TypeManager.InitCoreTypes (ctx, ctypes))
                                return false;
 
                        TypeManager.InitOptionalCoreTypes (ctx);
@@ -1731,8 +1734,7 @@ namespace Mono.CSharp
                                return false;
                        if (timestamps)
                                ShowTime ("Populate tree");
-                       if (!RootContext.StdLib)
-                               RootContext.BootCorlib_PopulateCoreTypes ();
+
                        RootContext.PopulateTypes ();
 
                        if (Report.Errors == 0 &&
@@ -1755,7 +1757,6 @@ namespace Mono.CSharp
                        if (RootContext.VerifyClsCompliance) {
                                if (CodeGen.Assembly.IsClsCompliant) {
                                        AttributeTester.VerifyModulesClsCompliance (ctx);
-                                       TypeManager.LoadAllImportedTypes ();
                                }
                        }
                        if (Report.Errors > 0)
@@ -2024,19 +2025,28 @@ namespace Mono.CSharp
                {
                        Driver.Reset ();
                        CSharpParser.yacc_verbose_flag = 0;
-                       RootContext.Reset (full_flag);
                        Location.Reset ();
+
+                       if (!full_flag)
+                               return;
+
+                       RootContext.Reset (full_flag);
                        TypeManager.Reset ();
                        PredefinedAttributes.Reset ();
-                       TypeHandle.Reset ();
-
-                       if (full_flag)
-                               GlobalRootNamespace.Reset ();
+                       ArrayContainer.Reset ();
+                       ReferenceContainer.Reset ();
+                       PointerContainer.Reset ();
+                       Parameter.Reset ();
+
+                       GlobalRootNamespace.Reset ();
+                       Unary.Reset ();
+                       Binary.Reset ();
+                       ConstantFold.Reset ();
+                       CastFromDecimal.Reset ();
                        
                        NamespaceEntry.Reset ();
                        CodeGen.Reset ();
                        Attribute.Reset ();
-                       AttributeTester.Reset ();
                        AnonymousTypeClass.Reset ();
                        AnonymousMethodBody.Reset ();
                        AnonymousMethodStorey.Reset ();
index 09287b4f744aa09e09d796e8b9c8473b9abe2965..3a466401fb857036e2506f1ab314108f870ab70f 100644 (file)
@@ -71,19 +71,18 @@ namespace Mono.CSharp
 #if !NET_4_0
                public class DynamicMetaObject
                {
-                       public Type RuntimeType;
-                       public Type LimitType;
+                       public TypeSpec RuntimeType;
+                       public TypeSpec LimitType;
                        public SLE.Expression Expression;
                }
 #endif
 
                readonly DynamicMetaObject obj;
 
-               public RuntimeValueExpression (DynamicMetaObject obj, bool isCompileTimeType)
+               public RuntimeValueExpression (DynamicMetaObject obj, TypeSpec type)
                {
                        this.obj = obj;
-                       this.type = isCompileTimeType ? obj.LimitType : obj.RuntimeType;
-                       this.type = obj.LimitType;
+                       this.type = type;
                        this.eclass = ExprClass.Variable;
                }
 
@@ -133,7 +132,7 @@ namespace Mono.CSharp
 
                public override SLE.Expression MakeExpression (BuilderContext ctx)
                {
-                       return SLE.Expression.Convert (obj.Expression, type);
+                       return SLE.Expression.Convert (obj.Expression, type.GetMetaInfo ());
                }
 
                public DynamicMetaObject MetaObject {
@@ -148,7 +147,7 @@ namespace Mono.CSharp
        //
        public class DynamicResultCast : ShimExpression
        {
-               public DynamicResultCast (Type type, Expression expr)
+               public DynamicResultCast (TypeSpec type, Expression expr)
                        : base (expr)
                {
                        this.type = type;
@@ -164,7 +163,7 @@ namespace Mono.CSharp
 #if NET_4_0
                public override SLE.Expression MakeExpression (BuilderContext ctx)
                {
-                       return SLE.Expression.Block (expr.MakeExpression (ctx), SLE.Expression.Default (type));
+                       return SLE.Expression.Block (expr.MakeExpression (ctx), SLE.Expression.Default (type.GetMetaInfo ()));
                }
 #endif
        }
@@ -261,6 +260,7 @@ namespace Mono.CSharp
                        if (global_site_container == null) {
                                global_site_container = new StaticDataClass ();
                                RootContext.ToplevelTypes.AddCompilerGeneratedClass (global_site_container);
+                               global_site_container.CreateType ();
                                global_site_container.DefineType ();
                                global_site_container.Define ();
                        }
@@ -310,7 +310,7 @@ namespace Mono.CSharp
 
                        if (TypeManager.generic_call_site_type == null)
                                TypeManager.generic_call_site_type = TypeManager.CoreLookupType (rc.Compiler,
-                                       "System.Runtime.CompilerServices", "CallSite`1", MemberKind.Class, true);
+                                       "System.Runtime.CompilerServices", "CallSite", 1, MemberKind.Class, true);
 
                        if (TypeManager.binder_flags == null) {
                                TypeManager.binder_flags = TypeManager.CoreLookupType (rc.Compiler,
@@ -346,7 +346,7 @@ namespace Mono.CSharp
                        TypeExpr site_type = CreateSiteType (RootContext.ToplevelTypes.Compiler, arguments, dyn_args_count, isStatement);
                        FieldExpr site_field_expr = new FieldExpr (CreateSiteField (site_type), loc);
 
-                       SymbolWriter.OpenCompilerGeneratedBlock (ec.ig);
+                       SymbolWriter.OpenCompilerGeneratedBlock (ec);
 
                        Arguments args = new Arguments (1);
                        args.Add (new Argument (binder));
@@ -376,7 +376,7 @@ namespace Mono.CSharp
                        if (target != null)
                                target.Emit (ec);
 
-                       SymbolWriter.CloseCompilerGeneratedBlock (ec.ig);
+                       SymbolWriter.CloseCompilerGeneratedBlock (ec);
                }
 
                public static MemberAccess GetBinderNamespace (Location loc)
@@ -398,7 +398,7 @@ namespace Mono.CSharp
                        FullNamedExpression[] targs = new FullNamedExpression[dyn_args_count + default_args];
                        targs [0] = new TypeExpression (TypeManager.call_site_type, loc);
                        for (int i = 0; i < dyn_args_count; ++i) {
-                               Type arg_type;
+                               TypeSpec arg_type;
                                Argument a = arguments [i];
                                if (a.Type == TypeManager.null_type)
                                        arg_type = TypeManager.object_type;
@@ -413,9 +413,9 @@ namespace Mono.CSharp
 
                        TypeExpr del_type = null;
                        if (!has_ref_out_argument) {
-                               string d_name = is_statement ? "Action`" : "Func`";
+                               string d_name = is_statement ? "Action" : "Func";
 
-                               Type t = TypeManager.CoreLookupType (ctx, "System", d_name + (dyn_args_count + default_args), MemberKind.Delegate, false);
+                               TypeSpec t = TypeManager.CoreLookupType (ctx, "System", d_name, dyn_args_count + default_args, MemberKind.Delegate, false);
                                if (t != null) {
                                        if (!is_statement)
                                                targs [targs.Length - 1] = new TypeExpression (type, loc);
@@ -428,7 +428,7 @@ namespace Mono.CSharp
                        // Create custom delegate when no appropriate predefined one is found
                        //
                        if (del_type == null) {
-                               Type rt = is_statement ? TypeManager.void_type : type;
+                               TypeSpec rt = is_statement ? TypeManager.void_type : type;
                                Parameter[] p = new Parameter [dyn_args_count + 1];
                                p[0] = new Parameter (targs [0], "p0", Parameter.Modifier.NONE, null, loc);
 
@@ -441,12 +441,13 @@ namespace Mono.CSharp
                                        new MemberName ("Container" + container_counter++.ToString ("X")),
                                        new ParametersCompiled (ctx, p), null);
 
+                               d.CreateType ();
                                d.DefineType ();
                                d.Define ();
                                d.Emit ();
 
                                parent.AddDelegate (d);
-                               del_type = new TypeExpression (d.TypeBuilder, loc);
+                               del_type = new TypeExpression (d.Definition, loc);
                        }
 
                        TypeExpr site_type = new GenericTypeExpr (TypeManager.generic_call_site_type, new TypeArguments (del_type), loc);
@@ -502,7 +503,7 @@ namespace Mono.CSharp
 
        class DynamicConversion : DynamicExpressionStatement, IDynamicBinder
        {
-               public DynamicConversion (Type targetType, CSharpBinderFlags flags, Arguments args, Location loc)
+               public DynamicConversion (TypeSpec targetType, CSharpBinderFlags flags, Arguments args, Location loc)
                        : base (null, args, loc)
                {
                        type = targetType;
@@ -525,7 +526,7 @@ namespace Mono.CSharp
 
        class DynamicConstructorBinder : DynamicExpressionStatement, IDynamicBinder
        {
-               public DynamicConstructorBinder (Type type, Arguments args, Location loc)
+               public DynamicConstructorBinder (TypeSpec type, Arguments args, Location loc)
                        : base (null, args, loc)
                {
                        this.type = type;
@@ -574,7 +575,7 @@ namespace Mono.CSharp
                        this.member = member;
                }
 
-               public DynamicInvocation (ATypeNameExpression member, Arguments args, Type type, Location loc)
+               public DynamicInvocation (ATypeNameExpression member, Arguments args, TypeSpec type, Location loc)
                        : this (member, args, loc)
                {
                        // When a return type is known not to be dynamic
@@ -610,7 +611,7 @@ namespace Mono.CSharp
                                TypeArguments ta = member.TypeArguments;
                                if (ta.Resolve (ec)) {
                                        var targs = new ArrayInitializer (ta.Count, loc);
-                                       foreach (Type t in ta.Arguments)
+                                       foreach (TypeSpec t in ta.Arguments)
                                                targs.Add (new TypeOf (new TypeExpression (t, loc), loc));
 
                                        binder_args.Add (new Argument (new ImplicitlyTypedArrayCreation ("[]", targs, loc)));
index 336bd0be58b5ac78caaaeb36840a2634eedac569..ab04c7cb904237a2e574c67896151998bd00cb88 100644 (file)
@@ -120,10 +120,10 @@ namespace Mono.CSharp {
        /// </remarks>
        public abstract class Expression {
                public ExprClass eclass;
-               protected Type type;
+               protected TypeSpec type;
                protected Location loc;
                
-               public Type Type {
+               public TypeSpec Type {
                        get { return type; }
                        set { type = value; }
                }
@@ -137,19 +137,12 @@ namespace Mono.CSharp {
                {
                }
 
-               public virtual bool GetAttributableValue (ResolveContext ec, Type value_type, out object value)
-               {
-                       Attribute.Error_AttributeArgumentNotValid (ec, loc);
-                       value = null;
-                       return false;
-               }
-
                public virtual string GetSignatureForError ()
                {
-                       return TypeManager.CSharpName (type);
+                       return type.GetDefinition ().GetSignatureForError ();
                }
 
-               public static bool IsAccessorAccessible (Type invocation_type, MethodSpec mi, out bool must_do_cs1540_check)
+               public static bool IsMemberAccessible (TypeSpec invocation_type, MemberSpec mi, out bool must_do_cs1540_check)
                {
                        var ma = mi.Modifiers & Modifiers.AccessibilityMask;
 
@@ -157,16 +150,17 @@ namespace Mono.CSharp {
 
                        if (ma == Modifiers.PUBLIC)
                                return true;
-                       
+               
                        //
                        // If only accessible to the current class or children
                        //
                        if (ma == Modifiers.PRIVATE)
-                               return TypeManager.IsPrivateAccessible (invocation_type, mi.DeclaringType) ||
+                               return invocation_type.MemberDefinition == mi.DeclaringType.MemberDefinition ||
                                        TypeManager.IsNestedChildOf (invocation_type, mi.DeclaringType);
 
                        if ((ma & Modifiers.INTERNAL) != 0) {
-                               var b = TypeManager.IsThisOrFriendAssembly (invocation_type.Assembly, mi.DeclaringType.Assembly);
+                               var b = TypeManager.IsThisOrFriendAssembly (invocation_type == InternalType.FakeInternalType ?
+                                        CodeGen.Assembly.Builder : invocation_type.Assembly, mi.DeclaringType.Assembly);
                                if (b || ma == Modifiers.INTERNAL)
                                        return b;
                        }
@@ -252,43 +246,7 @@ namespace Mono.CSharp {
                // value will be returned if the expression is not a type
                // reference
                //
-               public virtual TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
-               {
-                       TypeExpr te = ResolveAsBaseTerminal (ec, silent);
-                       if (te == null)
-                               return null;
-
-                       if (!silent) { // && !(te is TypeParameterExpr)) {
-                               ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (te.Type);
-                               if (obsolete_attr != null && !ec.IsObsolete) {
-                                       AttributeTester.Report_ObsoleteMessage (obsolete_attr, te.GetSignatureForError (), Location, ec.Compiler.Report);
-                               }
-                       }
-
-                       GenericTypeExpr ct = te as GenericTypeExpr;
-                       if (ct != null) {
-                               //
-                               // TODO: Constrained type parameters check for parameters of generic method overrides is broken
-                               // There are 2 solutions.
-                               // 1, Skip this check completely when we are in override/explicit impl scope
-                               // 2, Copy type parameters constraints from base implementation and pass (they have to be emitted anyway)
-                               //
-                               MemberCore gm = ec as GenericMethod;
-                               if (gm == null)
-                                       gm = ec as Method;
-                               if (gm != null && ((gm.ModFlags & Modifiers.OVERRIDE) != 0 || gm.MemberName.Left != null)) {
-                                       te.loc = loc;
-                                       return te;
-                               }
-
-                               // TODO: silent flag is ignored
-                               ct.CheckConstraints (ec);
-                       }
-
-                       return te;
-               }
-       
-               public TypeExpr ResolveAsBaseTerminal (IMemberContext ec, bool silent)
+               public virtual TypeExpr ResolveAsTypeTerminal (IMemberContext ec , bool silent)
                {
                        int errors = ec.Compiler.Report.Errors;
 
@@ -307,23 +265,34 @@ namespace Mono.CSharp {
                        if (!te.CheckAccessLevel (ec)) {
                                ec.Compiler.Report.SymbolRelatedToPreviousError (te.Type);
                                ErrorIsInaccesible (loc, TypeManager.CSharpName (te.Type), ec.Compiler.Report);
-                               return null;
                        }
 
                        te.loc = loc;
+
+                       //
+                       // Obsolete checks cannot be done when resolving base context as they
+                       // require type dependecies to be set but we are just resolving them
+                       //
+                       if (!silent && !(ec is TypeContainer.BaseContext)) {
+                               ObsoleteAttribute obsolete_attr = te.Type.GetAttributeObsolete ();
+                               if (obsolete_attr != null && !ec.IsObsolete) {
+                                       AttributeTester.Report_ObsoleteMessage (obsolete_attr, te.GetSignatureForError (), Location, ec.Compiler.Report);
+                               }
+                       }
+
                        return te;
                }
-
+       
                public static void ErrorIsInaccesible (Location loc, string name, Report Report)
                {
                        Report.Error (122, loc, "`{0}' is inaccessible due to its protection level", name);
                }
 
-               protected static void Error_CannotAccessProtected (ResolveContext ec, Location loc, MemberInfo m, Type qualifier, Type container)
+               protected static void Error_CannotAccessProtected (ResolveContext ec, Location loc, MemberSpec m, TypeSpec qualifier, TypeSpec container)
                {
                        ec.Report.Error (1540, loc, "Cannot access protected member `{0}' via a qualifier of type `{1}'."
                                + " The qualifier must be of type `{2}' or derived from it", 
-                               TypeManager.GetFullNameSignature (m),
+                               m.GetSignatureForError (),
                                TypeManager.CSharpName (qualifier),
                                TypeManager.CSharpName (container));
 
@@ -334,7 +303,7 @@ namespace Mono.CSharp {
                        rc.Report.Error (133, loc, "The expression being assigned to `{0}' must be constant", e_name);
                }
 
-               public void Error_ConstantCanBeInitializedWithNullOnly (ResolveContext rc, Type type, Location loc, string name)
+               public void Error_ConstantCanBeInitializedWithNullOnly (ResolveContext rc, TypeSpec type, Location loc, string name)
                {
                        rc.Report.Error (134, loc, "A constant `{0}' of reference type `{1}' can only be initialized with null",
                                name, TypeManager.CSharpName (type));
@@ -356,17 +325,18 @@ namespace Mono.CSharp {
                        Report.Error (1547, loc, "Keyword `void' cannot be used in this context");
                }
 
-               public virtual void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, Type target, bool expl)
+               public virtual void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, TypeSpec target, bool expl)
                {
                        Error_ValueCannotBeConvertedCore (ec, loc, target, expl);
                }
 
-               protected void Error_ValueCannotBeConvertedCore (ResolveContext ec, Location loc, Type target, bool expl)
+               protected void Error_ValueCannotBeConvertedCore (ResolveContext ec, Location loc, TypeSpec target, bool expl)
                {
                        // The error was already reported as CS1660
                        if (type == InternalType.AnonymousMethod)
                                return;
 
+/*
                        if (TypeManager.IsGenericParameter (Type) && TypeManager.IsGenericParameter (target) && type.Name == target.Name) {
                                string sig1 = type.DeclaringMethod == null ?
                                        TypeManager.CSharpName (type.DeclaringType) :
@@ -378,13 +348,13 @@ namespace Mono.CSharp {
                                        String.Format (
                                                "The generic parameter `{0}' of `{1}' cannot be converted to the generic parameter `{0}' of `{2}' (in the previous ",
                                                Type.Name, sig1, sig2));
-                       } else if (Type.FullName == target.FullName){
+                       } else if (Type.MetaInfo.FullName == target.MetaInfo.FullName) {
                                ec.Report.ExtraInformation (loc,
                                        String.Format (
                                        "The type `{0}' has two conflicting definitions, one comes from `{1}' and the other from `{2}' (in the previous ",
-                                       Type.FullName, Type.Assembly.FullName, target.Assembly.FullName));
+                                       Type.MetaInfo.FullName, Type.Assembly.FullName, target.Assembly.FullName));
                        }
-
+*/
                        if (expl) {
                                ec.Report.Error (30, loc, "Cannot convert type `{0}' to `{1}'",
                                        TypeManager.CSharpName (type), TypeManager.CSharpName (target));
@@ -403,8 +373,7 @@ namespace Mono.CSharp {
                        }
 
                        ec.Report.Error (29, loc, "Cannot implicitly convert type `{0}' to `{1}'",
-                               TypeManager.CSharpName (type),
-                               TypeManager.CSharpName (target));
+                               type.GetSignatureForError (), target.GetSignatureForError ());
                }
 
                public virtual void Error_VariableIsUsedBeforeItIsDeclared (Report Report, string name)
@@ -412,28 +381,36 @@ namespace Mono.CSharp {
                        Report.Error (841, loc, "A local variable `{0}' cannot be used before it is declared", name);
                }
 
-               public void Error_TypeArgumentsCannotBeUsed (Report report, Location loc)
+               public void Error_TypeArgumentsCannotBeUsed (Report report, Location loc, MemberSpec member, int arity)
                {
                        // Better message for possible generic expressions
-                       if (eclass == ExprClass.MethodGroup || eclass == ExprClass.Type) {
-                               if (this is TypeExpr)
-                                       report.SymbolRelatedToPreviousError (type);
+                       if (member != null && (member.Kind & MemberKind.GenericMask) != 0) {
+                               report.SymbolRelatedToPreviousError (member);
+                               if (member is TypeSpec)
+                                       member = ((TypeSpec) member).GetDefinition ();
+                               else
+                                       member = ((MethodSpec) member).GetGenericMethodDefinition ();
 
-                               string name = eclass == ExprClass.Type ? ExprClassName : "method";
-                               report.Error (308, loc, "The non-generic {0} `{1}' cannot be used with the type arguments",
-                                       name, GetSignatureForError ());
+                               string name = member.Kind == MemberKind.Method ? "method" : "type";
+                               if (member.IsGeneric) {
+                                       report.Error (305, loc, "Using the generic {0} `{1}' requires `{2}' type argument(s)",
+                                               name, member.GetSignatureForError (), member.Arity.ToString ());
+                               } else {
+                                       report.Error (308, loc, "The non-generic {0} `{1}' cannot be used with the type arguments",
+                                               name, member.GetSignatureForError ());
+                               }
                        } else {
                                report.Error (307, loc, "The {0} `{1}' cannot be used with type arguments",
                                        ExprClassName, GetSignatureForError ());
                        }
                }
 
-               protected virtual void Error_TypeDoesNotContainDefinition (ResolveContext ec, Type type, string name)
+               protected virtual void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
                {
                        Error_TypeDoesNotContainDefinition (ec, loc, type, name);
                }
 
-               public static void Error_TypeDoesNotContainDefinition (ResolveContext ec, Location loc, Type type, string name)
+               public static void Error_TypeDoesNotContainDefinition (ResolveContext ec, Location loc, TypeSpec type, string name)
                {
                        ec.Report.SymbolRelatedToPreviousError (type);
                        ec.Report.Error (117, loc, "`{0}' does not contain a definition for `{1}'",
@@ -556,6 +533,11 @@ namespace Mono.CSharp {
                        return e;
                }
 
+               public virtual void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
+               {
+                       Attribute.Error_AttributeArgumentNotValid (rc, loc);
+               }
+
                /// <summary>
                ///   Emits the code for the expression
                /// </summary>
@@ -566,6 +548,7 @@ namespace Mono.CSharp {
                /// </remarks>
                public abstract void Emit (EmitContext ec);
 
+
                // Emit code to branch to @target if this expression is equivalent to @on_true.
                // The default implementation is to emit the value, and then emit a brtrue or brfalse.
                // Subclasses can provide more efficient implementations, but those MUST be equivalent,
@@ -573,7 +556,7 @@ namespace Mono.CSharp {
                public virtual void EmitBranchable (EmitContext ec, Label target, bool on_true)
                {
                        Emit (ec);
-                       ec.ig.Emit (on_true ? OpCodes.Brtrue : OpCodes.Brfalse, target);
+                       ec.Emit (on_true ? OpCodes.Brtrue : OpCodes.Brfalse, target);
                }
 
                // Emit this expression for its side effects, not for its value.
@@ -582,7 +565,7 @@ namespace Mono.CSharp {
                public virtual void EmitSideEffect (EmitContext ec)
                {
                        Emit (ec);
-                       ec.ig.Emit (OpCodes.Pop);
+                       ec.Emit (OpCodes.Pop);
                }
 
                /// <summary>
@@ -598,28 +581,22 @@ namespace Mono.CSharp {
                ///   Returns a fully formed expression after a MemberLookup
                /// </summary>
                /// 
-               public static Expression ExprClassFromMemberInfo (Type container_type, MemberInfo mi, Location loc)
-               {
-                       if (mi is EventInfo)
-                               return new EventExpr (Import.CreateEvent ((EventInfo) mi), loc);
-                       else if (mi is FieldInfo) {
-                               FieldInfo fi = (FieldInfo) mi;
-                               var spec = Import.CreateField (fi);
-                               if (spec is ConstSpec)
-                                       return new ConstantExpr ((ConstSpec) spec, loc);
-                               return new FieldExpr (spec, loc);
-                       } else if (mi is PropertyInfo)
-                               return new PropertyExpr (container_type, Import.CreateProperty ((PropertyInfo) mi), loc);
-                       else if (mi is Type) {
-                               return new TypeExpression ((System.Type) mi, loc);
-                       }
+               public static Expression ExprClassFromMemberInfo (TypeSpec container_type, MemberSpec spec, Location loc)
+               {
+                       if (spec is EventSpec)
+                               return new EventExpr ((EventSpec) spec, loc);
+                       if (spec is ConstSpec)
+                               return new ConstantExpr ((ConstSpec) spec, loc);
+                       if (spec is FieldSpec)
+                               return new FieldExpr ((FieldSpec) spec, loc);
+                       if (spec is PropertySpec)
+                               return new PropertyExpr (container_type, (PropertySpec) spec, loc);
+                       if (spec is TypeSpec)
+                               return new TypeExpression (((TypeSpec) spec), loc);
 
                        return null;
                }
 
-               // TODO: [Obsolete ("Can be removed")]
-               protected static IList<MemberInfo> almost_matched_members = new List<MemberInfo> (4);
-
                //
                // FIXME: Probably implement a cache for (t,name,current_access_set)?
                //
@@ -648,135 +625,64 @@ namespace Mono.CSharp {
                // FIXME: Potential optimization, have a static ArrayList
                //
 
-               public static Expression MemberLookup (CompilerContext ctx, Type container_type, Type queried_type, string name,
-                                                      MemberTypes mt, BindingFlags bf, Location loc)
+               public static Expression MemberLookup (CompilerContext ctx, TypeSpec container_type, TypeSpec queried_type, string name, int arity,
+                                                      MemberKind mt, BindingRestriction bf, Location loc)
                {
-                       return MemberLookup (ctx, container_type, null, queried_type, name, mt, bf, loc);
+                       return MemberLookup (ctx, container_type, null, queried_type, name, arity, mt, bf, loc);
                }
 
                //
                // Lookup type `queried_type' for code in class `container_type' with a qualifier of
                // `qualifier_type' or null to lookup members in the current class.
                //
-
-               public static Expression MemberLookup (CompilerContext ctx, Type container_type,
-                                                      Type qualifier_type, Type queried_type,
-                                                      string name, MemberTypes mt,
-                                                      BindingFlags bf, Location loc)
+               public static Expression MemberLookup (CompilerContext ctx, TypeSpec container_type,
+                                                      TypeSpec qualifier_type, TypeSpec queried_type,
+                                                      string name, int arity, MemberKind mt,
+                                                      BindingRestriction binding, Location loc)
                {
-                       almost_matched_members.Clear ();
-
-                       MemberInfo [] mi = TypeManager.MemberLookup (container_type, qualifier_type,
-                                                                    queried_type, mt, bf, name, almost_matched_members);
-
+                       var mi = TypeManager.MemberLookup (container_type, qualifier_type,
+                                                                    queried_type, mt, binding, name, arity, null);
                        if (mi == null)
                                return null;
 
-                       if (mi.Length > 1) {
-                               bool is_interface = qualifier_type != null && qualifier_type.IsInterface;
-                               var methods = new List<MethodSpec> (2);
-                               List<MemberInfo> non_methods = null;
-
-                               foreach (var m in mi) {
-                                       if (m is MethodBase) {
-                                               methods.Add (Import.CreateMethod ((MethodBase) m));
-                                               continue;
-                                       }
-
-                                       if (non_methods == null)
-                                               non_methods = new List<MemberInfo> (2);
-
-                                       bool is_candidate = true;
-                                       for (int i = 0; i < non_methods.Count; ++i) {
-                                               MemberInfo n_m = non_methods [i];
-                                               if (n_m.DeclaringType.IsInterface && TypeManager.ImplementsInterface (m.DeclaringType, n_m.DeclaringType)) {
-                                                       non_methods.Remove (n_m);
-                                                       --i;
-                                               } else if (m.DeclaringType.IsInterface && TypeManager.ImplementsInterface (n_m.DeclaringType, m.DeclaringType)) {
-                                                       is_candidate = false;
-                                                       break;
-                                               }
-                                       }
-                                       
-                                       if (is_candidate) {
-                                               non_methods.Add (m);
-                                       }
-                               }
-                               
-                               if (methods.Count == 0 && non_methods != null && non_methods.Count > 1) {
-                                       ctx.Report.SymbolRelatedToPreviousError (non_methods [1]);
-                                       ctx.Report.SymbolRelatedToPreviousError (non_methods [0]);
-                                       ctx.Report.Error (229, loc, "Ambiguity between `{0}' and `{1}'",
-                                               TypeManager.GetFullNameSignature (non_methods [1]),
-                                               TypeManager.GetFullNameSignature (non_methods [0]));
-                                       return null;
-                               }
-
-                               if (methods.Count == 0)
-                                       return ExprClassFromMemberInfo (container_type, (MemberInfo)non_methods [0], loc);
-
-                               if (non_methods != null && non_methods.Count > 0) {
-                                       var method = methods [0];
-                                       MemberInfo non_method = (MemberInfo) non_methods [0];
-                                       if (method.DeclaringType == non_method.DeclaringType) {
-                                               // Cannot happen with C# code, but is valid in IL
-                                               ctx.Report.SymbolRelatedToPreviousError (method.MetaInfo);
-                                               ctx.Report.SymbolRelatedToPreviousError (non_method);
-                                               ctx.Report.Error (229, loc, "Ambiguity between `{0}' and `{1}'",
-                                                             TypeManager.GetFullNameSignature (non_method),
-                                                             TypeManager.CSharpSignature (method.MetaInfo));
-                                               return null;
-                                       }
-
-                                       if (is_interface) {
-                                               ctx.Report.SymbolRelatedToPreviousError (method.MetaInfo);
-                                               ctx.Report.SymbolRelatedToPreviousError (non_method);
-                                               ctx.Report.Warning (467, 2, loc, "Ambiguity between method `{0}' and non-method `{1}'. Using method `{0}'",
-                                                               TypeManager.CSharpSignature (method.MetaInfo), TypeManager.GetFullNameSignature (non_method));
-                                       }
+                       var first = mi [0];
+                       if (mi.Count > 1) {
+                               foreach (var mc in mi) {
+                                       if (mc is MethodSpec)
+                                               return new MethodGroupExpr (mi, queried_type, loc);
                                }
 
-                               return new MethodGroupExpr (methods, queried_type, loc);
+                               ctx.Report.SymbolRelatedToPreviousError (mi [1]);
+                               ctx.Report.SymbolRelatedToPreviousError (first);
+                               ctx.Report.Error (229, loc, "Ambiguity between `{0}' and `{1}'",
+                                       first.GetSignatureForError (), mi [1].GetSignatureForError ());
                        }
 
-                       if (mi [0] is MethodBase)
-                               return new MethodGroupExpr (mi.Select (l => Import.CreateMethod ((MethodBase) l)).ToArray (), queried_type, loc);
+                       if (first is MethodSpec)
+                               return new MethodGroupExpr (mi, queried_type, loc);
 
-                       return ExprClassFromMemberInfo (container_type, mi [0], loc);
+                       return ExprClassFromMemberInfo (container_type, first, loc);
                }
 
-               public const MemberTypes AllMemberTypes =
-                       MemberTypes.Constructor |
-                       MemberTypes.Event       |
-                       MemberTypes.Field       |
-                       MemberTypes.Method      |
-                       MemberTypes.NestedType  |
-                       MemberTypes.Property;
-               
-               public const BindingFlags AllBindingFlags =
-                       BindingFlags.Public |
-                       BindingFlags.Static |
-                       BindingFlags.Instance;
-
-               public static Expression MemberLookup (CompilerContext ctx, Type container_type, Type queried_type,
-                                                      string name, Location loc)
+               public static Expression MemberLookup (CompilerContext ctx, TypeSpec container_type, TypeSpec queried_type,
+                                                          string name, int arity, BindingRestriction binding, Location loc)
                {
-                       return MemberLookup (ctx, container_type, null, queried_type, name,
-                                            AllMemberTypes, AllBindingFlags, loc);
+                       return MemberLookup (ctx, container_type, null, queried_type, name, arity,
+                                            MemberKind.All, binding | BindingRestriction.AccessibleOnly, loc);
                }
 
-               public static Expression MemberLookup (CompilerContext ctx, Type container_type, Type qualifier_type,
-                                                      Type queried_type, string name, Location loc)
+               public static Expression MemberLookup (CompilerContext ctx, TypeSpec container_type, TypeSpec qualifier_type,
+                                                          TypeSpec queried_type, string name, int arity, BindingRestriction binding, Location loc)
                {
                        return MemberLookup (ctx, container_type, qualifier_type, queried_type,
-                                            name, AllMemberTypes, AllBindingFlags, loc);
+                                                name, arity, MemberKind.All, binding | BindingRestriction.AccessibleOnly, loc);
                }
 
-               public static MethodGroupExpr MethodLookup (CompilerContext ctx, Type container_type, Type queried_type,
-                                                      string name, Location loc)
+               public static MethodGroupExpr MethodLookup (CompilerContext ctx, TypeSpec container_type, TypeSpec queried_type,
+                                                      MemberKind kind, string name, int arity, Location loc)
                {
-                       return (MethodGroupExpr)MemberLookup (ctx, container_type, null, queried_type, name,
-                                            MemberTypes.Method, AllBindingFlags, loc);
+                       return (MethodGroupExpr)MemberLookup (ctx, container_type, null, queried_type, name, arity,
+                                            kind, BindingRestriction.AccessibleOnly, loc);
                }
 
                /// <summary>
@@ -785,35 +691,36 @@ namespace Mono.CSharp {
                ///   look for private members and display a useful debugging message if we
                ///   find it.
                /// </summary>
-               protected Expression MemberLookupFinal (ResolveContext ec, Type qualifier_type,
-                                                           Type queried_type, string name,
-                                                           MemberTypes mt, BindingFlags bf,
+               protected Expression MemberLookupFinal (ResolveContext ec, TypeSpec qualifier_type,
+                                                           TypeSpec queried_type, string name, int arity,
+                                                           MemberKind mt, BindingRestriction bf,
                                                            Location loc)
                {
                        Expression e;
 
                        int errors = ec.Report.Errors;
-                       e = MemberLookup (ec.Compiler, ec.CurrentType, qualifier_type, queried_type, name, mt, bf, loc);
+                       e = MemberLookup (ec.Compiler, ec.CurrentType, qualifier_type, queried_type, name, arity, mt, bf, loc);
 
                        if (e != null || errors != ec.Report.Errors)
                                return e;
 
                        // No errors were reported by MemberLookup, but there was an error.
                        return Error_MemberLookupFailed (ec, ec.CurrentType, qualifier_type, queried_type,
-                                       name, null, mt, bf);
+                                       name, arity, null, mt, bf);
                }
 
-               protected virtual Expression Error_MemberLookupFailed (ResolveContext ec, Type container_type, Type qualifier_type,
-                                                      Type queried_type, string name, string class_name,
-                                                          MemberTypes mt, BindingFlags bf)
+               protected virtual Expression Error_MemberLookupFailed (ResolveContext ec, TypeSpec container_type, TypeSpec qualifier_type,
+                                                      TypeSpec queried_type, string name, int arity, string class_name,
+                                                          MemberKind mt, BindingRestriction bf)
                {
-                       MemberInfo[] lookup = null;
+                       IList<MemberSpec> lookup = null;
                        if (queried_type == null) {
                                class_name = "global::";
                        } else {
+                               BindingRestriction restriction = bf & BindingRestriction.DeclaredOnly;
+
                                lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
-                                       mt, (bf & ~BindingFlags.Public) | BindingFlags.NonPublic,
-                                       name, null);
+                                       mt, restriction, name, arity, null);
 
                                if (lookup != null) {
                                        Expression e = Error_MemberLookupFailed (ec, queried_type, lookup);
@@ -823,10 +730,10 @@ namespace Mono.CSharp {
                                        // OverloadResolve to do correct arguments matching.
                                        // Requires MemberLookup accessiblity check removal
                                        //
-                                       if (e == null || (mt & (MemberTypes.Method | MemberTypes.Constructor)) == 0) {
-                                               MemberInfo mi = lookup[0];
+                                       if (e == null || (mt & (MemberKind.Method | MemberKind.Constructor)) == 0) {
+                                               var mi = lookup.First ();
                                                ec.Report.SymbolRelatedToPreviousError (mi);
-                                               if (qualifier_type != null && container_type != null && qualifier_type != container_type &&
+                                               if ((mi.Modifiers & Modifiers.PROTECTED) != 0 && qualifier_type != null && container_type != null && qualifier_type != container_type &&
                                                        TypeManager.IsNestedFamilyAccessible (container_type, mi.DeclaringType)) {
                                                        // Although a derived class can access protected members of
                                                        // its base class it cannot do so through an instance of the
@@ -843,8 +750,7 @@ namespace Mono.CSharp {
                                }
 
                                lookup = TypeManager.MemberLookup (queried_type, null, queried_type,
-                                       AllMemberTypes, AllBindingFlags | BindingFlags.NonPublic,
-                                       name, null);
+                                       MemberKind.All, BindingRestriction.None, name, -System.Math.Max (1, arity), null);
                        }
 
                        if (lookup == null) {
@@ -857,36 +763,21 @@ namespace Mono.CSharp {
                                return null;
                        }
 
-                       if (TypeManager.MemberLookup (queried_type, null, queried_type,
-                                                     AllMemberTypes, AllBindingFlags |
-                                                     BindingFlags.NonPublic, name, null) == null) {
-                               if ((lookup.Length == 1) && (lookup [0] is Type)) {
-                                       Type t = (Type) lookup [0];
-
-                                       ec.Report.Error (305, loc,
-                                                     "Using the generic type `{0}' " +
-                                                     "requires {1} type arguments",
-                                                     TypeManager.CSharpName (t),
-                                                     TypeManager.GetNumberOfTypeArguments (t).ToString ());
-                                       return null;
-                               }
+                       var mge = Error_MemberLookupFailed (ec, queried_type, lookup);
+                       if (arity > 0 && mge != null) {
+                               mge.SetTypeArguments (ec, new TypeArguments (new FullNamedExpression [arity]));
                        }
 
-                       return Error_MemberLookupFailed (ec, queried_type, lookup);
+                       return mge;
                }
 
-               protected virtual Expression Error_MemberLookupFailed (ResolveContext ec, Type type, MemberInfo[] members)
+               protected virtual MemberExpr Error_MemberLookupFailed (ResolveContext ec, TypeSpec type, IList<MemberSpec> members)
                {
-                       List<MethodSpec> methods = new List<MethodSpec> ();
-                       for (int i = 0; i < members.Length; ++i) {
-                               if (!(members [i] is MethodBase))
-                                       return null;
-
-                               methods.Add (Import.CreateMethod (members[i] as MethodBase));
-                       }
+                       if (members.Any ((m) => !(m is MethodSpec)))
+                               return (MemberExpr) ExprClassFromMemberInfo (type, members.First (), loc);
 
                        // By default propagate the closest candidates upwards
-                       return new MethodGroupExpr (methods.ToArray (), type, loc, true);
+                       return new MethodGroupExpr (members, type, loc, true);
                }
 
                protected virtual void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
@@ -921,7 +812,7 @@ namespace Mono.CSharp {
                {
                        MethodGroupExpr operator_group;
                        string mname = Operator.GetMetadataName (is_true ? Operator.OpType.True : Operator.OpType.False);
-                       operator_group = MethodLookup (ec.Compiler, ec.CurrentType, e.Type, mname, loc) as MethodGroupExpr;
+                       operator_group = MethodLookup (ec.Compiler, ec.CurrentType, e.Type, MemberKind.Operator, mname, 0, loc) as MethodGroupExpr;
                        if (operator_group == null)
                                return null;
 
@@ -1030,85 +921,12 @@ namespace Mono.CSharp {
                        Report.Error (214, loc, "Pointers and fixed size buffers may only be used in an unsafe context");
                }
 
-               //
-               // Load the object from the pointer.  
-               //
-               public static void LoadFromPtr (ILGenerator ig, Type t)
-               {
-                       if (t == TypeManager.int32_type)
-                               ig.Emit (OpCodes.Ldind_I4);
-                       else if (t == TypeManager.uint32_type)
-                               ig.Emit (OpCodes.Ldind_U4);
-                       else if (t == TypeManager.short_type)
-                               ig.Emit (OpCodes.Ldind_I2);
-                       else if (t == TypeManager.ushort_type)
-                               ig.Emit (OpCodes.Ldind_U2);
-                       else if (t == TypeManager.char_type)
-                               ig.Emit (OpCodes.Ldind_U2);
-                       else if (t == TypeManager.byte_type)
-                               ig.Emit (OpCodes.Ldind_U1);
-                       else if (t == TypeManager.sbyte_type)
-                               ig.Emit (OpCodes.Ldind_I1);
-                       else if (t == TypeManager.uint64_type)
-                               ig.Emit (OpCodes.Ldind_I8);
-                       else if (t == TypeManager.int64_type)
-                               ig.Emit (OpCodes.Ldind_I8);
-                       else if (t == TypeManager.float_type)
-                               ig.Emit (OpCodes.Ldind_R4);
-                       else if (t == TypeManager.double_type)
-                               ig.Emit (OpCodes.Ldind_R8);
-                       else if (t == TypeManager.bool_type)
-                               ig.Emit (OpCodes.Ldind_I1);
-                       else if (t == TypeManager.intptr_type)
-                               ig.Emit (OpCodes.Ldind_I);
-                       else if (TypeManager.IsEnumType (t)) {
-                               if (t == TypeManager.enum_type)
-                                       ig.Emit (OpCodes.Ldind_Ref);
-                               else
-                                       LoadFromPtr (ig, TypeManager.GetEnumUnderlyingType (t));
-                       } else if (TypeManager.IsStruct (t) || TypeManager.IsGenericParameter (t))
-                               ig.Emit (OpCodes.Ldobj, t);
-                       else if (t.IsPointer)
-                               ig.Emit (OpCodes.Ldind_I);
-                       else
-                               ig.Emit (OpCodes.Ldind_Ref);
-               }
-
-               //
-               // The stack contains the pointer and the value of type `type'
-               //
-               public static void StoreFromPtr (ILGenerator ig, Type type)
-               {
-                       if (TypeManager.IsEnumType (type))
-                               type = TypeManager.GetEnumUnderlyingType (type);
-                       if (type == TypeManager.int32_type || type == TypeManager.uint32_type)
-                               ig.Emit (OpCodes.Stind_I4);
-                       else if (type == TypeManager.int64_type || type == TypeManager.uint64_type)
-                               ig.Emit (OpCodes.Stind_I8);
-                       else if (type == TypeManager.char_type || type == TypeManager.short_type ||
-                                type == TypeManager.ushort_type)
-                               ig.Emit (OpCodes.Stind_I2);
-                       else if (type == TypeManager.float_type)
-                               ig.Emit (OpCodes.Stind_R4);
-                       else if (type == TypeManager.double_type)
-                               ig.Emit (OpCodes.Stind_R8);
-                       else if (type == TypeManager.byte_type || type == TypeManager.sbyte_type ||
-                                type == TypeManager.bool_type)
-                               ig.Emit (OpCodes.Stind_I1);
-                       else if (type == TypeManager.intptr_type)
-                               ig.Emit (OpCodes.Stind_I);
-                       else if (TypeManager.IsStruct (type) || TypeManager.IsGenericParameter (type))
-                               ig.Emit (OpCodes.Stobj, type);
-                       else
-                               ig.Emit (OpCodes.Stind_Ref);
-               }
-               
+       
                //
                // Returns the size of type `t' if known, otherwise, 0
                //
-               public static int GetTypeSize (Type t)
+               public static int GetTypeSize (TypeSpec t)
                {
-                       t = TypeManager.TypeToCoreType (t);
                        if (t == TypeManager.int32_type ||
                            t == TypeManager.uint32_type ||
                            t == TypeManager.float_type)
@@ -1153,7 +971,7 @@ namespace Mono.CSharp {
                //
                protected Expression ConvertExpressionToArrayIndex (ResolveContext ec, Expression source)
                {
-                       if (TypeManager.IsDynamicType (source.type)) {
+                       if (source.type == InternalType.Dynamic) {
                                Arguments args = new Arguments (1);
                                args.Add (new Argument (source));
                                return new DynamicConversion (TypeManager.int32_type, CSharpBinderFlags.ConvertArrayIndex, args, loc).Resolve (ec);
@@ -1247,7 +1065,7 @@ namespace Mono.CSharp {
                {
                        TypeExpr texpr = TypeManager.expression_type_expr;
                        if (texpr == null) {
-                               Type t = TypeManager.CoreLookupType (ec.Compiler, "System.Linq.Expressions", "Expression", MemberKind.Class, true);
+                               TypeSpec t = TypeManager.CoreLookupType (ec.Compiler, "System.Linq.Expressions", "Expression", MemberKind.Class, true);
                                if (t == null)
                                        return null;
 
@@ -1266,11 +1084,6 @@ namespace Mono.CSharp {
                {
                        throw new NotImplementedException ("MakeExpression for " + GetType ());
                }
-
-               public virtual void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       // TODO: It should probably be type = storey.MutateType (type);
-               }
        }
 
        /// <summary>
@@ -1325,7 +1138,7 @@ namespace Mono.CSharp {
        {
                protected readonly Expression child;
 
-               protected TypeCast (Expression child, Type return_type)
+               protected TypeCast (Expression child, TypeSpec return_type)
                {
                        eclass = child.eclass;
                        loc = child.Location;
@@ -1333,6 +1146,12 @@ namespace Mono.CSharp {
                        this.child = child;
                }
 
+               public Expression Child {
+                       get {
+                               return child;
+                       }
+               }
+
                public override Expression CreateExpressionTree (ResolveContext ec)
                {
                        Arguments args = new Arguments (2);
@@ -1358,22 +1177,11 @@ namespace Mono.CSharp {
                        child.Emit (ec);
                }
 
-               public override bool GetAttributableValue (ResolveContext ec, Type value_type, out object value)
-               {
-                       return child.GetAttributableValue (ec, value_type, out value);
-               }
-
                public override SLE.Expression MakeExpression (BuilderContext ctx)
                {
                        return ctx.HasSet (BuilderContext.Options.CheckedScope) ?
-                               SLE.Expression.ConvertChecked (child.MakeExpression (ctx), type) :
-                               SLE.Expression.Convert (child.MakeExpression (ctx), type);
-               }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       type = storey.MutateType (type);
-                       child.MutateHoistedGenericType (storey);
+                               SLE.Expression.ConvertChecked (child.MakeExpression (ctx), type.GetMetaInfo ()) :
+                               SLE.Expression.Convert (child.MakeExpression (ctx), type.GetMetaInfo ());
                }
 
                protected override void CloneTo (CloneContext clonectx, Expression t)
@@ -1387,12 +1195,12 @@ namespace Mono.CSharp {
        }
 
        public class EmptyCast : TypeCast {
-               EmptyCast (Expression child, Type target_type)
+               EmptyCast (Expression child, TypeSpec target_type)
                        : base (child, target_type)
                {
                }
 
-               public static Expression Create (Expression child, Type type)
+               public static Expression Create (Expression child, TypeSpec type)
                {
                        Constant c = child as Constant;
                        if (c != null)
@@ -1420,14 +1228,14 @@ namespace Mono.CSharp {
        // Used for predefined class library user casts (no obsolete check, etc.)
        //
        public class OperatorCast : TypeCast {
-               MethodInfo conversion_operator;
+               MethodSpec conversion_operator;
                        
-               public OperatorCast (Expression child, Type target_type) 
+               public OperatorCast (Expression child, TypeSpec target_type) 
                        : this (child, target_type, false)
                {
                }
 
-               public OperatorCast (Expression child, Type target_type, bool find_explicit)
+               public OperatorCast (Expression child, TypeSpec target_type, bool find_explicit)
                        : base (child, target_type)
                {
                        conversion_operator = GetConversionOperator (find_explicit);
@@ -1437,24 +1245,23 @@ namespace Mono.CSharp {
 
                // Returns the implicit operator that converts from
                // 'child.Type' to our target type (type)
-               MethodInfo GetConversionOperator (bool find_explicit)
+               MethodSpec GetConversionOperator (bool find_explicit)
                {
                        string operator_name = find_explicit ? "op_Explicit" : "op_Implicit";
 
-                       MemberInfo [] mi;
-
-                       mi = TypeManager.MemberLookup (child.Type, child.Type, child.Type, MemberTypes.Method,
-                               BindingFlags.Static | BindingFlags.Public, operator_name, null);
+                       // Operators are always public
+                       var mi = TypeManager.MemberLookup (child.Type, child.Type, child.Type, MemberKind.Operator,
+                               BindingRestriction.None, operator_name, 0, null);
 
                        if (mi == null){
-                               mi = TypeManager.MemberLookup (type, type, type, MemberTypes.Method,
-                                                              BindingFlags.Static | BindingFlags.Public, operator_name, null);
+                               mi = TypeManager.MemberLookup (type, type, type, MemberKind.Operator,
+                                       BindingRestriction.None, operator_name, 0, null);
                        }
                        
-                       foreach (MethodInfo oper in mi) {
-                               AParametersCollection pd = TypeManager.GetParameterData (oper);
+                       foreach (MethodSpec oper in mi) {
+                               AParametersCollection pd = oper.Parameters;
 
-                               if (pd.Types [0] == child.Type && TypeManager.TypeToCoreType (oper.ReturnType) == type)
+                               if (pd.Types [0] == child.Type && oper.ReturnType == type)
                                        return oper;
                        }
 
@@ -1464,7 +1271,7 @@ namespace Mono.CSharp {
                public override void Emit (EmitContext ec)
                {
                        child.Emit (ec);
-                       ec.ig.Emit (OpCodes.Call, conversion_operator);
+                       ec.Emit (OpCodes.Call, conversion_operator);
                }
        }
        
@@ -1488,14 +1295,13 @@ namespace Mono.CSharp {
        /// </summary>
        public class CastFromDecimal : TypeCast
        {
-               static Dictionary<Type, MethodInfo> operators;
+               static Dictionary<TypeSpec, MethodSpec> operators;
 
-               public CastFromDecimal (Expression child, Type return_type)
+               public CastFromDecimal (Expression child, TypeSpec return_type)
                        : base (child, return_type)
                {
                        if (child.Type != TypeManager.decimal_type)
-                               throw new InternalErrorException (
-                                       "The expected type is Decimal, instead it is " + child.Type.FullName);
+                               throw new ArgumentException ("Expected decimal child " + child.Type.GetSignatureForError ());
                }
 
                // Returns the explicit operator that converts from an
@@ -1503,15 +1309,15 @@ namespace Mono.CSharp {
                public Expression Resolve ()
                {
                        if (operators == null) {
-                               MemberInfo[] all_oper = TypeManager.MemberLookup (TypeManager.decimal_type,
-                                  TypeManager.decimal_type, TypeManager.decimal_type, MemberTypes.Method,
-                                  BindingFlags.Static | BindingFlags.Public, "op_Explicit", null);
+                               var all_oper = TypeManager.MemberLookup (TypeManager.decimal_type,
+                                  TypeManager.decimal_type, TypeManager.decimal_type, MemberKind.Operator,
+                                  BindingRestriction.None, "op_Explicit", 0, null);
 
-                               operators = new Dictionary<Type, MethodInfo> (ReferenceEquality<Type>.Default);
-                               foreach (MethodInfo oper in all_oper) {
-                                       AParametersCollection pd = TypeManager.GetParameterData (oper);
+                               operators = new Dictionary<TypeSpec, MethodSpec> ();
+                               foreach (MethodSpec oper in all_oper) {
+                                       AParametersCollection pd = oper.Parameters;
                                        if (pd.Types [0] == TypeManager.decimal_type)
-                                               operators.Add (TypeManager.TypeToCoreType (oper.ReturnType), oper);
+                                               operators.Add (oper.ReturnType, oper);
                                }
                        }
 
@@ -1520,10 +1326,14 @@ namespace Mono.CSharp {
 
                public override void Emit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
                        child.Emit (ec);
 
-                       ig.Emit (OpCodes.Call, operators [type]);
+                       ec.Emit (OpCodes.Call, operators [type]);
+               }
+
+               public static void Reset ()
+               {
+                       operators = null;
                }
        }
 
@@ -1537,7 +1347,7 @@ namespace Mono.CSharp {
        {
                public Constant child;
 
-               public EmptyConstantCast (Constant child, Type type)
+               public EmptyConstantCast (Constant child, TypeSpec type)
                        : base (child.Location)
                {
                        if (child == null)
@@ -1558,7 +1368,7 @@ namespace Mono.CSharp {
                        return child.GetValue ();
                }
 
-               public override Constant ConvertExplicitly (bool in_checked_context, Type target_type)
+               public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
                {
                        if (child.Type == target_type)
                                return child;
@@ -1615,7 +1425,7 @@ namespace Mono.CSharp {
 
                        // Only to make verifier happy
                        if (TypeManager.IsGenericParameter (type) && child.IsNull)
-                               ec.ig.Emit (OpCodes.Unbox_Any, type);
+                               ec.Emit (OpCodes.Unbox_Any, type);
                }
 
                public override void EmitSideEffect (EmitContext ec)
@@ -1623,18 +1433,13 @@ namespace Mono.CSharp {
                        child.EmitSideEffect (ec);
                }
 
-               public override Constant ConvertImplicitly (ResolveContext rc, Type target_type)
+               public override Constant ConvertImplicitly (ResolveContext rc, TypeSpec target_type)
                {
                        // FIXME: Do we need to check user conversions?
                        if (!Convert.ImplicitStandardConversionExists (this, target_type))
                                return null;
                        return child.ConvertImplicitly (rc, target_type);
                }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       child.MutateHoistedGenericType (storey);
-               }
        }
 
        /// <summary>
@@ -1644,7 +1449,7 @@ namespace Mono.CSharp {
        {
                public Constant Child;
 
-               public EnumConstant (Constant child, Type enum_type)
+               public EnumConstant (Constant child, TypeSpec enum_type)
                        : base (child.Location)
                {
                        this.Child = child;
@@ -1668,6 +1473,11 @@ namespace Mono.CSharp {
                        Child.Emit (ec);
                }
 
+               public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
+               {
+                       Child.EncodeAttributeValue (rc, enc, Child.Type);
+               }
+
                public override void EmitBranchable (EmitContext ec, Label label, bool on_true)
                {
                        Child.EmitBranchable (ec, label, on_true);
@@ -1678,12 +1488,6 @@ namespace Mono.CSharp {
                        Child.EmitSideEffect (ec);
                }
 
-               public override bool GetAttributableValue (ResolveContext ec, Type value_type, out object value)
-               {
-                       value = GetTypedValue ();
-                       return true;
-               }
-
                public override string GetSignatureForError()
                {
                        return TypeManager.CSharpName (Type);
@@ -1709,11 +1513,11 @@ namespace Mono.CSharp {
                        //
                        // This works only sometimes
                        //
-                       if (TypeManager.IsBeingCompiled (type))
+                       if (type.MemberDefinition is TypeContainer)
                                return Child.GetValue ();
 #endif
 
-                       return System.Enum.ToObject (type, Child.GetValue ());
+                       return System.Enum.ToObject (type.GetMetaInfo (), Child.GetValue ());
                }
                
                public override string AsString ()
@@ -1742,7 +1546,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override Constant ConvertExplicitly(bool in_checked_context, Type target_type)
+               public override Constant ConvertExplicitly(bool in_checked_context, TypeSpec target_type)
                {
                        if (Child.Type == target_type)
                                return Child;
@@ -1750,19 +1554,9 @@ namespace Mono.CSharp {
                        return Child.ConvertExplicitly (in_checked_context, target_type);
                }
 
-               public override Constant ConvertImplicitly (ResolveContext rc, Type type)
+               public override Constant ConvertImplicitly (ResolveContext rc, TypeSpec type)
                {
-                       Type this_type = TypeManager.DropGenericTypeArguments (Type);
-                       type = TypeManager.DropGenericTypeArguments (type);
-
-                       if (this_type == type) {
-                               // This is workaround of mono bug. It can be removed when the latest corlib spreads enough
-                               if (TypeManager.IsEnumType (type.UnderlyingSystemType))
-                                       return this;
-
-                               Type child_type = TypeManager.DropGenericTypeArguments (Child.Type);
-                               if (type.UnderlyingSystemType != child_type)
-                                       Child = Child.ConvertImplicitly (rc, type.UnderlyingSystemType);
+                       if (this.type == type) {
                                return this;
                        }
 
@@ -1782,7 +1576,7 @@ namespace Mono.CSharp {
        /// </summary>
        public class BoxedCast : TypeCast {
 
-               public BoxedCast (Expression expr, Type target_type)
+               public BoxedCast (Expression expr, TypeSpec target_type)
                        : base (expr, target_type)
                {
                        eclass = ExprClass.Value;
@@ -1796,11 +1590,17 @@ namespace Mono.CSharp {
                        return this;
                }
 
+               public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
+               {
+                       enc.Encode (child.Type);
+                       child.EncodeAttributeValue (rc, enc, child.Type);
+               }
+
                public override void Emit (EmitContext ec)
                {
                        base.Emit (ec);
                        
-                       ec.ig.Emit (OpCodes.Box, child.Type);
+                       ec.Emit (OpCodes.Box, child.Type);
                }
 
                public override void EmitSideEffect (EmitContext ec)
@@ -1816,7 +1616,7 @@ namespace Mono.CSharp {
        }
 
        public class UnboxCast : TypeCast {
-               public UnboxCast (Expression expr, Type return_type)
+               public UnboxCast (Expression expr, TypeSpec return_type)
                        : base (expr, return_type)
                {
                }
@@ -1840,14 +1640,7 @@ namespace Mono.CSharp {
                {
                        base.Emit (ec);
 
-                       ILGenerator ig = ec.ig;
-                       ig.Emit (OpCodes.Unbox_Any, type);
-               }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       type = storey.MutateType (type);
-                       base.MutateHoistedGenericType (storey);                 
+                       ec.Emit (OpCodes.Unbox_Any, type);
                }
        }
        
@@ -1876,7 +1669,7 @@ namespace Mono.CSharp {
 
                Mode mode;
                
-               public ConvCast (Expression child, Type return_type, Mode m)
+               public ConvCast (Expression child, TypeSpec return_type, Mode m)
                        : base (child, return_type)
                {
                        mode = m;
@@ -1897,179 +1690,177 @@ namespace Mono.CSharp {
                
                public override void Emit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-                       
                        base.Emit (ec);
 
                        if (ec.HasSet (EmitContext.Options.CheckedScope)) {
                                switch (mode){
-                               case Mode.I1_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
-                               case Mode.I1_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
-                               case Mode.I1_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
-                               case Mode.I1_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
-                               case Mode.I1_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
+                               case Mode.I1_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
+                               case Mode.I1_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+                               case Mode.I1_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
+                               case Mode.I1_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
+                               case Mode.I1_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
 
-                               case Mode.U1_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
+                               case Mode.U1_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break;
                                case Mode.U1_CH: /* nothing */ break;
 
-                               case Mode.I2_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
-                               case Mode.I2_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
-                               case Mode.I2_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
-                               case Mode.I2_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
-                               case Mode.I2_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
-                               case Mode.I2_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
+                               case Mode.I2_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break;
+                               case Mode.I2_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
+                               case Mode.I2_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+                               case Mode.I2_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
+                               case Mode.I2_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
+                               case Mode.I2_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
 
-                               case Mode.U2_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
-                               case Mode.U2_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
-                               case Mode.U2_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
+                               case Mode.U2_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break;
+                               case Mode.U2_U1: ec.Emit (OpCodes.Conv_Ovf_U1_Un); break;
+                               case Mode.U2_I2: ec.Emit (OpCodes.Conv_Ovf_I2_Un); break;
                                case Mode.U2_CH: /* nothing */ break;
 
-                               case Mode.I4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
-                               case Mode.I4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
-                               case Mode.I4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
-                               case Mode.I4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
-                               case Mode.I4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
-                               case Mode.I4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
-                               case Mode.I4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
-
-                               case Mode.U4_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
-                               case Mode.U4_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
-                               case Mode.U4_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
-                               case Mode.U4_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
-                               case Mode.U4_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
-                               case Mode.U4_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
-
-                               case Mode.I8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
-                               case Mode.I8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
-                               case Mode.I8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
-                               case Mode.I8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
-                               case Mode.I8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
-                               case Mode.I8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
-                               case Mode.I8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
-                               case Mode.I8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
-                               case Mode.I8_I: ig.Emit (OpCodes.Conv_Ovf_U); break;
-
-                               case Mode.U8_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
-                               case Mode.U8_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
-                               case Mode.U8_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
-                               case Mode.U8_U2: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
-                               case Mode.U8_I4: ig.Emit (OpCodes.Conv_Ovf_I4_Un); break;
-                               case Mode.U8_U4: ig.Emit (OpCodes.Conv_Ovf_U4_Un); break;
-                               case Mode.U8_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
-                               case Mode.U8_CH: ig.Emit (OpCodes.Conv_Ovf_U2_Un); break;
-                               case Mode.U8_I: ig.Emit (OpCodes.Conv_Ovf_U_Un); break;
-
-                               case Mode.CH_I1: ig.Emit (OpCodes.Conv_Ovf_I1_Un); break;
-                               case Mode.CH_U1: ig.Emit (OpCodes.Conv_Ovf_U1_Un); break;
-                               case Mode.CH_I2: ig.Emit (OpCodes.Conv_Ovf_I2_Un); break;
-
-                               case Mode.R4_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
-                               case Mode.R4_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
-                               case Mode.R4_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
-                               case Mode.R4_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
-                               case Mode.R4_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
-                               case Mode.R4_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
-                               case Mode.R4_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
-                               case Mode.R4_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
-                               case Mode.R4_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
-
-                               case Mode.R8_I1: ig.Emit (OpCodes.Conv_Ovf_I1); break;
-                               case Mode.R8_U1: ig.Emit (OpCodes.Conv_Ovf_U1); break;
-                               case Mode.R8_I2: ig.Emit (OpCodes.Conv_Ovf_I2); break;
-                               case Mode.R8_U2: ig.Emit (OpCodes.Conv_Ovf_U2); break;
-                               case Mode.R8_I4: ig.Emit (OpCodes.Conv_Ovf_I4); break;
-                               case Mode.R8_U4: ig.Emit (OpCodes.Conv_Ovf_U4); break;
-                               case Mode.R8_I8: ig.Emit (OpCodes.Conv_Ovf_I8); break;
-                               case Mode.R8_U8: ig.Emit (OpCodes.Conv_Ovf_U8); break;
-                               case Mode.R8_CH: ig.Emit (OpCodes.Conv_Ovf_U2); break;
-                               case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
-
-                               case Mode.I_I8: ig.Emit (OpCodes.Conv_Ovf_I8_Un); break;
+                               case Mode.I4_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break;
+                               case Mode.I4_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
+                               case Mode.I4_I2: ec.Emit (OpCodes.Conv_Ovf_I2); break;
+                               case Mode.I4_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
+                               case Mode.I4_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+                               case Mode.I4_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
+                               case Mode.I4_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+
+                               case Mode.U4_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break;
+                               case Mode.U4_U1: ec.Emit (OpCodes.Conv_Ovf_U1_Un); break;
+                               case Mode.U4_I2: ec.Emit (OpCodes.Conv_Ovf_I2_Un); break;
+                               case Mode.U4_U2: ec.Emit (OpCodes.Conv_Ovf_U2_Un); break;
+                               case Mode.U4_I4: ec.Emit (OpCodes.Conv_Ovf_I4_Un); break;
+                               case Mode.U4_CH: ec.Emit (OpCodes.Conv_Ovf_U2_Un); break;
+
+                               case Mode.I8_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break;
+                               case Mode.I8_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
+                               case Mode.I8_I2: ec.Emit (OpCodes.Conv_Ovf_I2); break;
+                               case Mode.I8_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+                               case Mode.I8_I4: ec.Emit (OpCodes.Conv_Ovf_I4); break;
+                               case Mode.I8_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
+                               case Mode.I8_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
+                               case Mode.I8_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+                               case Mode.I8_I: ec.Emit (OpCodes.Conv_Ovf_U); break;
+
+                               case Mode.U8_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break;
+                               case Mode.U8_U1: ec.Emit (OpCodes.Conv_Ovf_U1_Un); break;
+                               case Mode.U8_I2: ec.Emit (OpCodes.Conv_Ovf_I2_Un); break;
+                               case Mode.U8_U2: ec.Emit (OpCodes.Conv_Ovf_U2_Un); break;
+                               case Mode.U8_I4: ec.Emit (OpCodes.Conv_Ovf_I4_Un); break;
+                               case Mode.U8_U4: ec.Emit (OpCodes.Conv_Ovf_U4_Un); break;
+                               case Mode.U8_I8: ec.Emit (OpCodes.Conv_Ovf_I8_Un); break;
+                               case Mode.U8_CH: ec.Emit (OpCodes.Conv_Ovf_U2_Un); break;
+                               case Mode.U8_I: ec.Emit (OpCodes.Conv_Ovf_U_Un); break;
+
+                               case Mode.CH_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break;
+                               case Mode.CH_U1: ec.Emit (OpCodes.Conv_Ovf_U1_Un); break;
+                               case Mode.CH_I2: ec.Emit (OpCodes.Conv_Ovf_I2_Un); break;
+
+                               case Mode.R4_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break;
+                               case Mode.R4_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
+                               case Mode.R4_I2: ec.Emit (OpCodes.Conv_Ovf_I2); break;
+                               case Mode.R4_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+                               case Mode.R4_I4: ec.Emit (OpCodes.Conv_Ovf_I4); break;
+                               case Mode.R4_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
+                               case Mode.R4_I8: ec.Emit (OpCodes.Conv_Ovf_I8); break;
+                               case Mode.R4_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
+                               case Mode.R4_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+
+                               case Mode.R8_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break;
+                               case Mode.R8_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
+                               case Mode.R8_I2: ec.Emit (OpCodes.Conv_Ovf_I2); break;
+                               case Mode.R8_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+                               case Mode.R8_I4: ec.Emit (OpCodes.Conv_Ovf_I4); break;
+                               case Mode.R8_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
+                               case Mode.R8_I8: ec.Emit (OpCodes.Conv_Ovf_I8); break;
+                               case Mode.R8_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
+                               case Mode.R8_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
+                               case Mode.R8_R4: ec.Emit (OpCodes.Conv_R4); break;
+
+                               case Mode.I_I8: ec.Emit (OpCodes.Conv_Ovf_I8_Un); break;
                                }
                        } else {
                                switch (mode){
-                               case Mode.I1_U1: ig.Emit (OpCodes.Conv_U1); break;
-                               case Mode.I1_U2: ig.Emit (OpCodes.Conv_U2); break;
-                               case Mode.I1_U4: ig.Emit (OpCodes.Conv_U4); break;
-                               case Mode.I1_U8: ig.Emit (OpCodes.Conv_I8); break;
-                               case Mode.I1_CH: ig.Emit (OpCodes.Conv_U2); break;
-
-                               case Mode.U1_I1: ig.Emit (OpCodes.Conv_I1); break;
-                               case Mode.U1_CH: ig.Emit (OpCodes.Conv_U2); break;
-
-                               case Mode.I2_I1: ig.Emit (OpCodes.Conv_I1); break;
-                               case Mode.I2_U1: ig.Emit (OpCodes.Conv_U1); break;
-                               case Mode.I2_U2: ig.Emit (OpCodes.Conv_U2); break;
-                               case Mode.I2_U4: ig.Emit (OpCodes.Conv_U4); break;
-                               case Mode.I2_U8: ig.Emit (OpCodes.Conv_I8); break;
-                               case Mode.I2_CH: ig.Emit (OpCodes.Conv_U2); break;
-
-                               case Mode.U2_I1: ig.Emit (OpCodes.Conv_I1); break;
-                               case Mode.U2_U1: ig.Emit (OpCodes.Conv_U1); break;
-                               case Mode.U2_I2: ig.Emit (OpCodes.Conv_I2); break;
+                               case Mode.I1_U1: ec.Emit (OpCodes.Conv_U1); break;
+                               case Mode.I1_U2: ec.Emit (OpCodes.Conv_U2); break;
+                               case Mode.I1_U4: ec.Emit (OpCodes.Conv_U4); break;
+                               case Mode.I1_U8: ec.Emit (OpCodes.Conv_I8); break;
+                               case Mode.I1_CH: ec.Emit (OpCodes.Conv_U2); break;
+
+                               case Mode.U1_I1: ec.Emit (OpCodes.Conv_I1); break;
+                               case Mode.U1_CH: ec.Emit (OpCodes.Conv_U2); break;
+
+                               case Mode.I2_I1: ec.Emit (OpCodes.Conv_I1); break;
+                               case Mode.I2_U1: ec.Emit (OpCodes.Conv_U1); break;
+                               case Mode.I2_U2: ec.Emit (OpCodes.Conv_U2); break;
+                               case Mode.I2_U4: ec.Emit (OpCodes.Conv_U4); break;
+                               case Mode.I2_U8: ec.Emit (OpCodes.Conv_I8); break;
+                               case Mode.I2_CH: ec.Emit (OpCodes.Conv_U2); break;
+
+                               case Mode.U2_I1: ec.Emit (OpCodes.Conv_I1); break;
+                               case Mode.U2_U1: ec.Emit (OpCodes.Conv_U1); break;
+                               case Mode.U2_I2: ec.Emit (OpCodes.Conv_I2); break;
                                case Mode.U2_CH: /* nothing */ break;
 
-                               case Mode.I4_I1: ig.Emit (OpCodes.Conv_I1); break;
-                               case Mode.I4_U1: ig.Emit (OpCodes.Conv_U1); break;
-                               case Mode.I4_I2: ig.Emit (OpCodes.Conv_I2); break;
+                               case Mode.I4_I1: ec.Emit (OpCodes.Conv_I1); break;
+                               case Mode.I4_U1: ec.Emit (OpCodes.Conv_U1); break;
+                               case Mode.I4_I2: ec.Emit (OpCodes.Conv_I2); break;
                                case Mode.I4_U4: /* nothing */ break;
-                               case Mode.I4_U2: ig.Emit (OpCodes.Conv_U2); break;
-                               case Mode.I4_U8: ig.Emit (OpCodes.Conv_I8); break;
-                               case Mode.I4_CH: ig.Emit (OpCodes.Conv_U2); break;
-
-                               case Mode.U4_I1: ig.Emit (OpCodes.Conv_I1); break;
-                               case Mode.U4_U1: ig.Emit (OpCodes.Conv_U1); break;
-                               case Mode.U4_I2: ig.Emit (OpCodes.Conv_I2); break;
-                               case Mode.U4_U2: ig.Emit (OpCodes.Conv_U2); break;
+                               case Mode.I4_U2: ec.Emit (OpCodes.Conv_U2); break;
+                               case Mode.I4_U8: ec.Emit (OpCodes.Conv_I8); break;
+                               case Mode.I4_CH: ec.Emit (OpCodes.Conv_U2); break;
+
+                               case Mode.U4_I1: ec.Emit (OpCodes.Conv_I1); break;
+                               case Mode.U4_U1: ec.Emit (OpCodes.Conv_U1); break;
+                               case Mode.U4_I2: ec.Emit (OpCodes.Conv_I2); break;
+                               case Mode.U4_U2: ec.Emit (OpCodes.Conv_U2); break;
                                case Mode.U4_I4: /* nothing */ break;
-                               case Mode.U4_CH: ig.Emit (OpCodes.Conv_U2); break;
-
-                               case Mode.I8_I1: ig.Emit (OpCodes.Conv_I1); break;
-                               case Mode.I8_U1: ig.Emit (OpCodes.Conv_U1); break;
-                               case Mode.I8_I2: ig.Emit (OpCodes.Conv_I2); break;
-                               case Mode.I8_U2: ig.Emit (OpCodes.Conv_U2); break;
-                               case Mode.I8_I4: ig.Emit (OpCodes.Conv_I4); break;
-                               case Mode.I8_U4: ig.Emit (OpCodes.Conv_U4); break;
+                               case Mode.U4_CH: ec.Emit (OpCodes.Conv_U2); break;
+
+                               case Mode.I8_I1: ec.Emit (OpCodes.Conv_I1); break;
+                               case Mode.I8_U1: ec.Emit (OpCodes.Conv_U1); break;
+                               case Mode.I8_I2: ec.Emit (OpCodes.Conv_I2); break;
+                               case Mode.I8_U2: ec.Emit (OpCodes.Conv_U2); break;
+                               case Mode.I8_I4: ec.Emit (OpCodes.Conv_I4); break;
+                               case Mode.I8_U4: ec.Emit (OpCodes.Conv_U4); break;
                                case Mode.I8_U8: /* nothing */ break;
-                               case Mode.I8_CH: ig.Emit (OpCodes.Conv_U2); break;
-                               case Mode.I8_I: ig.Emit (OpCodes.Conv_U); break;
-
-                               case Mode.U8_I1: ig.Emit (OpCodes.Conv_I1); break;
-                               case Mode.U8_U1: ig.Emit (OpCodes.Conv_U1); break;
-                               case Mode.U8_I2: ig.Emit (OpCodes.Conv_I2); break;
-                               case Mode.U8_U2: ig.Emit (OpCodes.Conv_U2); break;
-                               case Mode.U8_I4: ig.Emit (OpCodes.Conv_I4); break;
-                               case Mode.U8_U4: ig.Emit (OpCodes.Conv_U4); break;
+                               case Mode.I8_CH: ec.Emit (OpCodes.Conv_U2); break;
+                               case Mode.I8_I: ec.Emit (OpCodes.Conv_U); break;
+
+                               case Mode.U8_I1: ec.Emit (OpCodes.Conv_I1); break;
+                               case Mode.U8_U1: ec.Emit (OpCodes.Conv_U1); break;
+                               case Mode.U8_I2: ec.Emit (OpCodes.Conv_I2); break;
+                               case Mode.U8_U2: ec.Emit (OpCodes.Conv_U2); break;
+                               case Mode.U8_I4: ec.Emit (OpCodes.Conv_I4); break;
+                               case Mode.U8_U4: ec.Emit (OpCodes.Conv_U4); break;
                                case Mode.U8_I8: /* nothing */ break;
-                               case Mode.U8_CH: ig.Emit (OpCodes.Conv_U2); break;
-                               case Mode.U8_I: ig.Emit (OpCodes.Conv_U); break;
-
-                               case Mode.CH_I1: ig.Emit (OpCodes.Conv_I1); break;
-                               case Mode.CH_U1: ig.Emit (OpCodes.Conv_U1); break;
-                               case Mode.CH_I2: ig.Emit (OpCodes.Conv_I2); break;
-
-                               case Mode.R4_I1: ig.Emit (OpCodes.Conv_I1); break;
-                               case Mode.R4_U1: ig.Emit (OpCodes.Conv_U1); break;
-                               case Mode.R4_I2: ig.Emit (OpCodes.Conv_I2); break;
-                               case Mode.R4_U2: ig.Emit (OpCodes.Conv_U2); break;
-                               case Mode.R4_I4: ig.Emit (OpCodes.Conv_I4); break;
-                               case Mode.R4_U4: ig.Emit (OpCodes.Conv_U4); break;
-                               case Mode.R4_I8: ig.Emit (OpCodes.Conv_I8); break;
-                               case Mode.R4_U8: ig.Emit (OpCodes.Conv_U8); break;
-                               case Mode.R4_CH: ig.Emit (OpCodes.Conv_U2); break;
-
-                               case Mode.R8_I1: ig.Emit (OpCodes.Conv_I1); break;
-                               case Mode.R8_U1: ig.Emit (OpCodes.Conv_U1); break;
-                               case Mode.R8_I2: ig.Emit (OpCodes.Conv_I2); break;
-                               case Mode.R8_U2: ig.Emit (OpCodes.Conv_U2); break;
-                               case Mode.R8_I4: ig.Emit (OpCodes.Conv_I4); break;
-                               case Mode.R8_U4: ig.Emit (OpCodes.Conv_U4); break;
-                               case Mode.R8_I8: ig.Emit (OpCodes.Conv_I8); break;
-                               case Mode.R8_U8: ig.Emit (OpCodes.Conv_U8); break;
-                               case Mode.R8_CH: ig.Emit (OpCodes.Conv_U2); break;
-                               case Mode.R8_R4: ig.Emit (OpCodes.Conv_R4); break;
-
-                               case Mode.I_I8: ig.Emit (OpCodes.Conv_U8); break;
+                               case Mode.U8_CH: ec.Emit (OpCodes.Conv_U2); break;
+                               case Mode.U8_I: ec.Emit (OpCodes.Conv_U); break;
+
+                               case Mode.CH_I1: ec.Emit (OpCodes.Conv_I1); break;
+                               case Mode.CH_U1: ec.Emit (OpCodes.Conv_U1); break;
+                               case Mode.CH_I2: ec.Emit (OpCodes.Conv_I2); break;
+
+                               case Mode.R4_I1: ec.Emit (OpCodes.Conv_I1); break;
+                               case Mode.R4_U1: ec.Emit (OpCodes.Conv_U1); break;
+                               case Mode.R4_I2: ec.Emit (OpCodes.Conv_I2); break;
+                               case Mode.R4_U2: ec.Emit (OpCodes.Conv_U2); break;
+                               case Mode.R4_I4: ec.Emit (OpCodes.Conv_I4); break;
+                               case Mode.R4_U4: ec.Emit (OpCodes.Conv_U4); break;
+                               case Mode.R4_I8: ec.Emit (OpCodes.Conv_I8); break;
+                               case Mode.R4_U8: ec.Emit (OpCodes.Conv_U8); break;
+                               case Mode.R4_CH: ec.Emit (OpCodes.Conv_U2); break;
+
+                               case Mode.R8_I1: ec.Emit (OpCodes.Conv_I1); break;
+                               case Mode.R8_U1: ec.Emit (OpCodes.Conv_U1); break;
+                               case Mode.R8_I2: ec.Emit (OpCodes.Conv_I2); break;
+                               case Mode.R8_U2: ec.Emit (OpCodes.Conv_U2); break;
+                               case Mode.R8_I4: ec.Emit (OpCodes.Conv_I4); break;
+                               case Mode.R8_U4: ec.Emit (OpCodes.Conv_U4); break;
+                               case Mode.R8_I8: ec.Emit (OpCodes.Conv_I8); break;
+                               case Mode.R8_U8: ec.Emit (OpCodes.Conv_U8); break;
+                               case Mode.R8_CH: ec.Emit (OpCodes.Conv_U2); break;
+                               case Mode.R8_R4: ec.Emit (OpCodes.Conv_R4); break;
+
+                               case Mode.I_I8: ec.Emit (OpCodes.Conv_U8); break;
                                }
                        }
                }
@@ -2078,7 +1869,7 @@ namespace Mono.CSharp {
        public class OpcodeCast : TypeCast {
                readonly OpCode op;
                
-               public OpcodeCast (Expression child, Type return_type, OpCode op)
+               public OpcodeCast (Expression child, TypeSpec return_type, OpCode op)
                        : base (child, return_type)
                {
                        this.op = op;
@@ -2095,10 +1886,10 @@ namespace Mono.CSharp {
                public override void Emit (EmitContext ec)
                {
                        base.Emit (ec);
-                       ec.ig.Emit (op);
+                       ec.Emit (op);
                }
 
-               public Type UnderlyingType {
+               public TypeSpec UnderlyingType {
                        get { return child.Type; }
                }
        }
@@ -2110,12 +1901,12 @@ namespace Mono.CSharp {
        public sealed class ClassCast : TypeCast {
                readonly bool forced;
                
-               public ClassCast (Expression child, Type return_type)
+               public ClassCast (Expression child, TypeSpec return_type)
                        : base (child, return_type)
                {
                }
                
-               public ClassCast (Expression child, Type return_type, bool forced)
+               public ClassCast (Expression child, TypeSpec return_type, bool forced)
                        : base (child, return_type)
                {
                        this.forced = forced;
@@ -2127,17 +1918,17 @@ namespace Mono.CSharp {
 
                        bool gen = TypeManager.IsGenericParameter (child.Type);
                        if (gen)
-                               ec.ig.Emit (OpCodes.Box, child.Type);
+                               ec.Emit (OpCodes.Box, child.Type);
                        
                        if (type.IsGenericParameter) {
-                               ec.ig.Emit (OpCodes.Unbox_Any, type);
+                               ec.Emit (OpCodes.Unbox_Any, type);
                                return;
                        }
                        
                        if (gen && !forced)
                                return;
                        
-                       ec.ig.Emit (OpCodes.Castclass, type);
+                       ec.Emit (OpCodes.Castclass, type);
                }
        }
 
@@ -2157,7 +1948,7 @@ namespace Mono.CSharp {
                                this.orig_expr = orig_expr;
                        }
 
-                       public override Constant ConvertImplicitly (ResolveContext rc, Type target_type)
+                       public override Constant ConvertImplicitly (ResolveContext rc, TypeSpec target_type)
                        {
                                Constant c = base.ConvertImplicitly (rc, target_type);
                                if (c != null)
@@ -2171,18 +1962,7 @@ namespace Mono.CSharp {
                                return orig_expr.CreateExpressionTree (ec);
                        }
 
-                       public override bool GetAttributableValue (ResolveContext ec, Type value_type, out object value)
-                       {
-                               //
-                               // Even if resolved result is a constant original expression was not
-                               // and attribute accepts constants only
-                               //
-                               Attribute.Error_AttributeArgumentNotValid (ec, orig_expr.Location);
-                               value = null;
-                               return false;
-                       }
-
-                       public override Constant ConvertExplicitly (bool in_checked_context, Type target_type)
+                       public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
                        {
                                Constant c = base.ConvertExplicitly (in_checked_context, target_type);
                                if (c != null)
@@ -2224,11 +2004,6 @@ namespace Mono.CSharp {
                        {
                                stm.EmitStatement (ec);
                        }
-
-                       public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-                       {
-                               stm.MutateHoistedGenericType (storey);
-                       }
                }
 
                readonly Expression expr, orig_expr;
@@ -2302,11 +2077,6 @@ namespace Mono.CSharp {
                {
                        return orig_expr.MakeExpression (ctx);
                }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       expr.MutateHoistedGenericType (storey);
-               }
        }
 
        //
@@ -2386,11 +2156,6 @@ namespace Mono.CSharp {
                public Expression Expr {
                        get { return expr; }
                }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       throw new InternalErrorException ("Missing Resolve call");
-               }
        }
 
        //
@@ -2414,12 +2179,42 @@ namespace Mono.CSharp {
                        loc = l;
                }
 
+               protected ATypeNameExpression (string name, int arity, Location l)
+                       : this (name, new UnboundTypeArguments (arity), l)
+               {
+               }
+
+               #region Properties
+
+               protected int Arity {
+                       get {
+                               return targs == null ? 0 : targs.Count;
+                       }
+               }
+
                public bool HasTypeArguments {
                        get {
-                               return targs != null;
+                               return targs != null && !targs.IsEmpty;
                        }
                }
 
+               public string Name {
+                       get {
+                               return name;
+                       }
+                       set {
+                               name = value;
+                       }
+               }
+
+               public TypeArguments TypeArguments {
+                       get {
+                               return targs;
+                       }
+               }
+
+               #endregion
+
                public override bool Equals (object obj)
                {
                        ATypeNameExpression atne = obj as ATypeNameExpression;
@@ -2432,29 +2227,32 @@ namespace Mono.CSharp {
                        return Name.GetHashCode ();
                }
 
-               public override string GetSignatureForError ()
+               // TODO: Move it to MemberCore
+               public static string GetMemberType (MemberCore mc)
                {
-                       if (targs != null) {
-                               return TypeManager.RemoveGenericArity (Name) + "<" +
-                                       targs.GetSignatureForError () + ">";
-                       }
+                       if (mc is Property)
+                               return "property";
+                       if (mc is Indexer)
+                               return "indexer";
+                       if (mc is FieldBase)
+                               return "field";
+                       if (mc is MethodCore)
+                               return "method";
+                       if (mc is EnumMember)
+                               return "enum";
+                       if (mc is Event)
+                               return "event";
 
-                       return Name;
+                       return "type";
                }
 
-               public string Name {
-                       get {
-                               return name;
-                       }
-                       set {
-                               name = value;
+               public override string GetSignatureForError ()
+               {
+                       if (targs != null) {
+                               return Name + "<" + targs.GetSignatureForError () + ">";
                        }
-               }
 
-               public TypeArguments TypeArguments {
-                       get {
-                               return targs;
-                       }
+                       return Name;
                }
        }
        
@@ -2474,45 +2272,14 @@ namespace Mono.CSharp {
                {
                }
 
-               public SimpleName (string name, TypeParameter[] type_params, Location l)
-                       : base (name, l)
+               public SimpleName (string name, int arity, Location l)
+                       : base (name, arity, l)
                {
-                       targs = new TypeArguments ();
-                       foreach (TypeParameter type_param in type_params)
-                               targs.Add (new TypeParameterExpr (type_param, l));
-               }
-
-               public static string RemoveGenericArity (string name)
-               {
-                       int start = 0;
-                       StringBuilder sb = null;
-                       do {
-                               int pos = name.IndexOf ('`', start);
-                               if (pos < 0) {
-                                       if (start == 0)
-                                               return name;
-
-                                       sb.Append (name.Substring (start));
-                                       break;
-                               }
-
-                               if (sb == null)
-                                       sb = new StringBuilder ();
-                               sb.Append (name.Substring (start, pos-start));
-
-                               pos++;
-                               while ((pos < name.Length) && Char.IsNumber (name [pos]))
-                                       pos++;
-
-                               start = pos;
-                       } while (start < name.Length);
-
-                       return sb.ToString ();
                }
 
                public SimpleName GetMethodGroup ()
                {
-                       return new SimpleName (RemoveGenericArity (Name), targs, loc);
+                       return new SimpleName (Name, targs, loc);
                }
 
                public static void Error_ObjectRefRequired (ResolveContext ec, Location l, string name)
@@ -2527,11 +2294,67 @@ namespace Mono.CSharp {
                                        name);
                }
 
+               protected virtual void Error_TypeOrNamespaceNotFound (IMemberContext ec)
+               {
+                       if (ec.CurrentType != null) {
+                               if (ec.CurrentMemberDefinition != null) {
+                                       MemberCore mc = ec.CurrentMemberDefinition.Parent.GetDefinition (Name);
+                                       if (mc != null) {
+                                               Error_UnexpectedKind (ec.Compiler.Report, mc, "type", GetMemberType (mc), loc);
+                                               return;
+                                       }
+                               }
+
+                               /*
+                                                               // TODO MemberCache: Implement
+                                                               string ns = ec.CurrentType.Namespace;
+                                                               string fullname = (ns.Length > 0) ? ns + "." + Name : Name;
+                                                               foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
+                                                                       var type = a.GetType (fullname);
+                                                                       if (type != null) {
+                                                                               ec.Compiler.Report.SymbolRelatedToPreviousError (type);
+                                                                               Expression.ErrorIsInaccesible (loc, TypeManager.CSharpName (type), ec.Compiler.Report);
+                                                                               return;
+                                                                       }
+                                                               }
+
+                                                               if (ec.CurrentTypeDefinition != null) {
+                                                                       TypeSpec t = ec.CurrentTypeDefinition.LookupAnyGeneric (Name);
+                                                                       if (t != null) {
+                                                                               Namespace.Error_InvalidNumberOfTypeArguments (ec.Compiler.Report, t, loc);
+                                                                               return;
+                                                                       }
+                                                               }
+                               */
+                       }
+
+                       FullNamedExpression retval = ec.LookupNamespaceOrType (Name, -System.Math.Max (1, Arity), loc, true);
+                       if (retval != null) {
+                               Error_TypeArgumentsCannotBeUsed (ec.Compiler.Report, loc, retval.Type, Arity);
+/*
+                               var te = retval as TypeExpr;
+                               if (HasTypeArguments && te != null && !te.Type.IsGeneric)
+                                       retval.Error_TypeArgumentsCannotBeUsed (ec.Compiler.Report, loc);
+                               else
+                                       Namespace.Error_InvalidNumberOfTypeArguments (ec.Compiler.Report, retval.Type, loc);
+*/
+                               return;
+                       }
+
+                       NamespaceEntry.Error_NamespaceNotFound (loc, Name, ec.Compiler.Report);
+               }
+
                public bool IdenticalNameAndTypeName (IMemberContext mc, Expression resolved_to, Location loc)
                {
-                       return resolved_to != null && resolved_to.Type != null && 
-                               resolved_to.Type.Name == Name &&
-                               (mc.LookupNamespaceOrType (Name, loc, /* ignore_cs0104 = */ true) != null);
+                       if (resolved_to == null || resolved_to.Type == null)
+                               return false;
+
+                       if (resolved_to.Type is ElementTypeSpec || resolved_to.Type is InternalType)
+                               return false;
+
+                       return resolved_to.Type.Name == Name &&
+                               (mc.LookupNamespaceOrType (Name, Arity, loc, /* ignore_cs0104 = */ true) != null);
                }
 
                protected override Expression DoResolve (ResolveContext ec)
@@ -2549,10 +2372,10 @@ namespace Mono.CSharp {
                        return SimpleNameResolve (ec, null, intermediate);
                }
 
-               static bool IsNestedChild (Type t, Type parent)
+               static bool IsNestedChild (TypeSpec t, TypeSpec parent)
                {
                        while (parent != null) {
-                               if (TypeManager.IsNestedChildOf (t, TypeManager.DropGenericTypeArguments (parent)))
+                               if (TypeManager.IsNestedChildOf (t, parent))
                                        return true;
 
                                parent = parent.BaseType;
@@ -2561,59 +2384,15 @@ namespace Mono.CSharp {
                        return false;
                }
 
-               FullNamedExpression ResolveNested (Type t)
-               {
-                       if (!TypeManager.IsGenericTypeDefinition (t) && !TypeManager.IsGenericType (t))
-                               return null;
-
-                       Type ds = t;
-                       while (ds != null && !IsNestedChild (t, ds))
-                               ds = ds.DeclaringType;
-
-                       if (ds == null)
-                               return null;
-
-                       Type[] gen_params = TypeManager.GetTypeArguments (t);
-
-                       int arg_count = targs != null ? targs.Count : 0;
-
-                       for (; (ds != null) && TypeManager.IsGenericType (ds); ds = ds.DeclaringType) {
-                               Type[] gargs = TypeManager.GetTypeArguments (ds);
-                               if (arg_count + gargs.Length == gen_params.Length) {
-                                       TypeArguments new_args = new TypeArguments ();
-                                       foreach (Type param in gargs)
-                                               new_args.Add (new TypeExpression (param, loc));
-
-                                       if (targs != null)
-                                               new_args.Add (targs);
-
-                                       return new GenericTypeExpr (t, new_args, loc);
-                               }
-                       }
-
-                       return null;
-               }
-
                public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
                {
                        int errors = ec.Compiler.Report.Errors;
-                       FullNamedExpression fne = ec.LookupNamespaceOrType (Name, loc, /*ignore_cs0104=*/ false);
+                       FullNamedExpression fne = ec.LookupNamespaceOrType (Name, Arity, loc, /*ignore_cs0104=*/ false);
 
                        if (fne != null) {
-                               if (fne.Type == null)
-                                       return fne;
-
-                               FullNamedExpression nested = ResolveNested (fne.Type);
-                               if (nested != null)
-                                       return nested.ResolveAsTypeStep (ec, false);
-
-                               if (targs != null) {
-                                       if (TypeManager.IsGenericType (fne.Type)) {
-                                               GenericTypeExpr ct = new GenericTypeExpr (fne.Type, targs, loc);
-                                               return ct.ResolveAsTypeStep (ec, false);
-                                       }
-
-                                       fne.Error_TypeArgumentsCannotBeUsed (ec.Compiler.Report, loc);
+                               if (HasTypeArguments && fne.Type != null && TypeManager.IsGenericType (fne.Type)) {
+                                       GenericTypeExpr ct = new GenericTypeExpr (fne.Type, targs, loc);
+                                       return ct.ResolveAsTypeStep (ec, false);
                                }
 
                                return fne;
@@ -2639,68 +2418,6 @@ namespace Mono.CSharp {
                        return null;
                }
 
-               protected virtual void Error_TypeOrNamespaceNotFound (IMemberContext ec)
-               {
-                       if (ec.CurrentType != null) {
-                               if (ec.CurrentTypeDefinition != null) {
-                                       MemberCore mc = ec.CurrentTypeDefinition.GetDefinition (Name);
-                                       if (mc != null) {
-                                               Error_UnexpectedKind (ec.Compiler.Report, mc, "type", GetMemberType (mc), loc);
-                                               return;
-                                       }
-                               }
-
-                               string ns = ec.CurrentType.Namespace;
-                               string fullname = (ns.Length > 0) ? ns + "." + Name : Name;
-                               foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
-                                       Type type = a.GetType (fullname);
-                                       if (type != null) {
-                                               ec.Compiler.Report.SymbolRelatedToPreviousError (type);
-                                               Expression.ErrorIsInaccesible (loc, TypeManager.CSharpName (type), ec.Compiler.Report);
-                                               return;
-                                       }
-                               }
-
-                               if (ec.CurrentTypeDefinition != null) {
-                                       Type t = ec.CurrentTypeDefinition.LookupAnyGeneric (Name);
-                                       if (t != null) {
-                                               Namespace.Error_InvalidNumberOfTypeArguments (ec.Compiler.Report, t, loc);
-                                               return;
-                                       }
-                               }
-                       }
-
-                       if (targs != null) {
-                               FullNamedExpression retval = ec.LookupNamespaceOrType (SimpleName.RemoveGenericArity (Name), loc, true);
-                               if (retval != null) {
-                                       retval.Error_TypeArgumentsCannotBeUsed (ec.Compiler.Report, loc);
-                                       return;
-                               }
-                       }
-                                               
-                       NamespaceEntry.Error_NamespaceNotFound (loc, Name, ec.Compiler.Report);
-               }
-
-               // TODO: I am still not convinced about this. If someone else will need it
-               // implement this as virtual property in MemberCore hierarchy
-               public static string GetMemberType (MemberCore mc)
-               {
-                       if (mc is Property)
-                               return "property";
-                       if (mc is Indexer)
-                               return "indexer";
-                       if (mc is FieldBase)
-                               return "field";
-                       if (mc is MethodCore)
-                               return "method";
-                       if (mc is EnumMember)
-                               return "enum";
-                       if (mc is Event)
-                               return "event";
-
-                       return "type";
-               }
-
                Expression SimpleNameResolve (ResolveContext ec, Expression right_side, bool intermediate)
                {
                        Expression e = DoSimpleNameResolve (ec, right_side, intermediate);
@@ -2756,8 +2473,8 @@ namespace Mono.CSharp {
                                                }
                                        }
 
-                                       if (targs != null && e != null)
-                                               e.Error_TypeArgumentsCannotBeUsed (ec.Report, loc);
+                                       if (HasTypeArguments && e != null)
+                                               e.Error_TypeArgumentsCannotBeUsed (ec.Report, loc, null, 0);
 
                                        return e;
                                }
@@ -2769,8 +2486,8 @@ namespace Mono.CSharp {
                                        else
                                                e = e.Resolve (ec);
 
-                                       if (targs != null && e != null)
-                                               e.Error_TypeArgumentsCannotBeUsed (ec.Report, loc);
+                                       if (HasTypeArguments && e != null)
+                                               e.Error_TypeArgumentsCannotBeUsed (ec.Report, loc, null, 0);
 
                                        return e;
                                }
@@ -2779,24 +2496,22 @@ namespace Mono.CSharp {
                        //
                        // Stage 2: Lookup members 
                        //
-
-                       Type almost_matched_type = null;
-                       IList<MemberInfo> almost_matched = null;
-                       for (Type lookup_ds = ec.CurrentType; lookup_ds != null; lookup_ds = lookup_ds.DeclaringType) {
-                               e = MemberLookup (ec.Compiler, ec.CurrentType, lookup_ds, Name, loc);
+                       int arity = HasTypeArguments ? Arity : -1;
+//                     TypeSpec almost_matched_type = null;
+//                     IList<MemberSpec> almost_matched = null;
+                       for (TypeSpec lookup_ds = ec.CurrentType; lookup_ds != null; lookup_ds = lookup_ds.DeclaringType) {
+                               e = MemberLookup (ec.Compiler, ec.CurrentType, lookup_ds, Name, arity, BindingRestriction.NoOverrides, loc);
                                if (e != null) {
                                        PropertyExpr pe = e as PropertyExpr;
                                        if (pe != null) {
-                                               AParametersCollection param = TypeManager.GetParameterData (pe.PropertyInfo);
-
                                                // since TypeManager.MemberLookup doesn't know if we're doing a lvalue access or not,
                                                // it doesn't know which accessor to check permissions against
-                                               if (param.IsEmpty && pe.IsAccessibleFrom (ec.CurrentType, right_side != null))
+                                               if (pe.PropertyInfo.Kind == MemberKind.Property && pe.IsAccessibleFrom (ec.CurrentType, right_side != null))
                                                        break;
                                        } else if (e is EventExpr) {
                                                if (((EventExpr) e).IsAccessibleFrom (ec.CurrentType))
                                                        break;
-                                       } else if (targs != null && e is TypeExpression) {
+                                       } else if (HasTypeArguments && e is TypeExpression) {
                                                e = new GenericTypeExpr (e.Type, targs, loc).ResolveAsTypeStep (ec, false);
                                                break;
                                        } else {
@@ -2804,18 +2519,21 @@ namespace Mono.CSharp {
                                        }
                                        e = null;
                                }
-
+/*
                                if (almost_matched == null && almost_matched_members.Count > 0) {
                                        almost_matched_type = lookup_ds;
-                                       almost_matched = new List<MemberInfo>(almost_matched_members);
+                                       almost_matched = new List<MemberSpec>(almost_matched_members);
                                }
+*/ 
                        }
 
                        if (e == null) {
+/*
                                if (almost_matched == null && almost_matched_members.Count > 0) {
                                        almost_matched_type = ec.CurrentType;
-                                       almost_matched = new List<MemberInfo> (almost_matched_members);
+                                       almost_matched = new List<MemberSpec> (almost_matched_members);
                                }
+*/ 
                                e = ResolveAsTypeStep (ec, true);
                        }
 
@@ -2836,17 +2554,17 @@ namespace Mono.CSharp {
                                if (RootContext.EvalMode){
                                        FieldInfo fi = Evaluator.LookupField (Name);
                                        if (fi != null)
-                                               return new FieldExpr (Import.CreateField (fi), loc).Resolve (ec);
+                                               return new FieldExpr (Import.CreateField (fi, null), loc).Resolve (ec);
                                }
-
+/*
                                if (almost_matched != null)
                                        almost_matched_members = almost_matched;
                                if (almost_matched_type == null)
                                        almost_matched_type = ec.CurrentType;
-
+*/
                                string type_name = ec.MemberContext.CurrentType == null ? null : ec.MemberContext.CurrentType.Name;
-                               return Error_MemberLookupFailed (ec, ec.CurrentType, null, almost_matched_type, Name,
-                                       type_name, AllMemberTypes, AllBindingFlags);
+                               return Error_MemberLookupFailed (ec, ec.CurrentType, null, ec.CurrentType, Name, arity,
+                                       type_name, MemberKind.All, BindingRestriction.AccessibleOnly);
                        }
 
                        if (e is MemberExpr) {
@@ -2861,13 +2579,13 @@ namespace Mono.CSharp {
                                                // and each predicate is true if the MethodGroupExpr contains
                                                // at least one of that kind of method.
                                                //
-
+/*
                                                if (!me.IsStatic &&
                                                    (!intermediate || !IdenticalNameAndTypeName (ec, me, loc))) {
                                                        Error_ObjectRefRequired (ec, loc, me.GetSignatureForError ());
                                                        return null;
                                                }
-
+*/
                                                //
                                                // Pass the buck to MemberAccess and Invocation.
                                                //
@@ -2883,7 +2601,7 @@ namespace Mono.CSharp {
                                if (me == null)
                                        return null;
 
-                               if (targs != null) {
+                               if (HasTypeArguments) {
                                        if (!targs.Resolve (ec))
                                                return null;
 
@@ -2926,11 +2644,6 @@ namespace Mono.CSharp {
                        throw new NotSupportedException ("ET");
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       throw new NotSupportedException ();
-               }
-
                public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
                {
                        return this;
@@ -2964,35 +2677,11 @@ namespace Mono.CSharp {
 
                public virtual bool CheckAccessLevel (IMemberContext mc)
                {
-                       return mc.CurrentTypeDefinition.CheckAccessLevel (Type);
-               }
-
-               public virtual bool IsClass {
-                       get { return Type.IsClass; }
-               }
+                       DeclSpace c = mc.CurrentMemberDefinition as DeclSpace;
+                       if (c == null)
+                               c = mc.CurrentMemberDefinition.Parent;
 
-               public virtual bool IsValueType {
-                       get { return TypeManager.IsStruct (Type); }
-               }
-
-               public virtual bool IsInterface {
-                       get { return Type.IsInterface; }
-               }
-
-               public virtual bool IsSealed {
-                       get { return Type.IsSealed; }
-               }
-
-               public virtual bool CanInheritFrom ()
-               {
-                       if (Type == TypeManager.enum_type ||
-                           (Type == TypeManager.value_type && RootContext.StdLib) ||
-                           Type == TypeManager.multicast_delegate_type ||
-                           Type == TypeManager.delegate_type ||
-                           Type == TypeManager.array_type)
-                               return false;
-
-                       return true;
+                       return c.CheckAccessLevel (Type);
                }
 
                protected abstract TypeExpr DoResolveAsTypeStep (IMemberContext ec);
@@ -3010,18 +2699,13 @@ namespace Mono.CSharp {
                {
                        return Type.GetHashCode ();
                }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       type = storey.MutateType (type);
-               }
        }
 
        /// <summary>
        ///   Fully resolved Expression that already evaluated to a type
        /// </summary>
        public class TypeExpression : TypeExpr {
-               public TypeExpression (Type t, Location l)
+               public TypeExpression (TypeSpec t, Location l)
                {
                        Type = t;
                        eclass = ExprClass.Type;
@@ -3044,48 +2728,16 @@ namespace Mono.CSharp {
        // by the parser to setup the core types.
        //
        public sealed class TypeLookupExpression : TypeExpr {
-               readonly string ns_name;
-               readonly string name;
                
-               public TypeLookupExpression (string ns, string name)
+               public TypeLookupExpression (TypeSpec type)
                {
-                       this.name = name;
-                       this.ns_name = ns;
                        eclass = ExprClass.Type;
+                       this.type = type;
                }
 
-               public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
-               {
-                       //
-                       // It's null only during mscorlib bootstrap when DefineType
-                       // nees to resolve base type of same type
-                       //
-                       // For instance struct Char : IComparable<char>
-                       //
-                       // TODO: it could be removed when Resolve starts to use 
-                       // DeclSpace instead of Type
-                       //
-                       if (type == null) {
-                               Namespace ns = GlobalRootNamespace.Instance.GetNamespace (ns_name, false);
-                               FullNamedExpression fne = ns.Lookup (ec.Compiler, name, loc);
-                               if (fne != null)
-                                       type = fne.Type;
-                       }
-
-                       return this;
-               }
-
-               protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
-               {
-                       return this;
-               }
-
-               public override string GetSignatureForError ()
+               protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
                {
-                       if (type == null)
-                               return TypeManager.CSharpName (ns_name + "." + name, null);
-
-                       return base.GetSignatureForError ();
+                       return this;
                }
        }
 
@@ -3129,7 +2781,7 @@ namespace Mono.CSharp {
                /// <summary>
                ///   The type which declares this member.
                /// </summary>
-               public abstract Type DeclaringType {
+               public abstract TypeSpec DeclaringType {
                        get;
                }
 
@@ -3150,14 +2802,6 @@ namespace Mono.CSharp {
                        ec.Report.Error (831, loc, "An expression tree may not contain a base access");
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       if (InstanceExpression != null)
-                               InstanceExpression.MutateHoistedGenericType (storey);
-               }
-
-               // TODO: possible optimalization
-               // Cache resolved constant result in FieldBuilder <-> expression map
                public virtual MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, Location loc,
                                                               SimpleName original)
                {
@@ -3167,20 +2811,20 @@ namespace Mono.CSharp {
                        //
 
                        if (left is TypeExpr) {
-                               left = left.ResolveAsBaseTerminal (ec, false);
+                               left = ((TypeExpr) left).ResolveAsTypeTerminal (ec, false);
                                if (left == null)
                                        return null;
 
                                // TODO: Same problem as in class.cs, TypeTerminal does not
                                // always do all necessary checks
-                               ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (left.Type);
+                               ObsoleteAttribute oa = left.Type.GetAttributeObsolete ();
                                if (oa != null && !ec.IsObsolete) {
                                        AttributeTester.Report_ObsoleteMessage (oa, left.GetSignatureForError (), loc, ec.Report);
                                }
 
-                               GenericTypeExpr ct = left as GenericTypeExpr;
-                               if (ct != null && !ct.CheckConstraints (ec))
-                                       return null;
+//                             GenericTypeExpr ct = left as GenericTypeExpr;
+//                             if (ct != null && !ct.CheckConstraints (ec))
+//                                     return null;
                                //
 
                                if (!IsStatic) {
@@ -3232,7 +2876,7 @@ namespace Mono.CSharp {
                                InstanceExpression.Emit (ec);
 
                        if (prepare_for_load)
-                               ec.ig.Emit (OpCodes.Dup);
+                               ec.Emit (OpCodes.Dup);
                }
 
                public virtual void SetTypeArguments (ResolveContext ec, TypeArguments ta)
@@ -3250,10 +2894,9 @@ namespace Mono.CSharp {
        {
                readonly NamespaceEntry namespace_entry;
                public Expression ExtensionExpression;
-               Argument extension_argument;
 
-               public ExtensionMethodGroupExpr (List<MethodSpec> list, NamespaceEntry n, Type extensionType, Location l)
-                       : base (list, extensionType, l)
+               public ExtensionMethodGroupExpr (List<MethodSpec> list, NamespaceEntry n, TypeSpec extensionType, Location l)
+                       : base (list.Cast<MemberSpec>().ToList (), extensionType, l)
                {
                        this.namespace_entry = n;
                }
@@ -3266,12 +2909,6 @@ namespace Mono.CSharp {
                        get { return namespace_entry == null; }
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       extension_argument.Expr.MutateHoistedGenericType (storey);
-                       base.MutateHoistedGenericType (storey);
-               }
-
                public override MethodGroupExpr OverloadResolve (ResolveContext ec, ref Arguments arguments, bool may_fail, Location loc)
                {
                        if (arguments == null)
@@ -3281,9 +2918,7 @@ namespace Mono.CSharp {
                        MethodGroupExpr mg = ResolveOverloadExtensions (ec, ref arguments, namespace_entry, loc);
 
                        // Store resolved argument and restore original arguments
-                       if (mg != null)
-                               ((ExtensionMethodGroupExpr)mg).extension_argument = arguments [0];
-                       else
+                       if (mg == null)
                                arguments.RemoveAt (0); // Clean-up modified arguments for error reporting
 
                        return mg;
@@ -3300,7 +2935,8 @@ namespace Mono.CSharp {
                                return null;
 
                        // Search continues
-                       ExtensionMethodGroupExpr e = ns.LookupExtensionMethod (type, Name, loc);
+                       int arity = type_arguments == null ? -1 : type_arguments.Count;
+                       ExtensionMethodGroupExpr e = ns.LookupExtensionMethod (type, Name, arity, loc);
                        if (e == null)
                                return base.OverloadResolve (ec, ref arguments, false, loc);
 
@@ -3323,47 +2959,34 @@ namespace Mono.CSharp {
                }
 
                public IErrorHandler CustomErrorHandler;
-               public MethodSpec [] Methods;
+               public IList<MemberSpec> Methods;
                MethodSpec best_candidate;
                // TODO: make private
                public TypeArguments type_arguments;
                bool identical_type_name;
                bool has_inaccessible_candidates_only;
-               Type delegate_type;
-               Type queried_type;
-               
-               public MethodGroupExpr (MethodSpec [] mi, Type type, Location l)
+               TypeSpec delegate_type;
+               TypeSpec queried_type;
+
+               public MethodGroupExpr (IList<MemberSpec> mi, TypeSpec type, Location l)
                        : this (type, l)
                {
-                       Methods = new MethodSpec[mi.Length];
-                       mi.CopyTo (Methods, 0);
+                       Methods = mi;
                }
 
-               public MethodGroupExpr (MethodSpec[] mi, Type type, Location l, bool inacessibleCandidatesOnly)
-                       : this (mi, type, l)
+               public MethodGroupExpr (MethodSpec m, TypeSpec type, Location l)
+                       : this (type, l)
                {
-                       has_inaccessible_candidates_only = inacessibleCandidatesOnly;
+                       Methods = new List<MemberSpec> (1) { m };
                }
 
-               public MethodGroupExpr (List<MethodSpec> list, Type type, Location l)
-                       : this (type, l)
+               public MethodGroupExpr (IList<MemberSpec> mi, TypeSpec type, Location l, bool inacessibleCandidatesOnly)
+                       : this (mi, type, l)
                {
-                       try {
-                               Methods = list.ToArray ();
-                       } catch {
-                               //foreach (MemberInfo m in list){
-                               //    if (!(m is MethodBase)){
-                               //        Console.WriteLine ("Name " + m.Name);
-                               //        Console.WriteLine ("Found a: " + m.GetType ().FullName);
-                               //    }
-                               //}
-                               throw;
-                       }
-
-
+                       has_inaccessible_candidates_only = inacessibleCandidatesOnly;
                }
-
-               protected MethodGroupExpr (Type type, Location loc)
+               
+               protected MethodGroupExpr (TypeSpec type, Location loc)
                {
                        this.loc = loc;
                        eclass = ExprClass.MethodGroup;
@@ -3371,7 +2994,7 @@ namespace Mono.CSharp {
                        queried_type = type;
                }
 
-               public override Type DeclaringType {
+               public override TypeSpec DeclaringType {
                        get {
                                return queried_type;
                        }
@@ -3383,7 +3006,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               public Type DelegateType {
+               public TypeSpec DelegateType {
                        set {
                                delegate_type = value;
                        }
@@ -3398,14 +3021,14 @@ namespace Mono.CSharp {
                public override string GetSignatureForError ()
                {
                        if (best_candidate != null)
-                               return TypeManager.CSharpSignature (best_candidate.MetaInfo);
-                       
-                       return TypeManager.CSharpSignature (Methods [0].MetaInfo);
+                               return best_candidate.GetSignatureForError ();
+
+                       return Methods.First ().GetSignatureForError ();
                }
 
                public override string Name {
                        get {
-                               return Methods [0].Name;
+                               return Methods.First ().Name;
                        }
                }
 
@@ -3446,22 +3069,22 @@ namespace Mono.CSharp {
                //              2    if a->q is better,
                //              0 if neither is better
                //
-               static int BetterExpressionConversion (ResolveContext ec, Argument a, Type p, Type q)
+               static int BetterExpressionConversion (ResolveContext ec, Argument a, TypeSpec p, TypeSpec q)
                {
-                       Type argument_type = TypeManager.TypeToCoreType (a.Type);
+                       TypeSpec argument_type = a.Type;
                        if (argument_type == InternalType.AnonymousMethod && RootContext.Version > LanguageVersion.ISO_2) {
                                //
                                // Uwrap delegate from Expression<T>
                                //
-                               if (TypeManager.DropGenericTypeArguments (p) == TypeManager.expression_type) {
+                               if (p.GetDefinition () == TypeManager.expression_type) {
                                        p = TypeManager.GetTypeArguments (p) [0];
                                }
-                               if (TypeManager.DropGenericTypeArguments (q) == TypeManager.expression_type) {
+                               if (q.GetDefinition () == TypeManager.expression_type) {
                                        q = TypeManager.GetTypeArguments (q) [0];
                                }
                                
-                               p = Delegate.GetInvokeMethod (ec.Compiler, null, p).ReturnType;
-                               q = Delegate.GetInvokeMethod (ec.Compiler, null, q).ReturnType;
+                               p = Delegate.GetInvokeMethod (ec.Compiler, p).ReturnType;
+                               q = Delegate.GetInvokeMethod (ec.Compiler, q).ReturnType;
                                if (p == TypeManager.void_type && q != TypeManager.void_type)
                                        return 2;
                                if (q == TypeManager.void_type && p != TypeManager.void_type)
@@ -3480,7 +3103,7 @@ namespace Mono.CSharp {
                //
                // 7.4.3.4  Better conversion from type
                //
-               public static int BetterTypeConversion (ResolveContext ec, Type p, Type q)
+               public static int BetterTypeConversion (ResolveContext ec, TypeSpec p, TypeSpec q)
                {
                        if (p == null || q == null)
                                throw new InternalErrorException ("BetterTypeConversion got a null conversion");
@@ -3565,8 +3188,8 @@ namespace Mono.CSharp {
                                if (a.IsDefaultArgument && candidate_params == best_params)
                                        return false;
 
-                               Type ct = candidate_pd.Types [c_idx];
-                               Type bt = best_pd.Types [b_idx];
+                               TypeSpec ct = candidate_pd.Types [c_idx];
+                               TypeSpec bt = best_pd.Types [b_idx];
 
                                if (candidate_params && candidate_pd.FixedParameters [c_idx].ModFlags == Parameter.Modifier.PARAMS) 
                                {
@@ -3615,10 +3238,10 @@ namespace Mono.CSharp {
                        //
                        // The two methods have equal parameter types.  Now apply tie-breaking rules
                        //
-                       if (best.IsGenericMethod) {
-                               if (!candidate.IsGenericMethod)
+                       if (best.IsGeneric) {
+                               if (!candidate.IsGeneric)
                                        return true;
-                       } else if (candidate.IsGenericMethod) {
+                       } else if (candidate.IsGeneric) {
                                return false;
                        }
 
@@ -3643,24 +3266,20 @@ namespace Mono.CSharp {
                                return candidate_param_count > best_param_count && best_pd.HasParams;
 
                        //
-                       // now, both methods have the same number of parameters, and the parameters have the same types
-                       // Pick the "more specific" signature
+                       // Both methods have the same number of parameters, and the parameters have equal types
+                       // Pick the "more specific" signature using rules over original (non-inflated) types
                        //
-
-                       MethodBase orig_candidate = TypeManager.DropGenericMethodArguments (candidate);
-                       MethodBase orig_best = TypeManager.DropGenericMethodArguments (best);
-
-                       AParametersCollection orig_candidate_pd = TypeManager.GetParameterData (orig_candidate);
-                       AParametersCollection orig_best_pd = TypeManager.GetParameterData (orig_best);
+                       var candidate_def_pd = ((IParametersMember) candidate.MemberDefinition).Parameters;
+                       var best_def_pd = ((IParametersMember) best.MemberDefinition).Parameters;
 
                        bool specific_at_least_once = false;
                        for (int j = 0; j < candidate_param_count; ++j) 
                        {
-                               Type ct = orig_candidate_pd.Types [j];
-                               Type bt = orig_best_pd.Types [j];
-                               if (ct.Equals (bt))
+                               var ct = candidate_def_pd.Types [j];
+                               var bt = best_def_pd.Types [j];
+                               if (ct == bt)
                                        continue;
-                               Type specific = MoreSpecific (ct, bt);
+                               TypeSpec specific = MoreSpecific (ct, bt);
                                if (specific == bt)
                                        return false;
                                if (specific == ct)
@@ -3706,8 +3325,7 @@ namespace Mono.CSharp {
                                return null;
                        }
 
-                       IMethodData md = TypeManager.GetMethod (best_candidate.MetaInfo);
-                       if (md != null && md.IsExcluded ())
+                       if (best_candidate.IsConditionallyExcluded (loc))
                                ec.Report.Error (765, loc,
                                        "Partial methods with only a defining declaration or removed conditional methods cannot be used in an expression tree");
                        
@@ -3749,18 +3367,18 @@ namespace Mono.CSharp {
                        if (CustomErrorHandler != null && CustomErrorHandler.AmbiguousCall (ec, ambiguous))
                                return;
 
-                       ec.Report.SymbolRelatedToPreviousError (best_candidate.MetaInfo);
+                       ec.Report.SymbolRelatedToPreviousError (best_candidate);
                        ec.Report.Error (121, loc, "The call is ambiguous between the following methods or properties: `{0}' and `{1}'",
-                               TypeManager.CSharpSignature (ambiguous), TypeManager.CSharpSignature (best_candidate.MetaInfo));
+                               best_candidate.GetSignatureForError (), ambiguous.GetSignatureForError ());
                }
 
                protected virtual void Error_InvalidArguments (ResolveContext ec, Location loc, int idx, MethodSpec method,
-                                                                                                       Argument a, AParametersCollection expected_par, Type paramType)
+                                                                                                       Argument a, AParametersCollection expected_par, TypeSpec paramType)
                {
                        ExtensionMethodGroupExpr emg = this as ExtensionMethodGroupExpr;
 
                        if (a is CollectionElementInitializer.ElementInitializerArgument) {
-                               ec.Report.SymbolRelatedToPreviousError (method.MetaInfo);
+                               ec.Report.SymbolRelatedToPreviousError (method);
                                if ((expected_par.FixedParameters [idx].ModFlags & Parameter.Modifier.ISBYREF) != 0) {
                                        ec.Report.Error (1954, loc, "The best overloaded collection initalizer method `{0}' cannot have 'ref', or `out' modifier",
                                                TypeManager.CSharpSignature (method));
@@ -3772,7 +3390,7 @@ namespace Mono.CSharp {
                                ec.Report.Error (1594, loc, "Delegate `{0}' has some invalid arguments",
                                        TypeManager.CSharpName (method.DeclaringType));
                        } else {
-                               ec.Report.SymbolRelatedToPreviousError (method.MetaInfo);
+                               ec.Report.SymbolRelatedToPreviousError (method);
                                if (emg != null) {
                                        ec.Report.Error (1928, loc,
                                                "Type `{0}' does not contain a member `{1}' and the best extension method overload `{2}' has some invalid arguments",
@@ -3815,7 +3433,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, Type target, bool expl)
+               public override void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, TypeSpec target, bool expl)
                {
                        ec.Report.Error (428, loc, "Cannot convert method group `{0}' to non-delegate type `{1}'. Consider using parentheses to invoke the method",
                                Name, TypeManager.CSharpName (target));
@@ -3830,13 +3448,27 @@ namespace Mono.CSharp {
                protected virtual int GetApplicableParametersCount (MethodSpec method, AParametersCollection parameters)
                {
                        return parameters.Count;
-               }               
+               }
 
-               public static bool IsAncestralType (Type first_type, Type second_type)
+               protected virtual IList<MemberSpec> GetBaseTypeMethods (ResolveContext rc, TypeSpec type)
                {
-                       return first_type != second_type &&
-                               (TypeManager.IsSubclassOf (second_type, first_type) ||
-                               TypeManager.ImplementsInterface (second_type, first_type));
+                       return TypeManager.MemberLookup (rc.CurrentType, null, type,
+                               MemberKind.Method, BindingRestriction.AccessibleOnly | BindingRestriction.NoOverrides,
+                               Name, 0, null); // TODO MemberCache: Arity !
+               }
+
+               bool GetBaseTypeMethods (ResolveContext rc)
+               {
+                       var base_type = Methods.First ().DeclaringType.BaseType;
+                       if (base_type == null)
+                               return false;
+
+                       var methods = GetBaseTypeMethods (rc, base_type);
+                       if (methods == null)
+                               return false;
+
+                       Methods = methods;
+                       return true;
                }
 
                ///
@@ -3948,13 +3580,13 @@ namespace Mono.CSharp {
                        //
                        // 1. Handle generic method using type arguments when specified or type inference
                        //
-                       if (candidate.IsGenericMethod) {
+                       if (candidate.IsGeneric) {
                                if (type_arguments != null) {
-                                       Type [] g_args = candidate.GetGenericArguments ();
-                                       if (g_args.Length != type_arguments.Count)
-                                               return int.MaxValue - 20000 + System.Math.Abs (type_arguments.Count - g_args.Length);
+                                       var g_args_count = candidate.Arity;
+                                       if (g_args_count != type_arguments.Count)
+                                               return int.MaxValue - 20000 + System.Math.Abs (type_arguments.Count - g_args_count);
 
-                                       method = candidate.Inflate (type_arguments.Arguments);
+                                       method = candidate.MakeGenericMethod (type_arguments.Arguments);
                                        candidate = method;
                                        pd = candidate.Parameters;
                                } else {
@@ -3962,10 +3594,6 @@ namespace Mono.CSharp {
                                        if (score != 0)
                                                return score - 20000;
 
-                                       if (TypeManager.IsGenericMethodDefinition (candidate.MetaInfo))
-                                               throw new InternalErrorException ("A generic method `{0}' definition took part in overload resolution",
-                                                       TypeManager.CSharpSignature (candidate.MetaInfo));
-
                                        pd = candidate.Parameters;
                                }
                        } else {
@@ -3978,7 +3606,7 @@ namespace Mono.CSharp {
                        //
                        method = candidate;
                        Parameter.Modifier p_mod = 0;
-                       Type pt = null;
+                       TypeSpec pt = null;
                        for (int i = 0; i < arg_count; i++) {
                                Argument a = arguments [i];
                                if (a == null) {
@@ -4025,7 +3653,7 @@ namespace Mono.CSharp {
                        return 0;
                }
 
-               int IsArgumentCompatible (ResolveContext ec, Parameter.Modifier arg_mod, Argument argument, Parameter.Modifier param_mod, Type parameter)
+               int IsArgumentCompatible (ResolveContext ec, Parameter.Modifier arg_mod, Argument argument, Parameter.Modifier param_mod, TypeSpec parameter)
                {
                        //
                        // Types have to be identical when ref or out modifer is used 
@@ -4034,19 +3662,19 @@ namespace Mono.CSharp {
                                if (TypeManager.HasElementType (parameter))
                                        parameter = TypeManager.GetElementType (parameter);
 
-                               Type a_type = argument.Type;
+                               TypeSpec a_type = argument.Type;
                                if (TypeManager.HasElementType (a_type))
                                        a_type = TypeManager.GetElementType (a_type);
 
                                if (a_type != parameter) {
-                                       if (TypeManager.IsDynamicType (a_type))
+                                       if (a_type == InternalType.Dynamic)
                                                return 0;
 
                                        return 2;
                                }
                        } else {
                                if (!Convert.ImplicitConversionExists (ec, argument.Expr, parameter)) {
-                                       if (TypeManager.IsDynamicType (argument.Type))
+                                       if (argument.Type == InternalType.Dynamic)
                                                return 0;
 
                                        return 2;
@@ -4059,31 +3687,6 @@ namespace Mono.CSharp {
                        return 0;
                }
 
-               public static bool IsOverride (MethodBase cand_method, MethodBase base_method)
-               {
-                       if (!IsAncestralType (base_method.DeclaringType, cand_method.DeclaringType))
-                               return false;
-
-                       AParametersCollection cand_pd = TypeManager.GetParameterData (cand_method);
-                       AParametersCollection base_pd = TypeManager.GetParameterData (base_method);
-               
-                       if (cand_pd.Count != base_pd.Count)
-                               return false;
-
-                       for (int j = 0; j < cand_pd.Count; ++j) 
-                       {
-                               Parameter.Modifier cm = cand_pd.FixedParameters [j].ModFlags;
-                               Parameter.Modifier bm = base_pd.FixedParameters [j].ModFlags;
-                               Type ct = cand_pd.Types [j];
-                               Type bt = base_pd.Types [j];
-
-                               if (cm != bm || ct != bt)
-                                       return false;
-                       }
-
-                       return true;
-               }
-
                public static MethodGroupExpr MakeUnionSet (MethodGroupExpr mg1, MethodGroupExpr mg2, Location loc)
                {
                        if (mg1 == null) {
@@ -4095,46 +3698,42 @@ namespace Mono.CSharp {
                        if (mg2 == null)
                                return mg1;
 
-                       var all = new List<MethodSpec> (mg1.Methods);
-                       foreach (var m in mg2.Methods){
-                               if (!TypeManager.ArrayContainsMethod (mg1.Methods.Select (l => l.MetaInfo).ToArray (), m.MetaInfo, false))
+                       var all = new List<MemberSpec> (mg1.Methods);
+                       foreach (MethodSpec m in mg2.Methods){
+                               if (!TypeManager.ArrayContainsMethod (all, m, false))
                                        all.Add (m);
                        }
 
                        return new MethodGroupExpr (all, null, loc);
                }               
 
-               static Type MoreSpecific (Type p, Type q)
+               static TypeSpec MoreSpecific (TypeSpec p, TypeSpec q)
                {
                        if (TypeManager.IsGenericParameter (p) && !TypeManager.IsGenericParameter (q))
                                return q;
                        if (!TypeManager.IsGenericParameter (p) && TypeManager.IsGenericParameter (q))
                                return p;
 
-                       if (TypeManager.HasElementType (p)) 
-                       {
-                               Type pe = TypeManager.GetElementType (p);
-                               Type qe = TypeManager.GetElementType (q);
-                               Type specific = MoreSpecific (pe, qe);
-                               if (specific == pe)
+                       var ac_p = p as ArrayContainer;
+                       if (ac_p != null) {
+                               var ac_q = ((ArrayContainer) q);
+                               TypeSpec specific = MoreSpecific (ac_p.Element, (ac_q.Element));
+                               if (specific == ac_p.Element)
                                        return p;
-                               if (specific == qe)
+                               if (specific == ac_q.Element)
                                        return q;
-                       } 
-                       else if (TypeManager.IsGenericType (p)) 
-                       {
-                               Type[] pargs = TypeManager.GetTypeArguments (p);
-                               Type[] qargs = TypeManager.GetTypeArguments (q);
+                       } else if (TypeManager.IsGenericType (p)) {
+                               var pargs = TypeManager.GetTypeArguments (p);
+                               var qargs = TypeManager.GetTypeArguments (q);
 
                                bool p_specific_at_least_once = false;
                                bool q_specific_at_least_once = false;
 
-                               for (int i = 0; i < pargs.Length; i++) 
-                               {
-                                       Type specific = MoreSpecific (TypeManager.TypeToCoreType (pargs [i]), TypeManager.TypeToCoreType (qargs [i]));
-                                       if (specific == pargs [i])
+                               for (int i = 0; i < pargs.Length; i++) {
+                                       TypeSpec specific = MoreSpecific (pargs[i], qargs[i]);
+                                       if (specific == pargs[i])
                                                p_specific_at_least_once = true;
-                                       if (specific == qargs [i])
+                                       if (specific == qargs[i])
                                                q_specific_at_least_once = true;
                                }
 
@@ -4147,17 +3746,6 @@ namespace Mono.CSharp {
                        return null;
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       base.MutateHoistedGenericType (storey);
-
-                       if (best_candidate.IsConstructor) {
-                               storey.MutateConstructor (best_candidate);
-                       } else {
-                               storey.MutateGenericMethod (best_candidate);                            
-                       }
-               }
-
                /// <summary>
                ///   Find the Applicable Function Members (7.4.2.1)
                ///
@@ -4177,126 +3765,81 @@ namespace Mono.CSharp {
                public virtual MethodGroupExpr OverloadResolve (ResolveContext ec, ref Arguments Arguments,
                        bool may_fail, Location loc)
                {
-                       bool method_params = false;
-                       Type applicable_type = null;
                        var candidates = new List<MethodSpec> (2);
-                       List<MethodSpec> candidate_overrides = null;
+                       List<MethodSpec> params_candidates = null;
 
-                       //
-                       // Used to keep a map between the candidate
-                       // and whether it is being considered in its
-                       // normal or expanded form
-                       //
-                       // false is normal form, true is expanded form
-                       //
-                       Dictionary<MethodSpec, MethodSpec> candidate_to_form = null;
+                       int arg_count = Arguments != null ? Arguments.Count : 0;
                        Dictionary<MethodSpec, Arguments> candidates_expanded = null;
                        Arguments candidate_args = Arguments;
 
-                       int arg_count = Arguments != null ? Arguments.Count : 0;
-
                        if (RootContext.Version == LanguageVersion.ISO_1 && Name == "Invoke" && TypeManager.IsDelegateType (DeclaringType)) {
                                if (!may_fail)
                                        ec.Report.Error (1533, loc, "Invoke cannot be called directly on a delegate");
                                return null;
                        }
 
-                       int nmethods = Methods.Length;
-
-                       if (!IsBase) {
-                               //
-                               // Methods marked 'override' don't take part in 'applicable_type'
-                               // computation, nor in the actual overload resolution.
-                               // However, they still need to be emitted instead of a base virtual method.
-                               // So, we salt them away into the 'candidate_overrides' array.
-                               //
-                               // In case of reflected methods, we replace each overriding method with
-                               // its corresponding base virtual method.  This is to improve compatibility
-                               // with non-C# libraries which change the visibility of overrides (#75636)
-                               //
-                               int j = 0;
-                               MethodBase mb = null;
-                               for (int i = 0; i < Methods.Length; ++i) {
-                                       var m = Methods [i];
-                                       mb = m.MetaInfo;
-                                       if (TypeManager.IsOverride (m)) {
-                                               if (candidate_overrides == null)
-                                                       candidate_overrides = new List<MethodSpec> ();
-                                               candidate_overrides.Add (m);
-                                               mb = TypeManager.TryGetBaseDefinition (mb);
-                                               if (mb != null && Array.Exists (Methods, l => l.MetaInfo == mb))
-                                                       continue;
-                                       }
-                                       if (mb != null)
-                                               Methods [j++] = Import.CreateMethod (mb);
-                               }
-                               nmethods = j;
-                       }
-
                        //
                        // Enable message recording, it's used mainly by lambda expressions
                        //
-                       SessionReportPrinter msg_recorder = new SessionReportPrinter ();
-                       ReportPrinter prev_recorder = ec.Report.SetPrinter (msg_recorder);
-
-                       //
-                       // First we construct the set of applicable methods
-                       //
-                       bool is_sorted = true;
-                       int best_candidate_rate = int.MaxValue;
-                       for (int i = 0; i < nmethods; i++) {
-                               Type decl_type = Methods [i].DeclaringType;
+                       var msg_recorder = new SessionReportPrinter ();
+                       var prev_recorder = ec.Report.SetPrinter (msg_recorder);
 
+                       do {
                                //
-                               // If we have already found an applicable method
-                               // we eliminate all base types (Section 14.5.5.1)
+                               // Methods in a base class are not candidates if any method in a derived
+                               // class is applicable
                                //
-                               if (applicable_type != null && IsAncestralType (decl_type, applicable_type))
-                                       continue;
+                               int best_candidate_rate = int.MaxValue;
+
+                               foreach (var member in Methods) {
+                                       var m = member as MethodSpec;
+                                       if (m == null) {
+                                               // TODO: It's wrong when non-member is before applicable method
+                                               // TODO: Should report only when at least 1 from the batch is applicable
+                                               if (candidates.Count != 0) {
+                                                       ec.Report.SymbolRelatedToPreviousError (candidates [0]);
+                                                       ec.Report.SymbolRelatedToPreviousError (member);
+                                                       ec.Report.Warning (467, 2, loc, "Ambiguity between method `{0}' and non-method `{1}'. Using method `{0}'",
+                                                               candidates[0].GetSignatureForError (), member.GetSignatureForError ());
+                                               }
+                                               continue;
+                                       }
 
-                               //
-                               // Check if candidate is applicable (section 14.4.2.1)
-                               //
-                               bool params_expanded_form = false;
-                               int candidate_rate = IsApplicable (ec, ref candidate_args, arg_count, ref Methods [i], ref params_expanded_form);
+                                       //
+                                       // Check if candidate is applicable (section 14.4.2.1)
+                                       //
+                                       bool params_expanded_form = false;
+                                       int candidate_rate = IsApplicable (ec, ref candidate_args, arg_count, ref m, ref params_expanded_form);
 
-                               if (candidate_rate < best_candidate_rate) {
-                                       best_candidate_rate = candidate_rate;
-                                       best_candidate = Methods [i];
-                               }
-                               
-                               if (params_expanded_form) {
-                                       if (candidate_to_form == null)
-                                               candidate_to_form = new Dictionary<MethodSpec, MethodSpec> (4, ReferenceEquality<MethodSpec>.Default);
-                                       var candidate = Methods [i];
-                                       candidate_to_form [candidate] = candidate;
-                               }
-                               
-                               if (candidate_args != Arguments) {
-                                       if (candidates_expanded == null)
-                                               candidates_expanded = new Dictionary<MethodSpec, Arguments> (4, ReferenceEquality<MethodSpec>.Default);
+                                       if (candidate_rate < best_candidate_rate) {
+                                               best_candidate_rate = candidate_rate;
+                                               best_candidate = m;
+                                       }
 
-                                       candidates_expanded.Add (Methods [i], candidate_args);
-                                       candidate_args = Arguments;
-                               }
+                                       if (params_expanded_form) {
+                                               if (params_candidates == null)
+                                                       params_candidates = new List<MethodSpec> (2);
+                                               params_candidates.Add (m);
+                                       }
 
-                               if (candidate_rate != 0 || has_inaccessible_candidates_only) {
-                                       if (msg_recorder != null)
-                                               msg_recorder.EndSession ();
-                                       continue;
-                               }
+                                       if (candidate_args != Arguments) {
+                                               if (candidates_expanded == null)
+                                                       candidates_expanded = new Dictionary<MethodSpec, Arguments> (2);
+
+                                               candidates_expanded.Add (m, candidate_args);
+                                               candidate_args = Arguments;
+                                       }
 
-                               msg_recorder = null;
-                               candidates.Add (Methods [i]);
+                                       if (candidate_rate != 0 || has_inaccessible_candidates_only) {
+                                               if (msg_recorder != null)
+                                                       msg_recorder.EndSession ();
+                                               continue;
+                                       }
 
-                               if (applicable_type == null)
-                                       applicable_type = decl_type;
-                               else if (applicable_type != decl_type) {
-                                       is_sorted = false;
-                                       if (IsAncestralType (applicable_type, decl_type))
-                                               applicable_type = decl_type;
+                                       msg_recorder = null;
+                                       candidates.Add (m);
                                }
-                       }
+                       } while (candidates.Count == 0 && GetBaseTypeMethods (ec));
 
                        ec.Report.SetPrinter (prev_recorder);
                        if (msg_recorder != null && !msg_recorder.IsEmpty) {
@@ -4305,16 +3848,17 @@ namespace Mono.CSharp {
 
                                return null;
                        }
-                       
-                       int candidate_top = candidates.Count;
 
-                       if (applicable_type == null) {
+                       int candidate_top = candidates.Count;
+                       if (candidate_top == 0) {
                                //
                                // When we found a top level method which does not match and it's 
                                // not an extension method. We start extension methods lookup from here
                                //
                                if (InstanceExpression != null) {
-                                       ExtensionMethodGroupExpr ex_method_lookup = ec.LookupExtensionMethod (type, Name, loc);
+                                       var first = Methods.First ();
+                                       var arity = type_arguments == null ? -1 : type_arguments.Count;
+                                       ExtensionMethodGroupExpr ex_method_lookup = ec.LookupExtensionMethod (type, first.Name, arity, loc);
                                        if (ex_method_lookup != null) {
                                                ex_method_lookup.ExtensionExpression = InstanceExpression;
                                                ex_method_lookup.SetTypeArguments (ec, type_arguments);
@@ -4333,18 +3877,19 @@ namespace Mono.CSharp {
                                        if (CustomErrorHandler != null && !has_inaccessible_candidates_only && CustomErrorHandler.NoExactMatch (ec, best_candidate))
                                                return null;
 
-                                       if (NoExactMatch (ec, ref Arguments, candidate_to_form))
+                                       bool params_expanded = params_candidates != null && params_candidates.Contains (best_candidate);
+                                       if (NoExactMatch (ec, ref Arguments, params_expanded))
                                                return null;
                                }
 
                                //
                                // We failed to find any method with correct argument count
                                //
-                               if (Name == ConstructorInfo.ConstructorName) {
+                               if (Methods.First ().Kind == MemberKind.Constructor) {
                                        ec.Report.SymbolRelatedToPreviousError (queried_type);
                                        ec.Report.Error (1729, loc,
                                                "The type `{0}' does not contain a constructor that takes `{1}' arguments",
-                                               TypeManager.CSharpName (queried_type), arg_count);
+                                               TypeManager.CSharpName (queried_type), arg_count.ToString ());
                                } else {
                                        Error_ArgumentCountWrong (ec, arg_count);
                                }
@@ -4357,80 +3902,24 @@ namespace Mono.CSharp {
                                return this;
                        }
 
-                       if (!is_sorted) {
-                               //
-                               // At this point, applicable_type is _one_ of the most derived types
-                               // in the set of types containing the methods in this MethodGroup.
-                               // Filter the candidates so that they only contain methods from the
-                               // most derived types.
-                               //
-
-                               int finalized = 0; // Number of finalized candidates
-
-                               do {
-                                       // Invariant: applicable_type is a most derived type
-                                       
-                                       // We'll try to complete Section 14.5.5.1 for 'applicable_type' by 
-                                       // eliminating all it's base types.  At the same time, we'll also move
-                                       // every unrelated type to the end of the array, and pick the next
-                                       // 'applicable_type'.
-
-                                       Type next_applicable_type = null;
-                                       int j = finalized; // where to put the next finalized candidate
-                                       int k = finalized; // where to put the next undiscarded candidate
-                                       for (int i = finalized; i < candidate_top; ++i) {
-                                               var candidate = candidates [i];
-                                               Type decl_type = candidate.DeclaringType;
-
-                                               if (decl_type == applicable_type) {
-                                                       candidates [k++] = candidates [j];
-                                                       candidates [j++] = candidates [i];
-                                                       continue;
-                                               }
-
-                                               if (IsAncestralType (decl_type, applicable_type))
-                                                       continue;
-
-                                               if (next_applicable_type != null &&
-                                                       IsAncestralType (decl_type, next_applicable_type))
-                                                       continue;
-
-                                               candidates [k++] = candidates [i];
-
-                                               if (next_applicable_type == null ||
-                                                       IsAncestralType (next_applicable_type, decl_type))
-                                                       next_applicable_type = decl_type;
-                                       }
-
-                                       applicable_type = next_applicable_type;
-                                       finalized = j;
-                                       candidate_top = k;
-                               } while (applicable_type != null);
-                       }
-
                        //
                        // Now we actually find the best method
                        //
-
                        best_candidate = candidates [0];
-                       method_params = candidate_to_form != null && candidate_to_form.ContainsKey (best_candidate);
-
-                       //
-                       // TODO: Broken inverse order of candidates logic does not work with optional
-                       // parameters used for method overrides and I am not going to fix it for SRE
-                       //
-                       if (candidates_expanded != null && candidates_expanded.ContainsKey (best_candidate)) {
-                               candidate_args = candidates_expanded [best_candidate];
-                               arg_count = candidate_args.Count;
-                       }
+                       bool method_params = params_candidates != null && params_candidates.Contains (best_candidate);
 
                        for (int ix = 1; ix < candidate_top; ix++) {
                                var candidate = candidates [ix];
 
-                               if (candidate.MetaInfo == best_candidate.MetaInfo)
+                               if (candidate == best_candidate)
                                        continue;
 
-                               bool cand_params = candidate_to_form != null && candidate_to_form.ContainsKey (candidate);
+                               bool cand_params = params_candidates != null && params_candidates.Contains (candidate);
+
+                               if (candidates_expanded != null && candidates_expanded.ContainsKey (candidate)) {
+                                       candidate_args = candidates_expanded[candidate];
+                                       arg_count = candidate_args.Count;
+                               }
 
                                if (BetterFunction (ec, candidate_args, arg_count, 
                                        candidate, cand_params,
@@ -4438,7 +3927,18 @@ namespace Mono.CSharp {
                                        best_candidate = candidate;
                                        method_params = cand_params;
                                }
+
+                               if (candidate_args != Arguments) {
+                                       candidate_args = Arguments;
+                                       arg_count = candidate_args != null ? candidate_args.Count : 0;
+                               }
                        }
+
+                       if (candidates_expanded != null && candidates_expanded.ContainsKey (best_candidate)) {
+                               candidate_args = candidates_expanded[best_candidate];
+                               arg_count = candidate_args.Count;
+                       }
+
                        //
                        // Now check that there are no ambiguities i.e the selected method
                        // should be better than all the others
@@ -4447,16 +3947,16 @@ namespace Mono.CSharp {
                        for (int ix = 1; ix < candidate_top; ix++) {
                                var candidate = candidates [ix];
 
-                               if (candidate.MetaInfo == best_candidate.MetaInfo)
+                               if (candidate == best_candidate)
                                        continue;
 
-                               bool cand_params = candidate_to_form != null && candidate_to_form.ContainsKey (candidate);
+                               bool cand_params = params_candidates != null && params_candidates.Contains (candidate);
                                if (!BetterFunction (ec, candidate_args, arg_count,
                                        best_candidate, method_params,
                                        candidate, cand_params)) 
                                {
                                        if (!may_fail)
-                                               ec.Report.SymbolRelatedToPreviousError (candidate.MetaInfo);
+                                               ec.Report.SymbolRelatedToPreviousError (candidate);
                                        ambiguous = candidate;
                                }
                        }
@@ -4466,44 +3966,6 @@ namespace Mono.CSharp {
                                return this;
                        }
 
-                       //
-                       // If the method is a virtual function, pick an override closer to the LHS type.
-                       //
-                       if (!IsBase && best_candidate.IsVirtual) {
-                               if (TypeManager.IsOverride (best_candidate))
-                                       throw new InternalErrorException (
-                                               "Should not happen.  An 'override' method took part in overload resolution: " + best_candidate);
-
-                               if (candidate_overrides != null) {
-                                       Type[] gen_args = null;
-                                       bool gen_override = false;
-                                       if (best_candidate.IsGenericMethod)
-                                               gen_args = TypeManager.GetGenericArguments (best_candidate.MetaInfo);
-
-                                       foreach (var candidate in candidate_overrides) {
-                                               if (candidate.IsGenericMethod) {
-                                                       if (gen_args == null)
-                                                               continue;
-
-                                                       if (gen_args.Length != TypeManager.GetGenericArguments (candidate.MetaInfo).Length)
-                                                               continue;
-                                               } else {
-                                                       if (gen_args != null)
-                                                               continue;
-                                               }
-                                               
-                                               if (IsOverride (candidate.MetaInfo, best_candidate.MetaInfo)) {
-                                                       gen_override = true;
-                                                       best_candidate = candidate;
-                                               }
-                                       }
-
-                                       if (gen_override && gen_args != null) {
-                                               best_candidate = best_candidate.Inflate (gen_args);
-                                       }
-                               }
-                       }
-
                        //
                        // And now check if the arguments are all
                        // compatible, perform conversions if
@@ -4517,54 +3979,43 @@ namespace Mono.CSharp {
                        if (best_candidate == null)
                                return null;
 
-                       MethodBase the_method = TypeManager.DropGenericMethodArguments (best_candidate);
-                       if (TypeManager.IsGenericMethodDefinition (the_method) &&
-                           !ConstraintChecker.CheckConstraints (ec, the_method, best_candidate.MetaInfo, loc))
-                               return null;
+                       if (best_candidate.IsGeneric) {
+                               ConstraintChecker.CheckAll (best_candidate.GetGenericMethodDefinition (), best_candidate.TypeArguments,
+                                       best_candidate.Constraints, loc, ec.Report);
+                       }
 
                        //
                        // Check ObsoleteAttribute on the best method
                        //
-                       ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (the_method);
+                       ObsoleteAttribute oa = best_candidate.GetAttributeObsolete ();
                        if (oa != null && !ec.IsObsolete)
                                AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
 
-                       IMethodData data = TypeManager.GetMethod (the_method);
-                       if (data != null)
-                               data.SetIsUsed ();
+                       best_candidate.MemberDefinition.SetIsUsed ();
 
                        Arguments = candidate_args;
                        return this;
                }
 
-               bool NoExactMatch (ResolveContext ec, ref Arguments Arguments, IDictionary<MethodSpec, MethodSpec> candidate_to_form)
+               bool NoExactMatch (ResolveContext ec, ref Arguments Arguments, bool params_expanded)
                {
                        AParametersCollection pd = best_candidate.Parameters;
                        int arg_count = Arguments == null ? 0 : Arguments.Count;
 
                        if (arg_count == pd.Count || pd.HasParams) {
-                               if (TypeManager.IsGenericMethodDefinition (best_candidate.MetaInfo)) {
+                               if (best_candidate.IsGeneric) {
                                        if (type_arguments == null) {
                                                ec.Report.Error (411, loc,
-                                                       "The type arguments for method `{0}' cannot be inferred from " +
-                                                       "the usage. Try specifying the type arguments explicitly",
-                                                       TypeManager.CSharpSignature (best_candidate.MetaInfo));
+                                                       "The type arguments for method `{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly",
+                                                       best_candidate.GetGenericMethodDefinition().GetSignatureForError ());
                                                return true;
                                        }
+                               }
 
-                                       Type[] g_args = TypeManager.GetGenericArguments (best_candidate.MetaInfo);
-                                       if (type_arguments.Count != g_args.Length) {
-                                               ec.Report.SymbolRelatedToPreviousError (best_candidate.MetaInfo);
-                                               ec.Report.Error (305, loc, "Using the generic method `{0}' requires `{1}' type argument(s)",
-                                                       TypeManager.CSharpSignature (best_candidate.MetaInfo),
-                                                       g_args.Length.ToString ());
-                                               return true;
-                                       }
-                               } else {
-                                       if (type_arguments != null && !best_candidate.IsGenericMethod) {
-                                               Error_TypeArgumentsCannotBeUsed (ec.Report, loc);
-                                               return true;
-                                       }
+                               var ta = type_arguments == null ? 0 : type_arguments.Count;
+                               if (ta != best_candidate.Arity) {
+                                       Error_TypeArgumentsCannotBeUsed (ec.Report, loc, best_candidate, type_arguments.Count);
+                                       return true;
                                }
 
                                if (has_inaccessible_candidates_only) {
@@ -4574,15 +4025,14 @@ namespace Mono.CSharp {
                                                // base class (CS1540).  If the qualifier_type is a base of the
                                                // ec.CurrentType and the lookup succeeds with the latter one,
                                                // then we are in this situation.
-                                               Error_CannotAccessProtected (ec, loc, best_candidate.MetaInfo, queried_type, ec.CurrentType);
+                                               Error_CannotAccessProtected (ec, loc, best_candidate, queried_type, ec.CurrentType);
                                        } else {
-                                               ec.Report.SymbolRelatedToPreviousError (best_candidate.MetaInfo);
+                                               ec.Report.SymbolRelatedToPreviousError (best_candidate);
                                                ErrorIsInaccesible (loc, GetSignatureForError (), ec.Report);
                                        }
                                }
 
-                               bool cand_params = candidate_to_form != null && candidate_to_form.ContainsKey (best_candidate);
-                               if (!VerifyArgumentsCompat (ec, ref Arguments, arg_count, best_candidate, cand_params, false, loc))
+                               if (!VerifyArgumentsCompat (ec, ref Arguments, arg_count, best_candidate, params_expanded, false, loc))
                                        return true;
 
                                if (has_inaccessible_candidates_only)
@@ -4607,7 +4057,7 @@ namespace Mono.CSharp {
 
                        int errors = ec.Report.Errors;
                        Parameter.Modifier p_mod = 0;
-                       Type pt = null;
+                       TypeSpec pt = null;
                        int a_idx = 0, a_pos = 0;
                        Argument a = null;
                        ArrayInitializer params_initializers = null;
@@ -4650,16 +4100,16 @@ namespace Mono.CSharp {
                                                                        "The delegate `{0}' does not contain a parameter named `{1}'",
                                                                        TypeManager.CSharpName (DeclaringType), na.Name);
                                                        } else {
-                                                               ec.Report.SymbolRelatedToPreviousError (best_candidate.MetaInfo);
+                                                               ec.Report.SymbolRelatedToPreviousError (best_candidate);
                                                                ec.Report.Error (1739, na.Location,
                                                                        "The best overloaded method match for `{0}' does not contain a parameter named `{1}'",
-                                                                       TypeManager.CSharpSignature (method.MetaInfo), na.Name);
+                                                                       TypeManager.CSharpSignature (method), na.Name);
                                                        }
                                                } else if (arguments[name_index] != a) {
                                                        if (DeclaringType != null && TypeManager.IsDelegateType (DeclaringType))
                                                                ec.Report.SymbolRelatedToPreviousError (DeclaringType);
                                                        else
-                                                               ec.Report.SymbolRelatedToPreviousError (best_candidate.MetaInfo);
+                                                               ec.Report.SymbolRelatedToPreviousError (best_candidate);
 
                                                        ec.Report.Error (1744, na.Location,
                                                                "Named argument `{0}' cannot be used for a parameter which has positional argument specified",
@@ -4668,7 +4118,7 @@ namespace Mono.CSharp {
                                        }
                                }
 
-                               if (TypeManager.IsDynamicType (a.Expr.Type))
+                               if (a.Expr.Type == InternalType.Dynamic)
                                        continue;
 
                                if (delegate_type != null && !Delegate.IsTypeCovariant (a.Expr, pt))
@@ -4764,7 +4214,7 @@ namespace Mono.CSharp {
                        get { return true; }
                }
 
-               public override Type DeclaringType {
+               public override TypeSpec DeclaringType {
                        get { return constant.DeclaringType; }
                }
 
@@ -4778,16 +4228,16 @@ namespace Mono.CSharp {
                        constant.MemberDefinition.SetIsUsed ();
 
                        if (!rc.IsObsolete) {
-                               var oa = constant.GetObsoleteAttribute ();
+                               var oa = constant.GetAttributeObsolete ();
                                if (oa != null)
-                                       AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (constant.MetaInfo), loc, rc.Report);
+                                       AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (constant), loc, rc.Report);
                        }
 
                        // Constants are resolved on-demand
                        var c = constant.Value.Resolve (rc) as Constant;
 
                        // Creates reference expression to the constant value
-                       return Constant.CreateConstant (rc, c.Type, c.GetValue (), loc);
+                       return Constant.CreateConstant (rc, constant.MemberType, c.GetValue (), loc);
                }
 
                public override void Emit (EmitContext ec)
@@ -4797,7 +4247,7 @@ namespace Mono.CSharp {
 
                public override string GetSignatureForError ()
                {
-                       return TypeManager.GetFullNameSignature (constant.MetaInfo);
+                       return TypeManager.GetFullNameSignature (constant);
                }
        }
 
@@ -4806,7 +4256,6 @@ namespace Mono.CSharp {
        /// </summary>
        public class FieldExpr : MemberExpr, IDynamicAssign, IMemoryLocation, IVariableReference {
                protected FieldSpec spec;
-               readonly Type constructed_generic_type;
                VariableInfo variable_info;
                
                LocalTemporary temp;
@@ -4822,7 +4271,7 @@ namespace Mono.CSharp {
                        this.spec = spec;
                        this.loc = loc;
 
-                       type = TypeManager.TypeToCoreType (spec.FieldType);
+                       type = spec.MemberType;
                }
                
                public FieldExpr (FieldBase fi, Location l)
@@ -4831,14 +4280,6 @@ namespace Mono.CSharp {
                        loc = l;
                }
 
-               public FieldExpr (Field fi, Type genericType, Location l)
-                       : this (fi, l)
-               {
-                       if (TypeManager.IsGenericTypeDefinition (genericType))
-                               return;
-                       this.constructed_generic_type = genericType;
-               }
-
                public override string Name {
                        get {
                                return spec.Name;
@@ -4863,15 +4304,15 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override Type DeclaringType {
+               public override TypeSpec DeclaringType {
                        get {
-                               return spec.MetaInfo.DeclaringType;
+                               return spec.DeclaringType;
                        }
                }
 
                public override string GetSignatureForError ()
                {
-                       return TypeManager.GetFullNameSignature (spec.MetaInfo);
+                       return TypeManager.GetFullNameSignature (spec);
                }
 
                public VariableInfo VariableInfo {
@@ -4883,10 +4324,7 @@ namespace Mono.CSharp {
                public override MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, Location loc,
                                                                SimpleName original)
                {
-                       FieldInfo fi = TypeManager.GetGenericFieldDefinition (spec.MetaInfo);
-                       Type t = fi.FieldType;
-
-                       if (t.IsPointer && !ec.IsUnsafe) {
+                       if (spec.MemberType.IsPointer && !ec.IsUnsafe) {
                                UnsafeError (ec, loc);
                        }
 
@@ -4918,7 +4356,7 @@ namespace Mono.CSharp {
 
                public Expression CreateTypeOfExpression ()
                {
-                       return new TypeOfField (Import.CreateField (GetConstructedFieldInfo ()), loc);
+                       return new TypeOfField (spec, loc);
                }
 
                protected override Expression DoResolve (ResolveContext ec)
@@ -4967,14 +4405,9 @@ namespace Mono.CSharp {
                        }
 
                        if (!ec.IsObsolete) {
-                               FieldBase f = TypeManager.GetField (spec.MetaInfo);
-                               if (f != null) {
-                                       f.CheckObsoleteness (loc);
-                               } else {
-                                       ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (spec.MetaInfo);
-                                       if (oa != null)
-                                               AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (spec.MetaInfo), loc, ec.Report);
-                               }
+                               ObsoleteAttribute oa = spec.GetAttributeObsolete ();
+                               if (oa != null)
+                                       AttributeTester.Report_ObsoleteMessage (oa, TypeManager.GetFullNameSignature (spec), loc, ec.Report);
                        }
 
                        var fb = spec as FixedFieldSpec;
@@ -4987,9 +4420,9 @@ namespace Mono.CSharp {
                                }
 
                                if (InstanceExpression.eclass != ExprClass.Variable) {
-                                       ec.Report.SymbolRelatedToPreviousError (spec.MetaInfo);
+                                       ec.Report.SymbolRelatedToPreviousError (spec);
                                        ec.Report.Error (1708, loc, "`{0}': Fixed size buffers can only be accessed through locals or fields",
-                                               TypeManager.GetFullNameSignature (spec.MetaInfo));
+                                               TypeManager.GetFullNameSignature (spec));
                                } else if (var != null && var.IsHoisted) {
                                        AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, var, loc);
                                }
@@ -5054,7 +4487,7 @@ namespace Mono.CSharp {
                        if (var != null && var.VariableInfo != null)
                                var.VariableInfo.SetFieldAssigned (ec, Name);
 
-                       bool lvalue_instance = !spec.IsStatic && TypeManager.IsValueType (spec.MetaInfo.DeclaringType);
+                       bool lvalue_instance = !spec.IsStatic && TypeManager.IsValueType (spec.DeclaringType);
                        bool out_access = right_side == EmptyExpression.OutAccess.Instance || right_side == EmptyExpression.LValueMemberOutAccess;
 
                        Expression e = DoResolve (ec, lvalue_instance, out_access);
@@ -5062,16 +4495,13 @@ namespace Mono.CSharp {
                        if (e == null)
                                return null;
 
-                       FieldBase fb = TypeManager.GetField (spec.MetaInfo);
-                       if (fb != null) {
-                               fb.SetAssigned ();
+                       spec.MemberDefinition.SetIsAssigned ();
 
-                               if ((right_side == EmptyExpression.UnaryAddress || right_side == EmptyExpression.OutAccess.Instance) &&
-                                       (fb.ModFlags & Modifiers.VOLATILE) != 0) {
-                                       ec.Report.Warning (420, 1, loc,
-                                               "`{0}': A volatile field references will not be treated as volatile",
-                                               fb.GetSignatureForError ());
-                               }
+                       if ((right_side == EmptyExpression.UnaryAddress || right_side == EmptyExpression.OutAccess.Instance) &&
+                                       (spec.Modifiers & Modifiers.VOLATILE) != 0) {
+                               ec.Report.Warning (420, 1, loc,
+                                       "`{0}': A volatile field references will not be treated as volatile",
+                                       spec.GetSignatureForError ());
                        }
 
                        if (spec.IsReadOnly) {
@@ -5080,10 +4510,9 @@ namespace Mono.CSharp {
                                        return Report_AssignToReadonly (ec, right_side);
 
                                if (ec.HasSet (ResolveContext.Options.ConstructorScope)) {
-                                       Type ctype = ec.CurrentType;
 
                                        // InitOnly fields cannot be assigned-to in a different constructor from their declaring type
-                                       if (!TypeManager.IsEqual (ctype, DeclaringType))
+                                       if (!TypeManager.IsEqual (ec.CurrentMemberDefinition.Parent.Definition, DeclaringType.GetDefinition ()))
                                                return Report_AssignToReadonly (ec, right_side);
                                        // static InitOnly fields cannot be assigned-to in an instance constructor
                                        if (IsStatic && !ec.IsStatic)
@@ -5132,7 +4561,7 @@ namespace Mono.CSharp {
                                //
                                IVariableReference variable = InstanceExpression as IVariableReference;
                                if (variable != null)
-                                       return TypeManager.IsStruct (InstanceExpression.Type) && variable.IsFixed;
+                                       return InstanceExpression.Type.IsStruct && variable.IsFixed;
 
                                IFixedExpression fe = InstanceExpression as IFixedExpression;
                                return fe != null && fe.IsFixed;
@@ -5152,7 +4581,7 @@ namespace Mono.CSharp {
                        if (fe == null)
                                return false;
 
-                       if (spec.MetaInfo != fe.spec.MetaInfo)
+                       if (spec != fe.spec)
                                return false;
 
                        if (InstanceExpression == null || fe.InstanceExpression == null)
@@ -5163,45 +4592,41 @@ namespace Mono.CSharp {
                
                public void Emit (EmitContext ec, bool leave_copy)
                {
-                       ILGenerator ig = ec.ig;
                        bool is_volatile = false;
 
-                       var f = TypeManager.GetField (spec.MetaInfo);
-                       if (f != null){
-                               if ((f.ModFlags & Modifiers.VOLATILE) != 0)
-                                       is_volatile = true;
+                       if ((spec.Modifiers & Modifiers.VOLATILE) != 0)
+                               is_volatile = true;
 
-                               f.SetIsUsed ();
-                       }
+                       spec.MemberDefinition.SetIsUsed ();
                        
                        if (IsStatic){
                                if (is_volatile)
-                                       ig.Emit (OpCodes.Volatile);
+                                       ec.Emit (OpCodes.Volatile);
 
-                               ig.Emit (OpCodes.Ldsfld, GetConstructedFieldInfo ());
+                               ec.Emit (OpCodes.Ldsfld, spec);
                        } else {
                                if (!prepared)
                                        EmitInstance (ec, false);
 
                                // Optimization for build-in types
                                if (TypeManager.IsStruct (type) && TypeManager.IsEqual (type, ec.MemberContext.CurrentType) && TypeManager.IsEqual (InstanceExpression.Type, type)) {
-                                       LoadFromPtr (ig, type);
+                                       ec.EmitLoadFromPtr (type);
                                } else {
                                        var ff = spec as FixedFieldSpec;
                                        if (ff != null) {
-                                               ig.Emit (OpCodes.Ldflda, GetConstructedFieldInfo ());
-                                               ig.Emit (OpCodes.Ldflda, ff.Element);
+                                               ec.Emit (OpCodes.Ldflda, spec);
+                                               ec.Emit (OpCodes.Ldflda, ff.Element);
                                        } else {
                                                if (is_volatile)
-                                                       ig.Emit (OpCodes.Volatile);
+                                                       ec.Emit (OpCodes.Volatile);
 
-                                               ig.Emit (OpCodes.Ldfld, GetConstructedFieldInfo ());
+                                               ec.Emit (OpCodes.Ldfld, spec);
                                        }
                                }
                        }
 
                        if (leave_copy) {
-                               ec.ig.Emit (OpCodes.Dup);
+                               ec.Emit (OpCodes.Dup);
                                if (!IsStatic) {
                                        temp = new LocalTemporary (this.Type);
                                        temp.Store (ec);
@@ -5211,34 +4636,27 @@ namespace Mono.CSharp {
 
                public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
                {
-                       //FieldAttributes fa = FieldInfo.Attributes;
-                       //bool is_static = (fa & FieldAttributes.Static) != 0;
-                       ILGenerator ig = ec.ig;
-
                        prepared = prepare_for_load;
                        EmitInstance (ec, prepared);
 
                        source.Emit (ec);
                        if (leave_copy) {
-                               ec.ig.Emit (OpCodes.Dup);
+                               ec.Emit (OpCodes.Dup);
                                if (!IsStatic) {
                                        temp = new LocalTemporary (this.Type);
                                        temp.Store (ec);
                                }
                        }
 
-                       FieldBase f = TypeManager.GetField (spec.MetaInfo);
-                       if (f != null){
-                               if ((f.ModFlags & Modifiers.VOLATILE) != 0)
-                                       ig.Emit (OpCodes.Volatile);
+                       if ((spec.Modifiers & Modifiers.VOLATILE) != 0)
+                               ec.Emit (OpCodes.Volatile);
                                        
-                               f.SetAssigned ();
-                       }
+                       spec.MemberDefinition.SetIsAssigned ();
 
                        if (IsStatic)
-                               ig.Emit (OpCodes.Stsfld, GetConstructedFieldInfo ());
+                               ec.Emit (OpCodes.Stsfld, spec);
                        else
-                               ig.Emit (OpCodes.Stfld, GetConstructedFieldInfo ());
+                               ec.Emit (OpCodes.Stfld, spec);
                        
                        if (temp != null) {
                                temp.Emit (ec);
@@ -5254,8 +4672,7 @@ namespace Mono.CSharp {
 
                public override void EmitSideEffect (EmitContext ec)
                {
-                       FieldBase f = TypeManager.GetField (spec.MetaInfo);
-                       bool is_volatile = f != null && (f.ModFlags & Modifiers.VOLATILE) != 0;
+                       bool is_volatile = (spec.Modifiers & Modifiers.VOLATILE) != 0;
 
                        if (is_volatile || is_marshal_by_ref ())
                                base.EmitSideEffect (ec);
@@ -5270,15 +4687,10 @@ namespace Mono.CSharp {
 
                public void AddressOf (EmitContext ec, AddressOp mode)
                {
-                       ILGenerator ig = ec.ig;
-
-                       FieldBase f = TypeManager.GetField (spec.MetaInfo);
-                       if (f != null){                         
-                               if ((mode & AddressOp.Store) != 0)
-                                       f.SetAssigned ();
-                               if ((mode & AddressOp.Load) != 0)
-                                       f.SetIsUsed ();
-                       }
+                       if ((mode & AddressOp.Store) != 0)
+                               spec.MemberDefinition.SetIsAssigned ();
+                       if ((mode & AddressOp.Load) != 0)
+                               spec.MemberDefinition.SetIsUsed ();
 
                        //
                        // Handle initonly fields specially: make a copy and then
@@ -5300,30 +4712,22 @@ namespace Mono.CSharp {
                        if (need_copy){
                                LocalBuilder local;
                                Emit (ec);
-                               local = ig.DeclareLocal (type);
-                               ig.Emit (OpCodes.Stloc, local);
-                               ig.Emit (OpCodes.Ldloca, local);
+                               local = ec.DeclareLocal (type, false);
+                               ec.Emit (OpCodes.Stloc, local);
+                               ec.Emit (OpCodes.Ldloca, local);
                                return;
                        }
 
 
                        if (IsStatic){
-                               ig.Emit (OpCodes.Ldsflda, GetConstructedFieldInfo ());
+                               ec.Emit (OpCodes.Ldsflda, spec);
                        } else {
                                if (!prepared)
                                        EmitInstance (ec, false);
-                               ig.Emit (OpCodes.Ldflda, GetConstructedFieldInfo ());
+                               ec.Emit (OpCodes.Ldflda, spec);
                        }
                }
 
-               FieldInfo GetConstructedFieldInfo ()
-               {
-                       if (constructed_generic_type == null)
-                               return spec.MetaInfo;
-
-                       return TypeBuilder.GetField (constructed_generic_type, spec.MetaInfo);
-               }
-
                public SLE.Expression MakeAssignExpression (BuilderContext ctx)
                {
                        return MakeExpression (ctx);
@@ -5331,14 +4735,8 @@ namespace Mono.CSharp {
 
                public override SLE.Expression MakeExpression (BuilderContext ctx)
                {
-                       return SLE.Expression.Field (InstanceExpression.MakeExpression (ctx), spec.MetaInfo);
+                       return SLE.Expression.Field (InstanceExpression.MakeExpression (ctx), spec.GetMetaInfo ());
                }
-               
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       storey.MutateField (spec);
-                       base.MutateHoistedGenericType (storey);
-               }               
        }
 
        
@@ -5352,24 +4750,21 @@ namespace Mono.CSharp {
        public class PropertyExpr : MemberExpr, IDynamicAssign
        {
                PropertySpec spec;
-               MethodSpec getter, setter;
-               bool is_static;
-
                TypeArguments targs;
                
                LocalTemporary temp;
                bool prepared;
 
-               public PropertyExpr (Type container_type, PropertySpec spec, Location l)
+               public PropertyExpr (TypeSpec container_type, PropertySpec spec, Location l)
                {
                        this.spec = spec;
                        loc = l;
 
-                       type = TypeManager.TypeToCoreType (spec.PropertyType);
-
-                       ResolveAccessors (container_type);
+                       type = spec.MemberType;
                }
 
+               #region Properties
+
                public override string Name {
                        get {
                                return spec.Name;
@@ -5378,16 +4773,18 @@ namespace Mono.CSharp {
 
                public override bool IsInstance {
                        get {
-                               return !is_static;
+                               return !IsStatic;
                        }
                }
 
                public override bool IsStatic {
                        get {
-                               return is_static;
+                               return spec.IsStatic;
                        }
                }
 
+               #endregion
+
                public override Expression CreateExpressionTree (ResolveContext ec)
                {
                        Arguments args;
@@ -5407,16 +4804,16 @@ namespace Mono.CSharp {
                                args.Add (new Argument (new NullLiteral (loc)));
                        else
                                args.Add (new Argument (InstanceExpression.CreateExpressionTree (ec)));
-                       args.Add (new Argument (new TypeOfMethod (getter, loc)));
+                       args.Add (new Argument (new TypeOfMethod (spec.Get, loc)));
                        return CreateExpressionFactoryCall (ec, "Property", args);
                }
 
                public Expression CreateSetterTypeOfExpression ()
                {
-                       return new TypeOfMethod (setter, loc);
+                       return new TypeOfMethod (spec.Set, loc);
                }
 
-               public override Type DeclaringType {
+               public override TypeSpec DeclaringType {
                        get {
                                return spec.DeclaringType;
                        }
@@ -5424,108 +4821,28 @@ namespace Mono.CSharp {
 
                public override string GetSignatureForError ()
                {
-                       return TypeManager.GetFullNameSignature (spec.MetaInfo);
-               }
-
-               void FindAccessors (Type invocation_type)
-               {
-                       const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
-                               BindingFlags.Static | BindingFlags.Instance |
-                               BindingFlags.DeclaredOnly;
-
-                       Type current = spec.DeclaringType;
-                       for (; current != null; current = current.BaseType) {
-                               MemberInfo[] group = TypeManager.MemberLookup (
-                                       invocation_type, invocation_type, current,
-                                       MemberTypes.Property, flags, spec.Name, null);
-
-                               if (group == null)
-                                       continue;
-
-                               if (group.Length != 1)
-                                       // Oooops, can this ever happen ?
-                                       return;
-
-                               PropertyInfo pi = (PropertyInfo) group [0];
-
-                               if (getter == null) {
-                                       var m = pi.GetGetMethod (true);
-                                       if (m != null)
-                                               getter = Import.CreateMethod (m);
-                               }
-
-                               if (setter == null) {
-                                       var m = pi.GetSetMethod (true);
-                                       if (m != null)
-                                               setter = Import.CreateMethod (m);
-                               }
-
-                               var accessor = getter != null ? getter : setter;
-
-                               if (!accessor.IsVirtual)
-                                       return;
-                       }
-               }
-
-               //
-               // We also perform the permission checking here, as the PropertyInfo does not
-               // hold the information for the accessibility of its setter/getter
-               //
-               // TODO: Refactor to use some kind of cache together with GetPropertyFromAccessor
-               void ResolveAccessors (Type container_type)
-               {
-                       FindAccessors (container_type);
-
-                       if (getter != null) {
-                               MethodBase the_getter = TypeManager.DropGenericMethodArguments (getter);
-                               IMethodData md = TypeManager.GetMethod (the_getter);
-                               if (md != null)
-                                       md.SetIsUsed ();
-
-                               is_static = getter.IsStatic;
-                       }
-
-                       if (setter != null) {
-                               MethodBase the_setter = TypeManager.DropGenericMethodArguments (setter);
-                               IMethodData md = TypeManager.GetMethod (the_setter);
-                               if (md != null)
-                                       md.SetIsUsed ();
-
-                               is_static = setter.IsStatic;
-                       }
+                       return TypeManager.GetFullNameSignature (spec);
                }
 
                public SLE.Expression MakeAssignExpression (BuilderContext ctx)
                {
-                       return SLE.Expression.Property (InstanceExpression.MakeExpression (ctx), (MethodInfo) setter.MetaInfo);
+                       return SLE.Expression.Property (InstanceExpression.MakeExpression (ctx), (MethodInfo) spec.Set.GetMetaInfo ());
                }
 
                public override SLE.Expression MakeExpression (BuilderContext ctx)
                {
-                       return SLE.Expression.Property (InstanceExpression.MakeExpression (ctx), (MethodInfo) getter.MetaInfo);
-               }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       if (InstanceExpression != null)
-                               InstanceExpression.MutateHoistedGenericType (storey);
-
-                       type = storey.MutateType (type);
-                       if (getter != null)
-                               storey.MutateGenericMethod (getter);
-                       if (setter != null)
-                               storey.MutateGenericMethod (setter);
+                       return SLE.Expression.Property (InstanceExpression.MakeExpression (ctx), (MethodInfo) spec.Get.GetMetaInfo ());
                }
 
-               public PropertyInfo PropertyInfo {
+               public PropertySpec PropertyInfo {
                        get {
-                               return spec.MetaInfo;
+                               return spec;
                        }
                }
 
                bool InstanceResolve (ResolveContext ec, bool lvalue_instance, bool must_do_cs1540_check)
                {
-                       if (is_static) {
+                       if (IsStatic) {
                                InstanceExpression = null;
                                return true;
                        }
@@ -5548,51 +4865,37 @@ namespace Mono.CSharp {
                            !TypeManager.IsInstantiationOfSameGenericType (InstanceExpression.Type, ec.CurrentType) &&
                            !TypeManager.IsNestedChildOf (ec.CurrentType, InstanceExpression.Type) &&
                            !TypeManager.IsSubclassOf (InstanceExpression.Type, ec.CurrentType)) {
-                               ec.Report.SymbolRelatedToPreviousError (spec.MetaInfo);
-                               Error_CannotAccessProtected (ec, loc, spec.MetaInfo, InstanceExpression.Type, ec.CurrentType);
+                               ec.Report.SymbolRelatedToPreviousError (spec);
+                               Error_CannotAccessProtected (ec, loc, spec, InstanceExpression.Type, ec.CurrentType);
                                return false;
                        }
 
                        return true;
                }
 
-               void Error_PropertyNotFound (ResolveContext ec, MethodSpec mi, bool getter)
+               void Error_PropertyNotValid (ResolveContext ec)
                {
-                       // TODO: correctly we should compare arguments but it will lead to bigger changes
-                       if (mi.MetaInfo is MethodBuilder) {
-                               Error_TypeDoesNotContainDefinition (ec, loc, spec.DeclaringType, Name);
-                               return;
-                       }
-                       
-                       StringBuilder sig = new StringBuilder (TypeManager.CSharpName (mi.DeclaringType));
-                       sig.Append ('.');
-                       AParametersCollection iparams = mi.Parameters;
-                       sig.Append (getter ? "get_" : "set_");
-                       sig.Append (Name);
-                       sig.Append (iparams.GetSignatureForError ());
-
-                       ec.Report.SymbolRelatedToPreviousError (mi.MetaInfo);
-                       ec.Report.Error (1546, loc, "Property `{0}' is not supported by the C# language. Try to call the accessor method `{1}' directly",
-                               Name, sig.ToString ());
+                       ec.Report.SymbolRelatedToPreviousError (spec);
+                       ec.Report.Error (1546, loc, "Property or event `{0}' is not supported by the C# language",
+                               GetSignatureForError ());
                }
 
-               public bool IsAccessibleFrom (Type invocation_type, bool lvalue)
+               public bool IsAccessibleFrom (TypeSpec invocation_type, bool lvalue)
                {
                        bool dummy;
-                       var accessor = lvalue ? setter : getter;
+                       var accessor = lvalue ? spec.Set : spec.Get;
                        if (accessor == null && lvalue)
-                               accessor = getter;
-                       return accessor != null && IsAccessorAccessible (invocation_type, accessor, out dummy);
+                               accessor = spec.Get;
+                       return accessor != null && IsMemberAccessible (invocation_type, accessor, out dummy);
                }
 
                bool IsSingleDimensionalArrayLength ()
                {
-                       if (DeclaringType != TypeManager.array_type || getter == null || Name != "Length")
+                       if (DeclaringType != TypeManager.array_type || !spec.HasGet || Name != "Length")
                                return false;
 
-                       string t_name = InstanceExpression.Type.Name;
-                       int t_name_len = t_name.Length;
-                       return t_name_len > 2 && t_name [t_name_len - 2] == '[';
+                       ArrayContainer ac = InstanceExpression.Type as ArrayContainer;
+                       return ac != null && ac.Rank == 1;
                }
 
                protected override Expression DoResolve (ResolveContext ec)
@@ -5606,8 +4909,8 @@ namespace Mono.CSharp {
 
                        if (!res) {
                                if (InstanceExpression != null) {
-                                       Type expr_type = InstanceExpression.Type;
-                                       ExtensionMethodGroupExpr ex_method_lookup = ec.LookupExtensionMethod (expr_type, Name, loc);
+                                       TypeSpec expr_type = InstanceExpression.Type;
+                                       ExtensionMethodGroupExpr ex_method_lookup = ec.LookupExtensionMethod (expr_type, Name, 0, loc);
                                        if (ex_method_lookup != null) {
                                                ex_method_lookup.ExtensionExpression = InstanceExpression;
                                                ex_method_lookup.SetTypeArguments (ec, targs);
@@ -5625,23 +4928,18 @@ namespace Mono.CSharp {
                        //
                        // Only base will allow this invocation to happen.
                        //
-                       if (IsBase && getter.IsAbstract) {
-                               Error_CannotCallAbstractBase (ec, TypeManager.GetFullNameSignature (spec.MetaInfo));
+                       if (IsBase && spec.IsAbstract) {
+                               Error_CannotCallAbstractBase (ec, TypeManager.GetFullNameSignature (spec));
                        }
 
-                       if (spec.PropertyType.IsPointer && !ec.IsUnsafe){
+                       if (spec.MemberType.IsPointer && !ec.IsUnsafe){
                                UnsafeError (ec, loc);
                        }
 
                        if (!ec.IsObsolete) {
-                               PropertyBase pb = TypeManager.GetProperty (spec.MetaInfo);
-                               if (pb != null) {
-                                       pb.CheckObsoleteness (loc);
-                               } else {
-                                       ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (spec.MetaInfo);
-                                       if (oa != null)
-                                               AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
-                               }
+                               ObsoleteAttribute oa = spec.GetAttributeObsolete ();
+                               if (oa != null)
+                                       AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
                        }
 
                        return this;
@@ -5665,16 +4963,12 @@ namespace Mono.CSharp {
                                Error_CannotModifyIntermediateExpressionValue (ec);
                        }
 
-                       if (setter == null){
-                               //
-                               // The following condition happens if the PropertyExpr was
-                               // created, but is invalid (ie, the property is inaccessible),
-                               // and we did not want to embed the knowledge about this in
-                               // the caller routine.  This only avoids double error reporting.
-                               //
-                               if (getter == null)
-                                       return null;
+                       if (spec.IsNotRealProperty) {
+                               Error_PropertyNotValid (ec);
+                               return null;
+                       }
 
+                       if (!spec.HasSet){
                                if (ec.CurrentBlock.Toplevel.GetParameterReference (spec.Name, loc) is MemberAccess) {
                                        ec.Report.Error (1947, loc, "A range variable `{0}' cannot be assigned to. Consider using `let' clause to store the value",
                                                spec.Name);
@@ -5690,22 +4984,15 @@ namespace Mono.CSharp {
                                return null;
                        }
 
-                       if (setter.Parameters.Count != 1){
-                               Error_PropertyNotFound (ec, setter, false);
-                               return null;
-                       }
-
                        bool must_do_cs1540_check;
-                       if (!IsAccessorAccessible (ec.CurrentType, setter, out must_do_cs1540_check)) {
-                               PropertyBase.PropertyMethod pm = TypeManager.GetMethod (setter.MetaInfo) as PropertyBase.PropertyMethod;
-                               if (pm != null && pm.HasCustomAccessModifier) {
-                                       ec.Report.SymbolRelatedToPreviousError (pm);
+                       if (!IsMemberAccessible (ec.CurrentType, spec.Set, out must_do_cs1540_check)) {
+                               if (spec.HasDifferentAccessibility) {
+                                       ec.Report.SymbolRelatedToPreviousError (spec.Set);
                                        ec.Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
-                                               TypeManager.CSharpSignature (setter));
-                               }
-                               else {
-                                       ec.Report.SymbolRelatedToPreviousError (setter.MetaInfo);
-                                       ErrorIsInaccesible (loc, TypeManager.CSharpSignature (setter), ec.Report);
+                                               TypeManager.CSharpSignature (spec));
+                               } else {
+                                       ec.Report.SymbolRelatedToPreviousError (spec.Set);
+                                       ErrorIsInaccesible (loc, TypeManager.CSharpSignature (spec.Set), ec.Report);
                                }
                                return null;
                        }
@@ -5716,23 +5003,18 @@ namespace Mono.CSharp {
                        //
                        // Only base will allow this invocation to happen.
                        //
-                       if (IsBase && setter.IsAbstract){
-                               Error_CannotCallAbstractBase (ec, TypeManager.GetFullNameSignature (spec.MetaInfo));
+                       if (IsBase && spec.IsAbstract){
+                               Error_CannotCallAbstractBase (ec, TypeManager.GetFullNameSignature (spec));
                        }
 
-                       if (spec.PropertyType.IsPointer && !ec.IsUnsafe) {
+                       if (spec.MemberType.IsPointer && !ec.IsUnsafe) {
                                UnsafeError (ec, loc);
                        }
 
                        if (!ec.IsObsolete) {
-                               PropertyBase pb = TypeManager.GetProperty (spec.MetaInfo);
-                               if (pb != null) {
-                                       pb.CheckObsoleteness (loc);
-                               } else {
-                                       ObsoleteAttribute oa = AttributeTester.GetMemberObsoleteAttribute (spec.MetaInfo);
-                                       if (oa != null)
-                                               AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
-                               }
+                               ObsoleteAttribute oa = spec.GetAttributeObsolete ();
+                               if (oa != null)
+                                       AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
                        }
 
                        return this;
@@ -5751,16 +5033,16 @@ namespace Mono.CSharp {
                        if (IsSingleDimensionalArrayLength ()) {
                                if (!prepared)
                                        EmitInstance (ec, false);
-                               ec.ig.Emit (OpCodes.Ldlen);
-                               ec.ig.Emit (OpCodes.Conv_I4);
+                               ec.Emit (OpCodes.Ldlen);
+                               ec.Emit (OpCodes.Conv_I4);
                                return;
                        }
 
-                       Invocation.EmitCall (ec, IsBase, InstanceExpression, getter, null, loc, prepared, false);
+                       Invocation.EmitCall (ec, IsBase, InstanceExpression, spec.Get, null, loc, prepared, false);
                        
                        if (leave_copy) {
-                               ec.ig.Emit (OpCodes.Dup);
-                               if (!is_static) {
+                               ec.Emit (OpCodes.Dup);
+                               if (!IsStatic) {
                                        temp = new LocalTemporary (this.Type);
                                        temp.Store (ec);
                                }
@@ -5779,8 +5061,8 @@ namespace Mono.CSharp {
                                source.Emit (ec);
                                
                                if (leave_copy) {
-                                       ec.ig.Emit (OpCodes.Dup);
-                                       if (!is_static) {
+                                       ec.Emit (OpCodes.Dup);
+                                       if (!IsStatic) {
                                                temp = new LocalTemporary (this.Type);
                                                temp.Store (ec);
                                        }
@@ -5795,7 +5077,7 @@ namespace Mono.CSharp {
                        Arguments args = new Arguments (1);
                        args.Add (new Argument (my_source));
                        
-                       Invocation.EmitCall (ec, IsBase, InstanceExpression, setter, args, loc, false, prepared);
+                       Invocation.EmitCall (ec, IsBase, InstanceExpression, spec.Set, args, loc, false, prepared);
                        
                        if (temp != null) {
                                temp.Emit (ec);
@@ -5810,40 +5092,28 @@ namespace Mono.CSharp {
                                return false;
                        }
 
-                       if (getter != null) {
-                               if (!getter.Parameters.IsEmpty) {
-                                       Error_PropertyNotFound (ec, getter, true);
-                                       return false;
-                               }
+                       if (spec.IsNotRealProperty) {
+                               Error_PropertyNotValid (ec);
+                               return false;
                        }
 
-                       if (getter == null) {
-                               //
-                               // The following condition happens if the PropertyExpr was
-                               // created, but is invalid (ie, the property is inaccessible),
-                               // and we did not want to embed the knowledge about this in
-                               // the caller routine.  This only avoids double error reporting.
-                               //
-                               if (setter == null)
-                                       return false;
-
+                       if (!spec.HasGet) {
                                if (InstanceExpression != EmptyExpression.Null) {
+                                       ec.Report.SymbolRelatedToPreviousError (spec);
                                        ec.Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
-                                               TypeManager.GetFullNameSignature (spec.MetaInfo));
+                                               spec.GetSignatureForError ());
                                        return false;
                                }
                        }
 
-                       if (getter != null &&
-                               !IsAccessorAccessible (ec.CurrentType, getter, out must_do_cs1540_check)) {
-                               PropertyBase.PropertyMethod pm = TypeManager.GetMethod (getter.MetaInfo) as PropertyBase.PropertyMethod;
-                               if (pm != null && pm.HasCustomAccessModifier) {
-                                       ec.Report.SymbolRelatedToPreviousError (pm);
+                       if (spec.HasGet && !IsMemberAccessible (ec.CurrentType, spec.Get, out must_do_cs1540_check)) {
+                               if (spec.HasDifferentAccessibility) {
+                                       ec.Report.SymbolRelatedToPreviousError (spec.Get);
                                        ec.Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
-                                               TypeManager.CSharpSignature (getter.MetaInfo));
+                                               TypeManager.CSharpSignature (spec));
                                } else {
-                                       ec.Report.SymbolRelatedToPreviousError (getter.MetaInfo);
-                                       ErrorIsInaccesible (loc, TypeManager.CSharpSignature (getter.MetaInfo), ec.Report);
+                                       ec.Report.SymbolRelatedToPreviousError (spec.Get);
+                                       ErrorIsInaccesible (loc, TypeManager.CSharpSignature (spec.Get), ec.Report);
                                }
 
                                return false;
@@ -5889,7 +5159,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override Type DeclaringType {
+               public override TypeSpec DeclaringType {
                        get {
                                return spec.DeclaringType;
                        }
@@ -5912,7 +5182,7 @@ namespace Mono.CSharp {
                            TypeManager.IsNestedChildOf(ec.CurrentType, spec.DeclaringType)) {
                                        
                                // TODO: Breaks dynamic binder as currect context fields are imported and not compiled
-                               EventField mi = TypeManager.GetEventField (spec.MetaInfo).MemberDefinition as EventField;
+                               EventField mi = spec.MemberDefinition as EventField;
 
                                if (mi != null && mi.HasBackingField) {
                                        mi.SetIsUsed ();
@@ -5953,7 +5223,7 @@ namespace Mono.CSharp {
                                return false;
 
                        if (IsBase && spec.IsAbstract) {
-                               Error_CannotCallAbstractBase (ec, TypeManager.CSharpSignature(spec.MetaInfo));
+                               Error_CannotCallAbstractBase (ec, TypeManager.CSharpSignature(spec));
                                return false;
                        }
 
@@ -5967,19 +5237,19 @@ namespace Mono.CSharp {
                            !TypeManager.IsInstantiationOfSameGenericType (InstanceExpression.Type, ec.CurrentType) &&
                            !TypeManager.IsNestedChildOf (ec.CurrentType, InstanceExpression.Type) &&
                            !TypeManager.IsSubclassOf (InstanceExpression.Type, ec.CurrentType)) {
-                               ec.Report.SymbolRelatedToPreviousError (spec.MetaInfo);
-                               ErrorIsInaccesible (loc, TypeManager.CSharpSignature (spec.MetaInfo), ec.Report);
+                               ec.Report.SymbolRelatedToPreviousError (spec);
+                               ErrorIsInaccesible (loc, TypeManager.CSharpSignature (spec), ec.Report);
                                return false;
                        }
 
                        return true;
                }
 
-               public bool IsAccessibleFrom (Type invocation_type)
+               public bool IsAccessibleFrom (TypeSpec invocation_type)
                {
                        bool dummy;
-                       return IsAccessorAccessible (invocation_type, spec.AccessorAdd, out dummy) &&
-                               IsAccessorAccessible (invocation_type, spec.AccessorRemove, out dummy);
+                       return IsMemberAccessible (invocation_type, spec.AccessorAdd, out dummy) &&
+                               IsMemberAccessible (invocation_type, spec.AccessorRemove, out dummy);
                }
 
                public override Expression CreateExpressionTree (ResolveContext ec)
@@ -5999,10 +5269,10 @@ namespace Mono.CSharp {
                        eclass = ExprClass.EventAccess;
 
                        bool must_do_cs1540_check;
-                       if (!(IsAccessorAccessible (ec.CurrentType, spec.AccessorAdd, out must_do_cs1540_check) &&
-                             IsAccessorAccessible (ec.CurrentType, spec.AccessorRemove, out must_do_cs1540_check))) {
-                               ec.Report.SymbolRelatedToPreviousError (spec.MetaInfo);
-                               ErrorIsInaccesible (loc, TypeManager.CSharpSignature (spec.MetaInfo), ec.Report);
+                       if (!(IsMemberAccessible (ec.CurrentType, spec.AccessorAdd, out must_do_cs1540_check) &&
+                             IsMemberAccessible (ec.CurrentType, spec.AccessorRemove, out must_do_cs1540_check))) {
+                               ec.Report.SymbolRelatedToPreviousError (spec);
+                               ErrorIsInaccesible (loc, TypeManager.CSharpSignature (spec), ec.Report);
                                return null;
                        }
 
@@ -6015,13 +5285,13 @@ namespace Mono.CSharp {
                        }
 
                        if (!ec.IsObsolete) {
-                               var oa = spec.GetObsoleteAttribute ();
+                               var oa = spec.GetAttributeObsolete ();
                                if (oa != null)
                                        AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
                        }
 
                        spec.MemberDefinition.SetIsUsed ();
-                       type = spec.EventType;
+                       type = spec.MemberType;
                        
                        return this;
                }               
@@ -6041,7 +5311,7 @@ namespace Mono.CSharp {
 
                public override string GetSignatureForError ()
                {
-                       return TypeManager.CSharpSignature (spec.MetaInfo);
+                       return TypeManager.CSharpSignature (spec);
                }
 
                public void EmitAddOrRemove (EmitContext ec, bool is_add, Expression source)
@@ -6058,7 +5328,7 @@ namespace Mono.CSharp {
        {
                LocalInfo li;
 
-               public TemporaryVariable (Type type, Location loc)
+               public TemporaryVariable (TypeSpec type, Location loc)
                {
                        this.type = type;
                        this.loc = loc;
index 1aa4e361f90f92f01f80494d38b54444d709f715..d323e062d02ce2db1676b70944d5eeffe79a3510 100644 (file)
@@ -23,16 +23,9 @@ namespace Mono.CSharp {
        {
                class EnumTypeExpr : TypeExpr
                {
-                       public readonly Enum Enum;
-
-                       public EnumTypeExpr (Enum e)
-                       {
-                               this.Enum = e;
-                       }
-
                        protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
                        {
-                               type = Enum.CurrentType != null ? Enum.CurrentType : Enum.TypeBuilder;
+                               type = ec.CurrentType;
                                return this;
                        }
 
@@ -44,13 +37,13 @@ namespace Mono.CSharp {
 
                public EnumMember (Enum parent, EnumMember prev_member, string name, Expression expr,
                                   Attributes attrs, Location loc)
-                       : base (parent, new EnumTypeExpr (parent), name, null, Modifiers.PUBLIC,
+                       : base (parent, new EnumTypeExpr (), name, null, Modifiers.PUBLIC,
                                attrs, loc)
                {
                        initializer = new EnumInitializer (this, expr, prev_member);
                }
 
-               static bool IsValidEnumType (Type t)
+               static bool IsValidEnumType (TypeSpec t)
                {
                        return (t == TypeManager.int32_type || t == TypeManager.uint32_type || t == TypeManager.int64_type ||
                                t == TypeManager.byte_type || t == TypeManager.sbyte_type || t == TypeManager.short_type ||
@@ -84,12 +77,10 @@ namespace Mono.CSharp {
                                return false;
 
                        const FieldAttributes attr = FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal;
-                       FieldBuilder = Parent.TypeBuilder.DefineField (Name, MemberType, attr);
-                       spec = new ConstSpec (this, FieldBuilder, ModFlags, initializer);
-
-                       Parent.MemberCache.AddMember (FieldBuilder, spec);
-                       TypeManager.RegisterConstant (FieldBuilder, (ConstSpec) spec);
+                       FieldBuilder = Parent.TypeBuilder.DefineField (Name, MemberType.GetMetaInfo (), attr);
+                       spec = new ConstSpec (Parent.Definition, this, MemberType, FieldBuilder, ModFlags, initializer);
 
+                       Parent.MemberCache.AddMember (spec);
                        return true;
                }
        }
@@ -113,7 +104,7 @@ namespace Mono.CSharp {
                                return field.ConvertInitializer (rc, null);
 
                        try {
-                               var ec = prev.Initializer.Resolve (rc) as EnumConstant;
+                               var ec = prev.DefineValue () as EnumConstant;
                                expr = ec.Increment ().Resolve (rc);
                        } catch (OverflowException) {
                                rc.Report.Error (543, field.Location,
@@ -151,6 +142,7 @@ namespace Mono.CSharp {
                        this.base_type = type;
                        var accmods = IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE;
                        ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod_flags, accmods, Location, Report);
+                       spec = new EnumSpec (null, this, null, null, ModFlags);
                }
 
                public void AddEnumMember (EnumMember em)
@@ -175,19 +167,19 @@ namespace Mono.CSharp {
                        if (!base.DefineNestedTypes ())
                                return false;
 
-                       //
-                       // Call MapToInternalType for corlib
-                       //
-                       TypeBuilder.DefineField (UnderlyingValueField, UnderlyingType,
-                                                FieldAttributes.Public | FieldAttributes.SpecialName
-                                                | FieldAttributes.RTSpecialName);
+                       ((EnumSpec) spec).UnderlyingType = UnderlyingType;
+
+                       TypeBuilder.DefineField (UnderlyingValueField, UnderlyingType.GetMetaInfo (),
+                               FieldAttributes.Public | FieldAttributes.SpecialName | FieldAttributes.RTSpecialName);
+
+                       if (!RootContext.StdLib)
+                               RootContext.hack_corlib_enums.Add (this);
 
                        return true;
                }
 
                protected override bool DoDefineMembers ()
                {
-                       member_cache = new MemberCache (TypeManager.enum_type, this);
                        DefineContainerMembers (constants);
                        return true;
                }
@@ -197,7 +189,7 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public Type UnderlyingType {
+               public TypeSpec UnderlyingType {
                        get {
                                return base_type.Type;
                        }
@@ -231,14 +223,31 @@ namespace Mono.CSharp {
                }
        }
 
-       public class EnumSpec : TypeSpec
+       class EnumSpec : TypeSpec
        {
-               public EnumSpec (MemberKind kind, ITypeDefinition definition, TypeSpec underlyingType, Type info, string name, Modifiers modifiers)
-                       : base (kind, definition, info, name, modifiers)
+               TypeSpec underlying;
+
+               public EnumSpec (TypeSpec declaringType, ITypeDefinition definition, TypeSpec underlyingType, Type info, Modifiers modifiers)
+                       : base (MemberKind.Enum, declaringType, definition, info, modifiers | Modifiers.SEALED)
                {
-                       this.UnderlyingType = underlyingType;
+                       this.underlying = underlyingType;
                }
 
-               public TypeSpec UnderlyingType { get; private set; }
+               public TypeSpec UnderlyingType {
+                       get {
+                               return underlying;
+                       }
+                       set {
+                               if (underlying != null)
+                                       throw new InternalErrorException ("UnderlyingType reset");
+
+                               underlying = value;
+                       }
+               }
+
+               public static TypeSpec GetUnderlyingType (TypeSpec t)
+               {
+                       return ((EnumSpec) t.GetDefinition ()).UnderlyingType;
+               }
        }
 }
index a1ba9e235371cb7d79b0420af2067d871c645d43..66fc039a53ee0ff2a5d76777cc3b8b8dabe2ec06 100644 (file)
@@ -59,7 +59,7 @@ namespace Mono.CSharp {
                internal static List<NamespaceEntry.UsingEntry> using_list = new List<NamespaceEntry.UsingEntry> ();
                static Dictionary<string, FieldInfo> fields = new Dictionary<string, FieldInfo> ();
 
-               static Type   interactive_base_class = typeof (InteractiveBase);
+               static TypeSpec interactive_base_class;
                static Driver driver;
                static bool inited;
 
@@ -127,7 +127,10 @@ namespace Mono.CSharp {
                                
                                CompilerCallableEntryPoint.Reset ();
                                RootContext.ToplevelTypes = new ModuleCompiled (ctx, true);
+                               /*var ctypes = */TypeManager.InitCoreTypes ();
+                               TypeManager.InitExpressionTypes ();
 
+                               Import.Initialize ();
                                driver.LoadReferences ();
                                RootContext.EvalMode = true;
                                inited = true;
@@ -144,6 +147,7 @@ namespace Mono.CSharp {
                static void Reset ()
                {
                        CompilerCallableEntryPoint.PartialReset ();
+                       RootContext.PartialReset ();
                        
                        // Workaround for API limitation where full message printer cannot be passed
                        ReportPrinter printer;
@@ -160,8 +164,8 @@ namespace Mono.CSharp {
                        //
                        // PartialReset should not reset the core types, this is very redundant.
                        //
-                       if (!TypeManager.InitCoreTypes (ctx))
-                               throw new Exception ("Failed to InitCoreTypes");
+//                     if (!TypeManager.InitCoreTypes (ctx, null))
+//                             throw new Exception ("Failed to InitCoreTypes");
                        TypeManager.InitOptionalCoreTypes (ctx);
                        
                        Location.AddFile (null, "{interactive}");
@@ -188,9 +192,12 @@ namespace Mono.CSharp {
                ///   base class and the static members that are
                ///   available to your evaluated code.
                /// </remarks>
-               static public Type InteractiveBaseClass {
+               static public TypeSpec InteractiveBaseClass {
                        get {
-                               return interactive_base_class;
+                               if (interactive_base_class != null)
+                                       return interactive_base_class;
+
+                               return interactive_base_class = Import.ImportType (typeof (InteractiveBase));
                        }
 
                        set {
@@ -743,7 +750,7 @@ namespace Mono.CSharp {
                        // Unlike Mono, .NET requires that the MethodInfo is fetched, it cant
                        // work from MethodBuilders.   Retarded, I know.
                        //
-                       Type tt = CodeGen.Assembly.Builder.GetType (tb.Name);
+                       var tt = CodeGen.Assembly.Builder.GetType (tb.Name);
                        MethodInfo mi = tt.GetMethod (mb.Name);
                        
                        // Pull the FieldInfos from the type, and keep track of them
@@ -755,7 +762,7 @@ namespace Mono.CSharp {
                                // If a previous value was set, nullify it, so that we do
                                // not leak memory
                                if (fields.TryGetValue (field.Name, out old)){
-                                       if (TypeManager.IsStruct (old.FieldType)){
+                                       if (old.FieldType.IsValueType){
                                                //
                                                // TODO: Clear fields for structs
                                                //
@@ -861,7 +868,7 @@ namespace Mono.CSharp {
                                foreach (var de in fields){
                                        FieldInfo fi = LookupField (de.Key);
                                        object value = null;
-                                       bool error = false;
+                                       //bool error = false;
                                        
                                        try {
                                                if (value == null)
@@ -870,13 +877,14 @@ namespace Mono.CSharp {
                                                if (value is string)
                                                        value = Quote ((string)value);
                                        } catch {
-                                               error = true;
+                                               //error = true;
                                        }
-                                       
-                                       if (error)
-                                               sb.Append (String.Format ("{0} {1} <error reading value>", TypeManager.CSharpName(fi.FieldType), de.Key));
-                                       else
-                                               sb.Append (String.Format ("{0} {1} = {2}", TypeManager.CSharpName(fi.FieldType), de.Key, value));
+
+                                       throw new NotImplementedException ("net");
+                                       //if (error)
+                                       //    sb.Append (String.Format ("{0} {1} <error reading value>", TypeManager.CSharpName(fi.FieldType), de.Key));
+                                       //else
+                                       //    sb.Append (String.Format ("{0} {1} = {2}", TypeManager.CSharpName(fi.FieldType), de.Key, value));
                                }
                                
                                return sb.ToString ();
@@ -900,8 +908,9 @@ namespace Mono.CSharp {
                static public void ReferenceAssembly (Assembly a)
                {
                        lock (evaluator_lock){
-                               GlobalRootNamespace.Instance.AddAssemblyReference (a);
-                               GlobalRootNamespace.Instance.ComputeNamespaces (ctx);
+//                             GlobalRootNamespace.Instance.AddAssemblyReference (a);
+//                             GlobalRootNamespace.Instance.ComputeNamespaces (ctx);
+                               GlobalRootNamespace.Instance.ImportAssembly (a);
                        }
                }
 
@@ -1086,12 +1095,12 @@ namespace Mono.CSharp {
                        if (x == null)
                                return "";
                        
-                       Type t = x as Type;
-                       if (t == null)
-                               t = x.GetType ();
+                       TypeSpec t = x as TypeSpec;
+//                     if (t == null)
+//                             t = x.GetType ();
 
                        StringWriter sw = new StringWriter ();
-                       new Outline (t, sw, true, false, false).OutlineType ();
+                       new Outline (t.GetMetaInfo (), sw, true, false, false).OutlineType ();
                        return sw.ToString ();
                }
 #endif
index 84980efd5f599e287b40d3b870acd2b1e9f83c56..233f9295ebfc03c02109681509afbd85c43a7d9d 100644 (file)
@@ -36,7 +36,7 @@ namespace Mono.CSharp {
                        this.arguments = args;
                        this.expr_tree = expr_tree;
 
-                       type = TypeManager.TypeToCoreType (((MethodSpec) mg).ReturnType);
+                       type = mg.BestCandidate.ReturnType;
                        eclass = ExprClass.Value;
                        this.loc = loc;
                }
@@ -73,19 +73,13 @@ namespace Mono.CSharp {
 
                public override SLE.Expression MakeExpression (BuilderContext ctx)
                {
-                       var method = ((MethodSpec) mg).MetaInfo as MethodInfo;
+                       var method = mg.BestCandidate.GetMetaInfo () as MethodInfo;
                        return SLE.Expression.Call (method, Arguments.MakeExpression (arguments, ctx));
                }
 
                public MethodGroupExpr Method {
                        get { return mg; }
                }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       arguments.MutateHoistedGenericType (storey);
-                       mg.MutateHoistedGenericType (storey);
-               }
        }
 
        public class ParenthesizedExpression : ShimExpression
@@ -117,7 +111,7 @@ namespace Mono.CSharp {
                        AddressOf,  TOP
                }
 
-               static Type [] [] predefined_operators;
+               static TypeSpec[][] predefined_operators;
 
                public readonly Operator Oper;
                public Expression Expr;
@@ -144,7 +138,7 @@ namespace Mono.CSharp {
                                return r == null ? null : new SideEffectConstant (r, e, r.Location);
                        }
 
-                       Type expr_type = e.Type;
+                       TypeSpec expr_type = e.Type;
                        
                        switch (Oper){
                        case Operator.UnaryPlus:
@@ -293,7 +287,7 @@ namespace Mono.CSharp {
                        if (predefined_operators == null)
                                CreatePredefinedOperatorsTable ();
 
-                       Type expr_type = expr.Type;
+                       TypeSpec expr_type = expr.Type;
                        Expression best_expr;
 
                        //
@@ -320,7 +314,7 @@ namespace Mono.CSharp {
 
                protected virtual Expression ResolveEnumOperator (ResolveContext ec, Expression expr)
                {
-                       Type underlying_type = TypeManager.GetEnumUnderlyingType (expr.Type);
+                       TypeSpec underlying_type = EnumSpec.GetUnderlyingType (expr.Type);
                        Expression best_expr = ResolvePrimitivePredefinedType (EmptyCast.Create (expr, underlying_type));
                        if (best_expr == null)
                                return null;
@@ -369,12 +363,12 @@ namespace Mono.CSharp {
 
                static void CreatePredefinedOperatorsTable ()
                {
-                       predefined_operators = new Type [(int) Operator.TOP] [];
+                       predefined_operators = new TypeSpec [(int) Operator.TOP] [];
 
                        //
                        // 7.6.1 Unary plus operator
                        //
-                       predefined_operators [(int) Operator.UnaryPlus] = new Type [] {
+                       predefined_operators [(int) Operator.UnaryPlus] = new TypeSpec [] {
                                TypeManager.int32_type, TypeManager.uint32_type,
                                TypeManager.int64_type, TypeManager.uint64_type,
                                TypeManager.float_type, TypeManager.double_type,
@@ -384,7 +378,7 @@ namespace Mono.CSharp {
                        //
                        // 7.6.2 Unary minus operator
                        //
-                       predefined_operators [(int) Operator.UnaryNegation] = new Type [] {
+                       predefined_operators [(int) Operator.UnaryNegation] = new TypeSpec [] {
                                TypeManager.int32_type, 
                                TypeManager.int64_type,
                                TypeManager.float_type, TypeManager.double_type,
@@ -394,14 +388,14 @@ namespace Mono.CSharp {
                        //
                        // 7.6.3 Logical negation operator
                        //
-                       predefined_operators [(int) Operator.LogicalNot] = new Type [] {
+                       predefined_operators [(int) Operator.LogicalNot] = new TypeSpec [] {
                                TypeManager.bool_type
                        };
 
                        //
                        // 7.6.4 Bitwise complement operator
                        //
-                       predefined_operators [(int) Operator.OnesComplement] = new Type [] {
+                       predefined_operators [(int) Operator.OnesComplement] = new TypeSpec [] {
                                TypeManager.int32_type, TypeManager.uint32_type,
                                TypeManager.int64_type, TypeManager.uint64_type
                        };
@@ -412,7 +406,7 @@ namespace Mono.CSharp {
                //
                static Expression DoNumericPromotion (Operator op, Expression expr)
                {
-                       Type expr_type = expr.Type;
+                       TypeSpec expr_type = expr.Type;
                        if ((op == Operator.UnaryPlus || op == Operator.UnaryNegation || op == Operator.OnesComplement) &&
                                expr_type == TypeManager.byte_type || expr_type == TypeManager.sbyte_type ||
                                expr_type == TypeManager.short_type || expr_type == TypeManager.ushort_type ||
@@ -435,7 +429,7 @@ namespace Mono.CSharp {
                        if (Expr == null)
                                return null;
 
-                       if (TypeManager.IsDynamicType (Expr.Type)) {
+                       if (Expr.Type == InternalType.Dynamic) {
                                Arguments args = new Arguments (1);
                                args.Add (new Argument (Expr));
                                return new DynamicUnaryConversion (GetOperatorExpressionTypeName (), args, loc).Resolve (ec);
@@ -477,10 +471,8 @@ namespace Mono.CSharp {
                        EmitOperator (ec, type);
                }
 
-               protected void EmitOperator (EmitContext ec, Type type)
+               protected void EmitOperator (EmitContext ec, TypeSpec type)
                {
-                       ILGenerator ig = ec.ig;
-
                        switch (Oper) {
                        case Operator.UnaryPlus:
                                Expr.Emit (ec);
@@ -488,27 +480,27 @@ namespace Mono.CSharp {
                                
                        case Operator.UnaryNegation:
                                if (ec.HasSet (EmitContext.Options.CheckedScope) && !IsFloat (type)) {
-                                       ig.Emit (OpCodes.Ldc_I4_0);
+                                       ec.Emit (OpCodes.Ldc_I4_0);
                                        if (type == TypeManager.int64_type)
-                                               ig.Emit (OpCodes.Conv_U8);
+                                               ec.Emit (OpCodes.Conv_U8);
                                        Expr.Emit (ec);
-                                       ig.Emit (OpCodes.Sub_Ovf);
+                                       ec.Emit (OpCodes.Sub_Ovf);
                                } else {
                                        Expr.Emit (ec);
-                                       ig.Emit (OpCodes.Neg);
+                                       ec.Emit (OpCodes.Neg);
                                }
                                
                                break;
                                
                        case Operator.LogicalNot:
                                Expr.Emit (ec);
-                               ig.Emit (OpCodes.Ldc_I4_0);
-                               ig.Emit (OpCodes.Ceq);
+                               ec.Emit (OpCodes.Ldc_I4_0);
+                               ec.Emit (OpCodes.Ceq);
                                break;
                                
                        case Operator.OnesComplement:
                                Expr.Emit (ec);
-                               ig.Emit (OpCodes.Not);
+                               ec.Emit (OpCodes.Not);
                                break;
                                
                        case Operator.AddressOf:
@@ -540,7 +532,7 @@ namespace Mono.CSharp {
                        Expr.EmitSideEffect (ec);
                }
 
-               public static void Error_OperatorCannotBeApplied (ResolveContext ec, Location loc, string oper, Type t)
+               public static void Error_OperatorCannotBeApplied (ResolveContext ec, Location loc, string oper, TypeSpec t)
                {
                        ec.Report.Error (23, loc, "The `{0}' operator cannot be applied to operand of type `{1}'",
                                oper, TypeManager.CSharpName (t));
@@ -565,7 +557,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               static bool IsFloat (Type t)
+               static bool IsFloat (TypeSpec t)
                {
                        return t == TypeManager.float_type || t == TypeManager.double_type;
                }
@@ -610,10 +602,9 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               public static void Reset ()
                {
-                       type = storey.MutateType (type);
-                       Expr.MutateHoistedGenericType (storey);
+                       predefined_operators = null;
                }
 
                Expression ResolveAddressOf (ResolveContext ec)
@@ -660,7 +651,7 @@ namespace Mono.CSharp {
                                ec.Report.Error (212, loc, "You can only take the address of unfixed expression inside of a fixed statement initializer");
                        }
 
-                       type = TypeManager.GetPointerType (Expr.Type);
+                       type = PointerContainer.MakeType (Expr.Type);
                        eclass = ExprClass.Value;
                        return this;
                }
@@ -668,9 +659,9 @@ namespace Mono.CSharp {
                Expression ResolvePrimitivePredefinedType (Expression expr)
                {
                        expr = DoNumericPromotion (Oper, expr);
-                       Type expr_type = expr.Type;
-                       Type[] predefined = predefined_operators [(int) Oper];
-                       foreach (Type t in predefined) {
+                       TypeSpec expr_type = expr.Type;
+                       TypeSpec[] predefined = predefined_operators [(int) Oper];
+                       foreach (TypeSpec t in predefined) {
                                if (t == expr_type)
                                        return expr;
                        }
@@ -697,7 +688,7 @@ namespace Mono.CSharp {
                        }
 
                        string op_name = CSharp.Operator.GetMetadataName (op_type);
-                       MethodGroupExpr user_op = MemberLookup (ec.Compiler, ec.CurrentType, expr.Type, op_name, MemberTypes.Method, AllBindingFlags, expr.Location) as MethodGroupExpr;
+                       MethodGroupExpr user_op = MethodLookup (ec.Compiler, ec.CurrentType, expr.Type, MemberKind.Operator, op_name, 0, expr.Location);
                        if (user_op == null)
                                return null;
 
@@ -721,8 +712,8 @@ namespace Mono.CSharp {
                        if (best_expr != null)
                                return best_expr;
 
-                       Type[] predefined = predefined_operators [(int) Oper];
-                       foreach (Type t in predefined) {
+                       TypeSpec[] predefined = predefined_operators [(int) Oper];
+                       foreach (TypeSpec t in predefined) {
                                Expression oper_expr = Convert.UserDefinedConversion (ec, expr, t, expr.Location, false, false);
                                if (oper_expr == null)
                                        continue;
@@ -809,14 +800,14 @@ namespace Mono.CSharp {
                        if (!prepared)
                                expr.Emit (ec);
                        
-                       LoadFromPtr (ec.ig, Type);
+                       ec.EmitLoadFromPtr (Type);
                }
 
                public void Emit (EmitContext ec, bool leave_copy)
                {
                        Emit (ec);
                        if (leave_copy) {
-                               ec.ig.Emit (OpCodes.Dup);
+                               ec.Emit (OpCodes.Dup);
                                temporary = new LocalTemporary (expr.Type);
                                temporary.Store (ec);
                        }
@@ -829,16 +820,16 @@ namespace Mono.CSharp {
                        expr.Emit (ec);
 
                        if (prepare_for_load)
-                               ec.ig.Emit (OpCodes.Dup);
+                               ec.Emit (OpCodes.Dup);
                        
                        source.Emit (ec);
                        if (leave_copy) {
-                               ec.ig.Emit (OpCodes.Dup);
+                               ec.Emit (OpCodes.Dup);
                                temporary = new LocalTemporary (expr.Type);
                                temporary.Store (ec);
                        }
                        
-                       StoreFromPtr (ec.ig, type);
+                       ec.EmitStoreFromPtr (type);
                        
                        if (temporary != null) {
                                temporary.Emit (ec);
@@ -1007,7 +998,7 @@ namespace Mono.CSharp {
                        if (expr == null)
                                return null;
 
-                       if (TypeManager.IsDynamicType (expr.Type)) {
+                       if (expr.Type == InternalType.Dynamic) {
                                //
                                // Handle postfix unary operators using local
                                // temporary variable
@@ -1077,7 +1068,7 @@ namespace Mono.CSharp {
                //   use pre-post incr-decr operations on it, but it is not a
                //   System.Decimal, which we require operator overloading to catch)
                //
-               static bool IsPredefinedOperator (Type t)
+               static bool IsPredefinedOperator (TypeSpec t)
                {
                        return (TypeManager.IsPrimitiveType (t) && t != TypeManager.bool_type) ||
                                TypeManager.IsEnumType (t) ||
@@ -1141,7 +1132,6 @@ namespace Mono.CSharp {
                        //
                        // Step 2: Perform Operator Overload location
                        //
-                       MethodGroupExpr mg;
                        string op_name;
 
                        if (IsDecrement)
@@ -1149,7 +1139,7 @@ namespace Mono.CSharp {
                        else
                                op_name = Operator.GetMetadataName (Operator.OpType.Increment);
 
-                       mg = MemberLookup (ec.Compiler, ec.CurrentType, type, op_name, MemberTypes.Method, AllBindingFlags, loc) as MethodGroupExpr;
+                       var mg = MethodLookup (ec.Compiler, ec.CurrentType, type, MemberKind.Operator, op_name, 0, loc);
 
                        if (mg != null) {
                                Arguments args = new Arguments (1);
@@ -1209,7 +1199,7 @@ namespace Mono.CSharp {
                        if (expr == null)
                                return null;
 
-                       if ((probe_type_expr.Type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
+                       if (probe_type_expr.Type.IsStatic) {
                                ec.Report.Error (-244, loc, "The `{0}' operator cannot be applied to an operand of a static type",
                                        OperatorName);
                        }
@@ -1229,12 +1219,6 @@ namespace Mono.CSharp {
                        return this;
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       expr.MutateHoistedGenericType (storey);
-                       probe_type_expr.MutateHoistedGenericType (storey);
-               }
-
                protected abstract string OperatorName { get; }
 
                protected override void CloneTo (CloneContext clonectx, Expression t)
@@ -1269,28 +1253,26 @@ namespace Mono.CSharp {
                
                public override void Emit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
                        if (expr_unwrap != null) {
                                expr_unwrap.EmitCheck (ec);
                                return;
                        }
 
                        expr.Emit (ec);
-                       ig.Emit (OpCodes.Isinst, probe_type_expr.Type);
-                       ig.Emit (OpCodes.Ldnull);
-                       ig.Emit (OpCodes.Cgt_Un);
+                       ec.Emit (OpCodes.Isinst, probe_type_expr.Type);
+                       ec.Emit (OpCodes.Ldnull);
+                       ec.Emit (OpCodes.Cgt_Un);
                }
 
                public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
                {
-                       ILGenerator ig = ec.ig;
                        if (expr_unwrap != null) {
                                expr_unwrap.EmitCheck (ec);
                        } else {
                                expr.Emit (ec);
-                               ig.Emit (OpCodes.Isinst, probe_type_expr.Type);
+                               ec.Emit (OpCodes.Isinst, probe_type_expr.Type);
                        }                       
-                       ig.Emit (on_true ? OpCodes.Brtrue : OpCodes.Brfalse, target);
+                       ec.Emit (on_true ? OpCodes.Brtrue : OpCodes.Brfalse, target);
                }
                
                Expression CreateConstantResult (ResolveContext ec, bool result)
@@ -1310,7 +1292,7 @@ namespace Mono.CSharp {
                        if (base.DoResolve (ec) == null)
                                return null;
 
-                       Type d = expr.Type;
+                       TypeSpec d = expr.Type;
                        bool d_is_nullable = false;
 
                        //
@@ -1320,18 +1302,24 @@ namespace Mono.CSharp {
                        if (expr.IsNull || expr.eclass == ExprClass.MethodGroup)
                                return CreateConstantResult (ec, false);
 
-                       if (TypeManager.IsNullableType (d) && !TypeManager.ContainsGenericParameters (d)) {
-                               d = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (d) [0]);
-                               d_is_nullable = true;
+                       if (TypeManager.IsNullableType (d)) {
+                               var ut = Nullable.NullableInfo.GetUnderlyingType (d);
+                               if (!ut.IsGenericParameter) {
+                                       d = ut;
+                                       d_is_nullable = true;
+                               }
                        }
 
                        type = TypeManager.bool_type;
                        eclass = ExprClass.Value;
-                       Type t = probe_type_expr.Type;
+                       TypeSpec t = probe_type_expr.Type;
                        bool t_is_nullable = false;
-                       if (TypeManager.IsNullableType (t) && !TypeManager.ContainsGenericParameters (t)) {
-                               t = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (t) [0]);
-                               t_is_nullable = true;
+                       if (TypeManager.IsNullableType (t)) {
+                               var ut = Nullable.NullableInfo.GetUnderlyingType (t);
+                               if (!ut.IsGenericParameter) {
+                                       t = ut;
+                                       t_is_nullable = true;
+                               }
                        }
 
                        if (TypeManager.IsStruct (t)) {
@@ -1350,8 +1338,9 @@ namespace Mono.CSharp {
                                        return CreateConstantResult (ec, true);
                                }
 
-                               if (TypeManager.IsGenericParameter (d))
-                                       return ResolveGenericParameter (ec, t, d);
+                               var tp = d as TypeParameterSpec;
+                               if (tp != null)
+                                       return ResolveGenericParameter (ec, t, tp);
 
                                //
                                // An unboxing conversion exists
@@ -1360,7 +1349,7 @@ namespace Mono.CSharp {
                                        return this;
                        } else {
                                if (TypeManager.IsGenericParameter (t))
-                                       return ResolveGenericParameter (ec, d, t);
+                                       return ResolveGenericParameter (ec, d, (TypeParameterSpec) t);
 
                                if (TypeManager.IsStruct (d)) {
                                        bool temp;
@@ -1368,7 +1357,7 @@ namespace Mono.CSharp {
                                                return CreateConstantResult (ec, true);
                                } else {
                                        if (TypeManager.IsGenericParameter (d))
-                                               return ResolveGenericParameter (ec, t, d);
+                                               return ResolveGenericParameter (ec, t, (TypeParameterSpec) d);
 
                                        if (TypeManager.ContainsGenericParameters (d))
                                                return this;
@@ -1383,16 +1372,15 @@ namespace Mono.CSharp {
                        return CreateConstantResult (ec, false);
                }
 
-               Expression ResolveGenericParameter (ResolveContext ec, Type d, Type t)
+               Expression ResolveGenericParameter (ResolveContext ec, TypeSpec d, TypeParameterSpec t)
                {
-                       GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
-                       if (constraints != null) {
-                               if (constraints.IsReferenceType && TypeManager.IsStruct (d))
+                       if (t.IsReferenceType) {
+                               if (TypeManager.IsStruct (d))
                                        return CreateConstantResult (ec, false);
                        }
 
                        if (TypeManager.IsGenericParameter (expr.Type)) {
-                               if (constraints != null && constraints.IsValueType && expr.Type == t)
+                               if (t.IsValueType && expr.Type == t)
                                        return CreateConstantResult (ec, true);
 
                                expr = new BoxedCast (expr, d);
@@ -1429,15 +1417,13 @@ namespace Mono.CSharp {
 
                public override void Emit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-
                        expr.Emit (ec);
 
                        if (do_isinst)
-                               ig.Emit (OpCodes.Isinst, type);
+                               ec.Emit (OpCodes.Isinst, type);
 
                        if (TypeManager.IsGenericParameter (type) || TypeManager.IsNullableType (type))
-                               ig.Emit (OpCodes.Unbox_Any, type);
+                               ec.Emit (OpCodes.Unbox_Any, type);
                }
 
                protected override Expression DoResolve (ResolveContext ec)
@@ -1451,7 +1437,7 @@ namespace Mono.CSharp {
 
                        type = probe_type_expr.Type;
                        eclass = ExprClass.Value;
-                       Type etype = expr.Type;
+                       TypeSpec etype = expr.Type;
 
                        if (!TypeManager.IsReferenceType (type) && !TypeManager.IsNullableType (type)) {
                                if (TypeManager.IsGenericParameter (type)) {
@@ -1501,17 +1487,6 @@ namespace Mono.CSharp {
                protected override string OperatorName {
                        get { return "as"; }
                }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       type = storey.MutateType (type);
-                       base.MutateHoistedGenericType (storey);
-               }
-       
-               public override bool GetAttributableValue (ResolveContext ec, Type value_type, out object value)
-               {
-                       return expr.GetAttributableValue (ec, value_type, out value);
-               }
        }
        
        /// <summary>
@@ -1551,7 +1526,7 @@ namespace Mono.CSharp {
 
                        type = target.Type;
 
-                       if (type.IsAbstract && type.IsSealed) {
+                       if (type.IsStatic) {
                                ec.Report.Error (716, loc, "Cannot convert to static type `{0}'", TypeManager.CSharpName (type));
                                return null;
                        }
@@ -1567,7 +1542,7 @@ namespace Mono.CSharp {
 
                        if (type.IsPointer && !ec.IsUnsafe) {
                                UnsafeError (ec, loc);
-                       } else if (TypeManager.IsDynamicType (expr.Type)) {
+                       } else if (expr.Type == InternalType.Dynamic) {
                                Arguments arg = new Arguments (1);
                                arg.Add (new Argument (expr));
                                return new DynamicConversion (type, CSharpBinderFlags.ConvertExplicit, arg, loc).Resolve (ec);
@@ -1590,7 +1565,7 @@ namespace Mono.CSharp {
        {
                bool arrayAccess;
 
-               public ImplicitCast (Expression expr, Type target, bool arrayAccess)
+               public ImplicitCast (Expression expr, TypeSpec target, bool arrayAccess)
                        : base (expr)
                {
                        this.loc = expr.Location;
@@ -1642,7 +1617,7 @@ namespace Mono.CSharp {
 
                        type = texpr.Type;
 
-                       if ((type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
+                       if (type.IsStatic) {
                                ec.Report.Error (-244, loc, "The `default value' operator cannot be applied to an operand of a static type");
                        }
 
@@ -1665,15 +1640,10 @@ namespace Mono.CSharp {
                        LocalTemporary temp_storage = new LocalTemporary(type);
 
                        temp_storage.AddressOf(ec, AddressOp.LoadStore);
-                       ec.ig.Emit(OpCodes.Initobj, type);
+                       ec.Emit(OpCodes.Initobj, type);
                        temp_storage.Emit(ec);
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       type = storey.MutateType (type);
-               }
-               
                protected override void CloneTo (CloneContext clonectx, Expression t)
                {
                        DefaultValueExpression target = (DefaultValueExpression) t;
@@ -1688,27 +1658,27 @@ namespace Mono.CSharp {
        public class Binary : Expression, IDynamicBinder
        {
                protected class PredefinedOperator {
-                       protected readonly Type left;
-                       protected readonly Type right;
+                       protected readonly TypeSpec left;
+                       protected readonly TypeSpec right;
                        public readonly Operator OperatorsMask;
-                       public Type ReturnType;
+                       public TypeSpec ReturnType;
 
-                       public PredefinedOperator (Type ltype, Type rtype, Operator op_mask)
+                       public PredefinedOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
                                : this (ltype, rtype, op_mask, ltype)
                        {
                        }
 
-                       public PredefinedOperator (Type type, Operator op_mask, Type return_type)
+                       public PredefinedOperator (TypeSpec type, Operator op_mask, TypeSpec return_type)
                                : this (type, type, op_mask, return_type)
                        {
                        }
 
-                       public PredefinedOperator (Type type, Operator op_mask)
+                       public PredefinedOperator (TypeSpec type, Operator op_mask)
                                : this (type, type, op_mask, type)
                        {
                        }
 
-                       public PredefinedOperator (Type ltype, Type rtype, Operator op_mask, Type return_type)
+                       public PredefinedOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec return_type)
                        {
                                if ((op_mask & Operator.ValuesOnlyMask) != 0)
                                        throw new InternalErrorException ("Only masked values can be used");
@@ -1755,7 +1725,7 @@ namespace Mono.CSharp {
                                return b;
                        }
 
-                       public bool IsPrimitiveApplicable (Type ltype, Type rtype)
+                       public bool IsPrimitiveApplicable (TypeSpec ltype, TypeSpec rtype)
                        {
                                //
                                // We are dealing with primitive types only
@@ -1795,13 +1765,13 @@ namespace Mono.CSharp {
                }
 
                class PredefinedStringOperator : PredefinedOperator {
-                       public PredefinedStringOperator (Type type, Operator op_mask)
+                       public PredefinedStringOperator (TypeSpec type, Operator op_mask)
                                : base (type, op_mask, type)
                        {
                                ReturnType = TypeManager.string_type;
                        }
 
-                       public PredefinedStringOperator (Type ltype, Type rtype, Operator op_mask)
+                       public PredefinedStringOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
                                : base (ltype, rtype, op_mask)
                        {
                                ReturnType = TypeManager.string_type;
@@ -1831,7 +1801,7 @@ namespace Mono.CSharp {
                }
 
                class PredefinedShiftOperator : PredefinedOperator {
-                       public PredefinedShiftOperator (Type ltype, Operator op_mask) :
+                       public PredefinedShiftOperator (TypeSpec ltype, Operator op_mask) :
                                base (ltype, TypeManager.int32_type, op_mask)
                        {
                        }
@@ -1868,17 +1838,17 @@ namespace Mono.CSharp {
                }
 
                class PredefinedPointerOperator : PredefinedOperator {
-                       public PredefinedPointerOperator (Type ltype, Type rtype, Operator op_mask)
+                       public PredefinedPointerOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask)
                                : base (ltype, rtype, op_mask)
                        {
                        }
 
-                       public PredefinedPointerOperator (Type ltype, Type rtype, Operator op_mask, Type retType)
+                       public PredefinedPointerOperator (TypeSpec ltype, TypeSpec rtype, Operator op_mask, TypeSpec retType)
                                : base (ltype, rtype, op_mask, retType)
                        {
                        }
 
-                       public PredefinedPointerOperator (Type type, Operator op_mask, Type return_type)
+                       public PredefinedPointerOperator (TypeSpec type, Operator op_mask, TypeSpec return_type)
                                : base (type, op_mask, return_type)
                        {
                        }
@@ -1912,7 +1882,7 @@ namespace Mono.CSharp {
                                        b.right = EmptyCast.Create (b.right, right);
                                }
 
-                               Type r_type = ReturnType;
+                               TypeSpec r_type = ReturnType;
                                Expression left_arg, right_arg;
                                if (r_type == null) {
                                        if (left == null) {
@@ -1978,8 +1948,8 @@ namespace Mono.CSharp {
                readonly bool is_compound;
                Expression enum_conversion;
 
-               static PredefinedOperator [] standard_operators;
-               static PredefinedOperator [] pointer_operators;
+               static PredefinedOperator[] standard_operators;
+               static PredefinedOperator[] pointer_operators;
                
                public Binary (Operator oper, Expression left, Expression right, bool isCompound, Location loc)
                        : this (oper, left, right, loc)
@@ -2183,10 +2153,9 @@ namespace Mono.CSharp {
                        return CSharp.Operator.GetMetadataName (op_type);
                }
 
-               public static void EmitOperatorOpcode (EmitContext ec, Operator oper, Type l)
+               public static void EmitOperatorOpcode (EmitContext ec, Operator oper, TypeSpec l)
                {
                        OpCode opcode;
-                       ILGenerator ig = ec.ig;
 
                        switch (oper){
                        case Operator.Multiply:
@@ -2256,8 +2225,8 @@ namespace Mono.CSharp {
                                break;
 
                        case Operator.Inequality:
-                               ig.Emit (OpCodes.Ceq);
-                               ig.Emit (OpCodes.Ldc_I4_0);
+                               ec.Emit (OpCodes.Ceq);
+                               ec.Emit (OpCodes.Ldc_I4_0);
                                
                                opcode = OpCodes.Ceq;
                                break;
@@ -2278,21 +2247,21 @@ namespace Mono.CSharp {
 
                        case Operator.LessThanOrEqual:
                                if (IsUnsigned (l) || IsFloat (l))
-                                       ig.Emit (OpCodes.Cgt_Un);
+                                       ec.Emit (OpCodes.Cgt_Un);
                                else
-                                       ig.Emit (OpCodes.Cgt);
-                               ig.Emit (OpCodes.Ldc_I4_0);
+                                       ec.Emit (OpCodes.Cgt);
+                               ec.Emit (OpCodes.Ldc_I4_0);
                                
                                opcode = OpCodes.Ceq;
                                break;
 
                        case Operator.GreaterThanOrEqual:
                                if (IsUnsigned (l) || IsFloat (l))
-                                       ig.Emit (OpCodes.Clt_Un);
+                                       ec.Emit (OpCodes.Clt_Un);
                                else
-                                       ig.Emit (OpCodes.Clt);
+                                       ec.Emit (OpCodes.Clt);
                                
-                               ig.Emit (OpCodes.Ldc_I4_0);
+                               ec.Emit (OpCodes.Ldc_I4_0);
                                
                                opcode = OpCodes.Ceq;
                                break;
@@ -2313,10 +2282,10 @@ namespace Mono.CSharp {
                                throw new InternalErrorException (oper.ToString ());
                        }
 
-                       ig.Emit (opcode);
+                       ec.Emit (opcode);
                }
 
-               static bool IsUnsigned (Type t)
+               static bool IsUnsigned (TypeSpec t)
                {
                        if (t.IsPointer)
                                return true;
@@ -2325,15 +2294,20 @@ namespace Mono.CSharp {
                                t == TypeManager.ushort_type || t == TypeManager.byte_type);
                }
 
-               static bool IsFloat (Type t)
+               static bool IsFloat (TypeSpec t)
                {
                        return t == TypeManager.float_type || t == TypeManager.double_type;
                }
 
+               public static void Reset ()
+               {
+                       pointer_operators = standard_operators = null;
+               }
+
                Expression ResolveOperator (ResolveContext ec)
                {
-                       Type l = left.Type;
-                       Type r = right.Type;
+                       TypeSpec l = left.Type;
+                       TypeSpec r = right.Type;
                        Expression expr;
                        bool primitives_only = false;
 
@@ -2498,7 +2472,7 @@ namespace Mono.CSharp {
                static void CreateStandardOperatorsTable ()
                {
                        var temp = new List<PredefinedOperator> ();
-                       Type bool_type = TypeManager.bool_type;
+                       TypeSpec bool_type = TypeManager.bool_type;
 
                        temp.Add (new PredefinedOperator (TypeManager.int32_type, Operator.ArithmeticMask | Operator.BitwiseMask));
                        temp.Add (new PredefinedOperator (TypeManager.uint32_type, Operator.ArithmeticMask | Operator.BitwiseMask));
@@ -2536,10 +2510,10 @@ namespace Mono.CSharp {
                //
                // Rules used during binary numeric promotion
                //
-               static bool DoNumericPromotion (ResolveContext rc, ref Expression prim_expr, ref Expression second_expr, Type type)
+               static bool DoNumericPromotion (ResolveContext rc, ref Expression prim_expr, ref Expression second_expr, TypeSpec type)
                {
                        Expression temp;
-                       Type etype;
+                       TypeSpec etype;
 
                        Constant c = prim_expr as Constant;
                        if (c != null) {
@@ -2588,11 +2562,11 @@ namespace Mono.CSharp {
                //
                public bool DoBinaryOperatorPromotion (ResolveContext ec)
                {
-                       Type ltype = left.Type;
-                       Type rtype = right.Type;
+                       TypeSpec ltype = left.Type;
+                       TypeSpec rtype = right.Type;
                        Expression temp;
 
-                       foreach (Type t in ConstantFold.binary_promotions) {
+                       foreach (TypeSpec t in ConstantFold.BinaryPromotionsTypes) {
                                if (t == ltype)
                                        return t == rtype || DoNumericPromotion (ec, ref right, ref left, t);
 
@@ -2600,7 +2574,7 @@ namespace Mono.CSharp {
                                        return t == ltype || DoNumericPromotion (ec, ref left, ref right, t);
                        }
 
-                       Type int32 = TypeManager.int32_type;
+                       TypeSpec int32 = TypeManager.int32_type;
                        if (ltype != int32) {
                                Constant c = left as Constant;
                                if (c != null)
@@ -2695,7 +2669,7 @@ namespace Mono.CSharp {
                                CheckUselessComparison (ec, rc, left.Type);
                        }
 
-                       if (TypeManager.IsDynamicType (left.Type) || TypeManager.IsDynamicType (right.Type)) {
+                       if (left.Type == InternalType.Dynamic || right.Type == InternalType.Dynamic) {
                                Arguments args = new Arguments (2);
                                args.Add (new Argument (left));
                                args.Add (new Argument (right));
@@ -2775,22 +2749,16 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       left.MutateHoistedGenericType (storey);
-                       right.MutateHoistedGenericType (storey);
-               }
-
                //
                // D operator + (D x, D y)
                // D operator - (D x, D y)
                // bool operator == (D x, D y)
                // bool operator != (D x, D y)
                //
-               Expression ResolveOperatorDelegate (ResolveContext ec, Type l, Type r)
+               Expression ResolveOperatorDelegate (ResolveContext ec, TypeSpec l, TypeSpec r)
                {
                        bool is_equality = (oper & Operator.EqualityMask) != 0;
-                       if (!TypeManager.IsEqual (l, r) && !TypeManager.IsVariantOf (r, l)) {
+                       if (!TypeManager.IsEqual (l, r) && !TypeSpecComparer.Variant.IsEqual (r, l)) {
                                Expression tmp;
                                if (right.eclass == ExprClass.MethodGroup || (r == InternalType.AnonymousMethod && !is_equality)) {
                                        tmp = Convert.ImplicitConversionRequired (ec, right, l, loc);
@@ -2836,7 +2804,10 @@ namespace Mono.CSharp {
                                method = TypeManager.delegate_remove_delegate_delegate;
                        }
 
-                       MethodGroupExpr mg = new MethodGroupExpr (new [] { method }, TypeManager.delegate_type, loc);
+                       if (method == null)
+                               return new EmptyExpression (TypeManager.decimal_type);
+
+                       MethodGroupExpr mg = new MethodGroupExpr (method, TypeManager.delegate_type, loc);
                        mg = mg.OverloadResolve (ec, ref args, false, loc);
 
                        return new ClassCast (new UserOperatorCall (mg, args, CreateExpressionTree, loc), l);
@@ -2845,7 +2816,7 @@ namespace Mono.CSharp {
                //
                // Enumeration operators
                //
-               Expression ResolveOperatorEnum (ResolveContext ec, bool lenum, bool renum, Type ltype, Type rtype)
+               Expression ResolveOperatorEnum (ResolveContext ec, bool lenum, bool renum, TypeSpec ltype, TypeSpec rtype)
                {
                        //
                        // bool operator == (E x, E y);
@@ -2872,7 +2843,7 @@ namespace Mono.CSharp {
 
                        Expression ltemp = left;
                        Expression rtemp = right;
-                       Type underlying_type;
+                       TypeSpec underlying_type;
                        Expression expr;
                        
                        if ((oper & (Operator.ComparisonMask | Operator.BitwiseMask)) != 0) {
@@ -2892,7 +2863,7 @@ namespace Mono.CSharp {
                        }                       
 
                        if (TypeManager.IsEqual (ltype, rtype)) {
-                               underlying_type = TypeManager.GetEnumUnderlyingType (ltype);
+                               underlying_type = EnumSpec.GetUnderlyingType (ltype);
 
                                if (left is Constant)
                                        left = ((Constant) left).ConvertExplicitly (false, underlying_type).Resolve (ec);
@@ -2904,7 +2875,7 @@ namespace Mono.CSharp {
                                else
                                        right = EmptyCast.Create (right, underlying_type);
                        } else if (lenum) {
-                               underlying_type = TypeManager.GetEnumUnderlyingType (ltype);
+                               underlying_type = EnumSpec.GetUnderlyingType (ltype);
 
                                if (oper != Operator.Subtraction && oper != Operator.Addition) {
                                        Constant c = right as Constant;
@@ -2923,7 +2894,7 @@ namespace Mono.CSharp {
                                        left = EmptyCast.Create (left, underlying_type);
 
                        } else if (renum) {
-                               underlying_type = TypeManager.GetEnumUnderlyingType (rtype);
+                               underlying_type = EnumSpec.GetUnderlyingType (rtype);
 
                                if (oper != Operator.Addition) {
                                        Constant c = left as Constant;
@@ -2955,9 +2926,9 @@ namespace Mono.CSharp {
                                return null;
                        }
 
-                       Type res_type = null;
+                       TypeSpec res_type = null;
                        if ((oper & Operator.BitwiseMask) != 0 || oper == Operator.Subtraction || oper == Operator.Addition) {
-                               Type promoted_type = lenum ? left.Type : right.Type;
+                               TypeSpec promoted_type = lenum ? left.Type : right.Type;
                                enum_conversion = Convert.ExplicitNumericConversion (
                                        new EmptyExpression (promoted_type), underlying_type);
 
@@ -3002,7 +2973,7 @@ namespace Mono.CSharp {
                //
                // 7.9.6 Reference type equality operators
                //
-               Binary ResolveOperatorEqualityRerefence (ResolveContext ec, Type l, Type r)
+               Binary ResolveOperatorEqualityRerefence (ResolveContext ec, TypeSpec l, TypeSpec r)
                {
                        //
                        // operator != (object a, object b)
@@ -3015,12 +2986,14 @@ namespace Mono.CSharp {
                                return null;
 
                        type = TypeManager.bool_type;
-                       GenericConstraints constraints;
 
-                       bool lgen = TypeManager.IsGenericParameter (l);
+                       var lgen = l as TypeParameterSpec;
 
-                       if (TypeManager.IsEqual (l, r)) {
-                               if (lgen) {
+                       if (l == r) {
+                               if (l is InternalType)
+                                       return null;
+
+                               if (lgen != null) {
                                        //
                                        // Only allow to compare same reference type parameter
                                        //
@@ -3033,16 +3006,13 @@ namespace Mono.CSharp {
                                        return null;
                                }
 
-                               if (l == InternalType.AnonymousMethod)
-                                       return null;
-
                                if (TypeManager.IsValueType (l))
                                        return null;
 
                                return this;
                        }
 
-                       bool rgen = TypeManager.IsGenericParameter (r);
+                       var rgen = r as TypeParameterSpec;
 
                        //
                        // a, Both operands are reference-type values or the value null
@@ -3051,18 +3021,16 @@ namespace Mono.CSharp {
                        // value type constrain
                        //
                        if (left is NullLiteral || right is NullLiteral) {
-                               if (lgen) {
-                                       constraints = TypeManager.GetTypeParameterConstraints (l);
-                                       if (constraints != null && constraints.HasValueTypeConstraint)
+                               if (lgen != null) {
+                                       if (lgen.HasSpecialStruct)
                                                return null;
 
                                        left = new BoxedCast (left, TypeManager.object_type);
                                        return this;
                                }
 
-                               if (rgen) {
-                                       constraints = TypeManager.GetTypeParameterConstraints (r);
-                                       if (constraints != null && constraints.HasValueTypeConstraint)
+                               if (rgen != null) {
+                                       if (rgen.HasSpecialStruct)
                                                return null;
 
                                        right = new BoxedCast (right, TypeManager.object_type);
@@ -3075,7 +3043,7 @@ namespace Mono.CSharp {
                        // standard conversion is applied. It's not clear from the
                        // standard but it looks like it works like that.
                        //
-                       if (lgen) {
+                       if (lgen != null) {
                                if (!TypeManager.IsReferenceType (l))
                                        return null;
 
@@ -3087,7 +3055,7 @@ namespace Mono.CSharp {
                                return null;
                        }
 
-                       if (rgen) {
+                       if (rgen != null) {
                                if (!TypeManager.IsReferenceType (r))
                                        return null;
 
@@ -3125,7 +3093,7 @@ namespace Mono.CSharp {
                }
 
 
-               Expression ResolveOperatorPointer (ResolveContext ec, Type l, Type r)
+               Expression ResolveOperatorPointer (ResolveContext ec, TypeSpec l, TypeSpec r)
                {
                        //
                        // bool operator == (void* x, void* y);
@@ -3164,11 +3132,11 @@ namespace Mono.CSharp {
                //
                // Build-in operators method overloading
                //
-               protected virtual Expression ResolveOperatorPredefined (ResolveContext ec, PredefinedOperator [] operators, bool primitives_only, Type enum_type)
+               protected virtual Expression ResolveOperatorPredefined (ResolveContext ec, PredefinedOperator [] operators, bool primitives_only, TypeSpec enum_type)
                {
                        PredefinedOperator best_operator = null;
-                       Type l = left.Type;
-                       Type r = right.Type;
+                       TypeSpec l = left.Type;
+                       TypeSpec r = right.Type;
                        Operator oper_mask = oper & ~Operator.ValuesOnlyMask;
 
                        foreach (PredefinedOperator po in operators) {
@@ -3238,7 +3206,7 @@ namespace Mono.CSharp {
                //
                // Performs user-operator overloading
                //
-               protected virtual Expression ResolveUserOperator (ResolveContext ec, Type l, Type r)
+               protected virtual Expression ResolveUserOperator (ResolveContext ec, TypeSpec l, TypeSpec r)
                {
                        Operator user_oper;
                        if (oper == Operator.LogicalAnd)
@@ -3250,11 +3218,11 @@ namespace Mono.CSharp {
 
                        string op = GetOperatorMetadataName (user_oper);
 
-                       MethodGroupExpr left_operators = MemberLookup (ec.Compiler, ec.CurrentType, l, op, MemberTypes.Method, AllBindingFlags, loc) as MethodGroupExpr;
+                       MethodGroupExpr left_operators = MethodLookup (ec.Compiler, ec.CurrentType, l, MemberKind.Operator, op, 0, loc);
                        MethodGroupExpr right_operators = null;
 
                        if (!TypeManager.IsEqual (r, l)) {
-                               right_operators = MemberLookup (ec.Compiler, ec.CurrentType, r, op, MemberTypes.Method, AllBindingFlags, loc) as MethodGroupExpr;
+                               right_operators = MethodLookup (ec.Compiler, ec.CurrentType, r, MemberKind.Operator, op, 0, loc);
                                if (right_operators == null && left_operators == null)
                                        return null;
                        } else if (left_operators == null) {
@@ -3336,7 +3304,7 @@ namespace Mono.CSharp {
                        return null;
                }
 
-               private void CheckUselessComparison (ResolveContext ec, Constant c, Type type)
+               private void CheckUselessComparison (ResolveContext ec, Constant c, TypeSpec type)
                {
                        if (c == null || !IsTypeIntegral (type)
                                || c is StringConstant
@@ -3389,7 +3357,7 @@ namespace Mono.CSharp {
                                WarnUselessComparison (ec, type);
                }
 
-               static bool IsValueOutOfRange (long value, Type type)
+               static bool IsValueOutOfRange (long value, TypeSpec type)
                {
                        if (IsTypeUnsigned (type) && value < 0)
                                return true;
@@ -3401,13 +3369,13 @@ namespace Mono.CSharp {
                                type == TypeManager.uint32_type && value >= 0x100000000;
                }
 
-               static bool IsBuildInEqualityOperator (Type t)
+               static bool IsBuildInEqualityOperator (TypeSpec t)
                {
                        return t == TypeManager.object_type || t == TypeManager.string_type ||
                                t == TypeManager.delegate_type || TypeManager.IsDelegateType (t);
                }
 
-               static bool IsPredefinedUserOperator (Type t, Operator op)
+               static bool IsPredefinedUserOperator (TypeSpec t, Operator op)
                {
                        //
                        // Some predefined types have user operators
@@ -3415,7 +3383,7 @@ namespace Mono.CSharp {
                        return (op & Operator.EqualityMask) != 0 && (t == TypeManager.string_type || t == TypeManager.decimal_type);
                }
 
-               private static bool IsTypeIntegral (Type type)
+               private static bool IsTypeIntegral (TypeSpec type)
                {
                        return type == TypeManager.uint64_type ||
                                type == TypeManager.int64_type ||
@@ -3428,7 +3396,7 @@ namespace Mono.CSharp {
                                type == TypeManager.char_type;
                }
 
-               private static bool IsTypeUnsigned (Type type)
+               private static bool IsTypeUnsigned (TypeSpec type)
                {
                        return type == TypeManager.uint64_type ||
                                type == TypeManager.uint32_type ||
@@ -3437,7 +3405,7 @@ namespace Mono.CSharp {
                                type == TypeManager.char_type;
                }
 
-               private void WarnUselessComparison (ResolveContext ec, Type type)
+               private void WarnUselessComparison (ResolveContext ec, TypeSpec type)
                {
                        ec.Report.Warning (652, 2, loc, "A comparison between a constant and a variable is useless. The constant is out of the range of the variable type `{0}'",
                                TypeManager.CSharpName (type));
@@ -3453,8 +3421,6 @@ namespace Mono.CSharp {
                /// </remarks>
                public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
                {
-                       ILGenerator ig = ec.ig;
-
                        //
                        // This is more complicated than it looks, but its just to avoid
                        // duplicated tests: basically, we allow ==, !=, >, <, >= and <=
@@ -3486,11 +3452,11 @@ namespace Mono.CSharp {
                        } else if (oper == Operator.LogicalAnd) {
 
                                if (on_true) {
-                                       Label tests_end = ig.DefineLabel ();
+                                       Label tests_end = ec.DefineLabel ();
                                        
                                        left.EmitBranchable (ec, tests_end, false);
                                        right.EmitBranchable (ec, target, true);
-                                       ig.MarkLabel (tests_end);                                       
+                                       ec.MarkLabel (tests_end);                                       
                                } else {
                                        //
                                        // This optimizes code like this 
@@ -3511,10 +3477,10 @@ namespace Mono.CSharp {
                                        right.EmitBranchable (ec, target, true);
                                        
                                } else {
-                                       Label tests_end = ig.DefineLabel ();
+                                       Label tests_end = ec.DefineLabel ();
                                        left.EmitBranchable (ec, tests_end, true);
                                        right.EmitBranchable (ec, target, false);
-                                       ig.MarkLabel (tests_end);
+                                       ec.MarkLabel (tests_end);
                                }
                                
                                return;
@@ -3529,76 +3495,76 @@ namespace Mono.CSharp {
                        left.Emit (ec);
                        right.Emit (ec);
 
-                       Type t = left.Type;
+                       TypeSpec t = left.Type;
                        bool is_float = IsFloat (t);
                        bool is_unsigned = is_float || IsUnsigned (t);
                        
                        switch (oper){
                        case Operator.Equality:
                                if (on_true)
-                                       ig.Emit (OpCodes.Beq, target);
+                                       ec.Emit (OpCodes.Beq, target);
                                else
-                                       ig.Emit (OpCodes.Bne_Un, target);
+                                       ec.Emit (OpCodes.Bne_Un, target);
                                break;
 
                        case Operator.Inequality:
                                if (on_true)
-                                       ig.Emit (OpCodes.Bne_Un, target);
+                                       ec.Emit (OpCodes.Bne_Un, target);
                                else
-                                       ig.Emit (OpCodes.Beq, target);
+                                       ec.Emit (OpCodes.Beq, target);
                                break;
 
                        case Operator.LessThan:
                                if (on_true)
                                        if (is_unsigned && !is_float)
-                                               ig.Emit (OpCodes.Blt_Un, target);
+                                               ec.Emit (OpCodes.Blt_Un, target);
                                        else
-                                               ig.Emit (OpCodes.Blt, target);
+                                               ec.Emit (OpCodes.Blt, target);
                                else
                                        if (is_unsigned)
-                                               ig.Emit (OpCodes.Bge_Un, target);
+                                               ec.Emit (OpCodes.Bge_Un, target);
                                        else
-                                               ig.Emit (OpCodes.Bge, target);
+                                               ec.Emit (OpCodes.Bge, target);
                                break;
 
                        case Operator.GreaterThan:
                                if (on_true)
                                        if (is_unsigned && !is_float)
-                                               ig.Emit (OpCodes.Bgt_Un, target);
+                                               ec.Emit (OpCodes.Bgt_Un, target);
                                        else
-                                               ig.Emit (OpCodes.Bgt, target);
+                                               ec.Emit (OpCodes.Bgt, target);
                                else
                                        if (is_unsigned)
-                                               ig.Emit (OpCodes.Ble_Un, target);
+                                               ec.Emit (OpCodes.Ble_Un, target);
                                        else
-                                               ig.Emit (OpCodes.Ble, target);
+                                               ec.Emit (OpCodes.Ble, target);
                                break;
 
                        case Operator.LessThanOrEqual:
                                if (on_true)
                                        if (is_unsigned && !is_float)
-                                               ig.Emit (OpCodes.Ble_Un, target);
+                                               ec.Emit (OpCodes.Ble_Un, target);
                                        else
-                                               ig.Emit (OpCodes.Ble, target);
+                                               ec.Emit (OpCodes.Ble, target);
                                else
                                        if (is_unsigned)
-                                               ig.Emit (OpCodes.Bgt_Un, target);
+                                               ec.Emit (OpCodes.Bgt_Un, target);
                                        else
-                                               ig.Emit (OpCodes.Bgt, target);
+                                               ec.Emit (OpCodes.Bgt, target);
                                break;
 
 
                        case Operator.GreaterThanOrEqual:
                                if (on_true)
                                        if (is_unsigned && !is_float)
-                                               ig.Emit (OpCodes.Bge_Un, target);
+                                               ec.Emit (OpCodes.Bge_Un, target);
                                        else
-                                               ig.Emit (OpCodes.Bge, target);
+                                               ec.Emit (OpCodes.Bge, target);
                                else
                                        if (is_unsigned)
-                                               ig.Emit (OpCodes.Blt_Un, target);
+                                               ec.Emit (OpCodes.Blt_Un, target);
                                        else
-                                               ig.Emit (OpCodes.Blt, target);
+                                               ec.Emit (OpCodes.Blt, target);
                                break;
                        default:
                                throw new InternalErrorException (oper.ToString ());
@@ -3610,26 +3576,24 @@ namespace Mono.CSharp {
                        EmitOperator (ec, left.Type);
                }
 
-               protected virtual void EmitOperator (EmitContext ec, Type l)
+               protected virtual void EmitOperator (EmitContext ec, TypeSpec l)
                {
-                       ILGenerator ig = ec.ig;
-
                        //
                        // Handle short-circuit operators differently
                        // than the rest
                        //
                        if ((oper & Operator.LogicalMask) != 0) {
-                               Label load_result = ig.DefineLabel ();
-                               Label end = ig.DefineLabel ();
+                               Label load_result = ec.DefineLabel ();
+                               Label end = ec.DefineLabel ();
 
                                bool is_or = oper == Operator.LogicalOr;
                                left.EmitBranchable (ec, load_result, is_or);
                                right.Emit (ec);
-                               ig.Emit (OpCodes.Br_S, end);
+                               ec.Emit (OpCodes.Br_S, end);
                                
-                               ig.MarkLabel (load_result);
-                               ig.Emit (is_or ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
-                               ig.MarkLabel (end);
+                               ec.MarkLabel (load_result);
+                               ec.Emit (is_or ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
+                               ec.MarkLabel (end);
                                return;
                        }
 
@@ -3640,7 +3604,7 @@ namespace Mono.CSharp {
                                var lc = left as IntegralConstant;
                                if (lc != null && lc.IsDefaultValue) {
                                        right.Emit (ec);
-                                       ig.Emit (OpCodes.Neg);
+                                       ec.Emit (OpCodes.Neg);
                                        return;
                                }
                        }
@@ -3915,14 +3879,9 @@ namespace Mono.CSharp {
                        if (arguments.Count != 2)
                                throw new NotImplementedException ("arguments.Count != 2");
 
-                       var concat = TypeManager.string_type.GetMethod ("Concat", new[] { typeof (object), typeof (object) });
+                       var concat = typeof (string).GetMethod ("Concat", new[] { typeof (object), typeof (object) });
                        return SLE.Expression.Add (arguments[0].Expr.MakeExpression (ctx), arguments[1].Expr.MakeExpression (ctx), concat);
                }
-               
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       arguments.MutateHoistedGenericType (storey);
-               }               
        }
 
        //
@@ -3943,12 +3902,12 @@ namespace Mono.CSharp {
                protected override Expression DoResolve (ResolveContext ec)
                {
                        var method = mg.BestCandidate;
-                       type = TypeManager.TypeToCoreType (method.ReturnType);
+                       type = method.ReturnType;
                        AParametersCollection pd = method.Parameters;
                        if (!TypeManager.IsEqual (type, type) || !TypeManager.IsEqual (type, pd.Types [0]) || !TypeManager.IsEqual (type, pd.Types [1])) {
                                ec.Report.Error (217, loc,
                                        "A user-defined operator `{0}' must have parameters and return values of the same type in order to be applicable as a short circuit operator",
-                                       TypeManager.CSharpSignature (method.MetaInfo));
+                                       TypeManager.CSharpSignature (method));
                                return null;
                        }
 
@@ -3958,7 +3917,7 @@ namespace Mono.CSharp {
                        if (op_true == null || op_false == null) {
                                ec.Report.Error (218, loc,
                                        "The type `{0}' must have operator `true' and operator `false' defined when `{1}' is used as a short circuit operator",
-                                       TypeManager.CSharpName (type), TypeManager.CSharpSignature (method.MetaInfo));
+                                       TypeManager.CSharpName (type), TypeManager.CSharpSignature (method));
                                return null;
                        }
 
@@ -3969,19 +3928,18 @@ namespace Mono.CSharp {
 
                public override void Emit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-                       Label end_target = ig.DefineLabel ();
+                       Label end_target = ec.DefineLabel ();
 
                        //
                        // Emit and duplicate left argument
                        //
                        arguments [0].Expr.Emit (ec);
-                       ig.Emit (OpCodes.Dup);
+                       ec.Emit (OpCodes.Dup);
                        arguments.RemoveAt (0);
 
                        oper.EmitBranchable (ec, end_target, true);
                        base.Emit (ec);
-                       ig.MarkLabel (end_target);
+                       ec.MarkLabel (end_target);
                }
        }
 
@@ -3992,7 +3950,7 @@ namespace Mono.CSharp {
                //
                // We assume that `l' is always a pointer
                //
-               public PointerArithmetic (Binary.Operator op, Expression l, Expression r, Type t, Location loc)
+               public PointerArithmetic (Binary.Operator op, Expression l, Expression r, TypeSpec t, Location loc)
                {
                        type = t;
                        this.loc = loc;
@@ -4021,11 +3979,10 @@ namespace Mono.CSharp {
 
                public override void Emit (EmitContext ec)
                {
-                       Type op_type = left.Type;
-                       ILGenerator ig = ec.ig;
+                       TypeSpec op_type = left.Type;
                        
                        // It must be either array or fixed buffer
-                       Type element;
+                       TypeSpec element;
                        if (TypeManager.HasElementType (op_type)) {
                                element = TypeManager.GetElementType (op_type);
                        } else {
@@ -4037,7 +3994,7 @@ namespace Mono.CSharp {
                        }
 
                        int size = GetTypeSize (element);
-                       Type rtype = right.Type;
+                       TypeSpec rtype = right.Type;
                        
                        if ((op & Binary.Operator.SubtractionMask) != 0 && rtype.IsPointer){
                                //
@@ -4045,16 +4002,16 @@ namespace Mono.CSharp {
                                //
                                left.Emit (ec);
                                right.Emit (ec);
-                               ig.Emit (OpCodes.Sub);
+                               ec.Emit (OpCodes.Sub);
 
                                if (size != 1){
                                        if (size == 0)
-                                               ig.Emit (OpCodes.Sizeof, element);
+                                               ec.Emit (OpCodes.Sizeof, element);
                                        else 
-                                               IntLiteral.EmitInt (ig, size);
-                                       ig.Emit (OpCodes.Div);
+                                               ec.EmitInt (size);
+                                       ec.Emit (OpCodes.Div);
                                }
-                               ig.Emit (OpCodes.Conv_I8);
+                               ec.Emit (OpCodes.Conv_I8);
                        } else {
                                //
                                // handle + and - on (pointer op int)
@@ -4096,27 +4053,27 @@ namespace Mono.CSharp {
                                right.Emit (ec);
                                if (rtype == TypeManager.sbyte_type || rtype == TypeManager.byte_type ||
                                        rtype == TypeManager.short_type || rtype == TypeManager.ushort_type) {
-                                       ig.Emit (OpCodes.Conv_I);
+                                       ec.Emit (OpCodes.Conv_I);
                                } else if (rtype == TypeManager.uint32_type) {
-                                       ig.Emit (OpCodes.Conv_U);
+                                       ec.Emit (OpCodes.Conv_U);
                                }
 
                                if (right_const == null && size != 1){
                                        if (size == 0)
-                                               ig.Emit (OpCodes.Sizeof, element);
+                                               ec.Emit (OpCodes.Sizeof, element);
                                        else 
-                                               IntLiteral.EmitInt (ig, size);
+                                               ec.EmitInt (size);
                                        if (rtype == TypeManager.int64_type || rtype == TypeManager.uint64_type)
-                                               ig.Emit (OpCodes.Conv_I8);
+                                               ec.Emit (OpCodes.Conv_I8);
 
                                        Binary.EmitOperatorOpcode (ec, Binary.Operator.Multiply, rtype);
                                }
 
                                if (left_const == null) {
                                        if (rtype == TypeManager.int64_type)
-                                               ig.Emit (OpCodes.Conv_I);
+                                               ec.Emit (OpCodes.Conv_I);
                                        else if (rtype == TypeManager.uint64_type)
-                                               ig.Emit (OpCodes.Conv_U);
+                                               ec.Emit (OpCodes.Conv_U);
 
                                        Binary.EmitOperatorOpcode (ec, op, op_type);
                                }
@@ -4162,7 +4119,7 @@ namespace Mono.CSharp {
                        if (expr.Type == TypeManager.bool_type)
                                return expr;
 
-                       if (TypeManager.IsDynamicType (expr.Type)) {
+                       if (expr.Type == InternalType.Dynamic) {
                                Arguments args = new Arguments (1);
                                args.Add (new Argument (expr));
                                return new DynamicUnaryConversion ("IsTrue", args, loc).Resolve (ec);
@@ -4237,8 +4194,8 @@ namespace Mono.CSharp {
                                return null;
 
                        eclass = ExprClass.Value;
-                       Type true_type = true_expr.Type;
-                       Type false_type = false_expr.Type;
+                       TypeSpec true_type = true_expr.Type;
+                       TypeSpec false_type = false_expr.Type;
                        type = true_type;
 
                        //
@@ -4280,14 +4237,6 @@ namespace Mono.CSharp {
                        return this;
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       expr.MutateHoistedGenericType (storey);
-                       true_expr.MutateHoistedGenericType (storey);
-                       false_expr.MutateHoistedGenericType (storey);
-                       type = storey.MutateType (type);
-               }
-
                public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
                {
                        return null;
@@ -4295,24 +4244,23 @@ namespace Mono.CSharp {
 
                public override void Emit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-                       Label false_target = ig.DefineLabel ();
-                       Label end_target = ig.DefineLabel ();
+                       Label false_target = ec.DefineLabel ();
+                       Label end_target = ec.DefineLabel ();
 
                        expr.EmitBranchable (ec, false_target, false);
                        true_expr.Emit (ec);
 
                        if (type.IsInterface) {
                                LocalBuilder temp = ec.GetTemporaryLocal (type);
-                               ig.Emit (OpCodes.Stloc, temp);
-                               ig.Emit (OpCodes.Ldloc, temp);
+                               ec.Emit (OpCodes.Stloc, temp);
+                               ec.Emit (OpCodes.Ldloc, temp);
                                ec.FreeTemporaryLocal (temp, type);
                        }
 
-                       ig.Emit (OpCodes.Br, end_target);
-                       ig.MarkLabel (false_target);
+                       ec.Emit (OpCodes.Br, end_target);
+                       ec.MarkLabel (false_target);
                        false_expr.Emit (ec);
-                       ig.MarkLabel (end_target);
+                       ec.MarkLabel (end_target);
                }
 
                protected override void CloneTo (CloneContext clonectx, Expression t)
@@ -4410,11 +4358,11 @@ namespace Mono.CSharp {
                                // If we are a reference, we loaded on the stack a pointer
                                // Now lets load the real value
                                //
-                               LoadFromPtr (ec.ig, type);
+                               ec.EmitLoadFromPtr (type);
                        }
 
                        if (leave_copy) {
-                               ec.ig.Emit (OpCodes.Dup);
+                               ec.Emit (OpCodes.Dup);
 
                                if (IsRef) {
                                        temp = new LocalTemporary (Type);
@@ -4447,7 +4395,7 @@ namespace Mono.CSharp {
                        }
 
                        if (leave_copy) {
-                               ec.ig.Emit (OpCodes.Dup);
+                               ec.Emit (OpCodes.Dup);
                                if (IsRef) {
                                        temp = new LocalTemporary (Type);
                                        temp.Store (ec);
@@ -4455,7 +4403,7 @@ namespace Mono.CSharp {
                        }
 
                        if (IsRef)
-                               StoreFromPtr (ec.ig, type);
+                               ec.EmitStoreFromPtr (type);
                        else
                                Variable.EmitAssign (ec);
 
@@ -4468,11 +4416,6 @@ namespace Mono.CSharp {
                public bool IsHoisted {
                        get { return GetHoistedVariable ((AnonymousExpression) null) != null; }
                }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       type = storey.MutateType (type);
-               }
        }
 
        /// <summary>
@@ -4877,18 +4820,18 @@ namespace Mono.CSharp {
                        return this;
                }
 
-               static public void EmitLdArg (ILGenerator ig, int x)
+               static public void EmitLdArg (EmitContext ec, int x)
                {
                        switch (x) {
-                       case 0: ig.Emit (OpCodes.Ldarg_0); break;
-                       case 1: ig.Emit (OpCodes.Ldarg_1); break;
-                       case 2: ig.Emit (OpCodes.Ldarg_2); break;
-                       case 3: ig.Emit (OpCodes.Ldarg_3); break;
+                       case 0: ec.Emit (OpCodes.Ldarg_0); break;
+                       case 1: ec.Emit (OpCodes.Ldarg_1); break;
+                       case 2: ec.Emit (OpCodes.Ldarg_2); break;
+                       case 3: ec.Emit (OpCodes.Ldarg_3); break;
                        default:
                                if (x > byte.MaxValue)
-                                       ig.Emit (OpCodes.Ldarg, x);
+                                       ec.Emit (OpCodes.Ldarg, x);
                                else
-                                       ig.Emit (OpCodes.Ldarg_S, (byte) x);
+                                       ec.Emit (OpCodes.Ldarg_S, (byte) x);
                                break;
                        }
                }
@@ -4956,10 +4899,10 @@ namespace Mono.CSharp {
                        if (arguments != null && !arguments_resolved)
                                arguments.Resolve (ec, out dynamic_arg);
 
-                       Type expr_type = member_expr.Type;
+                       TypeSpec expr_type = member_expr.Type;
                        mg = member_expr as MethodGroupExpr;
 
-                       bool dynamic_member = TypeManager.IsDynamicType (expr_type);
+                       bool dynamic_member = expr_type == InternalType.Dynamic;
 
                        if (!dynamic_member) {
                                Expression invoke = null;
@@ -4977,7 +4920,7 @@ namespace Mono.CSharp {
                                                        return null;
                                                }
 
-                                               mg = ec.LookupExtensionMethod (me.Type, me.Name, loc);
+                                               mg = ec.LookupExtensionMethod (me.Type, me.Name, -1, loc);
                                                if (mg == null) {
                                                        ec.Report.Error (1955, loc, "The member `{0}' cannot be used as method or delegate",
                                                                member_expr.GetSignatureForError ());
@@ -5000,7 +4943,7 @@ namespace Mono.CSharp {
 
                        var method = mg.BestCandidate;
                        if (method != null) {
-                               type = TypeManager.TypeToCoreType (method.ReturnType);
+                               type = method.ReturnType;
 
                                // TODO: this is a copy of mg.ResolveMemberAccess method
                                Expression iexpr = mg.InstanceExpression;
@@ -5097,15 +5040,15 @@ namespace Mono.CSharp {
 
                public static bool IsSpecialMethodInvocation (ResolveContext ec, MethodSpec method, Location loc)
                {
-                       if (!TypeManager.IsSpecialMethod (method.MetaInfo))
+                       if (!method.IsReservedMethod)
                                return false;
 
                        if (ec.HasSet (ResolveContext.Options.InvokeSpecialName))
                                return false;
 
-                       ec.Report.SymbolRelatedToPreviousError (method.MetaInfo);
+                       ec.Report.SymbolRelatedToPreviousError (method);
                        ec.Report.Error (571, loc, "`{0}': cannot explicitly call operator or accessor",
-                               TypeManager.CSharpSignature (method.MetaInfo, true));
+                               method.GetSignatureForError ());
        
                        return true;
                }
@@ -5120,28 +5063,6 @@ namespace Mono.CSharp {
                        return list.ArgumentTypes;
                }
 
-               /// <summary>
-               /// This checks the ConditionalAttribute on the method 
-               /// </summary>
-               public static bool IsMethodExcluded (MethodSpec method, Location loc)
-               {
-                       if (method.IsConstructor)
-                               return false;
-
-                       var mb = TypeManager.DropGenericMethodArguments (method.MetaInfo);
-                       if (TypeManager.IsBeingCompiled (mb)) {
-                               IMethodData md = TypeManager.GetMethod (mb);
-                               if (md != null)
-                                       return md.IsExcluded ();
-
-                               // For some methods (generated by delegate class) GetMethod returns null
-                               // because they are not included in builder_to_method table
-                               return false;
-                       }
-
-                       return AttributeTester.IsConditionalMethodExcluded (mb, loc);
-               }
-
                /// <remarks>
                ///   is_base tells whether we want to force the use of the `call'
                ///   opcode instead of using callvirt.  Call is required to call
@@ -5175,14 +5096,14 @@ namespace Mono.CSharp {
                                             MethodSpec method, Arguments Arguments, Location loc,
                                             bool dup_args, bool omit_args)
                {
-                       ILGenerator ig = ec.ig;
                        bool struct_call = false;
                        bool this_call = false;
                        LocalTemporary this_arg = null;
 
-                       Type decl_type = method.DeclaringType;
+                       TypeSpec decl_type = method.DeclaringType;
 
-                       if (IsMethodExcluded (method, loc))
+                       // Speed up the check by not doing it on not allowed targets
+                       if (method.ReturnType == TypeManager.void_type && method.IsConditionallyExcluded (loc))
                                return;
                        
                        bool is_static = method.IsStatic;
@@ -5195,8 +5116,8 @@ namespace Mono.CSharp {
                                // If this is ourselves, push "this"
                                //
                                if (!omit_args) {
-                                       Type t = null;
-                                       Type iexpr_type = instance_expr.Type;
+                                       TypeSpec t = null;
+                                       TypeSpec iexpr_type = instance_expr.Type;
 
                                        //
                                        // Push the instance expression
@@ -5227,13 +5148,13 @@ namespace Mono.CSharp {
 
                                                        // avoid the overhead of doing this all the time.
                                                        if (dup_args)
-                                                               t = TypeManager.GetReferenceType (iexpr_type);
+                                                               t = ReferenceContainer.MakeType (iexpr_type);
                                                } else {
                                                        instance_expr.Emit (ec);
                                                        
                                                        // FIXME: should use instance_expr is IMemoryLocation + constraint.
                                                        // to help JIT to produce better code
-                                                       ig.Emit (OpCodes.Box, instance_expr.Type);
+                                                       ec.Emit (OpCodes.Box, instance_expr.Type);
                                                        t = TypeManager.object_type;
                                                }
                                        } else {
@@ -5242,7 +5163,7 @@ namespace Mono.CSharp {
                                        }
 
                                        if (dup_args) {
-                                               ig.Emit (OpCodes.Dup);
+                                               ec.Emit (OpCodes.Dup);
                                                if (Arguments != null && Arguments.Count != 0) {
                                                        this_arg = new LocalTemporary (t);
                                                        this_arg.Store (ec);
@@ -5261,12 +5182,12 @@ namespace Mono.CSharp {
                                call_op = OpCodes.Callvirt;
                                
                                if ((instance_expr != null) && (instance_expr.Type.IsGenericParameter))
-                                       ig.Emit (OpCodes.Constrained, instance_expr.Type);
+                                       ec.Emit (OpCodes.Constrained, instance_expr.Type);
                        }
 
-                       if ((method.MetaInfo.CallingConvention & CallingConventions.VarArgs) != 0) {
+                       if (method.Parameters.HasArglist) {
                                Type[] varargs_types = GetVarargsTypes (method, Arguments);
-                               ig.EmitCall (call_op, (MethodInfo) method.MetaInfo, varargs_types);
+                               ec.Emit (call_op, method, varargs_types);
                                return;
                        }
 
@@ -5276,10 +5197,7 @@ namespace Mono.CSharp {
                        // and DoFoo is not virtual, you can omit the callvirt,
                        // because you don't need the null checking behavior.
                        //
-                       if (method.IsConstructor)
-                               ig.Emit (call_op, (ConstructorInfo) method.MetaInfo);
-                       else
-                               ig.Emit (call_op, (MethodInfo) method.MetaInfo);
+                       ec.Emit (call_op, method);
                }
 
                public override void Emit (EmitContext ec)
@@ -5294,8 +5212,8 @@ namespace Mono.CSharp {
                        // 
                        // Pop the return value if there is one
                        //
-                       if (TypeManager.TypeToCoreType (type) != TypeManager.void_type)
-                               ec.ig.Emit (OpCodes.Pop);
+                       if (type != TypeManager.void_type)
+                               ec.Emit (OpCodes.Pop);
                }
 
                protected override void CloneTo (CloneContext clonectx, Expression t)
@@ -5316,16 +5234,7 @@ namespace Mono.CSharp {
                public static SLE.Expression MakeExpression (BuilderContext ctx, Expression instance, MethodSpec mi, Arguments args)
                {
                        var instance_expr = instance == null ? null : instance.MakeExpression (ctx);
-                       return SLE.Expression.Call (instance_expr, (MethodInfo) mi.MetaInfo, Arguments.MakeExpression (args, ctx));
-               }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       mg.MutateHoistedGenericType (storey);
-                       type = storey.MutateType (type);
-                       if (arguments != null) {
-                               arguments.MutateHoistedGenericType (storey);
-                       }
+                       return SLE.Expression.Call (instance_expr, (MethodInfo) mi.GetMetaInfo (), Arguments.MakeExpression (args, ctx));
                }
        }
 
@@ -5344,8 +5253,6 @@ namespace Mono.CSharp {
 
                protected MethodGroupExpr method;
 
-               bool is_type_parameter;
-
                public New (Expression requested_type, Arguments arguments, Location l)
                {
                        RequestedType = requested_type;
@@ -5356,7 +5263,7 @@ namespace Mono.CSharp {
                /// <summary>
                /// Converts complex core type syntax like 'new int ()' to simple constant
                /// </summary>
-               public static Constant Constantify (Type t)
+               public static Constant Constantify (TypeSpec t)
                {
                        if (t == TypeManager.int32_type)
                                return new IntConstant (0, Location.Null);
@@ -5385,7 +5292,7 @@ namespace Mono.CSharp {
                        if (t == TypeManager.decimal_type)
                                return new DecimalConstant (0, Location.Null);
                        if (TypeManager.IsEnumType (t))
-                               return new EnumConstant (Constantify (TypeManager.GetEnumUnderlyingType (t)), t);
+                               return new EnumConstant (Constantify (EnumSpec.GetUnderlyingType (t)), t);
                        if (TypeManager.IsNullableType (t))
                                return Nullable.LiftedNull.Create (t, Location.Null);
 
@@ -5406,7 +5313,7 @@ namespace Mono.CSharp {
                        // Turn the call into:
                        // (the-interface-stated) (new class-referenced-in-coclassattribute ())
                        //
-                       Type real_class = AttributeTester.GetCoClassAttribute (type);
+                       var real_class = type.MemberDefinition.GetAttributeCoClass ();
                        if (real_class == null)
                                return null;
 
@@ -5468,37 +5375,33 @@ namespace Mono.CSharp {
                                return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
                        }
 
-                       if (TypeManager.IsGenericParameter (type)) {
-                               GenericConstraints gc = TypeManager.GetTypeParameterConstraints (type);
-
-                               if ((gc == null) || (!gc.HasConstructorConstraint && !gc.IsValueType)) {
+                       var tparam = type as TypeParameterSpec;
+                       if (tparam != null) {
+                               if (!tparam.HasSpecialConstructor && !tparam.HasSpecialStruct) {
                                        ec.Report.Error (304, loc,
-                                               "Cannot create an instance of the variable type '{0}' because it doesn't have the new() constraint",
+                                               "Cannot create an instance of the variable type `{0}' because it does not have the new() constraint",
                                                TypeManager.CSharpName (type));
-                                       return null;
                                }
 
                                if ((Arguments != null) && (Arguments.Count != 0)) {
                                        ec.Report.Error (417, loc,
                                                "`{0}': cannot provide arguments when creating an instance of a variable type",
                                                TypeManager.CSharpName (type));
-                                       return null;
                                }
 
                                if (TypeManager.activator_create_instance == null) {
-                                       Type activator_type = TypeManager.CoreLookupType (ec.Compiler, "System", "Activator", MemberKind.Class, true);
+                                       TypeSpec activator_type = TypeManager.CoreLookupType (ec.Compiler, "System", "Activator", MemberKind.Class, true);
                                        if (activator_type != null) {
                                                TypeManager.activator_create_instance = TypeManager.GetPredefinedMethod (
-                                                       activator_type, "CreateInstance", loc, Type.EmptyTypes);
+                                                       activator_type, MemberFilter.Method ("CreateInstance", 1, ParametersCompiled.EmptyReadOnlyParameters, null), loc);
                                        }
                                }
 
-                               is_type_parameter = true;
                                eclass = ExprClass.Value;
                                return this;
                        }
 
-                       if (type.IsAbstract && type.IsSealed) {
+                       if (type.IsStatic) {
                                ec.Report.SymbolRelatedToPreviousError (type);
                                ec.Report.Error (712, loc, "Cannot create an instance of the static class `{0}'", TypeManager.CSharpName (type));
                                return null;
@@ -5527,8 +5430,8 @@ namespace Mono.CSharp {
                                return this;
 
                        // For member-lookup, treat 'new Foo (bar)' as call to 'foo.ctor (bar)', where 'foo' is of type 'Foo'.
-                       Expression ml = MemberLookupFinal (ec, type, type, ConstructorInfo.ConstructorName,
-                               MemberTypes.Constructor, AllBindingFlags | BindingFlags.DeclaredOnly, loc);
+                       Expression ml = MemberLookupFinal (ec, type, type, ConstructorInfo.ConstructorName, 0,
+                               MemberKind.Constructor, BindingRestriction.AccessibleOnly | BindingRestriction.DeclaredOnly, loc);
 
                        bool dynamic;
                        if (Arguments != null) {
@@ -5560,14 +5463,11 @@ namespace Mono.CSharp {
 
                bool DoEmitTypeParameter (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
+                       var ctor_factory = TypeManager.activator_create_instance.MakeGenericMethod (type);
+                       var tparam = (TypeParameterSpec) type;
 
-                       MethodInfo ci = (MethodInfo) TypeManager.activator_create_instance.MetaInfo;
-                       ci = ci.MakeGenericMethod (new Type [] { type });
-
-                       GenericConstraints gc = TypeManager.GetTypeParameterConstraints (type);
-                       if (gc.HasReferenceTypeConstraint || gc.HasClassConstraint) {
-                               ig.Emit (OpCodes.Call, ci);
+                       if (tparam.IsReferenceType) {
+                               ec.Emit (OpCodes.Call, ctor_factory);
                                return true;
                        }
 
@@ -5576,25 +5476,25 @@ namespace Mono.CSharp {
                        // you can't share LocalBuilders among ILGeneators.
                        LocalTemporary temp = new LocalTemporary (type);
 
-                       Label label_activator = ig.DefineLabel ();
-                       Label label_end = ig.DefineLabel ();
+                       Label label_activator = ec.DefineLabel ();
+                       Label label_end = ec.DefineLabel ();
 
                        temp.AddressOf (ec, AddressOp.Store);
-                       ig.Emit (OpCodes.Initobj, type);
+                       ec.Emit (OpCodes.Initobj, type);
 
                        temp.Emit (ec);
-                       ig.Emit (OpCodes.Box, type);
-                       ig.Emit (OpCodes.Brfalse, label_activator);
+                       ec.Emit (OpCodes.Box, type);
+                       ec.Emit (OpCodes.Brfalse, label_activator);
 
                        temp.AddressOf (ec, AddressOp.Store);
-                       ig.Emit (OpCodes.Initobj, type);
+                       ec.Emit (OpCodes.Initobj, type);
                        temp.Emit (ec);
-                       ig.Emit (OpCodes.Br_S, label_end);
+                       ec.Emit (OpCodes.Br_S, label_end);
 
-                       ig.MarkLabel (label_activator);
+                       ec.MarkLabel (label_activator);
 
-                       ig.Emit (OpCodes.Call, ci);
-                       ig.MarkLabel (label_end);
+                       ec.Emit (OpCodes.Call, ctor_factory);
+                       ec.MarkLabel (label_end);
                        return true;
                }
 
@@ -5628,7 +5528,6 @@ namespace Mono.CSharp {
                public virtual bool Emit (EmitContext ec, IMemoryLocation target)
                {
                        bool is_value_type = TypeManager.IsValueType (type);
-                       ILGenerator ig = ec.ig;
                        VariableReference vr = target as VariableReference;
 
                        if (target != null && is_value_type && (vr != null || method == null)) {
@@ -5642,26 +5541,20 @@ namespace Mono.CSharp {
 
                        if (is_value_type) {
                                if (method == null) {
-                                       ig.Emit (OpCodes.Initobj, type);
+                                       ec.Emit (OpCodes.Initobj, type);
                                        return false;
                                }
 
                                if (vr != null) {
-                                       ig.Emit (OpCodes.Call, (ConstructorInfo) method.BestCandidate.MetaInfo);
+                                       ec.Emit (OpCodes.Call, method.BestCandidate);
                                        return false;
                                }
                        }
                        
-                       if (is_type_parameter)
+                       if (type is TypeParameterSpec)
                                return DoEmitTypeParameter (ec);                        
 
-                       ConstructorInfo ci = (ConstructorInfo) method.BestCandidate.MetaInfo;
-#if MS_COMPATIBLE
-                       if (TypeManager.IsGenericType (type) && type.IsGenericTypeDefinition)
-                               ci = TypeBuilder.GetConstructor (type, ci);
-#endif
-
-                       ig.Emit (OpCodes.Newobj, ci);
+                       ec.Emit (OpCodes.Newobj, method.BestCandidate);
                        return true;
                }
 
@@ -5686,7 +5579,7 @@ namespace Mono.CSharp {
                        }
 
                        if (Emit (ec, v))
-                               ec.ig.Emit (OpCodes.Pop);
+                               ec.Emit (OpCodes.Pop);
                }
 
                public virtual bool HasInitializer {
@@ -5704,7 +5597,7 @@ namespace Mono.CSharp {
                {
                        LocalTemporary value_target = new LocalTemporary (type);
 
-                       if (is_type_parameter) {
+                       if (type is TypeParameterSpec) {
                                DoEmitTypeParameter (ec);
                                value_target.Store (ec);
                                value_target.AddressOf (ec, mode);
@@ -5724,12 +5617,12 @@ namespace Mono.CSharp {
                        value_target.AddressOf (ec, AddressOp.Store);
 
                        if (method == null) {
-                               ec.ig.Emit (OpCodes.Initobj, type);
+                               ec.Emit (OpCodes.Initobj, type);
                        } else {
                                if (Arguments != null)
                                        Arguments.Emit (ec);
 
-                               ec.ig.Emit (OpCodes.Call, (ConstructorInfo) method.BestCandidate.MetaInfo);
+                               ec.Emit (OpCodes.Call, method.BestCandidate);
                        }
                        
                        value_target.AddressOf (ec, mode);
@@ -5748,19 +5641,7 @@ namespace Mono.CSharp {
 
                public override SLE.Expression MakeExpression (BuilderContext ctx)
                {
-                       return SLE.Expression.New ((ConstructorInfo) method.BestCandidate.MetaInfo, Arguments.MakeExpression (Arguments, ctx));
-               }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       if (method != null) {
-                               method.MutateHoistedGenericType (storey);
-                               if (Arguments != null) {
-                                       Arguments.MutateHoistedGenericType (storey);
-                               }
-                       }
-
-                       type = storey.MutateType (type);
+                       return SLE.Expression.New ((ConstructorInfo) method.BestCandidate.GetMetaInfo (), Arguments.MakeExpression (Arguments, ctx));
                }
        }
 
@@ -5836,7 +5717,7 @@ namespace Mono.CSharp {
                //
                protected List<Expression> arguments;
                
-               protected Type array_element_type;
+               protected TypeSpec array_element_type;
                bool expect_initializers = false;
                int num_arguments = 0;
                protected int dimensions;
@@ -5904,7 +5785,7 @@ namespace Mono.CSharp {
                                int value = (int) c.GetValue ();
                                
                                if (value != probe.Count) {
-                                       ec.Report.Error (847, loc, "An array initializer of length `{0}' was expected", value);
+                                       ec.Report.Error (847, loc, "An array initializer of length `{0}' was expected", value.ToString ());
                                        return false;
                                }
                                
@@ -5934,10 +5815,7 @@ namespace Mono.CSharp {
                                        // Initializers with the default values can be ignored
                                        Constant c = element as Constant;
                                        if (c != null) {
-                                               if (c.IsDefaultInitializer (array_element_type)) {
-                                                       element = null;
-                                               }
-                                               else {
+                                               if (!c.IsDefaultInitializer (array_element_type)) {
                                                        ++const_initializers_count;
                                                }
                                        } else {
@@ -5974,9 +5852,6 @@ namespace Mono.CSharp {
                        if (array_data != null) {
                                for (int i = 0; i < array_data.Count; ++i) {
                                        Expression e = array_data [i];
-                                       if (e == null)
-                                               e = Convert.ImplicitConversion (ec, initializers [i], array_element_type, loc);
-
                                        args.Add (new Argument (e.CreateExpressionTree (ec)));
                                }
                        }
@@ -6059,7 +5934,7 @@ namespace Mono.CSharp {
                                return false;
                        }
                        
-                       StringBuilder array_qualifier = new StringBuilder (rank);
+                       StringBuilder array_qualifier = new StringBuilder ();
 
                        //
                        // `In the first form allocates an array instace of the type that results
@@ -6072,6 +5947,8 @@ namespace Mono.CSharp {
                                array_qualifier.Append ("]");
                        }
 
+                       array_qualifier.Append (rank);
+
                        //
                        // Lookup the type
                        //
@@ -6082,13 +5959,14 @@ namespace Mono.CSharp {
                                return false;
 
                        type = array_type_expr.Type;
-                       if (!type.IsArray) {
+                       var ac = type as ArrayContainer;
+                       if (ac == null) {
                                ec.Report.Error (622, loc, "Can only use array initializer expressions to assign to array types. Try using a new expression instead");
                                return false;
                        }
 
-                       array_element_type = TypeManager.GetElementType (type);
-                       dimensions = type.GetArrayRank ();
+                       array_element_type = ac.Element;
+                       dimensions = ac.Rank;
 
                        return true;
                }
@@ -6120,26 +5998,6 @@ namespace Mono.CSharp {
                        return this;
                }
 
-               MethodInfo GetArrayMethod (EmitContext ec, int arguments)
-               {
-                       ModuleBuilder mb = RootContext.ToplevelTypes.Builder;
-
-                       Type[] arg_types = new Type[arguments];
-                       for (int i = 0; i < arguments; i++)
-                               arg_types[i] = TypeManager.int32_type;
-
-                       MethodInfo mi = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
-                                                       arg_types);
-
-                       if (mi == null) {
-                               ec.Report.Error (-6, "New invocation: Can not find a constructor for " +
-                                                 "this argument list");
-                               return null;
-                       }
-
-                       return mi; 
-               }
-
                byte [] MakeByteBlob ()
                {
                        int factor;
@@ -6147,9 +6005,9 @@ namespace Mono.CSharp {
                        byte [] element;
                        int count = array_data.Count;
 
-                       Type element_type = array_element_type;
+                       TypeSpec element_type = array_element_type;
                        if (TypeManager.IsEnumType (element_type))
-                               element_type = TypeManager.GetEnumUnderlyingType (element_type);
+                               element_type = EnumSpec.GetUnderlyingType (element_type);
 
                        factor = GetTypeSize (element_type);
                        if (factor == 0)
@@ -6298,35 +6156,14 @@ namespace Mono.CSharp {
                        var initializers = new SLE.Expression [array_data.Count];
                        for (var i = 0; i < initializers.Length; i++) {
                                if (array_data [i] == null)
-                                       initializers [i] = SLE.Expression.Default (array_element_type);
+                                       initializers [i] = SLE.Expression.Default (array_element_type.GetMetaInfo ());
                                else
                                        initializers [i] = array_data [i].MakeExpression (ctx);
                        }
 
-                       return SLE.Expression.NewArrayInit (array_element_type, initializers);
+                       return SLE.Expression.NewArrayInit (array_element_type.GetMetaInfo (), initializers);
                }
 #endif
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       array_element_type = storey.MutateType (array_element_type);
-                       type = storey.MutateType (type);
-                       if (arguments != null) {
-                               foreach (Expression e in arguments)
-                                       e.MutateHoistedGenericType (storey);
-                       }
-                       
-                       if (array_data != null) {
-                               foreach (Expression e in array_data) {
-                                       // Don't mutate values optimized away
-                                       if (e == null)
-                                               continue;
-
-                                       e.MutateHoistedGenericType (storey);
-                               }
-                       }
-               }
-
                //
                // Emits the initializers for the array
                //
@@ -6345,15 +6182,14 @@ namespace Mono.CSharp {
                        // First, the static data
                        //
                        FieldBuilder fb;
-                       ILGenerator ig = ec.ig;
                        
                        byte [] data = MakeByteBlob ();
 
                        fb = RootContext.MakeStaticData (data);
 
-                       ig.Emit (OpCodes.Dup);
-                       ig.Emit (OpCodes.Ldtoken, fb);
-                       ig.Emit (OpCodes.Call, (MethodInfo) TypeManager.void_initializearray_array_fieldhandle.MetaInfo);
+                       ec.Emit (OpCodes.Dup);
+                       ec.Emit (OpCodes.Ldtoken, fb);
+                       ec.Emit (OpCodes.Call, TypeManager.void_initializearray_array_fieldhandle);
                }
 
                //
@@ -6364,37 +6200,22 @@ namespace Mono.CSharp {
                //
                void EmitDynamicInitializers (EmitContext ec, bool emitConstants)
                {
-                       ILGenerator ig = ec.ig;
                        int dims = bounds.Count;
                        int [] current_pos = new int [dims];
 
-                       MethodInfo set = null;
-
-                       if (dims != 1){
-                               Type [] args = new Type [dims + 1];
-
-                               for (int j = 0; j < dims; j++)
-                                       args [j] = TypeManager.int32_type;
-                               args [dims] = array_element_type;
-
-                               set = RootContext.ToplevelTypes.Builder.GetArrayMethod (
-                                       type, "Set",
-                                       CallingConventions.HasThis | CallingConventions.Standard,
-                                       TypeManager.void_type, args);
-                       }
-
                        for (int i = 0; i < array_data.Count; i++){
 
                                Expression e = array_data [i];
+                               var c = e as Constant;
 
                                // Constant can be initialized via StaticInitializer
-                               if (e != null && !(!emitConstants && e is Constant)) {
-                                       Type etype = e.Type;
+                               if (c == null || (c != null && emitConstants && !c.IsDefaultInitializer (array_element_type))) {
+                                       TypeSpec etype = e.Type;
 
-                                       ig.Emit (OpCodes.Dup);
+                                       ec.Emit (OpCodes.Dup);
 
                                        for (int idx = 0; idx < dims; idx++) 
-                                               IntConstant.EmitInt (ig, current_pos [idx]);
+                                               ec.EmitInt (current_pos [idx]);
 
                                        //
                                        // If we are dealing with a struct, get the
@@ -6404,23 +6225,12 @@ namespace Mono.CSharp {
                                            (!TypeManager.IsBuiltinOrEnum (etype) ||
                                             etype == TypeManager.decimal_type)) {
 
-                                               ig.Emit (OpCodes.Ldelema, etype);
+                                               ec.Emit (OpCodes.Ldelema, etype);
                                        }
 
                                        e.Emit (ec);
 
-                                       if (dims == 1) {
-                                               bool is_stobj, has_type_arg;
-                                               OpCode op = ArrayAccess.GetStoreOpcode (etype, out is_stobj, out has_type_arg);
-                                               if (is_stobj)
-                                                       ig.Emit (OpCodes.Stobj, etype);
-                                               else if (has_type_arg)
-                                                       ig.Emit (op, etype);
-                                               else
-                                                       ig.Emit (op);
-                                       } else 
-                                               ig.Emit (OpCodes.Call, set);
-
+                                       ec.EmitArrayStore ((ArrayContainer) type);
                                }
                                
                                //
@@ -6437,8 +6247,6 @@ namespace Mono.CSharp {
 
                public override void Emit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-
                        if (first_emit != null) {
                                first_emit.Emit (ec);
                                first_emit_temp.Store (ec);
@@ -6447,11 +6255,7 @@ namespace Mono.CSharp {
                        foreach (Expression e in arguments)
                                e.Emit (ec);
 
-                       if (arguments.Count == 1)
-                               ig.Emit (OpCodes.Newarr, TypeManager.TypeToReflectionType (array_element_type));
-                       else {
-                               ig.Emit (OpCodes.Newobj, GetArrayMethod (ec, arguments.Count));
-                       }
+                       ec.EmitArrayNew ((ArrayContainer) type);
                        
                        if (initializers == null)
                                return;
@@ -6473,43 +6277,40 @@ namespace Mono.CSharp {
                                first_emit_temp.Release (ec);
                }
 
-               public override bool GetAttributableValue (ResolveContext ec, Type value_type, out object value)
+               public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
                {
-                       if (arguments.Count != 1) {
-                               // ec.Report.Error (-211, Location, "attribute can not encode multi-dimensional arrays");
-                               return base.GetAttributableValue (ec, null, out value);
+                       // no multi dimensional or jagged arrays
+                       if (arguments.Count != 1 || array_element_type.IsArray) {
+                               base.EncodeAttributeValue (rc, enc, targetType);
+                               return;
                        }
 
-                       if (array_data == null) {
-                               Expression arg = arguments [0];
-                               object arg_value;
-                               if (arg.GetAttributableValue (ec, arg.Type, out arg_value) && arg_value is int && (int)arg_value == 0) {
-                                       value = Array.CreateInstance (array_element_type, 0);
-                                       return true;
+                       // No array covariance, except for array -> object
+                       if (type != targetType) {
+                               if (targetType != TypeManager.object_type) {
+                                       base.EncodeAttributeValue (rc, enc, targetType);
+                                       return;
                                }
 
-                               // ec.Report.Error (-212, Location, "array should be initialized when passing it to an attribute");
-                               return base.GetAttributableValue (ec, null, out value);
+                               enc.Encode (type);
                        }
-                       
-                       Array ret = Array.CreateInstance (array_element_type, array_data.Count);
-                       object element_value;
-                       for (int i = 0; i < ret.Length; ++i)
-                       {
-                               Expression e = array_data [i];
-
-                               // Is null when an initializer is optimized (value == predefined value)
-                               if (e == null) 
-                                       continue;
 
-                               if (!e.GetAttributableValue (ec, array_element_type, out element_value)) {
-                                       value = null;
-                                       return false;
+                       // Single dimensional array of 0 size
+                       if (array_data == null) {
+                               IntConstant ic = arguments[0] as IntConstant;
+                               if (ic == null || !ic.IsDefaultValue) {
+                                       base.EncodeAttributeValue (rc, enc, targetType);
+                               } else {
+                                       enc.Stream.Write (0);
                                }
-                               ret.SetValue (element_value, i);
+
+                               return;
+                       }
+
+                       enc.Stream.Write ((int) array_data.Count);
+                       foreach (var element in array_data) {
+                               element.EncodeAttributeValue (rc, enc, array_element_type);
                        }
-                       value = ret;
-                       return true;
                }
                
                protected override void CloneTo (CloneContext clonectx, Expression t)
@@ -6627,7 +6428,7 @@ namespace Mono.CSharp {
                {
                }
 
-               public CompilerGeneratedThis (Type type, Location loc)
+               public CompilerGeneratedThis (TypeSpec type, Location loc)
                        : base (loc)
                {
                        this.type = type;
@@ -6639,7 +6440,7 @@ namespace Mono.CSharp {
                        if (type == null)
                                type = ec.CurrentType;
 
-                       is_struct = type.IsValueType;
+                       is_struct = TypeManager.IsStruct (type);
                        return this;
                }
 
@@ -6661,7 +6462,7 @@ namespace Mono.CSharp {
 
                        public void Emit (EmitContext ec)
                        {
-                               ec.ig.Emit (OpCodes.Ldarg_0);
+                               ec.Emit (OpCodes.Ldarg_0);
                        }
 
                        public void EmitAssign (EmitContext ec)
@@ -6671,7 +6472,7 @@ namespace Mono.CSharp {
 
                        public void EmitAddressOf (EmitContext ec)
                        {
-                               ec.ig.Emit (OpCodes.Ldarg_0);
+                               ec.Emit (OpCodes.Ldarg_0);
                        }
                }
 
@@ -6731,7 +6532,7 @@ namespace Mono.CSharp {
                        if (ec.CurrentAnonymousMethod == null)
                                return true;
 
-                       if (ec.CurrentType.IsValueType && ec.CurrentIterator == null)
+                       if (TypeManager.IsStruct (ec.CurrentType) && ec.CurrentIterator == null)
                                return false;
 
                        return true;
@@ -6754,7 +6555,7 @@ namespace Mono.CSharp {
                                }
                        }
 
-                       is_struct = type.IsValueType;
+                       is_struct = TypeManager.IsStruct (type);
 
                        if (block != null) {
                                if (block.Toplevel.ThisVariable != null)
@@ -6879,7 +6680,7 @@ namespace Mono.CSharp {
 
                public override void Emit (EmitContext ec)
                {
-                       ec.ig.Emit (OpCodes.Arglist);
+                       ec.Emit (OpCodes.Arglist);
                }
 
                protected override void CloneTo (CloneContext clonectx, Expression target)
@@ -6909,11 +6710,11 @@ namespace Mono.CSharp {
                public Type[] ArgumentTypes {
                    get {
                                if (Arguments == null)
-                                       return Type.EmptyTypes;
+                                       return System.Type.EmptyTypes;
 
-                       Type[] retval = new Type [Arguments.Count];
+                       var retval = new Type [Arguments.Count];
                        for (int i = 0; i < retval.Length; i++)
-                           retval [i] = Arguments [i].Expr.Type;
+                                       retval[i] = Arguments[i].Expr.Type.GetMetaInfo ();
 
                        return retval;
                    }
@@ -6943,12 +6744,6 @@ namespace Mono.CSharp {
                                Arguments.Emit (ec);
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       if (Arguments != null)
-                               Arguments.MutateHoistedGenericType (storey);
-               }
-
                protected override void CloneTo (CloneContext clonectx, Expression t)
                {
                        Arglist target = (Arglist) t;
@@ -6963,7 +6758,7 @@ namespace Mono.CSharp {
        /// </summary>
        public class TypeOf : Expression {
                Expression QueriedType;
-               protected Type typearg;
+               protected TypeSpec typearg;
                
                public TypeOf (Expression queried_type, Location l)
                {
@@ -7014,38 +6809,44 @@ namespace Mono.CSharp {
                        return this;
                }
 
-               public override void Emit (EmitContext ec)
-               {
-                       ec.ig.Emit (OpCodes.Ldtoken, TypeManager.TypeToReflectionType (typearg));
-                       ec.ig.Emit (OpCodes.Call, (MethodInfo) TypeManager.system_type_get_type_from_handle.MetaInfo);
-               }
-
-               public override bool GetAttributableValue (ResolveContext ec, Type value_type, out object value)
-               {
-                       if (TypeManager.ContainsGenericParameters (typearg) &&
-                               !TypeManager.IsGenericTypeDefinition (typearg)) {
-                               ec.Report.SymbolRelatedToPreviousError (typearg);
-                               ec.Report.Error (416, loc, "`{0}': an attribute argument cannot use type parameters",
-                                            TypeManager.CSharpName (typearg));
-                               value = null;
-                               return false;
+               public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
+               {
+                       // Target type is not System.Type therefore must be object
+                       // and we need to use different encoding sequence
+                       if (targetType != type)
+                               enc.Encode (type);
+
+/*
+                       var gi = typearg as InflatedTypeSpec;
+                       if (gi != null) {
+                               // TODO: This has to be recursive, handle arrays, etc.
+                               // I could probably do it after CustomAttribute encoder rewrite
+                               foreach (var ta in gi.TypeArguments) {
+                                       if (ta.IsGenericParameter) {
+                                               ec.Report.SymbolRelatedToPreviousError (typearg);
+                                               ec.Report.Error (416, loc, "`{0}': an attribute argument cannot use type parameters",
+                                                                TypeManager.CSharpName (typearg));
+                                               value = null;
+                                               return false;
+                                       }
+                               }
                        }
+ */
 
-                       if (value_type == TypeManager.object_type) {
-                               value = (object)typearg;
-                               return true;
+                       if (!enc.EncodeTypeName (typearg)) {
+                               rc.Compiler.Report.SymbolRelatedToPreviousError (typearg);
+                               rc.Compiler.Report.Error (416, loc, "`{0}': an attribute argument cannot use type parameters",
+                                       TypeManager.CSharpName (typearg));
                        }
-                       value = typearg;
-                       return true;
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
+               public override void Emit (EmitContext ec)
                {
-                       if (!TypeManager.IsGenericTypeDefinition (typearg))
-                               typearg = storey.MutateType (typearg);
+                       ec.Emit (OpCodes.Ldtoken, typearg);
+                       ec.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
                }
 
-               public Type TypeArgument {
+               public TypeSpec TypeArgument {
                        get {
                                return typearg;
                        }
@@ -7101,13 +6902,10 @@ namespace Mono.CSharp {
 
                public override void Emit (EmitContext ec)
                {
-                       if (member.IsConstructor)
-                               ec.ig.Emit (OpCodes.Ldtoken, (ConstructorInfo) member.MetaInfo);
-                       else
-                               ec.ig.Emit (OpCodes.Ldtoken, (MethodInfo) member.MetaInfo);
+                       ec.Emit (OpCodes.Ldtoken, member);
 
                        base.Emit (ec);
-                       ec.ig.Emit (OpCodes.Castclass, type);
+                       ec.Emit (OpCodes.Castclass, type);
                }
 
                protected override string GetMethodName {
@@ -7161,20 +6959,20 @@ namespace Mono.CSharp {
 
                protected override Expression DoResolve (ResolveContext ec)
                {
-                       bool is_generic = TypeManager.IsGenericType (member.DeclaringType);
+                       bool is_generic = member.DeclaringType.IsGenericOrParentIsGeneric;
                        var mi = is_generic ? TypeFromHandleGeneric : TypeFromHandle;
 
                        if (mi == null) {
-                               Type t = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", TypeName, MemberKind.Class, true);
-                               Type handle_type = TypeManager.CoreLookupType (ec.Compiler, "System", RuntimeHandleName, MemberKind.Class, true);
+                               TypeSpec t = TypeManager.CoreLookupType (ec.Compiler, "System.Reflection", TypeName, MemberKind.Class, true);
+                               TypeSpec handle_type = TypeManager.CoreLookupType (ec.Compiler, "System", RuntimeHandleName, MemberKind.Struct, true);
 
                                if (t == null || handle_type == null)
                                        return null;
 
                                mi = TypeManager.GetPredefinedMethod (t, GetMethodName, loc,
                                        is_generic ?
-                                       new Type[] { handle_type, TypeManager.runtime_handle_type } :
-                                       new Type[] { handle_type } );
+                                       new TypeSpec[] { handle_type, TypeManager.runtime_handle_type } :
+                                       new TypeSpec[] { handle_type } );
 
                                if (is_generic)
                                        TypeFromHandleGeneric = mi;
@@ -7188,16 +6986,16 @@ namespace Mono.CSharp {
 
                public override void Emit (EmitContext ec)
                {
-                       bool is_generic = TypeManager.IsGenericType (member.DeclaringType);
+                       bool is_generic = member.DeclaringType.IsGenericOrParentIsGeneric;
                        MethodSpec mi;
                        if (is_generic) {
                                mi = TypeFromHandleGeneric;
-                               ec.ig.Emit (OpCodes.Ldtoken, member.DeclaringType);
+                               ec.Emit (OpCodes.Ldtoken, member.DeclaringType);
                        } else {
                                mi = TypeFromHandle;
                        }
 
-                       ec.ig.Emit (OpCodes.Call, (MethodInfo) mi.MetaInfo);
+                       ec.Emit (OpCodes.Call, mi);
                }
 
                protected abstract string GetMethodName { get; }
@@ -7225,7 +7023,7 @@ namespace Mono.CSharp {
 
                public override void Emit (EmitContext ec)
                {
-                       ec.ig.Emit (OpCodes.Ldtoken, member.MetaInfo);
+                       ec.Emit (OpCodes.Ldtoken, member);
                        base.Emit (ec);
                }
 
@@ -7265,7 +7063,7 @@ namespace Mono.CSharp {
        /// </summary>
        public class SizeOf : Expression {
                readonly Expression QueriedType;
-               Type type_queried;
+               TypeSpec type_queried;
                
                public SizeOf (Expression queried_type, Location l)
                {
@@ -7287,7 +7085,7 @@ namespace Mono.CSharp {
 
                        type_queried = texpr.Type;
                        if (TypeManager.IsEnumType (type_queried))
-                               type_queried = TypeManager.GetEnumUnderlyingType (type_queried);
+                               type_queried = EnumSpec.GetUnderlyingType (type_queried);
 
                        int size_of = GetTypeSize (type_queried);
                        if (size_of > 0) {
@@ -7311,7 +7109,7 @@ namespace Mono.CSharp {
 
                public override void Emit (EmitContext ec)
                {
-                       ec.ig.Emit (OpCodes.Sizeof, type_queried);
+                       ec.Emit (OpCodes.Sizeof, type_queried);
                }
 
                protected override void CloneTo (CloneContext clonectx, Expression t)
@@ -7327,14 +7125,20 @@ namespace Mono.CSharp {
                readonly string alias;
                public static readonly string GlobalAlias = "global";
 
+               public QualifiedAliasMember (string alias, string identifier, Location l)
+                       : base (null, identifier, l)
+               {
+                       this.alias = alias;
+               }
+
                public QualifiedAliasMember (string alias, string identifier, TypeArguments targs, Location l)
                        : base (null, identifier, targs, l)
                {
                        this.alias = alias;
                }
 
-               public QualifiedAliasMember (string alias, string identifier, Location l)
-                       : base (null, identifier, l)
+               public QualifiedAliasMember (string alias, string identifier, int arity, Location l)
+                       : base (null, identifier, arity, l)
                {
                        this.alias = alias;
                }
@@ -7374,7 +7178,7 @@ namespace Mono.CSharp {
                        return ResolveAsTypeStep (ec, false);
                }
 
-               protected override void Error_IdentifierNotFound (IMemberContext rc, FullNamedExpression expr_type, string identifier)
+               protected override void Error_IdentifierNotFound (IMemberContext rc, TypeSpec expr_type, string identifier)
                {
                        rc.Compiler.Report.Error (687, loc,
                                "A namespace alias qualifier `{0}' did not resolve to a namespace or a type",
@@ -7385,8 +7189,7 @@ namespace Mono.CSharp {
                {
                        string name = Name;
                        if (targs != null) {
-                               name = TypeManager.RemoveGenericArity (Name) + "<" +
-                                       targs.GetSignatureForError () + ">";
+                               name = Name + "<" + targs.GetSignatureForError () + ">";
                        }
 
                        return alias + "::" + name;
@@ -7422,6 +7225,12 @@ namespace Mono.CSharp {
                        this.expr = expr;
                }
 
+               public MemberAccess (Expression expr, string identifier, int arity, Location loc)
+                       : base (identifier, arity, loc)
+               {
+                       this.expr = expr;
+               }
+
                Expression DoResolve (ResolveContext ec, Expression right_side)
                {
                        if (type != null)
@@ -7443,22 +7252,20 @@ namespace Mono.CSharp {
                        if (expr_resolved == null)
                                return null;
 
-                       string LookupIdentifier = MemberName.MakeName (Name, targs);
-
                        Namespace ns = expr_resolved as Namespace;
                        if (ns != null) {
-                               FullNamedExpression retval = ns.Lookup (ec.Compiler, LookupIdentifier, loc);
+                               FullNamedExpression retval = ns.Lookup (ec.Compiler, Name, Arity, loc);
 
                                if (retval == null)
-                                       ns.Error_NamespaceDoesNotExist (loc, LookupIdentifier, ec);
-                               else if (targs != null)
+                                       ns.Error_NamespaceDoesNotExist (loc, Name, Arity, ec);
+                               else if (HasTypeArguments)
                                        retval = new GenericTypeExpr (retval.Type, targs, loc).ResolveAsTypeStep (ec, false);
 
                                return retval;
                        }
 
-                       Type expr_type = expr_resolved.Type;
-                       if (TypeManager.IsDynamicType (expr_type)) {
+                       TypeSpec expr_type = expr_resolved.Type;
+                       if (expr_type == InternalType.Dynamic) {
                                Arguments args = new Arguments (1);
                                args.Add (new Argument (expr_resolved.Resolve (ec)));
                                expr = new DynamicMemberBinder (Name, args, loc);
@@ -7480,19 +7287,10 @@ namespace Mono.CSharp {
                                        "System.NullReferenceException");
                        }
 
-                       if (targs != null) {
-                               if (!targs.Resolve (ec))
-                                       return null;
-                       }
+                       var arity = HasTypeArguments ? targs.Count : -1;
 
-                       Expression member_lookup;
-                       member_lookup = MemberLookup (ec.Compiler,
-                               ec.CurrentType, expr_type, expr_type, Name, loc);
-
-                       if (member_lookup == null && targs != null) {
-                               member_lookup = MemberLookup (ec.Compiler,
-                                       ec.CurrentType, expr_type, expr_type, LookupIdentifier, loc);
-                       }
+                       var member_lookup = MemberLookup (ec.Compiler,
+                               ec.CurrentType, expr_type, expr_type, Name, arity, BindingRestriction.NoOverrides, loc);
 
                        if (member_lookup == null) {
                                ExprClass expr_eclass = expr_resolved.eclass;
@@ -7503,11 +7301,14 @@ namespace Mono.CSharp {
                                if (expr_eclass == ExprClass.Value || expr_eclass == ExprClass.Variable ||
                                        expr_eclass == ExprClass.IndexerAccess || expr_eclass == ExprClass.PropertyAccess ||
                                        expr_eclass == ExprClass.EventAccess) {
-                                       ExtensionMethodGroupExpr ex_method_lookup = ec.LookupExtensionMethod (expr_type, Name, loc);
+                                       ExtensionMethodGroupExpr ex_method_lookup = ec.LookupExtensionMethod (expr_type, Name, arity, loc);
                                        if (ex_method_lookup != null) {
                                                ex_method_lookup.ExtensionExpression = expr_resolved;
 
-                                               if (targs != null) {
+                                               if (HasTypeArguments) {
+                                                       if (!targs.Resolve (ec))
+                                                               return null;
+
                                                        ex_method_lookup.SetTypeArguments (ec, targs);
                                                }
 
@@ -7517,8 +7318,8 @@ namespace Mono.CSharp {
 
                                expr = expr_resolved;
                                member_lookup = Error_MemberLookupFailed (ec,
-                                       ec.CurrentType, expr_type, expr_type, Name, null,
-                                       AllMemberTypes, AllBindingFlags);
+                                       ec.CurrentType, expr_type, expr_type, Name, arity, null,
+                                       MemberKind.All, BindingRestriction.AccessibleOnly);
                                if (member_lookup == null)
                                        return null;
                        }
@@ -7539,25 +7340,8 @@ namespace Mono.CSharp {
                                }
 
                                GenericTypeExpr ct = expr_resolved as GenericTypeExpr;
-                               if (ct != null) {
-                                       //
-                                       // When looking up a nested type in a generic instance
-                                       // via reflection, we always get a generic type definition
-                                       // and not a generic instance - so we have to do this here.
-                                       //
-                                       // See gtest-172-lib.cs and gtest-172.cs for an example.
-                                       //
-
-                                       TypeArguments nested_targs;
-                                       if (HasTypeArguments) {
-                                               nested_targs = ct.TypeArguments.Clone ();
-                                               nested_targs.Add (targs);
-                                       } else {
-                                               nested_targs = ct.TypeArguments;
-                                       }
-
-                                       ct = new GenericTypeExpr (member_lookup.Type, nested_targs, loc);
-
+                               if (ct != null && Arity > 0) {
+                                       ct = new GenericTypeExpr (member_lookup.Type, targs, loc);
                                        return ct.ResolveAsTypeStep (ec, false);
                                }
 
@@ -7569,7 +7353,10 @@ namespace Mono.CSharp {
                        if (me == null)
                                return null;
 
-                       if (targs != null) {
+                       if (HasTypeArguments) {
+                               if (!targs.Resolve (ec))
+                                       return null;
+
                                me.SetTypeArguments (ec, targs);
                        }
 
@@ -7612,16 +7399,16 @@ namespace Mono.CSharp {
                        if (expr_resolved == null)
                                return null;
 
-                       string LookupIdentifier = MemberName.MakeName (Name, targs);
-
                        Namespace ns = expr_resolved as Namespace;
                        if (ns != null) {
-                               FullNamedExpression retval = ns.Lookup (rc.Compiler, LookupIdentifier, loc);
+                               FullNamedExpression retval = ns.Lookup (rc.Compiler, Name, Arity, loc);
 
-                               if (retval == null && !silent)
-                                       ns.Error_NamespaceDoesNotExist (loc, LookupIdentifier, rc);
-                               else if (targs != null)
+                               if (retval == null) {
+                                       if (!silent)
+                                               ns.Error_NamespaceDoesNotExist (loc, Name, Arity, rc);
+                               } else if (HasTypeArguments) {
                                        retval = new GenericTypeExpr (retval.Type, targs, loc).ResolveAsTypeStep (rc, silent);
+                               }
 
                                return retval;
                        }
@@ -7630,71 +7417,49 @@ namespace Mono.CSharp {
                        if (tnew_expr == null)
                                return null;
 
-                       Type expr_type = tnew_expr.Type;
+                       TypeSpec expr_type = tnew_expr.Type;
                        if (TypeManager.IsGenericParameter (expr_type)) {
                                rc.Compiler.Report.Error (704, loc, "A nested type cannot be specified through a type parameter `{0}'",
                                        tnew_expr.GetSignatureForError ());
                                return null;
                        }
 
-                       Expression member_lookup = MemberLookup (rc.Compiler,
-                               rc.CurrentType, expr_type, expr_type, LookupIdentifier,
-                               MemberTypes.NestedType, BindingFlags.Public | BindingFlags.NonPublic, loc);
-                       if (member_lookup == null) {
+                       var nested = MemberCache.FindNestedType (expr_type, Name, Arity);
+                       if (nested == null) {
                                if (silent)
                                        return null;
 
-                               Error_IdentifierNotFound (rc, expr_resolved, LookupIdentifier);
+                               Error_IdentifierNotFound (rc, expr_type, Name);
                                return null;
                        }
 
-                       TypeExpr texpr = member_lookup.ResolveAsTypeTerminal (rc, false);
-                       if (texpr == null)
-                               return null;
-
-                       TypeArguments the_args = targs;
-                       Type declaring_type = texpr.Type.DeclaringType;
-                       if (TypeManager.HasGenericArguments (declaring_type) && !TypeManager.IsGenericTypeDefinition (expr_type)) {
-                               while (!TypeManager.IsEqual (TypeManager.DropGenericTypeArguments (expr_type), declaring_type)) {
-                                       expr_type = expr_type.BaseType;
-                               }
-                               
-                               TypeArguments new_args = new TypeArguments ();
-                               foreach (Type decl in TypeManager.GetTypeArguments (expr_type))
-                                       new_args.Add (new TypeExpression (TypeManager.TypeToCoreType (decl), loc));
-
-                               if (targs != null)
-                                       new_args.Add (targs);
-
-                               the_args = new_args;
+                       bool extra_check;
+                       if (!IsMemberAccessible (rc.CurrentType ?? InternalType.FakeInternalType, nested, out extra_check)) {
+                               ErrorIsInaccesible (loc, nested.GetSignatureForError (), rc.Compiler.Report);
                        }
-
-                       if (the_args != null) {
-                               GenericTypeExpr ctype = new GenericTypeExpr (texpr.Type, the_args, loc);
-                               return ctype.ResolveAsTypeStep (rc, false);
+                       
+                       TypeExpr texpr;
+                       if (HasTypeArguments) {
+                               texpr = new GenericTypeExpr (nested, targs, loc);
+                       } else {
+                               texpr = new TypeExpression (nested, loc);
                        }
 
-                       return texpr;
+                       return texpr.ResolveAsTypeStep (rc, false);
                }
 
-               protected virtual void Error_IdentifierNotFound (IMemberContext rc, FullNamedExpression expr_type, string identifier)
+               protected virtual void Error_IdentifierNotFound (IMemberContext rc, TypeSpec expr_type, string identifier)
                {
-                       Expression member_lookup = MemberLookup (rc.Compiler,
-                               rc.CurrentType, expr_type.Type, expr_type.Type, SimpleName.RemoveGenericArity (identifier),
-                               MemberTypes.NestedType, BindingFlags.Public | BindingFlags.NonPublic, loc);
+                       var nested = MemberCache.FindNestedType (expr_type, Name, -System.Math.Max (1, Arity));
 
-                       if (member_lookup != null) {
-                               expr_type = member_lookup.ResolveAsTypeTerminal (rc, false);
-                               if (expr_type == null)
-                                       return;
-
-                               expr_type.Error_TypeArgumentsCannotBeUsed (rc.Compiler.Report, loc);
+                       if (nested != null) {
+                               Error_TypeArgumentsCannotBeUsed (rc.Compiler.Report, expr.Location, nested, Arity);
                                return;
                        }
 
-                       member_lookup = MemberLookup (rc.Compiler,
-                               rc.CurrentType, expr_type.Type, expr_type.Type, identifier,
-                                       MemberTypes.All, BindingFlags.Public | BindingFlags.NonPublic, loc);
+                       var member_lookup = MemberLookup (rc.Compiler,
+                               rc.CurrentType, expr_type, expr_type, identifier, -1,
+                                       MemberKind.All, BindingRestriction.None, loc);
 
                        if (member_lookup == null) {
                                rc.Compiler.Report.Error (426, loc, "The nested type `{0}' does not exist in the type `{1}'",
@@ -7705,7 +7470,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, Type type, string name)
+               protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
                {
                        if (RootContext.Version > LanguageVersion.ISO_2 && !ec.Compiler.IsRuntimeBinder &&
                                ((expr.eclass & (ExprClass.Value | ExprClass.Variable)) != 0)) {
@@ -7792,11 +7557,6 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       Expr.MutateHoistedGenericType (storey);
-               }
-
                protected override void CloneTo (CloneContext clonectx, Expression t)
                {
                        CheckedExpr target = (CheckedExpr) t;
@@ -7852,11 +7612,6 @@ namespace Mono.CSharp {
                                Expr.EmitBranchable (ec, target, on_true);
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       Expr.MutateHoistedGenericType (storey);
-               }
-
                protected override void CloneTo (CloneContext clonectx, Expression t)
                {
                        UnCheckedExpr target = (UnCheckedExpr) t;
@@ -7890,7 +7645,7 @@ namespace Mono.CSharp {
                        return CreateExpressionFactoryCall (ec, "ArrayIndex", args);
                }
 
-               Expression MakePointerAccess (ResolveContext ec, Type t)
+               Expression MakePointerAccess (ResolveContext ec, TypeSpec t)
                {
                        if (Arguments.Count != 1){
                                ec.Report.Error (196, loc, "A pointer must be indexed by only one value");
@@ -7916,7 +7671,7 @@ namespace Mono.CSharp {
                        //
                        // I am experimenting with this pattern.
                        //
-                       Type t = Expr.Type;
+                       TypeSpec t = Expr.Type;
 
                        if (t == TypeManager.array_type){
                                ec.Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `System.Array'");
@@ -8017,11 +7772,11 @@ namespace Mono.CSharp {
                        bool dynamic;
                        ea.Arguments.Resolve (ec, out dynamic);
 
-                       Type t = ea.Expr.Type;
+                       TypeSpec t = ea.Expr.Type;
                        int rank = ea.Arguments.Count;
-                       if (t.GetArrayRank () != rank) {
+                       if (t.GetMetaInfo ().GetArrayRank () != rank) {
                                ec.Report.Error (22, ea.Location, "Wrong number of indexes `{0}' inside [], expected `{1}'",
-                                         ea.Arguments.Count.ToString (), t.GetArrayRank ().ToString ());
+                                         ea.Arguments.Count.ToString (), t.GetMetaInfo ().GetArrayRank ().ToString ());
                                return null;
                        }
 
@@ -8042,137 +7797,27 @@ namespace Mono.CSharp {
                        return this;
                }
 
-               /// <summary>
-               ///    Emits the right opcode to load an object of Type `t'
-               ///    from an array of T
-               /// </summary>
-               void EmitLoadOpcode (ILGenerator ig, Type type, int rank)
-               {
-                       if (rank > 1) {
-                               MethodInfo get = FetchGetMethod ();
-                               ig.Emit (OpCodes.Call, get);
-                               return;
-                       }
-
-                       if (type == TypeManager.byte_type || type == TypeManager.bool_type)
-                               ig.Emit (OpCodes.Ldelem_U1);
-                       else if (type == TypeManager.sbyte_type)
-                               ig.Emit (OpCodes.Ldelem_I1);
-                       else if (type == TypeManager.short_type)
-                               ig.Emit (OpCodes.Ldelem_I2);
-                       else if (type == TypeManager.ushort_type || type == TypeManager.char_type)
-                               ig.Emit (OpCodes.Ldelem_U2);
-                       else if (type == TypeManager.int32_type)
-                               ig.Emit (OpCodes.Ldelem_I4);
-                       else if (type == TypeManager.uint32_type)
-                               ig.Emit (OpCodes.Ldelem_U4);
-                       else if (type == TypeManager.uint64_type)
-                               ig.Emit (OpCodes.Ldelem_I8);
-                       else if (type == TypeManager.int64_type)
-                               ig.Emit (OpCodes.Ldelem_I8);
-                       else if (type == TypeManager.float_type)
-                               ig.Emit (OpCodes.Ldelem_R4);
-                       else if (type == TypeManager.double_type)
-                               ig.Emit (OpCodes.Ldelem_R8);
-                       else if (type == TypeManager.intptr_type)
-                               ig.Emit (OpCodes.Ldelem_I);
-                       else if (TypeManager.IsEnumType (type)){
-                               EmitLoadOpcode (ig, TypeManager.GetEnumUnderlyingType (type), rank);
-                       } else if (TypeManager.IsStruct (type)){
-                               ig.Emit (OpCodes.Ldelema, type);
-                               ig.Emit (OpCodes.Ldobj, type);
-                       } else if (type.IsGenericParameter) {
-                               ig.Emit (OpCodes.Ldelem, type);
-                       } else if (type.IsPointer)
-                               ig.Emit (OpCodes.Ldelem_I);
-                       else
-                               ig.Emit (OpCodes.Ldelem_Ref);
-               }
-
                protected override void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
                {
                        ec.Report.Warning (251, 2, loc, "Indexing an array with a negative index (array indices always start at zero)");
                }
 
-               /// <summary>
-               ///    Returns the right opcode to store an object of Type `t'
-               ///    from an array of T.  
-               /// </summary>
-               static public OpCode GetStoreOpcode (Type t, out bool is_stobj, out bool has_type_arg)
-               {
-                       has_type_arg = false; is_stobj = false;
-                       t = TypeManager.TypeToCoreType (t);
-                       if (TypeManager.IsEnumType (t))
-                               t = TypeManager.GetEnumUnderlyingType (t);
-                       if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
-                           t == TypeManager.bool_type)
-                               return OpCodes.Stelem_I1;
-                       else if (t == TypeManager.short_type || t == TypeManager.ushort_type ||
-                                t == TypeManager.char_type)
-                               return OpCodes.Stelem_I2;
-                       else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
-                               return OpCodes.Stelem_I4;
-                       else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
-                               return OpCodes.Stelem_I8;
-                       else if (t == TypeManager.float_type)
-                               return OpCodes.Stelem_R4;
-                       else if (t == TypeManager.double_type)
-                               return OpCodes.Stelem_R8;
-                       else if (t == TypeManager.intptr_type) {
-                                has_type_arg = true;
-                               is_stobj = true;
-                                return OpCodes.Stobj;
-                       } else if (TypeManager.IsStruct (t)) {
-                               has_type_arg = true;
-                               is_stobj = true;
-                               return OpCodes.Stobj;
-                       } else if (t.IsGenericParameter) {
-                               has_type_arg = true;
-                               return OpCodes.Stelem;
-                       } else if (t.IsPointer)
-                               return OpCodes.Stelem_I;
-                       else
-                               return OpCodes.Stelem_Ref;
-               }
-
-               MethodInfo FetchGetMethod ()
-               {
-                       ModuleBuilder mb = RootContext.ToplevelTypes.Builder;
-                       int arg_count = ea.Arguments.Count;
-                       Type [] args = new Type [arg_count];
-                       MethodInfo get;
-                       
-                       for (int i = 0; i < arg_count; i++){
-                               //args [i++] = a.Type;
-                               args [i] = TypeManager.int32_type;
-                       }
-                       
-                       get = mb.GetArrayMethod (
-                               ea.Expr.Type, "Get",
-                               CallingConventions.HasThis |
-                               CallingConventions.Standard,
-                               type, args);
-                       return get;
-               }
-                               
-
                MethodInfo FetchAddressMethod ()
                {
                        ModuleBuilder mb = RootContext.ToplevelTypes.Builder;
                        int arg_count = ea.Arguments.Count;
-                       Type [] args = new Type [arg_count];
+                       var args = new Type [arg_count];
                        MethodInfo address;
-                       Type ret_type;
                        
-                       ret_type = TypeManager.GetReferenceType (type);
+                       var ret_type = TypeManager.GetReferenceType (type);
                        
                        for (int i = 0; i < arg_count; i++){
                                //args [i++] = a.Type;
-                               args [i] = TypeManager.int32_type;
+                               args[i] = TypeManager.int32_type.GetMetaInfo ();
                        }
                        
                        address = mb.GetArrayMethod (
-                               ea.Expr.Type, "Address",
+                               ea.Expr.Type.GetMetaInfo (), "Address",
                                CallingConventions.HasThis |
                                CallingConventions.Standard,
                                ret_type, args);
@@ -8194,18 +7839,17 @@ namespace Mono.CSharp {
 
                public void Emit (EmitContext ec, bool leave_copy)
                {
-                       int rank = ea.Expr.Type.GetArrayRank ();
-                       ILGenerator ig = ec.ig;
+                       var ac = ea.Expr.Type as ArrayContainer;
 
                        if (prepared) {
-                               LoadFromPtr (ig, this.type);
+                               ec.EmitLoadFromPtr (type);
                        } else {
                                LoadArrayAndArguments (ec);
-                               EmitLoadOpcode (ig, type, rank);
+                               ec.EmitArrayLoad (ac);
                        }       
 
                        if (leave_copy) {
-                               ig.Emit (OpCodes.Dup);
+                               ec.Emit (OpCodes.Dup);
                                temp = new LocalTemporary (this.type);
                                temp.Store (ec);
                        }
@@ -8218,74 +7862,43 @@ namespace Mono.CSharp {
 
                public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
                {
-                       int rank = ea.Expr.Type.GetArrayRank ();
-                       ILGenerator ig = ec.ig;
-                       Type t = source.Type;
+                       var ac = (ArrayContainer) ea.Expr.Type;
+                       TypeSpec t = source.Type;
                        prepared = prepare_for_load;
 
                        if (prepared) {
                                AddressOf (ec, AddressOp.LoadStore);
-                               ec.ig.Emit (OpCodes.Dup);
+                               ec.Emit (OpCodes.Dup);
                        } else {
                                LoadArrayAndArguments (ec);
-                       }
 
-                       if (rank == 1) {
-                               bool is_stobj, has_type_arg;
-                               OpCode op = GetStoreOpcode (t, out is_stobj, out has_type_arg);
+                               //
+                               // If we are dealing with a struct, get the
+                               // address of it, so we can store it.
+                               //
+                               // The stobj opcode used by value types will need
+                               // an address on the stack, not really an array/array
+                               // pair
+                               //
+                               if (ac.Rank == 1 && TypeManager.IsStruct (t) &&
+                                       (!TypeManager.IsBuiltinOrEnum (t) ||
+                                        t == TypeManager.decimal_type)) {
 
-                               if (!prepared) {
-                                       //
-                                       // The stobj opcode used by value types will need
-                                       // an address on the stack, not really an array/array
-                                       // pair
-                                       //
-                                       if (is_stobj)
-                                               ig.Emit (OpCodes.Ldelema, t);
-                               }
-                               
-                               source.Emit (ec);
-                               if (leave_copy) {
-                                       ec.ig.Emit (OpCodes.Dup);
-                                       temp = new LocalTemporary (this.type);
-                                       temp.Store (ec);
+                                       ec.Emit (OpCodes.Ldelema, t);
                                }
-                               
-                               if (prepared)
-                                       StoreFromPtr (ig, t);
-                               else if (is_stobj)
-                                       ig.Emit (OpCodes.Stobj, t);
-                               else if (has_type_arg)
-                                       ig.Emit (op, t);
-                               else
-                                       ig.Emit (op);
-                       } else {
-                               source.Emit (ec);
-                               if (leave_copy) {
-                                       ec.ig.Emit (OpCodes.Dup);
-                                       temp = new LocalTemporary (this.type);
-                                       temp.Store (ec);
-                               }
-
-                               if (prepared) {
-                                       StoreFromPtr (ig, t);
-                               } else {
-                                       int arg_count = ea.Arguments.Count;
-                                       Type [] args = new Type [arg_count + 1];
-                                       for (int i = 0; i < arg_count; i++) {
-                                               //args [i++] = a.Type;
-                                               args [i] = TypeManager.int32_type;
-                                       }
-                                       args [arg_count] = type;
+                       }
 
-                                       MethodInfo set = RootContext.ToplevelTypes.Builder.GetArrayMethod (
-                                               ea.Expr.Type, "Set",
-                                               CallingConventions.HasThis |
-                                               CallingConventions.Standard,
-                                               TypeManager.void_type, args);
+                       source.Emit (ec);
+                       if (leave_copy) {
+                               ec.Emit (OpCodes.Dup);
+                               temp = new LocalTemporary (this.type);
+                               temp.Store (ec);
+                       }
 
-                                       ig.Emit (OpCodes.Call, set);
-                               }
+                       if (prepared) {
+                               ec.EmitStoreFromPtr (t);
+                       } else {
+                               ec.EmitArrayStore (ac);
                        }
                        
                        if (temp != null) {
@@ -8308,16 +7921,15 @@ namespace Mono.CSharp {
 
                public void AddressOf (EmitContext ec, AddressOp mode)
                {
-                       int rank = ea.Expr.Type.GetArrayRank ();
-                       ILGenerator ig = ec.ig;
+                       int rank = ea.Expr.Type.GetMetaInfo ().GetArrayRank ();
 
                        LoadArrayAndArguments (ec);
 
                        if (rank == 1){
-                               ig.Emit (OpCodes.Ldelema, type);
+                               ec.Emit (OpCodes.Ldelema, type);
                        } else {
                                MethodInfo address = FetchAddressMethod ();
-                               ig.Emit (OpCodes.Call, address);
+                               ec.Emit (OpCodes.Call, address);
                        }
                }
 
@@ -8336,12 +7948,6 @@ namespace Mono.CSharp {
                                ea.Expr.MakeExpression (ctx),
                                Arguments.MakeExpression (ea.Arguments, ctx));
                }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       type = storey.MutateType (type);
-                       ea.Expr.Type = storey.MutateType (ea.Expr.Type);
-               }
        }
 
        /// <summary>
@@ -8351,10 +7957,36 @@ namespace Mono.CSharp {
        {
                class IndexerMethodGroupExpr : MethodGroupExpr
                {
-                       public IndexerMethodGroupExpr (Indexers indexers, Location loc)
-                               : base (null, loc)
+                       IEnumerable<IndexerSpec> candidates;
+
+                       public IndexerMethodGroupExpr (IEnumerable<IndexerSpec> indexers, Location loc)
+                               : base (FilterAccessors (indexers).ToList (), null, loc)
+                       {
+                               candidates = indexers;
+                       }
+
+                       public IndexerSpec BestIndexer ()
                        {
-                               Methods = indexers.Methods.ToArray ();
+                               return candidates.Where (l => l.Get == BestCandidate || l.Set == BestCandidate).First ();
+                       }
+
+                       static IEnumerable<MemberSpec> FilterAccessors (IEnumerable<IndexerSpec> indexers)
+                       {
+                               foreach (IndexerSpec i in indexers) {
+                                       if (i.HasGet)
+                                               yield return i.Get;
+                                       else
+                                               yield return i.Set;
+                               }
+                       }
+
+                       protected override IList<MemberSpec> GetBaseTypeMethods (ResolveContext rc, TypeSpec type)
+                       {
+                               candidates = GetIndexersForType (type);
+                               if (candidates == null)
+                                       return null;
+
+                               return FilterAccessors (candidates).ToList ();
                        }
 
                        public override string Name {
@@ -8378,100 +8010,18 @@ namespace Mono.CSharp {
                        }
                }
 
-               class Indexers
-               {
-                       // Contains either property getter or setter
-                       public List<MethodSpec> Methods;
-                       public List<PropertyInfo> Properties;
-
-                       Indexers ()
-                       {
-                       }
-
-                       void Append (Type caller_type, MemberInfo [] mi)
-                       {
-                               if (mi == null)
-                                       return;
-
-                               foreach (PropertyInfo property in mi) {
-                                       MethodInfo accessor = property.GetGetMethod (true);
-                                       if (accessor == null)
-                                               accessor = property.GetSetMethod (true);
-
-                                       if (Methods == null) {
-                                               Methods = new List<MethodSpec> ();
-                                               Properties = new List<PropertyInfo> ();
-                                       }
-
-                                       Methods.Add (Import.CreateMethod (accessor));
-                                       Properties.Add (property);
-                               }
-                       }
-
-                       static MemberInfo [] GetIndexersForTypeOrInterface (Type caller_type, Type lookup_type)
-                       {
-                               string p_name = TypeManager.IndexerPropertyName (lookup_type);
-
-                               return TypeManager.MemberLookup (
-                                       caller_type, caller_type, lookup_type, MemberTypes.Property,
-                                       BindingFlags.Public | BindingFlags.Instance |
-                                       BindingFlags.DeclaredOnly, p_name, null);
-                       }
-                       
-                       public static Indexers GetIndexersForType (Type caller_type, Type lookup_type) 
-                       {
-                               Indexers ix = new Indexers ();
-
-                               if (TypeManager.IsGenericParameter (lookup_type)) {
-                                       GenericConstraints gc = TypeManager.GetTypeParameterConstraints (lookup_type);
-                                       if (gc == null)
-                                               return ix;
-
-                                       if (gc.HasClassConstraint) {
-                                               Type class_contraint = gc.ClassConstraint;
-                                               while (class_contraint != TypeManager.object_type && class_contraint != null) {
-                                                       ix.Append (caller_type, GetIndexersForTypeOrInterface (caller_type, class_contraint));
-                                                       class_contraint = class_contraint.BaseType;
-                                               }
-                                       }
-
-                                       Type[] ifaces = gc.InterfaceConstraints;
-                                       foreach (Type itype in ifaces)
-                                               ix.Append (caller_type, GetIndexersForTypeOrInterface (caller_type, itype));
-
-                                       return ix;
-                               }
-
-                               Type copy = lookup_type;
-                               while (copy != TypeManager.object_type && copy != null){
-                                       ix.Append (caller_type, GetIndexersForTypeOrInterface (caller_type, copy));
-                                       copy = copy.BaseType;
-                               }
-
-                               if (lookup_type.IsInterface) {
-                                       Type [] ifaces = TypeManager.GetInterfaces (lookup_type);
-                                       if (ifaces != null) {
-                                               foreach (Type itype in ifaces)
-                                                       ix.Append (caller_type, GetIndexersForTypeOrInterface (caller_type, itype));
-                                       }
-                               }
-
-                               return ix;
-                       }
-               }
-
                //
                // Points to our "data" repository
                //
-               MethodSpec get, set;
+               IndexerSpec spec;
                bool is_base_indexer;
                bool prepared;
                LocalTemporary temp;
                LocalTemporary prepared_value;
                Expression set_expr;
 
-               protected Type indexer_type;
-               protected Type current_type;
+               protected TypeSpec indexer_type;
+               protected TypeSpec current_type;
                protected Expression instance_expr;
                protected Arguments arguments;
                
@@ -8498,11 +8048,16 @@ namespace Mono.CSharp {
                {
                        Arguments args = Arguments.CreateForExpressionTree (ec, arguments,
                                instance_expr.CreateExpressionTree (ec),
-                               new TypeOfMethod (get, loc));
+                               new TypeOfMethod (spec.Get, loc));
 
                        return CreateExpressionFactoryCall (ec, "Call", args);
                }
 
+               static IEnumerable<IndexerSpec> GetIndexersForType (TypeSpec lookup_type)
+               {
+                       return MemberCache.FindIndexers (lookup_type, BindingRestriction.AccessibleOnly | BindingRestriction.NoOverrides);
+               }
+
                protected virtual void CommonResolve (ResolveContext ec)
                {
                        indexer_type = instance_expr.Type;
@@ -8533,28 +8088,27 @@ namespace Mono.CSharp {
                {
                        CommonResolve (ec);
 
-                       MethodGroupExpr mg;
-                       Indexers ilist;
                        bool dynamic;
 
                        arguments.Resolve (ec, out dynamic);
 
-                       if (TypeManager.IsDynamicType (indexer_type)) {
+                       if (indexer_type == InternalType.Dynamic) {
                                dynamic = true;
-                               mg = null;
-                               ilist = null;
                        } else {
-                               ilist = Indexers.GetIndexersForType (current_type, indexer_type);
-                               if (ilist.Methods == null) {
+                               var ilist = GetIndexersForType (/*current_type,*/ indexer_type);
+                               if (ilist == null) {
                                        ec.Report.Error (21, loc, "Cannot apply indexing with [] to an expression of type `{0}'",
                                                          TypeManager.CSharpName (indexer_type));
                                        return null;
                                }
 
-                               mg = new IndexerMethodGroupExpr (ilist, loc);
-                               mg = mg.OverloadResolve (ec, ref arguments, false, loc);
+                               var mg = new IndexerMethodGroupExpr (ilist, loc);
+                               mg = mg.OverloadResolve (ec, ref arguments, false, loc) as IndexerMethodGroupExpr;
                                if (mg == null)
                                        return null;
+
+                               if (!dynamic)
+                                       spec = mg.BestIndexer ();
                        }
 
                        if (dynamic) {
@@ -8573,72 +8127,48 @@ namespace Mono.CSharp {
                                return expr.Resolve (ec);
                        }
 
-                       var mi = (MethodSpec) mg;
-                       PropertyInfo pi = null;
-                       for (int i = 0; i < ilist.Methods.Count; ++i) {
-                               if (ilist.Methods [i].MetaInfo == mi.MetaInfo) {
-                                       pi = (PropertyInfo) ilist.Properties [i];
-                                       break;
-                               }
-                       }
-
-                       type = TypeManager.TypeToCoreType (pi.PropertyType);
+                       type = spec.MemberType;
                        if (type.IsPointer && !ec.IsUnsafe)
                                UnsafeError (ec, loc);
 
-                       MethodSpec accessor = null;
+                       MethodSpec accessor;
                        if (right_side == null) {
-                               var m = pi.GetGetMethod (true);
-                               if (m != null)
-                                       accessor = get = Import.CreateMethod (m);
+                               accessor = spec.Get;
                        } else {
-                               var m = pi.GetSetMethod (true);
-                               if (m != null)
-                                       accessor = set = Import.CreateMethod (m);
-                               if (accessor == null && pi.GetGetMethod (true) != null) {
-                                       ec.Report.SymbolRelatedToPreviousError (pi);
+                               accessor = spec.Set;
+                               if (!spec.HasSet && spec.HasGet) {
+                                       ec.Report.SymbolRelatedToPreviousError (spec);
                                        ec.Report.Error (200, loc, "The read only property or indexer `{0}' cannot be assigned to",
-                                               TypeManager.GetFullNameSignature (pi));
+                                               spec.GetSignatureForError ());
                                        return null;
                                }
 
                                set_expr = Convert.ImplicitConversion (ec, right_side, type, loc);
                        }
 
-                       if (accessor == null) {
-                               ec.Report.SymbolRelatedToPreviousError (pi);
+                       if (accessor == null || accessor.Kind == MemberKind.FakeMethod) {
+                               ec.Report.SymbolRelatedToPreviousError (spec);
                                ec.Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks a `{1}' accessor",
-                                       TypeManager.GetFullNameSignature (pi), GetAccessorName (right_side != null));
+                                       spec.GetSignatureForError (), GetAccessorName (right_side != null));
                                return null;
                        }
 
                        //
                        // Only base will allow this invocation to happen.
                        //
-                       if (accessor.IsAbstract && this is BaseIndexerAccess) {
-                               Error_CannotCallAbstractBase (ec, TypeManager.GetFullNameSignature (pi));
+                       if (spec.IsAbstract && this is BaseIndexerAccess) {
+                               Error_CannotCallAbstractBase (ec, spec.GetSignatureForError ());
                        }
 
                        bool must_do_cs1540_check;
-                       if (!IsAccessorAccessible (ec.CurrentType, accessor, out must_do_cs1540_check)) {
-                               if (set == null) {
-                                       var m = pi.GetSetMethod (true);
-                                       if (m != null)
-                                               set = Import.CreateMethod (m);
-                               } else {
-                                       var m = pi.GetGetMethod (true);
-                                       if (m != null)
-                                               get = Import.CreateMethod (m);
-                               }
-
-                               if (set != null && get != null &&
-                                       (set.MetaInfo.Attributes & MethodAttributes.MemberAccessMask) != (get.MetaInfo.Attributes & MethodAttributes.MemberAccessMask)) {
-                                       ec.Report.SymbolRelatedToPreviousError (accessor.MetaInfo);
+                       if (!IsMemberAccessible (ec.CurrentType, accessor, out must_do_cs1540_check)) {
+                               if (spec.HasDifferentAccessibility) {
+                                       ec.Report.SymbolRelatedToPreviousError (accessor);
                                        ec.Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because a `{1}' accessor is inaccessible",
-                                               TypeManager.GetFullNameSignature (pi), GetAccessorName (right_side != null));
+                                               TypeManager.GetFullNameSignature (spec), GetAccessorName (right_side != null));
                                } else {
-                                       ec.Report.SymbolRelatedToPreviousError (pi);
-                                       ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (pi), ec.Report);
+                                       ec.Report.SymbolRelatedToPreviousError (spec);
+                                       ErrorIsInaccesible (loc, TypeManager.GetFullNameSignature (spec), ec.Report);
                                }
                        }
 
@@ -8648,8 +8178,8 @@ namespace Mono.CSharp {
                            !TypeManager.IsInstantiationOfSameGenericType (instance_expr.Type, ec.CurrentType) &&
                            !TypeManager.IsNestedChildOf (ec.CurrentType, instance_expr.Type) &&
                            !TypeManager.IsSubclassOf (instance_expr.Type, ec.CurrentType)) {
-                               ec.Report.SymbolRelatedToPreviousError (accessor.MetaInfo);
-                               Error_CannotAccessProtected (ec, loc, accessor.MetaInfo, instance_expr.Type, ec.CurrentType);
+                               ec.Report.SymbolRelatedToPreviousError (accessor);
+                               Error_CannotAccessProtected (ec, loc, spec, instance_expr.Type, ec.CurrentType);
                                return null;
                        }
 
@@ -8667,12 +8197,12 @@ namespace Mono.CSharp {
                        if (prepared) {
                                prepared_value.Emit (ec);
                        } else {
-                               Invocation.EmitCall (ec, is_base_indexer, instance_expr, get,
+                               Invocation.EmitCall (ec, is_base_indexer, instance_expr, spec.Get,
                                        arguments, loc, false, false);
                        }
 
                        if (leave_copy) {
-                               ec.ig.Emit (OpCodes.Dup);
+                               ec.Emit (OpCodes.Dup);
                                temp = new LocalTemporary (Type);
                                temp.Store (ec);
                        }
@@ -8689,7 +8219,7 @@ namespace Mono.CSharp {
                        Expression value = set_expr;
 
                        if (prepared) {
-                               Invocation.EmitCall (ec, is_base_indexer, instance_expr, get,
+                               Invocation.EmitCall (ec, is_base_indexer, instance_expr, spec.Get,
                                        arguments, loc, true, false);
 
                                prepared_value = new LocalTemporary (type);
@@ -8698,7 +8228,7 @@ namespace Mono.CSharp {
                                prepared_value.Release (ec);
 
                                if (leave_copy) {
-                                       ec.ig.Emit (OpCodes.Dup);
+                                       ec.Emit (OpCodes.Dup);
                                        temp = new LocalTemporary (Type);
                                        temp.Store (ec);
                                }
@@ -8712,7 +8242,7 @@ namespace Mono.CSharp {
                        if (!prepared)
                                arguments.Add (new Argument (value));
 
-                       Invocation.EmitCall (ec, is_base_indexer, instance_expr, set, arguments, loc, false, prepared);
+                       Invocation.EmitCall (ec, is_base_indexer, instance_expr, spec.Set, arguments, loc, false, prepared);
                        
                        if (temp != null) {
                                temp.Emit (ec);
@@ -8722,7 +8252,7 @@ namespace Mono.CSharp {
                
                public override string GetSignatureForError ()
                {
-                       return TypeManager.CSharpSignature (get != null ? get.MetaInfo : set.MetaInfo, false);
+                       return spec.GetSignatureForError ();
                }
 
 #if NET_4_0
@@ -8732,7 +8262,7 @@ namespace Mono.CSharp {
                        var args = Arguments.MakeExpression (arguments, ctx).Concat (value);
 
                        return SLE.Expression.Block (
-                                       SLE.Expression.Call (instance_expr.MakeExpression (ctx), (MethodInfo) set.MetaInfo, args),
+                                       SLE.Expression.Call (instance_expr.MakeExpression (ctx), (MethodInfo) spec.Set.GetMetaInfo (), args),
                                        value [0]);
                }
 #endif
@@ -8740,21 +8270,7 @@ namespace Mono.CSharp {
                public override SLE.Expression MakeExpression (BuilderContext ctx)
                {
                        var args = Arguments.MakeExpression (arguments, ctx);
-                       return SLE.Expression.Call (instance_expr.MakeExpression (ctx), (MethodInfo) get.MetaInfo, args);
-               }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       if (get != null)
-                               storey.MutateGenericMethod (get);
-                       if (set != null)
-                               storey.MutateGenericMethod (set);
-
-                       instance_expr.MutateHoistedGenericType (storey);
-                       if (arguments != null)
-                               arguments.MutateHoistedGenericType (storey);
-
-                       type = storey.MutateType (type);
+                       return SLE.Expression.Call (instance_expr.MakeExpression (ctx), (MethodInfo) spec.Get.GetMetaInfo (), args);
                }
 
                protected override void CloneTo (CloneContext clonectx, Expression t)
@@ -8827,8 +8343,8 @@ namespace Mono.CSharp {
                Expression CommonResolve (ResolveContext ec)
                {
                        Expression member_lookup;
-                       Type current_type = ec.CurrentType;
-                       Type base_type = current_type.BaseType;
+                       TypeSpec current_type = ec.CurrentType;
+                       TypeSpec base_type = current_type.BaseType;
 
                        if (!This.IsThisAvailable (ec)) {
                                if (ec.IsStatic) {
@@ -8838,12 +8354,13 @@ namespace Mono.CSharp {
                                }
                                return null;
                        }
-                       
-                       member_lookup = MemberLookup (ec.Compiler, ec.CurrentType, null, base_type, Identifier,
-                                                     AllMemberTypes, AllBindingFlags, loc);
+
+                       var arity = args == null ? -1 : args.Count;
+                       member_lookup = MemberLookup (ec.Compiler, ec.CurrentType, null, base_type, Identifier, arity,
+                                                     MemberKind.All, BindingRestriction.AccessibleOnly, loc);
                        if (member_lookup == null) {
-                               Error_MemberLookupFailed (ec, ec.CurrentType, base_type, base_type, Identifier,
-                                       null, AllMemberTypes, AllBindingFlags);
+                               Error_MemberLookupFailed (ec, ec.CurrentType, base_type, base_type, Identifier, arity,
+                                       null, MemberKind.All, BindingRestriction.AccessibleOnly);
                                return null;
                        }
 
@@ -8970,7 +8487,7 @@ namespace Mono.CSharp {
                        loc = Location.Null;
                }
 
-               public EmptyExpression (Type t)
+               public EmptyExpression (TypeSpec t)
                {
                        type = t;
                        eclass = ExprClass.Value;
@@ -9001,7 +8518,7 @@ namespace Mono.CSharp {
                // instead of creating gazillions of EmptyExpressions.
                // (CanImplicitConversion uses it)
                //
-               public void SetType (Type t)
+               public void SetType (TypeSpec t)
                {
                        type = t;
                }
@@ -9050,7 +8567,7 @@ namespace Mono.CSharp {
                {
                        this.method = method;
                        this.source = source;
-                       type = TypeManager.TypeToCoreType (method.ReturnType);
+                       type = method.ReturnType;
                        loc = l;
                }
 
@@ -9071,7 +8588,7 @@ namespace Mono.CSharp {
                        
                protected override Expression DoResolve (ResolveContext ec)
                {
-                       ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (method.MetaInfo);
+                       ObsoleteAttribute oa = method.GetAttributeObsolete ();
                        if (oa != null)
                                AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc, ec.Report);
 
@@ -9082,23 +8599,17 @@ namespace Mono.CSharp {
                public override void Emit (EmitContext ec)
                {
                        source.Emit (ec);
-                       ec.ig.Emit (OpCodes.Call, (MethodInfo) method.MetaInfo);
+                       ec.Emit (OpCodes.Call, method);
                }
 
                public override string GetSignatureForError ()
                {
-                       return TypeManager.CSharpSignature (method.MetaInfo);
+                       return TypeManager.CSharpSignature (method);
                }
 
                public override SLE.Expression MakeExpression (BuilderContext ctx)
                {
-                       return SLE.Expression.Convert (source.MakeExpression (ctx), type, (MethodInfo) method.MetaInfo);
-               }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       source.MutateHoistedGenericType (storey);
-                       storey.MutateGenericMethod (method);
+                       return SLE.Expression.Convert (source.MakeExpression (ctx), type.GetMetaInfo (), (MethodInfo) method.GetMetaInfo ());
                }
        }
 
@@ -9130,7 +8641,7 @@ namespace Mono.CSharp {
                        if (lexpr == null)
                                return null;
 
-                       Type ltype = lexpr.Type;
+                       TypeSpec ltype = lexpr.Type;
                        if ((dim.Length > 0) && (dim [0] == '?')) {
                                TypeExpr nullable = new Nullable.NullableType (lexpr, loc);
                                if (dim.Length > 1)
@@ -9147,7 +8658,7 @@ namespace Mono.CSharp {
                                        return null;
                                }
 
-                               if ((ltype.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
+                               if (ltype.IsStatic) {
                                        ec.Compiler.Report.SymbolRelatedToPreviousError (ltype);
                                        ec.Compiler.Report.Error (719, loc, "Array elements cannot be of static type `{0}'", 
                                                TypeManager.CSharpName (ltype));
@@ -9174,22 +8685,17 @@ namespace Mono.CSharp {
                {
                        return left.GetSignatureForError () + dim;
                }
-
-               public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
-               {
-                       return ResolveAsBaseTerminal (ec, silent);
-               }               
        }
 
        public class FixedBufferPtr : Expression {
                Expression array;
 
-               public FixedBufferPtr (Expression array, Type array_type, Location l)
+               public FixedBufferPtr (Expression array, TypeSpec array_type, Location l)
                {
                        this.array = array;
                        this.loc = l;
 
-                       type = TypeManager.GetPointerType (array_type);
+                       type = PointerContainer.MakeType (array_type);
                        eclass = ExprClass.Value;
                }
 
@@ -9220,9 +8726,9 @@ namespace Mono.CSharp {
        // for fixed (char *pa = a)
        //
        public class ArrayPtr : FixedBufferPtr {
-               Type array_type;
+               TypeSpec array_type;
                
-               public ArrayPtr (Expression array, Type array_type, Location l):
+               public ArrayPtr (Expression array, TypeSpec array_type, Location l):
                        base (array, array_type, l)
                {
                        this.array_type = array_type;
@@ -9232,9 +8738,8 @@ namespace Mono.CSharp {
                {
                        base.Emit (ec);
                        
-                       ILGenerator ig = ec.ig;
-                       IntLiteral.EmitInt (ig, 0);
-                       ig.Emit (OpCodes.Ldelema, array_type);
+                       ec.EmitInt (0);
+                       ec.Emit (OpCodes.Ldelema, array_type);
                }
        }
 
@@ -9264,26 +8769,21 @@ namespace Mono.CSharp {
                        var expr_type = child.Type;
 
                        if (expr_type == TypeManager.uint32_type)
-                               ec.ig.Emit (OpCodes.Conv_U);
+                               ec.Emit (OpCodes.Conv_U);
                        else if (expr_type == TypeManager.int64_type)
-                               ec.ig.Emit (OpCodes.Conv_Ovf_I);
+                               ec.Emit (OpCodes.Conv_Ovf_I);
                        else if (expr_type == TypeManager.uint64_type)
-                               ec.ig.Emit (OpCodes.Conv_Ovf_I_Un);
+                               ec.Emit (OpCodes.Conv_Ovf_I_Un);
                        else
                                throw new InternalErrorException ("Cannot emit cast to unknown array element type", type);
                }
-
-               public override bool GetAttributableValue (ResolveContext ec, Type value_type, out object value)
-               {
-                       return child.GetAttributableValue (ec, value_type, out value);
-               }
        }
 
        //
        // Implements the `stackalloc' keyword
        //
        public class StackAlloc : Expression {
-               Type otype;
+               TypeSpec otype;
                Expression t;
                Expression count;
                
@@ -9329,7 +8829,7 @@ namespace Mono.CSharp {
                        if (!TypeManager.VerifyUnmanaged (ec.Compiler, otype, loc))
                                return null;
 
-                       type = TypeManager.GetPointerType (otype);
+                       type = PointerContainer.MakeType (otype);
                        eclass = ExprClass.Value;
 
                        return this;
@@ -9338,17 +8838,16 @@ namespace Mono.CSharp {
                public override void Emit (EmitContext ec)
                {
                        int size = GetTypeSize (otype);
-                       ILGenerator ig = ec.ig;
 
                        count.Emit (ec);
 
                        if (size == 0)
-                               ig.Emit (OpCodes.Sizeof, otype);
+                               ec.Emit (OpCodes.Sizeof, otype);
                        else
-                               IntConstant.EmitInt (ig, size);
+                               ec.EmitInt (size);
 
-                       ig.Emit (OpCodes.Mul_Ovf_Un);
-                       ig.Emit (OpCodes.Localloc);
+                       ec.Emit (OpCodes.Mul_Ovf_Un);
+                       ec.Emit (OpCodes.Localloc);
                }
 
                protected override void CloneTo (CloneContext clonectx, Expression t)
@@ -9399,7 +8898,7 @@ namespace Mono.CSharp {
                                return EmptyExpressionStatement.Instance;
                        
                        MemberExpr me = MemberLookupFinal (ec, ec.CurrentInitializerVariable.Type, ec.CurrentInitializerVariable.Type,
-                               Name, MemberTypes.Field | MemberTypes.Property, BindingFlags.Public | BindingFlags.Instance, loc) as MemberExpr;
+                               Name, 0, MemberKind.Field | MemberKind.Property, BindingRestriction.AccessibleOnly | BindingRestriction.InstanceOnly, loc) as MemberExpr;
 
                        if (me == null)
                                return null;
@@ -9434,10 +8933,10 @@ namespace Mono.CSharp {
                        return expr;
                }
 
-               protected override Expression Error_MemberLookupFailed (ResolveContext ec, Type type, MemberInfo[] members)
+               protected override MemberExpr Error_MemberLookupFailed (ResolveContext ec, TypeSpec type, IList<MemberSpec> members)
                {
-                       MemberInfo member = members [0];
-                       if (member.MemberType != MemberTypes.Property && member.MemberType != MemberTypes.Field)
+                       var member = members.First ();
+                       if (member.Kind != MemberKind.Property && member.Kind != MemberKind.Field)
                                ec.Report.Error (1913, loc, "Member `{0}' cannot be initialized. An object " +
                                        "initializer may only be used for fields, or properties", TypeManager.GetFullNameSignature (member));
                        else
@@ -9476,7 +8975,7 @@ namespace Mono.CSharp {
                        {
                        }
 
-                       protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, Type type, string name)
+                       protected override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
                        {
                                if (TypeManager.HasElementType (type))
                                        return;
@@ -9595,7 +9094,7 @@ namespace Mono.CSharp {
                                                initializer.Resolve (ec);
                                                throw new InternalErrorException ("This line should never be reached");
                                        } else {
-                                               if (!TypeManager.ImplementsInterface (ec.CurrentInitializerVariable.Type, TypeManager.ienumerable_type)) {
+                                               if (!ec.CurrentInitializerVariable.Type.ImplementsInterface (TypeManager.ienumerable_type)) {
                                                        ec.Report.Error (1922, loc, "A field or property `{0}' cannot be initialized with a collection " +
                                                                "object initializer because type `{1}' does not implement `{2}' interface",
                                                                ec.CurrentInitializerVariable.GetSignatureForError (),
@@ -9652,12 +9151,6 @@ namespace Mono.CSharp {
                        foreach (ExpressionStatement e in initializers)
                                e.EmitStatement (ec);
                }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       foreach (Expression e in initializers)
-                               e.MutateHoistedGenericType (storey);
-               }
        }
        
        //
@@ -9808,17 +9301,11 @@ namespace Mono.CSharp {
                                return !initializers.IsEmpty;
                        }
                }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       base.MutateHoistedGenericType (storey);
-                       initializers.MutateHoistedGenericType (storey);
-               }
        }
 
        public class NewAnonymousType : New
        {
-               static readonly IList<AnonymousTypeParameter> EmptyParameters = Array.AsReadOnly (new AnonymousTypeParameter[0]);
+               static readonly AnonymousTypeParameter[] EmptyParameters = new AnonymousTypeParameter[0];
 
                List<AnonymousTypeParameter> parameters;
                readonly TypeContainer parent;
@@ -9852,7 +9339,9 @@ namespace Mono.CSharp {
                        if (type == null)
                                return null;
 
+                       type.CreateType ();
                        type.DefineType ();
+                       type.ResolveTypeParameters ();
                        type.Define ();
                        type.EmitType ();
                        if (ec.Report.Errors == 0)
@@ -9869,7 +9358,7 @@ namespace Mono.CSharp {
 
                        var init = new ArrayInitializer (parameters.Count, loc);
                        foreach (Property p in anonymous_type.Properties)
-                               init.Add (new TypeOfMethod (Import.CreateMethod (TypeBuilder.GetMethod (type, p.GetBuilder)), loc));
+                               init.Add (new TypeOfMethod (MemberCache.GetMember (type, p.Get.Spec), loc));
 
                        var ctor_args = new ArrayInitializer (Arguments.Count, loc);
                        foreach (Argument a in Arguments)
@@ -9892,7 +9381,7 @@ namespace Mono.CSharp {
 
                        if (parameters == null) {
                                anonymous_type = CreateAnonymousType (ec, EmptyParameters);
-                               RequestedType = new TypeExpression (anonymous_type.TypeBuilder, loc);
+                               RequestedType = new TypeExpression (anonymous_type.Definition, loc);
                                return base.DoResolve (ec);
                        }
 
@@ -9917,7 +9406,7 @@ namespace Mono.CSharp {
                        if (anonymous_type == null)
                                return null;
 
-                       RequestedType = new GenericTypeExpr (anonymous_type.TypeBuilder, new TypeArguments (t_args), loc);
+                       RequestedType = new GenericTypeExpr (anonymous_type.Definition, new TypeArguments (t_args), loc);
                        return base.DoResolve (ec);
                }
        }
index 5c01fb847243c377cdb92666fea3f0f6d34dd050..e43bf5ba4c53d5db0981fd7f1a96fc28487379f2 100644 (file)
@@ -51,7 +51,7 @@ namespace Mono.CSharp
                        }
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.Type == pa.FieldOffset) {
                                status |= Status.HAS_OFFSET;
@@ -91,26 +91,36 @@ namespace Mono.CSharp
                                return;
                        }
 
-                       FieldBuilder.SetCustomAttribute (cb);
+                       FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
                }
 
                protected override bool CheckBase ()
                {
                        if (!base.CheckBase ())
                                return false;
-                       MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
+
+                       MemberSpec candidate;
+                       var conflict_symbol = MemberCache.FindBaseMember (this, out candidate);
+                       if (conflict_symbol == null)
+                               conflict_symbol = candidate;
+
                        if (conflict_symbol == null) {
                                if ((ModFlags & Modifiers.NEW) != 0) {
-                                       Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
+                                       Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
+                                               GetSignatureForError ());
                                }
-                               return true;
-                       }
-                       if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.BACKING_FIELD)) == 0) {
-                               Report.SymbolRelatedToPreviousError (conflict_symbol);
-                               Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
-                                       GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
+                       } else {
+                               if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.BACKING_FIELD)) == 0) {
+                                       Report.SymbolRelatedToPreviousError (conflict_symbol);
+                                       Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
+                                               GetSignatureForError (), conflict_symbol.GetSignatureForError ());
+                               }
+
+                               if (conflict_symbol.IsAbstract) {
+                                       Report.SymbolRelatedToPreviousError (conflict_symbol);
+                                       Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
+                                               GetSignatureForError (), conflict_symbol.GetSignatureForError ());
+                               }
                        }
  
                        return true;
@@ -125,12 +135,11 @@ namespace Mono.CSharp
                {
                        base.DoMemberTypeDependentChecks ();
 
-                       if (TypeManager.IsGenericParameter (MemberType))
+                       if (MemberType.IsGenericParameter)
                                return;
 
-                       if (MemberType.IsSealed && MemberType.IsAbstract) {
+                       if (MemberType.IsStatic)
                                Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType, Report);
-                       }
 
                        CheckBase ();
                        IsTypePermitted ();
@@ -145,13 +154,13 @@ namespace Mono.CSharp
 
                public override void Emit ()
                {
-                       if (TypeManager.IsDynamicType (member_type)) {
+                       if (member_type == InternalType.Dynamic) {
                                PredefinedAttributes.Get.Dynamic.EmitAttribute (FieldBuilder);
                        } else {
                                var trans_flags = TypeManager.HasDynamicTypeUsed (member_type);
                                if (trans_flags != null) {
                                        var pa = PredefinedAttributes.Get.DynamicTransform;
-                                       if (pa.Constructor != null || pa.ResolveConstructor (Location, TypeManager.bool_type.MakeArrayType ())) {
+                                       if (pa.Constructor != null || pa.ResolveConstructor (Location, ArrayContainer.MakeType (TypeManager.bool_type, 1))) {
                                                FieldBuilder.SetCustomAttribute (new CustomAttributeBuilder (pa.Constructor, new object[] { trans_flags }));
                                        }
                                }
@@ -171,7 +180,7 @@ namespace Mono.CSharp
                        base.Emit ();
                }
 
-               public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class, Report Report)
+               public static void Error_VariableOfStaticClass (Location loc, string variable_name, TypeSpec static_class, Report Report)
                {
                        Report.SymbolRelatedToPreviousError (static_class);
                        Report.Error (723, loc, "`{0}': cannot declare variables of static types",
@@ -189,15 +198,6 @@ namespace Mono.CSharp
                        }
                }
 
-               protected virtual bool IsFieldClsCompliant {
-                       get {
-                               if (FieldBuilder == null)
-                                       return true;
-
-                               return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
-                       }
-               }
-
                public FieldSpec Spec {
                        get { return spec; }
                }
@@ -214,56 +214,90 @@ namespace Mono.CSharp
                        if (!base.VerifyClsCompliance ())
                                return false;
 
-                       if (!IsFieldClsCompliant) {
+                       if (!MemberType.IsCLSCompliant () || this is FixedField) {
                                Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
                                        GetSignatureForError ());
                        }
                        return true;
                }
-
-               public void SetAssigned ()
-               {
-                       caching_flags |= Flags.IsAssigned;
-               }
        }
 
        //
        // Field specification
        //
-       public class FieldSpec : MemberSpec
+       public class FieldSpec : MemberSpec, IInterfaceMemberSpec
        {
-               FieldInfo info;
+               FieldInfo metaInfo;
+               TypeSpec memberType;
 
-               public FieldSpec (IMemberDefinition definition, FieldInfo info, Modifiers modifiers)
-                       : base (MemberKind.Field, definition, info.Name, modifiers)
+               public FieldSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, FieldInfo info, Modifiers modifiers)
+                       : base (MemberKind.Field, declaringType, definition, modifiers)
                {
-                       this.info = info;
+                       this.metaInfo = info;
+                       this.memberType = memberType;
                }
 
-               public bool IsReadOnly {
-                       get { return (Modifiers & Modifiers.READONLY) != 0; }
-               }
+#region Properties
 
-               public FieldInfo MetaInfo {
+               public bool IsReadOnly {
                        get {
-                               return info;
-                       }
-                       set {
-                               info = value;
+                               return (Modifiers & Modifiers.READONLY) != 0;
                        }
                }
 
-               public override Type DeclaringType {
+               public TypeSpec MemberType {
                        get {
-                               return MetaInfo.DeclaringType;
+                               return memberType;
                        }
                }
 
-               // Obsolete
-               public Type FieldType {
-                       get {
-                                return MetaInfo.FieldType;
+#endregion
+
+               public FieldInfo GetMetaInfo ()
+               {
+                       if ((state & StateFlags.PendingMetaInflate) != 0) {
+                               var decl_meta = DeclaringType.GetMetaInfo ();
+                               if (DeclaringType.IsTypeBuilder) {
+                                       metaInfo = TypeBuilder.GetField (decl_meta, metaInfo);
+                               } else {
+                                       var orig_token = metaInfo.MetadataToken;
+                                       metaInfo = decl_meta.GetField (Name);
+                                       if (metaInfo.MetadataToken != orig_token)
+                                               throw new NotImplementedException ("Resolved to wrong meta token");
+
+                                       // What a stupid API, does not work because field handle is imported
+                                       // metaInfo = FieldInfo.GetFieldFromHandle (metaInfo.FieldHandle, DeclaringType.MetaInfo.TypeHandle);
+                               }
+
+                               state &= ~StateFlags.PendingMetaInflate;
                        }
+
+                       return metaInfo;
+               }
+
+               public override MemberSpec InflateMember (TypeParameterInflator inflator)
+               {
+                       var fs = (FieldSpec) base.InflateMember (inflator);
+                       fs.memberType = inflator.Inflate (memberType);
+                       return fs;
+               }
+
+               public FieldSpec Mutate (TypeParameterMutator mutator)
+               {
+                       var decl = DeclaringType;
+                       if (DeclaringType.IsGenericOrParentIsGeneric)
+                               decl = mutator.Mutate (decl);
+
+                       if (decl == DeclaringType)
+                               return this;
+
+                       var fs = (FieldSpec) MemberwiseClone ();
+                       fs.declaringType = decl;
+                       fs.state |= StateFlags.PendingMetaInflate;
+
+                       // Gets back FieldInfo in case of metaInfo was inflated
+                       fs.metaInfo = MemberCache.GetMember (DeclaringType.GetDefinition (), this).metaInfo;
+                       return fs;
                }
        }
 
@@ -313,17 +347,16 @@ namespace Mono.CSharp
                        // Create nested fixed buffer container
                        string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
                        fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name, Parent.Module.DefaultCharSetType |
-                               TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
-                       
-                       var element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
+                               TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type.GetMetaInfo ());
+
+                       fixed_buffer_type.DefineField (FixedElementName, MemberType.GetMetaInfo (), FieldAttributes.Public);
                        RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
                        
                        FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, ModifiersExtensions.FieldAttr (ModFlags));
-                       spec = new FixedFieldSpec (this, FieldBuilder, element, ModFlags);
-
-                       Parent.MemberCache.AddMember (FieldBuilder, spec);
-                       TypeManager.RegisterFieldBase (FieldBuilder, this);
+                       var element_spec = new FieldSpec (null, this, MemberType, FieldBuilder, ModFlags);
+                       spec = new FixedFieldSpec (Parent.Definition, this, FieldBuilder, element_spec, ModFlags);
 
+                       Parent.MemberCache.AddMember (spec);
                        return true;
                }
 
@@ -381,8 +414,10 @@ namespace Mono.CSharp
                                        return;
 
                        // TODO: It's not cleared
-                       if (fi == null)
-                               fi = new FieldInfo[] { pa.Type.GetField ("Size") };
+                       if (fi == null) {
+                               var field = (FieldSpec) MemberCache.FindMember (pa.Type, MemberFilter.Field ("Size", null), BindingRestriction.DeclaredOnly);
+                               fi = new FieldInfo[] { field.GetMetaInfo () };
+                       }
 
                        object[] fi_val = new object[] { buffer_size };
                        cab = new CustomAttributeBuilder (pa.Constructor,
@@ -400,16 +435,10 @@ namespace Mono.CSharp
                                !pa.ResolveConstructor (Location, TypeManager.type_type, TypeManager.int32_type))
                                return;
 
-                       cab = new CustomAttributeBuilder (pa.Constructor, new object[] { MemberType, buffer_size });
+                       cab = new CustomAttributeBuilder (pa.Constructor, new object[] { MemberType.GetMetaInfo (), buffer_size });
                        FieldBuilder.SetCustomAttribute (cab);
                }
 
-               protected override bool IsFieldClsCompliant {
-                       get {
-                               return false;
-                       }
-               }
-
                public void SetCharSet (TypeAttributes ta)
                {
                        TypeAttributes cta = fixed_buffer_type.Attributes;
@@ -434,23 +463,26 @@ namespace Mono.CSharp
 
        class FixedFieldSpec : FieldSpec
        {
-               readonly FieldInfo element;
+               readonly FieldSpec element;
 
-               public FixedFieldSpec (IMemberDefinition definition, FieldInfo info, FieldInfo element, Modifiers modifiers)
-                        : base (definition, info, modifiers)
+               public FixedFieldSpec (TypeSpec declaringType, IMemberDefinition definition, FieldInfo info, FieldSpec element, Modifiers modifiers)
+                       : base (declaringType, definition, element.MemberType, info, modifiers)
                {
                        this.element = element;
+
+                       // It's never CLS-Compliant
+                       state &= ~StateFlags.CLSCompliant_Undetected;
                }
 
-               public FieldInfo Element {
+               public FieldSpec Element {
                        get {
                                return element;
                        }
                }
 
-               public Type ElementType {
+               public TypeSpec ElementType {
                        get {
-                               return element.FieldType;
+                               return MemberType;
                        }
                }
        }
@@ -492,36 +524,9 @@ namespace Mono.CSharp
                                MemberType == TypeManager.intptr_type || MemberType == TypeManager.uintptr_type)
                                return true;
 
-                       if (TypeManager.IsEnumType (MemberType))
-                               return true;
-
-                       return false;
-               }
-
-               bool CheckStructLayout (Type type, bool isStatic)
-               {
-                       if (TypeManager.IsBuiltinType (type))
+                       if (MemberType.IsEnum)
                                return true;
 
-                       if (isStatic) {
-                               if (!TypeManager.IsValueType (type) || TypeManager.IsEqual (type, Parent.TypeBuilder))
-                                       return true;
-                       }
-
-                       if (!TypeManager.IsEqual (TypeManager.DropGenericTypeArguments (type), Parent.TypeBuilder)) {
-                               if (!TypeManager.IsGenericType (type))
-                                       return true;
-
-                               foreach (Type t in TypeManager.GetTypeArguments (type)) {
-                                       if (!CheckStructLayout (t, false))
-                                               return false;
-                               }
-                               return true;
-                       }
-                       
-                       Report.Error (523, Location,
-                               "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
-                               GetSignatureForError (), TypeManager.CSharpName (MemberType));
                        return false;
                }
 
@@ -538,20 +543,18 @@ namespace Mono.CSharp
                                                        "System.Runtime.CompilerServices", "IsVolatile", MemberKind.Class, true);
 
                                        if (TypeManager.isvolatile_type != null)
-                                               required_modifier = new Type [] { TypeManager.isvolatile_type };
+                                               required_modifier = new Type[] { TypeManager.isvolatile_type.GetMetaInfo () };
                                }
 
                                FieldBuilder = Parent.TypeBuilder.DefineField (
-                                       Name, MemberType, required_modifier, null, ModifiersExtensions.FieldAttr (ModFlags));
+                                       Name, member_type.GetMetaInfo (), required_modifier, null, ModifiersExtensions.FieldAttr (ModFlags));
 
-                               spec = new FieldSpec (this, FieldBuilder, ModFlags);
+                               spec = new FieldSpec (Parent.Definition, this, MemberType, FieldBuilder, ModFlags);
 
                                // Don't cache inaccessible fields
                                if ((ModFlags & Modifiers.BACKING_FIELD) == 0) {
-                                       Parent.MemberCache.AddMember (FieldBuilder, spec);
+                                       Parent.MemberCache.AddMember (spec);
                                }
-
-                               TypeManager.RegisterFieldBase (FieldBuilder, this);
                        }
                        catch (ArgumentException) {
                                Report.RuntimeMissingSupport (Location, "`void' or `void*' field type");
@@ -561,9 +564,6 @@ namespace Mono.CSharp
                        if (initializer != null) {
                                ((TypeContainer) Parent).RegisterFieldForInitialization (this,
                                        new FieldInitializer (this, initializer, this));
-                       } else {
-                               if (Parent.PartialContainer.Kind == MemberKind.Struct)
-                                       CheckStructLayout (member_type, (ModFlags & Modifiers.STATIC) != 0);
                        }
 
                        return true;
@@ -571,6 +571,9 @@ namespace Mono.CSharp
 
                protected override void DoMemberTypeDependentChecks ()
                {
+                       if ((ModFlags & Modifiers.BACKING_FIELD) != 0)
+                               return;
+
                        base.DoMemberTypeDependentChecks ();
 
                        if ((ModFlags & Modifiers.VOLATILE) != 0) {
index 035574ba5fe3184f8e5a43b7bee71de114235130..bc35e3591e9925c42d1eadcd95332a78336a3b06 100644 (file)
@@ -1014,7 +1014,7 @@ namespace Mono.CSharp
        // </summary>
        public class TypeInfo
        {
-               public readonly Type Type;
+               public readonly TypeSpec Type;
 
                // <summary>
                //   Total number of bits a variable of this type consumes in the flow vector.
@@ -1043,7 +1043,7 @@ namespace Mono.CSharp
                public TypeInfo[] SubStructInfo;
 
                readonly StructInfo struct_info;
-               private static Dictionary<Type, TypeInfo> type_hash;
+               private static Dictionary<TypeSpec, TypeInfo> type_hash;
                
                static TypeInfo ()
                {
@@ -1052,11 +1052,11 @@ namespace Mono.CSharp
                
                public static void Reset ()
                {
-                       type_hash = new Dictionary<Type, TypeInfo> ();
-                       StructInfo.field_type_hash = new Dictionary<Type, StructInfo> ();
+                       type_hash = new Dictionary<TypeSpec, TypeInfo> ();
+                       StructInfo.field_type_hash = new Dictionary<TypeSpec, StructInfo> ();
                }
 
-               public static TypeInfo GetTypeInfo (Type type)
+               public static TypeInfo GetTypeInfo (TypeSpec type)
                {
                        TypeInfo info;
                        if (type_hash.TryGetValue (type, out info))
@@ -1070,15 +1070,15 @@ namespace Mono.CSharp
                public static TypeInfo GetTypeInfo (TypeContainer tc)
                {
                        TypeInfo info;
-                       if (type_hash.TryGetValue (tc.TypeBuilder, out info))
+                       if (type_hash.TryGetValue (tc.Definition, out info))
                                return info;
 
                        info = new TypeInfo (tc);
-                       type_hash.Add (tc.TypeBuilder, info);
+                       type_hash.Add (tc.Definition, info);
                        return info;
                }
 
-               private TypeInfo (Type type)
+               private TypeInfo (TypeSpec type)
                {
                        this.Type = type;
 
@@ -1097,7 +1097,7 @@ namespace Mono.CSharp
 
                private TypeInfo (TypeContainer tc)
                {
-                       this.Type = tc.TypeBuilder;
+                       this.Type = tc.Definition;
 
                        struct_info = StructInfo.GetStructInfo (tc);
                        if (struct_info != null) {
@@ -1154,15 +1154,14 @@ namespace Mono.CSharp
                                var field = struct_info.Fields [i];
 
                                if (!branching.IsFieldAssigned (vi, field.Name)) {
-                                       FieldBase fb = TypeManager.GetField (field.MetaInfo);
-                                       if (fb is Property.BackingField) {
+                                       if (field.MemberDefinition is Property.BackingField) {
                                                ec.Report.Error (843, loc,
                                                        "An automatically implemented property `{0}' must be fully assigned before control leaves the constructor. Consider calling default contructor",
-                                                       fb.GetSignatureForError ());
+                                                       field.GetSignatureForError ());
                                        } else {
                                                ec.Report.Error (171, loc,
                                                        "Field `{0}' must be fully assigned before control leaves the constructor",
-                                                       TypeManager.GetFullNameSignature (field.MetaInfo));
+                                                       field.GetSignatureForError ());
                                        }
                                        ok = false;
                                }
@@ -1178,7 +1177,7 @@ namespace Mono.CSharp
                }
 
                class StructInfo {
-                       public readonly Type Type;
+                       public readonly TypeSpec Type;
                        public readonly FieldSpec[] Fields;
                        public readonly TypeInfo[] StructFields;
                        public readonly int Count;
@@ -1188,7 +1187,7 @@ namespace Mono.CSharp
                        public readonly int TotalLength;
                        public readonly bool HasStructFields;
 
-                       public static Dictionary<Type, StructInfo> field_type_hash;
+                       public static Dictionary<TypeSpec, StructInfo> field_type_hash;
                        private Dictionary<string, TypeInfo> struct_field_hash;
                        private Dictionary<string, int> field_hash;
 
@@ -1196,64 +1195,39 @@ namespace Mono.CSharp
 
                        // Private constructor.  To save memory usage, we only need to create one instance
                        // of this class per struct type.
-                       private StructInfo (Type type)
+                       private StructInfo (TypeSpec type)
                        {
                                this.Type = type;
 
                                field_type_hash.Add (type, this);
 
-                               if (TypeManager.IsBeingCompiled (type)) {
-                                       TypeContainer tc = TypeManager.LookupTypeContainer (TypeManager.DropGenericTypeArguments (type));
-
-                                       var public_fields = new List<FieldSpec> ();
-                                       var non_public_fields = new List<FieldSpec> ();
-
-                                       //
-                                       // TODO: tc != null is needed because FixedBuffers are not cached
-                                       //
-                                       if (tc != null) {
-                                               var fields = tc.Fields;
-
-                                               if (fields != null) {
-                                                       foreach (FieldBase field in fields) {
-                                                               if ((field.ModFlags & Modifiers.STATIC) != 0)
-                                                                       continue;
-                                                               if ((field.ModFlags & Modifiers.PUBLIC) != 0)
-                                                                       public_fields.Add (field.Spec);
-                                                               else
-                                                                       non_public_fields.Add (field.Spec);
-                                                       }
-                                               }
-                                       }
+                               TypeContainer tc = type.MemberDefinition as TypeContainer;
 
-                                       CountPublic = public_fields.Count;
-                                       CountNonPublic = non_public_fields.Count;
-                                       Count = CountPublic + CountNonPublic;
+                               var public_fields = new List<FieldSpec> ();
+                               var non_public_fields = new List<FieldSpec> ();
 
-                                       Fields = new FieldSpec [Count];
-                                       public_fields.CopyTo (Fields, 0);
-                                       non_public_fields.CopyTo (Fields, CountPublic);
-                               } else if (type is GenericTypeParameterBuilder) {
-                                       CountPublic = CountNonPublic = Count = 0;
-
-                                       Fields = new FieldSpec [0];
-                               } else {
-                                       FieldInfo[] public_fields = type.GetFields (
-                                               BindingFlags.Instance|BindingFlags.Public);
-                                       FieldInfo[] non_public_fields = type.GetFields (
-                                               BindingFlags.Instance|BindingFlags.NonPublic);
+                               if (tc != null) {
+                                       var fields = tc.Fields;
 
-                                       CountPublic = public_fields.Length;
-                                       CountNonPublic = non_public_fields.Length;
-                                       Count = CountPublic + CountNonPublic;
+                                       if (fields != null) {
+                                               foreach (FieldBase field in fields) {
+                                                       if ((field.ModFlags & Modifiers.STATIC) != 0)
+                                                               continue;
+                                                       if ((field.ModFlags & Modifiers.PUBLIC) != 0)
+                                                               public_fields.Add (field.Spec);
+                                                       else
+                                                               non_public_fields.Add (field.Spec);
+                                               }
+                                       }
+                               }
 
-                                       Fields = new FieldSpec [Count];
-                                       for (int i = 0; i < CountPublic; ++i)
-                                               Fields [i] = Import.CreateField (public_fields[i]);
+                               CountPublic = public_fields.Count;
+                               CountNonPublic = non_public_fields.Count;
+                               Count = CountPublic + CountNonPublic;
 
-                                       for (int i = 0; i < CountNonPublic; ++i)
-                                               Fields [i + CountPublic] = Import.CreateField (non_public_fields[i]);
-                               }
+                               Fields = new FieldSpec[Count];
+                               public_fields.CopyTo (Fields, 0);
+                               non_public_fields.CopyTo (Fields, CountPublic);
 
                                struct_field_hash = new Dictionary<string, TypeInfo> ();
                                field_hash = new Dictionary<string, int> ();
@@ -1267,14 +1241,10 @@ namespace Mono.CSharp
                                for (int i = 0; i < Count; i++) {
                                        var field = Fields [i];
 
-                                       sinfo [i] = GetStructInfo (field.FieldType);
+                                       sinfo [i] = GetStructInfo (field.MemberType);
                                        if (sinfo [i] == null)
                                                field_hash.Add (field.Name, ++Length);
                                        else if (sinfo [i].InTransit) {
-                                               RootContext.ToplevelTypes.Compiler.Report.Error (523, String.Format (
-                                                                     "Struct member `{0}.{1}' of type `{2}' causes " +
-                                                                     "a cycle in the structure layout",
-                                                                     type, field.Name, sinfo [i].Type));
                                                sinfo [i] = null;
                                                return;
                                        }
@@ -1317,7 +1287,7 @@ namespace Mono.CSharp
                                return null;
                        }
 
-                       public static StructInfo GetStructInfo (Type type)
+                       public static StructInfo GetStructInfo (TypeSpec type)
                        {
                                if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type) ||
                                    TypeManager.IsBuiltinType (type))
@@ -1336,10 +1306,10 @@ namespace Mono.CSharp
                        public static StructInfo GetStructInfo (TypeContainer tc)
                        {
                                StructInfo info;
-                               if (field_type_hash.TryGetValue (tc.TypeBuilder, out info))
+                               if (field_type_hash.TryGetValue (tc.Definition, out info))
                                        return info;
 
-                               return new StructInfo (tc.TypeBuilder);
+                               return new StructInfo (tc.Definition);
                        }
                }
        }
@@ -1381,7 +1351,7 @@ namespace Mono.CSharp
                        get { return is_ever_assigned; }
                }
 
-               protected VariableInfo (string name, Type type, int offset)
+               protected VariableInfo (string name, TypeSpec type, int offset)
                {
                        this.Name = name;
                        this.Offset = offset;
index 9df0cb14e6ee27712c2bb47300fe5f51f727a33f..53b5d841426cf94482cdb50f48dcb70a239a5582 100644 (file)
@@ -16,177 +16,9 @@ using System.Reflection.Emit;
 using System.Globalization;
 using System.Collections.Generic;
 using System.Text;
+using System.Linq;
        
 namespace Mono.CSharp {
-
-       /// <summary>
-       ///   Abstract base class for type parameter constraints.
-       ///   The type parameter can come from a generic type definition or from reflection.
-       /// </summary>
-       public abstract class GenericConstraints {
-               public abstract GenericParameterAttributes Attributes {
-                       get;
-               }
-
-               public bool HasConstructorConstraint {
-                       get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
-               }
-
-               public bool HasReferenceTypeConstraint {
-                       get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
-               }
-
-               public bool HasValueTypeConstraint {
-                       get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
-               }
-
-               public virtual bool HasClassConstraint {
-                       get { return ClassConstraint != null; }
-               }
-
-               public abstract Type ClassConstraint {
-                       get;
-               }
-
-               public abstract Type[] InterfaceConstraints {
-                       get;
-               }
-
-               public abstract Type EffectiveBaseClass {
-                       get;
-               }
-
-               // <summary>
-               //   Returns whether the type parameter is "known to be a reference type".
-               // </summary>
-               public virtual bool IsReferenceType {
-                       get {
-                               if (HasReferenceTypeConstraint)
-                                       return true;
-                               if (HasValueTypeConstraint)
-                                       return false;
-
-                               if (ClassConstraint != null) {
-                                       if (ClassConstraint.IsValueType)
-                                               return false;
-
-                                       if (ClassConstraint != TypeManager.object_type)
-                                               return true;
-                               }
-
-                               foreach (Type t in InterfaceConstraints) {
-                                       if (!t.IsGenericParameter)
-                                               continue;
-
-                                       GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
-                                       if ((gc != null) && gc.IsReferenceType)
-                                               return true;
-                               }
-
-                               return false;
-                       }
-               }
-
-               // <summary>
-               //   Returns whether the type parameter is "known to be a value type".
-               // </summary>
-               public virtual bool IsValueType {
-                       get {
-                               if (HasValueTypeConstraint)
-                                       return true;
-                               if (HasReferenceTypeConstraint)
-                                       return false;
-
-                               if (ClassConstraint != null) {
-                                       if (!TypeManager.IsValueType (ClassConstraint))
-                                               return false;
-
-                                       if (ClassConstraint != TypeManager.value_type)
-                                               return true;
-                               }
-
-                               foreach (Type t in InterfaceConstraints) {
-                                       if (!t.IsGenericParameter)
-                                               continue;
-
-                                       GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
-                                       if ((gc != null) && gc.IsValueType)
-                                               return true;
-                               }
-
-                               return false;
-                       }
-               }
-       }
-
-       public class ReflectionConstraints : GenericConstraints
-       {
-               GenericParameterAttributes attrs;
-               Type base_type;
-               Type class_constraint;
-               Type[] iface_constraints;
-
-               public static GenericConstraints GetConstraints (Type t)
-               {
-                       Type[] constraints = t.GetGenericParameterConstraints ();
-                       GenericParameterAttributes attrs = t.GenericParameterAttributes;
-                       if (constraints.Length == 0 && attrs == GenericParameterAttributes.None)
-                               return null;
-                       return new ReflectionConstraints (t.Name, constraints, attrs);
-               }
-
-               private ReflectionConstraints (string name, Type[] constraints, GenericParameterAttributes attrs)
-               {
-                       this.attrs = attrs;
-
-                       int interface_constraints_pos = 0;
-                       if ((attrs & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
-                               base_type = TypeManager.value_type;
-                               interface_constraints_pos = 1;
-                       } else if ((attrs & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
-                               if (constraints.Length > 0 && constraints[0].IsClass) {
-                                       class_constraint = base_type = constraints[0];
-                                       interface_constraints_pos = 1;
-                               } else {
-                                       base_type = TypeManager.object_type;
-                               }
-                       } else {
-                               base_type = TypeManager.object_type;
-                       }
-
-                       if (constraints.Length > interface_constraints_pos) {
-                               if (interface_constraints_pos == 0) {
-                                       iface_constraints = constraints;
-                               } else {
-                                       iface_constraints = new Type[constraints.Length - interface_constraints_pos];
-                                       Array.Copy (constraints, interface_constraints_pos, iface_constraints, 0, iface_constraints.Length);
-                               }
-                       } else {
-                               iface_constraints = Type.EmptyTypes;
-                       }
-               }
-
-               public override GenericParameterAttributes Attributes
-               {
-                       get { return attrs; }
-               }
-
-               public override Type ClassConstraint
-               {
-                       get { return class_constraint; }
-               }
-
-               public override Type EffectiveBaseClass
-               {
-                       get { return base_type; }
-               }
-
-               public override Type[] InterfaceConstraints
-               {
-                       get { return iface_constraints; }
-               }
-       }
-
        public enum Variance
        {
                //
@@ -225,26 +57,14 @@ namespace Mono.CSharp {
        //
        // A set of parsed constraints for a type parameter
        //
-       public class Constraints : GenericConstraints
+       public class Constraints
        {
                SimpleMemberName tparam;
                List<FullNamedExpression> constraints;
                Location loc;
-               GenericParameterAttributes attrs;
-               TypeExpr class_constraint;
-               List<TypeExpr> iface_constraints;
-               List<TypeExpr> type_param_constraints;
-               int num_constraints;
-               Type class_constraint_type;
-               Type[] iface_constraint_types;
-               Type effective_base_type;
                bool resolved;
-               bool resolved_types;
+               bool resolving;
                
-               //
-               // name is the identifier, constraints is an arraylist of
-               // Expressions (with types) or `true' for the constructor constraint.
-               // 
                public Constraints (SimpleMemberName tparam, List<FullNamedExpression> constraints, Location loc)
                {
                        this.tparam = tparam;
@@ -254,6 +74,12 @@ namespace Mono.CSharp {
 
                #region Properties
 
+               public Location Location {
+                       get {
+                               return loc;
+                       }
+               }
+
                public SimpleMemberName TypeParameter {
                        get {
                                return tparam;
@@ -262,473 +88,407 @@ namespace Mono.CSharp {
 
                #endregion
 
-               public Constraints Clone ()
+               bool CheckConflictingInheritedConstraint (TypeSpec ba, TypeSpec bb, IMemberContext context, Location loc)
                {
-                       return new Constraints (tparam, constraints, loc);
+                       if (!TypeManager.IsSubclassOf (ba, bb) && !TypeManager.IsSubclassOf (bb, ba)) {
+                               context.Compiler.Report.Error (455, loc,
+                                       "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
+                                       tparam.Value,
+                                       ba.GetSignatureForError (), bb.GetSignatureForError ());
+                               return false;
+                       }
+
+                       return true;
                }
 
-               /// <summary>
-               ///   Resolve the constraints - but only resolve things into Expression's, not
-               ///   into actual types.
-               /// </summary>
-               public bool Resolve (MemberCore ec, TypeParameter tp, Report Report)
+               public void CheckGenericConstraints (IMemberContext context)
+               {
+                       foreach (var c in constraints) {
+                               var ge = c as GenericTypeExpr;
+                               if (ge != null)
+                                       ge.CheckConstraints (context);
+                       }
+               }
+
+               //
+               // Resolve the constraints types with only possible early checks, return
+               // value `false' is reserved for recursive failure
+               //
+               public bool Resolve (IMemberContext context, TypeParameter tp)
                {
                        if (resolved)
                                return true;
 
-                       if (ec == null)
+                       if (resolving)
                                return false;
 
-                       iface_constraints = new List<TypeExpr> (2);     // TODO: Too expensive allocation
-                       type_param_constraints = new List<TypeExpr> ();
+                       resolving = true;
+                       var spec = tp.Type;
+                       List<TypeParameterSpec> tparam_types = null;
+                       bool iface_found = false;
 
-                       foreach (var obj in constraints) {
+                       spec.BaseType = TypeManager.object_type;
 
-                               if (obj is SpecialContraintExpr) {
-                                       SpecialConstraint sc = ((SpecialContraintExpr) obj).Constraint;
+                       for (int i = 0; i < constraints.Count; ++i) {
+                               var constraint = constraints[i];
 
-                                       if (sc == SpecialConstraint.Constructor) {
-                                               if (!HasValueTypeConstraint) {
-                                                       attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
-                                                       continue;
-                                               }
-                                       }
+                               if (constraint is SpecialContraintExpr) {
+                                       spec.SpecialConstraint |= ((SpecialContraintExpr) constraint).Constraint;
+                                       if (spec.HasSpecialStruct)
+                                               spec.BaseType = TypeManager.value_type;
 
-                                       if (sc == SpecialConstraint.Class)
-                                               attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
-                                       else
-                                               attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
+                                       // Set to null as it does not have a type
+                                       constraints[i] = null;
                                        continue;
                                }
 
-                               int errors = Report.Errors;
-                               FullNamedExpression fn = obj.ResolveAsTypeStep (ec, false);
-
-                               if (fn == null) {
-                                       if (errors != Report.Errors)
-                                               return false;
+                               var type_expr = constraints[i] = constraint.ResolveAsTypeTerminal (context, false);
+                               if (type_expr == null)
+                                       continue;
 
-                                       NamespaceEntry.Error_NamespaceNotFound (loc, obj.GetSignatureForError (), Report);
-                                       return false;
+                               var gexpr = type_expr as GenericTypeExpr;
+                               if (gexpr != null && gexpr.HasDynamicArguments ()) {
+                                       context.Compiler.Report.Error (1968, constraint.Location,
+                                               "A constraint cannot be the dynamic type `{0}'", gexpr.GetSignatureForError ());
+                                       continue;
                                }
 
-                               TypeExpr expr;
-                               GenericTypeExpr cexpr = fn as GenericTypeExpr;
-                               if (cexpr != null) {
-                                       expr = cexpr.ResolveAsBaseTerminal (ec, false);
-                                       if (expr != null && cexpr.HasDynamicArguments ()) {
-                                               Report.Error (1968, cexpr.Location,
-                                                       "A constraint cannot be the dynamic type `{0}'",
-                                                       cexpr.GetSignatureForError ());
-                                               expr = null;
-                                       }
-                               } else
-                                       expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false);
-
-                               if ((expr == null) || (expr.Type == null))
-                                       return false;
+                               var type = type_expr.Type;
 
-                               if (TypeManager.IsGenericParameter (expr.Type))
-                                       type_param_constraints.Add (expr);
-                               else if (expr.IsInterface)
-                                       iface_constraints.Add (expr);
-                               else if (class_constraint != null || iface_constraints.Count != 0) {
-                                       Report.Error (406, loc,
-                                               "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
-                                               expr.GetSignatureForError ());
-                                       return false;
-                               } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
-                                       Report.Error (450, loc, "`{0}': cannot specify both " +
-                                                     "a constraint class and the `class' " +
-                                                     "or `struct' constraint", expr.GetSignatureForError ());
-                                       return false;
-                               } else
-                                       class_constraint = expr;
+                               if (!context.CurrentMemberDefinition.IsAccessibleAs (type)) {
+                                       context.Compiler.Report.SymbolRelatedToPreviousError (type);
+                                       context.Compiler.Report.Error (703, loc,
+                                               "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
+                                               type.GetSignatureForError (), context.GetSignatureForError ());
+                               }
 
+                               if (type.IsInterface) {
+                                       if (!spec.AddInterface (type)) {
+                                               context.Compiler.Report.Error (405, constraint.Location,
+                                                       "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
+                                       }
 
-                               //
-                               // Checks whether each generic method parameter constraint type
-                               // is valid with respect to T
-                               //
-                               if (tp != null && tp.Type.DeclaringMethod != null) {
-                                       TypeManager.CheckTypeVariance (expr.Type, Variance.Contravariant, ec as MemberCore);
+                                       iface_found = true;
+                                       continue;
                                }
 
-                               if (!ec.IsAccessibleAs (fn.Type)) {
-                                       Report.SymbolRelatedToPreviousError (fn.Type);
-                                       Report.Error (703, loc,
-                                               "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
-                                               fn.GetSignatureForError (), ec.GetSignatureForError ());
-                               }
 
-                               num_constraints++;
-                       }
+                               var constraint_tp = type as TypeParameterSpec;
+                               if (constraint_tp != null) {
+                                       if (tparam_types == null) {
+                                               tparam_types = new List<TypeParameterSpec> (2);
+                                       } else if (tparam_types.Contains (constraint_tp)) {
+                                               context.Compiler.Report.Error (405, constraint.Location,
+                                                       "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
+                                               continue;
+                                       }
+
+                                       //
+                                       // Checks whether each generic method parameter constraint type
+                                       // is valid with respect to T
+                                       //
+                                       if (tp.IsMethodTypeParameter) {
+                                               TypeManager.CheckTypeVariance (type, Variance.Contravariant, context);
+                                       }
 
-                       var list = new List<Type> ();
-                       foreach (TypeExpr iface_constraint in iface_constraints) {
-                               foreach (Type type in list) {
-                                       if (!type.Equals (iface_constraint.Type))
+                                       var tp_def = constraint_tp.MemberDefinition as TypeParameter;
+                                       if (tp_def != null && !tp_def.ResolveConstraints (context)) {
+                                               context.Compiler.Report.Error (454, constraint.Location,
+                                                       "Circular constraint dependency involving `{0}' and `{1}'",
+                                                       constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
                                                continue;
+                                       }
 
-                                       Report.Error (405, loc,
-                                                     "Duplicate constraint `{0}' for type " +
-                                                     "parameter `{1}'.", iface_constraint.GetSignatureForError (),
-                                                     tparam.Value);
-                                       return false;
-                               }
+                                       //
+                                       // Checks whether there are no conflicts between type parameter constraints
+                                       //
+                                       // class Foo<T, U>
+                                       //      where T : A
+                                       //      where U : B, T
+                                       //
+                                       // A and B are not convertible and only 1 class constraint is allowed
+                                       //
+                                       if (constraint_tp.HasTypeConstraint) {
+                                               if (spec.HasTypeConstraint || spec.HasSpecialStruct) {
+                                                       if (!CheckConflictingInheritedConstraint (spec.BaseType, constraint_tp.BaseType, context, constraint.Location))
+                                                               continue;
+                                               } else {
+                                                       for (int ii = 0; ii < tparam_types.Count; ++ii) {
+                                                               if (!tparam_types[ii].HasTypeConstraint)
+                                                                       continue;
 
-                               list.Add (iface_constraint.Type);
-                       }
+                                                               if (!CheckConflictingInheritedConstraint (tparam_types[ii].BaseType, constraint_tp.BaseType, context, constraint.Location))
+                                                                       break;
+                                                       }
+                                               }
+                                       }
 
-                       foreach (TypeExpr expr in type_param_constraints) {
-                               foreach (Type type in list) {
-                                       if (!type.Equals (expr.Type))
+                                       if (constraint_tp.HasSpecialStruct) {
+                                               context.Compiler.Report.Error (456, constraint.Location,
+                                                       "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
+                                                       constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
                                                continue;
+                                       }
 
-                                       Report.Error (405, loc,
-                                                     "Duplicate constraint `{0}' for type " +
-                                                     "parameter `{1}'.", expr.GetSignatureForError (), tparam.Value);
-                                       return false;
+                                       tparam_types.Add (constraint_tp);
+                                       continue;
                                }
 
-                               list.Add (expr.Type);
-                       }
-
-                       iface_constraint_types = new Type [list.Count];
-                       list.CopyTo (iface_constraint_types, 0);
+                               if (iface_found || spec.HasTypeConstraint) {
+                                       context.Compiler.Report.Error (406, constraint.Location,
+                                               "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
+                                               type.GetSignatureForError ());
+                               }
 
-                       if (class_constraint != null) {
-                               class_constraint_type = class_constraint.Type;
-                               if (class_constraint_type == null)
-                                       return false;
+                               if (spec.HasSpecialStruct || spec.HasSpecialClass) {
+                                       context.Compiler.Report.Error (450, type_expr.Location,
+                                               "`{0}': cannot specify both a constraint class and the `class' or `struct' constraint",
+                                               type.GetSignatureForError ());
+                               }
 
-                               if (class_constraint_type.IsSealed) {
-                                       if (class_constraint_type.IsAbstract)
-                                       {
-                                               Report.Error (717, loc, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
-                                                       TypeManager.CSharpName (class_constraint_type));
-                                       }
-                                       else
-                                       {
-                                               Report.Error (701, loc, "`{0}' is not a valid constraint. A constraint must be an interface, " +
-                                                       "a non-sealed class or a type parameter", TypeManager.CSharpName(class_constraint_type));
-                                       }
-                                       return false;
+                               if (type == InternalType.Dynamic) {
+                                       context.Compiler.Report.Error (1967, constraint.Location, "A constraint cannot be the dynamic type");
+                                       continue;
                                }
 
-                               if ((class_constraint_type == TypeManager.array_type) ||
-                                   (class_constraint_type == TypeManager.delegate_type) ||
-                                   (class_constraint_type == TypeManager.enum_type) ||
-                                   (class_constraint_type == TypeManager.value_type) ||
-                                   (class_constraint_type == TypeManager.object_type) ||
-                                       class_constraint_type == TypeManager.multicast_delegate_type) {
-                                       Report.Error (702, loc,
-                                                         "A constraint cannot be special class `{0}'",
-                                                     TypeManager.CSharpName (class_constraint_type));
-                                       return false;
+                               if (type.IsSealed || !type.IsClass) {
+                                       context.Compiler.Report.Error (701, loc,
+                                               "`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
+                                               TypeManager.CSharpName (type));
+                                       continue;
                                }
 
-                               if (TypeManager.IsDynamicType (class_constraint_type)) {
-                                       Report.Error (1967, loc, "A constraint cannot be the dynamic type");
-                                       return false;
+                               if (type.IsStatic) {
+                                       context.Compiler.Report.Error (717, constraint.Location,
+                                               "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
+                                               type.GetSignatureForError ());
+                               } else if (type == TypeManager.array_type || type == TypeManager.delegate_type ||
+                                                       type == TypeManager.enum_type || type == TypeManager.value_type ||
+                                                       type == TypeManager.object_type || type == TypeManager.multicast_delegate_type) {
+                                       context.Compiler.Report.Error (702, constraint.Location,
+                                               "A constraint cannot be special class `{0}'", type.GetSignatureForError ());
+                                       continue;
                                }
-                       }
 
-                       if (class_constraint_type != null)
-                               effective_base_type = class_constraint_type;
-                       else if (HasValueTypeConstraint)
-                               effective_base_type = TypeManager.value_type;
-                       else
-                               effective_base_type = TypeManager.object_type;
+                               spec.BaseType = type;
+                       }
 
-                       if ((attrs & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0)
-                               attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
+                       if (tparam_types != null)
+                               spec.TypeArguments = tparam_types.ToArray ();
 
+                       resolving = false;
                        resolved = true;
                        return true;
                }
 
-               bool CheckTypeParameterConstraints (Type tparam, ref TypeExpr prevConstraint, List<Type> seen, Report Report)
+               public void VerifyClsCompliance (Report report)
                {
-                       seen.Add (tparam);
-
-                       Constraints constraints = TypeManager.LookupTypeParameter (tparam).Constraints;
-                       if (constraints == null)
-                               return true;
-
-                       if (constraints.HasValueTypeConstraint) {
-                               Report.Error (456, loc,
-                                       "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
-                                       tparam.Name, this.tparam.Value);
-                               return false;
-                       }
-
-                       //
-                       //  Checks whether there are no conflicts between type parameter constraints
-                       //
-                       //   class Foo<T, U>
-                       //      where T : A
-                       //      where U : A, B  // A and B are not convertible
-                       //
-                       if (constraints.HasClassConstraint) {
-                               if (prevConstraint != null) {
-                                       Type t2 = constraints.ClassConstraint;
-                                       TypeExpr e2 = constraints.class_constraint;
-
-                                       if (!Convert.ImplicitReferenceConversionExists (prevConstraint, t2) &&
-                                               !Convert.ImplicitReferenceConversionExists (e2, prevConstraint.Type)) {
-                                               Report.Error (455, loc,
-                                                       "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
-                                                       this.tparam.Value, TypeManager.CSharpName (prevConstraint.Type), TypeManager.CSharpName (t2));
-                                               return false;
-                                       }
-                               }
-
-                               prevConstraint = constraints.class_constraint;
-                       }
-
-                       if (constraints.type_param_constraints == null)
-                               return true;
+                       foreach (var c in constraints)
+                       {
+                               if (c == null)
+                                       continue;
 
-                       foreach (TypeExpr expr in constraints.type_param_constraints) {
-                               if (seen.Contains (expr.Type)) {
-                                       Report.Error (454, loc, "Circular constraint " +
-                                                     "dependency involving `{0}' and `{1}'",
-                                                     tparam.Name, expr.GetSignatureForError ());
-                                       return false;
+                               if (!c.Type.IsCLSCompliant ()) {
+                                       report.SymbolRelatedToPreviousError (c.Type);
+                                       report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
+                                               c.Type.GetSignatureForError ());
                                }
-
-                               if (!CheckTypeParameterConstraints (expr.Type, ref prevConstraint, seen, Report))
-                                       return false;
                        }
-
-                       return true;
                }
+       }
 
-               /// <summary>
-               ///   Resolve the constraints into actual types.
-               /// </summary>
-               public bool ResolveTypes (IMemberContext ec, Report r)
-               {
-                       if (resolved_types)
-                               return true;
+       //
+       // A type parameter for a generic type or generic method definition
+       //
+       public class TypeParameter : MemberCore, ITypeDefinition
+       {
+               static readonly string[] attribute_target = new string [] { "type parameter" };
+               
+               Constraints constraints;
+               GenericTypeParameterBuilder builder;
+//             Variance variance;
+               TypeParameterSpec spec;
 
-                       resolved_types = true;
+               public TypeParameter (DeclSpace parent, int index, MemberName name, Constraints constraints, Attributes attrs, Variance variance)
+                       : base (parent, name, attrs)
+               {
+                       this.constraints = constraints;
+//                     this.variance = variance;
+                       this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, variance, null);
+               }
 
-                       foreach (object obj in constraints) {
-                               GenericTypeExpr cexpr = obj as GenericTypeExpr;
-                               if (cexpr == null)
-                                       continue;
+               #region Properties
 
-                               if (!cexpr.CheckConstraints (ec))
-                                       return false;
+               public override AttributeTargets AttributeTargets {
+                       get {
+                               return AttributeTargets.GenericParameter;
                        }
+               }
 
-                       if (type_param_constraints.Count != 0) {
-                               var seen = new List<Type> ();
-                               TypeExpr prev_constraint = class_constraint;
-                               foreach (TypeExpr expr in type_param_constraints) {
-                                       if (!CheckTypeParameterConstraints (expr.Type, ref prev_constraint, seen, r))
-                                               return false;
-                                       seen.Clear ();
-                               }
+               public override string DocCommentHeader {
+                       get {
+                               throw new InvalidOperationException (
+                                       "Unexpected attempt to get doc comment from " + this.GetType ());
                        }
+               }
 
-                       for (int i = 0; i < iface_constraints.Count; ++i) {
-                               TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
-                               iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
-                               if (iface_constraint == null)
-                                       return false;
-                               iface_constraints [i] = iface_constraint;
+               public bool IsMethodTypeParameter {
+                       get {
+                               return spec.IsMethodOwned;
                        }
+               }
 
-                       if (class_constraint != null) {
-                               class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
-                               if (class_constraint == null)
-                                       return false;
+               public string Namespace {
+                       get {
+                               return null;
                        }
-
-                       return true;
                }
 
-               public override GenericParameterAttributes Attributes {
-                       get { return attrs; }
+               public TypeParameterSpec Type {
+                       get {
+                               return spec;
+                       }
                }
 
-               public override bool HasClassConstraint {
-                       get { return class_constraint != null; }
+               public int TypeParametersCount {
+                       get {
+                               return 0;
+                       }
                }
 
-               public override Type ClassConstraint {
-                       get { return class_constraint_type; }
+               public TypeParameterSpec[] TypeParameters {
+                       get {
+                               return null;
+                       }
                }
 
-               public override Type[] InterfaceConstraints {
-                       get { return iface_constraint_types; }
+               public override string[] ValidAttributeTargets {
+                       get {
+                               return attribute_target;
+                       }
                }
 
-               public override Type EffectiveBaseClass {
-                       get { return effective_base_type; }
+               public Variance Variance {
+                       get {
+                               return spec.Variance;
+                       }
                }
 
-               public bool IsSubclassOf (Type t)
+               #endregion
+
+               //
+               // This is called for each part of a partial generic type definition.
+               //
+               // If partial type parameters constraints are not null and we don't
+               // already have constraints they become our constraints. If we already
+               // have constraints, we must check that they're the same.
+               //
+               public bool AddPartialConstraints (TypeContainer part, TypeParameter tp)
                {
-                       if ((class_constraint_type != null) &&
-                           class_constraint_type.IsSubclassOf (t))
+                       if (builder == null)
+                               throw new InvalidOperationException ();
+
+                       var new_constraints = tp.constraints;
+                       if (new_constraints == null)
                                return true;
 
-                       if (iface_constraint_types == null)
+                       // TODO: could create spec only
+                       //tp.Define (null, -1, part.Definition);
+                       tp.spec.DeclaringType = part.Definition;
+                       if (!tp.ResolveConstraints (part))
                                return false;
 
-                       foreach (Type iface in iface_constraint_types) {
-                               if (TypeManager.IsSubclassOf (iface, t))
-                                       return true;
-                       }
+                       if (constraints != null)
+                               return spec.HasSameConstraintsDefinition (tp.Type);
 
-                       return false;
+                       constraints = new_constraints;
+                       return true;
                }
 
-               public Location Location {
-                       get {
-                               return loc;
-                       }
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+               {
+                       builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
                }
 
-               /// <summary>
-               ///   This is used when we're implementing a generic interface method.
-               ///   Each method type parameter in implementing method must have the same
-               ///   constraints than the corresponding type parameter in the interface
-               ///   method.  To do that, we're called on each of the implementing method's
-               ///   type parameters.
-               /// </summary>
-               public bool AreEqual (GenericConstraints gc)
+               public void CheckGenericConstraints ()
                {
-                       if (gc.Attributes != attrs)
-                               return false;
-
-                       if (HasClassConstraint != gc.HasClassConstraint)
-                               return false;
-                       if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
-                               return false;
-
-                       int gc_icount = gc.InterfaceConstraints != null ?
-                               gc.InterfaceConstraints.Length : 0;
-                       int icount = InterfaceConstraints != null ?
-                               InterfaceConstraints.Length : 0;
-
-                       if (gc_icount != icount)
-                               return false;
+                       if (constraints != null)
+                               constraints.CheckGenericConstraints (this);
+               }
 
-                       for (int i = 0; i < gc.InterfaceConstraints.Length; ++i) {
-                               Type iface = gc.InterfaceConstraints [i];
-                               if (iface.IsGenericType)
-                                       iface = iface.GetGenericTypeDefinition ();
-                               
-                               bool ok = false;
-                               for (int ii = 0; ii < InterfaceConstraints.Length; ii++) {
-                                       Type check = InterfaceConstraints [ii];
-                                       if (check.IsGenericType)
-                                               check = check.GetGenericTypeDefinition ();
-                                       
-                                       if (TypeManager.IsEqual (iface, check)) {
-                                               ok = true;
-                                               break;
-                                       }
+               public TypeParameter CreateHoistedCopy (TypeSpec declaringType)
+               {
+                       return new TypeParameter (Parent, spec.DeclaredPosition, MemberName, constraints, null, spec.Variance) {
+                               spec = new TypeParameterSpec (declaringType, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
+                                       BaseType = spec.BaseType,
+                                       InterfacesDefined = spec.InterfacesDefined,
+                                       TypeArguments = spec.TypeArguments
                                }
+                       };
+               }
 
-                               if (!ok)
-                                       return false;
-                       }
-
+               public override bool Define ()
+               {
                        return true;
                }
 
-               public void VerifyClsCompliance (Report r)
+               //
+               // This is the first method which is called during the resolving
+               // process; we're called immediately after creating the type parameters
+               // with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
+               // MethodBuilder).
+               //
+               public void Define (GenericTypeParameterBuilder type, TypeSpec declaringType)
                {
-                       if (class_constraint_type != null && !AttributeTester.IsClsCompliant (class_constraint_type))
-                               Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location, r);
+                       if (builder != null)
+                               throw new InternalErrorException ();
 
-                       if (iface_constraint_types != null) {
-                               for (int i = 0; i < iface_constraint_types.Length; ++i) {
-                                       if (!AttributeTester.IsClsCompliant (iface_constraint_types [i]))
-                                               Warning_ConstrainIsNotClsCompliant (iface_constraint_types [i],
-                                                       ((TypeExpr)iface_constraints [i]).Location, r);
-                               }
-                       }
+                       this.builder = type;
+                       spec.DeclaringType = declaringType;
+                       spec.SetMetaInfo (type);
                }
 
-               void Warning_ConstrainIsNotClsCompliant (Type t, Location loc, Report Report)
+               public void EmitConstraints (GenericTypeParameterBuilder builder)
                {
-                       Report.SymbolRelatedToPreviousError (t);
-                       Report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
-                               TypeManager.CSharpName (t));
-               }
-       }
-
-       /// <summary>
-       ///   A type parameter from a generic type definition.
-       /// </summary>
-       public class TypeParameter : MemberCore, IMemberContainer
-       {
-               static readonly string[] attribute_target = new string [] { "type parameter" };
-               
-               DeclSpace decl;
-               GenericConstraints gc;
-               Constraints constraints;
-               GenericTypeParameterBuilder type;
-               MemberCache member_cache;
-               Variance variance;
+                       var attr = GenericParameterAttributes.None;
+                       if (spec.Variance == Variance.Contravariant)
+                               attr |= GenericParameterAttributes.Contravariant;
+                       else if (spec.Variance == Variance.Covariant)
+                               attr |= GenericParameterAttributes.Covariant;
 
-               public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
-                                     Constraints constraints, Attributes attrs, Variance variance, Location loc)
-                       : base (parent, new MemberName (name, loc), attrs)
-               {
-                       this.decl = decl;
-                       this.constraints = constraints;
-                       this.variance = variance;
-               }
+                       if (spec.HasSpecialClass)
+                               attr |= GenericParameterAttributes.ReferenceTypeConstraint;
+                       else if (spec.HasSpecialStruct)
+                               attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
 
-               public GenericConstraints GenericConstraints {
-                       get { return gc != null ? gc : constraints; }
-               }
+                       if (spec.HasSpecialConstructor)
+                               attr |= GenericParameterAttributes.DefaultConstructorConstraint;
 
-               public Constraints Constraints {
-                       get { return constraints; }
-               }
+                       if (spec.BaseType != TypeManager.object_type)
+                               builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
 
-               public DeclSpace DeclSpace {
-                       get { return decl; }
-               }
+                       if (spec.InterfacesDefined != null)
+                               builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
 
-               public Variance Variance {
-                       get { return variance; }
-               }
+                       if (spec.TypeArguments != null)
+                               builder.SetInterfaceConstraints (spec.TypeArguments.Select (l => l.GetMetaInfo ()).ToArray ());
 
-               public Type Type {
-                       get { return type; }
+                       builder.SetGenericParameterAttributes (attr);
                }
 
-               /// <summary>
-               ///   This is the first method which is called during the resolving
-               ///   process; we're called immediately after creating the type parameters
-               ///   with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
-               ///   MethodBuilder).
-               ///
-               ///   We're either called from TypeContainer.DefineType() or from
-               ///   GenericMethod.Define() (called from Method.Define()).
-               /// </summary>
-               public void Define (GenericTypeParameterBuilder type)
+               public override void Emit ()
                {
-                       if (this.type != null)
-                               throw new InvalidOperationException ();
+                       EmitConstraints (builder);
 
-                       this.type = type;
-                       TypeManager.AddTypeParameter (type, this);
+                       if (OptAttributes != null)
+                               OptAttributes.Emit ();
+
+                       base.Emit ();
                }
 
                public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
                {
-// TODO:       Report.SymbolRelatedToPreviousError (mc);
+                       Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
                        string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
                        string gtype_variance;
                        switch (expected) {
@@ -745,448 +505,1018 @@ namespace Mono.CSharp {
                                        GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
                }
 
-               /// <summary>
-               ///   This is the second method which is called during the resolving
-               ///   process - in case of class type parameters, we're called from
-               ///   TypeContainer.ResolveType() - after it resolved the class'es
-               ///   base class and interfaces. For method type parameters, we're
-               ///   called immediately after Define().
-               ///
-               ///   We're just resolving the constraints into expressions here, we
-               ///   don't resolve them into actual types.
-               ///
-               ///   Note that in the special case of partial generic classes, we may be
-               ///   called _before_ Define() and we may also be called multiple types.
-               /// </summary>
-               public bool Resolve (DeclSpace ds)
+               public TypeSpec GetAttributeCoClass ()
                {
-                       if (constraints != null) {
-                               if (!constraints.Resolve (ds, this, Report)) {
-                                       constraints = null;
-                                       return false;
-                               }
-                       }
+                       return null;
+               }
+
+               public string GetAttributeDefaultMember ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override string GetSignatureForError ()
+               {
+                       return MemberName.Name;
+               }
+
+               public MemberCache LoadMembers (TypeSpec declaringType)
+               {
+                       throw new NotSupportedException ("Not supported for compiled definition");
+               }
 
+               //
+               // Resolves all type parameter constraints
+               //
+               public bool ResolveConstraints (IMemberContext context)
+               {
+                       if (constraints != null)
+                               return constraints.Resolve (context, this);
+
+                       spec.BaseType = TypeManager.object_type;
                        return true;
                }
 
-               /// <summary>
-               ///   This is the third method which is called during the resolving
-               ///   process.  We're called immediately after calling DefineConstraints()
-               ///   on all of the current class'es type parameters.
-               ///
-               ///   Our job is to resolve the constraints to actual types.
-               ///
-               ///   Note that we may have circular dependencies on type parameters - this
-               ///   is why Resolve() and ResolveType() are separate.
-               /// </summary>
-               public bool ResolveType (IMemberContext ec)
+               public static TypeParameter FindTypeParameter (TypeParameter[] tparams, string name)
                {
-                       if (constraints != null) {
-                               if (!constraints.ResolveTypes (ec, Report)) {
-                                       constraints = null;
-                                       return false;
+                       foreach (var tp in tparams) {
+                               if (tp.Name == name)
+                                       return tp;
+                       }
+
+                       return null;
+               }
+
+               public override bool IsClsComplianceRequired ()
+               {
+                       return false;
+               }
+
+               public new void VerifyClsCompliance ()
+               {
+                       if (constraints != null)
+                               constraints.VerifyClsCompliance (Report);
+               }
+       }
+
+       [System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
+       public class TypeParameterSpec : TypeSpec
+       {
+               public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
+
+               Variance variance;
+               SpecialConstraint spec;
+               readonly int tp_pos;
+               TypeSpec[] targs;
+               TypeSpec[] ifaces_defined;
+
+               //
+               // Creates type owned type parameter
+               //
+               public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, Type info)
+                       : base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
+               {
+                       this.variance = variance;
+                       this.spec = spec;
+                       state &= ~StateFlags.Obsolete_Undetected;
+                       tp_pos = index;
+               }
+
+               //
+               // Creates method owned type parameter
+               //
+               public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, Type info)
+                       : this (null, index, definition, spec, variance, info)
+               {
+               }
+
+               #region Properties
+
+               public int DeclaredPosition {
+                       get {
+                               return tp_pos;
+                       }
+               }
+
+               public bool HasSpecialConstructor {
+                       get {
+                               return (spec & SpecialConstraint.Constructor) != 0;
+                       }
+               }
+
+               public bool HasSpecialClass {
+                       get {
+                               return (spec & SpecialConstraint.Class) != 0;
+                       }
+               }
+
+               public bool HasSpecialStruct {
+                       get {
+                               return (spec & SpecialConstraint.Struct) != 0;
+                       }
+               }
+
+               public bool HasTypeConstraint {
+                       get {
+                               return BaseType != TypeManager.object_type && BaseType != TypeManager.value_type;
+                       }
+               }
+
+               public override IList<TypeSpec> Interfaces {
+                       get {
+                               if ((state & StateFlags.InterfacesExpanded) == 0) {
+                                       if (ifaces != null) {
+                                               for (int i = 0; i < ifaces.Count; ++i ) {
+                                                       var iface_type = ifaces[i];
+                                                       if (iface_type.Interfaces != null) {
+                                                               if (ifaces_defined == null)
+                                                                       ifaces_defined = ifaces.ToArray ();
+
+                                                               for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
+                                                                       var ii_iface_type = iface_type.Interfaces [ii];
+
+                                                                       AddInterface (ii_iface_type);
+                                                               }
+                                                       }
+                                               }
+                                       }
+
+                                       if (ifaces_defined == null && ifaces != null)
+                                               ifaces_defined = ifaces.ToArray ();
+
+                                       state |= StateFlags.InterfacesExpanded;
                                }
+
+                               return ifaces;
                        }
+               }
 
-                       return true;
+               //
+               // Unexpanded interfaces list
+               //
+               public TypeSpec[] InterfacesDefined {
+                       get {
+                               if (ifaces_defined == null && ifaces != null)
+                                       ifaces_defined = ifaces.ToArray ();
+
+                               return ifaces_defined;
+                       }
+                       set {
+                               ifaces_defined = value;
+                       }
                }
 
-               /// <summary>
-               ///   This is the fourth and last method which is called during the resolving
-               ///   process.  We're called after everything is fully resolved and actually
-               ///   register the constraints with SRE and the TypeManager.
-               /// </summary>
-               public bool DefineType (IMemberContext ec)
+               public bool IsConstrained {
+                       get {
+                               return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
+                       }
+               }
+
+               //
+               // Returns whether the type parameter is "known to be a reference type"
+               //
+               public bool IsReferenceType {
+                       get {
+                               return (spec & SpecialConstraint.Class) != 0 || HasTypeConstraint;
+                       }
+               }
+
+               public bool IsValueType {       // TODO: Do I need this ?
+                       get {
+                               // TODO MemberCache: probably wrong
+                               return HasSpecialStruct;
+                       }
+               }
+
+               public override string Name {
+                       get {
+                               return definition.Name;
+                       }
+               }
+
+               public bool IsMethodOwned {
+                       get {
+                               return DeclaringType == null;
+                       }
+               }
+
+               public SpecialConstraint SpecialConstraint {
+                       get {
+                               return spec;
+                       }
+                       set {
+                               spec = value;
+                       }
+               }
+
+               //
+               // Types used to inflate the generic type
+               //
+               public new TypeSpec[] TypeArguments {
+                       get {
+                               return targs;
+                       }
+                       set {
+                               targs = value;
+                       }
+               }
+
+               public Variance Variance {
+                       get {
+                               return variance;
+                       }
+               }
+
+               #endregion
+
+               public string DisplayDebugInfo ()
                {
-                       return DefineType (ec, null, null, false);
+                       var s = GetSignatureForError ();
+                       return IsMethodOwned ? s + "!!" : s + "!";
                }
 
-               /// <summary>
-               ///   This is the fith and last method which is called during the resolving
-               ///   process.  We're called after everything is fully resolved and actually
-               ///   register the constraints with SRE and the TypeManager.
-               ///
-               ///   The `builder', `implementing' and `is_override' arguments are only
-               ///   applicable to method type parameters.
-               /// </summary>
-               public bool DefineType (IMemberContext ec, MethodBuilder builder,
-                                       MethodInfo implementing, bool is_override)
+               //
+               // Finds effective base class
+               //
+               public TypeSpec GetEffectiveBase ()
+               {
+                       if (HasSpecialStruct) {
+                               return TypeManager.value_type;
+                       }
+
+                       if (BaseType != null && targs == null)
+                               return BaseType;
+
+                       var types = targs;
+                       if (HasTypeConstraint) {
+                               Array.Resize (ref types, types.Length + 1);
+                               types[types.Length - 1] = BaseType;
+                       }
+
+                       if (types != null)
+                               return Convert.FindMostEncompassedType (types.Select (l => l.BaseType));
+
+                       return TypeManager.object_type;
+               }
+
+               public override string GetSignatureForError ()
                {
-                       if (!ResolveType (ec))
+                       return Name;
+               }
+
+               //
+               // Constraints have to match by definition but not position, used by
+               // partial classes or methods
+               //
+               public bool HasSameConstraintsDefinition (TypeParameterSpec other)
+               {
+                       if (spec != other.spec)
                                return false;
 
-                       if (implementing != null) {
-                               MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
+                       if (BaseType != other.BaseType)
+                               return false;
 
-                               int pos = type.GenericParameterPosition;
-                               Type mparam = mb.GetGenericArguments () [pos];
-                               GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
+                       if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
+                               return false;
 
-                               if (temp_gc != null)
-                                       gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
-                               else if (constraints != null)
-                                       gc = new InflatedConstraints (constraints, implementing.DeclaringType);
+                       if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
+                               return false;
 
-                               bool ok = true;
-                               if (constraints != null) {
-                                       if (temp_gc == null)
-                                               ok = false;
-                                       else if (!constraints.AreEqual (gc))
-                                               ok = false;
-                               } else {
-                                       if (!is_override && (temp_gc != null))
-                                               ok = false;
+                       return true;
+               }
+
+               //
+               // Constraints have to match by using same set of types, used by
+               // implicit interface implementation
+               //
+               public bool HasSameConstraintsImplementation (TypeParameterSpec other)
+               {
+                       if (spec != other.spec)
+                               return false;
+
+                       //
+                       // It can be same base type or inflated type parameter
+                       //
+                       // interface I<T> { void Foo<U> where U : T; }
+                       // class A : I<int> { void Foo<X> where X : int {} }
+                       //
+                       bool found;
+                       if (BaseType != other.BaseType) {
+                               if (other.targs == null)
+                                       return false;
+
+                               found = false;
+                               foreach (var otarg in other.targs) {
+                                       if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
+                                               found = true;
+                                               break;
+                                       }
                                }
 
-                               if (!ok) {
-                                       Report.SymbolRelatedToPreviousError (implementing);
-
-                                       Report.Error (
-                                               425, Location, "The constraints for type " +
-                                               "parameter `{0}' of method `{1}' must match " +
-                                               "the constraints for type parameter `{2}' " +
-                                               "of interface method `{3}'. Consider using " +
-                                               "an explicit interface implementation instead",
-                                               Name, TypeManager.CSharpSignature (builder),
-                                               TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
+                               if (!found)
                                        return false;
+                       }
+
+                       // Check interfaces implementation -> definition
+                       if (InterfacesDefined != null) {
+                               foreach (var iface in InterfacesDefined) {
+                                       found = false;
+                                       if (other.InterfacesDefined != null) {
+                                               foreach (var oiface in other.InterfacesDefined) {
+                                                       if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
+                                                               found = true;
+                                                               break;
+                                                       }
+                                               }
+                                       }
+
+                                       if (found)
+                                               continue;
+
+                                       if (other.targs != null) {
+                                               foreach (var otarg in other.targs) {
+                                                       if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
+                                                               found = true;
+                                                               break;
+                                                       }
+                                               }
+                                       }
+
+                                       if (!found)
+                                               return false;
+                               }
+                       }
+
+                       // Check interfaces implementation <- definition
+                       if (other.InterfacesDefined != null) {
+                               if (InterfacesDefined == null)
+                                       return false;
+
+                               foreach (var oiface in other.InterfacesDefined) {
+                                       found = false;
+                                       foreach (var iface in InterfacesDefined) {
+                                               if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
+                                                       found = true;
+                                                       break;
+                                               }
+                                       }
+
+                                       if (!found)
+                                               return false;
                                }
-                       } else if (DeclSpace is CompilerGeneratedClass) {
-                               TypeParameter[] tparams = DeclSpace.TypeParameters;
-                               Type[] types = new Type [tparams.Length];
-                               for (int i = 0; i < tparams.Length; i++)
-                                       types [i] = tparams [i].Type;
-
-                               if (constraints != null)
-                                       gc = new InflatedConstraints (constraints, types);
-                       } else {
-                               gc = (GenericConstraints) constraints;
                        }
 
-                       SetConstraints (type);
+                       // Check type parameters implementation -> definition
+                       if (targs != null) {
+                               if (other.targs == null)
+                                       return false;
+
+                               foreach (var targ in targs) {
+                                       found = false;
+                                       foreach (var otarg in other.targs) {
+                                               if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
+                                                       found = true;
+                                                       break;
+                                               }
+                                       }
+
+                                       if (!found)
+                                               return false;
+                               }
+                       }
+
+                       // Check type parameters implementation <- definition
+                       if (other.targs != null) {
+                               foreach (var otarg in other.targs) {
+                                       // Ignore inflated type arguments, were checked above
+                                       if (!otarg.IsGenericParameter)
+                                               continue;
+
+                                       if (targs == null)
+                                               return false;
+
+                                       found = false;
+                                       foreach (var targ in targs) {
+                                               if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
+                                                       found = true;
+                                                       break;
+                                               }
+                                       }
+
+                                       if (!found)
+                                               return false;
+                               }                               
+                       }
+
                        return true;
                }
 
-               public static TypeParameter FindTypeParameter (TypeParameter[] tparams, string name)
+               public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
                {
-                       foreach (var tp in tparams) {
-                               if (tp.Name == name)
-                                       return tp;
+                       TypeParameterSpec[] constraints = null;
+
+                       for (int i = 0; i < tparams.Length; ++i) {
+                               var tp = tparams[i];
+                               if (tp.HasTypeConstraint || tp.Interfaces != null || tp.TypeArguments != null) {
+                                       if (constraints == null) {
+                                               constraints = new TypeParameterSpec[tparams.Length];
+                                               Array.Copy (tparams, constraints, constraints.Length);
+                                       }
+
+                                       constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator);
+                               }
                        }
 
-                       return null;
+                       if (constraints == null)
+                               constraints = tparams;
+
+                       return constraints;
                }
 
-               public void SetConstraints (GenericTypeParameterBuilder type)
+               public override MemberSpec InflateMember (TypeParameterInflator inflator)
                {
-                       GenericParameterAttributes attr = GenericParameterAttributes.None;
-                       if (variance == Variance.Contravariant)
-                               attr |= GenericParameterAttributes.Contravariant;
-                       else if (variance == Variance.Covariant)
-                               attr |= GenericParameterAttributes.Covariant;
+                       var tps = (TypeParameterSpec) MemberwiseClone ();
+                       tps.BaseType = inflator.Inflate (BaseType);
+                       if (ifaces != null) {
+                               tps.ifaces = new TypeSpec[ifaces.Count];
+                               for (int i = 0; i < ifaces.Count; ++i)
+                                       tps.ifaces[i] = inflator.Inflate (ifaces[i]);
+                       }
+                       if (targs != null) {
+                               tps.targs = new TypeSpec[targs.Length];
+                               for (int i = 0; i < targs.Length; ++i)
+                                       tps.targs[i] = inflator.Inflate (targs[i]);
+                       }
 
-                       if (gc != null) {
-                               if (gc.HasClassConstraint || gc.HasValueTypeConstraint)
-                                       type.SetBaseTypeConstraint (gc.EffectiveBaseClass);
+                       return tps;
+               }
 
-                               attr |= gc.Attributes;
-                               type.SetInterfaceConstraints (gc.InterfaceConstraints);
-                               TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
+               //
+               // Populates type parameter members using type parameter constraints
+               // The trick here is to be called late enough but not too late to
+               // populate member cache with all members from other types
+               //
+               protected override void InitializeMemberCache (bool onlyTypes)
+               {
+                       cache = new MemberCache ();
+                       if (ifaces != null) {
+                               foreach (var iface_type in Interfaces) {
+                                       cache.AddInterface (iface_type);
+                               }
                        }
-                       
-                       type.SetGenericParameterAttributes (attr);
                }
 
-               /// <summary>
-               ///   This is called for each part of a partial generic type definition.
-               ///
-               ///   If `new_constraints' is not null and we don't already have constraints,
-               ///   they become our constraints.  If we already have constraints, we must
-               ///   check that they're the same.
-               ///   con
-               /// </summary>
-               public bool UpdateConstraints (MemberCore ec, Constraints new_constraints)
+               public override TypeSpec Mutate (TypeParameterMutator mutator)
                {
-                       if (type == null)
-                               throw new InvalidOperationException ();
-
-                       if (new_constraints == null)
-                               return true;
-
-                       if (!new_constraints.Resolve (ec, this, Report))
-                               return false;
-                       if (!new_constraints.ResolveTypes (ec, Report))
-                               return false;
+                       return mutator.Mutate (this);
+               }
+       }
 
-                       if (constraints != null) 
-                               return constraints.AreEqual (new_constraints);
+       public struct TypeParameterInflator
+       {
+               readonly TypeSpec type;
+               readonly TypeParameterSpec[] tparams;
+               readonly TypeSpec[] targs;
 
-                       constraints = new_constraints;
-                       return true;
+               public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
+                       : this (type, nested.tparams, nested.targs)
+               {
                }
 
-               public override void Emit ()
+               public TypeParameterInflator (TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
                {
-                       if (OptAttributes != null)
-                               OptAttributes.Emit ();
+                       if (tparams.Length != targs.Length)
+                               throw new ArgumentException ("Invalid arguments");
 
-                       base.Emit ();
+                       this.tparams = tparams;
+                       this.targs = targs;
+                       this.type = type;
                }
 
-               public override string DocCommentHeader {
+               //
+               // Type parameters to inflate
+               //
+               public TypeParameterSpec[] TypeParameters {
                        get {
-                               throw new InvalidOperationException (
-                                       "Unexpected attempt to get doc comment from " + this.GetType () + ".");
+                               return tparams;
+                       }
+               }
+
+               public TypeSpec Inflate (TypeSpec ts)
+               {
+                       var tp = ts as TypeParameterSpec;
+                       if (tp != null)
+                               return Inflate (tp);
+
+                       var ac = ts as ArrayContainer;
+                       if (ac != null) {
+                               var et = Inflate (ac.Element);
+                               if (et != ac.Element)
+                                       return ArrayContainer.MakeType (et, ac.Rank);
+
+                               return ac;
+                       }
+
+                       //
+                       // When inflating a nested type, inflate its parent first
+                       // in case it's using same type parameters (was inflated within the type)
+                       //
+                       if (ts.IsNested) {
+                               var parent = Inflate (ts.DeclaringType);
+                               if (ts.DeclaringType != parent) {
+                                       //
+                                       // Keep the inflated type arguments
+                                       // 
+                                       var targs = ts.TypeArguments;
+
+                                       //
+                                       // Parent was inflated, find the same type on inflated type
+                                       // to use same cache for nested types on same generic parent
+                                       //
+                                       // TODO: Should use BindingRestriction.DeclaredOnly or GetMember
+                                       ts = MemberCache.FindNestedType (parent, ts.Name, targs.Length);
+
+                                       //
+                                       // Handle the tricky case where parent shares local type arguments
+                                       // which means inflating inflated type
+                                       //
+                                       // class Test<T> {
+                                       //              public static Nested<T> Foo () { return null; }
+                                       //
+                                       //              public class Nested<U> {}
+                                       //      }
+                                       //
+                                       //  return type of Test<string>.Foo() has to be Test<string>.Nested<string> 
+                                       //
+                                       if (targs.Length > 0) {
+                                               var inflated_targs = new TypeSpec [targs.Length];
+                                               for (var i = 0; i < targs.Length; ++i)
+                                                       inflated_targs[i] = Inflate (targs[i]);
+
+                                               ts = ts.MakeGenericType (inflated_targs);
+                                       }
+
+                                       return ts;
+                               }
                        }
+
+                       // Inflate generic type
+                       if (ts.IsGeneric)
+                               return InflateTypeParameters (ts);
+
+                       return ts;
+               }
+
+               public TypeSpec Inflate (TypeParameterSpec tp)
+               {
+                       for (int i = 0; i < tparams.Length; ++i)
+                               if (tparams [i] == tp)
+                                       return targs[i];
+
+                       // CECIL: This can happen when inflating nested types
+                       // without type arguments specified
+                       return tp;
                }
 
                //
-               // MemberContainer
+               // Inflates generic types
                //
+               TypeSpec InflateTypeParameters (TypeSpec type)
+               {
+                       var targs = new TypeSpec[type.Arity];
+                       var i = 0;
 
-               public override bool Define ()
+                       var gti = type as InflatedTypeSpec;
+
+                       //
+                       // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
+                       //
+                       if (gti != null) {
+                               for (; i < targs.Length; ++i)
+                                       targs[i] = Inflate (gti.TypeArguments[i]);
+
+                               return gti.GetDefinition ().MakeGenericType (targs);
+                       }
+
+                       //
+                       // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
+                       //
+                       var args = type.MemberDefinition.TypeParameters;
+                       foreach (var ds_tp in args)
+                               targs[i++] = Inflate (ds_tp);
+
+                       return type.MakeGenericType (targs);
+               }
+
+               public TypeSpec TypeInstance {
+                       get { return type; }
+               }
+       }
+
+       //
+       // Before emitting any code we have to change all MVAR references to VAR
+       // when the method is of generic type and has hoisted variables
+       //
+       public class TypeParameterMutator
+       {
+               TypeParameter[] mvar;
+               TypeParameter[] var;
+               Dictionary<TypeSpec, TypeSpec> mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
+
+               public TypeParameterMutator (TypeParameter[] mvar, TypeParameter[] var)
                {
-                       return true;
+                       if (mvar.Length != var.Length)
+                               throw new ArgumentException ();
+
+                       this.mvar = mvar;
+                       this.var = var;
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public TypeSpec Mutate (TypeSpec ts)
                {
-                       type.SetCustomAttribute (cb);
+                       TypeSpec value;
+                       if (mutated_typespec.TryGetValue (ts, out value))
+                               return value;
+
+                       value = ts.Mutate (this);
+                       mutated_typespec.Add (ts, value);
+                       return value;
                }
 
-               public override AttributeTargets AttributeTargets {
-                       get {
-                               return AttributeTargets.GenericParameter;
+               public FieldInfo Mutate (FieldSpec fs)
+               {
+                       // TODO:
+                       return fs.GetMetaInfo ();
+               }
+
+               public TypeParameterSpec Mutate (TypeParameterSpec tp)
+               {
+                       for (int i = 0; i < mvar.Length; ++i) {
+                               if (mvar[i].Type == tp)
+                                       return var[i].Type;
+                       }
+
+                       return tp;
+               }
+
+               public TypeSpec[] Mutate (TypeSpec[] targs)
+               {
+                       TypeSpec[] mutated = new TypeSpec[targs.Length];
+                       bool changed = false;
+                       for (int i = 0; i < targs.Length; ++i) {
+                               mutated[i] = Mutate (targs[i]);
+                               changed |= targs[i] != mutated[i];
                        }
+
+                       return changed ? mutated : targs;
                }
+       }
 
-               public override string[] ValidAttributeTargets {
+       /// <summary>
+       ///   A TypeExpr which already resolved to a type parameter.
+       /// </summary>
+       public class TypeParameterExpr : TypeExpr {
+               
+               public TypeParameterExpr (TypeParameter type_parameter, Location loc)
+               {
+                       this.type = type_parameter.Type;
+                       this.eclass = ExprClass.TypeParameter;
+                       this.loc = loc;
+               }
+
+               protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
+               {
+                       return this;
+               }
+
+               public override bool CheckAccessLevel (IMemberContext ds)
+               {
+                       return true;
+               }
+       }
+
+       public class InflatedTypeSpec : TypeSpec
+       {
+               TypeSpec[] targs;
+               TypeParameterSpec[] constraints;
+               readonly TypeSpec open_type;
+
+               public InflatedTypeSpec (TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
+                       : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
+               {
+                       if (targs == null)
+                               throw new ArgumentNullException ("targs");
+
+#if DEBUG
+                       if (ID == 4937)
+                               Console.WriteLine ("HIT");
+#endif
+
+//                     this.state = openType.state;
+                       this.open_type = openType;
+                       this.targs = targs;
+               }
+
+               #region Properties
+
+               public override TypeSpec BaseType {
                        get {
-                               return attribute_target;
+                               if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
+                                       InitializeMemberCache (true);
+
+                               return base.BaseType;
                        }
                }
 
                //
-               // IMemberContainer
+               // Inflated type parameters with constraints array, mapping with type arguments is based on index
                //
+               public TypeParameterSpec[] Constraints {
+                       get {
+                               if (constraints == null) {
+                                       var inflator = new TypeParameterInflator (this, MemberDefinition.TypeParameters, targs);
+                                       constraints = TypeParameterSpec.InflateConstraints (inflator, MemberDefinition.TypeParameters);
+                               }
 
-               string IMemberContainer.Name {
-                       get { return Name; }
+                               return constraints;
+                       }
                }
 
-               MemberCache IMemberContainer.BaseCache {
+               public override IList<TypeSpec> Interfaces {
                        get {
-                               if (gc == null)
-                                       return null;
-
-                               if (gc.EffectiveBaseClass.BaseType == null)
-                                       return null;
+                               if (cache == null)
+                                       InitializeMemberCache (true);
 
-                               return TypeManager.LookupMemberCache (gc.EffectiveBaseClass.BaseType);
+                               return base.Interfaces;
                        }
                }
 
-               bool IMemberContainer.IsInterface {
-                       get { return false; }
-               }
+               public override MemberCache MemberCacheTypes {
+                       get {
+                               if (cache == null)
+                                       InitializeMemberCache (true);
 
-               MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
-               {
-                       throw new NotSupportedException ();
+                               return cache;
+                       }
                }
 
-               public MemberCache MemberCache {
+               //
+               // Types used to inflate the generic  type
+               //
+               public override TypeSpec[] TypeArguments {
                        get {
-                               if (member_cache != null)
-                                       return member_cache;
-
-                               if (gc == null)
-                                       return null;
-
-                               Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
-                               member_cache = new MemberCache (this, gc.EffectiveBaseClass, ifaces);
-
-                               return member_cache;
+                               return targs;
                        }
                }
 
-               public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
-                                              MemberFilter filter, object criteria)
-               {
-                       if (gc == null)
-                               return MemberList.Empty;
-
-                       var members = new List<MemberInfo> ();
-
-                       if (gc.HasClassConstraint) {
-                               MemberList list = TypeManager.FindMembers (
-                                       gc.ClassConstraint, mt, bf, filter, criteria);
+               #endregion
 
-                               members.AddRange (list);
-                       }
+               Type CreateMetaInfo (TypeParameterMutator mutator)
+               {
+                       //
+                       // Converts nested type arguments into right order
+                       // Foo<string, bool>.Bar<int> => string, bool, int
+                       //
+                       var all = new List<Type> ();
+                       TypeSpec type = this;
+                       TypeSpec definition = type;
+                       do {
+                               if (type.GetDefinition().IsGeneric) {
+                                       all.InsertRange (0,
+                                               type.TypeArguments != TypeSpec.EmptyTypes ?
+                                               type.TypeArguments.Select (l => l.GetMetaInfo ()) :
+                                               type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
+                               }
 
-                       Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
-                       foreach (Type t in ifaces) {
-                               MemberList list = TypeManager.FindMembers (
-                                       t, mt, bf, filter, criteria);
+                               definition = definition.GetDefinition ();
+                               type = type.DeclaringType;
+                       } while (type != null);
 
-                               members.AddRange (list);
-                       }
+                       return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
+               }
 
-                       return new MemberList (members);
+               public override ObsoleteAttribute GetAttributeObsolete ()
+               {
+                       return open_type.GetAttributeObsolete ();
                }
 
-               public bool IsSubclassOf (Type t)
+               protected override bool IsNotCLSCompliant ()
                {
-                       if (type.Equals (t))
+                       if (base.IsNotCLSCompliant ())
                                return true;
 
-                       if (constraints != null)
-                               return constraints.IsSubclassOf (t);
+                       foreach (var ta in TypeArguments) {
+                               if (ta.MemberDefinition.IsNotCLSCompliant ())
+                                       return true;
+                       }
 
                        return false;
                }
 
-               public void InflateConstraints (Type declaring)
+               public override TypeSpec GetDefinition ()
                {
-                       if (constraints != null)
-                               gc = new InflatedConstraints (constraints, declaring);
+                       return open_type;
                }
-               
-               public override bool IsClsComplianceRequired ()
+
+               public override Type GetMetaInfo ()
                {
-                       return false;
+                       if (info == null)
+                               info = CreateMetaInfo (null);
+
+                       return info;
                }
 
-               protected class InflatedConstraints : GenericConstraints
+               public override string GetSignatureForError ()
                {
-                       GenericConstraints gc;
-                       Type base_type;
-                       Type class_constraint;
-                       Type[] iface_constraints;
-                       Type[] dargs;
+                       if (TypeManager.IsNullableType (open_type))
+                               return targs[0].GetSignatureForError () + "?";
 
-                       public InflatedConstraints (GenericConstraints gc, Type declaring)
-                               : this (gc, TypeManager.GetTypeArguments (declaring))
-                       { }
+                       if (MemberDefinition is AnonymousTypeClass)
+                               return ((AnonymousTypeClass) MemberDefinition).GetSignatureForError ();
 
-                       public InflatedConstraints (GenericConstraints gc, Type[] dargs)
-                       {
-                               this.gc = gc;
-                               this.dargs = dargs;
-
-                               var list = new List<Type> ();
-                               if (gc.HasClassConstraint)
-                                       list.Add (inflate (gc.ClassConstraint));
-                               foreach (Type iface in gc.InterfaceConstraints)
-                                       list.Add (inflate (iface));
-
-                               bool has_class_constr = false;
-                               if (list.Count > 0) {
-                                       Type first = (Type) list [0];
-                                       has_class_constr = !first.IsGenericParameter && !first.IsInterface;
-                               }
+                       return base.GetSignatureForError ();
+               }
+
+               protected override string GetTypeNameSignature ()
+               {
+                       if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
+                               return null;
 
-                               if ((list.Count > 0) && has_class_constr) {
-                                       class_constraint = (Type) list [0];
-                                       iface_constraints = new Type [list.Count - 1];
-                                       list.CopyTo (1, iface_constraints, 0, list.Count - 1);
+                       return "<" + TypeManager.CSharpName (targs) + ">";
+               }
+
+               protected override void InitializeMemberCache (bool onlyTypes)
+               {
+                       if (cache == null)
+                               cache = new MemberCache (open_type.MemberCache);
+
+                       TypeParameterSpec[] tparams_full;
+                       TypeSpec[] targs_full = targs;
+                       if (IsNested) {
+                               //
+                               // Special case is needed when we are inflating an open type (nested type definition)
+                               // on inflated parent. Consider following case
+                               //
+                               // Foo<T>.Bar<U> => Foo<string>.Bar<U>
+                               //
+                               // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
+                               //
+                               List<TypeSpec> merged_targs = null;
+                               List<TypeParameterSpec> merged_tparams = null;
+
+                               var type = DeclaringType;
+
+                               do {
+                                       if (type.TypeArguments.Length > 0) {
+                                               if (merged_targs == null) {
+                                                       merged_targs = new List<TypeSpec> ();
+                                                       merged_tparams = new List<TypeParameterSpec> ();
+                                                       if (targs.Length > 0) {
+                                                               merged_targs.AddRange (targs);
+                                                               merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
+                                                       }
+                                               }
+                                               merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
+                                               merged_targs.AddRange (type.TypeArguments);
+                                       }
+                                       type = type.DeclaringType;
+                               } while (type != null);
+
+                               if (merged_targs != null) {
+                                       // Type arguments are not in the right order but it should not matter in this case
+                                       targs_full = merged_targs.ToArray ();
+                                       tparams_full = merged_tparams.ToArray ();
+                               } else if (targs.Length == 0) {
+                                       tparams_full = TypeParameterSpec.EmptyTypes;
                                } else {
-                                       iface_constraints = new Type [list.Count];
-                                       list.CopyTo (iface_constraints, 0);
+                                       tparams_full = open_type.MemberDefinition.TypeParameters;
                                }
-
-                               if (HasValueTypeConstraint)
-                                       base_type = TypeManager.value_type;
-                               else if (class_constraint != null)
-                                       base_type = class_constraint;
-                               else
-                                       base_type = TypeManager.object_type;
+                       } else if (targs.Length == 0) {
+                               tparams_full = TypeParameterSpec.EmptyTypes;
+                       } else {
+                               tparams_full = open_type.MemberDefinition.TypeParameters;
                        }
 
-                       Type inflate (Type t)
-                       {
-                               if (t == null)
-                                       return null;
-                               if (t.IsGenericParameter)
-                                       return t.GenericParameterPosition < dargs.Length ? dargs [t.GenericParameterPosition] : t;
-                               if (t.IsGenericType) {
-                                       Type[] args = t.GetGenericArguments ();
-                                       Type[] inflated = new Type [args.Length];
+                       var inflator = new TypeParameterInflator (this, tparams_full, targs_full);
 
-                                       for (int i = 0; i < args.Length; i++)
-                                               inflated [i] = inflate (args [i]);
+                       //
+                       // Two stage inflate due to possible nested types recursive
+                       // references
+                       //
+                       // class A<T> {
+                       //    B b;
+                       //    class B {
+                       //      T Value;
+                       //    }
+                       // }
+                       //
+                       // When resolving type of `b' members of `B' cannot be 
+                       // inflated because are not yet available in membercache
+                       //
+                       if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
+                               open_type.MemberCache.InflateTypes (cache, inflator);
 
-                                       t = t.GetGenericTypeDefinition ();
-                                       t = t.MakeGenericType (inflated);
+                               //
+                               // Inflate any implemented interfaces
+                               //
+                               if (open_type.Interfaces != null) {
+                                       ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
+                                       foreach (var iface in open_type.Interfaces) {
+                                               var iface_inflated = inflator.Inflate (iface);
+                                               AddInterface (iface_inflated);
+                                       }
                                }
 
-                               return t;
+                               //
+                               // Handles the tricky case of recursive nested base generic type
+                               //
+                               // class A<T> : Base<A<T>.Nested> {
+                               //    class Nested {}
+                               // }
+                               //
+                               // When inflating A<T>. base type is not yet known, secondary
+                               // inflation is required (not common case) once base scope
+                               // is known
+                               //
+                               if (open_type.BaseType == null) {
+                                       if (IsClass)
+                                               state |= StateFlags.PendingBaseTypeInflate;
+                               } else {
+                                       BaseType = inflator.Inflate (open_type.BaseType);
+                               }
+                       } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
+                               BaseType = inflator.Inflate (open_type.BaseType);
+                               state &= ~StateFlags.PendingBaseTypeInflate;
                        }
 
-                       public override GenericParameterAttributes Attributes {
-                               get { return gc.Attributes; }
+                       if (onlyTypes) {
+                               state |= StateFlags.PendingMemberCacheMembers;
+                               return;
                        }
 
-                       public override Type ClassConstraint {
-                               get { return class_constraint; }
-                       }
+                       var tc = open_type.MemberDefinition as TypeContainer;
+                       if (tc != null && !tc.HasMembersDefined)
+                               throw new InternalErrorException ("Inflating MemberCache with undefined members");
 
-                       public override Type EffectiveBaseClass {
-                               get { return base_type; }
+                       if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
+                               BaseType = inflator.Inflate (open_type.BaseType);
+                               state &= ~StateFlags.PendingBaseTypeInflate;
                        }
 
-                       public override Type[] InterfaceConstraints {
-                               get { return iface_constraints; }
-                       }
+                       state &= ~StateFlags.PendingMemberCacheMembers;
+                       open_type.MemberCache.InflateMembers (cache, open_type, inflator);
                }
-       }
 
-       /// <summary>
-       ///   A TypeExpr which already resolved to a type parameter.
-       /// </summary>
-       public class TypeParameterExpr : TypeExpr {
-               
-               public TypeParameterExpr (TypeParameter type_parameter, Location loc)
+               public override TypeSpec Mutate (TypeParameterMutator mutator)
                {
-                       this.type = type_parameter.Type;
-                       this.eclass = ExprClass.TypeParameter;
-                       this.loc = loc;
-               }
+                       var targs = TypeArguments;
+                       if (targs != null)
+                               targs = mutator.Mutate (targs);
 
-               protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
-               {
-                       throw new NotSupportedException ();
-               }
+                       var decl = DeclaringType;
+                       if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
+                               decl = mutator.Mutate (decl);
 
-               public override FullNamedExpression ResolveAsTypeStep (IMemberContext ec, bool silent)
-               {
-                       return this;
-               }
+                       if (targs == TypeArguments && decl == DeclaringType)
+                               return this;
 
-               public override bool IsInterface {
-                       get { return false; }
-               }
+                       var mutated = (InflatedTypeSpec) MemberwiseClone ();
+                       if (decl != DeclaringType) {
+                               // Gets back MethodInfo in case of metaInfo was inflated
+                               //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
 
-               public override bool CheckAccessLevel (IMemberContext ds)
-               {
-                       return true;
+                               mutated.declaringType = decl;
+                               mutated.state |= StateFlags.PendingMetaInflate;
+                       }
+
+                       if (targs != null) {
+                               mutated.targs = targs;
+                               mutated.info = null;
+                       }
+
+                       return mutated;
                }
        }
 
+
        //
        // Tracks the type arguments when instantiating a generic type. It's used
        // by both type arguments and type parameters
        //
-       public class TypeArguments {
+       public class TypeArguments
+       {
                List<FullNamedExpression> args;
-               Type[] atypes;
-               
-               public TypeArguments ()
-               {
-                       args = new List<FullNamedExpression> ();
-               }
+               TypeSpec[] atypes;
 
                public TypeArguments (params FullNamedExpression[] types)
                {
@@ -1198,11 +1528,6 @@ namespace Mono.CSharp {
                        args.Add (type);
                }
 
-               public void Add (TypeArguments new_args)
-               {
-                       args.AddRange (new_args.args);
-               }
-
                // TODO: Kill this monster
                public TypeParameterName[] GetDeclarations ()
                {
@@ -1213,7 +1538,8 @@ namespace Mono.CSharp {
                ///   We may only be used after Resolve() is called and return the fully
                ///   resolved types.
                /// </summary>
-               public Type[] Arguments {
+               // TODO: Not needed, just return type from resolve
+               public TypeSpec[] Arguments {
                        get {
                                return atypes;
                        }
@@ -1225,34 +1551,42 @@ namespace Mono.CSharp {
                        }
                }
 
+               public virtual bool IsEmpty {
+                       get {
+                               return false;
+                       }
+               }
+
                public string GetSignatureForError()
                {
-                       StringBuilder sb = new StringBuilder();
-                       for (int i = 0; i < Count; ++i)
-                       {
-                               Expression expr = (Expression)args [i];
-                               sb.Append(expr.GetSignatureForError());
+                       StringBuilder sb = new StringBuilder ();
+                       for (int i = 0; i < Count; ++i) {
+                               var expr = args[i];
+                               if (expr != null)
+                                       sb.Append (expr.GetSignatureForError ());
+
                                if (i + 1 < Count)
-                                       sb.Append(',');
+                                       sb.Append (',');
                        }
-                       return sb.ToString();
+
+                       return sb.ToString ();
                }
 
                /// <summary>
                ///   Resolve the type arguments.
                /// </summary>
-               public bool Resolve (IMemberContext ec)
+               public virtual bool Resolve (IMemberContext ec)
                {
                        if (atypes != null)
-                               return atypes.Length != 0;
+                           return atypes.Length != 0;
 
                        int count = args.Count;
                        bool ok = true;
 
-                       atypes = new Type [count];
+                       atypes = new TypeSpec [count];
 
                        for (int i = 0; i < count; i++){
-                               TypeExpr te = ((FullNamedExpression) args[i]).ResolveAsTypeTerminal (ec, false);
+                               TypeExpr te = args[i].ResolveAsTypeTerminal (ec, false);
                                if (te == null) {
                                        ok = false;
                                        continue;
@@ -1260,7 +1594,7 @@ namespace Mono.CSharp {
 
                                atypes[i] = te.Type;
 
-                               if (te.Type.IsSealed && te.Type.IsAbstract) {
+                               if (te.Type.IsStatic) {
                                        ec.Compiler.Report.Error (718, te.Location, "`{0}': static classes cannot be used as generic arguments",
                                                te.GetSignatureForError ());
                                        ok = false;
@@ -1275,7 +1609,7 @@ namespace Mono.CSharp {
                        }
 
                        if (!ok)
-                               atypes = Type.EmptyTypes;
+                               atypes = TypeSpec.EmptyTypes;
 
                        return ok;
                }
@@ -1290,6 +1624,26 @@ namespace Mono.CSharp {
                }
        }
 
+       public class UnboundTypeArguments : TypeArguments
+       {
+               public UnboundTypeArguments (int arity)
+                       : base (new FullNamedExpression[arity])
+               {
+               }
+
+               public override bool IsEmpty {
+                       get {
+                               return true;
+                       }
+               }
+
+               public override bool Resolve (IMemberContext ec)
+               {
+                       // should not be called
+                       throw new NotSupportedException ();
+               }
+       }
+
        public class TypeParameterName : SimpleName
        {
                Attributes attributes;
@@ -1320,41 +1674,23 @@ namespace Mono.CSharp {
                }
        }
 
-       /// <summary>
-       ///   A reference expression to generic type
-       /// </summary>  
+       //
+       // A type expression of generic type with type arguments
+       //
        class GenericTypeExpr : TypeExpr
        {
                TypeArguments args;
-               Type[] gen_params;      // TODO: Waiting for constrains check cleanup
-               Type open_type;
-
-               //
-               // Should be carefully used only with defined generic containers. Type parameters
-               // can be used as type arguments in this case.
-               //
-               // TODO: This could be GenericTypeExpr specialization
-               //
-               public GenericTypeExpr (DeclSpace gType, Location l)
-               {
-                       open_type = gType.TypeBuilder.GetGenericTypeDefinition ();
-
-                       args = new TypeArguments ();
-                       foreach (TypeParameter type_param in gType.TypeParameters)
-                               args.Add (new TypeParameterExpr (type_param, l));
-
-                       this.loc = l;
-               }
+               TypeSpec open_type;
+               bool constraints_checked;
 
                /// <summary>
                ///   Instantiate the generic type `t' with the type arguments `args'.
                ///   Use this constructor if you already know the fully resolved
                ///   generic type.
                /// </summary>          
-               public GenericTypeExpr (Type t, TypeArguments args, Location l)
+               public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
                {
-                       open_type = t.GetGenericTypeDefinition ();
-
+                       this.open_type = open_type;
                        loc = l;
                        this.args = args;
                }
@@ -1370,38 +1706,51 @@ namespace Mono.CSharp {
 
                protected override TypeExpr DoResolveAsTypeStep (IMemberContext ec)
                {
-                       eclass = ExprClass.Type;
-
                        if (!args.Resolve (ec))
                                return null;
 
-                       gen_params = open_type.GetGenericArguments ();
-                       Type[] atypes = args.Arguments;
-                       
-                       if (atypes.Length != gen_params.Length) {
-                               Namespace.Error_InvalidNumberOfTypeArguments (ec.Compiler.Report, open_type, loc);
-                               return null;
-                       }
+                       TypeSpec[] atypes = args.Arguments;
 
                        //
                        // Now bind the parameters
                        //
                        type = open_type.MakeGenericType (atypes);
+
+                       //
+                       // Check constraints when context is not method/base type
+                       //
+                       if (!ec.HasUnresolvedConstraints)
+                               CheckConstraints (ec);
+
                        return this;
                }
 
-               /// <summary>
-               ///   Check the constraints; we're called from ResolveAsTypeTerminal()
-               ///   after fully resolving the constructed type.
-               /// </summary>
+               //
+               // Checks the constraints of open generic type against type
+               // arguments. Has to be called onafter all members are defined
+               //
                public bool CheckConstraints (IMemberContext ec)
                {
-                       return ConstraintChecker.CheckConstraints (ec, open_type, gen_params, args.Arguments, loc);
+                       if (constraints_checked)
+                               return true;
+
+                       constraints_checked = true;
+
+                       var gtype = (InflatedTypeSpec) type;
+                       var constraints = gtype.Constraints;
+                       if (constraints == null)
+                               return true;
+
+                       return ConstraintChecker.CheckAll (open_type, args.Arguments, constraints, loc, ec.Compiler.Report);
                }
        
                public override bool CheckAccessLevel (IMemberContext mc)
                {
-                       return mc.CurrentTypeDefinition.CheckAccessLevel (open_type);
+                       DeclSpace c = mc.CurrentMemberDefinition as DeclSpace;
+                       if (c == null)
+                               c = mc.CurrentMemberDefinition.Parent;
+
+                       return c.CheckAccessLevel (open_type);
                }
 
                public bool HasDynamicArguments ()
@@ -1409,36 +1758,19 @@ namespace Mono.CSharp {
                        return HasDynamicArguments (args.Arguments);
                }
 
-               static bool HasDynamicArguments (Type[] args)
+               static bool HasDynamicArguments (TypeSpec[] args)
                {
-                       foreach (var item in args)
-                       {
+                       foreach (var item in args) {
+                               if (item == InternalType.Dynamic)
+                                       return true;
+
                                if (TypeManager.IsGenericType (item))
                                        return HasDynamicArguments (TypeManager.GetTypeArguments (item));
-
-                               if (TypeManager.IsDynamicType (item))
-                                       return true;
                        }
 
                        return false;
                }
 
-               public override bool IsClass {
-                       get { return open_type.IsClass; }
-               }
-
-               public override bool IsValueType {
-                       get { return TypeManager.IsStruct (open_type); }
-               }
-
-               public override bool IsInterface {
-                       get { return open_type.IsInterface; }
-               }
-
-               public override bool IsSealed {
-                       get { return open_type.IsSealed; }
-               }
-
                public override bool Equals (object obj)
                {
                        GenericTypeExpr cobj = obj as GenericTypeExpr;
@@ -1455,335 +1787,144 @@ namespace Mono.CSharp {
                {
                        return base.GetHashCode ();
                }
-       }
-
-       public abstract class ConstraintChecker
-       {
-               protected readonly Type[] gen_params;
-               protected readonly Type[] atypes;
-               protected readonly Location loc;
-               protected Report Report;
-
-               protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc, Report r)
-               {
-                       this.gen_params = gen_params;
-                       this.atypes = atypes;
-                       this.loc = loc;
-                       this.Report = r;
-               }
-
-               /// <summary>
-               ///   Check the constraints; we're called from ResolveAsTypeTerminal()
-               ///   after fully resolving the constructed type.
-               /// </summary>
-               public bool CheckConstraints (IMemberContext ec)
-               {
-                       for (int i = 0; i < gen_params.Length; i++) {
-                               if (!CheckConstraints (ec, i))
-                                       return false;
-                       }
-
-                       return true;
-               }
-
-               protected bool CheckConstraints (IMemberContext ec, int index)
-               {
-                       Type atype = TypeManager.TypeToCoreType (atypes [index]);
-                       Type ptype = gen_params [index];
-
-                       if (atype == ptype)
-                               return true;
-
-                       Expression aexpr = new EmptyExpression (atype);
-
-                       GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
-                       if (gc == null)
-                               return true;
-
-                       bool is_class, is_struct;
-                       if (atype.IsGenericParameter) {
-                               GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
-                               if (agc != null) {
-                                       if (agc is Constraints) {
-                                               // FIXME: No constraints can be resolved here, we are in
-                                               // completely wrong/different context. This path is hit
-                                               // when resolving base type of unresolved generic type
-                                               // with constraints. We are waiting with CheckConsttraints
-                                               // after type-definition but not in this case
-                                               if (!((Constraints) agc).Resolve (null, null, Report))
-                                                       return true;
-                                       }
-                                       is_class = agc.IsReferenceType;
-                                       is_struct = agc.IsValueType;
-                               } else {
-                                       is_class = is_struct = false;
-                               }
-                       } else {
-                               is_class = TypeManager.IsReferenceType (atype);
-                               is_struct = TypeManager.IsValueType (atype) && !TypeManager.IsNullableType (atype);
-                       }
-
-                       //
-                       // First, check the `class' and `struct' constraints.
-                       //
-                       if (gc.HasReferenceTypeConstraint && !is_class) {
-                               Report.Error (452, loc, "The type `{0}' must be " +
-                                             "a reference type in order to use it " +
-                                             "as type parameter `{1}' in the " +
-                                             "generic type or method `{2}'.",
-                                             TypeManager.CSharpName (atype),
-                                             TypeManager.CSharpName (ptype),
-                                             GetSignatureForError ());
-                               return false;
-                       } else if (gc.HasValueTypeConstraint && !is_struct) {
-                               Report.Error (453, loc, "The type `{0}' must be a " +
-                                             "non-nullable value type in order to use it " +
-                                             "as type parameter `{1}' in the " +
-                                             "generic type or method `{2}'.",
-                                             TypeManager.CSharpName (atype),
-                                             TypeManager.CSharpName (ptype),
-                                             GetSignatureForError ());
-                               return false;
-                       }
-
-                       //
-                       // The class constraint comes next.
-                       //
-                       if (gc.HasClassConstraint) {
-                               if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
-                                       return false;
-                       }
-
-                       //
-                       // Now, check the interface constraints.
-                       //
-                       if (gc.InterfaceConstraints != null) {
-                               foreach (Type it in gc.InterfaceConstraints) {
-                                       if (!CheckConstraint (ec, ptype, aexpr, it))
-                                               return false;
-                               }
-                       }
-
-                       //
-                       // Finally, check the constructor constraint.
-                       //
-
-                       if (!gc.HasConstructorConstraint)
-                               return true;
-
-                       if (TypeManager.IsValueType (atype))
-                               return true;
-
-                       if (HasDefaultConstructor (atype))
-                               return true;
-
-                       Report_SymbolRelatedToPreviousError ();
-                       Report.SymbolRelatedToPreviousError (atype);
-                       Report.Error (310, loc, "The type `{0}' must have a public " +
-                                     "parameterless constructor in order to use it " +
-                                     "as parameter `{1}' in the generic type or " +
-                                     "method `{2}'",
-                                     TypeManager.CSharpName (atype),
-                                     TypeManager.CSharpName (ptype),
-                                     GetSignatureForError ());
-                       return false;
-               }
-               
-               Type InflateType(IMemberContext ec, Type ctype)
-               {
-                       Type[] types = TypeManager.GetTypeArguments (ctype);
-
-                       TypeArguments new_args = new TypeArguments ();
-
-                       for (int i = 0; i < types.Length; i++) {
-                               Type t = TypeManager.TypeToCoreType (types [i]);
-
-                               if (t.IsGenericParameter) {
-                                       int pos = t.GenericParameterPosition;
-                                       if (t.DeclaringMethod == null && this is MethodConstraintChecker) {
-                                               Type parent = ((MethodConstraintChecker) this).declaring_type;
-                                               t = parent.GetGenericArguments ()[pos];
-                                       } else {
-                                               t = atypes [pos];
-                                       }
-                               } else if(TypeManager.HasGenericArguments(t)) {
-                                       t = InflateType (ec, t);
-                                       if (t == null) {
-                                               return null;
-                                       }
-                               }
-                               new_args.Add (new TypeExpression (t, loc));
-                       }
-
-                       TypeExpr ct = new GenericTypeExpr (ctype, new_args, loc);
-                       if (ct.ResolveAsTypeStep (ec, false) == null)
-                               return null;
-                       
-                       return ct.Type;
-               }
+       }
 
-               protected bool CheckConstraint (IMemberContext ec, Type ptype, Expression expr,
-                                               Type ctype)
+       static class ConstraintChecker
+       {
+               /// <summary>
+               ///   Check the constraints; we're called from ResolveAsTypeTerminal()
+               ///   after fully resolving the constructed type.
+               /// </summary>
+               public static bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc, Report report)
                {
-                       //
-                       // All this is needed because we don't have
-                       // real inflated type hierarchy
-                       //
-                       if (TypeManager.HasGenericArguments (ctype)) {
-                               ctype = InflateType (ec, ctype);
-                               if(ctype == null) {
+                       for (int i = 0; i < tparams.Length; i++) {
+                               if (!CheckConstraint (context, targs [i], tparams [i], loc, report))
                                        return false;
-                               }
-                       } else if (ctype.IsGenericParameter) {
-                               int pos = ctype.GenericParameterPosition;
-                               if (ctype.DeclaringMethod == null) {
-                                       // FIXME: Implement
-                                       return true;
-                               } else {                                
-                                       ctype = atypes [pos];
-                               }
                        }
 
-                       if (Convert.ImplicitStandardConversionExists (expr, ctype))
-                               return true;
-
-                       Report_SymbolRelatedToPreviousError ();
-                       Report.SymbolRelatedToPreviousError (expr.Type);
-
-                       if (TypeManager.IsNullableType (expr.Type) && ctype.IsInterface) {
-                               Report.Error (313, loc,
-                                       "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. " +
-                                       "The nullable type `{0}' never satisfies interface constraint of type `{3}'",
-                                       TypeManager.CSharpName (expr.Type), TypeManager.CSharpName (ptype),
-                                       GetSignatureForError (), TypeManager.CSharpName (ctype));
-                       } else {
-                               Report.Error (309, loc,
-                                       "The type `{0}' must be convertible to `{1}' in order to " +
-                                       "use it as parameter `{2}' in the generic type or method `{3}'",
-                                       TypeManager.CSharpName (expr.Type), TypeManager.CSharpName (ctype),
-                                       TypeManager.CSharpName (ptype), GetSignatureForError ());
-                       }
-                       return false;
+                       return true;
                }
 
-               static bool HasDefaultConstructor (Type atype)
+               static bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc, Report report)
                {
-                       TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
-                       if (tparam != null) {
-                               if (tparam.GenericConstraints == null)
-                                       return false;
-                                               
-                               return tparam.GenericConstraints.HasConstructorConstraint || 
-                                       tparam.GenericConstraints.HasValueTypeConstraint;
-                       }
-               
-                       if (atype.IsAbstract)
+                       //
+                       // First, check the `class' and `struct' constraints.
+                       //
+                       if (tparam.HasSpecialClass && !TypeManager.IsReferenceType (atype)) {
+                               report.Error (452, loc,
+                                       "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
+                                       TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
                                return false;
+                       }
 
-               again:
-                       atype = TypeManager.DropGenericTypeArguments (atype);
-                       if (atype is TypeBuilder) {
-                               TypeContainer tc = TypeManager.LookupTypeContainer (atype);
-                               if (tc.InstanceConstructors == null) {
-                                       atype = atype.BaseType;
-                                       goto again;
-                               }
+                       if (tparam.HasSpecialStruct && (!TypeManager.IsValueType (atype) || TypeManager.IsNullableType (atype))) {
+                               report.Error (453, loc,
+                                       "The type `{0}' must be a non-nullable value type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
+                                       TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
+                               return false;
+                       }
 
-                               foreach (Constructor c in tc.InstanceConstructors) {
-                                       if ((c.ModFlags & Modifiers.PUBLIC) == 0)
-                                               continue;
-                                       if ((c.Parameters.FixedParameters != null) &&
-                                           (c.Parameters.FixedParameters.Length != 0))
-                                               continue;
-                                       if (c.Parameters.HasArglist || c.Parameters.HasParams)
-                                               continue;
+                       //
+                       // The class constraint comes next.
+                       //
+                       if (tparam.HasTypeConstraint) {
+                               CheckConversion (context, atype, tparam, tparam.BaseType, loc, report);
+                       }
 
-                                       return true;
+                       //
+                       // Now, check the interfaces and type parameters constraints
+                       //
+                       if (tparam.Interfaces != null) {
+                               if (TypeManager.IsNullableType (atype)) {
+                                       report.Error (313, loc,
+                                               "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. The nullable type `{0}' never satisfies interface constraint",
+                                               atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
+                               } else {
+                                       foreach (TypeSpec iface in tparam.Interfaces) {
+                                               CheckConversion (context, atype, tparam, iface, loc, report);
+                                       }
                                }
                        }
 
-                       MemberInfo [] list = TypeManager.MemberLookup (null, null, atype, MemberTypes.Constructor,
-                               BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
-                               ConstructorInfo.ConstructorName, null);
+                       //
+                       // Finally, check the constructor constraint.
+                       //
+                       if (!tparam.HasSpecialConstructor)
+                               return true;
 
-                       if (list == null)
+                       if (!HasDefaultConstructor (atype)) {
+                               report.SymbolRelatedToPreviousError (atype);
+                               report.Error (310, loc,
+                                       "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
+                                       TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
                                return false;
-
-                       foreach (MethodBase mb in list) {
-                               AParametersCollection pd = TypeManager.GetParameterData (mb);
-                               if (pd.Count == 0)
-                                       return true;
                        }
 
-                       return false;
+                       return true;
                }
 
-               protected abstract string GetSignatureForError ();
-               protected abstract void Report_SymbolRelatedToPreviousError ();
-
-               public static bool CheckConstraints (IMemberContext ec, MethodBase definition,
-                                                    MethodBase instantiated, Location loc)
+               static void CheckConversion (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc, Report report)
                {
-                       MethodConstraintChecker checker = new MethodConstraintChecker (
-                               definition, instantiated.DeclaringType, definition.GetGenericArguments (),
-                               instantiated.GetGenericArguments (), loc, ec.Compiler.Report);
-
-                       return checker.CheckConstraints (ec);
+                       var expr = new EmptyExpression (atype);
+                       if (!Convert.ImplicitStandardConversionExists (expr, ttype)) {
+                               report.SymbolRelatedToPreviousError (tparam);
+                               if (TypeManager.IsValueType (atype)) {
+                                       report.Error (315, loc, "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no boxing conversion from `{0}' to `{3}'",
+                                               atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
+                               } else if (atype.IsGenericParameter) {
+                                       report.Error (314, loc, "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no boxing or type parameter conversion from `{0}' to `{3}'",
+                                               atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
+                               } else {
+                                       report.Error (311, loc, "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no implicit reference conversion from `{0}' to `{3}'",
+                                               atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
+                               }
+                       }
                }
 
-               public static bool CheckConstraints (IMemberContext ec, Type gt, Type[] gen_params,
-                                                    Type[] atypes, Location loc)
+               static bool HasDefaultConstructor (TypeSpec atype)
                {
-                       TypeConstraintChecker checker = new TypeConstraintChecker (
-                               gt, gen_params, atypes, loc, ec.Compiler.Report);
-
-                       return checker.CheckConstraints (ec);
-               }
+                       var tp = atype as TypeParameterSpec;
+                       if (tp != null) {
+                               return tp.HasSpecialConstructor || tp.HasSpecialStruct;
+                       }
 
-               protected class MethodConstraintChecker : ConstraintChecker
-               {
-                       MethodBase definition;
-                       public Type declaring_type;
+                       if (atype.IsStruct || atype.IsEnum)
+                               return true;
 
-                       public MethodConstraintChecker (MethodBase definition, Type declaringType, Type[] gen_params,
-                                                       Type[] atypes, Location loc, Report r)
-                               : base (gen_params, atypes, loc, r)
-                       {
-                               this.declaring_type = declaringType;
-                               this.definition = definition;
-                       }
+                       if (atype.IsAbstract)
+                               return false;
 
-                       protected override string GetSignatureForError ()
-                       {
-                               return TypeManager.CSharpSignature (definition);
-                       }
+                       var tdef = atype.GetDefinition ();
 
-                       protected override void Report_SymbolRelatedToPreviousError ()
-                       {
-                               Report.SymbolRelatedToPreviousError (definition);
-                       }
-               }
+                       //
+                       // In some circumstances MemberCache is not yet populated and members
+                       // cannot be defined yet (recursive type new constraints)
+                       //
+                       // class A<T> where T : B<T>, new () {}
+                       // class B<T> where T : A<T>, new () {}
+                       //
+                       var tc = tdef.MemberDefinition as Class;
+                       if (tc != null) {
+                               if (tc.InstanceConstructors == null) {
+                                       // Default ctor will be generated later
+                                       return true;
+                               }
 
-               protected class TypeConstraintChecker : ConstraintChecker
-               {
-                       Type gt;
+                               foreach (var c in tc.InstanceConstructors) {
+                                       if (c.ParameterInfo.IsEmpty) {
+                                               if ((c.ModFlags & Modifiers.PUBLIC) != 0)
+                                                       return true;
+                                       }
+                               }
 
-                       public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
-                                                     Location loc, Report r)
-                               : base (gen_params, atypes, loc, r)
-                       {
-                               this.gt = gt;
+                               return false;
                        }
 
-                       protected override string GetSignatureForError ()
-                       {
-                               return TypeManager.CSharpName (gt);
-                       }
+                       var found = MemberCache.FindMember (tdef,
+                               MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
+                               BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
 
-                       protected override void Report_SymbolRelatedToPreviousError ()
-                       {
-                               Report.SymbolRelatedToPreviousError (gt);
-                       }
+                       return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
                }
        }
 
@@ -1792,21 +1933,20 @@ namespace Mono.CSharp {
        /// </summary>
        public class GenericMethod : DeclSpace
        {
-               FullNamedExpression return_type;
                ParametersCompiled parameters;
 
                public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
                                      FullNamedExpression return_type, ParametersCompiled parameters)
                        : base (ns, parent, name, null)
                {
-                       this.return_type = return_type;
                        this.parameters = parameters;
                }
 
-               public override TypeContainer CurrentTypeDefinition {
-                       get {
-                               return Parent.CurrentTypeDefinition;
-                       }
+               public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name, TypeParameter[] tparams,
+                                         FullNamedExpression return_type, ParametersCompiled parameters)
+                       : this (ns, parent, name, return_type, parameters)
+               {
+                       this.type_params = tparams;
                }
 
                public override TypeParameter[] CurrentTypeParameters {
@@ -1820,13 +1960,14 @@ namespace Mono.CSharp {
                        throw new Exception ();
                }
 
-               public override bool Define ()
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
-                       for (int i = 0; i < TypeParameters.Length; i++)
-                               if (!TypeParameters [i].Resolve (this))
-                                       return false;
+                       throw new NotSupportedException ();
+               }
 
-                       return true;
+               public override bool Define ()
+               {
+                       throw new NotSupportedException ();
                }
 
                /// <summary>
@@ -1854,64 +1995,22 @@ namespace Mono.CSharp {
 
                        GenericTypeParameterBuilder[] gen_params = m.MethodBuilder.DefineGenericParameters (snames);
                        for (int i = 0; i < TypeParameters.Length; i++)
-                               TypeParameters [i].Define (gen_params [i]);
-
-                       if (!Define ())
-                               return false;
-
-                       for (int i = 0; i < TypeParameters.Length; i++) {
-                               if (!TypeParameters [i].ResolveType (this))
-                                       return false;
-                       }
+                               TypeParameters [i].Define (gen_params [i], null);
 
                        return true;
                }
 
-               /// <summary>
-               ///   We're called from MethodData.Define() after creating the MethodBuilder.
-               /// </summary>
-               public bool DefineType (IMemberContext ec, MethodBuilder mb,
-                                       MethodInfo implementing, bool is_override)
-               {
-                       for (int i = 0; i < TypeParameters.Length; i++)
-                               if (!TypeParameters [i].DefineType (
-                                           ec, mb, implementing, is_override))
-                                       return false;
-
-                       bool ok = parameters.Resolve (ec);
-
-                       if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
-                               ok = false;
-
-                       return ok;
-               }
-
                public void EmitAttributes ()
                {
-                       for (int i = 0; i < TypeParameters.Length; i++)
-                               TypeParameters [i].Emit ();
-
                        if (OptAttributes != null)
                                OptAttributes.Emit ();
                }
 
-               public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
-                                                       MemberFilter filter, object criteria)
-               {
-                       throw new Exception ();
-               }
-
                public override string GetSignatureForError ()
                {
                        return base.GetSignatureForError () + parameters.GetSignatureForError ();
                }
 
-               public override MemberCache MemberCache {
-                       get {
-                               return null;
-                       }
-               }
-
                public override AttributeTargets AttributeTargets {
                        get {
                                return AttributeTargets.Method | AttributeTargets.ReturnValue;
@@ -1925,56 +2024,32 @@ namespace Mono.CSharp {
                public new void VerifyClsCompliance ()
                {
                        foreach (TypeParameter tp in TypeParameters) {
-                               if (tp.Constraints == null)
-                                       continue;
-
-                               tp.Constraints.VerifyClsCompliance (Report);
+                               tp.VerifyClsCompliance ();
                        }
                }
        }
 
-       partial class TypeManager
+       public partial class TypeManager
        {
-               public static TypeContainer LookupGenericTypeContainer (Type t)
+               public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
                {
-                       t = DropGenericTypeArguments (t);
-                       return LookupTypeContainer (t);
-               }
-
-               public static Variance GetTypeParameterVariance (Type type)
-               {
-                       TypeParameter tparam = LookupTypeParameter (type);
-                       if (tparam != null)
-                               return tparam.Variance;
-
-                       switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
-                       case GenericParameterAttributes.Covariant:
-                               return Variance.Covariant;
-                       case GenericParameterAttributes.Contravariant:
-                               return Variance.Contravariant;
-                       default:
-                               return Variance.None;
-                       }
-               }
-
-               public static Variance CheckTypeVariance (Type t, Variance expected, IMemberContext member)
-               {
-                       TypeParameter tp = LookupTypeParameter (t);
+                       var tp = t as TypeParameterSpec;
                        if (tp != null) {
                                Variance v = tp.Variance;
                                if (expected == Variance.None && v != expected ||
                                        expected == Variance.Covariant && v == Variance.Contravariant ||
-                                       expected == Variance.Contravariant && v == Variance.Covariant)
-                                       tp.ErrorInvalidVariance (member, expected);
+                                       expected == Variance.Contravariant && v == Variance.Covariant) {
+                                       ((TypeParameter)tp.MemberDefinition).ErrorInvalidVariance (member, expected);
+                               }
 
                                return expected;
                        }
 
-                       if (t.IsGenericType) {
-                               Type[] targs_definition = GetTypeArguments (DropGenericTypeArguments (t));
-                               Type[] targs = GetTypeArguments (t);
-                               for (int i = 0; i < targs_definition.Length; ++i) {
-                                       Variance v = GetTypeParameterVariance (targs_definition[i]);
+                       if (t.TypeArguments.Length > 0) {
+                               var targs_definition = t.MemberDefinition.TypeParameters;
+                               TypeSpec[] targs = GetTypeArguments (t);
+                               for (int i = 0; i < targs.Length; ++i) {
+                                       Variance v = targs_definition[i].Variance;
                                        CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
                                }
 
@@ -1987,163 +2062,6 @@ namespace Mono.CSharp {
                        return Variance.None;
                }
 
-               public static bool IsVariantOf (Type type1, Type type2)
-               {
-                       if (!type1.IsGenericType || !type2.IsGenericType)
-                               return false;
-
-                       Type generic_target_type = DropGenericTypeArguments (type2);
-                       if (DropGenericTypeArguments (type1) != generic_target_type)
-                               return false;
-
-                       Type[] t1 = GetTypeArguments (type1);
-                       Type[] t2 = GetTypeArguments (type2);
-                       Type[] targs_definition = GetTypeArguments (generic_target_type);
-                       for (int i = 0; i < targs_definition.Length; ++i) {
-                               Variance v = GetTypeParameterVariance (targs_definition [i]);
-                               if (v == Variance.None) {
-                                       if (t1[i] == t2[i])
-                                               continue;
-                                       return false;
-                               }
-
-                               if (v == Variance.Covariant) {
-                                       if (!Convert.ImplicitReferenceConversionExists (new EmptyExpression (t1 [i]), t2 [i]))
-                                               return false;
-                               } else if (!Convert.ImplicitReferenceConversionExists (new EmptyExpression (t2[i]), t1[i])) {
-                                       return false;
-                               }
-                       }
-
-                       return true;
-               }
-
-               /// <summary>
-               ///   Check whether `a' and `b' may become equal generic types.
-               ///   The algorithm to do that is a little bit complicated.
-               /// </summary>
-               public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
-                                                              Type[] method_inferred)
-               {
-                       if (a.IsGenericParameter) {
-                               //
-                               // If a is an array of a's type, they may never
-                               // become equal.
-                               //
-                               while (b.IsArray) {
-                                       b = GetElementType (b);
-                                       if (a.Equals (b))
-                                               return false;
-                               }
-
-                               //
-                               // If b is a generic parameter or an actual type,
-                               // they may become equal:
-                               //
-                               //    class X<T,U> : I<T>, I<U>
-                               //    class X<T> : I<T>, I<float>
-                               // 
-                               if (b.IsGenericParameter || !b.IsGenericType) {
-                                       int pos = a.GenericParameterPosition;
-                                       Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
-                                       if (args [pos] == null) {
-                                               args [pos] = b;
-                                               return true;
-                                       }
-
-                                       return args [pos] == a;
-                               }
-
-                               //
-                               // We're now comparing a type parameter with a
-                               // generic instance.  They may become equal unless
-                               // the type parameter appears anywhere in the
-                               // generic instance:
-                               //
-                               //    class X<T,U> : I<T>, I<X<U>>
-                               //        -> error because you could instanciate it as
-                               //           X<X<int>,int>
-                               //
-                               //    class X<T> : I<T>, I<X<T>> -> ok
-                               //
-
-                               Type[] bargs = GetTypeArguments (b);
-                               for (int i = 0; i < bargs.Length; i++) {
-                                       if (a.Equals (bargs [i]))
-                                               return false;
-                               }
-
-                               return true;
-                       }
-
-                       if (b.IsGenericParameter)
-                               return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
-
-                       //
-                       // At this point, neither a nor b are a type parameter.
-                       //
-                       // If one of them is a generic instance, let
-                       // MayBecomeEqualGenericInstances() compare them (if the
-                       // other one is not a generic instance, they can never
-                       // become equal).
-                       //
-
-                       if (a.IsGenericType || b.IsGenericType)
-                               return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
-
-                       //
-                       // If both of them are arrays.
-                       //
-
-                       if (a.IsArray && b.IsArray) {
-                               if (a.GetArrayRank () != b.GetArrayRank ())
-                                       return false;
-                       
-                               a = GetElementType (a);
-                               b = GetElementType (b);
-
-                               return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
-                       }
-
-                       //
-                       // Ok, two ordinary types.
-                       //
-
-                       return a.Equals (b);
-               }
-
-               //
-               // Checks whether two generic instances may become equal for some
-               // particular instantiation (26.3.1).
-               //
-               public static bool MayBecomeEqualGenericInstances (Type a, Type b,
-                                                                  Type[] class_inferred,
-                                                                  Type[] method_inferred)
-               {
-                       if (!a.IsGenericType || !b.IsGenericType)
-                               return false;
-                       if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
-                               return false;
-
-                       return MayBecomeEqualGenericInstances (
-                               GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
-               }
-
-               public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
-                                                                  Type[] class_inferred,
-                                                                  Type[] method_inferred)
-               {
-                       if (aargs.Length != bargs.Length)
-                               return false;
-
-                       for (int i = 0; i < aargs.Length; i++) {
-                               if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
-                                       return false;
-                       }
-
-                       return true;
-               }
-
                /// <summary>
                ///   Type inference.  Try to infer the type arguments from `method',
                ///   which is invoked with the arguments `arguments'.  This is used
@@ -2153,32 +2071,16 @@ namespace Mono.CSharp {
                public static int InferTypeArguments (ResolveContext ec, Arguments arguments, ref MethodSpec method)
                {
                        ATypeInference ti = ATypeInference.CreateInstance (arguments);
-                       Type[] i_args = ti.InferMethodArguments (ec, method);
+                       TypeSpec[] i_args = ti.InferMethodArguments (ec, method);
                        if (i_args == null)
                                return ti.InferenceScore;
 
                        if (i_args.Length == 0)
                                return 0;
 
-                       method = method.Inflate (i_args);
+                       method = method.MakeGenericMethod (i_args);
                        return 0;
                }
-
-/*
-               public static bool InferTypeArguments (ResolveContext ec, AParametersCollection param, ref MethodBase method)
-               {
-                       if (!TypeManager.IsGenericMethod (method))
-                               return true;
-
-                       ATypeInference ti = ATypeInference.CreateInstance (DelegateCreation.CreateDelegateMethodArguments (param, Location.Null));
-                       Type[] i_args = ti.InferDelegateArguments (ec, method);
-                       if (i_args == null)
-                               return false;
-
-                       method = ((MethodInfo) method).MakeGenericMethod (i_args);
-                       return true;
-               }
-*/
        }
 
        abstract class ATypeInference
@@ -2204,8 +2106,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               public abstract Type[] InferMethodArguments (ResolveContext ec, MethodSpec method);
-//             public abstract Type[] InferDelegateArguments (ResolveContext ec, MethodBase method);
+               public abstract TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method);
        }
 
        //
@@ -2229,38 +2130,12 @@ namespace Mono.CSharp {
                        }
                }
 
-/*
-               public override Type[] InferDelegateArguments (ResolveContext ec, MethodBase method)
-               {
-                       AParametersCollection pd = TypeManager.GetParameterData (method);
-                       if (arg_count != pd.Count)
-                               return null;
-
-                       Type[] d_gargs = method.GetGenericArguments ();
-                       TypeInferenceContext context = new TypeInferenceContext (d_gargs);
-
-                       // A lower-bound inference is made from each argument type Uj of D
-                       // to the corresponding parameter type Tj of M
-                       for (int i = 0; i < arg_count; ++i) {
-                               Type t = pd.Types [i];
-                               if (!t.IsGenericParameter)
-                                       continue;
-
-                               context.LowerBoundInference (arguments [i].Expr.Type, t);
-                       }
-
-                       if (!context.FixAllTypes (ec))
-                               return null;
-
-                       return context.InferredTypeArguments;
-               }
-*/
-               public override Type[] InferMethodArguments (ResolveContext ec, MethodSpec method)
+               public override TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
                {
-                       var method_generic_args = method.GetGenericArguments ();
+                       var method_generic_args = method.GenericDefinition.TypeParameters;
                        TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
                        if (!context.UnfixedVariableExists)
-                               return Type.EmptyTypes;
+                               return TypeSpec.EmptyTypes;
 
                        AParametersCollection pd = method.Parameters;
                        if (!InferInPhases (ec, context, pd))
@@ -2281,12 +2156,12 @@ namespace Mono.CSharp {
                                params_arguments_start = arg_count;
                        }
 
-                       Type [] ptypes = methodParameters.Types;
+                       TypeSpec [] ptypes = methodParameters.Types;
                        
                        //
                        // The first inference phase
                        //
-                       Type method_parameter = null;
+                       TypeSpec method_parameter = null;
                        for (int i = 0; i < arg_count; i++) {
                                Argument a = arguments [i];
                                if (a == null)
@@ -2300,7 +2175,7 @@ namespace Mono.CSharp {
                                        else
                                                method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
 
-                                       ptypes = (Type[]) ptypes.Clone ();
+                                       ptypes = (TypeSpec[]) ptypes.Clone ();
                                        ptypes [i] = method_parameter;
                                }
 
@@ -2320,7 +2195,7 @@ namespace Mono.CSharp {
                                        continue;
                                }
 
-                               if (a.Expr.Type == TypeManager.null_type)
+                               if (a.Expr.Type == InternalType.Null)
                                        continue;
 
                                if (TypeManager.IsValueType (method_parameter)) {
@@ -2345,7 +2220,7 @@ namespace Mono.CSharp {
                        return DoSecondPhase (ec, tic, ptypes, !fixed_any);
                }
 
-               bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, Type[] methodParameters, bool fixDependent)
+               bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
                {
                        bool fixed_any = false;
                        if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
@@ -2364,23 +2239,17 @@ namespace Mono.CSharp {
                        for (int i = 0; i < arg_count; i++) {
                                
                                // Align params arguments
-                               Type t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
+                               TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
                                
                                if (!TypeManager.IsDelegateType (t_i)) {
-                                       if (TypeManager.DropGenericTypeArguments (t_i) != TypeManager.expression_type)
+                                       if (t_i.GetDefinition () != TypeManager.expression_type)
                                                continue;
 
-                                       t_i = t_i.GetGenericArguments () [0];
+                                       t_i = TypeManager.GetTypeArguments (t_i) [0];
                                }
 
-                               var mi = Delegate.GetInvokeMethod (ec.Compiler, t_i, t_i);
-                               Type rtype = mi.ReturnType;
-
-#if MS_COMPATIBLE
-                               // Blablabla, because reflection does not work with dynamic types
-//                             Type[] g_args = t_i.GetGenericArguments ();
-//                             rtype = g_args[rtype.GenericParameterPosition];
-#endif
+                               var mi = Delegate.GetInvokeMethod (ec.Compiler, t_i);
+                               TypeSpec rtype = mi.ReturnType;
 
                                if (tic.IsReturnTypeNonDependent (ec, mi, rtype))
                                        score -= tic.OutputTypeInference (ec, arguments [i].Expr, t_i);
@@ -2402,10 +2271,10 @@ namespace Mono.CSharp {
 
                class BoundInfo
                {
-                       public readonly Type Type;
+                       public readonly TypeSpec Type;
                        public readonly BoundKind Kind;
 
-                       public BoundInfo (Type type, BoundKind kind)
+                       public BoundInfo (TypeSpec type, BoundKind kind)
                        {
                                this.Type = type;
                                this.Kind = kind;
@@ -2423,22 +2292,23 @@ namespace Mono.CSharp {
                        }
                }
 
-               readonly Type[] unfixed_types;
-               readonly Type[] fixed_types;
+               readonly TypeSpec[] unfixed_types;
+               readonly TypeSpec[] fixed_types;
                readonly List<BoundInfo>[] bounds;
                bool failed;
-               
-               public TypeInferenceContext (Type[] typeArguments)
+
+               // TODO MemberCache: Could it be TypeParameterSpec[] ??
+               public TypeInferenceContext (TypeSpec[] typeArguments)
                {
                        if (typeArguments.Length == 0)
                                throw new ArgumentException ("Empty generic arguments");
 
-                       fixed_types = new Type [typeArguments.Length];
+                       fixed_types = new TypeSpec [typeArguments.Length];
                        for (int i = 0; i < typeArguments.Length; ++i) {
                                if (typeArguments [i].IsGenericParameter) {
                                        if (bounds == null) {
                                                bounds = new List<BoundInfo> [typeArguments.Length];
-                                               unfixed_types = new Type [typeArguments.Length];
+                                               unfixed_types = new TypeSpec [typeArguments.Length];
                                        }
                                        unfixed_types [i] = typeArguments [i];
                                } else {
@@ -2453,19 +2323,19 @@ namespace Mono.CSharp {
                //
                public TypeInferenceContext ()
                {
-                       fixed_types = new Type [1];
-                       unfixed_types = new Type [1];
+                       fixed_types = new TypeSpec [1];
+                       unfixed_types = new TypeSpec [1];
                        unfixed_types[0] = InternalType.Arglist; // it can be any internal type
                        bounds = new List<BoundInfo> [1];
                }
 
-               public Type[] InferredTypeArguments {
+               public TypeSpec[] InferredTypeArguments {
                        get {
                                return fixed_types;
                        }
                }
 
-               public void AddCommonTypeBound (Type type)
+               public void AddCommonTypeBound (TypeSpec type)
                {
                        AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
                }
@@ -2500,17 +2370,17 @@ namespace Mono.CSharp {
                        a.Add (bound);
                }
                
-               bool AllTypesAreFixed (Type[] types)
+               bool AllTypesAreFixed (TypeSpec[] types)
                {
-                       foreach (Type t in types) {
+                       foreach (TypeSpec t in types) {
                                if (t.IsGenericParameter) {
                                        if (!IsFixed (t))
                                                return false;
                                        continue;
                                }
 
-                               if (t.IsGenericType)
-                                       return AllTypesAreFixed (t.GetGenericArguments ());
+                               if (TypeManager.IsGenericType (t))
+                                       return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
                        }
                        
                        return true;
@@ -2519,26 +2389,27 @@ namespace Mono.CSharp {
                //
                // 26.3.3.8 Exact Inference
                //
-               public int ExactInference (Type u, Type v)
+               public int ExactInference (TypeSpec u, TypeSpec v)
                {
                        // If V is an array type
                        if (v.IsArray) {
                                if (!u.IsArray)
                                        return 0;
 
-                               if (u.GetArrayRank () != v.GetArrayRank ())
+                               // TODO MemberCache: GetMetaInfo ()
+                               if (u.GetMetaInfo ().GetArrayRank () != v.GetMetaInfo ().GetArrayRank ())
                                        return 0;
 
                                return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
                        }
 
                        // If V is constructed type and U is constructed type
-                       if (v.IsGenericType && !v.IsGenericTypeDefinition) {
-                               if (!u.IsGenericType)
+                       if (TypeManager.IsGenericType (v)) {
+                               if (!TypeManager.IsGenericType (u))
                                        return 0;
 
-                               Type [] ga_u = u.GetGenericArguments ();
-                               Type [] ga_v = v.GetGenericArguments ();
+                               TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
+                               TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
                                if (ga_u.Length != ga_v.Length)
                                        return 0;
 
@@ -2593,39 +2464,32 @@ namespace Mono.CSharp {
                //
                // All unfixed type variables Xi which depend on no Xj are fixed
                //
-               public bool FixIndependentTypeArguments (ResolveContext ec, Type[] methodParameters, ref bool fixed_any)
+               public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
                {
-                       var types_to_fix = new List<Type> (unfixed_types);
+                       var types_to_fix = new List<TypeSpec> (unfixed_types);
                        for (int i = 0; i < methodParameters.Length; ++i) {
-                               Type t = methodParameters[i];
+                               TypeSpec t = methodParameters[i];
 
                                if (!TypeManager.IsDelegateType (t)) {
-                                       if (TypeManager.DropGenericTypeArguments (t) != TypeManager.expression_type)
+                                       if (TypeManager.expression_type == null || t.MemberDefinition != TypeManager.expression_type.MemberDefinition)
                                                continue;
 
-                                       t = t.GetGenericArguments () [0];
+                                       t =  TypeManager.GetTypeArguments (t) [0];
                                }
 
                                if (t.IsGenericParameter)
                                        continue;
 
-                               var invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
-                               Type rtype = invoke.ReturnType;
-                               if (!rtype.IsGenericParameter && !rtype.IsGenericType)
+                               var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
+                               TypeSpec rtype = invoke.ReturnType;
+                               if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
                                        continue;
 
-#if MS_COMPATIBLE
-                               // Blablabla, because reflection does not work with dynamic types
-//                             if (rtype.IsGenericParameter) {
-//                                     Type [] g_args = t.GetGenericArguments ();
-//                                     rtype = g_args [rtype.GenericParameterPosition];
-//                             }
-#endif
                                // Remove dependent types, they cannot be fixed yet
                                RemoveDependentTypes (types_to_fix, rtype);
                        }
 
-                       foreach (Type t in types_to_fix) {
+                       foreach (TypeSpec t in types_to_fix) {
                                if (t == null)
                                        continue;
 
@@ -2657,8 +2521,8 @@ namespace Mono.CSharp {
 
                        if (candidates.Count == 1) {
                                unfixed_types[i] = null;
-                               Type t = candidates[0].Type;
-                               if (t == TypeManager.null_type)
+                               TypeSpec t = candidates[0].Type;
+                               if (t == InternalType.Null)
                                        return false;
 
                                fixed_types [i] = t;
@@ -2670,16 +2534,16 @@ namespace Mono.CSharp {
                        // a standard implicit conversion to all the other
                        // candidate types.
                        //
-                       Type best_candidate = null;
+                       TypeSpec best_candidate = null;
                        int cii;
                        int candidates_count = candidates.Count;
                        for (int ci = 0; ci < candidates_count; ++ci) {
-                               BoundInfo bound = (BoundInfo)candidates [ci];
+                               BoundInfo bound = candidates [ci];
                                for (cii = 0; cii < candidates_count; ++cii) {
                                        if (cii == ci)
                                                continue;
 
-                                       BoundInfo cbound = (BoundInfo) candidates[cii];
+                                       BoundInfo cbound = candidates[cii];
                                        
                                        // Same type parameters with different bounds
                                        if (cbound.Type == bound.Type) {
@@ -2741,24 +2605,27 @@ namespace Mono.CSharp {
                //
                // Uses inferred types to inflate delegate type argument
                //
-               public Type InflateGenericArgument (Type parameter)
+               public TypeSpec InflateGenericArgument (TypeSpec parameter)
                {
-                       if (parameter.IsGenericParameter) {
+                       var tp = parameter as TypeParameterSpec;
+                       if (tp != null) {
                                //
                                // Inflate method generic argument (MVAR) only
                                //
-                               if (parameter.DeclaringMethod == null)
+                               if (!tp.IsMethodOwned)
                                        return parameter;
 
-                               return fixed_types [parameter.GenericParameterPosition];
+                               return fixed_types [tp.DeclaredPosition];
                        }
 
-                       if (parameter.IsGenericType) {
-                               Type [] parameter_targs = parameter.GetGenericArguments ();
-                               for (int ii = 0; ii < parameter_targs.Length; ++ii) {
-                                       parameter_targs [ii] = InflateGenericArgument (parameter_targs [ii]);
+                       var gt = parameter as InflatedTypeSpec;
+                       if (gt != null) {
+                               var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
+                               for (int ii = 0; ii < inflated_targs.Length; ++ii) {
+                                       inflated_targs[ii] = InflateGenericArgument (gt.TypeArguments [ii]);
                                }
-                               return parameter.GetGenericTypeDefinition ().MakeGenericType (parameter_targs);
+
+                               return gt.GetDefinition ().MakeGenericType (inflated_targs);
                        }
 
                        return parameter;
@@ -2768,18 +2635,18 @@ namespace Mono.CSharp {
                // Tests whether all delegate input arguments are fixed and generic output type
                // requires output type inference 
                //
-               public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, Type returnType)
+               public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, TypeSpec returnType)
                {
                        if (returnType.IsGenericParameter) {
                                if (IsFixed (returnType))
                                    return false;
-                       } else if (returnType.IsGenericType) {
+                       } else if (TypeManager.IsGenericType (returnType)) {
                                if (TypeManager.IsDelegateType (returnType)) {
-                                       invoke = Delegate.GetInvokeMethod (ec.Compiler, returnType, returnType);
+                                       invoke = Delegate.GetInvokeMethod (ec.Compiler, returnType);
                                        return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
                                }
                                        
-                               Type[] g_args = returnType.GetGenericArguments ();
+                               TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
                                
                                // At least one unfixed return type has to exist 
                                if (AllTypesAreFixed (g_args))
@@ -2793,12 +2660,12 @@ namespace Mono.CSharp {
                        return AllTypesAreFixed (d_parameters.Types);
                }
                
-               bool IsFixed (Type type)
+               bool IsFixed (TypeSpec type)
                {
                        return IsUnfixed (type) == -1;
                }               
 
-               int IsUnfixed (Type type)
+               int IsUnfixed (TypeSpec type)
                {
                        if (!type.IsGenericParameter)
                                return -1;
@@ -2815,7 +2682,7 @@ namespace Mono.CSharp {
                //
                // 26.3.3.9 Lower-bound Inference
                //
-               public int LowerBoundInference (Type u, Type v)
+               public int LowerBoundInference (TypeSpec u, TypeSpec v)
                {
                        return LowerBoundInference (u, v, false);
                }
@@ -2823,7 +2690,7 @@ namespace Mono.CSharp {
                //
                // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
                //
-               int LowerBoundInference (Type u, Type v, bool inversed)
+               int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
                {
                        // If V is one of the unfixed type arguments
                        int pos = IsUnfixed (v);
@@ -2833,75 +2700,67 @@ namespace Mono.CSharp {
                        }                       
 
                        // If U is an array type
-                       if (u.IsArray) {
-                               int u_dim = u.GetArrayRank ();
-                               Type v_i;
-                               Type u_i = TypeManager.GetElementType (u);
-
-                               if (v.IsArray) {
-                                       if (u_dim != v.GetArrayRank ())
+                       var u_ac = u as ArrayContainer;
+                       if (u_ac != null) {
+                               var v_ac = v as ArrayContainer;
+                               if (v_ac != null) {
+                                       if (u_ac.Rank != v_ac.Rank)
                                                return 0;
 
-                                       v_i = TypeManager.GetElementType (v);
-
-                                       if (TypeManager.IsValueType (u_i))
-                                               return ExactInference (u_i, v_i);
+                                       if (TypeManager.IsValueType (u_ac.Element))
+                                               return ExactInference (u_ac.Element, v_ac.Element);
 
-                                       return LowerBoundInference (u_i, v_i, inversed);
+                                       return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
                                }
 
-                               if (u_dim != 1)
+                               if (u_ac.Rank != 1)
                                        return 0;
 
-                               if (v.IsGenericType) {
-                                       Type g_v = v.GetGenericTypeDefinition ();
-                                       if ((g_v != TypeManager.generic_ilist_type) && (g_v != TypeManager.generic_icollection_type) &&
-                                               (g_v != TypeManager.generic_ienumerable_type))
+                               if (TypeManager.IsGenericType (v)) {
+                                       TypeSpec g_v = v.GetDefinition ();
+                                       if (g_v != TypeManager.generic_ilist_type &&
+                                               g_v != TypeManager.generic_icollection_type &&
+                                               g_v != TypeManager.generic_ienumerable_type)
                                                return 0;
 
-                                       v_i = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (v) [0]);
-                                       if (TypeManager.IsValueType (u_i))
-                                               return ExactInference (u_i, v_i);
+                                       var v_i = TypeManager.GetTypeArguments (v) [0];
+                                       if (TypeManager.IsValueType (u_ac.Element))
+                                               return ExactInference (u_ac.Element, v_i);
 
-                                       return LowerBoundInference (u_i, v_i);
+                                       return LowerBoundInference (u_ac.Element, v_i);
                                }
-                       } else if (v.IsGenericType && !v.IsGenericTypeDefinition) {
+                       } else if (TypeManager.IsGenericType (v)) {
                                //
                                // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
                                // such that U is identical to, inherits from (directly or indirectly),
                                // or implements (directly or indirectly) C<U1..Uk>
                                //
-                               var u_candidates = new List<Type> ();
-                               if (u.IsGenericType)
-                                       u_candidates.Add (u);
+                               var u_candidates = new List<TypeSpec> ();
+                               var open_v = v.MemberDefinition;
 
-                               for (Type t = u.BaseType; t != null; t = t.BaseType) {
-                                       if (t.IsGenericType && !t.IsGenericTypeDefinition)
+                               for (TypeSpec t = u; t != null; t = t.BaseType) {
+                                       if (open_v == t.MemberDefinition)
                                                u_candidates.Add (t);
-                               }
-
-                               // TODO: Implement GetGenericInterfaces only and remove
-                               // the if from foreach
-                               u_candidates.AddRange (TypeManager.GetInterfaces (u));
 
-                               Type open_v = v.GetGenericTypeDefinition ();
-                               Type [] unique_candidate_targs = null;
-                               Type [] ga_v = v.GetGenericArguments ();                        
-                               foreach (Type u_candidate in u_candidates) {
-                                       if (!u_candidate.IsGenericType || u_candidate.IsGenericTypeDefinition)
-                                               continue;
-
-                                       if (TypeManager.DropGenericTypeArguments (u_candidate) != open_v)
-                                               continue;
+                                       if (t.Interfaces != null) {
+                                               foreach (var iface in t.Interfaces) {
+                                                       if (open_v == iface.MemberDefinition)
+                                                               u_candidates.Add (iface);
+                                               }
+                                       }
+                               }
 
+                               TypeSpec [] unique_candidate_targs = null;
+                               TypeSpec[] ga_v = TypeManager.GetTypeArguments (v);
+                               foreach (TypeSpec u_candidate in u_candidates) {
                                        //
                                        // The unique set of types U1..Uk means that if we have an interface I<T>,
                                        // class U : I<int>, I<long> then no type inference is made when inferring
                                        // type I<T> by applying type U because T could be int or long
                                        //
                                        if (unique_candidate_targs != null) {
-                                               Type[] second_unique_candidate_targs = u_candidate.GetGenericArguments ();
-                                               if (TypeManager.IsEqual (unique_candidate_targs, second_unique_candidate_targs)) {
+                                               TypeSpec[] second_unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
+                                               if (TypeSpecComparer.Default.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
                                                        unique_candidate_targs = second_unique_candidate_targs;
                                                        continue;
                                                }
@@ -2913,16 +2772,16 @@ namespace Mono.CSharp {
                                                return 1;
                                        }
 
-                                       unique_candidate_targs = u_candidate.GetGenericArguments ();
+                                       unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
                                }
 
                                if (unique_candidate_targs != null) {
-                                       Type[] ga_open_v = open_v.GetGenericArguments ();
+                                       var ga_open_v = open_v.TypeParameters;
                                        int score = 0;
                                        for (int i = 0; i < unique_candidate_targs.Length; ++i) {
-                                               Variance variance = TypeManager.GetTypeParameterVariance (ga_open_v [i]);
+                                               Variance variance = ga_open_v [i].Variance;
 
-                                               Type u_i = unique_candidate_targs [i];
+                                               TypeSpec u_i = unique_candidate_targs [i];
                                                if (variance == Variance.None || TypeManager.IsValueType (u_i)) {
                                                        if (ExactInference (u_i, ga_v [i]) == 0)
                                                                ++score;
@@ -2944,25 +2803,20 @@ namespace Mono.CSharp {
                //
                // 26.3.3.6 Output Type Inference
                //
-               public int OutputTypeInference (ResolveContext ec, Expression e, Type t)
+               public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
                {
                        // If e is a lambda or anonymous method with inferred return type
                        AnonymousMethodExpression ame = e as AnonymousMethodExpression;
                        if (ame != null) {
-                               Type rt = ame.InferReturnType (ec, this, t);
-                               var invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
+                               TypeSpec rt = ame.InferReturnType (ec, this, t);
+                               var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
 
                                if (rt == null) {
                                        AParametersCollection pd = invoke.Parameters;
                                        return ame.Parameters.Count == pd.Count ? 1 : 0;
                                }
 
-                               Type rtype = invoke.ReturnType;
-#if MS_COMPATIBLE
-                               // Blablabla, because reflection does not work with dynamic types
-//                             Type [] g_args = t.GetGenericArguments ();
-//                             rtype = g_args [rtype.GenericParameterPosition];
-#endif
+                               TypeSpec rtype = invoke.ReturnType;
                                return LowerBoundInference (rt, rtype) + 1;
                        }
 
@@ -2977,13 +2831,8 @@ namespace Mono.CSharp {
                                if (!TypeManager.IsDelegateType (t))
                                        return 0;
 
-                               var invoke = Delegate.GetInvokeMethod (ec.Compiler, t, t);
-                               Type rtype = invoke.ReturnType;
-#if MS_COMPATIBLE
-                               // Blablabla, because reflection does not work with dynamic types
-//                             Type [] g_args = t.GetGenericArguments ();
-//                             rtype = g_args [rtype.GenericParameterPosition];
-#endif
+                               var invoke = Delegate.GetInvokeMethod (ec.Compiler, t);
+                               TypeSpec rtype = invoke.ReturnType;
 
                                if (!TypeManager.IsGenericType (rtype))
                                        return 0;
@@ -3006,7 +2855,7 @@ namespace Mono.CSharp {
                        return LowerBoundInference (e.Type, t) * 2;
                }
 
-               void RemoveDependentTypes (List<Type> types, Type returnType)
+               void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
                {
                        int idx = IsUnfixed (returnType);
                        if (idx >= 0) {
@@ -3014,8 +2863,8 @@ namespace Mono.CSharp {
                                return;
                        }
 
-                       if (returnType.IsGenericType) {
-                               foreach (Type t in returnType.GetGenericArguments ()) {
+                       if (TypeManager.IsGenericType (returnType)) {
+                               foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
                                        RemoveDependentTypes (types, t);
                                }
                        }
@@ -3026,7 +2875,7 @@ namespace Mono.CSharp {
                                if (unfixed_types == null)
                                        return false;
 
-                               foreach (Type ut in unfixed_types)
+                               foreach (TypeSpec ut in unfixed_types)
                                        if (ut != null)
                                                return true;
                                return false;
index 8c74402d8d59496a2ddb8104bab8216bc25aaf14..2a02515b3ac3a89abeadcfd3adcc22cee4e1b612 100644 (file)
@@ -12,22 +12,63 @@ using System;
 using System.Reflection;
 using System.Runtime.CompilerServices;
 using System.Linq;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Runtime.InteropServices;
 
 namespace Mono.CSharp
 {
-       static class Import
+       public static class Import
        {
-               public static FieldSpec CreateField (FieldInfo fi)
+               static Dictionary<Type, TypeSpec> import_cache;
+               static Dictionary<Type, PredefinedTypeSpec> type_2_predefined;
+
+               public static void Initialize ()
                {
-                       // TODO MemberCache: remove
-                       var cs = TypeManager.GetConstant (fi);
-                       if (cs != null)
-                               return cs;
-                       var fb = TypeManager.GetFieldCore (fi);
-                       if (fb != null)
-                               return fb.Spec;
-                       // End
+                       import_cache = new Dictionary<Type, TypeSpec> (1024, ReferenceEquality<Type>.Default);
+
+                       // Setup mapping for predefined types
+                       type_2_predefined = new Dictionary<Type, PredefinedTypeSpec> () {
+                               { typeof (object), TypeManager.object_type },
+                               { typeof (System.ValueType), TypeManager.value_type },
+                               { typeof (System.Attribute), TypeManager.attribute_type },
+
+                               { typeof (int), TypeManager.int32_type },
+                               { typeof (long), TypeManager.int64_type },
+                               { typeof (uint), TypeManager.uint32_type },
+                               { typeof (ulong), TypeManager.uint64_type },
+                               { typeof (byte), TypeManager.byte_type },
+                               { typeof (sbyte), TypeManager.sbyte_type },
+                               { typeof (short), TypeManager.short_type },
+                               { typeof (ushort), TypeManager.ushort_type },
+
+                               { typeof (System.Collections.IEnumerator), TypeManager.ienumerator_type },
+                               { typeof (System.Collections.IEnumerable), TypeManager.ienumerable_type },
+                               { typeof (System.IDisposable), TypeManager.idisposable_type },
+
+                               { typeof (char), TypeManager.char_type },
+                               { typeof (string), TypeManager.string_type },
+                               { typeof (float), TypeManager.float_type },
+                               { typeof (double), TypeManager.double_type },
+                               { typeof (decimal), TypeManager.decimal_type },
+                               { typeof (bool), TypeManager.bool_type },
+                               { typeof (System.IntPtr), TypeManager.intptr_type },
+                               { typeof (System.UIntPtr), TypeManager.uintptr_type },
+
+                               { typeof (System.MulticastDelegate), TypeManager.multicast_delegate_type },
+                               { typeof (System.Delegate), TypeManager.delegate_type },
+                               { typeof (System.Enum), TypeManager.enum_type },
+                               { typeof (System.Array), TypeManager.array_type },
+                               { typeof (void), TypeManager.void_type },
+                               { typeof (System.Type), TypeManager.type_type },
+                               { typeof (System.Exception), TypeManager.exception_type },
+                               { typeof (System.RuntimeFieldHandle), TypeManager.runtime_field_handle_type },
+                               { typeof (System.RuntimeTypeHandle), TypeManager.runtime_handle_type }
+                       };
+               }
 
+               public static FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
+               {
                        Modifiers mod = 0;
                        var fa = fi.Attributes;
                        switch (fa & FieldAttributes.FieldAccessMask) {
@@ -48,37 +89,18 @@ namespace Mono.CSharp
                                        break;
                        }
 
-                       // TODO MemberCache: Remove completely and use only Imported
-                       IMemberDefinition definition;
-                       var gfd = TypeManager.GetGenericFieldDefinition (fi);
-                       fb = TypeManager.GetFieldCore (gfd);
-                       if (fb != null) {
-                               definition = fb;
-                       } else {
-                               cs = TypeManager.GetConstant (gfd);
-                               if (cs != null)
-                                       definition = cs.MemberDefinition;
-                               else
-                                       definition = new ImportedMemberDefinition (fi);
-                       }
+                       var definition = new ImportedMemberDefinition (fi);
 
                        if ((fa & FieldAttributes.Literal) != 0) {
-                               Expression c;
-                               if (gfd is System.Reflection.Emit.FieldBuilder) {
-                                       // TODO: Remove after MemberCache
-                                       c = TypeManager.GetConstant (gfd).Value;
-                               } else {
-                                       c = Constant.CreateConstantFromValue (fi.FieldType, gfd.GetValue (gfd), Location.Null);
-                               }
-
-                               return new ConstSpec (definition, fi, mod, c);
+                               var     c = Constant.CreateConstantFromValue (ImportType (fi.FieldType), fi.GetValue (fi), Location.Null);
+                               return new ConstSpec (declaringType, definition, ImportType (fi.FieldType), fi, mod, c);
                        }
 
                        if ((fa & FieldAttributes.InitOnly) != 0) {
-                               if (fi.FieldType == TypeManager.decimal_type) {
-                                       var dc = ReadDecimalConstant (gfd);
+                               if (fi.FieldType == typeof (decimal)) {
+                                       var dc = ReadDecimalConstant (fi);
                                        if (dc != null)
-                                               return new ConstSpec (definition, fi, mod, dc);
+                                               return new ConstSpec (declaringType, definition, ImportType (fi.FieldType), fi, mod, dc);
                                }
 
                                mod |= Modifiers.READONLY;
@@ -87,94 +109,109 @@ namespace Mono.CSharp
                        if ((fa & FieldAttributes.Static) != 0)
                                mod |= Modifiers.STATIC;
 
-                       if (!TypeManager.IsReferenceType (fi.FieldType)) {
-                               PredefinedAttribute pa = PredefinedAttributes.Get.FixedBuffer;
-                               if (pa.IsDefined) {
-                                       if (gfd is System.Reflection.Emit.FieldBuilder) {
-                                                // TODO: Remove this after MemberCache fix
-                                       } else if (gfd.IsDefined (pa.Type, false)) {
-                                               var element_field = fi.FieldType.GetField (FixedField.FixedElementName);
-                                               return new FixedFieldSpec (definition, fi, element_field, mod);
-                                       }
+                       if (fi.FieldType.IsValueType) {
+                                if (fi.IsDefined (typeof (FixedBufferAttribute), false)) {
+                                       var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
+                                       return new FixedFieldSpec (declaringType, definition, fi, element_field, mod);
                                }
                        }
 
-                       // TODO: volatile
+                       // TODO: import volatile
 
-                       return new FieldSpec (definition, fi, mod);
+                       return new FieldSpec (declaringType, definition, ImportType (fi.FieldType), fi, mod);
                }
 
-               public static EventSpec CreateEvent (EventInfo ei)
+               public static EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
                {
-                       // TODO MemberCache: Remove
-                       var ef = TypeManager.GetEventField (ei);
-                       if (ef != null)
-                               return ef;
+                       add.IsAccessor = true;
+                       remove.IsAccessor = true;
 
-                       var add_accessor = CreateMethod (TypeManager.GetAddMethod (ei));
-                       var remove_accessor = CreateMethod (TypeManager.GetRemoveMethod (ei));
-
-                       if (add_accessor.Modifiers != remove_accessor.Modifiers)
+                       if (add.Modifiers != remove.Modifiers)
                                throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
 
                        var definition = new ImportedMemberDefinition (ei);
-                       return new EventSpec (definition, ei, add_accessor.Modifiers, add_accessor, remove_accessor) {
-                               EventType = ei.EventHandlerType
-                       };
+                       return new EventSpec (declaringType, definition, ImportType (ei.EventHandlerType), add.Modifiers, add, remove);
                }
 
-               public static MethodSpec CreateMethod (MethodBase mb)
+               static T[] CreateGenericParameters<T> (Type type, TypeSpec declaringType) where T : TypeSpec
                {
-                       // TODO MemberCache: Remove
-                       MethodCore mc = TypeManager.GetMethod (mb) as MethodCore;
-                       if (mc != null)
-                               return mc.Spec;
+                       Type[] tparams = type.GetGenericArguments ();
 
-                       Modifiers mod = 0;
-                       var ma = mb.Attributes;
-                       switch (ma & MethodAttributes.MemberAccessMask) {
-                               case MethodAttributes.Public:
-                                       mod = Modifiers.PUBLIC;
-                                       break;
-                               case MethodAttributes.Assembly:
-                                       mod = Modifiers.INTERNAL;
-                                       break;
-                               case MethodAttributes.Family:
-                                       mod = Modifiers.PROTECTED;
-                                       break;
-                               case MethodAttributes.FamORAssem:
-                                       mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
-                                       break;
-                               default:
-                                       mod = Modifiers.PRIVATE;
-                                       break;
-                       }
+                       int parent_owned_count;
+                       if (type.IsNested) {
+                               parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
 
-                       if ((ma & MethodAttributes.Static) != 0)
-                               mod |= Modifiers.STATIC;
-                       if ((ma & MethodAttributes.Virtual) != 0)
-                               mod |= Modifiers.VIRTUAL;
-                       if ((ma & MethodAttributes.Abstract) != 0)
-                               mod |= Modifiers.ABSTRACT;
-                       if ((ma & MethodAttributes.Final) != 0)
-                               mod |= Modifiers.SEALED;
+                               //
+                               // System.Reflection duplicates parent type parameters for each
+                               // nested type with slightly modified properties (eg. different owner)
+                               // This just makes things more complicated (think of cloned constraints)
+                               // therefore we remap any nested type owned by parent using `type_cache'
+                               // to the single TypeParameterSpec
+                               //
+                               if (declaringType != null && parent_owned_count > 0) {
+                                       int read_count = 0;
+                                       while (read_count != parent_owned_count) {
+                                               var tparams_count = declaringType.Arity;
+                                               if (tparams_count != 0) {
+                                                       var parent_tp = declaringType.MemberDefinition.TypeParameters;
+                                                       read_count += tparams_count;
+                                                       for (int i = 0; i < tparams_count; i++) {
+                                                               import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
+                                                       }
+                                               }
 
-                       IMemberDefinition definition;
-                       var gmd = mb as MethodInfo;
-                       if (gmd != null && gmd.IsGenericMethodDefinition) {
-                               definition = new ImportedGenericMethodDefinition (gmd);
-                       } else if (mb.IsGenericMethod) {        // TODO MemberCache: Remove me
-                               definition = new ImportedGenericMethodDefinition ((MethodInfo) TypeManager.DropGenericMethodArguments (mb));
+                                               declaringType = declaringType.DeclaringType;
+                                       }
+                               }                       
                        } else {
-                               definition = new ImportedMemberDefinition (mb);
+                               parent_owned_count = 0;
                        }
 
-                       // TODO MemberCache: Use AParametersCollection p = ParametersImported.Create (mb);
-                       AParametersCollection p = TypeManager.GetParameterData (mb);
+                       if (tparams.Length - parent_owned_count == 0)
+                               return null;
+
+                       return CreateGenericParameters<T> (parent_owned_count, tparams);
+               }
+
+               static T[] CreateGenericParameters<T> (int first, Type[] tparams) where T : TypeSpec
+               {
+                       var tspec = new T [tparams.Length - first];
+                       for (int pos = first; pos < tparams.Length; ++pos) {
+                               tspec [pos - first] = (T) CreateType (tparams [pos]);
+                       }
+
+                       return tspec;
+               }
+
+               public static MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
+               {
+                       Modifiers mod = ReadMethodModifiers (mb, declaringType);
+                       //if (declaringType.IsInterface) {
+                       //    mod = (mod & ~Modifiers.ABSTRACT) | Modifiers.VIRTUAL;
+                       //}
+
+                       bool is_generic;
+                       ImportedMethodDefinition definition;
+
+                       var parameters = ParametersImported.Create (declaringType, mb);
+
+                       if (mb.IsGenericMethod) {
+                               if (!mb.IsGenericMethodDefinition)
+                                       throw new NotSupportedException ("assert");
+
+                               var tparams = CreateGenericParameters<TypeParameterSpec>(0, mb.GetGenericArguments ());
+                               definition = new ImportedGenericMethodDefinition ((MethodInfo) mb, parameters, tparams);
+                               is_generic = true;
+                       } else {
+                               definition = new ImportedMethodDefinition (mb, parameters);
+                               is_generic = false;
+                       }
 
                        MemberKind kind;
-                       if (mb.IsConstructor) {
+                       TypeSpec returnType;
+                       if (mb.MemberType == MemberTypes.Constructor) {
                                kind = MemberKind.Constructor;
+                               returnType = TypeManager.void_type;
                        } else {
                                //
                                // Detect operators and destructors
@@ -182,85 +219,362 @@ namespace Mono.CSharp
                                string name = mb.Name;
                                kind = MemberKind.Method;
                                if (!mb.DeclaringType.IsInterface && name.Length > 6) {
-                                       if ((mod & Modifiers.STATIC) != 0 && name[2] == '_' && name[1] == 'p' && name[0] == 'o') {
-                                               var op_type = Operator.GetType (name);
-                                               if (op_type.HasValue) {
-                                                       kind = MemberKind.Operator;
+                                       if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
+                                               if (name[2] == '_' && name[1] == 'p' && name[0] == 'o') {
+                                                       var op_type = Operator.GetType (name);
+                                                       if (op_type.HasValue) {
+                                                               kind = MemberKind.Operator;
+                                                       }
                                                }
-                                       } else if (p.IsEmpty && (mod & Modifiers.STATIC) == 0 && name == Destructor.MetadataName) {
+                                       } else if (parameters.IsEmpty && name == Destructor.MetadataName) {
                                                kind = MemberKind.Destructor;
                                        }
                                }
+
+                               returnType = ImportType (((MethodInfo)mb).ReturnType);
                        }
-                               
-                       MethodSpec ms = new MethodSpec (kind, definition, mb, p, mod);
+
+                       MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, mb, parameters, mod);
+                       if (is_generic)
+                               ms.IsGeneric = true;
+
                        return ms;
                }
 
-               public static PropertySpec CreateProperty (PropertyInfo pi)
+               //
+               // Returns null when the property is not valid C# property
+               //
+               public static PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
                {
                        var definition = new ImportedMemberDefinition (pi);
-                       var mod = Modifiers.PRIVATE;    // TODO: modifiers
-                       return new PropertySpec (MemberKind.Property | MemberKind.Indexer, definition, pi, mod);
+
+                       Modifiers mod = 0;
+                       AParametersCollection param = null;
+                       TypeSpec type = null;
+                       if (get != null) {
+                               mod = get.Modifiers;
+                               param = get.Parameters;
+                               type = get.ReturnType;
+                       }
+
+                       bool is_valid_property = true;
+                       if (set != null) {
+                               if (set.ReturnType != TypeManager.void_type)
+                                       is_valid_property = false;
+
+                               var set_param_count = set.Parameters.Count - 1;
+                               if (set_param_count < 0)
+                                       is_valid_property = false;
+
+                               var data = new IParameterData [set_param_count];
+                               var types = new TypeSpec[set_param_count];
+                               for (int i = 0; i < set_param_count; ++i ) {
+                                       data[i] = set.Parameters.FixedParameters[i];
+                                       types[i] = set.Parameters.Types[i];
+                               }
+
+                               var set_param = new ParametersImported (data, types);
+                               var set_type = set.Parameters.Types[set_param_count];
+
+                               if (mod == 0) {
+                                       mod = set.Modifiers;
+                                       param = set_param;
+                                       type = set_type;
+                               } else {
+                                       if (set_param_count != get.Parameters.Count)
+                                               is_valid_property = false;
+
+                                       if (get.ReturnType != set_type)
+                                               is_valid_property = false;
+
+                                       // Possible custom accessor modifiers
+                                       if ((mod & ~Modifiers.AccessibilityMask) != (set.Modifiers & ~Modifiers.AccessibilityMask)) {
+                                               var get_acc = mod & Modifiers.AccessibilityMask;
+                                               if (get_acc != Modifiers.PUBLIC) {
+                                                       var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
+                                                       // If the accessor modifiers are not same, do extra restriction checks
+                                                       if (get_acc != set_acc) {
+                                                               var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
+                                                               var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
+                                                               if (get_restr && set_restr) {
+                                                                       is_valid_property = false; // Neither is more restrictive
+                                                               }
+
+                                                               if (set_restr) {
+                                                                       mod &= ~Modifiers.AccessibilityMask;
+                                                                       mod |= set_acc;
+                                                               }
+                                                       }
+                                               }
+                                       }
+                               }
+                       }
+
+                       PropertySpec spec = null;
+                       if (!param.IsEmpty) {
+                               var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
+                               if (index_name == null) {
+                                       is_valid_property = false;
+                               } else {
+                                       if (get != null) {
+                                               if (get.IsStatic)
+                                                       is_valid_property = false;
+                                               if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
+                                                       is_valid_property = false;
+                                       }
+                                       if (set != null) {
+                                               if (set.IsStatic)
+                                                       is_valid_property = false;
+                                               if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
+                                                       is_valid_property = false;
+                                       }
+                               }
+
+                               if (is_valid_property)
+                                       spec = new IndexerSpec (declaringType, definition, type, param, pi, mod);
+                       }
+
+                       if (spec == null)
+                               spec = new PropertySpec (MemberKind.Property, declaringType, definition, type, pi, mod);
+
+                       if (!is_valid_property) {
+                               spec.IsNotRealProperty = true;
+                               return spec;
+                       }
+
+                       if (set != null)
+                               spec.Set = set;
+                       if (get != null)
+                               spec.Get = get;
+
+                       return spec;
                }
 
-               static TypeSpec CreateType (Type type)
+               public static TypeSpec CreateType (Type type)
                {
-                       Modifiers mod = 0;
+                       return CreateType (type, null);
+               }
+
+               public static TypeSpec CreateType (Type type, TypeSpec declaringType)
+               {
+                       TypeSpec spec;
+                       if (import_cache.TryGetValue (type, out spec))
+                               return spec;
+
+                       if (type.IsGenericType && !type.IsGenericTypeDefinition) {      
+                               var type_def = type.GetGenericTypeDefinition ();
+                               spec = CreateType (type_def, declaringType);
+
+                               var targs = CreateGenericParameters<TypeSpec> (type, null);
+
+                               InflatedTypeSpec inflated;
+                               if (targs == null) {
+                                       // Inflating nested non-generic type, same in TypeSpec::InflateMember
+                                       inflated = new InflatedTypeSpec (spec, declaringType, TypeSpec.EmptyTypes);
+                               } else {
+                                       // CreateGenericParameters constraint could inflate type
+                                       if (import_cache.ContainsKey (type))
+                                               return import_cache[type];
+
+                                       inflated = spec.MakeGenericType (targs);
+
+                                       // Use of reading cache to speed up reading only
+                                       import_cache.Add (type, inflated);
+                               }
+
+                               return inflated;
+                       }
+
+                       Modifiers mod;
+                       MemberKind kind;
+
                        var ma = type.Attributes;
                        switch (ma & TypeAttributes.VisibilityMask) {
-                               case TypeAttributes.Public:
-                               case TypeAttributes.NestedPublic:
-                                       mod = Modifiers.PUBLIC;
-                                       break;
-                case TypeAttributes.NestedPrivate:
-                                       mod = Modifiers.PRIVATE;
-                                       break;
-                               case TypeAttributes.NestedFamily:
-                                       mod = Modifiers.PROTECTED;
-                                       break;
-                               case TypeAttributes.NestedFamORAssem:
-                                       mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
-                                       break;
-                               default:
-                                       mod = Modifiers.INTERNAL;
-                                       break;
+                       case TypeAttributes.Public:
+                       case TypeAttributes.NestedPublic:
+                               mod = Modifiers.PUBLIC;
+                               break;
+                       case TypeAttributes.NestedPrivate:
+                               mod = Modifiers.PRIVATE;
+                               break;
+                       case TypeAttributes.NestedFamily:
+                               mod = Modifiers.PROTECTED;
+                               break;
+                       case TypeAttributes.NestedFamORAssem:
+                               mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
+                               break;
+                       default:
+                               mod = Modifiers.INTERNAL;
+                               break;
                        }
 
-                       var type_def = TypeManager.DropGenericTypeArguments (type);
-
-                       MemberKind kind;
-                       if (type_def.IsInterface)
+                       if ((ma & TypeAttributes.Interface) != 0) {
                                kind = MemberKind.Interface;
-                       else if (type_def.IsEnum)
-                               kind = MemberKind.Enum;
-                       else if (type_def.IsClass) {
-                               if (type_def.BaseType == TypeManager.multicast_delegate_type)
+                       } else if (type.IsGenericParameter) {
+                               kind = MemberKind.TypeParameter;
+                       } else if (type.IsClass || type.IsAbstract) {                           // SRE: System.Enum returns false for IsClass
+                               if ((ma & TypeAttributes.Sealed) != 0 && type.IsSubclassOf (typeof (MulticastDelegate))) {
                                        kind = MemberKind.Delegate;
-                               else
+                               } else {
                                        kind = MemberKind.Class;
+
+                                       if (type == typeof (object)) {
+#if NET_4_0
+                                               var pa = PredefinedAttributes.Get.Dynamic.Type;
+                                               if (pa != null && type.IsDefined (typeof (DynamicAttribute), false))
+                                                       return InternalType.Dynamic;
+#endif
+                                       }
+
+                                       if ((ma & TypeAttributes.Sealed) != 0) {
+                                               mod |= Modifiers.SEALED;
+                                               if ((ma & TypeAttributes.Abstract) != 0)
+                                                       mod |= Modifiers.STATIC;
+                                       } else if ((ma & TypeAttributes.Abstract) != 0) {
+                                               mod |= Modifiers.ABSTRACT;
+                                       }
+                               }
+                       } else if (type.IsEnum) {
+                               kind = MemberKind.Enum;
                        } else {
                                kind = MemberKind.Struct;
+                               mod |= Modifiers.SEALED;
                        }
 
-                       if (type.IsGenericType) {
-                               throw new NotImplementedException ();
+                       var definition = new ImportedTypeDefinition (type);
+                       PredefinedTypeSpec pt;
+
+                       if (kind == MemberKind.Enum) {
+                               const BindingFlags any_member = BindingFlags.DeclaredOnly |
+                                       BindingFlags.Static | BindingFlags.Instance |
+                                       BindingFlags.Public | BindingFlags.NonPublic;
+
+                               var u_type = type.GetField (Enum.UnderlyingValueField, any_member);
+                               if (u_type != null) {
+                                       spec = new EnumSpec (declaringType, definition, Import.CreateType (u_type.FieldType), type, mod);
+                               }
+                       } else if (kind == MemberKind.TypeParameter) {
+                               // Return as type_cache was updated
+                               return CreateTypeParameter (type, declaringType);
+                       } else if (type.IsGenericTypeDefinition) {
+                               definition.TypeParameters = CreateGenericParameters<TypeParameterSpec>(type, declaringType);
+
+                               // Constraints are not loaded on demand and can reference this type
+                               if (import_cache.TryGetValue (type, out spec))
+                                       return spec;
+
+                       } else if (type_2_predefined.TryGetValue (type, out pt)) {
+                               spec = pt;
+                               pt.SetDefinition (definition, type);
                        }
 
-                       var definition = new ImportedTypeDefinition (type_def);
-                       var spec = new TypeSpec (kind, definition, type, type.Name, mod);
+                       if (spec == null)
+                               spec = new TypeSpec (kind, declaringType, definition, type, mod);
+
+                       import_cache.Add (type, spec);
 
-                       // TODO: BaseType for class only?
+                       if (kind == MemberKind.Interface)
+                               spec.BaseType = TypeManager.object_type;
+                       else if (type.BaseType != null)
+                               spec.BaseType = CreateType (type.BaseType);
+
+                       var ifaces = type.GetInterfaces ();
+                       if (ifaces.Length > 0) {
+                               foreach (Type iface in ifaces) {
+                                       spec.AddInterface (Import.CreateType (iface));
+                               }
+                       }
+
+                       return spec;
+               }
+
+               static TypeParameterSpec CreateTypeParameter (Type type, TypeSpec declaringType)
+               {
+                       Variance variance;
+                       switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
+                       case GenericParameterAttributes.Covariant:
+                               variance = Variance.Covariant;
+                               break;
+                       case GenericParameterAttributes.Contravariant:
+                               variance = Variance.Contravariant;
+                               break;
+                       default:
+                               variance = Variance.None;
+                               break;
+                       }
+
+                       SpecialConstraint special = SpecialConstraint.None;
+                       var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
+
+                       if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
+                               special |= SpecialConstraint.Struct;
+                       } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
+                               special = SpecialConstraint.Constructor;
+                       }
+
+                       if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
+                               special |= SpecialConstraint.Class;
+                       }
+
+                       TypeParameterSpec spec;
+                       var def = new ImportedTypeParameterDefinition (type);
+                       if (type.DeclaringMethod != null)
+                               spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
+                       else
+                               spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
+
+                       // Add it now, so any constraint can reference it and get same instance
+                       import_cache.Add (type, spec);
+
+                       var constraints = type.GetGenericParameterConstraints ();
+                       foreach (var ct in constraints) {
+                               // TODO MemberCache: What to do ??
+                               if (ct.IsGenericParameter) {
+                                       continue;
+                               }
+
+                               if (ct.IsClass) {
+                                       if (ct == typeof (ValueType)) {
+                                               spec.BaseType = TypeManager.value_type;
+                                       } else {
+                                               spec.BaseType = CreateType (ct);
+                                       }
+
+                                       continue;
+                               }
+
+                               spec.AddInterface (CreateType (ct));
+                       }
+
+                       if (spec.BaseType == null)
+                               spec.BaseType = TypeManager.object_type;
 
                        return spec;
                }
 
                public static TypeSpec ImportType (Type type)
                {
-                       if (type.IsDefined (typeof (CompilerGeneratedAttribute), false))
-                               return null;
+                       if (type.HasElementType) {
+                               var element = type.GetElementType ();
+                               var spec = ImportType (element);
+
+                               if (type.IsArray)
+                                       return ArrayContainer.MakeType (spec, type.GetArrayRank ());
+                               if (type.IsByRef)
+                                       return ReferenceContainer.MakeType (spec);
+                               if (type.IsPointer)
+                                       return PointerContainer.MakeType (spec);
+
+                               throw new NotImplementedException ("Unknown element type " + type.ToString ());
+                       }
+
+                       TypeSpec dtype;
+                       if (type.IsNested)
+                               dtype = ImportType (type.DeclaringType);
+                       else
+                               dtype = null;
 
-                       return CreateType (type);
+                       return CreateType (type, dtype);
                }
 
                //
@@ -270,34 +584,211 @@ namespace Mono.CSharp
                //
                static Constant ReadDecimalConstant (FieldInfo fi)
                {
-                       PredefinedAttribute pa = PredefinedAttributes.Get.DecimalConstant;
-                       if (!pa.IsDefined)
-                               return null;
-
-                       object[] attrs = fi.GetCustomAttributes (pa.Type, false);
+                       object[] attrs = fi.GetCustomAttributes (typeof (DecimalConstantAttribute), false);
                        if (attrs.Length != 1)
                                return null;
 
                        return new DecimalConstant (((DecimalConstantAttribute) attrs [0]).Value, Location.Null);
                }
+
+               static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
+               {
+                       Modifiers mod;
+                       var ma = mb.Attributes;
+                       switch (ma & MethodAttributes.MemberAccessMask) {
+                       case MethodAttributes.Public:
+                               mod = Modifiers.PUBLIC;
+                               break;
+                       case MethodAttributes.Assembly:
+                               mod = Modifiers.INTERNAL;
+                               break;
+                       case MethodAttributes.Family:
+                               mod = Modifiers.PROTECTED;
+                               break;
+                       case MethodAttributes.FamORAssem:
+                               mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
+                               break;
+                       default:
+                               mod = Modifiers.PRIVATE;
+                               break;
+                       }
+
+                       if ((ma & MethodAttributes.Static) != 0) {
+                               mod |= Modifiers.STATIC;
+                       } else if ((ma & MethodAttributes.Final) != 0) {
+                               mod |= Modifiers.SEALED;
+                       } else if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
+                               mod |= Modifiers.ABSTRACT;
+                       }
+
+                       // It can be sealed and override
+                       if ((ma & MethodAttributes.Virtual) != 0) {
+                               if ((ma & MethodAttributes.NewSlot) != 0 || !declaringType.IsClass || mod == Modifiers.PRIVATE) {
+                                       mod |= Modifiers.VIRTUAL;
+                               } else {
+                                       // Cannot set to OVERRIDE without full hierarchy checks
+                                       // this flag indicates that the method could be override
+                                       // but further validation is needed
+                                       mod |= Modifiers.OVERRIDE_UNCHECKED;
+                               }
+                       }
+
+                       return mod;
+               }
        }
 
        class ImportedMemberDefinition : IMemberDefinition
        {
-               protected readonly ICustomAttributeProvider provider;
+               protected class AttributesBag
+               {
+                       public static readonly AttributesBag Default = new AttributesBag ();
+
+                       public AttributeUsageAttribute AttributeUsage;
+                       public ObsoleteAttribute Obsolete;
+                       public string[] Conditionals;
+                       public string DefaultIndexerName;
+                       public bool IsNotCLSCompliant;
+
+                       public static AttributesBag Read (MemberInfo mi)
+                       {
+                               AttributesBag bag = null;
+                               List<string> conditionals = null;
+
+                               var attrs = CustomAttributeData.GetCustomAttributes (mi);
+                               foreach (var a in attrs) {
+                                       var type = a.Constructor.DeclaringType;
+                                       if (type == typeof (ObsoleteAttribute)) {
+                                               if (bag == null)
+                                                       bag = new AttributesBag ();
+
+                                               var args = a.ConstructorArguments;
+
+                                               if (args.Count == 1) {
+                                                       bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
+                                               } else if (args.Count == 2) {
+                                                       bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
+                                               } else {
+                                                       bag.Obsolete = new ObsoleteAttribute ();
+                                               }
+
+                                               continue;
+                                       }
+
+                                       if (type == typeof (ConditionalAttribute)) {
+                                               if (bag == null)
+                                                       bag = new AttributesBag ();
+
+                                               if (conditionals == null)
+                                                       conditionals = new List<string> (2);
+
+                                               conditionals.Add ((string) a.ConstructorArguments[0].Value);
+                                               continue;
+                                       }
+
+                                       if (type == typeof (CLSCompliantAttribute)) {
+                                               if (bag == null)
+                                                       bag = new AttributesBag ();
+
+                                               bag.IsNotCLSCompliant = !(bool) a.ConstructorArguments[0].Value;
+                                               continue;
+                                       }
+
+                                       // Type only attributes
+                                       if (type == typeof (DefaultMemberAttribute)) {
+                                               if (bag == null)
+                                                       bag = new AttributesBag ();
+
+                                               bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
+                                               continue;
+                                       }
+
+                                       if (type == typeof (AttributeUsageAttribute)) {
+                                               if (bag == null)
+                                                       bag = new AttributesBag ();
+
+                                               bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
+                                               foreach (var named in a.NamedArguments) {
+                                                       if (named.MemberInfo.Name == "AllowMultiple")
+                                                               bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
+                                                       else if (named.MemberInfo.Name == "Inherited")
+                                                               bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
+                                               }
+                                               continue;
+                                       }
+                               }
+
+                               if (bag == null)
+                                       return Default;
+
+                               if (conditionals != null)
+                                       bag.Conditionals = conditionals.ToArray ();
+
+                               return bag;
+                       }
+               }
+
+               protected readonly MemberInfo provider;
+               protected AttributesBag cattrs;
 
-               public ImportedMemberDefinition (ICustomAttributeProvider provider)
+               public ImportedMemberDefinition (MemberInfo provider)
                {
                        this.provider = provider;
                }
 
-               public ObsoleteAttribute GetObsoleteAttribute ()
+               #region Properties
+
+               public Assembly Assembly {
+                       get { 
+                               return provider.Module.Assembly;
+                       }
+               }
+
+               public bool IsImported {
+                       get {
+                               return true;
+                       }
+               }
+
+               public virtual string Name {
+                       get {
+                               return provider.Name;
+                       }
+               }
+
+               #endregion
+
+               public string[] ConditionalConditions ()
                {
-                       var res = provider.GetCustomAttributes (typeof (ObsoleteAttribute), false);
-                       if (res == null || res.Length < 1)
-                               return null;
+                       if (cattrs == null)
+                               ReadAttributes ();
 
-                       return res [0] as ObsoleteAttribute;
+                       return cattrs.Conditionals;
+               }
+
+               public ObsoleteAttribute GetAttributeObsolete ()
+               {
+                       if (cattrs == null)
+                               ReadAttributes ();
+
+                       return cattrs.Obsolete;
+               }
+
+               public bool IsNotCLSCompliant ()
+               {
+                       if (cattrs == null)
+                               ReadAttributes ();
+
+                       return cattrs.IsNotCLSCompliant;
+               }
+
+               protected void ReadAttributes ()
+               {
+                       cattrs = AttributesBag.Read (provider);
+               }
+
+               public void SetIsAssigned ()
+               {
+                       // Unused for imported members
                }
 
                public void SetIsUsed ()
@@ -306,27 +797,322 @@ namespace Mono.CSharp
                }
        }
 
-       class ImportedGenericMethodDefinition : ImportedMemberDefinition, IGenericMethodDefinition
+       class ImportedMethodDefinition : ImportedMemberDefinition, IParametersMember
        {
-               public ImportedGenericMethodDefinition (MethodInfo provider)
+               readonly AParametersCollection parameters;
+
+               public ImportedMethodDefinition (MethodBase provider, AParametersCollection parameters)
                        : base (provider)
                {
+                       this.parameters = parameters;
+               }
+
+               #region Properties
+
+               public AParametersCollection Parameters {
+                       get {
+                               return parameters;
+                       }
                }
 
-               public MethodInfo MakeGenericMethod (Type[] targs)
+               public TypeSpec MemberType {
+                       get {
+                               throw new NotImplementedException ();
+                       }
+               }
+
+               #endregion
+       }
+
+       class ImportedGenericMethodDefinition : ImportedMethodDefinition, IGenericMethodDefinition
+       {
+               TypeParameterSpec[] tparams;
+
+               public ImportedGenericMethodDefinition (MethodInfo provider, AParametersCollection parameters, TypeParameterSpec[] tparams)
+                       : base (provider, parameters)
                {
-                       return ((MethodInfo) provider).MakeGenericMethod (targs);
+                       this.tparams = tparams;
+               }
+
+               #region Properties
+
+               public TypeParameterSpec[] TypeParameters {
+                       get {
+                               return tparams;
+                       }
                }
+
+               public int TypeParametersCount {
+                       get {
+                               return tparams.Length;
+                       }
+               }
+
+               #endregion
        }
 
        class ImportedTypeDefinition : ImportedMemberDefinition, ITypeDefinition
        {
+               TypeParameterSpec[] tparams;
+               string name;
+
                public ImportedTypeDefinition (Type type)
                        : base (type)
                {
                }
 
-               public void LoadMembers (MemberCache cache)
+               #region Properties
+
+               public override string Name {
+                       get {
+                               if (name == null) {
+                                       name = base.Name;
+                                       if (tparams != null)
+                                               name = name.Substring (0, name.IndexOf ('`'));
+                               }
+
+                               return name;
+                       }
+               }
+
+               public string Namespace {
+                       get {
+                               return ((Type) provider).Namespace;
+                       }
+               }
+
+               public int TypeParametersCount {
+                       get {
+                               return tparams == null ? 0 : tparams.Length;
+                       }
+               }
+
+               public TypeParameterSpec[] TypeParameters {
+                       get {
+                               return tparams;
+                       }
+                       set {
+                               tparams = value;
+                       }
+               }
+
+               #endregion
+
+               public TypeSpec GetAttributeCoClass ()
+               {
+                       // TODO: Use ReadAttributes
+                       var attr =  provider.GetCustomAttributes (typeof (CoClassAttribute), false);
+                       if (attr.Length < 1)
+                               return null;
+
+                       return Import.CreateType (((CoClassAttribute) attr[0]).CoClass);
+               }
+
+               public string GetAttributeDefaultMember ()
+               {
+                       if (cattrs == null)
+                               ReadAttributes ();
+
+                       return cattrs.DefaultIndexerName;
+               }
+
+               public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
+               {
+                       if (cattrs == null)
+                               ReadAttributes ();
+
+                       return cattrs.AttributeUsage;
+               }
+
+               public MemberCache LoadMembers (TypeSpec declaringType)
+               {
+                       var loading_type = (Type) provider;
+                       const BindingFlags all_members = BindingFlags.DeclaredOnly |
+                               BindingFlags.Static | BindingFlags.Instance |
+                               BindingFlags.Public | BindingFlags.NonPublic;
+
+                       const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
+                                       MethodAttributes.Virtual | MethodAttributes.HideBySig |
+                                       MethodAttributes.Final | MethodAttributes.Private;
+
+                       Dictionary<MethodBase, MethodSpec> possible_accessors = null;
+                       MemberSpec imported;
+                       MethodInfo m;
+                       List<string> fields_to_ignore = null;
+
+                       //
+                       // This requires methods to be returned first which seems to work for both Mono and .NET
+                       //
+                       var all = loading_type.GetMembers (all_members);
+
+                       var cache = new MemberCache (all.Length);
+                       foreach (var member in all) {
+                               switch (member.MemberType) {
+                               case MemberTypes.Constructor:
+                               case MemberTypes.Method:
+                                       MethodBase mb = (MethodBase) member;
+
+                                       // Ignore explicitly implemented members
+                                       if ((mb.Attributes & explicit_impl) == explicit_impl)
+                                               continue;
+
+                                       // Ignore compiler generated methods
+                                       if (mb.IsPrivate && mb.IsDefined (typeof (CompilerGeneratedAttribute), false))
+                                               continue;
+
+                                       imported = Import.CreateMethod (mb, declaringType);
+                                       var name = imported.Name;
+                                       if (imported.Kind == MemberKind.Method && name.Length > 4) {
+                                               if ((name[3] == '_' && (name.StartsWith ("get", StringComparison.Ordinal) ||
+                                                        name.StartsWith ("set", StringComparison.Ordinal) || 
+                                                        name.StartsWith ("add", StringComparison.Ordinal))) ||
+                                                       name.Length > 7 && name[6] == '_' && name.StartsWith ("remove", StringComparison.Ordinal)) {
+
+                                                       if (possible_accessors == null)
+                                                               possible_accessors = new Dictionary<MethodBase, MethodSpec> ();
+
+                                                       possible_accessors.Add (mb, (MethodSpec) imported);
+                                               }
+                                       }
+
+                                       break;
+                               case MemberTypes.Property:
+                                       if (possible_accessors == null)
+                                               continue;
+
+                                       var p = (PropertyInfo) member;
+                                       //
+                                       // Links possible accessors with property
+                                       //
+                                       MethodSpec get, set;
+                                       m = p.GetGetMethod (true);
+                                       if (m == null || !possible_accessors.TryGetValue (m, out get))
+                                               get = null;
+
+                                       m = p.GetSetMethod (true);
+                                       if (m == null || !possible_accessors.TryGetValue (m, out set))
+                                               set = null;
+
+                                       // No accessors registered (e.g. explicit implementation)
+                                       if (get == null && set == null)
+                                               continue;
+
+                                       imported = Import.CreateProperty (p, declaringType, get, set);
+                                       if (imported == null)
+                                               continue;
+
+                                       break;
+                               case MemberTypes.Event:
+                                       if (possible_accessors == null)
+                                               continue;
+
+                                       var e = (EventInfo) member;
+                                       //
+                                       // Links accessors with event
+                                       //
+                                       MethodSpec add, remove;
+                                       m = e.GetAddMethod (true);
+                                       if (m == null || !possible_accessors.TryGetValue (m, out add))
+                                               add = null;
+
+                                       m = e.GetRemoveMethod (true);
+                                       if (m == null || !possible_accessors.TryGetValue (m, out remove))
+                                               remove = null;
+
+                                       // Both accessors are required
+                                       if (add == null || remove == null)
+                                               continue;
+
+                                       if (fields_to_ignore == null)
+                                               fields_to_ignore = new List<string> ();
+
+                                       fields_to_ignore.Add (e.Name);
+
+                                       imported = Import.CreateEvent (e, declaringType, add, remove);
+                                       break;
+                               case MemberTypes.Field:
+                                       var fi = (FieldInfo) member;
+
+                                       // Ignore compiler generated fields
+                                       if (fi.IsPrivate && fi.IsDefined (typeof (CompilerGeneratedAttribute), false))
+                                               continue;
+
+                                       if (fields_to_ignore != null && fields_to_ignore.Contains (fi.Name))
+                                               continue;
+
+                                       imported = Import.CreateField (fi, declaringType);
+                                       break;
+                               case MemberTypes.NestedType:
+                                       Type t = (Type) member;
+
+                                       // Ignore compiler generated types, mostly lambda containers
+                                       if (t.IsNotPublic && t.IsDefined (typeof (CompilerGeneratedAttribute), false))
+                                               continue;
+
+                                       imported = Import.CreateType (t, declaringType);
+                                       break;
+                               default:
+                                       throw new NotImplementedException (member.ToString ());
+                               }
+
+                               cache.AddMember (imported);
+                       }
+
+                       if (declaringType.IsInterface && declaringType.Interfaces != null) {
+                               foreach (var iface in declaringType.Interfaces) {
+                                       cache.AddInterface (iface);
+                               }
+                       }
+
+                       return cache;
+               }
+       }
+
+       class ImportedTypeParameterDefinition : ImportedMemberDefinition, ITypeDefinition
+       {
+               public ImportedTypeParameterDefinition (Type type)
+                       : base (type)
+               {
+               }
+
+               #region Properties
+
+               public string Namespace {
+                       get {
+                               return null;
+                       }
+               }
+
+               public int TypeParametersCount {
+                       get {
+                               return 0;
+                       }
+               }
+
+               public TypeParameterSpec[] TypeParameters {
+                       get {
+                               return null;
+                       }
+               }
+
+               #endregion
+
+               public TypeSpec GetAttributeCoClass ()
+               {
+                       return null;
+               }
+
+               public string GetAttributeDefaultMember ()
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
+               {
+                       throw new NotSupportedException ();
+               }
+
+               public MemberCache LoadMembers (TypeSpec declaringType)
                {
                        throw new NotImplementedException ();
                }
index 20d6741406bac6b9cae6b96914458872c908bfca..b25dff540fc03dbaa26a73ea14a188e70b2f2cc8 100644 (file)
@@ -49,11 +49,6 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       expr.MutateHoistedGenericType (storey);
-               }
-               
                public override bool Resolve (BlockContext ec)
                {
                        expr = expr.Resolve (ec);
@@ -120,12 +115,7 @@ namespace Mono.CSharp {
 
                protected override void DoEmit (EmitContext ec)
                {
-                       iterator.EmitYieldBreak (ec.ig, unwind_protect);
-               }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       // nothing to do
+                       iterator.EmitYieldBreak (ec, unwind_protect);
                }
        }
 
@@ -163,12 +153,6 @@ namespace Mono.CSharp {
                {
                        iterator.EmitMoveNext (ec, original_block);
                }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       original_block.MutateHoistedGenericType (storey);
-                       iterator.MutateHoistedGenericType (storey);
-               }
        }
 
        public class IteratorStorey : AnonymousMethodStorey
@@ -218,7 +202,7 @@ namespace Mono.CSharp {
 
                                public override bool Resolve (BlockContext ec)
                                {
-                                       TypeExpression storey_type_expr = new TypeExpression (host.TypeBuilder, loc);
+                                       TypeExpression storey_type_expr = new TypeExpression (host.Definition, loc);
                                        List<Expression> init = null;
                                        if (host.hoisted_this != null) {
                                                init = new List<Expression> (host.hoisted_params == null ? 1 : host.HoistedParameters.Count + 1);
@@ -255,11 +239,20 @@ namespace Mono.CSharp {
                                                new_storey = Convert.ImplicitConversionRequired (ec, new_storey, host_method.MemberType, loc);
 
                                        if (TypeManager.int_interlocked_compare_exchange == null) {
-                                               Type t = TypeManager.CoreLookupType (ec.Compiler, "System.Threading", "Interlocked", MemberKind.Class, true);
+                                               TypeSpec t = TypeManager.CoreLookupType (ec.Compiler, "System.Threading", "Interlocked", MemberKind.Class, true);
                                                if (t != null) {
-                                                       TypeManager.int_interlocked_compare_exchange = TypeManager.GetPredefinedMethod (
-                                                               t, "CompareExchange", loc, TypeManager.int32_type,
-                                                               TypeManager.int32_type, TypeManager.int32_type);
+                                                       var p = ParametersCompiled.CreateFullyResolved (
+                                                               new[] {
+                                                                       new ParameterData (null, Parameter.Modifier.REF),
+                                                                       new ParameterData (null, Parameter.Modifier.NONE),
+                                                                       new ParameterData (null, Parameter.Modifier.NONE)
+                                                               },
+                                                               new[] {
+                                                                       TypeManager.int32_type, TypeManager.int32_type, TypeManager.int32_type
+                                                               }
+                                                               );
+                                                       var f = new MemberFilter ("CompareExchange", 0, MemberKind.Method, p, TypeManager.int32_type);
+                                                       TypeManager.int_interlocked_compare_exchange = TypeManager.GetPredefinedMethod (t, f, loc);
                                                }
                                        }
 
@@ -269,30 +262,24 @@ namespace Mono.CSharp {
 
                                protected override void DoEmit (EmitContext ec)
                                {
-                                       ILGenerator ig = ec.ig;
-                                       Label label_init = ig.DefineLabel ();
+                                       Label label_init = ec.DefineLabel ();
 
-                                       ig.Emit (OpCodes.Ldarg_0);
-                                       ig.Emit (OpCodes.Ldflda, host.PC.Spec.MetaInfo);
-                                       IntConstant.EmitInt (ig, (int) Iterator.State.Start);
-                                       IntConstant.EmitInt (ig, (int) Iterator.State.Uninitialized);
-                                       ig.Emit (OpCodes.Call, (MethodInfo) TypeManager.int_interlocked_compare_exchange.MetaInfo);
+                                       ec.Emit (OpCodes.Ldarg_0);
+                                       ec.Emit (OpCodes.Ldflda, host.PC.Spec);
+                                       ec.EmitInt ((int) Iterator.State.Start);
+                                       ec.EmitInt ((int) Iterator.State.Uninitialized);
+                                       ec.Emit (OpCodes.Call, TypeManager.int_interlocked_compare_exchange);
 
-                                       IntConstant.EmitInt (ig, (int) Iterator.State.Uninitialized);
-                                       ig.Emit (OpCodes.Bne_Un_S, label_init);
+                                       ec.EmitInt ((int) Iterator.State.Uninitialized);
+                                       ec.Emit (OpCodes.Bne_Un_S, label_init);
 
-                                       ig.Emit (OpCodes.Ldarg_0);
-                                       ig.Emit (OpCodes.Ret);
+                                       ec.Emit (OpCodes.Ldarg_0);
+                                       ec.Emit (OpCodes.Ret);
 
-                                       ig.MarkLabel (label_init);
+                                       ec.MarkLabel (label_init);
 
                                        new_storey.Emit (ec);
-                                       ig.Emit (OpCodes.Ret);
-                               }
-
-                               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-                               {
-                                       throw new NotSupportedException ();
+                                       ec.Emit (OpCodes.Ret);
                                }
                        }
 
@@ -329,11 +316,6 @@ namespace Mono.CSharp {
                                {
                                        iterator.EmitDispose (ec);
                                }
-
-                               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-                               {
-                                       throw new NotSupportedException ();
-                               }
                        }
 
                        public DisposeMethod (IteratorStorey host)
@@ -362,8 +344,8 @@ namespace Mono.CSharp {
 
                        protected override Expression DoResolve (ResolveContext ec)
                        {
-                               Methods = new [] { method.Spec };
-                               type = method.Parent.TypeBuilder;
+                               Methods = new List<MemberSpec> (1) { method.Spec };
+                               type = method.Parent.Definition;
                                InstanceExpression = new CompilerGeneratedThis (type, Location);
                                return base.DoResolve (ec);
                        }
@@ -382,7 +364,7 @@ namespace Mono.CSharp {
                        protected override Expression DoResolve (ResolveContext ec)
                        {
                                spec = field.Spec;
-                               type = TypeManager.TypeToCoreType (spec.FieldType);
+                               type = spec.MemberType;
                                InstanceExpression = new CompilerGeneratedThis (type, Location);
                                return base.DoResolve (ec);
                        }
@@ -424,7 +406,11 @@ namespace Mono.CSharp {
 
                protected override TypeExpr [] ResolveBaseTypes (out TypeExpr base_class)
                {
-                       iterator_type_expr = new TypeExpression (MutateType (Iterator.OriginalIteratorType), Location);
+                       var mtype = Iterator.OriginalIteratorType;
+                       if (Mutator != null)
+                               mtype = Mutator.Mutate (mtype);
+
+                       iterator_type_expr = new TypeExpression (mtype, Location);
                        generic_args = new TypeArguments (iterator_type_expr);
 
                        var list = new List<FullNamedExpression> ();
@@ -464,7 +450,13 @@ namespace Mono.CSharp {
                        return "<" + local_info.Name + ">__" + local_name_idx++.ToString ();
                }
 
-               public void DefineIteratorMembers ()
+               protected override bool DoDefineMembers ()
+               {
+                       DefineIteratorMembers ();
+                       return base.DoDefineMembers ();
+               }
+
+               void DefineIteratorMembers ()
                {
                        pc_field = AddCompilerGeneratedField ("$PC", TypeManager.system_int32_expr);
                        current_field = AddCompilerGeneratedField ("$current", iterator_type_expr);
@@ -563,7 +555,7 @@ namespace Mono.CSharp {
 
                        reset.Block = new ToplevelBlock (Compiler, Location);
 
-                       Type ex_type = TypeManager.CoreLookupType (Compiler, "System", "NotSupportedException", MemberKind.Class, true);
+                       TypeSpec ex_type = TypeManager.CoreLookupType (Compiler, "System", "NotSupportedException", MemberKind.Class, true);
                        if (ex_type == null)
                                return;
 
@@ -603,7 +595,7 @@ namespace Mono.CSharp {
                        get { return OriginalMethod.GenericMethod; }
                }
 
-               public readonly Type OriginalIteratorType;
+               public readonly TypeSpec OriginalIteratorType;
 
                readonly IteratorStorey IteratorHost;
 
@@ -614,40 +606,36 @@ namespace Mono.CSharp {
                        Start = 0
                }
 
-               public void EmitYieldBreak (ILGenerator ig, bool unwind_protect)
+               public void EmitYieldBreak (EmitContext ec, bool unwind_protect)
                {
-                       ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
+                       ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
                }
 
                void EmitMoveNext_NoResumePoints (EmitContext ec, Block original_block)
                {
-                       ILGenerator ig = ec.ig;
-
-                       ig.Emit (OpCodes.Ldarg_0);
-                       ig.Emit (OpCodes.Ldfld, IteratorHost.PC.Spec.MetaInfo);
+                       ec.Emit (OpCodes.Ldarg_0);
+                       ec.Emit (OpCodes.Ldfld, IteratorHost.PC.Spec);
 
-                       ig.Emit (OpCodes.Ldarg_0);
-                       IntConstant.EmitInt (ig, (int) State.After);
-                       ig.Emit (OpCodes.Stfld, IteratorHost.PC.Spec.MetaInfo);
+                       ec.Emit (OpCodes.Ldarg_0);
+                       ec.EmitInt ((int) State.After);
+                       ec.Emit (OpCodes.Stfld, IteratorHost.PC.Spec);
 
                        // We only care if the PC is zero (start executing) or non-zero (don't do anything)
-                       ig.Emit (OpCodes.Brtrue, move_next_error);
+                       ec.Emit (OpCodes.Brtrue, move_next_error);
 
-                       SymbolWriter.StartIteratorBody (ec.ig);
+                       SymbolWriter.StartIteratorBody (ec);
                        original_block.Emit (ec);
-                       SymbolWriter.EndIteratorBody (ec.ig);
+                       SymbolWriter.EndIteratorBody (ec);
 
-                       ig.MarkLabel (move_next_error);
-                       ig.Emit (OpCodes.Ldc_I4_0);
-                       ig.Emit (OpCodes.Ret);
+                       ec.MarkLabel (move_next_error);
+                       ec.Emit (OpCodes.Ldc_I4_0);
+                       ec.Emit (OpCodes.Ret);
                }
 
                internal void EmitMoveNext (EmitContext ec, Block original_block)
                {
-                       ILGenerator ig = ec.ig;
-
-                       move_next_ok = ig.DefineLabel ();
-                       move_next_error = ig.DefineLabel ();
+                       move_next_ok = ec.DefineLabel ();
+                       move_next_error = ec.DefineLabel ();
 
                        if (resume_points == null) {
                                EmitMoveNext_NoResumePoints (ec, original_block);
@@ -655,17 +643,17 @@ namespace Mono.CSharp {
                        }
 
                        current_pc = ec.GetTemporaryLocal (TypeManager.uint32_type);
-                       ig.Emit (OpCodes.Ldarg_0);
-                       ig.Emit (OpCodes.Ldfld, IteratorHost.PC.Spec.MetaInfo);
-                       ig.Emit (OpCodes.Stloc, current_pc);
+                       ec.Emit (OpCodes.Ldarg_0);
+                       ec.Emit (OpCodes.Ldfld, IteratorHost.PC.Spec);
+                       ec.Emit (OpCodes.Stloc, current_pc);
 
                        // We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
-                       ig.Emit (OpCodes.Ldarg_0);
-                       IntConstant.EmitInt (ig, (int) State.After);
-                       ig.Emit (OpCodes.Stfld, IteratorHost.PC.Spec.MetaInfo);
+                       ec.Emit (OpCodes.Ldarg_0);
+                       ec.EmitInt ((int) State.After);
+                       ec.Emit (OpCodes.Stfld, IteratorHost.PC.Spec);
 
                        Label [] labels = new Label [1 + resume_points.Count];
-                       labels [0] = ig.DefineLabel ();
+                       labels [0] = ec.DefineLabel ();
 
                        bool need_skip_finally = false;
                        for (int i = 0; i < resume_points.Count; ++i) {
@@ -676,45 +664,43 @@ namespace Mono.CSharp {
 
                        if (need_skip_finally) {
                                skip_finally = ec.GetTemporaryLocal (TypeManager.bool_type);
-                               ig.Emit (OpCodes.Ldc_I4_0);
-                               ig.Emit (OpCodes.Stloc, skip_finally);
+                               ec.Emit (OpCodes.Ldc_I4_0);
+                               ec.Emit (OpCodes.Stloc, skip_finally);
                        }
 
-                       SymbolWriter.StartIteratorDispatcher (ec.ig);
-                       ig.Emit (OpCodes.Ldloc, current_pc);
-                       ig.Emit (OpCodes.Switch, labels);
+                       SymbolWriter.StartIteratorDispatcher (ec);
+                       ec.Emit (OpCodes.Ldloc, current_pc);
+                       ec.Emit (OpCodes.Switch, labels);
 
-                       ig.Emit (OpCodes.Br, move_next_error);
-                       SymbolWriter.EndIteratorDispatcher (ec.ig);
+                       ec.Emit (OpCodes.Br, move_next_error);
+                       SymbolWriter.EndIteratorDispatcher (ec);
 
-                       ig.MarkLabel (labels [0]);
+                       ec.MarkLabel (labels [0]);
 
-                       SymbolWriter.StartIteratorBody (ec.ig);
+                       SymbolWriter.StartIteratorBody (ec);
                        original_block.Emit (ec);
-                       SymbolWriter.EndIteratorBody (ec.ig);
+                       SymbolWriter.EndIteratorBody (ec);
 
-                       SymbolWriter.StartIteratorDispatcher (ec.ig);
+                       SymbolWriter.StartIteratorDispatcher (ec);
 
-                       ig.Emit (OpCodes.Ldarg_0);
-                       IntConstant.EmitInt (ig, (int) State.After);
-                       ig.Emit (OpCodes.Stfld, IteratorHost.PC.Spec.MetaInfo);
+                       ec.Emit (OpCodes.Ldarg_0);
+                       ec.EmitInt ((int) State.After);
+                       ec.Emit (OpCodes.Stfld, IteratorHost.PC.Spec);
 
-                       ig.MarkLabel (move_next_error);
-                       ig.Emit (OpCodes.Ldc_I4_0);
-                       ig.Emit (OpCodes.Ret);
+                       ec.MarkLabel (move_next_error);
+                       ec.EmitInt (0);
+                       ec.Emit (OpCodes.Ret);
 
-                       ig.MarkLabel (move_next_ok);
-                       ig.Emit (OpCodes.Ldc_I4_1);
-                       ig.Emit (OpCodes.Ret);
+                       ec.MarkLabel (move_next_ok);
+                       ec.Emit (OpCodes.Ldc_I4_1);
+                       ec.Emit (OpCodes.Ret);
 
-                       SymbolWriter.EndIteratorDispatcher (ec.ig);
+                       SymbolWriter.EndIteratorDispatcher (ec);
                }
 
                public void EmitDispose (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-
-                       Label end = ig.DefineLabel ();
+                       Label end = ec.DefineLabel ();
 
                        Label [] labels = null;
                        int n_resume_points = resume_points == null ? 0 : resume_points.Count;
@@ -733,26 +719,26 @@ namespace Mono.CSharp {
 
                        if (labels != null) {
                                current_pc = ec.GetTemporaryLocal (TypeManager.uint32_type);
-                               ig.Emit (OpCodes.Ldarg_0);
-                               ig.Emit (OpCodes.Ldfld, IteratorHost.PC.Spec.MetaInfo);
-                               ig.Emit (OpCodes.Stloc, current_pc);
+                               ec.Emit (OpCodes.Ldarg_0);
+                               ec.Emit (OpCodes.Ldfld, IteratorHost.PC.Spec);
+                               ec.Emit (OpCodes.Stloc, current_pc);
                        }
 
-                       ig.Emit (OpCodes.Ldarg_0);
-                       IntConstant.EmitInt (ig, (int) State.After);
-                       ig.Emit (OpCodes.Stfld, IteratorHost.PC.Spec.MetaInfo);
+                       ec.Emit (OpCodes.Ldarg_0);
+                       ec.EmitInt ((int) State.After);
+                       ec.Emit (OpCodes.Stfld, IteratorHost.PC.Spec);
 
                        if (labels != null) {
                                //SymbolWriter.StartIteratorDispatcher (ec.ig);
-                               ig.Emit (OpCodes.Ldloc, current_pc);
-                               ig.Emit (OpCodes.Switch, labels);
+                               ec.Emit (OpCodes.Ldloc, current_pc);
+                               ec.Emit (OpCodes.Switch, labels);
                                //SymbolWriter.EndIteratorDispatcher (ec.ig);
 
                                foreach (ResumableStatement s in resume_points)
                                        s.EmitForDispose (ec, this, end, true);
                        }
 
-                       ig.MarkLabel (end);
+                       ec.MarkLabel (end);
                }
 
                public int AddResumePoint (ResumableStatement stmt)
@@ -769,28 +755,26 @@ namespace Mono.CSharp {
                //
                public void MarkYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
                {
-                       ILGenerator ig = ec.ig;
-
                        // Store the new current
-                       ig.Emit (OpCodes.Ldarg_0);
+                       ec.Emit (OpCodes.Ldarg_0);
                        expr.Emit (ec);
-                       ig.Emit (OpCodes.Stfld, IteratorHost.CurrentField.Spec.MetaInfo);
+                       ec.Emit (OpCodes.Stfld, IteratorHost.CurrentField.Spec);
 
                        // store resume program-counter
-                       ig.Emit (OpCodes.Ldarg_0);
-                       IntConstant.EmitInt (ig, resume_pc);
-                       ig.Emit (OpCodes.Stfld, IteratorHost.PC.Spec.MetaInfo);
+                       ec.Emit (OpCodes.Ldarg_0);
+                       ec.EmitInt (resume_pc);
+                       ec.Emit (OpCodes.Stfld, IteratorHost.PC.Spec);
 
                        // mark finally blocks as disabled
                        if (unwind_protect && skip_finally != null) {
-                               ig.Emit (OpCodes.Ldc_I4_1);
-                               ig.Emit (OpCodes.Stloc, skip_finally);
+                               ec.EmitInt (1);
+                               ec.Emit (OpCodes.Stloc, skip_finally);
                        }
 
                        // Return ok
-                       ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
+                       ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
 
-                       ig.MarkLabel (resume_point);
+                       ec.MarkLabel (resume_point);
                }
 
                public override string ContainerType {
@@ -808,7 +792,7 @@ namespace Mono.CSharp {
                //
                // Our constructor
                //
-               private Iterator (CompilerContext ctx, IMethodData method, TypeContainer host, Type iterator_type, bool is_enumerable)
+               private Iterator (CompilerContext ctx, IMethodData method, TypeContainer host, TypeSpec iterator_type, bool is_enumerable)
                        : base (
                                new ToplevelBlock (ctx, method.Block, ParametersCompiled.EmptyReadOnlyParameters, method.Block.StartLocation),
                                TypeManager.bool_type,
@@ -839,8 +823,6 @@ namespace Mono.CSharp {
                        if (Compatible (ec) == null)
                                return null;
 
-                       IteratorHost.DefineIteratorMembers ();
-
                        eclass = ExprClass.Value;
                        return this;
                }
@@ -856,15 +838,15 @@ namespace Mono.CSharp {
                        // Initialize iterator PC when it's unitialized
                        //
                        if (IsEnumerable) {
-                               ILGenerator ig = ec.ig;
-                               ig.Emit (OpCodes.Dup);
-                               IntConstant.EmitInt (ig, (int)State.Uninitialized);
+                               ec.Emit (OpCodes.Dup);
+                               ec.EmitInt ((int)State.Uninitialized);
 
-                               FieldInfo field = IteratorHost.PC.Spec.MetaInfo;
-                               if (Storey.MemberName.IsGeneric)
-                                       field = TypeBuilder.GetField (Storey.Instance.Type, field);
+                               var field = IteratorHost.PC.Spec;
+                               if (Storey.MemberName.IsGeneric) {
+                                       field = MemberCache.GetMember (Storey.Instance.Type, field);
+                               }
 
-                               ig.Emit (OpCodes.Stfld, field);
+                               ec.Emit (OpCodes.Stfld, field);
                        }
                }
 
@@ -876,9 +858,9 @@ namespace Mono.CSharp {
                public static void CreateIterator (IMethodData method, TypeContainer parent, Modifiers modifiers, CompilerContext ctx)
                {
                        bool is_enumerable;
-                       Type iterator_type;
+                       TypeSpec iterator_type;
 
-                       Type ret = method.ReturnType;
+                       TypeSpec ret = method.ReturnType;
                        if (ret == null)
                                return;
 
@@ -920,11 +902,11 @@ namespace Mono.CSharp {
                                return;
                        }
 
-                       Iterator iter = new Iterator (ctx, method, parent, iterator_type, is_enumerable);
-                       iter.Storey.DefineType ();
+                       // TODO: Ugly leftover
+                       new Iterator (ctx, method, parent, iterator_type, is_enumerable);
                }
 
-               static bool CheckType (Type ret, out Type original_iterator_type, out bool is_enumerable)
+               static bool CheckType (TypeSpec ret, out TypeSpec original_iterator_type, out bool is_enumerable)
                {
                        original_iterator_type = null;
                        is_enumerable = false;
@@ -940,22 +922,19 @@ namespace Mono.CSharp {
                                return true;
                        }
 
-                       if (!TypeManager.IsGenericType (ret))
-                               return false;
-
-                       Type[] args = TypeManager.GetTypeArguments (ret);
-                       if (args.Length != 1)
+                       InflatedTypeSpec inflated = ret as InflatedTypeSpec;
+                       if (inflated == null)
                                return false;
 
-                       Type gt = TypeManager.DropGenericTypeArguments (ret);
-                       if (gt == TypeManager.generic_ienumerable_type) {
-                               original_iterator_type = TypeManager.TypeToCoreType (args [0]);
+                       ret = inflated.GetDefinition ();
+                       if (ret == TypeManager.generic_ienumerable_type) {
+                               original_iterator_type = inflated.TypeArguments[0];
                                is_enumerable = true;
                                return true;
                        }
                        
-                       if (gt == TypeManager.generic_ienumerator_type) {
-                               original_iterator_type = TypeManager.TypeToCoreType (args [0]);
+                       if (ret == TypeManager.generic_ienumerator_type) {
+                               original_iterator_type = inflated.TypeArguments[0];
                                is_enumerable = false;
                                return true;
                        }
index 4289814fb92bd7048d0281bc80f91bdd7ccb0031..eb4907b1816bd663a7df3120411ff50119a3f3ca 100644 (file)
@@ -26,7 +26,7 @@ namespace Mono.CSharp {
                {
                }
 
-               protected override Expression CreateExpressionTree (ResolveContext ec, Type delegate_type)
+               protected override Expression CreateExpressionTree (ResolveContext ec, TypeSpec delegate_type)
                {
                        if (ec.IsInProbingMode)
                                return this;
@@ -54,12 +54,12 @@ namespace Mono.CSharp {
                        }
                }
 
-               protected override ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, Type delegateType)
+               protected override ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegateType)
                {
-                       if (!TypeManager.IsDelegateType (delegateType))
+                       if (!delegateType.IsDelegate)
                                return null;
 
-                       AParametersCollection d_params = TypeManager.GetDelegateParameters (ec, delegateType);
+                       AParametersCollection d_params = Delegate.GetParameters (ec.Compiler, delegateType);
 
                        if (HasExplicitParameters) {
                                if (!VerifyExplicitParameters (ec, delegateType, d_params))
@@ -75,19 +75,14 @@ namespace Mono.CSharp {
                        if (!VerifyParameterCompatibility (ec, delegateType, d_params, ec.IsInProbingMode))
                                return null;
 
-                       Type [] ptypes = new Type [Parameters.Count];
+                       TypeSpec [] ptypes = new TypeSpec [Parameters.Count];
                        for (int i = 0; i < d_params.Count; i++) {
                                // D has no ref or out parameters
                                if ((d_params.FixedParameters [i].ModFlags & Parameter.Modifier.ISBYREF) != 0)
                                        return null;
 
-                               Type d_param = d_params.Types [i];
+                               TypeSpec d_param = d_params.Types [i];
 
-#if MS_COMPATIBLE
-                               // Blablabla, because reflection does not work with dynamic types
-                               if (d_param.IsGenericParameter)
-                                       d_param = delegateType.GetGenericArguments () [d_param.GenericParameterPosition];
-#endif
                                //
                                // When type inference context exists try to apply inferred type arguments
                                //
@@ -96,7 +91,9 @@ namespace Mono.CSharp {
                                }
 
                                ptypes [i] = d_param;
-                               ((ImplicitLambdaParameter) Parameters.FixedParameters [i]).Type = d_param;
+                               ImplicitLambdaParameter ilp = (ImplicitLambdaParameter) Parameters.FixedParameters [i];
+                               ilp.Type = d_param;
+                               ilp.Resolve (null, i);
                        }
 
                        Parameters.Types = ptypes;
@@ -118,7 +115,7 @@ namespace Mono.CSharp {
                        return this;
                }
 
-               protected override AnonymousMethodBody CompatibleMethodFactory (Type returnType, Type delegateType, ParametersCompiled p, ToplevelBlock b)
+               protected override AnonymousMethodBody CompatibleMethodFactory (TypeSpec returnType, TypeSpec delegateType, ParametersCompiled p, ToplevelBlock b)
                {
                        return new LambdaMethod (p, b, returnType, delegateType, loc);
                }
@@ -132,7 +129,7 @@ namespace Mono.CSharp {
        public class LambdaMethod : AnonymousMethodBody
        {
                public LambdaMethod (ParametersCompiled parameters,
-                                       ToplevelBlock block, Type return_type, Type delegate_type,
+                                       ToplevelBlock block, TypeSpec return_type, TypeSpec delegate_type,
                                        Location loc)
                        : base (parameters, block, return_type, delegate_type, loc)
                {
@@ -189,7 +186,7 @@ namespace Mono.CSharp {
                {
                        if (statement != null) {
                                statement.EmitStatement (ec);
-                               ec.ig.Emit (OpCodes.Ret);
+                               ec.Emit (OpCodes.Ret);
                                return;
                        }
 
index 2932b650646114ce1122a6e1431730b7a79cd1fa..420dae4bf832e7c4fcc18125e7c51c3f31bb855b 100644 (file)
@@ -70,8 +70,8 @@ namespace Mono.CSharp.Linq
                        {
                        }
 
-                       protected override Expression Error_MemberLookupFailed (ResolveContext ec, Type container_type, Type qualifier_type,
-                               Type queried_type, string name, string class_name, MemberTypes mt, BindingFlags bf)
+                       protected override Expression Error_MemberLookupFailed (ResolveContext ec, TypeSpec container_type, TypeSpec qualifier_type,
+                               TypeSpec queried_type, string name, int arity, string class_name, MemberKind mt, BindingRestriction bf)
                        {
                                ec.Report.Error (1935, loc, "An implementation of `{0}' query expression pattern could not be found. " +
                                        "Are you missing `System.Linq' using directive or `System.Core.dll' assembly reference?",
@@ -96,8 +96,8 @@ namespace Mono.CSharp.Linq
 
                        public bool AmbiguousCall (ResolveContext ec, MethodSpec ambiguous)
                        {
-                               ec.Report.SymbolRelatedToPreviousError (mg.BestCandidate.MetaInfo);
-                               ec.Report.SymbolRelatedToPreviousError (ambiguous.MetaInfo);
+                               ec.Report.SymbolRelatedToPreviousError (mg.BestCandidate);
+                               ec.Report.SymbolRelatedToPreviousError (ambiguous);
                                ec.Report.Error (1940, loc, "Ambiguous implementation of the query pattern `{0}' for source type `{1}'",
                                        mg.Name, mg.InstanceExpression.GetSignatureForError ());
                                return true;
@@ -106,15 +106,15 @@ namespace Mono.CSharp.Linq
                        public bool NoExactMatch (ResolveContext ec, MethodSpec method)
                        {
                                var pd = method.Parameters;
-                               Type source_type = pd.ExtensionMethodType;
+                               TypeSpec source_type = pd.ExtensionMethodType;
                                if (source_type != null) {
                                        Argument a = arguments [0];
 
                                        if (TypeManager.IsGenericType (source_type) && TypeManager.ContainsGenericParameters (source_type)) {
-                                               TypeInferenceContext tic = new TypeInferenceContext (TypeManager.GetTypeArguments (source_type));
+                                               TypeInferenceContext tic = new TypeInferenceContext (source_type.TypeArguments);
                                                tic.OutputTypeInference (ec, a.Expr, source_type);
                                                if (tic.FixAllTypes (ec)) {
-                                                       source_type = TypeManager.DropGenericTypeArguments (source_type).MakeGenericType (tic.InferredTypeArguments);
+                                                       source_type = source_type.GetDefinition ().MakeGenericType (tic.InferredTypeArguments);
                                                }
                                        }
 
@@ -125,7 +125,7 @@ namespace Mono.CSharp.Linq
                                        }
                                }
 
-                               if (!method.IsGenericMethod)
+                               if (!method.IsGeneric)
                                        return false;
 
                                if (mg.Name == "SelectMany") {
@@ -251,12 +251,12 @@ namespace Mono.CSharp.Linq
                {
                }
 
-               protected static Expression CreateRangeVariableType (ToplevelBlock block, IMemberContext context, SimpleMemberName name, Expression init)
+               protected static Expression CreateRangeVariableType (ToplevelBlock block, TypeContainer container, SimpleMemberName name, Expression init)
                {
                        var args = new List<AnonymousTypeParameter> (2);
                        args.Add (new AnonymousTypeParameter (block.Parameters [0]));
                        args.Add (new RangeAnonymousTypeParameter (init, name));
-                       return new NewAnonymousType (args, context.CurrentTypeDefinition, name.Location);
+                       return new NewAnonymousType (args, container, name.Location);
                }
        }
 
@@ -273,7 +273,7 @@ namespace Mono.CSharp.Linq
                        if (expr == null)
                                return null;
 
-                       if (TypeManager.IsDynamicType (expr.Type) || expr.Type == TypeManager.void_type) {
+                       if (expr.Type == InternalType.Dynamic || expr.Type == TypeManager.void_type) {
                                ec.Report.Error (1979, expr.Location,
                                        "Query expression with a source or join sequence of type `{0}' is not allowed",
                                        TypeManager.CSharpName (expr.Type));
@@ -400,7 +400,7 @@ namespace Mono.CSharp.Linq
                                result_selector_expr = next.Expr;
                                next = next.next;
                        } else {
-                               result_selector_expr = CreateRangeVariableType (block, ec.MemberContext, into_variable,
+                               result_selector_expr = CreateRangeVariableType (block, ec.MemberContext.CurrentMemberDefinition.Parent, into_variable,
                                        new SimpleName (into_variable.Value, into_variable.Location));
                        }
 
@@ -510,7 +510,7 @@ namespace Mono.CSharp.Linq
                                result_selector_expr = next.Expr;
                                next = next.next;
                        } else {
-                               result_selector_expr = CreateRangeVariableType (block, ec.MemberContext, lt, new SimpleName (lt.Value, lt.Location));
+                               result_selector_expr = CreateRangeVariableType (block, ec.MemberContext.CurrentMemberDefinition.Parent, lt, new SimpleName (lt.Value, lt.Location));
                        }
 
                        LambdaExpression result_selector = new LambdaExpression (lt.Location);
@@ -609,7 +609,7 @@ namespace Mono.CSharp.Linq
                                Identifier = identifier.Value;
                        }
 
-                       public static void Reset ()
+                       public new static void Reset ()
                        {
                                Counter = 0;
                        }
index f371812c6268f0a5fba0704f4aed6a06d7d4a44b..7b1243f1112b22b09d63ff8b6ee18baadbfbaa6b 100644 (file)
@@ -36,7 +36,7 @@ namespace Mono.CSharp {
                // Default type of null is an object
                //
                public NullLiteral (Location loc)
-                       : base (typeof (NullLiteral), loc)
+                       : base (InternalType.Null, loc)
                {
                }
 
@@ -48,9 +48,9 @@ namespace Mono.CSharp {
                        return CreateExpressionFactoryCall (ec, "Constant", args);
                }               
 
-               public override void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, Type t, bool expl)
+               public override void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, TypeSpec t, bool expl)
                {
-                       if (TypeManager.IsGenericParameter (t)) {
+                       if (t.IsGenericParameter) {
                                ec.Report.Error(403, loc,
                                        "Cannot convert null to the type parameter `{0}' because it could be a value " +
                                        "type. Consider using `default ({0})' instead", t.Name);
@@ -66,7 +66,7 @@ namespace Mono.CSharp {
                        base.Error_ValueCannotBeConverted (ec, loc, t, expl);
                }
 
-               public override Constant ConvertImplicitly (ResolveContext rc, Type targetType)
+               public override Constant ConvertImplicitly (ResolveContext rc, TypeSpec targetType)
                {
                        //
                        // Null literal is of object type
@@ -99,13 +99,11 @@ namespace Mono.CSharp {
 
                public override void Emit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-                               
                        //
                        // Emits null pointer
                        //
-                       ig.Emit (OpCodes.Ldc_I4_0);
-                       ig.Emit (OpCodes.Conv_U);
+                       ec.Emit (OpCodes.Ldc_I4_0);
+                       ec.Emit (OpCodes.Conv_U);
                }
        }
 
@@ -134,13 +132,13 @@ namespace Mono.CSharp {
                {
                }
 
-               public override Constant ConvertImplicitly (ResolveContext rc, Type type)
+               public override Constant ConvertImplicitly (ResolveContext rc, TypeSpec type)
                {
                        //
                        // The 0 literal can be converted to an enum value
                        //
                        if (Value == 0 && TypeManager.IsEnumType (type)) {
-                               Constant c = ConvertImplicitly (rc, TypeManager.GetEnumUnderlyingType (type));
+                               Constant c = ConvertImplicitly (rc, EnumSpec.GetUnderlyingType (type));
                                if (c == null)
                                        return null;
 
@@ -202,7 +200,7 @@ namespace Mono.CSharp {
                {
                }
 
-               public override void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, Type target, bool expl)
+               public override void Error_ValueCannotBeConverted (ResolveContext ec, Location loc, TypeSpec target, bool expl)
                {
                        if (target == TypeManager.float_type) {
                                Error_664 (ec, loc, "float", "f");
index 9e22cdf99d1fa86d6ffcbbfaedb63fb4dedad2f1..22cff126c0c5dc7cc75b0e984b0da9e99b352aa3 100644 (file)
@@ -17,6 +17,7 @@ using System.Collections.Generic;
 using System.Globalization;
 using System.Reflection.Emit;
 using System.Reflection;
+using System.Linq;
 
 namespace Mono.CSharp {
 
@@ -31,17 +32,21 @@ namespace Mono.CSharp {
                Indexer = 1 << 5,
                Operator = 1 << 6,
                Destructor      = 1 << 7,
-               //Constant = 1 << 8,
-
-               NestedType      = 1 << 10,
 
                Class           = 1 << 11,
                Struct          = 1 << 12,
                Delegate        = 1 << 13,
                Enum            = 1 << 14,
                Interface       = 1 << 15,
+               TypeParameter = 1 << 16,
+
+               PointerType = 1 << 20,
+               InternalCompilerType = 1 << 21,
+               FakeMethod = 1 << 22,
 
-               MaskType = Constructor | Event | Field | Method | Property | NestedType | Indexer | Operator | Destructor,
+               NestedMask = Class | Struct | Delegate | Enum | Interface,
+               GenericMask = Method | Class | Struct | Delegate | Interface,
+               MaskType = Constructor | Event | Field | Method | Property | Indexer | Operator | Destructor | NestedMask,
                All = MaskType
        }
 
@@ -56,1332 +61,1122 @@ namespace Mono.CSharp {
                // Inspect only queried type members
                DeclaredOnly = 1 << 1,
 
-               // Excluded static
+               // Exclude static
                InstanceOnly = 1 << 2,
 
-               // 
-               NoOverloadableOverrides = 1 << 3
+               // Ignore member overrides
+               NoOverrides     = 1 << 3
        }
-/*
-       public struct MemberFilter : IEquatable<MemberCore>
+
+       public struct MemberFilter : IEquatable<MemberSpec>
        {
                public readonly string Name;
                public readonly MemberKind Kind;
-               public readonly TypeSpec[] Parameters;
+               public readonly AParametersCollection Parameters;
                public readonly TypeSpec MemberType;
 
-               public MemberFilter (IMethod m)
-               {
-                       Name = m.MethodBuilder.Name;
-                       Kind = MemberKind.Method;
-                       Parameters = m.Parameters.Types;
-                       MemberType = m.ReturnType;
-               }
+               int arity; // -1 to ignore the check
+               TypeSpec invocation_type;
 
-               public MemberFilter (string name, MemberKind kind)
+               private MemberFilter (string name, MemberKind kind)
                {
                        Name = name;
                        Kind = kind;
                        Parameters = null;
                        MemberType = null;
+                       arity = -1;
+                       invocation_type = null;
+               }
+
+               public MemberFilter (MethodSpec m)
+               {
+                       Name = m.Name;
+                       Kind = MemberKind.Method;
+                       Parameters = m.Parameters;
+                       MemberType = m.ReturnType;
+                       arity = m.Arity;
+                       invocation_type = null;
                }
 
-               public MemberFilter (string name, MemberKind kind, TypeSpec[] param, TypeSpec type)
-                       : this (name, kind)
+               public MemberFilter (string name, int arity, MemberKind kind, AParametersCollection param, TypeSpec type)
                {
                        Name = name;
                        Kind = kind;
                        Parameters = param;
                        MemberType = type;
+                       this.arity = arity;
+                       invocation_type = null;
                }
 
-               public static MemberFilter Constuctor (TypeSpec[] param)
+               public TypeSpec InvocationType {
+                       get {
+                               return invocation_type;
+                       }
+                       set {
+                               invocation_type = value;
+                       }
+               }
+
+               public static MemberFilter Constructor (AParametersCollection param)
                {
-                       return new MemberFilter (System.Reflection.ConstructorInfo.ConstructorName, MemberKind.Constructor, param, null);
+                       return new MemberFilter (System.Reflection.ConstructorInfo.ConstructorName, 0, MemberKind.Constructor, param, null);
                }
 
                public static MemberFilter Property (string name, TypeSpec type)
                {
-                       return new MemberFilter (name, MemberKind.Property, null, type);
+                       return new MemberFilter (name, 0, MemberKind.Property, null, type);
                }
 
                public static MemberFilter Field (string name, TypeSpec type)
                {
-                       return new MemberFilter (name, MemberKind.Field, null, type);
+                       return new MemberFilter (name, 0, MemberKind.Field, null, type);
                }
 
-               public static MemberFilter Method (string name, TypeSpec[] param, TypeSpec type)
+               public static MemberFilter Method (string name, int arity, AParametersCollection param, TypeSpec type)
                {
-                       return new MemberFilter (name, MemberKind.Method, param, type);
+                       return new MemberFilter (name, arity, MemberKind.Method, param, type);
                }
 
-               #region IEquatable<MemberCore> Members
+               #region IEquatable<MemberSpec> Members
 
-               public bool Equals (MemberCore other)
+               public bool Equals (MemberSpec other)
                {
                        // Is the member of the correct type ?
-                       if ((other.MemberKind & Kind & MemberKind.MaskType) == 0)
+                       // TODO: Isn't this redundant ?
+                       if ((other.Kind & Kind & MemberKind.MaskType) == 0)
+                               return false;
+
+                       // Check arity when not disabled
+                       if (arity >= 0 && arity != other.Arity)
                                return false;
 
                        if (Parameters != null) {
                                if (other is IParametersMember) {
-                                       AParametersCollection other_param = ((IParametersMember) other).Parameters;
-                                       if (TypeSpecArrayComparer.Default.Equals (Parameters, other_param.Types))
-                                               return true;
+                                       var other_param = ((IParametersMember) other).Parameters;
+                                       if (!TypeSpecComparer.Override.IsEqual (Parameters, other_param))
+                                               return false;
+                               } else {
+                                       return false;
                                }
-
-                               return false;
                        }
 
                        if (MemberType != null) {
-                               //throw new NotImplementedException ();
+                               if (other is IInterfaceMemberSpec) {
+                                       var other_type = ((IInterfaceMemberSpec) other).MemberType;
+                                       if (!TypeSpecComparer.Override.IsEqual (other_type, MemberType))
+                                               return false;
+                               } else {
+                                       return false;
+                               }
                        }
 
+                       if (invocation_type != null && !IsAccessible (other))
+                               return false;
+
                        return true;
                }
 
+               bool IsAccessible (MemberSpec other)
+               {
+                       bool extra;
+                       return Expression.IsMemberAccessible (invocation_type, other, out extra);
+               }
+
                #endregion
        }
-*/ 
+
        /// <summary>
-       ///   This is a readonly list of MemberInfo's.      
+       ///   The MemberCache is used by dynamic and non-dynamic types to speed up
+       ///   member lookups.  It has a member name based hash table; it maps each member
+       ///   name to a list of CacheEntry objects.  Each CacheEntry contains a MemberInfo
+       ///   and the BindingFlags that were initially used to get it.  The cache contains
+       ///   all members of the current class and all inherited members.  If this cache is
+       ///   for an interface types, it also contains all inherited members.
+       ///
+       ///   There are two ways to get a MemberCache:
+       ///   * if this is a dynamic type, lookup the corresponding DeclSpace and then
+       ///     use the DeclSpace.MemberCache property.
+       ///   * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
+       ///     TypeHandle instance for the type and then use TypeHandle.MemberCache.
        /// </summary>
-       public class MemberList : IList<MemberInfo> {
-               public readonly IList<MemberInfo> List;
-               int count;
-
-               /// <summary>
-               ///   Create a new MemberList from the given IList.
-               /// </summary>
-               public MemberList (IList<MemberInfo> list)
-               {
-                       if (list != null)
-                               this.List = list;
-                       else
-                               this.List = new List<MemberInfo> ();
-                       count = List.Count;
-               }
+       public class MemberCache
+       {
+               readonly Dictionary<string, IList<MemberSpec>> member_hash;
+               Dictionary<string, MemberSpec[]> locase_members;
+               IList<MethodSpec> missing_abstract;
 
-               /// <summary>
-               ///   Concatenate the ILists `first' and `second' to a new MemberList.
-               /// </summary>
-               public MemberList (IList<MemberInfo> first, IList<MemberInfo> second)
-               {
-                       var list = new List<MemberInfo> ();
-                       list.AddRange (first);
-                       list.AddRange (second);
-                       count = list.Count;
-                       List = list;
-               }
+               public static readonly string IndexerNameAlias = "<this>";
 
-               public static readonly MemberList Empty = new MemberList (Array.AsReadOnly (new MemberInfo[0]));
+               public static readonly MemberCache Empty = new MemberCache (0);
 
-               /// <summary>
-               ///   Cast the MemberList into a MemberInfo[] array.
-               /// </summary>
-               /// <remarks>
-               ///   This is an expensive operation, only use it if it's really necessary.
-               /// </remarks>
-               public static explicit operator MemberInfo [] (MemberList list)
+               public MemberCache ()
+                       : this (16)
                {
-                       Timer.StartTimer (TimerType.MiscTimer);
-                       MemberInfo [] result = new MemberInfo [list.Count];
-                       list.CopyTo (result, 0);
-                       Timer.StopTimer (TimerType.MiscTimer);
-                       return result;
                }
 
-               // ICollection
-
-               public int Count {
-                       get {
-                               return count;
-                       }
-               }
-
-               public void CopyTo (MemberInfo[] array, int index)
+               public MemberCache (int capacity)
                {
-                       List.CopyTo (array, index);
+                       member_hash = new Dictionary<string, IList<MemberSpec>> (capacity);
                }
 
-               // IEnumerable
-
-               public IEnumerator<MemberInfo> GetEnumerator ()
+               public MemberCache (MemberCache cache)
+                       : this (cache.member_hash.Count)
                {
-                       return List.GetEnumerator ();
                }
 
-               System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator ()
+               //
+               // Creates a new MemberCache for the given `container'.
+               //
+               public MemberCache (TypeContainer container)
+                       : this ()                               // TODO: Optimize the size
                {
-                       return List.GetEnumerator ();
                }
 
-               // IList
+               //
+               // Member-cache does not contain base members but it does
+               // contain all base interface members, so the Lookup code
+               // can use simple inheritance rules.
+               //
+               public void AddInterface (TypeSpec iface)
+               {
+                       var cache = iface.MemberCache;
 
-               public bool IsFixedSize {
-                       get {
-                               return true;
-                       }
-               }
+                       IList<MemberSpec> list;
+                       foreach (var entry in cache.member_hash) {
+                               if (!member_hash.TryGetValue (entry.Key, out list)) {
+                                       if (entry.Value.Count == 1) {
+                                               list = entry.Value;
+                                       } else {
+                                               list = new List<MemberSpec> (entry.Value);
+                                       }
 
-               public bool IsReadOnly {
-                       get {
-                               return true;
-                       }
-               }
+                                       member_hash.Add (entry.Key, list);
+                                       continue;
+                               }
 
-               MemberInfo IList<MemberInfo>.this [int index] {
-                       get {
-                               return List [index];
-                       }
+                               foreach (var ce in entry.Value) {
+                                       if (ce.DeclaringType != iface)
+                                               break;
 
-                       set {
-                               throw new NotSupportedException ();
-                       }
-               }
+                                       if (list.Contains (ce))
+                                               continue;
 
-               // FIXME: try to find out whether we can avoid the cast in this indexer.
-               public MemberInfo this [int index] {
-                       get {
-                               return (MemberInfo) List [index];
+                                       if (AddInterfaceMember (ce, ref list))
+                                               member_hash[entry.Key] = list;
+                               }
                        }
                }
 
-               public void Add (MemberInfo value)
+               public void AddMember (InterfaceMemberBase imb, string exlicitName, MemberSpec ms)
                {
-                       throw new NotSupportedException ();
+                       // Explicit names cannot be looked-up but can be used for
+                       // collision checking (no name mangling needed)
+                       if (imb.IsExplicitImpl)
+                               AddMember (exlicitName, ms);
+                       else
+                               AddMember (ms);
                }
 
-               public void Clear ()
+               //
+               // Add non-explicit member to member cache
+               //
+               public void AddMember (MemberSpec ms)
                {
-                       throw new NotSupportedException ();
+                       AddMember (GetLookupName (ms), ms);
                }
 
-               public bool Contains (MemberInfo value)
+               void AddMember (string name, MemberSpec member)
                {
-                       return List.Contains (value);
-               }
+                       IList<MemberSpec> list;
+                       if (!member_hash.TryGetValue (name, out list)) {
+                               member_hash.Add (name, new MemberSpec[] { member });
+                               return;
+                       }
 
-               public int IndexOf (MemberInfo value)
-               {
-                       return List.IndexOf (value);
-               }
+                       if (member.DeclaringType.IsInterface) {
+                               if (AddInterfaceMember (member, ref list))
+                                       member_hash[name] = list;
+                       } else {
+                               if (list is MemberSpec[]) {
+                                       list = new List<MemberSpec> () { list[0] };
+                                       member_hash[name] = list;
+                               }
 
-               public void Insert (int index, MemberInfo value)
-               {
-                       throw new NotSupportedException ();
+                               list.Add (member);
+                       }
                }
 
-               public bool Remove (MemberInfo value)
+               //
+               // Ignores any base interface member which can be hidden
+               // by this interface
+               //
+               static bool AddInterfaceMember (MemberSpec member, ref IList<MemberSpec> existing)
                {
-                       throw new NotSupportedException ();
-               }
+                       var member_param = member is IParametersMember ? ((IParametersMember) member).Parameters : ParametersCompiled.EmptyReadOnlyParameters;
 
-               public void RemoveAt (int index)
-               {
-                       throw new NotSupportedException ();
-               }
-       }
+                       //
+                       // interface IA : IB { int Prop { set; } }
+                       // interface IB { bool Prop { get; } }
+                       //
+                       // IB.Prop is never accessible from IA interface
+                       //
+                       for (int i = 0; i < existing.Count; ++i) {
+                               var entry = existing[i];
 
-       /// <summary>
-       ///   This interface is used to get all members of a class when creating the
-       ///   member cache.  It must be implemented by all DeclSpace derivatives which
-       ///   want to support the member cache and by TypeHandle to get caching of
-       ///   non-dynamic types.
-       /// </summary>
-       public interface IMemberContainer {
-               /// <summary>
-               ///   The name of the IMemberContainer.  This is only used for
-               ///   debugging purposes.
-               /// </summary>
-               string Name {
-                       get;
-               }
+                               if (entry.Arity != member.Arity)
+                                       continue;
 
-               /// <summary>
-               ///   The type of this IMemberContainer.
-               /// </summary>
-               Type Type {
-                       get;
-               }
+                               if (entry is IParametersMember) {
+                                       var entry_param = ((IParametersMember) entry).Parameters;
+                                       if (!TypeSpecComparer.Override.IsEqual (entry_param, member_param))
+                                               continue;
+                               }
 
-               /// <summary>
-               ///   Returns the IMemberContainer of the base class or null if this
-               ///   is an interface or TypeManger.object_type.
-               ///   This is used when creating the member cache for a class to get all
-               ///   members from the base class.
-               /// </summary>
-               MemberCache BaseCache {
-                       get;
-               }
+                               if (member.DeclaringType.ImplementsInterface (entry.DeclaringType)) {
+                                       if (existing is MemberSpec[]) {
+                                               existing = new MemberSpec[] { member };
+                                               return true;
+                                       }
 
-               /// <summary>
-               ///   Whether this is an interface.
-               /// </summary>
-               bool IsInterface {
-                       get;
-               }
+                                       existing.RemoveAt (i--);
+                                       continue;
+                               }
 
-               /// <summary>
-               ///   Returns all members of this class with the corresponding MemberTypes
-               ///   and BindingFlags.
-               /// </summary>
-               /// <remarks>
-               ///   When implementing this method, make sure not to return any inherited
-               ///   members and check the MemberTypes and BindingFlags properly.
-               ///   Unfortunately, System.Reflection is lame and doesn't provide a way to
-               ///   get the BindingFlags (static/non-static,public/non-public) in the
-               ///   MemberInfo class, but the cache needs this information.  That's why
-               ///   this method is called multiple times with different BindingFlags.
-               /// </remarks>
-               MemberList GetMembers (MemberTypes mt, BindingFlags bf);
-       }
+                               if (entry.DeclaringType == member.DeclaringType || entry.DeclaringType.ImplementsInterface (member.DeclaringType))
+                                       return false;
+                       }
 
-       /// <summary>
-       ///   The MemberCache is used by dynamic and non-dynamic types to speed up
-       ///   member lookups.  It has a member name based hash table; it maps each member
-       ///   name to a list of CacheEntry objects.  Each CacheEntry contains a MemberInfo
-       ///   and the BindingFlags that were initially used to get it.  The cache contains
-       ///   all members of the current class and all inherited members.  If this cache is
-       ///   for an interface types, it also contains all inherited members.
-       ///
-       ///   There are two ways to get a MemberCache:
-       ///   * if this is a dynamic type, lookup the corresponding DeclSpace and then
-       ///     use the DeclSpace.MemberCache property.
-       ///   * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
-       ///     TypeHandle instance for the type and then use TypeHandle.MemberCache.
-       /// </summary>
-       public class MemberCache {
-               public readonly IMemberContainer Container;
-               protected Dictionary<string, List<CacheEntry>> member_hash;
-               protected Dictionary<string, List<CacheEntry>> method_hash;
+                       if (existing is MemberSpec[]) {
+                               existing = new List<MemberSpec> () { existing[0], member };
+                               return true;
+                       }
 
-               Dictionary<string, object> locase_table;
+                       existing.Add (member);
+                       return false;
+               }
 
-               static List<MethodInfo> overrides = new List<MethodInfo> ();
+               public static IEnumerable<IndexerSpec> FindIndexers (TypeSpec container, BindingRestriction restrictions)
+               {
+                       var filter = new MemberFilter (IndexerNameAlias, 0, MemberKind.Indexer, null, null);
+                       var found = FindMembers (container, filter, restrictions);
+                       return found == null ? null : found.Cast<IndexerSpec> ();
+               }
 
-               /// <summary>
-               ///   Create a new MemberCache for the given IMemberContainer `container'.
-               /// </summary>
-               public MemberCache (IMemberContainer container)
+               public static MemberSpec FindMember (TypeSpec container, MemberFilter filter, BindingRestriction restrictions)
                {
-                       this.Container = container;
+                       do {
+                               IList<MemberSpec> applicable;
+                               if (container.MemberCache.member_hash.TryGetValue (filter.Name, out applicable)) {
+                                       // Start from the end because interface members are in reverse order
+                                       for (int i = applicable.Count - 1; i >= 0; i--) {
+                                               var entry = applicable [i];
+
+                                               if ((restrictions & BindingRestriction.InstanceOnly) != 0 && entry.IsStatic)
+                                                       continue;
 
-                       Timer.IncrementCounter (CounterType.MemberCache);
-                       Timer.StartTimer (TimerType.CacheInit);
+                                               if (filter.Equals (entry))
+                                                       return entry;
 
-                       // If we have a base class (we have a base class unless we're
-                       // TypeManager.object_type), we deep-copy its MemberCache here.
-                       if (Container.BaseCache != null)
-                               member_hash = SetupCache (Container.BaseCache);
-                       else
-                               member_hash = new Dictionary<string, List<CacheEntry>> ();
-
-                       // If this is neither a dynamic type nor an interface, create a special
-                       // method cache with all declared and inherited methods.
-                       Type type = container.Type;
-                       if (!(type is TypeBuilder) && !type.IsInterface &&
-                           // !(type.IsGenericType && (type.GetGenericTypeDefinition () is TypeBuilder)) &&
-                           !TypeManager.IsGenericType (type) && !TypeManager.IsGenericParameter (type) &&
-                           (Container.BaseCache == null || Container.BaseCache.method_hash != null)) {
-                                       method_hash = new Dictionary<string, List<CacheEntry>> ();
-                                       AddMethods (type);
-                       }
+                                               // TODO MemberCache:
+                                               //if ((restrictions & BindingRestriction.AccessibleOnly) != 0)
+                                               //      throw new NotImplementedException ("net");
+                                       }
+                               }
 
-                       // Add all members from the current class.
-                       AddMembers (Container);
+                               container = container.BaseType;
+                       } while (container != null && (restrictions & BindingRestriction.DeclaredOnly) == 0);
 
-                       Timer.StopTimer (TimerType.CacheInit);
+                       return null;
                }
 
-               public MemberCache (Type baseType, IMemberContainer container)
+               //
+               // Returns the first set of members starting from container
+               //
+               public static IList<MemberSpec> FindMembers (TypeSpec container, MemberFilter filter, BindingRestriction restrictions)
                {
-                       this.Container = container;
-                       if (baseType == null)
-                               this.member_hash = new Dictionary<string, List<CacheEntry>> ();
-                       else
-                               this.member_hash = SetupCache (TypeManager.LookupMemberCache (baseType));
-               }
+                       IList<MemberSpec> applicable;
+                       IList<MemberSpec> found = null;
 
-               public MemberCache (Type[] ifaces)
-               {
-                       //
-                       // The members of this cache all belong to other caches.  
-                       // So, 'Container' will not be used.
-                       //
-                       this.Container = null;
+                       do {
+                               if (container.MemberCache.member_hash.TryGetValue (filter.Name, out applicable)) {
+                                       for (int i = 0; i < applicable.Count; ++i) {
+                                               var entry = applicable [i];
 
-                       member_hash = new Dictionary<string, List<CacheEntry>> ();
-                       if (ifaces == null)
-                               return;
+                                               // Is the member of the correct type
+                                               if ((entry.Kind & filter.Kind & MemberKind.MaskType) == 0)
+                                                       continue;
 
-                       foreach (Type itype in ifaces)
-                               AddCacheContents (TypeManager.LookupMemberCache (itype));
-               }
+                                               //
+                                               // When using overloadable overrides filter ignore members which
+                                               // are not base members. Including properties because overrides can
+                                               // implement get or set only and we are looking for complete base member
+                                               //
+                                               const MemberKind overloadable = MemberKind.Indexer | MemberKind.Method | MemberKind.Property;
+                                               if ((restrictions & BindingRestriction.NoOverrides) != 0 && (entry.Kind & overloadable) != 0) {
+                                                       if ((entry.Modifiers & Modifiers.OVERRIDE) != 0)
+                                                               continue;
 
-               public MemberCache (IMemberContainer container, Type base_class, Type[] ifaces)
-               {
-                       this.Container = container;
+                                                       if ((entry.Modifiers & Modifiers.OVERRIDE_UNCHECKED) != 0) {
+                                                               // TODO: Implement this correctly for accessors
+                                                               var ms = entry as MethodSpec;
+                                                               if (ms == null || IsRealMethodOverride (ms)) {
+                                                                       entry.Modifiers = (entry.Modifiers & ~Modifiers.OVERRIDE_UNCHECKED) | Modifiers.OVERRIDE;
+                                                                       continue;
+                                                               }
+                                                       }
+                                               }
 
-                       // If we have a base class (we have a base class unless we're
-                       // TypeManager.object_type), we deep-copy its MemberCache here.
-                       if (Container.BaseCache != null)
-                               member_hash = SetupCache (Container.BaseCache);
-                       else
-                               member_hash = new Dictionary<string, List<CacheEntry>> ();
-
-                       if (base_class != null)
-                               AddCacheContents (TypeManager.LookupMemberCache (base_class));
-                       if (ifaces != null) {
-                               foreach (Type itype in ifaces) {
-                                       MemberCache cache = TypeManager.LookupMemberCache (itype);
-                                       if (cache != null)
-                                               AddCacheContents (cache);
+                                               if ((restrictions & BindingRestriction.InstanceOnly) != 0 && entry.IsStatic)
+                                                       continue;
+
+                                               // Apply the filter to it.
+                                               if (!filter.Equals (entry))
+                                                       continue;
+
+                                               if (found == null) {
+                                                       if (i == 0) {
+                                                               found = applicable;
+                                                       } else {
+                                                               found = new List<MemberSpec> ();
+                                                               found.Add (entry);
+                                                       }
+                                               } else if (found == applicable) {
+                                                       found = new List<MemberSpec> ();
+                                                       found.Add (applicable[0]);
+                                                       found.Add (entry);
+                                               } else {
+                                                       found.Add (entry);
+                                               }
+                                       }
+
+                                       if (found != null) {
+                                               if (found == applicable && applicable.Count != 1)
+                                                       return new MemberSpec[] { found[0] };
+
+                                               return found;
+                                       }
                                }
-                       }
-               }
 
-               /// <summary>
-               ///   Bootstrap this member cache by doing a deep-copy of our base.
-               /// </summary>
-               static Dictionary<string, List<CacheEntry>> SetupCache (MemberCache base_class)
-               {
-                       if (base_class == null)
-                               return new Dictionary<string, List<CacheEntry>> ();
+                               container = container.BaseType;
+                       } while (container != null && (restrictions & BindingRestriction.DeclaredOnly) == 0);
 
-                       var hash = new Dictionary<string, List<CacheEntry>> (base_class.member_hash.Count);
-                       var it = base_class.member_hash.GetEnumerator ();
-                       while (it.MoveNext ()) {
-                               hash.Add (it.Current.Key, new List<CacheEntry> (it.Current.Value));
-                       }
-                                
-                       return hash;
+                       return found;
                }
-               
+
                //
-               // Converts ModFlags to BindingFlags
+               // Finds the nested type in container
                //
-               static BindingFlags GetBindingFlags (Modifiers modifiers)
+               public static TypeSpec FindNestedType (TypeSpec container, string name, int arity)
                {
-                       BindingFlags bf;
-                       if ((modifiers & Modifiers.STATIC) != 0)
-                               bf = BindingFlags.Static;
-                       else
-                               bf = BindingFlags.Instance;
-
-                       if ((modifiers & Modifiers.PRIVATE) != 0)
-                               bf |= BindingFlags.NonPublic;
-                       else
-                               bf |= BindingFlags.Public;
-
-                       return bf;
-               }               
-
-               /// <summary>
-               ///   Add the contents of `cache' to the member_hash.
-               /// </summary>
-               void AddCacheContents (MemberCache cache)
-               {
-                       var it = cache.member_hash.GetEnumerator ();
-                       while (it.MoveNext ()) {
-                               List<CacheEntry> list;
-                               if (!member_hash.TryGetValue (it.Current.Key, out list))
-                                       member_hash [it.Current.Key] = list = new List<CacheEntry> ();
+                       IList<MemberSpec> applicable;
+                       TypeSpec best_match = null;
+                       do {
+                               // TODO: Don't know how to handle this yet
+                               // When resolving base type of nested type, parent type must have
+                               // base type resolved to scan full hierarchy correctly
+                               // Similarly MemberCacheTypes will inflate BaseType and Interfaces
+                               // based on type definition
+                               var tc = container.MemberDefinition as TypeContainer;
+                               if (tc != null)
+                                       tc.DefineType ();
+
+                               if (container.MemberCacheTypes.member_hash.TryGetValue (name, out applicable)) {
+                                       for (int i = applicable.Count - 1; i >= 0; i--) {
+                                               var entry = applicable[i];
+                                               if ((entry.Kind & MemberKind.NestedMask) == 0)
+                                                       continue;
 
-                               var entries = it.Current.Value;
-                               for (int i = entries.Count-1; i >= 0; i--) {
-                                       var entry = entries [i];
+                                               var ts = (TypeSpec) entry;
+                                               if (arity == ts.Arity)
+                                                       return ts;
 
-                                       if (entry.Container != cache.Container)
-                                               break;
-                                       list.Add (entry);
+                                               if (arity < 0) {
+                                                       if (best_match == null) {
+                                                               best_match = ts;
+                                                       } else if (System.Math.Abs (ts.Arity + arity) < System.Math.Abs (ts.Arity + arity)) {
+                                                               best_match = ts;
+                                                       }
+                                               }
+                                       }
                                }
-                       }
-               }
 
-               /// <summary>
-               ///   Add all members from class `container' to the cache.
-               /// </summary>
-               void AddMembers (IMemberContainer container)
-               {
-                       // We need to call AddMembers() with a single member type at a time
-                       // to get the member type part of CacheEntry.EntryType right.
-                       if (!container.IsInterface) {
-                               AddMembers (MemberTypes.Constructor, container);
-                               AddMembers (MemberTypes.Field, container);
-                       }
-                       AddMembers (MemberTypes.Method, container);
-                       AddMembers (MemberTypes.Property, container);
-                       AddMembers (MemberTypes.Event, container);
-                       // Nested types are returned by both Static and Instance searches.
-                       AddMembers (MemberTypes.NestedType,
-                                   BindingFlags.Static | BindingFlags.Public, container);
-                       AddMembers (MemberTypes.NestedType,
-                                   BindingFlags.Static | BindingFlags.NonPublic, container);
-               }
+                               container = container.BaseType;
+                       } while (container != null);
 
-               void AddMembers (MemberTypes mt, IMemberContainer container)
-               {
-                       AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
-                       AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
-                       AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
-                       AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
+                       return best_match;
                }
 
-               public void AddMember (MemberInfo mi, MemberSpec mc)
+               //
+               // Looks for extension methods with defined name and extension type
+               //
+               public List<MethodSpec> FindExtensionMethods (TypeSpec invocationType, TypeSpec extensionType, string name, int arity)
                {
-                       AddMember (mi.MemberType, GetBindingFlags (mc.Modifiers), Container, mi.Name, mi);
-               }
+                       IList<MemberSpec> entries;
+                       if (!member_hash.TryGetValue (name, out entries))
+                               return null;
 
-               public void AddGenericMember (MemberInfo mi, InterfaceMemberBase mc)
-               {
-                       AddMember (mi.MemberType, GetBindingFlags (mc.ModFlags), Container,
-                               MemberName.MakeName (mc.GetFullName (mc.MemberName), mc.MemberName.TypeArguments), mi);
-               }
+                       List<MethodSpec> candidates = null;
+                       foreach (var entry in entries) {
+                               if (entry.Kind != MemberKind.Method || (arity >= 0 && entry.Arity != arity))
+                                       continue;
 
-               public void AddNestedType (DeclSpace type)
-               {
-                       AddMember (MemberTypes.NestedType, GetBindingFlags (type.ModFlags), (IMemberContainer) type.Parent,
-                               type.TypeBuilder.Name, type.TypeBuilder);
-               }
+                               var ms = (MethodSpec) entry;
+                               if (!ms.IsExtensionMethod)
+                                       continue;
 
-               public void AddInterface (MemberCache baseCache)
-               {
-                       if (baseCache.member_hash.Count > 0)
-                               AddCacheContents (baseCache);
-               }
+                               bool extra;
+                               if (!Expression.IsMemberAccessible (invocationType, ms, out extra))
+                                       continue;
 
-               void AddMember (MemberTypes mt, BindingFlags bf, IMemberContainer container,
-                               string name, MemberInfo member)
-               {
-                       // We use a name-based hash table of ArrayList's.
-                       List<CacheEntry> list;
-                       if (!member_hash.TryGetValue (name, out list)) {
-                               list = new List<CacheEntry> (1);
-                               member_hash.Add (name, list);
+                               // TODO: CodeGen.Assembly.Builder
+                               if ((ms.DeclaringType.Modifiers & Modifiers.INTERNAL) != 0 &&
+                                       !TypeManager.IsThisOrFriendAssembly (CodeGen.Assembly.Builder, ms.Assembly))
+                                       continue;
+
+                               if (candidates == null)
+                                       candidates = new List<MethodSpec> ();
+                               candidates.Add (ms);
                        }
 
-                       // When this method is called for the current class, the list will
-                       // already contain all inherited members from our base classes.
-                       // We cannot add new members in front of the list since this'd be an
-                       // expensive operation, that's why the list is sorted in reverse order
-                       // (ie. members from the current class are coming last).
-                       list.Add (new CacheEntry (container, member, mt, bf));
+                       return candidates;
                }
 
-               /// <summary>
-               ///   Add all members from class `container' with the requested MemberTypes and
-               ///   BindingFlags to the cache.  This method is called multiple times with different
-               ///   MemberTypes and BindingFlags.
-               /// </summary>
-               void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
+               //
+               // Returns base members of @member member if no exact match is found @bestCandidate returns
+               // the best match
+               //
+               public static MemberSpec FindBaseMember (MemberCore member, out MemberSpec bestCandidate)
                {
-                       MemberList members = container.GetMembers (mt, bf);
+                       bestCandidate = null;
+                       var container = member.Parent.PartialContainer.Definition;
+                       if (!container.IsInterface)
+                               container = container.BaseType;
 
-                       foreach (MemberInfo member in members) {
-                               string name = member.Name;
+                       string name = GetLookupName (member);
+                       IList<MemberSpec> applicable;
+                       var member_param = member is IParametersMember ? ((IParametersMember) member).Parameters : null;
 
-                               AddMember (mt, bf, container, name, member);
+                       var mkind = GetMemberCoreKind (member);
 
-                               if (member is MethodInfo) {
-                                       string gname = TypeManager.GetMethodName ((MethodInfo) member);
-                                       if (gname != name)
-                                               AddMember (mt, bf, container, gname, member);
-                               }
-                       }
-               }
+                       do {
+                               if (container.MemberCache.member_hash.TryGetValue (name, out applicable)) {
+                                       for (int i = 0; i < applicable.Count; ++i) {
+                                               var entry = applicable [i];
 
-               /// <summary>
-               ///   Add all declared and inherited methods from class `type' to the method cache.
-               /// </summary>
-               void AddMethods (Type type)
-               {
-                       AddMethods (BindingFlags.Static | BindingFlags.Public |
-                                   BindingFlags.FlattenHierarchy, type);
-                       AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
-                                   BindingFlags.FlattenHierarchy, type);
-                       AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
-                       AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
-               }
+                                               if ((entry.Modifiers & Modifiers.PRIVATE) != 0)
+                                                       continue;
 
-               void AddMethods (BindingFlags bf, Type type)
-               {
-                       MethodBase [] members = type.GetMethods (bf);
+                                               if ((entry.Modifiers & Modifiers.AccessibilityMask) == Modifiers.INTERNAL) {
+                                                       if (!TypeManager.IsThisOrFriendAssembly (member.Assembly, entry.Assembly))
+                                                               continue;
+                                               }
+
+                                               // Is the member of the correct type ?
+                                               if ((entry.Kind & mkind & MemberKind.MaskType) == 0) {
+                                                       if (member_param == null || !(entry is IParametersMember)) {
+                                                               bestCandidate = entry;
+                                                               return null;
+                                                       }
 
-                        Array.Reverse (members);
+                                                       continue;
+                                               }
 
-                       foreach (MethodBase member in members) {
-                               string name = member.Name;
+                                               if (member_param == null)
+                                                       return entry;
 
-                               // We use a name-based hash table of ArrayList's.
-                               List<CacheEntry> list;
-                               if (!method_hash.TryGetValue (name, out list)) {
-                                       list = new List<CacheEntry> (1);
-                                       method_hash.Add (name, list);
-                               }
+                                               // Check arity match
+                                               int arity = member.MemberName.Arity;
+                                               if (arity != entry.Arity)
+                                                       continue;
 
-                               MethodInfo curr = (MethodInfo) member;
-                               while (curr.IsVirtual && (curr.Attributes & MethodAttributes.NewSlot) == 0) {
-                                       MethodInfo base_method = curr.GetBaseDefinition ();
+                                               if (entry is IParametersMember) {
+                                                       if (entry.IsAccessor != member is AbstractPropertyEventMethod)
+                                                               continue;
 
-                                       if (base_method == curr)
-                                               // Not every virtual function needs to have a NewSlot flag.
-                                               break;
+                                                       var entry_param = ((IParametersMember) entry).Parameters;
+                                                       if (TypeSpecComparer.Override.IsEqual (entry_param, member_param))
+                                                               return entry;
 
-                                       overrides.Add (curr);
-                                       list.Add (new CacheEntry (null, base_method, MemberTypes.Method, bf));
-                                       curr = base_method;
-                               }
+                                                       continue;
+                                               }
+
+                                               if (bestCandidate == null)
+                                                       bestCandidate = entry;
+                                       }
 
-                               if (overrides.Count > 0) {
-                                       for (int i = 0; i < overrides.Count; ++i)
-                                               TypeManager.RegisterOverride ((MethodBase) overrides [i], curr);
-                                       overrides.Clear ();
+                                       if (member_param == null)
+                                               return null;
                                }
 
-                               // Unfortunately, the elements returned by Type.GetMethods() aren't
-                               // sorted so we need to do this check for every member.
-                               BindingFlags new_bf = bf;
-                               if (member.DeclaringType == type)
-                                       new_bf |= BindingFlags.DeclaredOnly;
+                               if (container.IsInterface)
+                                       break;
 
-                               list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
-                       }
-               }
+                               container = container.BaseType;
+                       } while (container != null);
 
-               /// <summary>
-               ///   Compute and return a appropriate `EntryType' magic number for the given
-               ///   MemberTypes and BindingFlags.
-               /// </summary>
-               protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
-               {
-                       EntryType type = EntryType.None;
-
-                       if ((mt & MemberTypes.Constructor) != 0)
-                               type |= EntryType.Constructor;
-                       if ((mt & MemberTypes.Event) != 0)
-                               type |= EntryType.Event;
-                       if ((mt & MemberTypes.Field) != 0)
-                               type |= EntryType.Field;
-                       if ((mt & MemberTypes.Method) != 0)
-                               type |= EntryType.Method;
-                       if ((mt & MemberTypes.Property) != 0)
-                               type |= EntryType.Property;
-                       // Nested types are returned by static and instance searches.
-                       if ((mt & MemberTypes.NestedType) != 0)
-                               type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
-
-                       if ((bf & BindingFlags.Instance) != 0)
-                               type |= EntryType.Instance;
-                       if ((bf & BindingFlags.Static) != 0)
-                               type |= EntryType.Static;
-                       if ((bf & BindingFlags.Public) != 0)
-                               type |= EntryType.Public;
-                       if ((bf & BindingFlags.NonPublic) != 0)
-                               type |= EntryType.NonPublic;
-                       if ((bf & BindingFlags.DeclaredOnly) != 0)
-                               type |= EntryType.Declared;
-
-                       return type;
+                       return null;
                }
 
-               /// <summary>
-               ///   The `MemberTypes' enumeration type is a [Flags] type which means that it may
-               ///   denote multiple member types.  Returns true if the given flags value denotes a
-               ///   single member types.
-               /// </summary>
-               public static bool IsSingleMemberType (MemberTypes mt)
+               //
+               // Returns inflated version of MemberSpec, it works similarly to
+               // SRE TypeBuilder.GetMethod
+               //
+               public static T GetMember<T> (TypeSpec container, T spec) where T : MemberSpec
                {
-                       switch (mt) {
-                       case MemberTypes.Constructor:
-                       case MemberTypes.Event:
-                       case MemberTypes.Field:
-                       case MemberTypes.Method:
-                       case MemberTypes.Property:
-                       case MemberTypes.NestedType:
-                               return true;
-
-                       default:
-                               return false;
+                       IList<MemberSpec> applicable;
+                       if (container.MemberCache.member_hash.TryGetValue (GetLookupName (spec), out applicable)) {
+                               for (int i = applicable.Count - 1; i >= 0; i--) {
+                                       var entry = applicable[i];
+                                       if (entry.MemberDefinition == spec.MemberDefinition)
+                                               return (T) entry;
+                               }
                        }
-               }
 
-               /// <summary>
-               ///   We encode the MemberTypes and BindingFlags of each members in a "magic"
-               ///   number to speed up the searching process.
-               /// </summary>
-               [Flags]
-               public enum EntryType {
-                       None            = 0x000,
-
-                       Instance        = 0x001,
-                       Static          = 0x002,
-                       MaskStatic      = Instance|Static,
-
-                       Public          = 0x004,
-                       NonPublic       = 0x008,
-                       MaskProtection  = Public|NonPublic,
+                       throw new InternalErrorException ("Missing member `{0}' on inflated type `{1}'",
+                               spec.GetSignatureForError (), container.GetSignatureForError ());
+               }
 
-                       Declared        = 0x010,
+               static MemberKind GetMemberCoreKind (MemberCore member)
+               {
+                       if (member is FieldBase)
+                               return MemberKind.Field;
+                       if (member is Indexer)
+                               return MemberKind.Indexer;
+                       if (member is Class)
+                               return MemberKind.Class;
+                       if (member is Struct)
+                               return MemberKind.Struct;
+                       if (member is Destructor)
+                               return MemberKind.Destructor;
+                       if (member is Method)
+                               return MemberKind.Method;
+                       if (member is Property)
+                               return MemberKind.Property;
+                       if (member is EventField)
+                               return MemberKind.Event;
+                       if (member is Interface)
+                               return MemberKind.Interface;
+                       if (member is EventProperty)
+                               return MemberKind.Event;
+
+                       throw new NotImplementedException (member.GetType ().ToString ());
+               }
 
-                       Constructor     = 0x020,
-                       Event           = 0x040,
-                       Field           = 0x080,
-                       Method          = 0x100,
-                       Property        = 0x200,
-                       NestedType      = 0x400,
+               public static IList<MemberSpec> GetCompletitionMembers (TypeSpec container, string name)
+               {
+                       var matches = new List<MemberSpec> ();
+                       foreach (var entry in container.MemberCache.member_hash) {
+                               foreach (var name_entry in entry.Value) {
+                                       if (name_entry.IsAccessor)
+                                               continue;
 
-                       NotExtensionMethod      = 0x800,
+                                       if ((name_entry.Kind & (MemberKind.Constructor | MemberKind.FakeMethod | MemberKind.Destructor)) != 0)
+                                               continue;
 
-                       MaskType        = Constructor|Event|Field|Method|Property|NestedType
-               }
+                                       bool extra;
+                                       if (!Expression.IsMemberAccessible (InternalType.FakeInternalType, name_entry, out extra))
+                                               continue;
 
-               public class CacheEntry {
-                       public readonly IMemberContainer Container;
-                       public EntryType EntryType;
-                       public readonly MemberInfo Member;
-
-                       public CacheEntry (IMemberContainer container, MemberInfo member,
-                                          MemberTypes mt, BindingFlags bf)
-                       {
-                               this.Container = container;
-                               this.Member = member;
-                               this.EntryType = GetEntryType (mt, bf);
+                                       if (name == null || name_entry.Name.StartsWith (name)) {
+                                               matches.Add (name_entry);
+                                       }
+                               }
                        }
 
-                       public override string ToString ()
-                       {
-                               return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
-                                                     EntryType, Member);
-                       }
+                       return matches;
                }
 
-               /// <summary>
-               ///   This is called each time we're walking up one level in the class hierarchy
-               ///   and checks whether we can abort the search since we've already found what
-               ///   we were looking for.
-               /// </summary>
-               protected bool DoneSearching (IList<MemberInfo> list)
+               //
+               // Returns members of @iface only, base members are ignored
+               //
+               public static IList<MethodSpec> GetInterfaceMembers (TypeSpec iface)
                {
                        //
-                       // We've found exactly one member in the current class and it's not
-                       // a method or constructor.
+                       // MemberCache flatten interfaces, therefore in cases like this one
+                       // 
+                       // interface IA : IB {}
+                       // interface IB { void Foo () }
                        //
-                       if (list.Count == 1 && !(list [0] is MethodBase))
-                               return true;
-
-                       //
-                       // Multiple properties: we query those just to find out the indexer
-                       // name
+                       // we would return Foo inside IA which is not expected in this case
                        //
-                       if ((list.Count > 0) && (list [0] is PropertyInfo))
-                               return true;
+                       var methods = new List<MethodSpec> ();
+                       foreach (var entry in iface.MemberCache.member_hash.Values) {
+                               foreach (var name_entry in entry) {
+                                       if (iface == name_entry.DeclaringType) {
+                                               if (name_entry.Kind == MemberKind.Method) {
+                                                       methods.Add ((MethodSpec) name_entry);
+                                               }
+                                       }
+                               }
+                       }
 
-                       return false;
+                       return methods;
                }
 
-               /// <summary>
-               ///   Looks up members with name `name'.  If you provide an optional
-               ///   filter function, it'll only be called with members matching the
-               ///   requested member name.
-               ///
-               ///   This method will try to use the cache to do the lookup if possible.
-               ///
-               ///   Unlike other FindMembers implementations, this method will always
-               ///   check all inherited members - even when called on an interface type.
-               ///
-               ///   If you know that you're only looking for methods, you should use
-               ///   MemberTypes.Method alone since this speeds up the lookup a bit.
-               ///   When doing a method-only search, it'll try to use a special method
-               ///   cache (unless it's a dynamic type or an interface) and the returned
-               ///   MemberInfo's will have the correct ReflectedType for inherited methods.
-               ///   The lookup process will automatically restart itself in method-only
-               ///   search mode if it discovers that it's about to return methods.
-               /// </summary>
-               List<MemberInfo> global = new List<MemberInfo> ();
-               bool using_global;
-               
-               static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
-               
-               public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
-                                                 MemberFilter filter, object criteria)
+               public static IList<MethodSpec> GetNotImplementedAbstractMethods (TypeSpec type)
                {
-                       if (using_global)
-                               throw new Exception ();
-
-                       bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
-                       bool method_search = mt == MemberTypes.Method;
-                       // If we have a method cache and we aren't already doing a method-only search,
-                       // then we restart a method search if the first match is a method.
-                       bool do_method_search = !method_search && (method_hash != null);
-
-                       List<CacheEntry> applicable;
-
-                       // If this is a method-only search, we try to use the method cache if
-                       // possible; a lookup in the method cache will return a MemberInfo with
-                       // the correct ReflectedType for inherited methods.
-                       
-                       if (method_search && (method_hash != null))
-                               method_hash.TryGetValue (name, out applicable);
-                       else
-                               member_hash.TryGetValue (name, out applicable);
-
-                       if (applicable == null)
-                               return emptyMemberInfo;
+                       if (type.MemberCache.missing_abstract != null)
+                               return type.MemberCache.missing_abstract;
+                               
+                       var abstract_methods = new List<MethodSpec> ();
+                       List<TypeSpec> hierarchy = null;
 
                        //
-                       // 32  slots gives 53 rss/54 size
-                       // 2/4 slots gives 55 rss
+                       // Stage 1: top-to-bottom scan for abstract members
                        //
-                       // Strange: from 25,000 calls, only 1,800
-                       // are above 2.  Why does this impact it?
-                       //
-                       global.Clear ();
-                       using_global = true;
-
-                       Timer.StartTimer (TimerType.CachedLookup);
-
-                       EntryType type = GetEntryType (mt, bf);
-
-                       IMemberContainer current = Container;
+                       var abstract_type = type;
+                       while (true) {
+                               foreach (var entry in abstract_type.MemberCache.member_hash) {
+                                       foreach (var name_entry in entry.Value) {
+                                               if ((name_entry.Modifiers & Modifiers.ABSTRACT) == 0)
+                                                       continue;
 
-                       bool do_interface_search = current.IsInterface;
+                                               if (name_entry.Kind != MemberKind.Method)
+                                                       continue;
 
-                       // `applicable' is a list of all members with the given member name `name'
-                       // in the current class and all its base classes.  The list is sorted in
-                       // reverse order due to the way how the cache is initialy created (to speed
-                       // things up, we're doing a deep-copy of our base).
+                                               abstract_methods.Add ((MethodSpec) name_entry);
+                                       }
+                               }
 
-                       for (int i = applicable.Count-1; i >= 0; i--) {
-                               CacheEntry entry = (CacheEntry) applicable [i];
+                               var base_type = abstract_type.BaseType;
+                               if (!base_type.IsAbstract)
+                                       break;
 
-                               // This happens each time we're walking one level up in the class
-                               // hierarchy.  If we're doing a DeclaredOnly search, we must abort
-                               // the first time this happens (this may already happen in the first
-                               // iteration of this loop if there are no members with the name we're
-                               // looking for in the current class).
-                               if (entry.Container != current) {
-                                       if (declared_only)
-                                               break;
+                               if (hierarchy == null)
+                                       hierarchy = new List<TypeSpec> ();
 
-                                       if (!do_interface_search && DoneSearching (global))
-                                               break;
+                               hierarchy.Add (abstract_type);
+                               abstract_type = base_type;
+                       }
 
-                                       current = entry.Container;
-                               }
+                       int not_implemented_count = abstract_methods.Count;
+                       if (not_implemented_count == 0 || hierarchy == null) {
+                               type.MemberCache.missing_abstract = abstract_methods;
+                               return type.MemberCache.missing_abstract;
+                       }
 
-                               // Is the member of the correct type ?
-                               if ((entry.EntryType & type & EntryType.MaskType) == 0)
+                       //
+                       // Stage 2: Remove already implemented methods
+                       //
+                       foreach (var type_up in hierarchy) {
+                               var members = type_up.MemberCache.member_hash;
+                               if (members.Count == 0)
                                        continue;
 
-                               // Is the member static/non-static ?
-                               if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
-                                       continue;
+                               for (int i = 0; i < abstract_methods.Count; ++i) {
+                                       var candidate = abstract_methods [i];
+                                       if (candidate == null)
+                                               continue;
 
-                               // Apply the filter to it.
-                               if (filter (entry.Member, criteria)) {
-                                       if ((entry.EntryType & EntryType.MaskType) != EntryType.Method) {
-                                               do_method_search = false;
-                                       }
-                                       
-                                       // Because interfaces support multiple inheritance we have to be sure that
-                                       // base member is from same interface, so only top level member will be returned
-                                       if (do_interface_search && global.Count > 0) {
-                                               bool member_already_exists = false;
-
-                                               foreach (MemberInfo mi in global) {
-                                                       if (mi is MethodBase)
-                                                               continue;
+                                       IList<MemberSpec> applicable;
+                                       if (!members.TryGetValue (candidate.Name, out applicable))
+                                               continue;
 
-                                                       if (IsInterfaceBaseInterface (TypeManager.GetInterfaces (mi.DeclaringType), entry.Member.DeclaringType)) {
-                                                               member_already_exists = true;
-                                                               break;
-                                                       }
-                                               }
-                                               if (member_already_exists)
+                                       var filter = new MemberFilter (candidate);
+                                       foreach (var item in applicable) {
+                                               // TODO: Need to test what should happen for OVERRIDE_UNCHECKED
+                                               if ((item.Modifiers & (Modifiers.OVERRIDE | Modifiers.OVERRIDE_UNCHECKED | Modifiers.VIRTUAL)) == 0)
                                                        continue;
-                                       }
 
-                                       global.Add (entry.Member);
+                                               if (filter.Equals (item)) {
+                                                       --not_implemented_count;
+                                                       abstract_methods [i] = null;
+                                                       break;
+                                               }
+                                       }
                                }
                        }
 
-                       Timer.StopTimer (TimerType.CachedLookup);
+                       if (not_implemented_count == abstract_methods.Count) {
+                               type.MemberCache.missing_abstract = abstract_methods;
+                               return type.MemberCache.missing_abstract;
+                       }
 
-                       // If we have a method cache and we aren't already doing a method-only
-                       // search, we restart in method-only search mode if the first match is
-                       // a method.  This ensures that we return a MemberInfo with the correct
-                       // ReflectedType for inherited methods.
-                       if (do_method_search && (global.Count > 0)){
-                               using_global = false;
+                       var not_implemented = new MethodSpec[not_implemented_count];
+                       int counter = 0;
+                       foreach (var m in abstract_methods) {
+                               if (m == null)
+                                       continue;
 
-                               return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
+                               not_implemented[counter++] = m;
                        }
 
-                       using_global = false;
-                       MemberInfo [] copy = new MemberInfo [global.Count];
-                       global.CopyTo (copy);
-                       return copy;
+                       type.MemberCache.missing_abstract = not_implemented;
+                       return type.MemberCache.missing_abstract;
                }
 
-               /// <summary>
-               /// Returns true if iterface exists in any base interfaces (ifaces)
-               /// </summary>
-               static bool IsInterfaceBaseInterface (Type[] ifaces, Type ifaceToFind)
+               static string GetLookupName (MemberSpec ms)
                {
-                       foreach (Type iface in ifaces) {
-                               if (iface == ifaceToFind)
-                                       return true;
+                       if (ms.Kind == MemberKind.Indexer)
+                               return IndexerNameAlias;
 
-                               Type[] base_ifaces = TypeManager.GetInterfaces (iface);
-                               if (base_ifaces.Length > 0 && IsInterfaceBaseInterface (base_ifaces, ifaceToFind))
-                                       return true;
-                       }
-                       return false;
-               }
-               
-               // find the nested type @name in @this.
-               public Type FindNestedType (string name)
-               {
-                       List<CacheEntry> applicable;
-                       if (!member_hash.TryGetValue (name, out applicable))
-                               return null;
-                       
-                       for (int i = applicable.Count-1; i >= 0; i--) {
-                               CacheEntry entry = applicable [i];
-                               if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
-                                       return (Type) entry.Member;
+                       if (ms.Kind == MemberKind.Constructor) {
+                               if (ms.IsStatic)
+                                       return ConstructorInfo.TypeConstructorName;
+
+                               return ConstructorInfo.ConstructorName;
                        }
-                       
-                       return null;
+
+                       return ms.Name;
                }
 
-               public MemberInfo FindBaseEvent (Type invocation_type, string name)
+               static string GetLookupName (MemberCore mc)
                {
-                       List<CacheEntry> applicable;
-                       if (!member_hash.TryGetValue (name, out applicable))
-                               return null;
+                       if (mc is Indexer)
+                               return IndexerNameAlias;
 
-                       //
-                       // Walk the chain of events, starting from the top.
-                       //
-                       for (int i = applicable.Count - 1; i >= 0; i--) 
-                       {
-                               CacheEntry entry = applicable [i];
-                               if ((entry.EntryType & EntryType.Event) == 0)
-                                       continue;
-                               
-                               EventInfo ei = (EventInfo)entry.Member;
-                               return ei.GetAddMethod (true);
-                       }
+                       if (mc is Constructor)
+                               return ConstructorInfo.ConstructorName;
 
-                       return null;
+                       return mc.MemberName.Name;
                }
 
                //
-               // Looks for extension methods with defined name and extension type
+               // Inflates all member cache nested types
                //
-               public List<MethodSpec> FindExtensionMethods (Assembly thisAssembly, Type extensionType, string name, bool publicOnly)
+               public void InflateTypes (MemberCache inflated_cache, TypeParameterInflator inflator)
                {
-                       List<CacheEntry> entries;
-                       if (method_hash != null)
-                               method_hash.TryGetValue (name, out entries);
-                       else {
-                               member_hash.TryGetValue (name, out entries);
-                       }
-
-                       if (entries == null)
-                               return null;
-
-                       EntryType entry_type = EntryType.Static | EntryType.Method | EntryType.NotExtensionMethod;
-                       EntryType found_entry_type = entry_type & ~EntryType.NotExtensionMethod;
+                       foreach (var item in member_hash) {
+                               IList<MemberSpec> inflated_members = null;
+                               for (int i = 0; i < item.Value.Count; ++i ) {
+                                       var member = item.Value[i];
 
-                       List<MethodSpec> candidates = null;
-                       foreach (CacheEntry entry in entries) {
-                               if ((entry.EntryType & entry_type) == found_entry_type) {
-                                       MethodBase mb = (MethodBase)entry.Member;
-
-                                       // Simple accessibility check
-                                       if ((entry.EntryType & EntryType.Public) == 0 && publicOnly) {
-                                               MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
-                                               if (ma != MethodAttributes.Assembly && ma != MethodAttributes.FamORAssem)
-                                                       continue;
-                                               
-                                               if (!TypeManager.IsThisOrFriendAssembly (thisAssembly, mb.DeclaringType.Assembly))
-                                                       continue;
-                                       }
+                                       // FIXME: When inflating members refering nested types before they are inflated
+                                       if (member == null)
+                                               continue;
 
-                                       IMethodData md = TypeManager.GetMethod (mb);
-                                       AParametersCollection pd = md == null ?
-                                               TypeManager.GetParameterData (mb) : md.ParameterInfo;
+                                       if ((member.Kind & MemberKind.NestedMask) != 0 &&
+                                               (member.Modifiers & Modifiers.COMPILER_GENERATED) == 0) {
+                                               if (inflated_members == null) {
+                                                       inflated_members = new MemberSpec[item.Value.Count];
+                                                       inflated_cache.member_hash.Add (item.Key, inflated_members);
+                                               }
 
-                                       Type ex_type = pd.ExtensionMethodType;
-                                       if (ex_type == null) {
-                                               entry.EntryType |= EntryType.NotExtensionMethod;
-                                               continue;
+                                               inflated_members [i] = member.InflateMember (inflator);
                                        }
-
-                                       if (candidates == null)
-                                               candidates = new List<MethodSpec> (2);
-                                       candidates.Add (Import.CreateMethod (mb));
                                }
                        }
-
-                       return candidates;
                }
-               
-               //
-               // This finds the method or property for us to override. invocation_type is the type where
-               // the override is going to be declared, name is the name of the method/property, and
-               // param_types is the parameters, if any to the method or property
+
                //
-               // Because the MemberCache holds members from this class and all the base classes,
-               // we can avoid tons of reflection stuff.
+               // Inflates all open type members, requires InflateTypes to be called before
                //
-               public MemberInfo FindMemberToOverride (Type invocation_type, string name, AParametersCollection parameters, GenericMethod generic_method, bool is_property)
+               public void InflateMembers (MemberCache cacheToInflate, TypeSpec inflatedType, TypeParameterInflator inflator)
                {
-                       List<CacheEntry> applicable;
-                       if (method_hash != null && !is_property)
-                               method_hash.TryGetValue (name, out applicable);
-                       else
-                               member_hash.TryGetValue (name, out applicable);
-                       
-                       if (applicable == null)
-                               return null;
-                       //
-                       // Walk the chain of methods, starting from the top.
-                       //
-                       for (int i = applicable.Count - 1; i >= 0; i--) {
-                               CacheEntry entry = applicable [i];
-                               
-                               if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
-                                       continue;
+                       var inflated_member_hash = cacheToInflate.member_hash;
+                       Dictionary<MethodSpec, MethodSpec> accessor_relation = null;
+                       List<MemberSpec> accessor_members = null;
 
-                               PropertyInfo pi = null;
-                               MethodInfo mi = null;
-                               FieldInfo fi = null;
-                               AParametersCollection cmp_attrs;
-                               
-                               if (is_property) {
-                                       if ((entry.EntryType & EntryType.Field) != 0) {
-                                               fi = (FieldInfo)entry.Member;
-                                               cmp_attrs = ParametersCompiled.EmptyReadOnlyParameters;
-                                       } else {
-                                               pi = (PropertyInfo) entry.Member;
-                                               cmp_attrs = TypeManager.GetParameterData (pi);
-                                       }
-                               } else {
-                                       mi = (MethodInfo) entry.Member;
-                                       cmp_attrs = TypeManager.GetParameterData (mi);
-                               }
+                       foreach (var item in member_hash) {
+                               var members = item.Value;
+                               IList<MemberSpec> inflated_members = null;
+                               for (int i = 0; i < members.Count; ++i ) {
+                                       var member = members[i];
+
+                                       //
+                                       // All nested types have been inflated earlier except for
+                                       // compiler types which are created later and could miss InflateTypes
+                                       //
+                                       if ((member.Kind & MemberKind.NestedMask) != 0 &&
+                                               (member.Modifiers & Modifiers.COMPILER_GENERATED) == 0) {
+                                               if (inflated_members == null)
+                                                       inflated_members = inflated_member_hash[item.Key];
 
-                               if (fi != null) {
-                                       // TODO: Almost duplicate !
-                                       // Check visibility
-                                       switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
-                                       case FieldAttributes.PrivateScope:
                                                continue;
-                                       case FieldAttributes.Private:
+                                       }
+
+                                       //
+                                       // Clone the container first
+                                       //
+                                       if (inflated_members == null) {
+                                               inflated_members = new MemberSpec [item.Value.Count];
+                                               inflated_member_hash.Add (item.Key, inflated_members);
+                                       }
+
+                                       var local_inflator = inflator;
+
+                                       if (member.DeclaringType != inflatedType) {
                                                //
-                                               // A private method is Ok if we are a nested subtype.
-                                               // The spec actually is not very clear about this, see bug 52458.
+                                               // Don't inflate non generic interface members
+                                               // merged into generic interface
                                                //
-                                               if (!invocation_type.Equals (entry.Container.Type) &&
-                                                   !TypeManager.IsNestedChildOf (invocation_type, entry.Container.Type))
+                                               if (!member.DeclaringType.IsGeneric) {
+                                                       inflated_members [i] = member;
                                                        continue;
-                                               break;
-                                       case FieldAttributes.FamANDAssem:
-                                       case FieldAttributes.Assembly:
+                                               }
+
                                                //
-                                               // Check for assembly methods
+                                               // Needed when inflating flatten interfaces. It inflates
+                                               // container type only, type parameters are already done
                                                //
-                                               if (fi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
-                                                       continue;
-                                               break;
+                                               // Handles cases like:
+                                               //
+                                               // interface I<T> {}
+                                               // interface I<U, V> : I<U> {}
+                                               // 
+                                               // class C: I<int, bool> {}
+                                               //
+                                               var inflated_parent = inflator.Inflate (member.DeclaringType);
+                                               if (inflated_parent != inflator.TypeInstance)
+                                                       local_inflator = new TypeParameterInflator (inflator, inflated_parent);
                                        }
-                                       return entry.Member;
-                               }
 
-                               //
-                               // Check the arguments
-                               //
-                               if (cmp_attrs.Count != parameters.Count)
-                                       continue;
-       
-                               int j;
-                               for (j = 0; j < cmp_attrs.Count; ++j) {
                                        //
-                                       // LAMESPEC: No idea why `params' modifier is ignored
+                                       // Inflate every member, its parent is now different
                                        //
-                                       if ((parameters.FixedParameters [j].ModFlags & ~Parameter.Modifier.PARAMS) != 
-                                               (cmp_attrs.FixedParameters [j].ModFlags & ~Parameter.Modifier.PARAMS))
-                                               break;
-
-                                       if (!TypeManager.IsEqual (parameters.Types [j], cmp_attrs.Types [j]))
-                                               break;
-                               }
+                                       var inflated = member.InflateMember (local_inflator);
+                                       inflated_members [i] = inflated;
 
-                               if (j < cmp_attrs.Count)
-                                       continue;
+                                       if (member is PropertySpec || member is EventSpec) {
+                                               if (accessor_members == null)
+                                                       accessor_members = new List<MemberSpec> ();
 
-                               //
-                               // check generic arguments for methods
-                               //
-                               if (mi != null) {
-                                       Type [] cmpGenArgs = TypeManager.GetGenericArguments (mi);
-                                       if (generic_method == null && cmpGenArgs != null && cmpGenArgs.Length != 0)
-                                               continue;
-                                       if (generic_method != null && cmpGenArgs != null && cmpGenArgs.Length != generic_method.TypeParameters.Length)
+                                               accessor_members.Add (inflated);
                                                continue;
-                               }
+                                       }
 
-                               //
-                               // get one of the methods because this has the visibility info.
-                               //
-                               if (is_property) {
-                                       mi = pi.GetGetMethod (true);
-                                       if (mi == null)
-                                               mi = pi.GetSetMethod (true);
+                                       if (member.IsAccessor) {
+                                               if (accessor_relation == null)
+                                                       accessor_relation = new Dictionary<MethodSpec, MethodSpec> ();
+                                               accessor_relation.Add ((MethodSpec) member, (MethodSpec) inflated);
+                                       }
                                }
-                               
-                               //
-                               // Check visibility
-                               //
-                               switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
-                               case MethodAttributes.PrivateScope:
-                                       continue;
-                               case MethodAttributes.Private:
-                                       //
-                                       // A private method is Ok if we are a nested subtype.
-                                       // The spec actually is not very clear about this, see bug 52458.
-                                       //
-                                       if (!invocation_type.Equals (entry.Container.Type) &&
-                                           !TypeManager.IsNestedChildOf (invocation_type, entry.Container.Type))
-                                               continue;
-                                       break;
-                               case MethodAttributes.FamANDAssem:
-                               case MethodAttributes.Assembly:
-                                       //
-                                       // Check for assembly methods
-                                       //
-                                       if (!TypeManager.IsThisOrFriendAssembly (invocation_type.Assembly, mi.DeclaringType.Assembly))
+                       }
+
+                       if (accessor_members != null) {
+                               foreach (var member in accessor_members) {
+                                       var prop = member as PropertySpec;
+                                       if (prop != null) {
+                                               if (prop.Get != null)
+                                                       prop.Get = accessor_relation[prop.Get];
+                                               if (prop.Set != null)
+                                                       prop.Set = accessor_relation[prop.Set];
+
                                                continue;
-                                       break;
+                                       }
+
+                                       var ev = (EventSpec) member;
+                                       ev.AccessorAdd = accessor_relation[ev.AccessorAdd];
+                                       ev.AccessorRemove = accessor_relation[ev.AccessorRemove];
                                }
-                               return entry.Member;
                        }
-                       
-                       return null;
                }
 
-               /// <summary>
-               /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
-               /// We handle two cases. The first is for types without parameters (events, field, properties).
-               /// The second are methods, indexers and this is why ignore_complex_types is here.
-               /// The latest param is temporary hack. See DoDefineMembers method for more info.
-               /// </summary>
-               public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
-               {
-                       List<CacheEntry> applicable = null;
-                       if (method_hash != null)
-                               method_hash.TryGetValue (name, out applicable);
-                       if (applicable != null) {
-                               for (int i = applicable.Count - 1; i >= 0; i--) {
-                                       CacheEntry entry = (CacheEntry) applicable [i];
-                                       if ((entry.EntryType & EntryType.Public) != 0)
-                                               return entry.Member;
-                               }
-                       }
-                       if (member_hash == null)
-                               return null;
-
-                       if (member_hash.TryGetValue (name, out applicable)) {
-                               for (int i = applicable.Count - 1; i >= 0; i--) {
-                                       CacheEntry entry = (CacheEntry) applicable [i];
-                                       if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
-                                               if (ignore_complex_types) {
-                                                       if ((entry.EntryType & EntryType.Method) != 0)
-                                                               continue;
-                                                       // Does exist easier way how to detect indexer ?
-                                                       if ((entry.EntryType & EntryType.Property) != 0) {
-                                                               AParametersCollection arg_types = TypeManager.GetParameterData ((PropertyInfo)entry.Member);
-                                                               if (arg_types.Count > 0)
-                                                                       continue;
-                                                       }
-                                               }
-                                               return entry.Member;
-                                       }
-                               }
-                       }
-                       return null;
-               }
-
-
-               /// <summary>
-               /// Builds low-case table for CLS Compliance test
-               /// </summary>
-               public Dictionary<string, object> GetPublicMembers ()
-               {
-                       if (locase_table != null)
-                               return locase_table;
-
-                       locase_table = new Dictionary<string, object> ();
-                       foreach (var entry in member_hash) {
-                               var members = entry.Value;
-                               for (int ii = 0; ii < members.Count; ++ii) {
-                                       CacheEntry member_entry = members [ii];
-                                       if ((member_entry.EntryType & EntryType.Public) == 0)
-                                               continue;
-                                       // TODO: Does anyone know easier way how to detect that member is internal ?
-                                       switch (member_entry.EntryType & EntryType.MaskType) {
-                                       case EntryType.Constructor:
-                                               continue;
-                                               
-                                       case EntryType.Field:
-                                               if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
-                                                       continue;
-                                               break;
-                                               
-                                       case EntryType.Method:
-                                               if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
+               //
+               // For imported class method do additional validation to be sure that metadata
+               // override flag was correct
+               //
+               static bool IsRealMethodOverride (MethodSpec ms)
+               {
+                       IList<MemberSpec> candidates;
+                       var dt = ms.DeclaringType;
+                       while (dt.BaseType != null) {
+                               var base_cache = dt.BaseType.MemberCache;
+                               if (base_cache.member_hash.TryGetValue (ms.Name, out candidates)) {
+                                       foreach (var candidate in candidates) {
+                                               if (candidate.Kind != ms.Kind)
                                                        continue;
-                                               break;
-                                               
-                                       case EntryType.Property:
-                                               PropertyInfo pi = (PropertyInfo)member_entry.Member;
-                                               if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
+
+                                               if (candidate.Arity != ms.Arity)
                                                        continue;
-                                               break;
-                                               
-                                       case EntryType.Event:
-                                               EventInfo ei = (EventInfo)member_entry.Member;
-                                               MethodInfo mi = ei.GetAddMethod ();
-                                               if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
+
+                                               if (!TypeSpecComparer.Override.IsEqual (((MethodSpec) candidate).Parameters, ms.Parameters))
                                                        continue;
-                                               break;
-                                       }
-                                       string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
-                                       locase_table [lcase] = member_entry.Member;
-                                       break;
-                               }
-                       }
-                       return locase_table;
-               }
-               public IDictionary<string, List<CacheEntry>> Members {
-                       get {
-                               return member_hash;
-                       }
-               }
-               /// <summary>
-               /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
-               /// </summary>
-               /// 
-               // TODO: refactor as method is always 'this'
-               public static void VerifyClsParameterConflict (IList<CacheEntry> al, MethodCore method, MemberInfo this_builder, Report Report)
-               {
-                       EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
-                       for (int i = 0; i < al.Count; ++i) {
-                               var entry = al [i];
-               
-                               // skip itself
-                               if (entry.Member == this_builder)
-                                       continue;
-               
-                               if ((entry.EntryType & tested_type) != tested_type)
-                                       continue;
-               
-                               MethodBase method_to_compare = (MethodBase)entry.Member;
-                               AttributeTester.Result result = AttributeTester.AreOverloadedMethodParamsClsCompliant (
-                                       method.Parameters, TypeManager.GetParameterData (method_to_compare));
-
-                               if (result == AttributeTester.Result.Ok)
-                                       continue;
-
-                               IMethodData md = TypeManager.GetMethod (method_to_compare);
-
-                               // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
-                               // However it is exactly what csc does.
-                               if (md != null && !md.IsClsComplianceRequired ())
-                                       continue;
-               
-                               Report.SymbolRelatedToPreviousError (entry.Member);
-                               switch (result) {
-                               case AttributeTester.Result.RefOutArrayError:
-                                       Report.Warning (3006, 1, method.Location,
-                                                       "Overloaded method `{0}' differing only in ref or out, or in array rank, is not CLS-compliant",
-                                                       method.GetSignatureForError ());
-                                       continue;
-                               case AttributeTester.Result.ArrayArrayError:
-                                       Report.Warning (3007, 1, method.Location,
-                                                       "Overloaded method `{0}' differing only by unnamed array types is not CLS-compliant",
-                                                       method.GetSignatureForError ());
-                                       continue;
+
+                                               // Everything matches except modifiers, it's not correct soverride
+                                               if ((candidate.Modifiers & Modifiers.AccessibilityMask) != (ms.Modifiers & Modifiers.AccessibilityMask))
+                                                       return false;
+
+                                               return true;
+                                       }
                                }
 
-                               throw new NotImplementedException (result.ToString ());
-                       }
-               }
+                               dt = dt.BaseType;
+                       }
 
-               public bool CheckExistingMembersOverloads (MemberCore member, string name, ParametersCompiled parameters, Report Report)
+                       return false;
+               }
+
+               //
+               // Checks all appropriate container members for CLS compliance
+               //
+               public void VerifyClsCompliance (TypeSpec container, Report report)
                {
-                       List<CacheEntry> entries;
-                       if (!member_hash.TryGetValue (name, out entries))
-                               return true;
+                       if (locase_members != null)
+                               return;
 
-                       int method_param_count = parameters.Count;
-                       for (int i = entries.Count - 1; i >= 0; --i) {
-                               CacheEntry ce = (CacheEntry) entries [i];
+                       if (container.BaseType == null) {
+                               locase_members = new Dictionary<string, MemberSpec[]> (member_hash.Count); // StringComparer.OrdinalIgnoreCase);
+                       } else {
+                               container.BaseType.MemberCache.VerifyClsCompliance (container.BaseType, report);
+                               locase_members = new Dictionary<string, MemberSpec[]> (container.BaseType.MemberCache.locase_members); //, StringComparer.OrdinalIgnoreCase);
+                       }
 
-                               if (ce.Container != member.Parent.PartialContainer)
-                                       return true;
+                       var is_imported_type = container.MemberDefinition.IsImported;
+                       foreach (var entry in container.MemberCache.member_hash) {
+                               for (int i = 0; i < entry.Value.Count; ++i ) {
+                                       var name_entry = entry.Value[i];
+                                       if ((name_entry.Modifiers & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
+                                               continue;
 
-                               Type [] p_types;
-                               AParametersCollection pd;
-                               if ((ce.EntryType & EntryType.Property) != 0) {
-                                       pd = TypeManager.GetParameterData ((PropertyInfo) ce.Member);
-                                       p_types = pd.Types;
-                               } else {
-                                       MethodBase mb = (MethodBase) ce.Member;
-               
-                                       // TODO: This is more like a hack, because we are adding generic methods
-                                       // twice with and without arity name
-                                       if (TypeManager.IsGenericMethod (mb) && !member.MemberName.IsGeneric)
+                                       if ((name_entry.Modifiers & (Modifiers.OVERRIDE | Modifiers.COMPILER_GENERATED)) != 0)
                                                continue;
 
-                                       pd = TypeManager.GetParameterData (mb);
-                                       p_types = pd.Types;
+                                       if ((name_entry.Kind & MemberKind.MaskType) == 0)
+                                               continue;
+
+                                       if (name_entry.MemberDefinition.IsNotCLSCompliant ())
+                                           continue;
+
+                                       IParametersMember p_a = name_entry as IParametersMember;
+                                       if (p_a != null && !name_entry.IsAccessor) {
+                                               if (!is_imported_type) {
+                                                       var p_a_pd = p_a.Parameters;
+                                                       for (int ii = i + 1; ii < entry.Value.Count; ++ii) {
+                                                               var checked_entry = entry.Value[ii];
+                                                               IParametersMember p_b = checked_entry as IParametersMember;
+                                                               if (p_b == null)
+                                                                       continue;
+
+                                                               if (p_a_pd.Count != p_b.Parameters.Count)
+                                                                       continue;
+
+                                                               if (checked_entry.IsAccessor)
+                                                                       continue;
+
+                                                               var res = ParametersCompiled.IsSameClsSignature (p_a.Parameters, p_b.Parameters);
+                                                               if (res != 0) {
+                                                                       var last = GetLaterDefinedMember (checked_entry, name_entry);
+                                                                       if (last == checked_entry.MemberDefinition) {
+                                                                               report.SymbolRelatedToPreviousError (name_entry);
+                                                                       } else {
+                                                                               report.SymbolRelatedToPreviousError (checked_entry);
+                                                                       }
+
+                                                                       if ((res & 1) != 0) {
+                                                                               report.Warning (3006, 1, last.Location,
+                                                                                               "Overloaded method `{0}' differing only in ref or out, or in array rank, is not CLS-compliant",
+                                                                                               name_entry.GetSignatureForError ());
+                                                                       }
+
+                                                                       if ((res & 2) != 0) {
+                                                                               report.Warning (3007, 1, last.Location,
+                                                                                       "Overloaded method `{0}' differing only by unnamed array types is not CLS-compliant",
+                                                                                       name_entry.GetSignatureForError ());
+                                                                       }
+                                                               }
+                                                       }
+                                               }
+                                       }
+
+                                       if (i > 0 || name_entry.Kind == MemberKind.Constructor || name_entry.Kind == MemberKind.Indexer)
+                                               continue;
+
+                                       var name_entry_locase = name_entry.Name.ToLowerInvariant ();
+
+                                       MemberSpec[] found;
+                                       if (!locase_members.TryGetValue (name_entry_locase, out found)) {
+                                               found = new MemberSpec[] { name_entry };
+                                               locase_members.Add (name_entry_locase, found);
+                                       } else {
+                                               bool same_names_only = true;
+                                               foreach (var f in found) {
+                                                       if (f.Name == name_entry.Name)
+                                                               continue;
+
+//                                                     if (f.IsAccessor && name_entry.IsAccessor)
+//                                                             continue;
+
+                                                       same_names_only = false;
+                                                       if (!is_imported_type) {
+                                                               var last = GetLaterDefinedMember (f, name_entry);
+                                                               if (last == f.MemberDefinition) {
+                                                                       report.SymbolRelatedToPreviousError (name_entry);
+                                                               } else {
+                                                                       report.SymbolRelatedToPreviousError (f);
+                                                               }
+
+                                                               report.Warning (3005, 1, last.Location,
+                                                                       "Identifier `{0}' differing only in case is not CLS-compliant", last.GetSignatureForError ());
+                                                       }
+                                               }
+
+                                               if (!same_names_only) {
+                                                       Array.Resize (ref found, found.Length + 1);
+                                                       found[found.Length - 1] = name_entry;
+                                                       locase_members[name_entry_locase] = found;
+                                               }
+                                       }
                                }
+                       }
+               }
 
-                               if (p_types.Length != method_param_count)
+               //
+               // Local report helper to issue correctly ordered members stored in hashtable
+               //
+               static MemberCore GetLaterDefinedMember (MemberSpec a, MemberSpec b)
+               {
+                       var mc_a = a.MemberDefinition as MemberCore;
+                       var mc_b = b.MemberDefinition as MemberCore;
+                       if (mc_a == null)
+                               return mc_b;
+
+                       if (mc_b == null)
+                               return mc_a;
+
+                       if (mc_a.Location.File != mc_a.Location.File)
+                               return mc_b;
+
+                       return mc_b.Location.Row > mc_a.Location.Row ? mc_b : mc_a;
+               }
+
+               public bool CheckExistingMembersOverloads (MemberCore member, AParametersCollection parameters)
+               {
+                       var name = GetLookupName (member);
+                       var imb = member as InterfaceMemberBase;
+                       if (imb != null && imb.IsExplicitImpl) {
+                               name = imb.GetFullName (name);
+                       }
+
+                       return CheckExistingMembersOverloads (member, name, parameters);
+               }
+
+               public bool CheckExistingMembersOverloads (MemberCore member, string name, AParametersCollection parameters)
+               {
+                       IList<MemberSpec> entries;
+                       if (!member_hash.TryGetValue (name, out entries))
+                               return false;
+
+                       var Report = member.Compiler.Report;
+
+                       int method_param_count = parameters.Count;
+                       for (int i = entries.Count - 1; i >= 0; --i) {
+                               var ce = entries[i];
+                               var pm = ce as IParametersMember;
+                               var pd = pm == null ? ParametersCompiled.EmptyReadOnlyParameters : pm.Parameters;
+                               if (pd.Count != method_param_count)
+                                       continue;
+
+                               if (ce.Arity != member.MemberName.Arity)
                                        continue;
 
+                               // Ignore merged interface members
+                               if (member.Parent.PartialContainer != ce.DeclaringType.MemberDefinition)
+                                       continue;
+
+                               var p_types = pd.Types;
                                if (method_param_count > 0) {
                                        int ii = method_param_count - 1;
-                                       Type type_a, type_b;
+                                       TypeSpec type_a, type_b;
                                        do {
                                                type_a = parameters.Types [ii];
                                                type_b = p_types [ii];
 
-                                               if (TypeManager.IsGenericParameter (type_a) && type_a.DeclaringMethod != null)
-                                                       type_a = typeof (TypeParameter);
-
-                                               if (TypeManager.IsGenericParameter (type_b) && type_b.DeclaringMethod != null)
-                                                       type_b = typeof (TypeParameter);
-
                                                if ((pd.FixedParameters [ii].ModFlags & Parameter.Modifier.ISBYREF) !=
                                                        (parameters.FixedParameters [ii].ModFlags & Parameter.Modifier.ISBYREF))
                                                        break;
 
-                                       } while (TypeManager.IsEqual (type_a, type_b) && ii-- != 0);
+                                       } while (TypeSpecComparer.Override.IsEqual (type_a, type_b) && ii-- != 0);
 
                                        if (ii >= 0)
                                                continue;
@@ -1389,24 +1184,21 @@ namespace Mono.CSharp {
                                        //
                                        // Operators can differ in return type only
                                        //
-                                       if (member is Operator) {
-                                               Operator op = TypeManager.GetMethod ((MethodBase) ce.Member) as Operator;
-                                               if (op != null && op.ReturnType != ((Operator) member).ReturnType)
-                                                       continue;
-                                       }
+                                       if (member is Operator && ce.Kind == MemberKind.Operator && ((MethodSpec) ce).ReturnType != ((Operator) member).ReturnType)
+                                               continue;
 
                                        //
                                        // Report difference in parameter modifiers only
                                        //
                                        if (pd != null && member is MethodCore) {
                                                ii = method_param_count;
-                                               while (ii-- != 0 && parameters.FixedParameters [ii].ModFlags == pd.FixedParameters [ii].ModFlags &&
-                                                       parameters.ExtensionMethodType == pd.ExtensionMethodType);
+                                               while (ii-- != 0 && parameters.FixedParameters[ii].ModFlags == pd.FixedParameters[ii].ModFlags &&
+                                                       parameters.ExtensionMethodType == pd.ExtensionMethodType) ;
 
                                                if (ii >= 0) {
-                                                       MethodCore mc = TypeManager.GetMethod ((MethodBase) ce.Member) as MethodCore;
-                                                       Report.SymbolRelatedToPreviousError (ce.Member);
-                                                       if ((member.ModFlags & Modifiers.PARTIAL) != 0 && (mc.ModFlags & Modifiers.PARTIAL) != 0) {
+                                                       var mc = ce as MethodSpec;
+                                                       member.Compiler.Report.SymbolRelatedToPreviousError (ce);
+                                                       if ((member.ModFlags & Modifiers.PARTIAL) != 0 && (mc.Modifiers & Modifiers.PARTIAL) != 0) {
                                                                if (parameters.HasParams || pd.HasParams) {
                                                                        Report.Error (758, member.Location,
                                                                                "A partial method declaration and partial method implementation cannot differ on use of `params' modifier");
@@ -1414,25 +1206,23 @@ namespace Mono.CSharp {
                                                                        Report.Error (755, member.Location,
                                                                                "A partial method declaration and partial method implementation must be both an extension method or neither");
                                                                }
+                                                       } else if (member is Constructor) {
+                                                               Report.Error (851, member.Location,
+                                                                       "Overloaded contructor `{0}' cannot differ on use of parameter modifiers only",
+                                                                       member.GetSignatureForError ());
                                                        } else {
-                                                               if (member is Constructor) {
-                                                                       Report.Error (851, member.Location,
-                                                                               "Overloaded contructor `{0}' cannot differ on use of parameter modifiers only",
-                                                                               member.GetSignatureForError ());
-                                                               } else {
-                                                                       Report.Error (663, member.Location,
-                                                                               "Overloaded method `{0}' cannot differ on use of parameter modifiers only",
-                                                                               member.GetSignatureForError ());
-                                                               }
+                                                               Report.Error (663, member.Location,
+                                                                       "Overloaded method `{0}' cannot differ on use of parameter modifiers only",
+                                                                       member.GetSignatureForError ());
                                                        }
                                                        return false;
                                                }
                                        }
                                }
 
-                               if ((ce.EntryType & EntryType.Method) != 0) {
+                               if ((ce.Kind & (MemberKind.Method | MemberKind.FakeMethod)) != 0) {
                                        Method method_a = member as Method;
-                                       Method method_b = TypeManager.GetMethod ((MethodBase) ce.Member) as Method;
+                                       Method method_b = ce.MemberDefinition as Method;
                                        if (method_a != null && method_b != null && (method_a.ModFlags & method_b.ModFlags & Modifiers.PARTIAL) != 0) {
                                                const Modifiers partial_modifiers = Modifiers.STATIC | Modifiers.UNSAFE;
                                                if (method_a.IsPartialDefinition == method_b.IsPartialImplementation) {
@@ -1440,7 +1230,10 @@ namespace Mono.CSharp {
                                                                method_a.Parent.IsUnsafe && method_b.Parent.IsUnsafe) {
                                                                if (method_a.IsPartialImplementation) {
                                                                        method_a.SetPartialDefinition (method_b);
-                                                                       entries.RemoveAt (i);
+                                                                       if (entries.Count == 1)
+                                                                               member_hash.Remove (name);
+                                                                       else
+                                                                               entries.RemoveAt (i);
                                                                } else {
                                                                        method_b.SetPartialDefinition (method_a);
                                                                        method_a.caching_flags |= MemberCore.Flags.PartialDefinitionExists;
@@ -1448,52 +1241,51 @@ namespace Mono.CSharp {
                                                                continue;
                                                        }
 
-                                                       if ((method_a.ModFlags & Modifiers.STATIC) != (method_b.ModFlags & Modifiers.STATIC)) {
-                                                               Report.SymbolRelatedToPreviousError (ce.Member);
+                                                       if (method_a.IsStatic != method_b.IsStatic) {
+                                                               Report.SymbolRelatedToPreviousError (ce);
                                                                Report.Error (763, member.Location,
                                                                        "A partial method declaration and partial method implementation must be both `static' or neither");
                                                        }
 
-                                                       Report.SymbolRelatedToPreviousError (ce.Member);
+                                                       Report.SymbolRelatedToPreviousError (ce);
                                                        Report.Error (764, member.Location,
                                                                "A partial method declaration and partial method implementation must be both `unsafe' or neither");
                                                        return false;
                                                }
 
-                                               Report.SymbolRelatedToPreviousError (ce.Member);
+                                               Report.SymbolRelatedToPreviousError (ce);
                                                if (method_a.IsPartialDefinition) {
                                                        Report.Error (756, member.Location, "A partial method `{0}' declaration is already defined",
                                                                member.GetSignatureForError ());
-                                               } else {
-                                                       Report.Error (757, member.Location, "A partial method `{0}' implementation is already defined",
-                                                               member.GetSignatureForError ());
                                                }
 
+                                               Report.Error (757, member.Location, "A partial method `{0}' implementation is already defined",
+                                                       member.GetSignatureForError ());
                                                return false;
                                        }
 
-                                       Report.SymbolRelatedToPreviousError (ce.Member);
-                                       IMethodData duplicate_member = TypeManager.GetMethod ((MethodBase) ce.Member);
-                                       if (member is Operator && duplicate_member is Operator) {
-                                               Report.Error (557, member.Location, "Duplicate user-defined conversion in type `{0}'",
-                                                       member.Parent.GetSignatureForError ());
-                                               return false;
-                                       }
+                                       Report.SymbolRelatedToPreviousError (ce);
 
                                        bool is_reserved_a = member is AbstractPropertyEventMethod || member is Operator;
-                                       bool is_reserved_b = duplicate_member is AbstractPropertyEventMethod || duplicate_member is Operator;
+                                       bool is_reserved_b = ((MethodSpec) ce).IsReservedMethod;
 
                                        if (is_reserved_a || is_reserved_b) {
                                                Report.Error (82, member.Location, "A member `{0}' is already reserved",
                                                        is_reserved_a ?
-                                                       TypeManager.GetFullNameSignature (ce.Member) :
+                                                       ce.GetSignatureForError () :
                                                        member.GetSignatureForError ());
                                                return false;
                                        }
                                } else {
-                                       Report.SymbolRelatedToPreviousError (ce.Member);
+                                       Report.SymbolRelatedToPreviousError (ce);
                                }
-                               
+
+                               if (member is Operator && ce.Kind == MemberKind.Operator) {
+                                       Report.Error (557, member.Location, "Duplicate user-defined conversion in type `{0}'",
+                                               member.Parent.GetSignatureForError ());
+                                       return false;
+                               }
+
                                Report.Error (111, member.Location,
                                        "A member `{0}' is already defined. Rename this member or use different parameter types",
                                        member.GetSignatureForError ());
index 7c7e12e10858008c4526f82f1abd9d05550b1ffe..2932ae27837bc9a3c08adf772539b8eb3e1ba96f 100644 (file)
@@ -20,6 +20,7 @@ using System.Runtime.InteropServices;
 using System.Security;
 using System.Security.Permissions;
 using System.Text;
+using System.Linq;
 
 #if NET_2_1
 using XmlElement = System.Object;
@@ -31,9 +32,9 @@ using Mono.CompilerServices.SymbolWriter;
 
 namespace Mono.CSharp {
 
-       public abstract class MethodCore : InterfaceMemberBase
+       public abstract class MethodCore : InterfaceMemberBase, IParametersMember
        {
-               public readonly ParametersCompiled Parameters;
+               protected ParametersCompiled parameters;
                protected ToplevelBlock block;
                protected MethodSpec spec;
 
@@ -42,23 +43,27 @@ namespace Mono.CSharp {
                        MemberName name, Attributes attrs, ParametersCompiled parameters)
                        : base (parent, generic, type, mod, allowed_mod, name, attrs)
                {
-                       Parameters = parameters;
+                       this.parameters = parameters;
                }
 
                //
                //  Returns the System.Type array for the parameters of this method
                //
-               public Type [] ParameterTypes {
+               public TypeSpec [] ParameterTypes {
                        get {
-                               return Parameters.Types;
+                               return parameters.Types;
                        }
                }
 
                public ParametersCompiled ParameterInfo {
                        get {
-                               return Parameters;
+                               return parameters;
                        }
                }
+
+               AParametersCollection IParametersMember.Parameters {
+                       get { return parameters; }
+               }
                
                public ToplevelBlock Block {
                        get {
@@ -72,7 +77,7 @@ namespace Mono.CSharp {
 
                public CallingConventions CallingConventions {
                        get {
-                               CallingConventions cc = Parameters.CallingConvention;
+                               CallingConventions cc = parameters.CallingConvention;
                                if (!IsInterface)
                                        if ((ModFlags & Modifiers.STATIC) == 0)
                                                cc |= CallingConventions.HasThis;
@@ -83,10 +88,25 @@ namespace Mono.CSharp {
                        }
                }
 
+               protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
+               {
+                       bool res = base.CheckOverrideAgainstBase (base_member);
+
+                       //
+                       // Check that the permissions are not being changed
+                       //
+                       if (!CheckAccessModifiers (this, base_member)) {
+                               Error_CannotChangeAccessModifiers (this, base_member);
+                               res = false;
+                       }
+
+                       return res;
+               }
+
                protected override bool CheckBase ()
                {
                        // Check whether arguments were correct.
-                       if (!DefineParameters (Parameters))
+                       if (!DefineParameters (parameters))
                                return false;
 
                        return base.CheckBase ();
@@ -98,7 +118,7 @@ namespace Mono.CSharp {
                //
                public override string GetDocCommentName (DeclSpace ds)
                {
-                       return DocUtil.GetMethodDocCommentName (this, Parameters, ds);
+                       return DocUtil.GetMethodDocCommentName (this, parameters, ds);
                }
 
                //
@@ -140,74 +160,84 @@ namespace Mono.CSharp {
                        if (!base.VerifyClsCompliance ())
                                return false;
 
-                       if (Parameters.HasArglist) {
+                       if (parameters.HasArglist) {
                                Report.Warning (3000, 1, Location, "Methods with variable arguments are not CLS-compliant");
                        }
 
-                       if (!AttributeTester.IsClsCompliant (MemberType)) {
+                       if (member_type != null && !member_type.IsCLSCompliant ()) {
                                Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
                                        GetSignatureForError ());
                        }
 
-                       Parameters.VerifyClsCompliance (this);
+                       parameters.VerifyClsCompliance (this);
                        return true;
                }
        }
 
-       interface IGenericMethodDefinition : IMemberDefinition
+       public interface IGenericMethodDefinition : IMemberDefinition
        {
-               MethodInfo MakeGenericMethod (Type[] targs);
+               TypeParameterSpec[] TypeParameters { get; }
+               int TypeParametersCount { get; }
+
+//             MethodInfo MakeGenericMethod (TypeSpec[] targs);
        }
 
-       public class MethodSpec : MemberSpec
+       public class MethodSpec : MemberSpec, IParametersMember
        {
                MethodBase metaInfo;
-               readonly AParametersCollection parameters;
+               AParametersCollection parameters;
+               TypeSpec returnType;
+
+               TypeSpec[] targs;
+               TypeParameterSpec[] constraints;
 
-               public MethodSpec (MemberKind kind, IMemberDefinition details, MethodBase info, AParametersCollection parameters, Modifiers modifiers)
-                       : base (kind, details, info.Name, modifiers)
+               public MethodSpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition details, TypeSpec returnType,
+                       MethodBase info, AParametersCollection parameters, Modifiers modifiers)
+                       : base (kind, declaringType, details, modifiers)
                {
-                       this.MetaInfo = info;
+                       this.metaInfo = info;
                        this.parameters = parameters;
+                       this.returnType = returnType;
                }
 
-               public override Type DeclaringType {
+               #region Properties
+
+               public override int Arity {
                        get {
-                               return MetaInfo.DeclaringType;
+                               return IsGeneric ? GenericDefinition.TypeParametersCount : 0;
                        }
                }
 
-               public Type[] GetGenericArguments ()
-               {
-                       return MetaInfo.GetGenericArguments ();
-               }
-
-               public MethodSpec Inflate (Type[] targs)
-               {
-                       // TODO: Only create MethodSpec and inflate parameters, defer the call for later
-                       var mb = ((IGenericMethodDefinition) definition).MakeGenericMethod (targs);
+               public TypeParameterSpec[] Constraints {
+                       get {
+                               if (constraints == null && IsGeneric)
+                                       constraints = GenericDefinition.TypeParameters;
 
-                       // TODO: Does not work on .NET
-                       var par = TypeManager.GetParameterData (mb);
+                               return constraints;
+                       }
+               }
 
-                       return new MethodSpec (Kind, definition, mb, par, Modifiers);
+               public bool IsConstructor {
+                       get {
+                               return Kind == MemberKind.Constructor;
+                       }
                }
 
-               public bool IsAbstract {
+               public IGenericMethodDefinition GenericDefinition {
                        get {
-                               return (Modifiers & Modifiers.ABSTRACT) != 0;
+                               return (IGenericMethodDefinition) definition;
                        }
                }
 
-               public bool IsConstructor {
+               public bool IsExtensionMethod {
                        get {
-                               return MetaInfo.IsConstructor;
+                               return IsStatic && parameters.HasExtensionMethodType;
                        }
                }
 
-               public bool IsGenericMethod {
+               public bool IsSealed {
                        get {
-                               return MetaInfo.IsGenericMethod;
+                               return (Modifiers & Modifiers.SEALED) != 0;
                        }
                }
 
@@ -218,24 +248,185 @@ namespace Mono.CSharp {
                        }
                }
 
-               public MethodBase MetaInfo {
+               public bool IsReservedMethod {
                        get {
-                               return metaInfo;
+                               return Kind == MemberKind.Operator || IsAccessor;
                        }
-                       set {
-                               metaInfo = value;
+               }
+
+               TypeSpec IInterfaceMemberSpec.MemberType {
+                       get {
+                               return returnType;
                        }
                }
 
                public AParametersCollection Parameters {
-                       get { return parameters; }
+                       get { 
+                               return parameters;
+                       }
                }
 
-               public Type ReturnType {
+               public TypeSpec ReturnType {
                        get {
-                               return IsConstructor ?
-                                       TypeManager.void_type : ((MethodInfo) MetaInfo).ReturnType;
+                               return returnType;
+                       }
+               }
+
+               public TypeSpec[] TypeArguments {
+                       get {
+                               return targs;
+                       }
+               }
+
+               #endregion
+
+               public MethodSpec GetGenericMethodDefinition ()
+               {
+                       if (!IsGeneric && !DeclaringType.IsGeneric)
+                               return this;
+
+                       return MemberCache.GetMember (declaringType, this);
+               }
+
+               public MethodBase GetMetaInfo ()
+               {
+                       if ((state & StateFlags.PendingMetaInflate) != 0) {
+                               if (DeclaringType.IsTypeBuilder) {
+                                       if (IsConstructor)
+                                               metaInfo = TypeBuilder.GetConstructor (DeclaringType.GetMetaInfo (), (ConstructorInfo) metaInfo);
+                                       else
+                                               metaInfo = TypeBuilder.GetMethod (DeclaringType.GetMetaInfo (), (MethodInfo) metaInfo);
+                               } else {
+                                       metaInfo = MethodInfo.GetMethodFromHandle (metaInfo.MethodHandle, DeclaringType.GetMetaInfo ().TypeHandle);
+                               }
+
+                               state &= ~StateFlags.PendingMetaInflate;
+                       }
+
+                       if ((state & StateFlags.PendingMakeMethod) != 0) {
+                               metaInfo = ((MethodInfo) metaInfo).MakeGenericMethod (targs.Select (l => l.GetMetaInfo ()).ToArray ());
+                               state &= ~StateFlags.PendingMakeMethod;
                        }
+
+                       if (Kind == MemberKind.FakeMethod)
+                               throw new InternalErrorException ("Emitting fake method");
+
+                       return metaInfo;
+               }
+
+               public override string GetSignatureForError ()
+               {
+                       string name;
+                       if (IsConstructor) {
+                               name = DeclaringType.GetSignatureForError () + "." + DeclaringType.Name;
+                       } else if (Kind == MemberKind.Operator) {
+                               var op = Operator.GetType (Name).Value;
+                               if (op == Operator.OpType.Implicit || op == Operator.OpType.Explicit) {
+                                       name = DeclaringType.GetSignatureForError () + "." + Operator.GetName (op) + " operator " + returnType.GetSignatureForError ();
+                               } else {
+                                       name = DeclaringType.GetSignatureForError () + ".operator " + Operator.GetName (op);
+                               }
+                       } else if (IsAccessor) {
+                               int split = Name.IndexOf ('_');
+                               name = Name.Substring (split + 1);
+                               var postfix = Name.Substring (0, split);
+                               if (split == 3) {
+                                       var pc = parameters.Count;
+                                       if (pc > 0 && postfix == "get") {
+                                               name = "this" + parameters.GetSignatureForError ("[", "]", pc);
+                                       } else if (pc > 1 && postfix == "set") {
+                                               name = "this" + parameters.GetSignatureForError ("[", "]", pc - 1);
+                                       }
+                               }
+
+                               return DeclaringType.GetSignatureForError () + "." + name + "." + postfix;
+                       } else {
+                               name = base.GetSignatureForError ();
+                               if (targs != null)
+                                       name += "<" + TypeManager.CSharpName (targs) + ">";
+                               else if (IsGeneric)
+                                       name += "<" + TypeManager.CSharpName (GenericDefinition.TypeParameters) + ">";
+                       }
+
+                       return name + parameters.GetSignatureForError ();
+               }
+
+               public override MemberSpec InflateMember (TypeParameterInflator inflator)
+               {
+                       var ms = (MethodSpec) base.InflateMember (inflator);
+                       ms.returnType = inflator.Inflate (returnType);
+                       ms.parameters = parameters.Inflate (inflator);
+                       if (IsGeneric)
+                               ms.constraints = TypeParameterSpec.InflateConstraints (inflator, GenericDefinition.TypeParameters);
+
+                       return ms;
+               }
+
+               public MethodSpec MakeGenericMethod (params TypeSpec[] targs)
+               {
+                       if (targs == null)
+                               throw new ArgumentNullException ();
+// TODO MemberCache
+//                     if (generic_intances != null && generic_intances.TryGetValue (targs, out ginstance))
+//                             return ginstance;
+
+                       //if (generic_intances == null)
+                       //    generic_intances = new Dictionary<TypeSpec[], Method> (TypeSpecArrayComparer.Default);
+
+                       var inflator = new TypeParameterInflator (DeclaringType, GenericDefinition.TypeParameters, targs);
+
+                       var inflated = (MethodSpec) MemberwiseClone ();
+                       inflated.declaringType = inflator.TypeInstance;
+                       inflated.returnType = inflator.Inflate (returnType);
+                       inflated.parameters = parameters.Inflate (inflator);
+                       inflated.targs = targs;
+                       inflated.constraints = TypeParameterSpec.InflateConstraints (inflator, constraints ?? GenericDefinition.TypeParameters);
+                       inflated.state |= StateFlags.PendingMakeMethod;
+
+                       //                      if (inflated.parent == null)
+                       //                              inflated.parent = parent;
+
+                       //generic_intances.Add (targs, inflated);
+                       return inflated;
+               }
+
+               public MethodSpec Mutate (TypeParameterMutator mutator)
+               {
+                       var targs = TypeArguments;
+                       if (targs != null)
+                               targs = mutator.Mutate (targs);
+
+                       var decl = DeclaringType;
+                       if (DeclaringType.IsGenericOrParentIsGeneric) {
+                               decl = mutator.Mutate (decl);
+                       }
+
+                       if (targs == TypeArguments && decl == DeclaringType)
+                               return this;
+
+                       var ms = (MethodSpec) MemberwiseClone ();
+                       if (decl != DeclaringType) {
+                               // Gets back MethodInfo in case of metaInfo was inflated
+                               ms.metaInfo = MemberCache.GetMember (DeclaringType.GetDefinition (), this).metaInfo;
+
+                               ms.declaringType = decl;
+                               ms.state |= StateFlags.PendingMetaInflate;
+                       }
+
+                       if (targs != null) {
+                               ms.targs = targs;
+                               ms.state |= StateFlags.PendingMakeMethod;
+                       }
+
+                       return ms;
+               }
+
+               public void SetMetaInfo (MethodInfo info)
+               {
+                       if (this.metaInfo != null)
+                               throw new InternalErrorException ("MetaInfo reset");
+
+                       this.metaInfo = info;
                }
        }
 
@@ -256,13 +447,13 @@ namespace Mono.CSharp {
                {
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.Target == AttributeTargets.ReturnValue) {
                                if (return_attributes == null)
                                        return_attributes = new ReturnParameter (this, MethodBuilder, Location);
 
-                               return_attributes.ApplyAttributeBuilder (a, cb, pa);
+                               return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
                                return;
                        }
 
@@ -286,7 +477,7 @@ namespace Mono.CSharp {
                        }
 
                        if (MethodBuilder != null)
-                               MethodBuilder.SetCustomAttribute (cb);
+                               MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
                }
 
                public override AttributeTargets AttributeTargets {
@@ -297,28 +488,12 @@ namespace Mono.CSharp {
 
                protected override bool CheckForDuplications ()
                {
-                       string name = GetFullName (MemberName);
-                       if (MemberName.IsGeneric)
-                               name = MemberName.MakeName (name, MemberName.TypeArguments);
-
-                       return Parent.MemberCache.CheckExistingMembersOverloads (this, name, Parameters, Report);
+                       return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
                }
 
                public virtual EmitContext CreateEmitContext (ILGenerator ig)
                {
-                       return new EmitContext (
-                               this, ig, MemberType);
-               }
-
-               protected override bool ResolveMemberType ()
-               {
-                       if (GenericMethod != null) {
-                               MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
-                               if (!GenericMethod.Define (this))
-                                       return false;
-                       }
-
-                       return base.ResolveMemberType ();
+                       return new EmitContext (this, ig, MemberType);
                }
 
                public override bool Define ()
@@ -329,15 +504,6 @@ namespace Mono.CSharp {
                        if (!CheckBase ())
                                return false;
 
-                       if (block != null && block.IsIterator && !(Parent is IteratorStorey)) {
-                               //
-                               // Current method is turned into automatically generated
-                               // wrapper which creates an instance of iterator
-                               //
-                               Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags, Compiler);
-                               ModFlags |= Modifiers.DEBUGGER_HIDDEN;
-                       }
-
                        MemberKind kind;
                        if (this is Operator)
                                kind = MemberKind.Operator;
@@ -352,11 +518,10 @@ namespace Mono.CSharp {
 
                                // Add to member cache only when a partial method implementation has not been found yet
                                if ((caching_flags & Flags.PartialDefinitionExists) == 0) {
-                                       MethodBase mb = new PartialMethodDefinitionInfo (this);
+//                                     MethodBase mb = new PartialMethodDefinitionInfo (this);
 
-                                       spec = new MethodSpec (kind, this, mb, Parameters, ModFlags);
-                                       Parent.MemberCache.AddMember (mb, spec);
-                                       TypeManager.AddMethod (mb, this);
+                                       spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, null, parameters, ModFlags);
+                                       Parent.MemberCache.AddMember (spec);
                                }
 
                                return true;
@@ -370,12 +535,11 @@ namespace Mono.CSharp {
                                        
                        MethodBuilder = MethodData.MethodBuilder;
 
-                       spec = new MethodSpec (kind, this, MethodBuilder, Parameters, ModFlags);
-
-                       if (TypeManager.IsGenericMethod (MethodBuilder))
-                               Parent.MemberCache.AddGenericMember (MethodBuilder, this);
+                       spec = new MethodSpec (kind, Parent.Definition, this, ReturnType, MethodBuilder, parameters, ModFlags);
+                       if (MemberName.Arity > 0)
+                               spec.IsGeneric = true;
                        
-                       Parent.MemberCache.AddMember (MethodBuilder, spec);
+                       Parent.MemberCache.AddMember (this, MethodBuilder.Name, spec);
 
                        return true;
                }
@@ -387,8 +551,8 @@ namespace Mono.CSharp {
                        CheckAbstractAndExtern (block != null);
 
                        if ((ModFlags & Modifiers.PARTIAL) != 0) {
-                               for (int i = 0; i < Parameters.Count; ++i) {
-                                       IParameterData p = Parameters.FixedParameters [i];
+                               for (int i = 0; i < parameters.Count; ++i) {
+                                       IParameterData p = parameters.FixedParameters [i];
                                        if (p.ModFlags == Parameter.Modifier.OUT) {
                                                Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
                                                        GetSignatureForError ());
@@ -404,10 +568,8 @@ namespace Mono.CSharp {
                {
                        base.DoMemberTypeDependentChecks ();
 
-                       if (!TypeManager.IsGenericParameter (MemberType)) {
-                               if (MemberType.IsAbstract && MemberType.IsSealed) {
-                                       Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
-                               }
+                       if (MemberType.IsStatic) {
+                               Error_StaticReturnType ();
                        }
                }
 
@@ -418,14 +580,14 @@ namespace Mono.CSharp {
                        if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
                                PredefinedAttributes.Get.DebuggerHidden.EmitAttribute (MethodBuilder);
 
-                       if (TypeManager.IsDynamicType (ReturnType)) {
+                       if (ReturnType == InternalType.Dynamic) {
                                return_attributes = new ReturnParameter (this, MethodBuilder, Location);
                                PredefinedAttributes.Get.Dynamic.EmitAttribute (return_attributes.Builder);
                        } else {
                                var trans_flags = TypeManager.HasDynamicTypeUsed (ReturnType);
                                if (trans_flags != null) {
                                        var pa = PredefinedAttributes.Get.DynamicTransform;
-                                       if (pa.Constructor != null || pa.ResolveConstructor (Location, TypeManager.bool_type.MakeArrayType ())) {
+                                       if (pa.Constructor != null || pa.ResolveConstructor (Location, ArrayContainer.MakeType (TypeManager.bool_type))) {
                                                return_attributes = new ReturnParameter (this, MethodBuilder, Location);
                                                return_attributes.Builder.SetCustomAttribute (
                                                        new CustomAttributeBuilder (pa.Constructor, new object [] { trans_flags }));
@@ -478,7 +640,7 @@ namespace Mono.CSharp {
 
                #region IMethodData Members
 
-               public Type ReturnType {
+               public TypeSpec ReturnType {
                        get {
                                return MemberType;
                        }
@@ -493,48 +655,36 @@ namespace Mono.CSharp {
                /// <summary>
                /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
                /// </summary>
-               public bool IsExcluded () {
-                       if ((caching_flags & Flags.Excluded_Undetected) == 0)
-                               return (caching_flags & Flags.Excluded) != 0;
+               public override string[] ConditionalConditions ()
+               {
+                       if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
+                               return null;
+
+                       if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.Excluded) != 0)
+                               return new string [0];
 
                        caching_flags &= ~Flags.Excluded_Undetected;
+                       string[] conditions;
 
                        if (base_method == null) {
                                if (OptAttributes == null)
-                                       return false;
+                                       return null;
 
                                Attribute[] attrs = OptAttributes.SearchMulti (PredefinedAttributes.Get.Conditional);
-
                                if (attrs == null)
-                                       return false;
-
-                               foreach (Attribute a in attrs) {
-                                       string condition = a.GetConditionalAttributeValue ();
-                                       if (condition == null)
-                                               return false;
-
-                                       if (Location.CompilationUnit.IsConditionalDefined (condition))
-                                               return false;
-                               }
-
-                               caching_flags |= Flags.Excluded;
-                               return true;
-                       }
+                                       return null;
 
-                       IMethodData md = TypeManager.GetMethod (TypeManager.DropGenericMethodArguments (base_method));
-                       if (md == null) {
-                               if (AttributeTester.IsConditionalMethodExcluded (base_method, Location)) {
-                                       caching_flags |= Flags.Excluded;
-                                       return true;
-                               }
-                               return false;
+                               conditions = new string[attrs.Length];
+                               for (int i = 0; i < conditions.Length; ++i)
+                                       conditions[i] = attrs[i].GetConditionalAttributeValue ();
+                       } else {
+                               conditions = base_method.MemberDefinition.ConditionalConditions();
                        }
 
-                       if (md.IsExcluded ()) {
+                       if (conditions != null)
                                caching_flags |= Flags.Excluded;
-                               return true;
-                       }
-                       return false;
+
+                       return conditions;
                }
 
                GenericMethod IMethodData.GenericMethod {
@@ -645,10 +795,52 @@ namespace Mono.CSharp {
                        : base (parent, null, return_type, mod, amod, name, attrs, parameters)
                {
                }
-               
+
+#region Properties
+
+               public override TypeParameter[] CurrentTypeParameters {
+                       get {
+                               if (GenericMethod != null)
+                                       return GenericMethod.CurrentTypeParameters;
+
+                               return null;
+                       }
+               }
+
+               public override bool HasUnresolvedConstraints {
+                       get {
+                               if (CurrentTypeParameters == null)
+                                       return false;
+
+                               // When overriding base method constraints are fetched from
+                               // base method but to find it we have to resolve parameters
+                               // to find exact base method match
+                               if (IsExplicitImpl || (ModFlags & Modifiers.OVERRIDE) != 0)
+                                       return base_method == null;
+
+                               // Even for non-override generic method constraints check has to be
+                               // delayed after all constraints are resolved
+                               return true;
+                       }
+               }
+
+               public TypeParameterSpec[] TypeParameters {
+                       get {
+                               return CurrentTypeParameters.Select (l => l.Type).ToArray ();
+                       }
+               }
+
+               public int TypeParametersCount {
+                       get {
+                               return CurrentTypeParameters == null ? 0 : CurrentTypeParameters.Length;
+                       }
+               }
+
+#endregion
+
                public override string GetSignatureForError()
                {
-                       return base.GetSignatureForError () + Parameters.GetSignatureForError ();
+                       return base.GetSignatureForError () + parameters.GetSignatureForError ();
                }
 
                void Error_DuplicateEntryPoint (Method b)
@@ -664,31 +856,32 @@ namespace Mono.CSharp {
                                ReturnType != TypeManager.int32_type)
                                return false;
 
-                       if (Parameters.Count == 0)
+                       if (parameters.IsEmpty)
                                return true;
 
-                       if (Parameters.Count > 1)
+                       if (parameters.Count > 1)
                                return false;
 
-                       Type t = Parameters.Types [0];
-                       return t.IsArray && t.GetArrayRank () == 1 &&
-                                       TypeManager.GetElementType (t) == TypeManager.string_type &&
-                                       (Parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
+                       var ac = parameters.Types [0] as ArrayContainer;
+                       return ac != null && ac.Rank == 1 && ac.Element == TypeManager.string_type &&
+                                       (parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
                }
 
-               public override FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
+               public override FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
                {
-                       TypeParameter[] tp = CurrentTypeParameters;
-                       if (tp != null) {
-                               TypeParameter t = TypeParameter.FindTypeParameter (tp, name);
-                               if (t != null)
-                                       return new TypeParameterExpr (t, loc);
+                       if (arity == 0) {
+                               TypeParameter[] tp = CurrentTypeParameters;
+                               if (tp != null) {
+                                       TypeParameter t = TypeParameter.FindTypeParameter (tp, name);
+                                       if (t != null)
+                                               return new TypeParameterExpr (t, loc);
+                               }
                        }
 
-                       return base.LookupNamespaceOrType (name, loc, ignore_cs0104);
+                       return base.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.Type == pa.Conditional) {
                                if (IsExplicitImpl) {
@@ -718,8 +911,8 @@ namespace Mono.CSharp {
                                        return;
                                }
 
-                               for (int i = 0; i < Parameters.Count; ++i) {
-                                       if (Parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
+                               for (int i = 0; i < parameters.Count; ++i) {
+                                       if (parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
                                                Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
                                                return;
                                        }
@@ -731,7 +924,7 @@ namespace Mono.CSharp {
                                return;
                        }
 
-                       base.ApplyAttributeBuilder (a, cb, pa);
+                       base.ApplyAttributeBuilder (a, ctor, cdata, pa);
                }
 
                protected override bool CheckForDuplications ()
@@ -760,25 +953,44 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               protected override bool CheckBase ()
+               protected virtual void DefineTypeParameters ()
                {
-                       if (!base.CheckBase ())
-                               return false;
+                       var tparams = CurrentTypeParameters;
 
-                       if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == Destructor.MetadataName) {
-                               Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
-                                       TypeManager.CSharpSignature (base_method));
+                       TypeParameterSpec[] base_tparams = null;
+                       if (((ModFlags & Modifiers.OVERRIDE) != 0 || IsExplicitImpl)) {
+                               if (base_method != null)
+                                       base_tparams = base_method.GenericDefinition.TypeParameters;
+                               else if (MethodData.implementing != null)
+                                       base_tparams = MethodData.implementing.GenericDefinition.TypeParameters;
                        }
 
-                       return true;
-               }
+                       for (int i = 0; i < tparams.Length; ++i) {
+                               var tp = tparams[i];
 
-               public override TypeParameter[] CurrentTypeParameters {
-                       get {
-                               if (GenericMethod != null)
-                                       return GenericMethod.CurrentTypeParameters;
+                               if (!tp.ResolveConstraints (this))
+                                       continue;
 
-                               return null;
+                               //
+                               // Copy base constraints for override/explicit methods
+                               //
+                               if (base_tparams != null) {
+                                       var base_tparam = base_tparams[i];
+                                       tp.Type.SpecialConstraint = base_tparam.SpecialConstraint;
+                                       tp.Type.TypeArguments = base_tparam.TypeArguments;
+
+                                       // TODO MemberCache: Inflate with different MVAR ?
+                                       tp.Type.Interfaces = base_tparam.Interfaces;
+                                       tp.Type.BaseType = base_tparam.BaseType;
+                               } else if (MethodData.implementing != null) {
+                                       var base_tp = MethodData.implementing.Constraints[i];
+                                       if (!tp.Type.HasSameConstraintsImplementation (base_tp)) {
+                                               Report.SymbolRelatedToPreviousError (MethodData.implementing);
+                                               Report.Error (425, Location,
+                                                       "The constraints for type parameter `{0}' of method `{1}' must match the constraints for type parameter `{2}' of interface method `{3}'. Consider using an explicit interface implementation instead",
+                                                       tp.GetSignatureForError (), GetSignatureForError (), base_tp.GetSignatureForError (), MethodData.implementing.GetSignatureForError ());
+                                       }
+                               }
                        }
                }
 
@@ -787,7 +999,7 @@ namespace Mono.CSharp {
                //
                public override bool Define ()
                {
-                       if (type_name == TypeManager.system_void_expr && Parameters.IsEmpty && Name == Destructor.MetadataName) {
+                       if (type_expr == TypeManager.system_void_expr && parameters.IsEmpty && Name == Destructor.MetadataName) {
                                Report.Warning (465, 1, Location, "Introducing `Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
                        }
 
@@ -802,18 +1014,32 @@ namespace Mono.CSharp {
                                return false;
                        }
 
-                       if (base_method != null && (ModFlags & Modifiers.NEW) == 0) {
-                               if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
-                                       Parent.PartialContainer.Mark_HasEquals ();
-                               else if (Parameters.IsEmpty && Name == "GetHashCode")
-                                       Parent.PartialContainer.Mark_HasGetHashCode ();
+                       if (CurrentTypeParameters == null) {
+                               if (base_method != null) {
+                                       if (parameters.Count == 1 && ParameterTypes[0] == TypeManager.object_type && Name == "Equals")
+                                               Parent.PartialContainer.Mark_HasEquals ();
+                                       else if (parameters.IsEmpty && Name == "GetHashCode")
+                                               Parent.PartialContainer.Mark_HasGetHashCode ();
+                               }
+                                       
+                       } else {
+                               DefineTypeParameters ();
+                       }
+
+                       if (block != null && block.IsIterator && !(Parent is IteratorStorey)) {
+                               //
+                               // Current method is turned into automatically generated
+                               // wrapper which creates an instance of iterator
+                               //
+                               Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags, Compiler);
+                               ModFlags |= Modifiers.DEBUGGER_HIDDEN;
                        }
 
                        if ((ModFlags & Modifiers.STATIC) == 0)
                                return true;
 
-                       if (Parameters.HasExtensionMethodType) {
-                               if (Parent.PartialContainer.IsStaticClass && !Parent.IsGeneric) {
+                       if (parameters.HasExtensionMethodType) {
+                               if (Parent.PartialContainer.IsStatic && !Parent.IsGeneric) {
                                        if (!Parent.IsTopLevel)
                                                Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
                                                        GetSignatureForError ());
@@ -827,6 +1053,7 @@ namespace Mono.CSharp {
 
                                        ModFlags |= Modifiers.METHOD_EXTENSION;
                                        Parent.PartialContainer.ModFlags |= Modifiers.METHOD_EXTENSION;
+                                       Spec.DeclaringType.SetExtensionMethodContainer ();
                                        CodeGen.Assembly.HasExtensionMethods = true;
                                } else {
                                        Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
@@ -884,6 +1111,24 @@ namespace Mono.CSharp {
                                                GetSignatureForError ());
                                }
 
+                               if (CurrentTypeParameters != null) {
+                                       var ge = type_expr as GenericTypeExpr;
+                                       if (ge != null)
+                                               ge.CheckConstraints (this);
+
+                                       foreach (Parameter p in parameters.FixedParameters) {
+                                               ge = p.TypeExpression as GenericTypeExpr;
+                                               if (ge != null)
+                                                       ge.CheckConstraints (this);
+                                       }
+
+                                       for (int i = 0; i < CurrentTypeParameters.Length; ++i) {
+                                               var tp = CurrentTypeParameters [i];
+                                               tp.CheckGenericConstraints ();
+                                               tp.Emit ();
+                                       }
+                               }
+
                                base.Emit ();
                                
                                if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
@@ -907,29 +1152,20 @@ namespace Mono.CSharp {
                        return base.EnableOverloadChecks (overload);
                }
 
-               public static void Error1599 (Location loc, Type t, Report Report)
+               public static void Error1599 (Location loc, TypeSpec t, Report Report)
                {
                        Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
                }
 
-               protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
+               protected override bool ResolveMemberType ()
                {
-                       MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
-                               Parent.TypeBuilder, Name, Parameters, GenericMethod, false);
-
-                       if (mi == null)
-                               return null;
-
-                       if (mi.IsSpecialName)
-                               return null;
-
-                       base_ret_type = TypeManager.TypeToCoreType (mi.ReturnType);
-                       return mi;
-               }
+                       if (GenericMethod != null) {
+                               MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
+                               if (!GenericMethod.Define (this))
+                                       return false;
+                       }
 
-               public MethodInfo MakeGenericMethod (Type[] targs)
-               {
-                       return MethodBuilder.MakeGenericMethod (targs);
+                       return base.ResolveMemberType ();
                }
 
                public void SetPartialDefinition (Method methodDefinition)
@@ -938,9 +1174,9 @@ namespace Mono.CSharp {
                        methodDefinition.partialMethodImplementation = this;
 
                        // Ensure we are always using method declaration parameters
-                       for (int i = 0; i < methodDefinition.Parameters.Count; ++i ) {
-                               Parameters [i].Name = methodDefinition.Parameters [i].Name;
-                               Parameters [i].DefaultValue = methodDefinition.Parameters [i].DefaultValue;
+                       for (int i = 0; i < methodDefinition.parameters.Count; ++i ) {
+                               parameters [i].Name = methodDefinition.parameters [i].Name;
+                               parameters [i].DefaultValue = methodDefinition.parameters [i].DefaultValue;
                        }
 
                        if (methodDefinition.attributes == null)
@@ -952,20 +1188,6 @@ namespace Mono.CSharp {
                                attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
                        }
                }
-
-               protected override bool VerifyClsCompliance ()
-               {
-                       if (!base.VerifyClsCompliance ())
-                               return false;
-
-                       if (!Parameters.IsEmpty) {
-                               var al = Parent.PartialContainer.MemberCache.Members [Name];
-                               if (al.Count > 1)
-                                       MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder, Report);
-                       }
-
-                       return true;
-               }
        }
 
        public abstract class ConstructorInitializer : ExpressionStatement
@@ -994,8 +1216,8 @@ namespace Mono.CSharp {
                {
                        eclass = ExprClass.Value;
 
-                       // TODO: ec.GetSignatureForError ()
-                       ConstructorBuilder caller_builder = ((Constructor) ec.MemberContext).ConstructorBuilder;
+                       // FIXME: Hack
+                       var caller_builder = (Constructor) ec.MemberContext;
 
                        if (argument_list != null) {
                                bool dynamic;
@@ -1021,9 +1243,9 @@ namespace Mono.CSharp {
                                        return this;
 
                                type = ec.CurrentType.BaseType;
-                               if (TypeManager.IsStruct (ec.CurrentType)) {
+                               if (ec.CurrentType.IsStruct) {
                                        ec.Report.Error (522, loc,
-                                               "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
+                                               "`{0}': Struct constructors cannot call base constructors", caller_builder.GetSignatureForError ());
                                        return this;
                                }
                        } else {
@@ -1038,8 +1260,8 @@ namespace Mono.CSharp {
                        }
 
                        base_constructor_group = MemberLookupFinal (
-                               ec, null, type, ConstructorBuilder.ConstructorName, MemberTypes.Constructor,
-                               BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
+                               ec, null, type, ConstructorBuilder.ConstructorName, 0, MemberKind.Constructor,
+                               BindingRestriction.AccessibleOnly | BindingRestriction.DeclaredOnly,
                                loc) as MethodGroupExpr;
                        
                        if (base_constructor_group == null)
@@ -1056,8 +1278,10 @@ namespace Mono.CSharp {
                        
                        var base_ctor = base_constructor_group.BestCandidate;
 
-                       if (base_ctor.MetaInfo == caller_builder){
-                               ec.Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
+                       // TODO MemberCache: Does it work for inflated types ?
+                       if (base_ctor == caller_builder.Spec){
+                               ec.Report.Error (516, loc, "Constructor `{0}' cannot call itself",
+                                       caller_builder.GetSignatureForError ());
                        }
                                                
                        return this;
@@ -1147,14 +1371,14 @@ namespace Mono.CSharp {
                public bool IsDefault ()
                {
                        if ((ModFlags & Modifiers.STATIC) != 0)
-                               return Parameters.IsEmpty;
-                       
-                       return Parameters.IsEmpty &&
+                               return parameters.IsEmpty;
+
+                       return parameters.IsEmpty &&
                                        (Initializer is ConstructorBaseInitializer) &&
                                        (Initializer.Arguments == null);
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.IsValidSecurityAttribute ()) {
                                if (declarative_security == null) {
@@ -1168,13 +1392,13 @@ namespace Mono.CSharp {
                                is_external_implementation = true;
                        }
 
-                       ConstructorBuilder.SetCustomAttribute (cb);
+                       ConstructorBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
                }
 
                protected override bool CheckBase ()
                {
                        if ((ModFlags & Modifiers.STATIC) != 0) {
-                               if (!Parameters.IsEmpty) {
+                               if (!parameters.IsEmpty) {
                                        Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
                                                GetSignatureForError ());
                                        return false;
@@ -1185,19 +1409,16 @@ namespace Mono.CSharp {
                        }
 
                        // Check whether arguments were correct.
-                       if (!DefineParameters (Parameters))
+                       if (!DefineParameters (parameters))
                                return false;
 
                        if ((caching_flags & Flags.MethodOverloadsExist) != 0)
-                               Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorInfo.ConstructorName,
-                                       Parameters, Report);
+                               Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
 
-                       if (Parent.PartialContainer.Kind == MemberKind.Struct) {
-                               if (Parameters.Count == 0) {
-                                       Report.Error (568, Location, 
-                                               "Structs cannot contain explicit parameterless constructors");
-                                       return false;
-                               }
+                       if (Parent.PartialContainer.Kind == MemberKind.Struct && parameters.IsEmpty) {
+                               Report.Error (568, Location, 
+                                       "Structs cannot contain explicit parameterless constructors");
+                               return false;
                        }
 
                        CheckProtectedModifier ();
@@ -1213,25 +1434,12 @@ namespace Mono.CSharp {
                        if (ConstructorBuilder != null)
                                return true;
 
-                       MethodAttributes ca = (MethodAttributes.RTSpecialName |
-                                              MethodAttributes.SpecialName);
+                       var ca = MethodAttributes.RTSpecialName | MethodAttributes.SpecialName;
                        
                        if ((ModFlags & Modifiers.STATIC) != 0) {
                                ca |= MethodAttributes.Static | MethodAttributes.Private;
                        } else {
-                               ca |= MethodAttributes.HideBySig;
-
-                               if ((ModFlags & Modifiers.PUBLIC) != 0)
-                                       ca |= MethodAttributes.Public;
-                               else if ((ModFlags & Modifiers.PROTECTED) != 0){
-                                       if ((ModFlags & Modifiers.INTERNAL) != 0)
-                                               ca |= MethodAttributes.FamORAssem;
-                                       else 
-                                               ca |= MethodAttributes.Family;
-                               } else if ((ModFlags & Modifiers.INTERNAL) != 0)
-                                       ca |= MethodAttributes.Assembly;
-                               else
-                                       ca |= MethodAttributes.Private;
+                               ca |= ModifiersExtensions.MethodAttr (ModFlags);
                        }
 
                        if (!CheckAbstractAndExtern (block != null))
@@ -1243,20 +1451,11 @@ namespace Mono.CSharp {
 
                        ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
                                ca, CallingConventions,
-                               Parameters.GetEmitTypes ());
+                               parameters.GetMetaInfo ());
 
-                       spec = new MethodSpec (MemberKind.Constructor, this, ConstructorBuilder, Parameters, ModFlags);
-
-                       if (Parent.PartialContainer.IsComImport) {
-                               if (!IsDefault ()) {
-                                       Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
-                                               Parent.GetSignatureForError ());
-                               }
-                               ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
-                       }
+                       spec = new MethodSpec (MemberKind.Constructor, Parent.Definition, this, TypeManager.void_type, ConstructorBuilder, parameters, ModFlags);
                        
-                       Parent.MemberCache.AddMember (ConstructorBuilder, spec);
-                       TypeManager.AddMethod (ConstructorBuilder, this);
+                       Parent.MemberCache.AddMember (spec);
                        
                        // It's here only to report an error
                        if (block != null && block.IsIterator) {
@@ -1272,6 +1471,14 @@ namespace Mono.CSharp {
                //
                public override void Emit ()
                {
+                       if (Parent.PartialContainer.IsComImport) {
+                               if (!IsDefault ()) {
+                                       Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
+                                               Parent.GetSignatureForError ());
+                               }
+                               ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
+                       }
+
                        if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
                                PredefinedAttributes.Get.DebuggerHidden.EmitAttribute (ConstructorBuilder);
 
@@ -1310,12 +1517,12 @@ namespace Mono.CSharp {
                                }
                        }
 
-                       Parameters.ApplyAttributes (ConstructorBuilder);
+                       parameters.ApplyAttributes (ConstructorBuilder);
 
                        SourceMethod source = SourceMethod.Create (Parent, ConstructorBuilder, block);
 
                        if (block != null) {
-                               if (block.Resolve (null, bc, Parameters, this)) {
+                               if (block.Resolve (null, bc, parameters, this)) {
                                        EmitContext ec = new EmitContext (this, ConstructorBuilder.GetILGenerator (), bc.ReturnType);
                                        ec.With (EmitContext.Options.ConstructorScope, true);
 
@@ -1340,15 +1547,16 @@ namespace Mono.CSharp {
                        block = null;
                }
 
-               // Is never override
-               protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
+               protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate)
                {
+                       // Is never override
+                       bestCandidate = null;
                        return null;
                }
 
                public override string GetSignatureForError()
                {
-                       return base.GetSignatureForError () + Parameters.GetSignatureForError ();
+                       return base.GetSignatureForError () + parameters.GetSignatureForError ();
                }
 
                public override string[] ValidAttributeTargets {
@@ -1362,20 +1570,15 @@ namespace Mono.CSharp {
                        if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
                                return false;
                        }
-                       
-                       if (!Parameters.IsEmpty) {
-                               var al = Parent.MemberCache.Members [ConstructorInfo.ConstructorName];
-                               if (al.Count > 2)
-                                       MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder, Report);
-                               if (TypeManager.IsSubclassOf (Parent.TypeBuilder, TypeManager.attribute_type)) {
-                                       foreach (Type param in Parameters.Types) {
-                                               if (param.IsArray) {
-                                                       return true;
-                                               }
+
+                       if (!parameters.IsEmpty && Parent.Definition.IsAttribute) {
+                               foreach (TypeSpec param in parameters.Types) {
+                                       if (param.IsArray) {
+                                               return true;
                                        }
                                }
                        }
+
                        has_compliant_args = true;
                        return true;
                }
@@ -1388,7 +1591,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               public Type ReturnType {
+               public TypeSpec ReturnType {
                        get {
                                return MemberType;
                        }
@@ -1424,19 +1627,16 @@ namespace Mono.CSharp {
                CallingConventions CallingConventions { get; }
                Location Location { get; }
                MemberName MethodName { get; }
-               Type ReturnType { get; }
+               TypeSpec ReturnType { get; }
                GenericMethod GenericMethod { get; }
                ParametersCompiled ParameterInfo { get; }
+               MethodSpec Spec { get; }
 
                Attributes OptAttributes { get; }
                ToplevelBlock Block { get; set; }
 
                EmitContext CreateEmitContext (ILGenerator ig);
-               ObsoleteAttribute GetObsoleteAttribute ();
                string GetSignatureForError ();
-               bool IsExcluded ();
-               bool IsClsComplianceRequired ();
-               void SetIsUsed ();
                void EmitExtraSymbolInfo (SourceMethod source);
        }
 
@@ -1452,7 +1652,7 @@ namespace Mono.CSharp {
                //
                // Are we implementing an interface ?
                //
-               public MethodInfo implementing;
+               public MethodSpec implementing;
 
                //
                // Protected data.
@@ -1460,17 +1660,17 @@ namespace Mono.CSharp {
                protected InterfaceMemberBase member;
                protected Modifiers modifiers;
                protected MethodAttributes flags;
-               protected Type declaring_type;
-               protected MethodInfo parent_method;
+               protected TypeSpec declaring_type;
+               protected MethodSpec parent_method;
 
-               MethodBuilder builder = null;
+               MethodBuilder builder;
                public MethodBuilder MethodBuilder {
                        get {
                                return builder;
                        }
                }
 
-               public Type DeclaringType {
+               public TypeSpec DeclaringType {
                        get {
                                return declaring_type;
                        }
@@ -1489,7 +1689,7 @@ namespace Mono.CSharp {
                public MethodData (InterfaceMemberBase member,
                                   Modifiers modifiers, MethodAttributes flags, 
                                   IMethodData method, MethodBuilder builder,
-                                  GenericMethod generic, MethodInfo parent_method)
+                                  GenericMethod generic, MethodSpec parent_method)
                        : this (member, modifiers, flags, method)
                {
                        this.builder = builder;
@@ -1499,13 +1699,11 @@ namespace Mono.CSharp {
 
                public bool Define (DeclSpace parent, string method_full_name, Report Report)
                {
-                       string name = method.MethodName.Basename;
-
                        TypeContainer container = parent.PartialContainer;
 
                        PendingImplementation pending = container.PendingImplementations;
                        if (pending != null){
-                               implementing = pending.IsInterfaceMethod (name, member.InterfaceType, this);
+                               implementing = pending.IsInterfaceMethod (method.MethodName, member.InterfaceType, this);
 
                                if (member.InterfaceType != null){
                                        if (implementing == null){
@@ -1521,7 +1719,7 @@ namespace Mono.CSharp {
                                                }
                                                return false;
                                        }
-                                       if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
+                                       if (implementing.IsAccessor && !(method is AbstractPropertyEventMethod)) {
                                                Report.SymbolRelatedToPreviousError (implementing);
                                                Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
                                                        member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
@@ -1531,14 +1729,13 @@ namespace Mono.CSharp {
                                        if (implementing != null) {
                                                AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
                                                if (prop_method == null) {
-                                                       if (TypeManager.IsSpecialMethod (implementing)) {
+                                                       if (implementing.IsAccessor) {
                                                                Report.SymbolRelatedToPreviousError (implementing);
-                                                               Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
-                                                                       method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
-                                                                       implementing.Name.StartsWith ("get_") ? "get" : "set");
+                                                               Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}'",
+                                                                       method.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
                                                        }
                                                } else if (implementing.DeclaringType.IsInterface) {
-                                                       if (!implementing.IsSpecialName) {
+                                                       if (!implementing.IsAccessor) {
                                                                Report.SymbolRelatedToPreviousError (implementing);
                                                                Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
                                                                        method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
@@ -1548,7 +1745,7 @@ namespace Mono.CSharp {
                                                        if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
                                                                Report.SymbolRelatedToPreviousError (implementing);
                                                                Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
-                                                                       method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
+                                                                       method.GetSignatureForError (), implementing.GetSignatureForError ());
                                                                return false;
                                                        }
                                                }
@@ -1569,7 +1766,7 @@ namespace Mono.CSharp {
                                // but it wont get cleared
                                //
                                if (member.IsExplicitImpl){
-                                       if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
+                                       if (method.ParameterInfo.HasParams && !implementing.Parameters.HasParams) {
                                                Report.SymbolRelatedToPreviousError (implementing);
                                                Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
                                                        method.GetSignatureForError ());
@@ -1631,26 +1828,13 @@ namespace Mono.CSharp {
                        if (builder == null)
                                return false;
 
-                       if (container.CurrentType != null)
-                               declaring_type = container.CurrentType;
-                       else
-                               declaring_type = container.TypeBuilder;
+//                     if (container.CurrentType != null)
+//                             declaring_type = container.CurrentType;
+//                     else
+                               declaring_type = container.Definition;
 
                        if (implementing != null && member.IsExplicitImpl) {
-                                       container.TypeBuilder.DefineMethodOverride (builder, implementing);
-                       }
-
-                       TypeManager.AddMethod (builder, method);
-
-                       if (GenericMethod != null) {
-                               bool is_override = member.IsExplicitImpl |
-                                       ((modifiers & Modifiers.OVERRIDE) != 0);
-
-                               if (implementing != null)
-                                       parent_method = implementing;
-
-                               if (!GenericMethod.DefineType (GenericMethod, builder, parent_method, is_override))
-                                       return false;
+                               container.TypeBuilder.DefineMethodOverride (builder, (MethodInfo) implementing.GetMetaInfo ());
                        }
 
                        return true;
@@ -1662,11 +1846,13 @@ namespace Mono.CSharp {
                /// </summary>
                void DefineMethodBuilder (TypeContainer container, string method_name, ParametersCompiled param)
                {
+                       var return_type = method.ReturnType.GetMetaInfo ();
+                       var p_types = param.GetMetaInfo ();
+
                        if (builder == null) {
                                builder = container.TypeBuilder.DefineMethod (
                                        method_name, flags, method.CallingConventions,
-                                       method.ReturnType,
-                                       param.GetEmitTypes ());
+                                       return_type, p_types);
                                return;
                        }
 
@@ -1674,8 +1860,8 @@ namespace Mono.CSharp {
                        // Generic method has been already defined to resolve method parameters
                        // correctly when they use type parameters
                        //
-                       builder.SetParameters (param.GetEmitTypes ());
-                       builder.SetReturnType (method.ReturnType);
+                       builder.SetParameters (p_types);
+                       builder.SetReturnType (return_type);
                        if (builder.Attributes != flags) {
                                try {
                                        if (methodbuilder_attrs_field == null)
@@ -1692,16 +1878,16 @@ namespace Mono.CSharp {
                // 
                public void Emit (DeclSpace parent)
                {
-                       method.ParameterInfo.ApplyAttributes (MethodBuilder);
-
                        if (GenericMethod != null)
                                GenericMethod.EmitAttributes ();
 
+                       method.ParameterInfo.ApplyAttributes (MethodBuilder);
+
                        //
                        // clear the pending implementation flag
                        //
                        if (implementing != null)
-                               parent.PartialContainer.PendingImplementations.ImplementMethod (method.MethodName.Basename,
+                               parent.PartialContainer.PendingImplementations.ImplementMethod (method.MethodName,
                                        member.InterfaceType, this, member.IsExplicitImpl);
 
                        SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
@@ -1745,14 +1931,14 @@ namespace Mono.CSharp {
                        ModFlags |= Modifiers.PROTECTED | Modifiers.OVERRIDE;
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.Type == pa.Conditional) {
                                Error_ConditionalAttributeIsNotValid ();
                                return;
                        }
 
-                       base.ApplyAttributeBuilder (a, cb, pa);
+                       base.ApplyAttributeBuilder (a, ctor, cdata, pa);
                }
 
                protected override bool CheckBase ()
@@ -1760,17 +1946,17 @@ namespace Mono.CSharp {
                        if (!base.CheckBase ())
                                return false;
 
-                       if (Parent.PartialContainer.BaseCache == null)
+                       var base_type = Parent.PartialContainer.BaseType;
+                       if (base_type == null)
                                return true;
 
-                       Type base_type = Parent.PartialContainer.BaseCache.Container.Type;
-                       if (base_type != null && Block != null) {
-                               MethodGroupExpr method_expr = Expression.MethodLookup (Parent.Module.Compiler, Parent.TypeBuilder, base_type, MetadataName, Location);
+                       if (Block != null) {
+                               MethodGroupExpr method_expr = Expression.MethodLookup (Parent.Module.Compiler, Parent.Definition, base_type, MemberKind.Destructor, MetadataName, 0, Location);
                                if (method_expr == null)
                                        throw new NotImplementedException ();
 
                                method_expr.IsBase = true;
-                               method_expr.InstanceExpression = new CompilerGeneratedThis (Parent.TypeBuilder, Location);
+                               method_expr.InstanceExpression = new CompilerGeneratedThis (Parent.Definition, Location);
 
                                ToplevelBlock new_block = new ToplevelBlock (Compiler, Block.StartLocation);
                                new_block.EndLocation = Block.EndLocation;
@@ -1797,11 +1983,6 @@ namespace Mono.CSharp {
                        return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
                }
 
-               protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
-               {
-                       return null;
-               }
-
                public override string[] ValidAttributeTargets {
                        get {
                                return attribute_targets;
@@ -1891,18 +2072,18 @@ namespace Mono.CSharp {
                        }
                }
 
-               public Type[] ParameterTypes { 
+               public TypeSpec[] ParameterTypes { 
                        get {
                                return ParameterInfo.Types;
                        }
                }
 
                public abstract ParametersCompiled ParameterInfo { get ; }
-               public abstract Type ReturnType { get; }
+               public abstract TypeSpec ReturnType { get; }
 
                #endregion
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.Type == pa.CLSCompliant || a.Type == pa.Obsolete || a.Type == pa.Conditional) {
                                Report.Error (1667, a.Location,
@@ -1919,7 +2100,7 @@ namespace Mono.CSharp {
                        }
 
                        if (a.Target == AttributeTargets.Method) {
-                               method_data.MethodBuilder.SetCustomAttribute (cb);
+                               method_data.MethodBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
                                return;
                        }
 
@@ -1927,14 +2108,14 @@ namespace Mono.CSharp {
                                if (return_attributes == null)
                                        return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
 
-                               return_attributes.ApplyAttributeBuilder (a, cb, pa);
+                               return_attributes.ApplyAttributeBuilder (a, ctor, cdata, pa);
                                return;
                        }
 
-                       ApplyToExtraTarget (a, cb, pa);
+                       ApplyToExtraTarget (a, ctor, cdata, pa);
                }
 
-               protected virtual void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               protected virtual void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        throw new NotSupportedException ("You forgot to define special attribute target handling");
                }
@@ -1954,14 +2135,14 @@ namespace Mono.CSharp {
                        if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
                                PredefinedAttributes.Get.DebuggerHidden.EmitAttribute (method_data.MethodBuilder);
 
-                       if (TypeManager.IsDynamicType (ReturnType)) {
+                       if (ReturnType == InternalType.Dynamic) {
                                return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
                                PredefinedAttributes.Get.Dynamic.EmitAttribute (return_attributes.Builder);
                        } else {
                                var trans_flags = TypeManager.HasDynamicTypeUsed (ReturnType);
                                if (trans_flags != null) {
                                        var pa = PredefinedAttributes.Get.DynamicTransform;
-                                       if (pa.Constructor != null || pa.ResolveConstructor (Location, TypeManager.bool_type.MakeArrayType ())) {
+                                       if (pa.Constructor != null || pa.ResolveConstructor (Location, ArrayContainer.MakeType (TypeManager.bool_type))) {
                                                return_attributes = new ReturnParameter (this, method_data.MethodBuilder, Location);
                                                return_attributes.Builder.SetCustomAttribute (
                                                        new CustomAttributeBuilder (pa.Constructor, new object [] { trans_flags }));
@@ -2005,7 +2186,7 @@ namespace Mono.CSharp {
                        if (!MemberName.Equals (method.MemberName))
                                return false;
 
-                       Type[] param_types = method.ParameterTypes;
+                       TypeSpec[] param_types = method.ParameterTypes;
 
                        if (param_types == null || param_types.Length != ParameterTypes.Length)
                                return false;
@@ -2136,14 +2317,14 @@ namespace Mono.CSharp {
                        Block = block;
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.Type == pa.Conditional) {
                                Error_ConditionalAttributeIsNotValid ();
                                return;
                        }
 
-                       base.ApplyAttributeBuilder (a, cb, pa);
+                       base.ApplyAttributeBuilder (a, ctor, cdata, pa);
                }
                
                public override bool Define ()
@@ -2156,25 +2337,34 @@ namespace Mono.CSharp {
                        if (!base.Define ())
                                return false;
 
+                       if (block != null && block.IsIterator && !(Parent is IteratorStorey)) {
+                               //
+                               // Current method is turned into automatically generated
+                               // wrapper which creates an instance of iterator
+                               //
+                               Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags, Compiler);
+                               ModFlags |= Modifiers.DEBUGGER_HIDDEN;
+                       }
+
                        // imlicit and explicit operator of same types are not allowed
                        if (OperatorType == OpType.Explicit)
-                               Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), Parameters, Report);
+                               Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), parameters);
                        else if (OperatorType == OpType.Implicit)
-                               Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), Parameters, Report);
+                               Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), parameters);
 
-                       Type declaring_type = MethodData.DeclaringType;
-                       Type return_type = MemberType;
-                       Type first_arg_type = ParameterTypes [0];
+                       TypeSpec declaring_type = Parent.CurrentType;
+                       TypeSpec return_type = MemberType;
+                       TypeSpec first_arg_type = ParameterTypes [0];
                        
-                       Type first_arg_type_unwrap = first_arg_type;
+                       TypeSpec first_arg_type_unwrap = first_arg_type;
                        if (TypeManager.IsNullableType (first_arg_type))
-                               first_arg_type_unwrap = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (first_arg_type) [0]);
+                               first_arg_type_unwrap = TypeManager.GetTypeArguments (first_arg_type) [0];
                        
-                       Type return_type_unwrap = return_type;
+                       TypeSpec return_type_unwrap = return_type;
                        if (TypeManager.IsNullableType (return_type))
-                               return_type_unwrap = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (return_type) [0]);
+                               return_type_unwrap = TypeManager.GetTypeArguments (return_type) [0];
 
-                       if (TypeManager.IsDynamicType (return_type) || TypeManager.IsDynamicType (first_arg_type)) {
+                       if (return_type == InternalType.Dynamic || first_arg_type == InternalType.Dynamic) {
                                Report.Error (1964, Location,
                                        "User-defined operator `{0}' cannot convert to or from the dynamic type",
                                        GetSignatureForError ());
@@ -2192,7 +2382,7 @@ namespace Mono.CSharp {
                                        return false;
                                }
                                
-                               Type conv_type;
+                               TypeSpec conv_type;
                                if (TypeManager.IsEqual (declaring_type, return_type) || declaring_type == return_type_unwrap) {
                                        conv_type = first_arg_type;
                                } else if (TypeManager.IsEqual (declaring_type, first_arg_type) || declaring_type == first_arg_type_unwrap) {
@@ -2228,11 +2418,11 @@ namespace Mono.CSharp {
                                        }
                                }
                        } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
-                               if (first_arg_type != declaring_type || Parameters.Types [1] != TypeManager.int32_type) {
+                               if (first_arg_type != declaring_type || parameters.Types[1] != TypeManager.int32_type) {
                                        Report.Error (564, Location, "Overloaded shift operator must have the type of the first operand be the containing type, and the type of the second operand must be int");
                                        return false;
                                }
-                       } else if (Parameters.Count == 1) {
+                       } else if (parameters.Count == 1) {
                                // Checks for Unary operators
 
                                if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
@@ -2269,7 +2459,7 @@ namespace Mono.CSharp {
 
                                var second_arg_type = ParameterTypes [1];
                                if (TypeManager.IsNullableType (second_arg_type))
-                                       second_arg_type = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (second_arg_type) [0]);
+                                       second_arg_type = TypeManager.GetTypeArguments (second_arg_type) [0];
 
                                if (!TypeManager.IsEqual (second_arg_type, declaring_type)) {
                                        Report.Error (563, Location,
@@ -2290,9 +2480,10 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               // Operator cannot be override
-               protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
+               protected override MemberSpec FindBaseMember (out MemberSpec bestCandidate)
                {
+                       // Operator cannot be override
+                       bestCandidate = null;
                        return null;
                }
 
@@ -2363,136 +2554,15 @@ namespace Mono.CSharp {
                        StringBuilder sb = new StringBuilder ();
                        if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
                                sb.AppendFormat ("{0}.{1} operator {2}",
-                                       Parent.GetSignatureForError (), GetName (OperatorType), type_name.GetSignatureForError ());
+                                       Parent.GetSignatureForError (), GetName (OperatorType), type_expr.GetSignatureForError ());
                        }
                        else {
                                sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
                        }
 
-                       sb.Append (Parameters.GetSignatureForError ());
+                       sb.Append (parameters.GetSignatureForError ());
                        return sb.ToString ();
                }
        }
-
-       //
-       // This is used to compare method signatures
-       //
-       struct MethodSignature {
-               public string Name;
-               public Type RetType;
-               public Type [] Parameters;
-               
-               /// <summary>
-               ///    This delegate is used to extract methods which have the
-               ///    same signature as the argument
-               /// </summary>
-               public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
-               
-               public MethodSignature (string name, Type ret_type, Type [] parameters)
-               {
-                       Name = name;
-                       RetType = ret_type;
-
-                       if (parameters == null)
-                               Parameters = Type.EmptyTypes;
-                       else
-                               Parameters = parameters;
-               }
-
-               public override string ToString ()
-               {
-                       string pars = "";
-                       if (Parameters.Length != 0){
-                               System.Text.StringBuilder sb = new System.Text.StringBuilder ();
-                               for (int i = 0; i < Parameters.Length; i++){
-                                       sb.Append (Parameters [i]);
-                                       if (i+1 < Parameters.Length)
-                                               sb.Append (", ");
-                               }
-                               pars = sb.ToString ();
-                       }
-
-                       return String.Format ("{0} {1} ({2})", RetType, Name, pars);
-               }
-               
-               public override int GetHashCode ()
-               {
-                       return Name.GetHashCode ();
-               }
-
-               public override bool Equals (Object o)
-               {
-                       MethodSignature other = (MethodSignature) o;
-
-                       if (other.Name != Name)
-                               return false;
-
-                       if (other.RetType != RetType)
-                               return false;
-                       
-                       if (Parameters == null){
-                               if (other.Parameters == null)
-                                       return true;
-                               return false;
-                       }
-
-                       if (other.Parameters == null)
-                               return false;
-                       
-                       int c = Parameters.Length;
-                       if (other.Parameters.Length != c)
-                               return false;
-
-                       for (int i = 0; i < c; i++)
-                               if (other.Parameters [i] != Parameters [i])
-                                       return false;
-
-                       return true;
-               }
-
-               static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
-               {
-                       MethodSignature sig = (MethodSignature) filter_criteria;
-
-                       if (m.Name != sig.Name)
-                               return false;
-
-                       Type ReturnType;
-                       MethodInfo mi = m as MethodInfo;
-                       PropertyInfo pi = m as PropertyInfo;
-
-                       if (mi != null)
-                               ReturnType = mi.ReturnType;
-                       else if (pi != null)
-                               ReturnType = pi.PropertyType;
-                       else
-                               return false;
-
-                       //
-                       // we use sig.RetType == null to mean `do not check the
-                       // method return value.  
-                       //
-                       if (sig.RetType != null) {
-                               if (!TypeManager.IsEqual (ReturnType, sig.RetType))
-                                       return false;
-                       }
-
-                       Type [] args;
-                       if (mi != null)
-                               args = TypeManager.GetParameterData (mi).Types;
-                       else
-                               args = TypeManager.GetParameterData (pi).Types;
-                       Type [] sigp = sig.Parameters;
-
-                       if (args.Length != sigp.Length)
-                               return false;
-
-                       for (int i = args.Length - 1; i >= 0; i--)
-                               if (!TypeManager.IsEqual (args [i], sigp [i]))
-                                       return false;
-
-                       return true;
-               }
-       }
 }
 
index bf1e540f0b41cc189182e962ed144a8d6823c0a0..788c1f891e001036adb75aead377ccb82673af5e 100644 (file)
@@ -33,6 +33,7 @@ namespace Mono.CSharp
                // Compiler specific flags
                //
                PROPERTY_CUSTOM                 = 0x4000,
+               OVERRIDE_UNCHECKED              = 0x8000,
                PARTIAL                                 = 0x20000,
                DEFAULT_ACCESS_MODIFER  = 0x40000,
                METHOD_EXTENSION                = 0x80000,
@@ -46,6 +47,24 @@ namespace Mono.CSharp
 
        static class ModifiersExtensions
        {
+               public static string AccessibilityName (Modifiers mod)
+               {
+                       switch (mod & Modifiers.AccessibilityMask) {
+                       case Modifiers.PUBLIC:
+                               return "public";
+                       case Modifiers.PROTECTED:
+                               return "protected";
+                       case Modifiers.PROTECTED | Modifiers.INTERNAL:
+                               return "protected internal";
+                       case Modifiers.INTERNAL:
+                               return "internal";
+                       case Modifiers.PRIVATE:
+                               return "private";
+                       default:
+                               throw new NotImplementedException (mod.ToString ());
+                       }
+               }
+
                static public string Name (Modifiers i)
                {
                        string s = "";
@@ -84,26 +103,24 @@ namespace Mono.CSharp
                        return s;
                }
 
-               public static string GetDescription (MethodAttributes ma)
+               //
+               // Used by custom property accessors to check whether @modA is more restrictive than @modB
+               //
+               public static bool IsRestrictedModifier (Modifiers modA, Modifiers modB)
                {
-                       ma &= MethodAttributes.MemberAccessMask;
+                       Modifiers flags = 0;
 
-                       if (ma == MethodAttributes.Assembly)
-                               return "internal";
+                       if ((modB & Modifiers.PUBLIC) != 0) {
+                               flags = Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
+                       } else if ((modB & Modifiers.PROTECTED) != 0) {
+                               if ((modB & Modifiers.INTERNAL) != 0)
+                                       flags = Modifiers.PROTECTED | Modifiers.INTERNAL;
 
-                       if (ma == MethodAttributes.Family)
-                               return "protected";
+                               flags |= Modifiers.PRIVATE;
+                       } else if ((modB & Modifiers.INTERNAL) != 0)
+                               flags = Modifiers.PRIVATE;
 
-                       if (ma == MethodAttributes.Public)
-                               return "public";
-
-                       if (ma == MethodAttributes.FamORAssem)
-                               return "protected internal";
-
-                       if (ma == MethodAttributes.Private)
-                               return "private";
-
-                       throw new NotImplementedException (ma.ToString ());
+                       return modB != modA && (modA & (~flags)) == 0;
                }
 
                public static TypeAttributes TypeAttr (Modifiers mod_flags, bool is_toplevel)
@@ -166,18 +183,24 @@ namespace Mono.CSharp
                {
                        MethodAttributes ma = MethodAttributes.HideBySig;
 
-                       if ((mod_flags & Modifiers.PUBLIC) != 0)
+                       switch (mod_flags & Modifiers.AccessibilityMask) {
+                       case Modifiers.PUBLIC:
                                ma |= MethodAttributes.Public;
-                       else if ((mod_flags & Modifiers.PRIVATE) != 0)
+                               break;
+                       case Modifiers.PRIVATE:
                                ma |= MethodAttributes.Private;
-                       else if ((mod_flags & Modifiers.PROTECTED) != 0) {
-                               if ((mod_flags & Modifiers.INTERNAL) != 0)
-                                       ma |= MethodAttributes.FamORAssem;
-                               else 
-                                       ma |= MethodAttributes.Family;
-                       } else {
-                               if ((mod_flags & Modifiers.INTERNAL) != 0)
-                                       ma |= MethodAttributes.Assembly;
+                               break;
+                       case Modifiers.PROTECTED | Modifiers.INTERNAL:
+                               ma |= MethodAttributes.FamORAssem;
+                               break;
+                       case Modifiers.PROTECTED:
+                               ma |= MethodAttributes.Family;
+                               break;
+                       case Modifiers.INTERNAL:
+                               ma |= MethodAttributes.Assembly;
+                               break;
+                       default:
+                               throw new NotImplementedException (mod_flags.ToString ());
                        }
 
                        if ((mod_flags & Modifiers.STATIC) != 0)
@@ -191,9 +214,9 @@ namespace Mono.CSharp
                        if ((mod_flags & Modifiers.VIRTUAL) != 0)
                                ma |= MethodAttributes.Virtual;
 
-                       if ((mod_flags & Modifiers.OVERRIDE) != 0)
+                       if ((mod_flags & Modifiers.OVERRIDE) != 0) {
                                ma |= MethodAttributes.Virtual;
-                       else {
+                       else {
                                if ((ma & MethodAttributes.Virtual) != 0)
                                        ma |= MethodAttributes.NewSlot;
                        }
@@ -240,7 +263,7 @@ namespace Mono.CSharp
                                a = ((a & 2) >> 1) + (a & 5);
                                a = ((a & 4) >> 2) + (a & 3);
                                if (a > 1)
-                                       Report.Error (107, l, "More than one protection modifier specified", Report);
+                                       Report.Error (107, l, "More than one protection modifier specified");
                                
                                return mod;
                        }
@@ -257,7 +280,7 @@ namespace Mono.CSharp
 
                public static void Error_InvalidModifier (Location l, string name, Report Report)
                {
-                       Report.Error (106, l, "The modifier `" + name + "' is not valid for this item", Report);
+                       Report.Error (106, l, "The modifier `{0}' is not valid for this item", name);
                }
        }
 }
index f40d3ba2837ad0fcef427a52bf770427e0608da9..3e9140e9649e3927b8d9a298f22a787f0c927cbd 100644 (file)
 using System;
 using System.Collections.Generic;
 using System.Reflection;
+using System.Linq;
 
 namespace Mono.CSharp {
 
        public class RootNamespace : Namespace {
-               //
-               // Points to Mono's GetNamespaces method, an
-               // optimization when running on Mono to fetch all the
-               // namespaces in an assembly
-               //
-               static MethodInfo get_namespaces_method;
 
                protected readonly string alias_name;
                protected Assembly [] referenced_assemblies;
 
                Dictionary<string, Namespace> all_namespaces;
 
-               static RootNamespace ()
-               {
-                       get_namespaces_method = typeof (Assembly).GetMethod ("GetNamespaces", BindingFlags.Instance | BindingFlags.NonPublic);
-               }
-
                public RootNamespace (string alias_name)
                        : base (null, String.Empty)
                {
@@ -56,11 +46,11 @@ namespace Mono.CSharp {
                        referenced_assemblies = n;
                }
 
-               public void ComputeNamespace (CompilerContext ctx, Type extensionType)
+               public void ImportTypes (CompilerContext ctx)
                {
                        foreach (Assembly a in referenced_assemblies) {
                                try {
-                                       ComputeNamespaces (a, extensionType);
+                                       ImportAssembly (a);
                                } catch (TypeLoadException e) {
                                        ctx.Report.Error (11, Location.Null, e.Message);
                                } catch (System.IO.FileNotFoundException) {
@@ -70,77 +60,6 @@ namespace Mono.CSharp {
                        }
                }
 
-               public virtual Type LookupTypeReflection (CompilerContext ctx, string name, Location loc, bool must_be_unique)
-               {
-                       // FIXME: Breaks dynamic
-                       Assembly invocation_assembly = CodeGen.Assembly.Builder;
-
-                       Type found_type = null;
-                       foreach (Assembly a in referenced_assemblies) {
-                               Type t = GetTypeInAssembly (invocation_assembly, a, name);
-                               if (t == null)
-                                       continue;
-
-                               if (!must_be_unique)
-                                       return t;
-
-                               if (found_type == null) {
-                                       found_type = t;
-                                       continue;
-                               }
-
-                               // When type is forwarded
-                               if (t.Assembly == found_type.Assembly)
-                                       continue;                                       
-
-                               ctx.Report.SymbolRelatedToPreviousError (found_type);
-                               ctx.Report.SymbolRelatedToPreviousError (t);
-                               if (loc.IsNull) {
-                                       Error_AmbiguousPredefinedType (ctx, loc, name, found_type);
-                               } else {
-                                       ctx.Report.Error (433, loc, "The imported type `{0}' is defined multiple times", name);
-                               }
-
-                               return found_type;
-                       }
-
-                       return found_type;
-               }
-
-               //
-               // Returns the types starting with the given prefix
-               //
-               public ICollection<string> CompletionGetTypesStartingWith (string prefix)
-               {
-                       Dictionary<string, string> result = null;
-
-                       foreach (Assembly a in referenced_assemblies){
-                               Type [] mtypes = a.GetTypes ();
-
-                               foreach (Type t in mtypes){
-                                       if (t.IsNotPublic)
-                                               continue;
-                                       
-                                       string f = t.FullName;
-
-                                       if (f.StartsWith (prefix) && (result == null || !result.ContainsKey (f))){
-                                               if (result == null)
-                                                       result = new Dictionary<string, string> ();
-
-                                               result [f] = f;
-                                       }
-                               }
-                       }
-                       return result == null ? null : result.Keys;
-               }
-               
-               protected static void Error_AmbiguousPredefinedType (CompilerContext ctx, Location loc, string name, Type type)
-               {
-                       ctx.Report.Warning (1685, 1, loc,
-                               "The predefined type `{0}' is ambiguous. Using definition from `{1}'",
-                               name, type.Assembly.FullName);
-               }
-
                public void RegisterNamespace (Namespace child)
                {
                        if (child != this)
@@ -158,74 +77,43 @@ namespace Mono.CSharp {
                                GetNamespace (dotted_name, true);
                }
 
-               void RegisterExtensionMethodClass (Type t)
-               {
-                       string n = t.Namespace;
-                       Namespace ns = null;
-                       if (n == null)
-                               ns = GlobalRootNamespace.Instance;
-                       else
-                               all_namespaces.TryGetValue (n, out ns);
-
-                       if (ns == null)
-                               ns = GetNamespace (n, true);
-                       ns.RegisterExternalExtensionMethodClass (t);
-               }
-
-               void ComputeNamespaces (Assembly assembly, Type extensionType)
+               public void ImportAssembly (Assembly assembly)
                {
-                       bool contains_extension_methods = extensionType != null && assembly.IsDefined (extensionType, false);
-                       if (get_namespaces_method != null) {
-                               string [] namespaces = (string []) get_namespaces_method.Invoke (assembly, null);
-                               foreach (string ns in namespaces)
-                                       RegisterNamespace (ns);
-
-                               if (!contains_extension_methods)
-                                       return;
-                       }
-
-                       foreach (Type t in assembly.GetTypes ()) {
-                               if ((t.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute &&
-                                       contains_extension_methods && t.IsDefined (extensionType, false))
-                                       RegisterExtensionMethodClass (t);
-
-                               if (get_namespaces_method == null)
-                                       RegisterNamespace (t.Namespace);
-                       }
-               }
+                       Type extension_type = null;
+                       var all_attributes = CustomAttributeData.GetCustomAttributes (assembly);
+                       foreach (var attr in all_attributes) {
+                               var dt = attr.Constructor.DeclaringType;
+                               if (dt.Name == "ExtensionAttribute" && dt.Namespace == "System.Runtime.CompilerServices") {
+                                       extension_type = dt;
+                                       break;
+                               }
+                       }
 
-               protected static Type GetTypeInAssembly (Assembly invocation, Assembly assembly, string name)
-               {
-                       if (assembly == null)
-                               throw new ArgumentNullException ("assembly");
-                       if (name == null)
-                               throw new ArgumentNullException ("name");
-                       Type t = assembly.GetType (name);
-                       if (t == null)
-                               return null;
+                       Namespace ns = this;
+                       string prev_namespace = null;
+                       foreach (var t in assembly.GetTypes ()) {
+                               if (t.IsNested)
+                                       continue;
 
-                       if (t.IsPointer)
-                               throw new InternalErrorException ("Use GetPointerType() to get a pointer");
+                               if (t.Name[0] == '<')
+                                       continue;
 
-                       TypeAttributes ta = t.Attributes & TypeAttributes.VisibilityMask;
-                       if (ta == TypeAttributes.NestedPrivate)
-                               return null;
+                               var it = Import.CreateType (t);
+                               if (it == null)
+                                       continue;
 
-                       if ((ta == TypeAttributes.NotPublic ||
-                            ta == TypeAttributes.NestedAssembly ||
-                            ta == TypeAttributes.NestedFamANDAssem) &&
-                           !TypeManager.IsThisOrFriendAssembly (invocation, t.Assembly))
-                               return null;
+                               if (prev_namespace != t.Namespace) {
+                                       ns = t.Namespace == null ? this : GetNamespace (t.Namespace, true);
+                                       prev_namespace = t.Namespace;
+                               }
 
-                       return t;
-               }
+                               ns.AddType (it);
 
-               public override string ToString ()
-               {
-                       return String.Format ("RootNamespace ({0}::)", alias_name);
-               }
+                               if (it.IsStatic && extension_type != null && t.IsDefined (extension_type, false)) {
+                                       it.SetExtensionMethodContainer ();
+                               }
+                       }
+               }
 
                public override string GetSignatureForError ()
                {
@@ -271,20 +159,14 @@ namespace Mono.CSharp {
                        if (m == RootContext.ToplevelTypes.Builder)
                                return;
 
-                       foreach (Type t in m.GetTypes ())
+                       foreach (var t in m.GetTypes ())
                                RegisterNamespace (t.Namespace);
                }
 
                public void ComputeNamespaces (CompilerContext ctx)
                {
-                       //
-                       // Do very early lookup because type is required when we cache
-                       // imported extension types in ComputeNamespaces
-                       //
-                       Type extension_attribute_type = TypeManager.CoreLookupType (ctx, "System.Runtime.CompilerServices", "ExtensionAttribute", MemberKind.Class, false);
-
                        foreach (RootNamespace rn in root_namespaces.Values) {
-                               rn.ComputeNamespace (ctx, extension_attribute_type);
+                               rn.ImportTypes (ctx);
                        }
                }
 
@@ -304,7 +186,7 @@ namespace Mono.CSharp {
                        retval.AddAssemblyReference (assembly);
                }
 
-               public override void Error_NamespaceDoesNotExist (Location loc, string name, IMemberContext ctx)
+               public override void Error_NamespaceDoesNotExist (Location loc, string name, int arity, IMemberContext ctx)
                {
                        ctx.Compiler.Report.Error (400, loc,
                                "The type or namespace name `{0}' could not be found in the global namespace (are you missing an assembly reference?)",
@@ -319,37 +201,6 @@ namespace Mono.CSharp {
 
                        return rn;
                }
-
-               public override Type LookupTypeReflection (CompilerContext ctx, string name, Location loc, bool must_be_unique)
-               {
-                       Type found_type = base.LookupTypeReflection (ctx, name, loc, must_be_unique);
-
-                       if (modules != null) {
-                               foreach (Module module in modules) {
-                                       Type t = module.GetType (name);
-                                       if (t == null)
-                                               continue;
-
-                                       if (found_type == null) {
-                                               found_type = t;
-                                               continue;
-                                       }
-
-                                       ctx.Report.SymbolRelatedToPreviousError (found_type);
-                                       if (loc.IsNull) {
-                                               DeclSpace ds = TypeManager.LookupDeclSpace (t);
-                                               Error_AmbiguousPredefinedType (ctx, ds.Location, name, found_type);
-                                               return found_type;
-                                       }
-                                       ctx.Report.SymbolRelatedToPreviousError (t);
-                                       ctx.Report.Warning (436, 2, loc, "The type `{0}' conflicts with the imported type `{1}'. Ignoring the imported type definition",
-                                               TypeManager.CSharpName (t), TypeManager.CSharpName (found_type));
-                                       return t;
-                               }
-                       }
-
-                       return found_type;
-               }
        }
 
        /// <summary>
@@ -362,11 +213,11 @@ namespace Mono.CSharp {
                
                Namespace parent;
                string fullname;
-               Dictionary<string, Namespace> namespaces;
-               Dictionary<string, DeclSpace> declspaces;
+               protected Dictionary<string, Namespace> namespaces;
+               protected Dictionary<string, IList<TypeSpec>> types;
                Dictionary<string, TypeExpr> cached_types;
                RootNamespace root;
-               List<Type> external_exmethod_classes;
+               bool cls_checked;
 
                public readonly MemberName MemberName;
 
@@ -379,7 +230,7 @@ namespace Mono.CSharp {
                {
                        // Expression members.
                        this.eclass = ExprClass.Namespace;
-                       this.Type = typeof (Namespace);
+                       this.Type = InternalType.FakeInternalType;
                        this.loc = Location.Null;
 
                        this.parent = parent;
@@ -415,25 +266,42 @@ namespace Mono.CSharp {
                        root.RegisterNamespace (this);
                }
 
+               #region Properties
+
+               /// <summary>
+               ///   The qualified name of the current namespace
+               /// </summary>
+               public string Name {
+                       get { return fullname; }
+               }
+
+               /// <summary>
+               ///   The parent of this namespace, used by the parser to "Pop"
+               ///   the current namespace declaration
+               /// </summary>
+               public Namespace Parent {
+                       get { return parent; }
+               }
+
+               #endregion
+
                protected override Expression DoResolve (ResolveContext ec)
                {
                        return this;
                }
 
-               public virtual void Error_NamespaceDoesNotExist (Location loc, string name, IMemberContext ctx)
+               public virtual void Error_NamespaceDoesNotExist (Location loc, string name, int arity, IMemberContext ctx)
                {
-                       if (name.IndexOf ('`') > 0) {
-                               FullNamedExpression retval = Lookup (ctx.Compiler, SimpleName.RemoveGenericArity (name), loc);
-                               if (retval != null) {
-                                       retval.Error_TypeArgumentsCannotBeUsed (ctx.Compiler.Report, loc);
-                                       return;
-                               }
-                       } else {
-                               Type t = LookForAnyGenericType (name);
-                               if (t != null) {
-                                       Error_InvalidNumberOfTypeArguments (ctx.Compiler.Report, t, loc);
-                                       return;
-                               }
+                       FullNamedExpression retval = Lookup (ctx.Compiler, name, -System.Math.Max (1, arity), loc);
+                       if (retval != null) {
+                               Error_TypeArgumentsCannotBeUsed (ctx.Compiler.Report, loc, retval.Type, arity);
+                               return;
+                       }
+
+                       Namespace ns;
+                       if (arity > 0 && namespaces.TryGetValue (name, out ns)) {
+                               ns.Error_TypeArgumentsCannotBeUsed (ctx.Compiler.Report, loc, null, arity);
+                               return;
                        }
 
                        ctx.Compiler.Report.Error (234, loc,
@@ -441,13 +309,6 @@ namespace Mono.CSharp {
                                name, GetSignatureForError ());
                }
 
-               public static void Error_InvalidNumberOfTypeArguments (Report report, Type t, Location loc)
-               {
-                       report.SymbolRelatedToPreviousError (t);
-                       report.Error (305, loc, "Using the generic type `{0}' requires `{1}' type argument(s)",
-                               TypeManager.CSharpName(t), TypeManager.GetNumberOfTypeArguments(t).ToString());
-               }
-
                public override string GetSignatureForError ()
                {
                        return fullname;
@@ -478,204 +339,318 @@ namespace Mono.CSharp {
                        return ns;
                }
 
-               public bool HasDefinition (string name)
+               TypeExpr LookupType (CompilerContext ctx, string name, int arity, Location loc)
                {
-                       return declspaces != null && declspaces.ContainsKey (name);
-               }
+                       if (types == null)
+                               return null;
 
-               TypeExpr LookupType (CompilerContext ctx, string name, Location loc)
-               {
                        TypeExpr te;
-                       if (cached_types.TryGetValue (name, out te))
+                       if (arity == 0 && cached_types.TryGetValue (name, out te))
                                return te;
 
-                       Type t = null;
-                       if (declspaces != null) {
-                               DeclSpace tdecl;
-                               if (declspaces.TryGetValue (name, out tdecl)) {
-                                       //
-                                       // Note that this is not:
-                                       //
-                                       //   t = tdecl.DefineType ()
-                                       //
-                                       // This is to make it somewhat more useful when a DefineType
-                                       // fails due to problems in nested types (more useful in the sense
-                                       // of fewer misleading error messages)
-                                       //
-                                       tdecl.DefineType ();
-                                       t = tdecl.TypeBuilder;
-
-                                       if (RootContext.EvalMode){
-                                               // Replace the TypeBuilder with a System.Type, as
-                                               // Reflection.Emit fails otherwise (we end up pretty
-                                               // much with Random type definitions later on).
-                                               Type tt = t.Assembly.GetType (t.Name);
-                                               if (tt != null)
-                                                       t = tt;
+                       IList<TypeSpec> found;
+                       if (!types.TryGetValue (name, out found))
+                               return null;
+
+                       TypeSpec best = null;
+                       foreach (var ts in found) {
+                               if (ts.Arity == arity) {
+                                       if (best == null) {
+                                               best = ts;
+                                               continue;
+                                       }
+
+                                       if (best.MemberDefinition.IsImported && ts.MemberDefinition.IsImported) {
+                                               ctx.Report.SymbolRelatedToPreviousError (best);
+                                               ctx.Report.SymbolRelatedToPreviousError (ts);
+                                               ctx.Report.Error (433, loc, "The imported type `{0}' is defined multiple times", ts.GetSignatureForError ());
+                                               break;
+                                       }
+
+                                       var pts = best as PredefinedTypeSpec;
+                                       if (pts == null)
+                                               pts = ts as PredefinedTypeSpec;
+
+                                       if (pts != null) {
+                                               ctx.Report.SymbolRelatedToPreviousError (best);
+                                               ctx.Report.SymbolRelatedToPreviousError (ts);
+                                               ctx.Report.Warning (1685, 1, loc,
+                                                       "The predefined type `{0}.{1}' is redefined in the source code. Ignoring the local type definition",
+                                                       pts.Namespace, pts.Name);
+                                               best = pts;
+                                               continue;
+                                       }
+
+                                       if (best.MemberDefinition.IsImported)
+                                               best = ts;
+
+                                       if ((best.Modifiers & Modifiers.INTERNAL) != 0 && !TypeManager.IsThisOrFriendAssembly (CodeGen.Assembly.Builder, best.MemberDefinition.Assembly))
+                                               continue;
+
+                                       if (ts.MemberDefinition.IsImported)
+                                               ctx.Report.SymbolRelatedToPreviousError (ts);
+
+                                       ctx.Report.Warning (436, 2, loc,
+                                               "The type `{0}' conflicts with the imported type of same name'. Ignoring the imported type definition",
+                                               best.GetSignatureForError ());
+                               }
+
+                               //
+                               // Lookup for the best candidate with closest arity match
+                               //
+                               if (arity < 0) {
+                                       if (best == null) {
+                                               best = ts;
+                                       } else if (System.Math.Abs (ts.Arity + arity) < System.Math.Abs (best.Arity + arity)) {
+                                               best = ts;
                                        }
                                }
                        }
-                       string lookup = t != null ? t.FullName : (fullname.Length == 0 ? name : fullname + "." + name);
-                       Type rt = root.LookupTypeReflection (ctx, lookup, loc, t == null);
 
-                       // HACK: loc.IsNull when the type is core type
-                       if (t == null || (rt != null && loc.IsNull))
-                               t = rt;
+                       if (best == null)
+                               return null;
+
+                       te = new TypeExpression (best, Location.Null);
+
+                       // TODO MemberCache: Cache more
+                       if (arity == 0)
+                               cached_types.Add (name, te);
 
-                       te = t == null ? null : new TypeExpression (t, Location.Null);
-                       cached_types [name] = te;
                        return te;
                }
 
-               ///
-               /// Used for better error reporting only
-               /// 
-               public Type LookForAnyGenericType (string typeName)
+               TypeSpec LookupType (string name, int arity)
                {
-                       if (declspaces == null)
+                       if (types == null)
                                return null;
 
-                       typeName = SimpleName.RemoveGenericArity (typeName);
+                       IList<TypeSpec> found;
+                       if (types.TryGetValue (name, out found)) {
+                               TypeSpec best = null;
+
+                               foreach (var ts in found) {
+                                       if (ts.Arity == arity)
+                                               return ts;
 
-                       foreach (var de in declspaces) {
-                               string type_item = de.Key;
-                               int pos = type_item.LastIndexOf ('`');
-                               if (pos == typeName.Length && String.Compare (typeName, 0, type_item, 0, pos) == 0)
-                                       return de.Value.TypeBuilder;
+                                       //
+                                       // Lookup for the best candidate with closest arity match
+                                       //
+                                       if (arity < 0) {
+                                               if (best == null) {
+                                                       best = ts;
+                                               } else if (System.Math.Abs (ts.Arity + arity) < System.Math.Abs (best.Arity + arity)) {
+                                                       best = ts;
+                                               }
+                                       }
+                               }
+                               
+                               return best;
                        }
+
                        return null;
                }
 
-               public FullNamedExpression Lookup (CompilerContext ctx, string name, Location loc)
+               public FullNamedExpression Lookup (CompilerContext ctx, string name, int arity, Location loc)
                {
-                       if (namespaces.ContainsKey (name))
+                       if (arity == 0 && namespaces.ContainsKey (name))
                                return namespaces [name];
 
-                       return LookupType (ctx, name, loc);
+                       return LookupType (ctx, name, arity, loc);
                }
 
                //
-               // Completes types with the given `prefix' and stores the results in `result'
+               // Completes types with the given `prefix'
                //
-               public void CompletionGetTypesStartingWith (string prefix, Dictionary<string, string> result)
+               public IEnumerable<string> CompletionGetTypesStartingWith (string prefix)
                {
-                       int l = fullname.Length + 1;
-                       var res = root.CompletionGetTypesStartingWith (fullname + "." + prefix);
-
-                       if (res == null)
-                               return;
-                       
-                       foreach (string match in res){
-                               string x = match.Substring (l);
+                       if (types == null)
+                               return Enumerable.Empty<string> ();
 
-                               // Turn reflection nested classes foo+bar into foo.bar
-                               x = x.Replace ('+', '.');
+                       var res = from item in types
+                                         where item.Key.StartsWith (prefix) && item.Value.Any (l => (l.Modifiers & Modifiers.PUBLIC) != 0)
+                                         select item.Key;
 
-                               // Only get the first name element, no point in adding anything beyond the first dot.
-                               int p = x.IndexOf ('.');
-                               if (p != -1)
-                                       x = x.Substring (0, p);
+                       if (namespaces != null)
+                               res = res.Concat (from item in namespaces where item.Key.StartsWith (prefix) select item.Key);
 
-                               // Turn Foo`N into Foo<
-                               p = x.IndexOf ('`');
-                               if (p != -1)
-                                       x = x.Substring (0, p) + "<";
-
-                               if (!result.ContainsKey (x))
-                                       result [x] = x;
-                       }
-               }
-
-               public void RegisterExternalExtensionMethodClass (Type type)
-               {
-                       // Ignore, extension methods cannot be nested
-                       if (type.DeclaringType != null)
-                               return;
-
-                       // TODO: CodeGen.Assembly.Builder is global
-                       if (type.IsNotPublic && !TypeManager.IsThisOrFriendAssembly (CodeGen.Assembly.Builder, type.Assembly))
-                               return;
-
-                       if (external_exmethod_classes == null)
-                               external_exmethod_classes = new List<Type> ();
-
-                       external_exmethod_classes.Add (type);
+                       return res;
                }
 
                /// 
                /// Looks for extension method in this namespace
                /// 
-               public List<MethodSpec> LookupExtensionMethod (Type extensionType, ClassOrStruct currentClass, string name)
+               public List<MethodSpec> LookupExtensionMethod (TypeSpec extensionType, ClassOrStruct currentClass, string name, int arity)
                {
+                       if (types == null)
+                               return null;
+
                        List<MethodSpec> found = null;
 
-                       // TODO: problematic
-                       var invocation_assembly = CodeGen.Assembly.Builder;
+                       var invocation_type = currentClass == null ? InternalType.FakeInternalType : currentClass.CurrentType;
 
-                       if (declspaces != null) {
-                               var e = declspaces.Values.GetEnumerator ();
-                               while (e.MoveNext ()) {
-                                       Class c = e.Current as Class;
-                                       if (c == null)
-                                               continue;
+                       // TODO: Add per namespace flag when at least 1 type has extension
 
-                                       if ((c.ModFlags & Modifiers.METHOD_EXTENSION) == 0)
+                       foreach (var tgroup in types.Values) {
+                               foreach (var ts in tgroup) {
+                                       if ((ts.Modifiers & Modifiers.METHOD_EXTENSION) == 0)
                                                continue;
 
-                                       var res = c.MemberCache.FindExtensionMethods (invocation_assembly, extensionType, name, c != currentClass);
+                                       var res = ts.MemberCache.FindExtensionMethods (invocation_type, extensionType, name, arity);
                                        if (res == null)
                                                continue;
 
-                                       if (found == null)
+                                       if (found == null) {
                                                found = res;
-                                       else
+                                       } else {
                                                found.AddRange (res);
+                                       }
                                }
                        }
 
-                       if (external_exmethod_classes == null)
-                               return found;
-
-                       foreach (Type t in external_exmethod_classes) {
-                               MemberCache m = TypeHandle.GetMemberCache (t);
-                               var res = m.FindExtensionMethods (invocation_assembly, extensionType, name, true);
-                               if (res == null)
-                                       continue;
+                       return found;
+               }
 
-                               if (found == null)
-                                       found = res;
-                               else
-                                       found.AddRange (res);
+               public void AddType (TypeSpec ts)
+               {
+                       if (types == null) {
+                               types = new Dictionary<string, IList<TypeSpec>> (64);
                        }
 
-                       return found;
+                       var name = ts.Name;
+                       IList<TypeSpec> existing;
+                       if (types.TryGetValue (name, out existing)) {
+                               TypeSpec better_type;
+                               TypeSpec found;
+                               if (existing.Count == 1) {
+                                       found = existing[0];
+                                       if (ts.Arity == found.Arity) {
+                                               better_type = IsImportedTypeOverride (ts, found);
+                                               if (better_type == found)
+                                                       return;
+
+                                               if (better_type != null) {
+                                                       existing [0] = better_type;
+                                                       return;
+                                               }
+                                       }
+
+                                       existing = new List<TypeSpec> ();
+                                       existing.Add (found);
+                                       types[name] = existing;
+                               } else {
+                                       for (int i = 0; i < existing.Count; ++i) {
+                                               found = existing[i];
+                                               if (ts.Arity != found.Arity)
+                                                       continue;
+
+                                               better_type = IsImportedTypeOverride (ts, found);
+                                               if (better_type == found)
+                                                       return;
+
+                                               if (better_type != null) {
+                                                       existing.RemoveAt (i);
+                                                       --i;
+                                                       continue;
+                                               }
+                                       }
+                               }
+
+                               existing.Add (ts);
+                       } else {
+                               types.Add (name, new TypeSpec[] { ts });
+                       }
                }
 
-               public void AddDeclSpace (string name, DeclSpace ds)
+               //
+               // We import any types but in the situation there are same types
+               // but one has better visibility (either public or internal with friend)
+               // the less visible type is removed from the namespace cache
+               //
+               public static TypeSpec IsImportedTypeOverride (TypeSpec ts, TypeSpec found)
                {
-                       if (declspaces == null)
-                               declspaces = new Dictionary<string, DeclSpace> ();
-                       declspaces.Add (name, ds);
+                       var ts_accessible = (ts.Modifiers & Modifiers.PUBLIC) != 0 || TypeManager.IsThisOrFriendAssembly (CodeGen.Assembly.Builder, ts.MemberDefinition.Assembly);
+                       var found_accessible = (found.Modifiers & Modifiers.PUBLIC) != 0 || TypeManager.IsThisOrFriendAssembly (CodeGen.Assembly.Builder, found.MemberDefinition.Assembly);
+
+                       if (ts_accessible && !found_accessible)
+                               return ts;
+
+                       // found is better always better for accessible or inaccessible ts
+                       if (!ts_accessible)
+                               return found;
+
+                       return null;
                }
 
                public void RemoveDeclSpace (string name)
                {
-                       declspaces.Remove (name);
+                       types.Remove (name);
                }
-               
-               /// <summary>
-               ///   The qualified name of the current namespace
-               /// </summary>
-               public string Name {
-                       get { return fullname; }
+
+               public void ReplaceTypeWithPredefined (TypeSpec ts, PredefinedTypeSpec pts)
+               {
+                       var found = types [ts.Name];
+                       cached_types.Remove (ts.Name);
+                       if (found.Count == 1) {
+                               types[ts.Name][0] = pts;
+                       } else {
+                               throw new NotImplementedException ();
+                       }
                }
 
-               /// <summary>
-               ///   The parent of this namespace, used by the parser to "Pop"
-               ///   the current namespace declaration
-               /// </summary>
-               public Namespace Parent {
-                       get { return parent; }
+               public void VerifyClsCompliance ()
+               {
+                       if (types == null || cls_checked)
+                               return;
+
+                       cls_checked = true;
+
+                       // TODO: This is quite ugly way to check for CLS compliance at namespace level
+
+                       var locase_types = new Dictionary<string, List<TypeSpec>> (StringComparer.OrdinalIgnoreCase);
+                       foreach (var tgroup in types.Values) {
+                               foreach (var tm in tgroup) {
+                                       if ((tm.Modifiers & Modifiers.PUBLIC) == 0 || !tm.IsCLSCompliant ())
+                                               continue;
+
+                                       List<TypeSpec> found;
+                                       if (!locase_types.TryGetValue (tm.Name, out found)) {
+                                               found = new List<TypeSpec> ();
+                                               locase_types.Add (tm.Name, found);
+                                       }
+
+                                       found.Add (tm);
+                               }
+                       }
+
+                       foreach (var locase in locase_types.Values) {
+                               if (locase.Count < 2)
+                                       continue;
+
+                               bool all_same = true;
+                               foreach (var notcompliant in locase) {
+                                       all_same = notcompliant.Name == locase[0].Name;
+                                       if (!all_same)
+                                               break;
+                               }
+
+                               if (all_same)
+                                       continue;
+
+                               TypeContainer compiled = null;
+                               foreach (var notcompliant in locase) {
+                                       if (!notcompliant.MemberDefinition.IsImported) {
+                                               if (compiled != null)
+                                                       compiled.Compiler.Report.SymbolRelatedToPreviousError (compiled);
+
+                                               compiled = notcompliant.MemberDefinition as TypeContainer;
+                                       } else {
+                                               compiled.Compiler.Report.SymbolRelatedToPreviousError (notcompliant);
+                                       }
+                               }
+
+                               compiled.Compiler.Report.Warning (3005, 1, compiled.Location,
+                                       "Identifier `{0}' differing only in case is not CLS-compliant", compiled.GetSignatureForError ());
+                       }
                }
        }
 
@@ -789,7 +764,7 @@ namespace Mono.CSharp {
                                }
 
                                if (resolved is TypeExpr)
-                                       resolved = resolved.ResolveAsBaseTerminal (rc, false);
+                                       resolved = resolved.ResolveAsTypeTerminal (rc, false);
 
                                return resolved;
                        }
@@ -1034,11 +1009,11 @@ namespace Mono.CSharp {
                /// Does extension methods look up to find a method which matches name and extensionType.
                /// Search starts from this namespace and continues hierarchically up to top level.
                ///
-               public ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
+               public ExtensionMethodGroupExpr LookupExtensionMethod (TypeSpec extensionType, string name, int arity, Location loc)
                {
                        List<MethodSpec> candidates = null;
                        foreach (Namespace n in GetUsingTable ()) {
-                               var a = n.LookupExtensionMethod (extensionType, null, name);
+                               var a = n.LookupExtensionMethod (extensionType, null, name, arity);
                                if (a == null)
                                        continue;
 
@@ -1059,7 +1034,7 @@ namespace Mono.CSharp {
                        //
                        Namespace parent_ns = ns.Parent;
                        do {
-                               candidates = parent_ns.LookupExtensionMethod (extensionType, null, name);
+                               candidates = parent_ns.LookupExtensionMethod (extensionType, null, name, arity);
                                if (candidates != null)
                                        return new ExtensionMethodGroupExpr (candidates, parent, extensionType, loc);
 
@@ -1069,23 +1044,24 @@ namespace Mono.CSharp {
                        //
                        // Continue in parent scope
                        //
-                       return parent.LookupExtensionMethod (extensionType, name, loc);
+                       return parent.LookupExtensionMethod (extensionType, name, arity, loc);
                }
 
-               public FullNamedExpression LookupNamespaceOrType (string name, Location loc, bool ignore_cs0104)
+               public FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
                {
                        // Precondition: Only simple names (no dots) will be looked up with this function.
                        FullNamedExpression resolved = null;
                        for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent) {
-                               if ((resolved = curr_ns.Lookup (name, loc, ignore_cs0104)) != null)
+                               if ((resolved = curr_ns.Lookup (name, arity, loc, ignore_cs0104)) != null)
                                        break;
                        }
+
                        return resolved;
                }
 
-               public ICollection<string> CompletionGetTypesStartingWith (string prefix)
+               public IList<string> CompletionGetTypesStartingWith (string prefix)
                {
-                       var result = new Dictionary<string, string> ();
+                       IEnumerable<string> all = Enumerable.Empty<string> ();
                        
                        for (NamespaceEntry curr_ns = this; curr_ns != null; curr_ns = curr_ns.ImplicitParent){
                                foreach (Namespace using_ns in GetUsingTable ()){
@@ -1094,24 +1070,16 @@ namespace Mono.CSharp {
                                                if (ld != -1){
                                                        string rest = prefix.Substring (ld+1);
 
-                                                       using_ns.CompletionGetTypesStartingWith (rest, result);
+                                                       all = all.Concat (using_ns.CompletionGetTypesStartingWith (rest));
                                                }
                                        }
-                                       using_ns.CompletionGetTypesStartingWith (prefix, result);
+                                       all = all.Concat (using_ns.CompletionGetTypesStartingWith (prefix));
                                }
                        }
 
-                       return result.Keys;
+                       return all.Distinct ().ToList ();
                }
                
-               void Error_AmbiguousTypeReference (Location loc, string name, FullNamedExpression t1, FullNamedExpression t2)
-               {
-                       Compiler.Report.SymbolRelatedToPreviousError (t1.Type);
-                       Compiler.Report.SymbolRelatedToPreviousError (t2.Type);
-                       Compiler.Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
-                               name, t1.GetSignatureForError (), t2.GetSignatureForError ());
-               }
-
                // Looks-up a alias named @name in this and surrounding namespace declarations
                public FullNamedExpression LookupNamespaceAlias (string name)
                {
@@ -1128,17 +1096,17 @@ namespace Mono.CSharp {
                        return null;
                }
 
-               private FullNamedExpression Lookup (string name, Location loc, bool ignore_cs0104)
+               private FullNamedExpression Lookup (string name, int arity, Location loc, bool ignore_cs0104)
                {
                        //
                        // Check whether it's in the namespace.
                        //
-                       FullNamedExpression fne = ns.Lookup (Compiler, name, loc);
+                       FullNamedExpression fne = ns.Lookup (Compiler, name, arity, loc);
 
                        //
                        // Check aliases. 
                        //
-                       if (using_aliases != null) {
+                       if (using_aliases != null && arity == 0) {
                                foreach (UsingAliasEntry ue in using_aliases) {
                                        if (ue.Alias == name) {
                                                if (fne != null) {
@@ -1159,8 +1127,10 @@ namespace Mono.CSharp {
                                }
                        }
 
-                       if (fne != null)
-                               return fne;
+                       if (fne != null) {
+                               if (!((fne.Type.Modifiers & Modifiers.INTERNAL) != 0 && !TypeManager.IsThisOrFriendAssembly (CodeGen.Assembly.Builder, fne.Type.Assembly)))
+                                       return fne;
+                       }
 
                        if (IsImplicit)
                                return null;
@@ -1170,18 +1140,43 @@ namespace Mono.CSharp {
                        //
                        FullNamedExpression match = null;
                        foreach (Namespace using_ns in GetUsingTable ()) {
-                               match = using_ns.Lookup (Compiler, name, loc);
-                               if (match == null || !(match is TypeExpr))
+                               fne = using_ns.Lookup (Compiler, name, arity, loc);
+                               if (fne == null)
+                                       continue;
+
+                               if (match == null) {
+                                       match = fne;
                                        continue;
-                               if (fne != null) {
-                                       if (!ignore_cs0104)
-                                               Error_AmbiguousTypeReference (loc, name, fne, match);
-                                       return null;
                                }
-                               fne = match;
+
+                               // Prefer types over namespaces
+                               var texpr_fne = fne as TypeExpr;
+                               var texpr_match = match as TypeExpr;
+                               if (texpr_fne != null && texpr_match == null) {
+                                       match = fne;
+                                       continue;
+                               } else if (texpr_fne == null && texpr_match != null) {
+                                       continue;
+                               }
+
+                               if (ignore_cs0104)
+                                       return match;
+
+                               // It can be top level accessibility only
+                               var better = Namespace.IsImportedTypeOverride (texpr_match.Type, texpr_fne.Type);
+                               if (better == null) {
+                                       Compiler.Report.SymbolRelatedToPreviousError (texpr_match.Type);
+                                       Compiler.Report.SymbolRelatedToPreviousError (texpr_fne.Type);
+                                       Compiler.Report.Error (104, loc, "`{0}' is an ambiguous reference between `{1}' and `{2}'",
+                                               name, texpr_match.GetSignatureForError (), texpr_fne.GetSignatureForError ());
+                                       return match;
+                               }
+
+                               if (better == texpr_fne.Type)
+                                       match = texpr_fne;
                        }
 
-                       return fne;
+                       return match;
                }
 
                Namespace [] GetUsingTable ()
@@ -1314,18 +1309,22 @@ namespace Mono.CSharp {
                        get { return RootContext.ToplevelTypes.Compiler; }
                }
 
-               public Type CurrentType {
+               public TypeSpec CurrentType {
                        get { return SlaveDeclSpace.CurrentType; }
                }
 
-               public TypeContainer CurrentTypeDefinition {
-                       get { return SlaveDeclSpace.CurrentTypeDefinition; }
+               public MemberCore CurrentMemberDefinition {
+                       get { return SlaveDeclSpace.CurrentMemberDefinition; }
                }
 
                public TypeParameter[] CurrentTypeParameters {
                        get { return SlaveDeclSpace.CurrentTypeParameters; }
                }
 
+               public bool HasUnresolvedConstraints {
+                       get { return false; }
+               }
+
                public bool IsObsolete {
                        get { return SlaveDeclSpace.IsObsolete; }
                }
index 878e4a02370aa6a09d972f751400e44ddeb54f1a..8e2dc682bbc0fbbfc2403f8ed3842c0c87c11dd4 100644 (file)
@@ -29,7 +29,7 @@ namespace Mono.CSharp.Nullable
                        eclass = ExprClass.Type;
                }
 
-               public NullableType (Type type, Location loc)
+               public NullableType (TypeSpec type, Location loc)
                        : this (new TypeExpression (type, loc), loc)
                { }
 
@@ -37,68 +37,54 @@ namespace Mono.CSharp.Nullable
                {
                        if (TypeManager.generic_nullable_type == null) {
                                TypeManager.generic_nullable_type = TypeManager.CoreLookupType (ec.Compiler,
-                                       "System", "Nullable`1", MemberKind.Struct, true);
+                                       "System", "Nullable", 1, MemberKind.Struct, true);
                        }
 
                        TypeArguments args = new TypeArguments (underlying);
                        GenericTypeExpr ctype = new GenericTypeExpr (TypeManager.generic_nullable_type, args, loc);
                        return ctype.ResolveAsTypeTerminal (ec, false);
                }
-
-               public override TypeExpr ResolveAsTypeTerminal (IMemberContext ec, bool silent)
-               {
-                       return ResolveAsBaseTerminal (ec, silent);
-               }               
        }
 
-       public sealed class NullableInfo
+       static class NullableInfo
        {
-               public readonly Type Type;
-               public readonly Type UnderlyingType;
-               public MethodSpec HasValue;
-               public MethodSpec Value;
-               public MethodSpec GetValueOrDefault;
-               public MethodSpec Constructor;
-
-               public NullableInfo (Type type)
+               public static MethodSpec GetConstructor (TypeSpec nullableType)
                {
-                       Type = type;
-                       UnderlyingType = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (type) [0]);
-
-                       var has_value_pi = TypeManager.GetPredefinedProperty (type, "HasValue", Location.Null, Type.EmptyTypes);
-                       var value_pi = TypeManager.GetPredefinedProperty (type, "Value", Location.Null, Type.EmptyTypes);
-                       GetValueOrDefault = TypeManager.GetPredefinedMethod (type, "GetValueOrDefault", Location.Null, Type.EmptyTypes);
+                       return TypeManager.GetPredefinedConstructor (nullableType, Location.Null, GetUnderlyingType (nullableType));
+               }
 
-                       HasValue = Import.CreateMethod (has_value_pi.MetaInfo.GetGetMethod (false));
-                       Value = Import.CreateMethod (value_pi.MetaInfo.GetGetMethod (false));
+               public static MethodSpec GetHasValue (TypeSpec nullableType)
+               {
+                       return (MethodSpec) MemberCache.FindMember (nullableType,
+                               MemberFilter.Method ("get_HasValue", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
+               }
 
-                       // When compiling corlib
-                       if (TypeManager.IsBeingCompiled (type)) {
-                               TypeContainer tc = TypeManager.LookupGenericTypeContainer (type);
-                               
-                               // TODO: check for correct overload
-                               Constructor c = ((Constructor) tc.InstanceConstructors [0]);
+               public static MethodSpec GetGetValueOrDefault (TypeSpec nullableType)
+               {
+                       return (MethodSpec) MemberCache.FindMember (nullableType,
+                               MemberFilter.Method ("GetValueOrDefault", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
+               }
 
-                               Constructor = Import.CreateMethod (TypeBuilder.GetConstructor (type, c.ConstructorBuilder));
-                               return;
-                       }
+               public static MethodSpec GetValue (TypeSpec nullableType)
+               {
+                       return (MethodSpec) MemberCache.FindMember (nullableType,
+                               MemberFilter.Method ("get_Value", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None);
+               }
 
-#if MS_COMPATIBLE
-//                     if (TypeManager.IsBeingCompiled (UnderlyingType)) {
-//                             ConstructorInfo cinfo = TypeManager.DropGenericTypeArguments (type).GetConstructors ()[0];
-//                             Constructor = TypeBuilder.GetConstructor (type, cinfo);
-//                             return;
-//                     }
-#endif
+               public static TypeSpec GetUnderlyingType (TypeSpec nullableType)
+               {
+                       return ((InflatedTypeSpec) nullableType).TypeArguments[0];
+               }
 
-                       Constructor = Import.CreateMethod (type.GetConstructor (new Type[] { UnderlyingType }));
+               public static bool IsNullableType (TypeSpec type)
+               {
+                       throw new NotImplementedException ("net");
                }
        }
 
        public class Unwrap : Expression, IMemoryLocation, IAssignMethod
        {
                Expression expr;
-               NullableInfo info;
 
                LocalTemporary temp;
                readonly bool useDefaultValue;
@@ -109,8 +95,7 @@ namespace Mono.CSharp.Nullable
                        this.loc = expr.Location;
                        this.useDefaultValue = useDefaultValue;
 
-                       info = new NullableInfo (expr.Type);
-                       type = info.UnderlyingType;
+                       type = NullableInfo.GetUnderlyingType (expr.Type);
                        eclass = expr.eclass;
                }
 
@@ -150,15 +135,15 @@ namespace Mono.CSharp.Nullable
                {
                        Store (ec);
                        if (useDefaultValue)
-                               Invocation.EmitCall (ec, false, this, info.GetValueOrDefault, null, loc);
+                               Invocation.EmitCall (ec, false, this, NullableInfo.GetGetValueOrDefault (expr.Type), null, loc);
                        else
-                               Invocation.EmitCall (ec, false, this, info.Value, null, loc);
+                               Invocation.EmitCall (ec, false, this, NullableInfo.GetValue (expr.Type), null, loc);
                }
 
                public void EmitCheck (EmitContext ec)
                {
                        Store (ec);
-                       Invocation.EmitCall (ec, false, this, info.HasValue, null, loc);
+                       Invocation.EmitCall (ec, false, this, NullableInfo.GetHasValue (expr.Type), null, loc);
                }
 
                public override bool Equals (object obj)
@@ -209,15 +194,6 @@ namespace Mono.CSharp.Nullable
                        return expr.MakeExpression (ctx);
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       type = storey.MutateType (type);
-                       storey.MutateConstructor (info.Constructor);
-                       storey.MutateGenericMethod (info.HasValue);
-                       storey.MutateGenericMethod (info.GetValueOrDefault);
-                       storey.MutateGenericMethod (info.Value);
-               }
-
                public void AddressOf (EmitContext ec, AddressOp mode)
                {
                        IMemoryLocation ml = expr as VariableReference;
@@ -233,7 +209,7 @@ namespace Mono.CSharp.Nullable
                LocalTemporary LocalVariable {
                        get {
                                if (temp == null)
-                                       temp = new LocalTemporary (info.Type);
+                                       temp = new LocalTemporary (expr.Type);
                                return temp;
                        }
                }
@@ -249,22 +225,20 @@ namespace Mono.CSharp.Nullable
                public void EmitAssign (EmitContext ec, Expression source,
                                        bool leave_copy, bool prepare_for_load)
                {
-                       InternalWrap wrap = new InternalWrap (source, info, loc);
+                       InternalWrap wrap = new InternalWrap (source, expr.Type, loc);
                        ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
                }
 
-               protected class InternalWrap : Expression
+               class InternalWrap : Expression
                {
                        public Expression expr;
-                       public NullableInfo info;
 
-                       public InternalWrap (Expression expr, NullableInfo info, Location loc)
+                       public InternalWrap (Expression expr, TypeSpec type, Location loc)
                        {
                                this.expr = expr;
-                               this.info = info;
                                this.loc = loc;
+                               this.type = type;
 
-                               type = info.Type;
                                eclass = ExprClass.Value;
                        }
 
@@ -281,26 +255,19 @@ namespace Mono.CSharp.Nullable
                        public override void Emit (EmitContext ec)
                        {
                                expr.Emit (ec);
-                               ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) info.Constructor.MetaInfo);
+                               ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
                        }
                }
        }
 
        public class Wrap : TypeCast
        {
-               readonly NullableInfo info;
-
-               protected Wrap (Expression expr, Type type)
+               private Wrap (Expression expr, TypeSpec type)
                        : base (expr, type)
                {
-                       info = new NullableInfo (type);
                        eclass = ExprClass.Value;
                }
 
-               public Expression Child {
-                       get { return child; }
-               }
-
                public override Expression CreateExpressionTree (ResolveContext ec)
                {
                        TypeCast child_cast = child as TypeCast;
@@ -312,13 +279,13 @@ namespace Mono.CSharp.Nullable
                        return base.CreateExpressionTree (ec);
                }
 
-               public static Expression Create (Expression expr, Type type)
+               public static Expression Create (Expression expr, TypeSpec type)
                {
                        //
                        // Avoid unwraping and wraping of the same type
                        //
                        Unwrap unwrap = expr as Unwrap;
-                       if (unwrap != null && TypeManager.IsEqual (expr.Type, TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (type) [0])))
+                       if (unwrap != null && TypeManager.IsEqual (expr.Type, NullableInfo.GetUnderlyingType (type)))
                                return unwrap.Original;
                
                        return new Wrap (expr, type);
@@ -327,7 +294,7 @@ namespace Mono.CSharp.Nullable
                public override void Emit (EmitContext ec)
                {
                        child.Emit (ec);
-                       ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) info.Constructor.MetaInfo);
+                       ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
                }
        }
 
@@ -336,13 +303,13 @@ namespace Mono.CSharp.Nullable
        //
        public class LiftedNull : NullConstant, IMemoryLocation
        {
-               private LiftedNull (Type nullable_type, Location loc)
+               private LiftedNull (TypeSpec nullable_type, Location loc)
                        : base (nullable_type, loc)
                {
                        eclass = ExprClass.Value;
                }
 
-               public static Constant Create (Type nullable, Location loc)
+               public static Constant Create (TypeSpec nullable, Location loc)
                {
                        return new LiftedNull (nullable, loc);
                }
@@ -361,7 +328,7 @@ namespace Mono.CSharp.Nullable
                        LocalTemporary value_target = new LocalTemporary (type);
 
                        value_target.AddressOf (ec, AddressOp.Store);
-                       ec.ig.Emit (OpCodes.Initobj, type);
+                       ec.Emit (OpCodes.Initobj, type);
                        value_target.Emit (ec);
                }
 
@@ -370,7 +337,7 @@ namespace Mono.CSharp.Nullable
                        LocalTemporary value_target = new LocalTemporary (type);
                                
                        value_target.AddressOf (ec, AddressOp.Store);
-                       ec.ig.Emit (OpCodes.Initobj, type);
+                       ec.Emit (OpCodes.Initobj, type);
                        ((IMemoryLocation) value_target).AddressOf (ec, Mode);
                }
        }
@@ -383,7 +350,7 @@ namespace Mono.CSharp.Nullable
                Expression expr, null_value;
                Unwrap unwrap;
 
-               public Lifted (Expression expr, Unwrap unwrap, Type type)
+               public Lifted (Expression expr, Unwrap unwrap, TypeSpec type)
                {
                        this.expr = expr;
                        this.unwrap = unwrap;
@@ -391,7 +358,7 @@ namespace Mono.CSharp.Nullable
                        this.type = type;
                }
 
-               public Lifted (Expression expr, Expression unwrap, Type type)
+               public Lifted (Expression expr, Expression unwrap, TypeSpec type)
                        : this (expr, unwrap as Unwrap, type)
                {
                }
@@ -432,20 +399,19 @@ namespace Mono.CSharp.Nullable
 
                public override void Emit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-                       Label is_null_label = ig.DefineLabel ();
-                       Label end_label = ig.DefineLabel ();
+                       Label is_null_label = ec.DefineLabel ();
+                       Label end_label = ec.DefineLabel ();
 
                        unwrap.EmitCheck (ec);
-                       ig.Emit (OpCodes.Brfalse, is_null_label);
+                       ec.Emit (OpCodes.Brfalse, is_null_label);
 
                        expr.Emit (ec);
 
-                       ig.Emit (OpCodes.Br, end_label);
-                       ig.MarkLabel (is_null_label);
+                       ec.Emit (OpCodes.Br, end_label);
+                       ec.MarkLabel (is_null_label);
 
                        null_value.Emit (ec);
-                       ig.MarkLabel (end_label);
+                       ec.MarkLabel (end_label);
                }
 
                public void AddressOf (EmitContext ec, AddressOp mode)
@@ -504,28 +470,25 @@ namespace Mono.CSharp.Nullable
 
                public override void Emit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-                       Label is_null_label = ig.DefineLabel ();
-                       Label end_label = ig.DefineLabel ();
+                       Label is_null_label = ec.DefineLabel ();
+                       Label end_label = ec.DefineLabel ();
 
                        unwrap.EmitCheck (ec);
-                       ig.Emit (OpCodes.Brfalse, is_null_label);
-
-                       NullableInfo ni = new NullableInfo (type);
+                       ec.Emit (OpCodes.Brfalse, is_null_label);
 
                        if (user_operator != null) {
                                user_operator.Emit (ec);
                        } else {
-                               EmitOperator (ec, ni.UnderlyingType);
+                               EmitOperator (ec, NullableInfo.GetUnderlyingType (type));
                        }
 
-                       ig.Emit (OpCodes.Newobj, (ConstructorInfo) ni.Constructor.MetaInfo);
-                       ig.Emit (OpCodes.Br_S, end_label);
+                       ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type));
+                       ec.Emit (OpCodes.Br_S, end_label);
 
-                       ig.MarkLabel (is_null_label);
+                       ec.MarkLabel (is_null_label);
                        LiftedNull.Create (type, loc).Emit (ec);
 
-                       ig.MarkLabel (end_label);
+                       ec.MarkLabel (end_label);
                }
 
                Expression LiftExpression (ResolveContext ec, Expression expr)
@@ -654,23 +617,21 @@ namespace Mono.CSharp.Nullable
 
                void EmitBitwiseBoolean (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-
-                       Label load_left = ig.DefineLabel ();
-                       Label load_right = ig.DefineLabel ();
-                       Label end_label = ig.DefineLabel ();
+                       Label load_left = ec.DefineLabel ();
+                       Label load_right = ec.DefineLabel ();
+                       Label end_label = ec.DefineLabel ();
 
                        left_unwrap.Emit (ec);
-                       ig.Emit (OpCodes.Brtrue_S, load_right);
+                       ec.Emit (OpCodes.Brtrue_S, load_right);
 
                        right_unwrap.Emit (ec);
-                       ig.Emit (OpCodes.Brtrue_S, load_left);
+                       ec.Emit (OpCodes.Brtrue_S, load_left);
 
                        left_unwrap.EmitCheck (ec);
-                       ig.Emit (OpCodes.Brfalse_S, load_right);
+                       ec.Emit (OpCodes.Brfalse_S, load_right);
 
                        // load left
-                       ig.MarkLabel (load_left);
+                       ec.MarkLabel (load_left);
 
                        if (Oper == Operator.BitwiseAnd) {
                                left_unwrap.Load (ec);
@@ -678,13 +639,13 @@ namespace Mono.CSharp.Nullable
                                right_unwrap.Load (ec);
                                right_unwrap = left_unwrap;
                        }
-                       ig.Emit (OpCodes.Br_S, end_label);
+                       ec.Emit (OpCodes.Br_S, end_label);
 
                        // load right
-                       ig.MarkLabel (load_right);
+                       ec.MarkLabel (load_right);
                        right_unwrap.Load (ec);
 
-                       ig.MarkLabel (end_label);
+                       ec.MarkLabel (end_label);
                }
 
                //
@@ -692,16 +653,14 @@ namespace Mono.CSharp.Nullable
                //
                void EmitEquality (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-
                        //
                        // Either left or right is null
                        //
                        if (left_unwrap != null && (right_null_lifted || right.IsNull)) {
                                left_unwrap.EmitCheck (ec);
                                if (Oper == Binary.Operator.Equality) {
-                                       ig.Emit (OpCodes.Ldc_I4_0);
-                                       ig.Emit (OpCodes.Ceq);
+                                       ec.Emit (OpCodes.Ldc_I4_0);
+                                       ec.Emit (OpCodes.Ceq);
                                }
                                return;
                        }
@@ -709,23 +668,23 @@ namespace Mono.CSharp.Nullable
                        if (right_unwrap != null && (left_null_lifted || left.IsNull)) {
                                right_unwrap.EmitCheck (ec);
                                if (Oper == Binary.Operator.Equality) {
-                                       ig.Emit (OpCodes.Ldc_I4_0);
-                                       ig.Emit (OpCodes.Ceq);
+                                       ec.Emit (OpCodes.Ldc_I4_0);
+                                       ec.Emit (OpCodes.Ceq);
                                }
                                return;
                        }
 
-                       Label dissimilar_label = ig.DefineLabel ();
-                       Label end_label = ig.DefineLabel ();
+                       Label dissimilar_label = ec.DefineLabel ();
+                       Label end_label = ec.DefineLabel ();
 
                        if (user_operator != null) {
                                user_operator.Emit (ec);
-                               ig.Emit (Oper == Operator.Equality ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, dissimilar_label);
+                               ec.Emit (Oper == Operator.Equality ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, dissimilar_label);
                        } else {
                                left.Emit (ec);
                                right.Emit (ec);
 
-                               ig.Emit (OpCodes.Bne_Un_S, dissimilar_label);
+                               ec.Emit (OpCodes.Bne_Un_S, dissimilar_label);
                        }
 
                        if (left_unwrap != null)
@@ -736,31 +695,31 @@ namespace Mono.CSharp.Nullable
 
                        if (left_unwrap != null && right_unwrap != null) {
                                if (Oper == Operator.Inequality)
-                                       ig.Emit (OpCodes.Xor);
+                                       ec.Emit (OpCodes.Xor);
                                else
-                                       ig.Emit (OpCodes.Ceq);
+                                       ec.Emit (OpCodes.Ceq);
                        } else {
                                if (Oper == Operator.Inequality) {
-                                       ig.Emit (OpCodes.Ldc_I4_0);
-                                       ig.Emit (OpCodes.Ceq);
+                                       ec.Emit (OpCodes.Ldc_I4_0);
+                                       ec.Emit (OpCodes.Ceq);
                                }
                        }
 
-                       ig.Emit (OpCodes.Br_S, end_label);
+                       ec.Emit (OpCodes.Br_S, end_label);
 
-                       ig.MarkLabel (dissimilar_label);
+                       ec.MarkLabel (dissimilar_label);
                        if (Oper == Operator.Inequality)
-                               ig.Emit (OpCodes.Ldc_I4_1);
+                               ec.Emit (OpCodes.Ldc_I4_1);
                        else
-                               ig.Emit (OpCodes.Ldc_I4_0);
+                               ec.Emit (OpCodes.Ldc_I4_0);
 
-                       ig.MarkLabel (end_label);
+                       ec.MarkLabel (end_label);
                }
                
                public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
                {
                        Emit (ec);
-                       ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
+                       ec.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
                }                       
 
                public override void Emit (EmitContext ec)
@@ -781,14 +740,12 @@ namespace Mono.CSharp.Nullable
                                return;
                        }
 
-                       ILGenerator ig = ec.ig;
-
-                       Label is_null_label = ig.DefineLabel ();
-                       Label end_label = ig.DefineLabel ();
+                       Label is_null_label = ec.DefineLabel ();
+                       Label end_label = ec.DefineLabel ();
 
                        if (left_unwrap != null) {
                                left_unwrap.EmitCheck (ec);
-                               ig.Emit (OpCodes.Brfalse, is_null_label);
+                               ec.Emit (OpCodes.Brfalse, is_null_label);
                        }
 
                        //
@@ -796,27 +753,27 @@ namespace Mono.CSharp.Nullable
                        //
                        if (right_unwrap != null && !left.Equals (right)) {
                                right_unwrap.EmitCheck (ec);
-                               ig.Emit (OpCodes.Brfalse, is_null_label);
+                               ec.Emit (OpCodes.Brfalse, is_null_label);
                        }
 
                        EmitOperator (ec, left.Type);
 
                        if (wrap_ctor != null)
-                               ig.Emit (OpCodes.Newobj, (ConstructorInfo) wrap_ctor.MetaInfo);
+                               ec.Emit (OpCodes.Newobj, wrap_ctor);
 
-                       ig.Emit (OpCodes.Br_S, end_label);
-                       ig.MarkLabel (is_null_label);
+                       ec.Emit (OpCodes.Br_S, end_label);
+                       ec.MarkLabel (is_null_label);
 
                        if ((Oper & Operator.ComparisonMask) != 0) {
-                               ig.Emit (OpCodes.Ldc_I4_0);
+                               ec.Emit (OpCodes.Ldc_I4_0);
                        } else {
                                LiftedNull.Create (type, loc).Emit (ec);
                        }
 
-                       ig.MarkLabel (end_label);
+                       ec.MarkLabel (end_label);
                }
 
-               protected override void EmitOperator (EmitContext ec, Type l)
+               protected override void EmitOperator (EmitContext ec, TypeSpec l)
                {
                        if (user_operator != null) {
                                user_operator.Emit (ec);
@@ -824,7 +781,7 @@ namespace Mono.CSharp.Nullable
                        }
 
                        if (TypeManager.IsNullableType (l))
-                               l = TypeManager.TypeToCoreType (TypeManager.GetTypeArguments (l) [0]);
+                               l = TypeManager.GetTypeArguments (l) [0];
 
                        base.EmitOperator (ec, l);
                }
@@ -873,7 +830,7 @@ namespace Mono.CSharp.Nullable
                                if (lifted_type == null)
                                        return null;
 
-                               wrap_ctor = new NullableInfo (lifted_type.Type).Constructor;
+                               wrap_ctor = NullableInfo.GetConstructor (lifted_type.Type);
                                type = res_expr.Type = lifted_type.Type;
                        }
 
@@ -906,7 +863,7 @@ namespace Mono.CSharp.Nullable
                        return res_expr;
                }
 
-               protected override Expression ResolveOperatorPredefined (ResolveContext ec, Binary.PredefinedOperator [] operators, bool primitives_only, Type enum_type)
+               protected override Expression ResolveOperatorPredefined (ResolveContext ec, Binary.PredefinedOperator [] operators, bool primitives_only, TypeSpec enum_type)
                {
                        Expression e = base.ResolveOperatorPredefined (ec, operators, primitives_only, enum_type);
 
@@ -928,7 +885,7 @@ namespace Mono.CSharp.Nullable
                        return e;
                }
 
-               protected override Expression ResolveUserOperator (ResolveContext ec, Type l, Type r)
+               protected override Expression ResolveUserOperator (ResolveContext ec, TypeSpec l, TypeSpec r)
                {
                        Expression expr = base.ResolveUserOperator (ec, l, r);
                        if (expr == null)
@@ -987,7 +944,7 @@ namespace Mono.CSharp.Nullable
                        if (left.eclass == ExprClass.MethodGroup)
                                return null;
 
-                       Type ltype = left.Type;
+                       TypeSpec ltype = left.Type;
 
                        //
                        // If left is a nullable type and an implicit conversion exists from right to underlying type of left,
@@ -1027,7 +984,7 @@ namespace Mono.CSharp.Nullable
                                return null;
                        }
 
-                       Type rtype = right.Type;
+                       TypeSpec rtype = right.Type;
                        if (!Convert.ImplicitConversionExists (ec, unwrap != null ? unwrap : left, rtype) || right.eclass == ExprClass.MethodGroup)
                                return null;
 
@@ -1063,42 +1020,33 @@ namespace Mono.CSharp.Nullable
 
                public override void Emit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-
-                       Label end_label = ig.DefineLabel ();
+                       Label end_label = ec.DefineLabel ();
 
                        if (unwrap != null) {
-                               Label is_null_label = ig.DefineLabel ();
+                               Label is_null_label = ec.DefineLabel ();
 
                                unwrap.EmitCheck (ec);
-                               ig.Emit (OpCodes.Brfalse, is_null_label);
+                               ec.Emit (OpCodes.Brfalse, is_null_label);
 
                                left.Emit (ec);
-                               ig.Emit (OpCodes.Br, end_label);
+                               ec.Emit (OpCodes.Br, end_label);
 
-                               ig.MarkLabel (is_null_label);
+                               ec.MarkLabel (is_null_label);
                                right.Emit (ec);
 
-                               ig.MarkLabel (end_label);
+                               ec.MarkLabel (end_label);
                                return;
                        }
 
                        left.Emit (ec);
 
-                       ig.Emit (OpCodes.Dup);
-                       ig.Emit (OpCodes.Brtrue, end_label);
+                       ec.Emit (OpCodes.Dup);
+                       ec.Emit (OpCodes.Brtrue, end_label);
 
-                       ig.Emit (OpCodes.Pop);
+                       ec.Emit (OpCodes.Pop);
                        right.Emit (ec);
 
-                       ig.MarkLabel (end_label);
-               }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       left.MutateHoistedGenericType (storey);
-                       right.MutateHoistedGenericType (storey);
-                       type = storey.MutateType (type);
+                       ec.MarkLabel (end_label);
                }
 
                protected override void CloneTo (CloneContext clonectx, Expression t)
@@ -1151,25 +1099,24 @@ namespace Mono.CSharp.Nullable
 
                void DoEmit (EmitContext ec, bool is_expr)
                {
-                       ILGenerator ig = ec.ig;
-                       Label is_null_label = ig.DefineLabel ();
-                       Label end_label = ig.DefineLabel ();
+                       Label is_null_label = ec.DefineLabel ();
+                       Label end_label = ec.DefineLabel ();
 
                        unwrap.EmitCheck (ec);
-                       ig.Emit (OpCodes.Brfalse, is_null_label);
+                       ec.Emit (OpCodes.Brfalse, is_null_label);
 
                        if (is_expr) {
                                underlying.Emit (ec);
-                               ig.Emit (OpCodes.Br_S, end_label);
+                               ec.Emit (OpCodes.Br_S, end_label);
                        } else {
                                underlying.EmitStatement (ec);
                        }
 
-                       ig.MarkLabel (is_null_label);
+                       ec.MarkLabel (is_null_label);
                        if (is_expr)
                                LiftedNull.Create (type, loc).Emit (ec);
 
-                       ig.MarkLabel (end_label);
+                       ec.MarkLabel (end_label);
                }
 
                public override void Emit (EmitContext ec)
index 26aa628a1ee1812b811fd775a57a5b638476a045..b25bae9cae2c7fc74194537c282d522ea96ff5fc 100644 (file)
@@ -14,6 +14,7 @@ using System;
 using System.Reflection;
 using System.Reflection.Emit;
 using System.Text;
+using System.Linq;
 
 namespace Mono.CSharp {
 
@@ -24,7 +25,7 @@ namespace Mono.CSharp {
        {
                protected ParameterBuilder builder;
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
 #if false
                        if (a.Type == pa.MarshalAs) {
@@ -45,7 +46,7 @@ namespace Mono.CSharp {
                                return;
                        }
 
-                       builder.SetCustomAttribute (cb);
+                       builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
                }
 
                public ParameterBuilder Builder {
@@ -79,7 +80,7 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.Type == pa.CLSCompliant) {
                                method.Compiler.Report.Warning (3023, 1, a.Location,
@@ -90,7 +91,7 @@ namespace Mono.CSharp {
                        if (builder == null)
                                return;
 
-                       base.ApplyAttributeBuilder (a, cb, pa);
+                       base.ApplyAttributeBuilder (a, ctor, cdata, pa);
                }
 
                public override AttributeTargets AttributeTargets {
@@ -144,16 +145,17 @@ namespace Mono.CSharp {
                {
                }
 
-               public override Type Resolve (IMemberContext ec)
+               public override TypeSpec Resolve (IMemberContext ec, int index)
                {
                        if (parameter_type == null)
                                throw new InternalErrorException ("A type of implicit lambda parameter `{0}' is not set",
                                        Name);
 
+                       base.idx = index;
                        return parameter_type;
                }
 
-               public Type Type {
+               public TypeSpec Type {
                        set { parameter_type = value; }
                }
        }
@@ -164,12 +166,13 @@ namespace Mono.CSharp {
                {
                }
 
-               public override Type Resolve (IMemberContext ec)
+               public override TypeSpec Resolve (IMemberContext ec, int index)
                {
-                       if (base.Resolve (ec) == null)
+                       if (base.Resolve (ec, index) == null)
                                return null;
 
-                       if (!parameter_type.IsArray || parameter_type.GetArrayRank () != 1) {
+                       var ac = parameter_type as ArrayContainer;
+                       if (ac == null || ac.Rank != 1) {
                                ec.Compiler.Report.Error (225, Location, "The params parameter must be a single dimensional array");
                                return null;
                        }
@@ -189,6 +192,7 @@ namespace Mono.CSharp {
                public ArglistParameter (Location loc) :
                        base (null, String.Empty, Parameter.Modifier.NONE, null, loc)
                {
+                       parameter_type = InternalType.Arglist;
                }
 
                public override void  ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index)
@@ -201,14 +205,9 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public override Type Resolve (IMemberContext ec)
+               public override TypeSpec Resolve (IMemberContext ec, int index)
                {
-                       return InternalType.Arglist;
-               }
-
-               public override string GetSignatureForError ()
-               {
-                       return "__arglist";
+                       return parameter_type;
                }
        }
 
@@ -240,13 +239,13 @@ namespace Mono.CSharp {
 
                static string[] attribute_targets = new string [] { "param" };
 
-               protected FullNamedExpression TypeName;
+               FullNamedExpression texpr;
                readonly Modifier modFlags;
                string name;
                Expression default_expr;
-               protected Type parameter_type;
+               protected TypeSpec parameter_type;
                public readonly Location Location;
-               int idx;
+               protected int idx;
                public bool HasAddressTaken;
 
                Expression expr_tree_variable;
@@ -259,13 +258,21 @@ namespace Mono.CSharp {
                        this.name = name;
                        modFlags = mod;
                        Location = loc;
-                       TypeName = type;
+                       texpr = type;
 
                        // Only assign, attributes will be attached during resolve
                        base.attributes = attrs;
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+#region Properties
+               public FullNamedExpression TypeExpression  {
+                       get {
+                               return texpr;
+                       }
+               }
+#endregion
+
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.Type == pa.In && ModFlags == Modifier.OUT) {
                                a.Report.Error (36, a.Location, "An out parameter cannot have the `In' attribute");
@@ -296,34 +303,30 @@ namespace Mono.CSharp {
                        }
 
                        if (a.Type == pa.DefaultParameterValue) {
-                               object val = a.GetParameterDefaultValue ();
-                               if (val != null) {
-                                       Type t = val.GetType ();
-                                       if (t.IsArray || TypeManager.IsSubclassOf (t, TypeManager.type_type)) {
-                                               if (parameter_type == TypeManager.object_type) {
-                                                       if (!t.IsArray)
-                                                               t = TypeManager.type_type;
-
-                                                       a.Report.Error (1910, a.Location, "Argument of type `{0}' is not applicable for the DefaultParameterValue attribute",
-                                                               TypeManager.CSharpName (t));
-                                               } else {
-                                                       a.Report.Error (1909, a.Location, "The DefaultParameterValue attribute is not applicable on parameters of type `{0}'",
-                                                               TypeManager.CSharpName (parameter_type)); ;
-                                               }
-                                               return;
+                               TypeSpec arg_type;
+                               var c = a.GetParameterDefaultValue (out arg_type);
+                               if (c == null) {
+                                       if (parameter_type == TypeManager.object_type) {
+                                               a.Report.Error (1910, a.Location, "Argument of type `{0}' is not applicable for the DefaultParameterValue attribute",
+                                                       arg_type.GetSignatureForError ());
+                                       } else {
+                                               a.Report.Error (1909, a.Location, "The DefaultParameterValue attribute is not applicable on parameters of type `{0}'",
+                                                       parameter_type.GetSignatureForError ()); ;
                                        }
+
+                                       return;
                                }
 
-                               if (parameter_type == TypeManager.object_type ||
-                                   (val == null && !TypeManager.IsGenericParameter (parameter_type) && TypeManager.IsReferenceType (parameter_type)) ||
-                                   (val != null && TypeManager.TypeToCoreType (val.GetType ()) == parameter_type))
-                                       builder.SetConstant (val);
+                               if (arg_type == parameter_type || parameter_type == TypeManager.object_type || 
+                                       (c.IsNull && TypeManager.IsReferenceType (parameter_type) && !TypeManager.IsGenericParameter (parameter_type)))
+                                       builder.SetConstant (c.GetValue ());
                                else
                                        a.Report.Error (1908, a.Location, "The type of the default value should match the type of the parameter");
+
                                return;
                        }
 
-                       base.ApplyAttributeBuilder (a, cb, pa);
+                       base.ApplyAttributeBuilder (a, ctor, cdata, pa);
                }
                
                public virtual bool CheckAccessibility (InterfaceMemberBase member)
@@ -334,10 +337,15 @@ namespace Mono.CSharp {
                        return member.IsAccessibleAs (parameter_type);
                }
 
+               public static void Reset ()
+               {
+                       parameter_expr_tree_type = null;
+               }
+
                // <summary>
                //   Resolve is used in method definitions
                // </summary>
-               public virtual Type Resolve (IMemberContext rc)
+               public virtual TypeSpec Resolve (IMemberContext rc, int index)
                {
                        if (parameter_type != null)
                                return parameter_type;
@@ -345,20 +353,19 @@ namespace Mono.CSharp {
                        if (attributes != null)
                                attributes.AttachTo (this, rc);
 
-                       TypeExpr texpr = TypeName.ResolveAsTypeTerminal (rc, false);
-                       if (texpr == null)
+                       var expr = texpr.ResolveAsTypeTerminal (rc, false);
+                       if (expr == null)
                                return null;
 
+                       this.idx = index;
+                       texpr = expr;
                        parameter_type = texpr.Type;
 
                        // Ignore all checks for dummy members
                        AbstractPropertyEventMethod pem = rc as AbstractPropertyEventMethod;
                        if (pem != null && pem.IsDummy)
                                return parameter_type;
-
-                       if (default_expr != null)
-                               default_expr = ResolveDefaultValue (new ResolveContext (rc));
-
+                       
                        if ((modFlags & Parameter.Modifier.ISBYREF) != 0 &&
                                TypeManager.IsSpecialType (parameter_type)) {
                                rc.Compiler.Report.Error (1601, Location, "Method or delegate parameter cannot be of type `{0}'",
@@ -370,16 +377,13 @@ namespace Mono.CSharp {
                                (modFlags & Parameter.Modifier.ISBYREF) != 0 ? Variance.None : Variance.Contravariant,
                                rc);
 
-                       if (TypeManager.IsGenericParameter (parameter_type))
-                               return parameter_type;
-
-                       if ((parameter_type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
+                       if (parameter_type.IsStatic) {
                                rc.Compiler.Report.Error (721, Location, "`{0}': static types cannot be used as parameters",
                                        texpr.GetSignatureForError ());
                                return parameter_type;
                        }
 
-                       if ((modFlags & Modifier.This) != 0 && (parameter_type.IsPointer || TypeManager.IsDynamicType (parameter_type))) {
+                       if ((modFlags & Modifier.This) != 0 && (parameter_type.IsPointer || parameter_type == InternalType.Dynamic)) {
                                rc.Compiler.Report.Error (1103, Location, "The extension method cannot be of type `{0}'",
                                        TypeManager.CSharpName (parameter_type));
                        }
@@ -387,7 +391,13 @@ namespace Mono.CSharp {
                        return parameter_type;
                }
 
-               Expression ResolveDefaultValue (ResolveContext rc)
+               public void ResolveDefaultValue (ResolveContext rc)
+               {
+                       if (default_expr != null)
+                               default_expr = ResolveDefaultExpression (rc);
+               }
+
+               Expression ResolveDefaultExpression (ResolveContext rc)
                {
                        default_expr = default_expr.Resolve (rc);
                        if (default_expr == null)
@@ -435,11 +445,6 @@ namespace Mono.CSharp {
                        return null;
                }
 
-               public void ResolveVariable (int idx)
-               {
-                       this.idx = idx;
-               }
-
                public bool HasDefaultValue {
                        get { return default_expr != null; }
                }
@@ -486,7 +491,7 @@ namespace Mono.CSharp {
                        if (parameter_type != null)
                                type_name = TypeManager.CSharpName (parameter_type);
                        else
-                               type_name = TypeName.GetSignatureForError ();
+                               type_name = texpr.GetSignatureForError ();
 
                        string mod = GetModifierSignature (modFlags);
                        if (mod.Length > 0)
@@ -513,7 +518,7 @@ namespace Mono.CSharp {
 
                public void IsClsCompliant (IMemberContext ctx)
                {
-                       if (AttributeTester.IsClsCompliant (parameter_type))
+                       if (parameter_type.IsCLSCompliant ())
                                return;
 
                        ctx.Compiler.Report.Warning (3001, 1, Location,
@@ -545,13 +550,13 @@ namespace Mono.CSharp {
                                }
                        }
 
-                       if (TypeManager.IsDynamicType (parameter_type)) {
+                       if (parameter_type == InternalType.Dynamic) {
                                PredefinedAttributes.Get.Dynamic.EmitAttribute (builder);
                        } else {
                                var trans_flags = TypeManager.HasDynamicTypeUsed (parameter_type);
                                if (trans_flags != null) {
                                        var pa = PredefinedAttributes.Get.DynamicTransform;
-                                       if (pa.Constructor != null || pa.ResolveConstructor (Location, TypeManager.bool_type.MakeArrayType ())) {
+                                       if (pa.Constructor != null || pa.ResolveConstructor (Location, ArrayContainer.MakeType (TypeManager.bool_type))) {
                                                builder.SetCustomAttribute (
                                                        new CustomAttributeBuilder (pa.Constructor, new object [] { trans_flags }));
                                        }
@@ -601,7 +606,7 @@ namespace Mono.CSharp {
                        if (!ec.IsStatic)
                                arg_idx++;
 
-                       ParameterReference.EmitLdArg (ec.ig, arg_idx);
+                       ParameterReference.EmitLdArg (ec, arg_idx);
                }
 
                public void EmitAssign (EmitContext ec)
@@ -611,9 +616,9 @@ namespace Mono.CSharp {
                                arg_idx++;
 
                        if (arg_idx <= 255)
-                               ec.ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
+                               ec.Emit (OpCodes.Starg_S, (byte) arg_idx);
                        else
-                               ec.ig.Emit (OpCodes.Starg, arg_idx);
+                               ec.Emit (OpCodes.Starg, arg_idx);
                }
 
                public void EmitAddressOf (EmitContext ec)
@@ -625,12 +630,12 @@ namespace Mono.CSharp {
 
                        bool is_ref = (ModFlags & Modifier.ISBYREF) != 0;
                        if (is_ref) {
-                               ParameterReference.EmitLdArg (ec.ig, arg_idx);
+                               ParameterReference.EmitLdArg (ec, arg_idx);
                        } else {
                                if (arg_idx <= 255)
-                                       ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
+                                       ec.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
                                else
-                                       ec.ig.Emit (OpCodes.Ldarga, arg_idx);
+                                       ec.Emit (OpCodes.Ldarga, arg_idx);
                        }
                }
 
@@ -647,7 +652,7 @@ namespace Mono.CSharp {
                        if (parameter_expr_tree_type != null)
                                return parameter_expr_tree_type;
 
-                       Type p_type = TypeManager.parameter_expression_type;
+                       TypeSpec p_type = TypeManager.parameter_expression_type;
                        if (p_type == null) {
                                p_type = TypeManager.CoreLookupType (ec.Compiler, "System.Linq.Expressions", "ParameterExpression", MemberKind.Class, true);
                                TypeManager.parameter_expression_type = p_type;
@@ -720,11 +725,7 @@ namespace Mono.CSharp {
 
                // Null object pattern
                protected IParameterData [] parameters;
-               protected Type [] types;
-
-               public ParametersCompiled AsCompiled {
-                       get { return (ParametersCompiled) this; }
-               }
+               protected TypeSpec [] types;
 
                public CallingConventions CallingConvention {
                        get {
@@ -738,7 +739,7 @@ namespace Mono.CSharp {
                        get { return parameters.Length; }
                }
 
-               public Type ExtensionMethodType {
+               public TypeSpec ExtensionMethodType {
                        get {
                                if (Count == 0)
                                        return null;
@@ -760,30 +761,32 @@ namespace Mono.CSharp {
                                ParameterAttributes.Out : ParameterAttributes.None;
                }
 
-               public Type [] GetEmitTypes ()
+               // Very expensive operation
+               public Type[] GetMetaInfo ()
                {
-                       Type [] types = null;
+                       Type[] types;
                        if (has_arglist) {
                                if (Count == 1)
                                        return Type.EmptyTypes;
 
                                types = new Type [Count - 1];
-                               Array.Copy (Types, types, types.Length);
+                       } else {
+                               if (Count == 0)
+                                       return Type.EmptyTypes;
+
+                               types = new Type [Count];
                        }
 
-                       for (int i = 0; i < Count; ++i) {
+                       for (int i = 0; i < types.Length; ++i) {
+                               types[i] = Types[i].GetMetaInfo ();
+
                                if ((FixedParameters [i].ModFlags & Parameter.Modifier.ISBYREF) == 0)
                                        continue;
 
-                               if (types == null)
-                                       types = (Type []) Types.Clone ();
-
-                               types [i] = TypeManager.GetReferenceType (types [i]);
+                               // TODO MemberCache: Should go to MetaInfo getter
+                               types [i] = types [i].MakeByRefType ();
                        }
 
-                       if (types == null)
-                               types = Types;
-
                        return types;
                }
 
@@ -802,13 +805,18 @@ namespace Mono.CSharp {
 
                public string GetSignatureForError ()
                {
-                       StringBuilder sb = new StringBuilder ("(");
-                       for (int i = 0; i < Count; ++i) {
+                       return GetSignatureForError ("(", ")", Count);
+               }
+
+               public string GetSignatureForError (string start, string end, int count)
+               {
+                       StringBuilder sb = new StringBuilder (start);
+                       for (int i = 0; i < count; ++i) {
                                if (i != 0)
                                        sb.Append (", ");
                                sb.Append (ParameterDesc (i));
                        }
-                       sb.Append (')');
+                       sb.Append (end);
                        return sb.ToString ();
                }
 
@@ -833,6 +841,43 @@ namespace Mono.CSharp {
                        get { return parameters.Length == 0; }
                }
 
+               public AParametersCollection Inflate (TypeParameterInflator inflator)
+               {
+                       TypeSpec[] inflated_types = null;
+                       bool default_value = false;
+
+                       for (int i = 0; i < Count; ++i) {
+                               var inflated_param = inflator.Inflate (types[i]);
+                               if (inflated_types == null) {
+                                       if (inflated_param == types[i])
+                                               continue;
+
+                                       default_value |= FixedParameters[i] is DefaultValueExpression;
+                                       inflated_types = new TypeSpec[types.Length];
+                                       Array.Copy (types, inflated_types, types.Length);       
+                               }
+
+                               inflated_types[i] = inflated_param;
+                       }
+
+                       if (inflated_types == null)
+                               return this;
+
+                       var clone = (AParametersCollection) MemberwiseClone ();
+                       clone.types = inflated_types;
+                       if (default_value) {
+                               for (int i = 0; i < Count; ++i) {
+                                       var dve = clone.FixedParameters[i] as DefaultValueExpression;
+                                       if (dve != null) {
+                                               throw new NotImplementedException ("net");
+                                               //      clone.FixedParameters [i].DefaultValue = new DefaultValueExpression ();
+                                       }
+                               }
+                       }
+
+                       return clone;
+               }
+
                public string ParameterDesc (int pos)
                {
                        if (types == null || types [pos] == null)
@@ -849,42 +894,10 @@ namespace Mono.CSharp {
                        return Parameter.GetModifierSignature (mod) + " " + type;
                }
 
-               public Type[] Types {
+               public TypeSpec[] Types {
                        get { return types; }
                        set { types = value; }
                }
-
-#if MS_COMPATIBLE
-               public AParametersCollection InflateTypes (Type[] genArguments, Type[] argTypes)
-               {
-                       AParametersCollection p = (AParametersCollection) MemberwiseClone (); // Clone ();
-
-                       for (int i = 0; i < Count; ++i) {
-                               if (types[i].IsGenericType) {
-                                       Type[] gen_arguments_open = new Type[types[i].GetGenericTypeDefinition ().GetGenericArguments ().Length];
-                                       Type[] gen_arguments = types[i].GetGenericArguments ();
-                                       for (int ii = 0; ii < gen_arguments_open.Length; ++ii) {
-                                               if (gen_arguments[ii].IsGenericParameter) {
-                                                       Type t = argTypes[gen_arguments[ii].GenericParameterPosition];
-                                                       gen_arguments_open[ii] = t;
-                                               } else
-                                                       gen_arguments_open[ii] = gen_arguments[ii];
-                                       }
-
-                                       p.types[i] = types[i].GetGenericTypeDefinition ().MakeGenericType (gen_arguments_open);
-                                       continue;
-                               }
-
-                               if (types[i].IsGenericParameter) {
-                                       Type gen_argument = argTypes[types[i].GenericParameterPosition];
-                                       p.types[i] = gen_argument;
-                                       continue;
-                               }
-                       }
-
-                       return p;
-               }
-#endif
        }
 
        //
@@ -892,7 +905,7 @@ namespace Mono.CSharp {
        //
        public class ParametersImported : AParametersCollection
        {
-               ParametersImported (AParametersCollection param, Type[] types)
+               ParametersImported (AParametersCollection param, TypeSpec[] types)
                {
                        this.parameters = param.FixedParameters;
                        this.types = types;
@@ -900,7 +913,7 @@ namespace Mono.CSharp {
                        has_params = param.HasParams;
                }
 
-               ParametersImported (IParameterData [] parameters, Type [] types, bool hasArglist, bool hasParams)
+               ParametersImported (IParameterData [] parameters, TypeSpec [] types, bool hasArglist, bool hasParams)
                {
                        this.parameters = parameters;
                        this.types = types;
@@ -908,60 +921,36 @@ namespace Mono.CSharp {
                        this.has_params = hasParams;
                }
 
-               public ParametersImported (IParameterData [] param, Type[] types)
+               public ParametersImported (IParameterData [] param, TypeSpec[] types)
                {
                        this.parameters = param;
                        this.types = types;
                }
 
-               public static AParametersCollection Create (MethodBase method)
+               public static AParametersCollection Create (TypeSpec parent, MethodBase method)
                {
-                       return Create (method.GetParameters (), method);
-               }
-
-               //
-               // Generic method parameters importer, param is shared between all instances
-               //
-               public static AParametersCollection Create (AParametersCollection param, MethodBase method)
-               {
-                       if (param.IsEmpty)
-                               return param;
-
-                       ParameterInfo [] pi = method.GetParameters ();
-                       Type [] types = new Type [pi.Length];
-                       for (int i = 0; i < types.Length; i++) {
-                               Type t = pi [i].ParameterType;
-                               if (t.IsByRef)
-                                       t = TypeManager.GetElementType (t);
-
-                               types [i] = TypeManager.TypeToCoreType (t);
-                       }
-
-                       return new ParametersImported (param, types);
+                       return Create (parent, method.GetParameters (), method);
                }
 
                //
                // Imports SRE parameters
                //
-               public static AParametersCollection Create (ParameterInfo [] pi, MethodBase method)
+               public static AParametersCollection Create (TypeSpec parent, ParameterInfo [] pi, MethodBase method)
                {
                        int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
 
                        if (pi.Length == 0 && varargs == 0)
                                return ParametersCompiled.EmptyReadOnlyParameters;
 
-                       Type [] types = new Type [pi.Length + varargs];
+                       TypeSpec [] types = new TypeSpec [pi.Length + varargs];
                        IParameterData [] par = new IParameterData [pi.Length + varargs];
                        bool is_params = false;
                        PredefinedAttribute extension_attr = PredefinedAttributes.Get.Extension;
-                       PredefinedAttribute param_attr = PredefinedAttributes.Get.ParamArray;
                        for (int i = 0; i < pi.Length; i++) {
-                               types [i] = TypeManager.TypeToCoreType (pi [i].ParameterType);
-
                                ParameterInfo p = pi [i];
                                Parameter.Modifier mod = 0;
                                Expression default_value = null;
-                               if (types [i].IsByRef) {
+                               if (p.ParameterType.IsByRef) {
                                        if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
                                                mod = Parameter.Modifier.OUT;
                                        else
@@ -970,14 +959,17 @@ namespace Mono.CSharp {
                                        //
                                        // Strip reference wrapping
                                        //
-                                       types [i] = TypeManager.GetElementType (types [i]);
-                               } else if (i == 0 && extension_attr.IsDefined && method != null && method.IsStatic &&
-                               (method.DeclaringType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute &&
-                                       method.IsDefined (extension_attr.Type, false)) {
+                                       types [i] = Import.ImportType (p.ParameterType.GetElementType ());
+                               } else if (i == 0 && method.IsStatic && parent.IsStatic &&
+                                       extension_attr.IsDefined && extension_attr.IsDefined && method.IsDefined (extension_attr.Type.GetMetaInfo (), false)) {
                                        mod = Parameter.Modifier.This;
+                                       types[i] = Import.ImportType (p.ParameterType);
                                } else {
-                                       if (i >= pi.Length - 2 && types[i].IsArray) {
-                                               if (p.IsDefined (param_attr.Type, false)) {
+                                       types[i] = Import.ImportType (p.ParameterType);
+
+                                       if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
+                                               var cattrs = CustomAttributeData.GetCustomAttributes (p);
+                                               if (cattrs != null && cattrs.Any (l => l.Constructor.DeclaringType == typeof (ParamArrayAttribute))) {
                                                        mod = Parameter.Modifier.PARAMS;
                                                        is_params = true;
                                                }
@@ -990,7 +982,7 @@ namespace Mono.CSharp {
                                                } else if (value == null) {
                                                        default_value = new NullLiteral (Location.Null);
                                                } else {
-                                                       default_value = Constant.CreateConstant (null, value.GetType (), value, Location.Null);
+                                                       default_value = Constant.CreateConstant (null, Import.ImportType (value.GetType ()), value, Location.Null);
                                                }
                                        }
                                }
@@ -1022,10 +1014,10 @@ namespace Mono.CSharp {
                private ParametersCompiled ()
                {
                        parameters = new Parameter [0];
-                       types = Type.EmptyTypes;
+                       types = TypeSpec.EmptyTypes;
                }
 
-               private ParametersCompiled (Parameter [] parameters, Type [] types)
+               private ParametersCompiled (IParameterData [] parameters, TypeSpec [] types)
                {
                        this.parameters = parameters;
                    this.types = types;
@@ -1067,34 +1059,85 @@ namespace Mono.CSharp {
                        this.has_arglist = has_arglist;
                }
                
-               public static ParametersCompiled CreateFullyResolved (Parameter p, Type type)
+               public static ParametersCompiled CreateFullyResolved (Parameter p, TypeSpec type)
                {
-                       return new ParametersCompiled (new Parameter [] { p }, new Type [] { type });
+                       return new ParametersCompiled (new Parameter [] { p }, new TypeSpec [] { type });
                }
                
-               public static ParametersCompiled CreateFullyResolved (Parameter[] parameters, Type[] types)
+               public static ParametersCompiled CreateFullyResolved (IParameterData[] parameters, TypeSpec[] types)
                {
                        return new ParametersCompiled (parameters, types);
                }
 
-               public static ParametersCompiled MergeGenerated (CompilerContext ctx, ParametersCompiled userParams, bool checkConflicts, Parameter compilerParams, Type compilerTypes)
+               public static AParametersCollection CreateFullyResolved (TypeSpec[] types)
+               {
+                       var pd = new ParameterData [types.Length];
+                       for (int i = 0; i < pd.Length; ++i)
+                               pd[i] = new ParameterData (null, Parameter.Modifier.NONE, null);
+
+                       return new ParametersCompiled (pd, types);
+               }
+
+               //
+               // Returns non-zero value for equal CLS parameter signatures
+               //
+               public static int IsSameClsSignature (AParametersCollection a, AParametersCollection b)
+               {
+                       int res = 0;
+
+                       for (int i = 0; i < a.Count; ++i) {
+                               var a_type = a.Types[i];
+                               var b_type = b.Types[i];
+                               if (TypeSpecComparer.Override.IsEqual (a_type, b_type)) {
+                                       const Parameter.Modifier ref_out = Parameter.Modifier.REF | Parameter.Modifier.OUT;
+                                       if ((a.FixedParameters[i].ModFlags & ref_out) != (b.FixedParameters[i].ModFlags & ref_out))
+                                               res |= 1;
+
+                                       continue;
+                               }
+
+                               var ac_a = a_type as ArrayContainer;
+                               if (ac_a == null)
+                                       return 0;
+
+                               var ac_b = b_type as ArrayContainer;
+                               if (ac_b == null)
+                                       return 0;
+
+                               if (ac_a.Element is ArrayContainer || ac_b.Element is ArrayContainer) {
+                                       res |= 2;
+                                       continue;
+                               }
+
+                               if (ac_a.Rank != ac_b.Rank && TypeSpecComparer.Override.IsEqual (ac_a.Element, ac_b.Element)) {
+                                       res |= 1;
+                                       continue;
+                               }
+
+                               return 0;
+                       }
+
+                       return res;
+               }
+
+               public static ParametersCompiled MergeGenerated (CompilerContext ctx, ParametersCompiled userParams, bool checkConflicts, Parameter compilerParams, TypeSpec compilerTypes)
                {
                        return MergeGenerated (ctx, userParams, checkConflicts,
                                new Parameter [] { compilerParams },
-                               new Type [] { compilerTypes });
+                               new TypeSpec [] { compilerTypes });
                }
 
                //
                // Use this method when you merge compiler generated parameters with user parameters
                //
-               public static ParametersCompiled MergeGenerated (CompilerContext ctx, ParametersCompiled userParams, bool checkConflicts, Parameter[] compilerParams, Type[] compilerTypes)
+               public static ParametersCompiled MergeGenerated (CompilerContext ctx, ParametersCompiled userParams, bool checkConflicts, Parameter[] compilerParams, TypeSpec[] compilerTypes)
                {
                        Parameter[] all_params = new Parameter [userParams.Count + compilerParams.Length];
                        userParams.FixedParameters.CopyTo(all_params, 0);
 
-                       Type [] all_types;
+                       TypeSpec [] all_types;
                        if (userParams.types != null) {
-                               all_types = new Type [all_params.Length];
+                               all_types = new TypeSpec [all_params.Length];
                                userParams.Types.CopyTo (all_types, 0);
                        } else {
                                all_types = null;
@@ -1133,13 +1176,13 @@ namespace Mono.CSharp {
                        if (types != null)
                                return true;
                        
-                       types = new Type [Count];
+                       types = new TypeSpec [Count];
                        
                        bool ok = true;
                        Parameter p;
                        for (int i = 0; i < FixedParameters.Length; ++i) {
                                p = this [i];
-                               Type t = p.Resolve (ec);
+                               TypeSpec t = p.Resolve (ec, i);
                                if (t == null) {
                                        ok = false;
                                        continue;
@@ -1151,10 +1194,10 @@ namespace Mono.CSharp {
                        return ok;
                }
 
-               public void ResolveVariable ()
+               public void ResolveDefaultValues (ResolveContext rc)
                {
                        for (int i = 0; i < FixedParameters.Length; ++i) {
-                               this [i].ResolveVariable (i);
+                               this [i].ResolveDefaultValue (rc);
                        }
                }
 
index e2aed9a1cf31e5fd7bebe0deb14a21c3dfbf6624..9e2e5c40ba7ffa650438e53a6b32dfea40c41680 100644 (file)
@@ -1,8 +1,9 @@
 //
 // pending.cs: Pending method implementation
 //
-// Author:
+// Authors:
 //   Miguel de Icaza (miguel@gnu.org)
+//   Marek Safar (marek.safar@gmail.com)
 //
 // Dual licensed under the terms of the MIT X11 or GNU GPL
 //
@@ -14,12 +15,13 @@ using System;
 using System.Collections.Generic;
 using System.Reflection;
 using System.Reflection.Emit;
+using System.Linq;
 
 namespace Mono.CSharp {
 
        struct TypeAndMethods {
-               public Type          type;
-               public MethodInfo [] methods;
+               public TypeSpec          type;
+               public IList<MethodSpec> methods;
 
                // 
                // Whether it is optional, this is used to allow the explicit/implicit
@@ -30,14 +32,7 @@ namespace Mono.CSharp {
                // class X : IA { }  class Y : X, IA { IA.Explicit (); }
                //
                public bool          optional;
-               
-               // Far from ideal, but we want to avoid creating a copy
-               // of methods above.
-               public Type [][]     args;
-
-               //This is used to store the modifiers of arguments
-               public Parameter.Modifier [][] mods;
-               
+                               
                //
                // This flag on the method says `We found a match, but
                // because it was private, we could not use the match
@@ -47,95 +42,25 @@ namespace Mono.CSharp {
                // If a method is defined here, then we always need to
                // create a proxy for it.  This is used when implementing
                // an interface's indexer with a different IndexerName.
-               public MethodInfo [] need_proxy;
+               public MethodSpec [] need_proxy;
        }
 
-       public class PendingImplementation {
+       public class PendingImplementation
+       {
                /// <summary>
                ///   The container for this PendingImplementation
                /// </summary>
                TypeContainer container;
                
-               /// <summary>
-               ///   This filter is used by FindMembers, and it is used to
-               ///   extract only virtual/abstract fields
-               /// </summary>
-               static MemberFilter virtual_method_filter;
-
                /// <summary>
                ///   This is the array of TypeAndMethods that describes the pending implementations
                ///   (both interfaces and abstract methods in base class)
                /// </summary>
                TypeAndMethods [] pending_implementations;
 
-               static bool IsVirtualFilter (MemberInfo m, object filterCriteria)
-               {
-                       MethodInfo mi = m as MethodInfo;
-                       return (mi == null) ? false : mi.IsVirtual;
-               }
-
-               /// <summary>
-               ///   Inits the virtual_method_filter
-               /// </summary>
-               static PendingImplementation ()
-               {
-                       virtual_method_filter = new MemberFilter (IsVirtualFilter);
-               }
-
-               // <remarks>
-               //   Returns a list of the abstract methods that are exposed by all of our
-               //   bases that we must implement.  Notice that this `flattens' the
-               //   method search space, and takes into account overrides.  
-               // </remarks>
-               static IList<MethodBase> GetAbstractMethods (Type t)
-               {
-                       List<MethodBase> list = null;
-                       bool searching = true;
-                       Type current_type = t;
-                       
-                       do {
-                               MemberList mi;
-                               
-                               mi = TypeContainer.FindMembers (
-                                       current_type, MemberTypes.Method,
-                                       BindingFlags.Public | BindingFlags.NonPublic |
-                                       BindingFlags.Instance | BindingFlags.DeclaredOnly,
-                                       virtual_method_filter, null);
-
-                               if (current_type == TypeManager.object_type)
-                                       searching = false;
-                               else {
-                                       current_type = current_type.BaseType;
-                                       if (!current_type.IsAbstract)
-                                               searching = false;
-                               }
-
-                               if (mi.Count == 0)
-                                       continue;
-
-                               if (mi.Count == 1 && !(mi [0] is MethodBase))
-                                       searching = false;
-                               else 
-                                       list = TypeManager.CopyNewMethods (list, mi);
-                       } while (searching);
-
-                       if (list == null)
-                               return null;
-                       
-                       for (int i = 0; i < list.Count; i++){
-                               while (list.Count > i && !((MethodInfo) list [i]).IsAbstract)
-                                       list.RemoveAt (i);
-                       }
-
-                       if (list.Count == 0)
-                               return null;
-
-                       return list;
-               }
-
-               PendingImplementation (TypeContainer container, MissingInterfacesInfo[] missing_ifaces, IList<MethodBase> abstract_methods, int total)
+               PendingImplementation (TypeContainer container, MissingInterfacesInfo[] missing_ifaces, IList<MethodSpec> abstract_methods, int total)
                {
-                       TypeBuilder type_builder = container.TypeBuilder;
+                       var type_builder = container.Definition;
                        
                        this.container = container;
                        pending_implementations = new TypeAndMethods [total];
@@ -143,91 +68,34 @@ namespace Mono.CSharp {
                        int i = 0;
                        if (abstract_methods != null) {
                                int count = abstract_methods.Count;
-                               pending_implementations [i].methods = new MethodInfo [count];
-                               pending_implementations [i].need_proxy = new MethodInfo [count];
-                               
-                               abstract_methods.CopyTo (pending_implementations [i].methods, 0);
+                               pending_implementations [i].methods = new MethodSpec [count];
+                               pending_implementations [i].need_proxy = new MethodSpec [count];
+
+                               pending_implementations [i].methods = abstract_methods;
                                pending_implementations [i].found = new MethodData [count];
-                               pending_implementations [i].args = new Type [count][];
-                               pending_implementations [i].mods = new Parameter.Modifier [count][];
                                pending_implementations [i].type = type_builder;
-
-                               int j = 0;
-                               foreach (MemberInfo m in abstract_methods) {
-                                       MethodInfo mi = (MethodInfo) m;
-                                       
-                                       AParametersCollection pd = TypeManager.GetParameterData (mi);
-                                       Type [] types = pd.Types;
-                                       
-                                       pending_implementations [i].args [j] = types;
-                                       pending_implementations [i].mods [j] = null;
-                                       if (pd.Count > 0) {
-                                               Parameter.Modifier [] pm = new Parameter.Modifier [pd.Count];
-                                               for (int k = 0; k < pd.Count; k++)
-                                                       pm [k] = pd.FixedParameters[k].ModFlags;
-                                               pending_implementations [i].mods [j] = pm;
-                                       }
-                                               
-                                       j++;
-                               }
                                ++i;
                        }
 
                        foreach (MissingInterfacesInfo missing in missing_ifaces) {
-                               MethodInfo [] mi;
-                               Type t = missing.Type;
-                               
-                               if (!t.IsInterface)
-                                       continue;
-
-                               if (t is TypeBuilder){
-                                       TypeContainer iface;
+                               var iface = missing.Type;
+                               var mi = MemberCache.GetInterfaceMembers (iface);
 
-                                       iface = TypeManager.LookupInterface (t);
-                                       
-                                       mi = iface.GetMethods ();
-                               } else 
-                                       mi = t.GetMethods ();
-                               
-                               int count = mi.Length;
-                               pending_implementations [i].type = t;
+                               int count = mi.Count;
+                               pending_implementations [i].type = iface;
                                pending_implementations [i].optional = missing.Optional;
                                pending_implementations [i].methods = mi;
-                               pending_implementations [i].args = new Type [count][];
-                               pending_implementations [i].mods = new Parameter.Modifier [count][];
                                pending_implementations [i].found = new MethodData [count];
-                               pending_implementations [i].need_proxy = new MethodInfo [count];
-                               
-                               int j = 0;
-                               foreach (MethodInfo m in mi){
-                                       pending_implementations [i].args [j] = Type.EmptyTypes;
-                                       pending_implementations [i].mods [j] = null;
-
-                                       // If there is a previous error, just ignore
-                                       if (m == null)
-                                               continue;
-
-                                       AParametersCollection pd = TypeManager.GetParameterData (m);
-                                       pending_implementations [i].args [j] = pd.Types;
-                                       
-                                       if (pd.Count > 0){
-                                               Parameter.Modifier [] pm = new Parameter.Modifier [pd.Count];
-                                               for (int k = 0; k < pd.Count; k++)
-                                                       pm [k] = pd.FixedParameters [k].ModFlags;
-                                               pending_implementations [i].mods [j] = pm;
-                                       }
-                       
-                                       j++;
-                               }
+                               pending_implementations [i].need_proxy = new MethodSpec [count];
                                i++;
                        }
                }
 
                struct MissingInterfacesInfo {
-                       public Type Type;
+                       public TypeSpec Type;
                        public bool Optional;
 
-                       public MissingInterfacesInfo (Type t)
+                       public MissingInterfacesInfo (TypeSpec t)
                        {
                                Type = t;
                                Optional = false;
@@ -236,42 +104,40 @@ namespace Mono.CSharp {
 
                static MissingInterfacesInfo [] EmptyMissingInterfacesInfo = new MissingInterfacesInfo [0];
                
-               static MissingInterfacesInfo [] GetMissingInterfaces (TypeBuilder type_builder)
+               static MissingInterfacesInfo [] GetMissingInterfaces (TypeContainer container)
                {
                        //
-                       // Notice that TypeBuilders will only return the interfaces that the Type
+                       // Notice that Interfaces will only return the interfaces that the Type
                        // is supposed to implement, not all the interfaces that the type implements.
                        //
-                       // Even better -- on MS it returns an empty array, no matter what.
-                       //
-                       // Completely broken.  So we do it ourselves!
-                       //
-                       Type [] impl = TypeManager.GetExplicitInterfaces (type_builder);
+                       var impl = container.Definition.Interfaces;
 
-                       if (impl == null || impl.Length == 0)
+                       if (impl == null || impl.Count == 0)
                                return EmptyMissingInterfacesInfo;
 
-                       MissingInterfacesInfo [] ret = new MissingInterfacesInfo [impl.Length];
+                       MissingInterfacesInfo[] ret = new MissingInterfacesInfo[impl.Count];
 
-                       for (int i = 0; i < impl.Length; i++)
+                       for (int i = 0; i < impl.Count; i++)
                                ret [i] = new MissingInterfacesInfo (impl [i]);
 
                        // we really should not get here because Object doesnt implement any
                        // interfaces. But it could implement something internal, so we have
                        // to handle that case.
-                       if (type_builder.BaseType == null)
+                       if (container.BaseType == null)
                                return ret;
                        
-                       Type [] base_impls = TypeManager.GetInterfaces (type_builder.BaseType);
-                       
-                       foreach (Type t in base_impls) {
-                               for (int i = 0; i < ret.Length; i ++) {
-                                       if (t == ret [i].Type) {
-                                               ret [i].Optional = true;
-                                               break;
+                       var base_impls = container.BaseType.Interfaces;
+                       if (base_impls != null) {
+                               foreach (TypeSpec t in base_impls) {
+                                       for (int i = 0; i < ret.Length; i++) {
+                                               if (t == ret[i].Type) {
+                                                       ret[i].Optional = true;
+                                                       break;
+                                               }
                                        }
                                }
                        }
+
                        return ret;
                }
                
@@ -284,11 +150,9 @@ namespace Mono.CSharp {
                //
                static public PendingImplementation GetPendingImplementations (TypeContainer container)
                {
-                       TypeBuilder type_builder = container.TypeBuilder;
-                       MissingInterfacesInfo [] missing_interfaces;
-                       Type b = type_builder.BaseType;
+                       TypeSpec b = container.BaseType;
 
-                       missing_interfaces = GetMissingInterfaces (type_builder);
+                       var missing_interfaces = GetMissingInterfaces (container);
 
                        //
                        // If we are implementing an abstract class, and we are not
@@ -298,11 +162,11 @@ namespace Mono.CSharp {
                        //
                        // We also pre-compute the methods.
                        //
-                       bool implementing_abstract = ((b != null) && b.IsAbstract && !type_builder.IsAbstract);
-                       IList<MethodBase> abstract_methods = null;
+                       bool implementing_abstract = ((b != null) && b.IsAbstract && (container.ModFlags & Modifiers.ABSTRACT) == 0);
+                       IList<MethodSpec> abstract_methods = null;
 
                        if (implementing_abstract){
-                               abstract_methods = GetAbstractMethods (b);
+                               abstract_methods = MemberCache.GetNotImplementedAbstractMethods (b);
                                
                                if (abstract_methods == null)
                                        implementing_abstract = false;
@@ -326,12 +190,12 @@ namespace Mono.CSharp {
                /// <summary>
                ///   Whether the specified method is an interface method implementation
                /// </summary>
-               public MethodInfo IsInterfaceMethod (string name, Type ifaceType, MethodData method)
+               public MethodSpec IsInterfaceMethod (MemberName name, TypeSpec ifaceType, MethodData method)
                {
                        return InterfaceMethod (name, ifaceType, method, Operation.Lookup);
                }
 
-               public void ImplementMethod (string name, Type ifaceType, MethodData method, bool clear_one) 
+               public void ImplementMethod (MemberName name, TypeSpec ifaceType, MethodData method, bool clear_one) 
                {
                        InterfaceMethod (name, ifaceType, method, clear_one ? Operation.ClearOne : Operation.ClearAll);
                }
@@ -353,38 +217,45 @@ namespace Mono.CSharp {
                ///   that was used in the interface, then we always need to create a proxy for it.
                ///
                /// </remarks>
-               public MethodInfo InterfaceMethod (string name, Type iType, MethodData method, Operation op)
+               public MethodSpec InterfaceMethod (MemberName name, TypeSpec iType, MethodData method, Operation op)
                {
                        if (pending_implementations == null)
                                return null;
 
-                       Type ret_type = method.method.ReturnType;
+                       TypeSpec ret_type = method.method.ReturnType;
                        ParametersCompiled args = method.method.ParameterInfo;
-                       int arg_len = args.Count;
                        bool is_indexer = method.method is Indexer.SetIndexerMethod || method.method is Indexer.GetIndexerMethod;
 
                        foreach (TypeAndMethods tm in pending_implementations){
                                if (!(iType == null || tm.type == iType))
                                        continue;
 
-                               int method_count = tm.methods.Length;
-                               MethodInfo m;
+                               int method_count = tm.methods.Count;
+                               MethodSpec m;
                                for (int i = 0; i < method_count; i++){
                                        m = tm.methods [i];
 
                                        if (m == null)
                                                continue;
 
-                                       //
-                                       // Check if we have the same parameters
-                                       //
+                                       if (is_indexer) {
+                                               if (!m.IsAccessor || m.Parameters.IsEmpty)
+                                                       continue;
+                                       } else {
+                                               if (name.Name != m.Name)
+                                                       continue;
 
-                                       if (tm.args [i] == null && arg_len != 0)
-                                               continue;
-                                       if (tm.args [i] != null && tm.args [i].Length != arg_len)
+                                               if (m.Arity != name.Arity)
+                                                       continue;
+                                       }
+
+                                       if (!TypeSpecComparer.Override.IsEqual (m.Parameters, args))
                                                continue;
 
-                                       string mname = TypeManager.GetMethodName (m);
+                                       if (!TypeSpecComparer.Override.IsEqual (m.ReturnType, ret_type)) {
+                                               tm.found[i] = method;
+                                               continue;
+                                       }
 
                                        //
                                        // `need_proxy' is not null when we're implementing an
@@ -394,45 +265,6 @@ namespace Mono.CSharp {
                                        // signature and not on the name (this is done in the Lookup
                                        // for an interface indexer).
                                        //
-
-                                       if (is_indexer) {
-                                               IMethodData md = TypeManager.GetMethod (m);
-                                               if (md != null) {
-                                                       if (!(md is Indexer.SetIndexerMethod || md is Indexer.GetIndexerMethod))
-                                                               continue;
-                                               } else {
-                                                       if (TypeManager.GetPropertyFromAccessor (m) == null)
-                                                               continue;
-                                               }
-                                       } else if (name != mname) {
-                                               continue;
-                                       }
-
-                                       int j;
-
-                                       for (j = 0; j < arg_len; j++) {
-                                               if (!TypeManager.IsEqual (tm.args [i][j], args.Types [j]))
-                                                       break;
-                                               if (tm.mods [i][j] == args.FixedParameters [j].ModFlags)
-                                                       continue;
-                                               // The modifiers are different, but if one of them
-                                               // is a PARAMS modifier, and the other isn't, ignore
-                                               // the difference.
-                                               if (tm.mods [i][j] != Parameter.Modifier.PARAMS &&
-                                                   args.FixedParameters [j].ModFlags != Parameter.Modifier.PARAMS)
-                                                       break;
-                                       }
-                                       if (j != arg_len)
-                                               continue;
-
-                                       Type rt = TypeManager.TypeToCoreType (m.ReturnType);
-                                       if (!TypeManager.IsEqual (ret_type, rt) &&
-                                               !(ret_type == null && rt == TypeManager.void_type) &&
-                                               !(rt == null && ret_type == TypeManager.void_type)) {
-                                               tm.found [i] = method;
-                                               continue;
-                                       }
-
                                        if (op != Operation.Lookup) {
                                                // If `t != null', then this is an explicitly interface
                                                // implementation and we can always clear the method.
@@ -440,10 +272,10 @@ namespace Mono.CSharp {
                                                // interface indexer.  In this case, we need to create
                                                // a proxy if the implementation's IndexerName doesn't
                                                // match the IndexerName in the interface.
-                                               if (iType == null && name != mname)
-                                                       tm.need_proxy [i] = method.MethodBuilder;
-                                               else
-                                                       tm.methods [i] = null;
+                                               if (iType == null && name.Name != m.Name) {     // TODO: This is very expensive comparison
+                                                       tm.need_proxy[i] = method.method.Spec;
+                                               else
+                                                       tm.methods[i] = null;
                                        } else {
                                                tm.found [i] = method;
                                        }
@@ -471,11 +303,17 @@ namespace Mono.CSharp {
                ///   For that case, we create an explicit implementation function
                ///   I.M in Y.
                /// </summary>
-               void DefineProxy (Type iface, MethodInfo base_method, MethodInfo iface_method,
-                                 AParametersCollection param)
+               void DefineProxy (TypeSpec iface, MethodSpec base_method, MethodSpec iface_method)
                {
                        // TODO: Handle nested iface names
-                       string proxy_name = SimpleName.RemoveGenericArity (iface.FullName) + "." + iface_method.Name;
+                       string proxy_name;
+                       var ns = iface.MemberDefinition.Namespace;
+                       if (string.IsNullOrEmpty (ns))
+                               proxy_name = iface.MemberDefinition.Name + "." + iface_method.Name;
+                       else
+                               proxy_name = ns + "." + iface.MemberDefinition.Name + "." + iface_method.Name;
+
+                       var param = iface_method.Parameters;
 
                        MethodBuilder proxy = container.TypeBuilder.DefineMethod (
                                proxy_name,
@@ -484,14 +322,10 @@ namespace Mono.CSharp {
                                MethodAttributes.CheckAccessOnOverride |
                                MethodAttributes.Virtual,
                                CallingConventions.Standard | CallingConventions.HasThis,
-                               base_method.ReturnType, param.GetEmitTypes ());
-
-                       Type[] gargs = TypeManager.GetGenericArguments (iface_method);
-                       if (gargs.Length > 0) {
-                               string[] gnames = new string[gargs.Length];
-                               for (int i = 0; i < gargs.Length; ++i)
-                                       gnames[i] = gargs[i].Name;
+                               base_method.ReturnType.GetMetaInfo (), param.GetMetaInfo ());
 
+                       if (iface_method.IsGeneric) {
+                               var gnames = iface_method.GenericDefinition.TypeParameters.Select (l => l.Name).ToArray ();
                                proxy.DefineGenericParameters (gnames);
                        }
 
@@ -502,15 +336,15 @@ namespace Mono.CSharp {
                        }
 
                        int top = param.Count;
-                       ILGenerator ig = proxy.GetILGenerator ();
+                       var ec = new EmitContext (null, proxy.GetILGenerator (), null);
 
                        for (int i = 0; i <= top; i++)
-                               ParameterReference.EmitLdArg (ig, i);
+                               ParameterReference.EmitLdArg (ec, i);
 
-                       ig.Emit (OpCodes.Call, base_method);
-                       ig.Emit (OpCodes.Ret);
+                       ec.Emit (OpCodes.Call, base_method);
+                       ec.Emit (OpCodes.Ret);
 
-                       container.TypeBuilder.DefineMethodOverride (proxy, iface_method);
+                       container.TypeBuilder.DefineMethodOverride (proxy, (MethodInfo) iface_method.GetMetaInfo ());
                }
                
                /// <summary>
@@ -518,39 +352,26 @@ namespace Mono.CSharp {
                ///   the given method (which turns out, it is valid to have an interface
                ///   implementation in a base
                /// </summary>
-               bool BaseImplements (Type iface_type, MethodInfo mi, out MethodInfo base_method)
+               bool BaseImplements (TypeSpec iface_type, MethodSpec mi, out MethodSpec base_method)
                {
-                       MethodSignature ms;
-                       
-                       AParametersCollection param = TypeManager.GetParameterData (mi);
-                       ms = new MethodSignature (mi.Name, TypeManager.TypeToCoreType (mi.ReturnType), param.Types);
-                       MemberList list = TypeContainer.FindMembers (
-                               container.TypeBuilder.BaseType, MemberTypes.Method | MemberTypes.Property,
-                               BindingFlags.Public | BindingFlags.Instance,
-                               MethodSignature.method_signature_filter, ms);
-
-                       if (list.Count == 0) {
-                               base_method = null;
-                               return false;
-                       }
-
-                       if (TypeManager.ImplementsInterface (container.TypeBuilder.BaseType, iface_type)) {
-                               base_method = null;
-                               return true;
-                       }
+                       var base_type = container.BaseType;
+                       base_method = (MethodSpec) MemberCache.FindMember (base_type, new MemberFilter (mi), BindingRestriction.None);
 
-                       base_method = (MethodInfo) list [0];
+                       if (base_method == null || (base_method.Modifiers & Modifiers.PUBLIC) == 0)
+                               return false;
 
                        if (base_method.DeclaringType.IsInterface)
                                return false;
 
-                       if (!base_method.IsPublic)
-                               return false;
+                       // Why was it here ????
+                       //if (TypeManager.ImplementsInterface (base_type, iface_type)) {
+                       //      return true;
+                       //}
 
                        if (!base_method.IsAbstract && !base_method.IsVirtual)
                                // FIXME: We can avoid creating a proxy if base_method can be marked 'final virtual' instead.
                                //        However, it's too late now, the MethodBuilder has already been created (see bug 377519)
-                               DefineProxy (iface_type, base_method, mi, param);
+                               DefineProxy (iface_type, base_method, mi);
 
                        return true;
                }
@@ -566,63 +387,64 @@ namespace Mono.CSharp {
                        int i;
                        
                        for (i = 0; i < top; i++){
-                               Type type = pending_implementations [i].type;
+                               TypeSpec type = pending_implementations [i].type;
                                int j = 0;
 
                                bool base_implements_type = type.IsInterface &&
-                                       container.TypeBuilder.BaseType != null &&
-                                       TypeManager.ImplementsInterface (container.TypeBuilder.BaseType, type);
+                                       container.BaseType != null &&
+                                       container.BaseType.ImplementsInterface (type);
 
-                               foreach (MethodInfo mi in pending_implementations [i].methods){
+                               foreach (var mi in pending_implementations [i].methods){
                                        if (mi == null)
                                                continue;
 
                                        if (type.IsInterface){
-                                               MethodInfo need_proxy =
+                                               var need_proxy =
                                                        pending_implementations [i].need_proxy [j];
 
                                                if (need_proxy != null) {
-                                                       DefineProxy (type, need_proxy, mi, TypeManager.GetParameterData (mi));
+                                                       DefineProxy (type, need_proxy, mi);
                                                        continue;
                                                }
 
                                                if (pending_implementations [i].optional)
                                                        continue;
 
-                                               MethodInfo candidate = null;
+                                               MethodSpec candidate = null;
                                                if (base_implements_type || BaseImplements (type, mi, out candidate))
                                                        continue;
 
                                                if (candidate == null) {
                                                        MethodData md = pending_implementations [i].found [j];
                                                        if (md != null)
-                                                               candidate = md.MethodBuilder;
+                                                               candidate = md.method.Spec;
                                                }
-                                               
+
                                                Report.SymbolRelatedToPreviousError (mi);
                                                if (candidate != null) {
                                                        Report.SymbolRelatedToPreviousError (candidate);
                                                        if (candidate.IsStatic) {
                                                                Report.Error (736, container.Location,
                                                                        "`{0}' does not implement interface member `{1}' and the best implementing candidate `{2}' is static",
-                                                                       container.GetSignatureForError (), TypeManager.CSharpSignature (mi, true), TypeManager.CSharpSignature (candidate));
-                                                       } else if (!candidate.IsPublic) {
+                                                                       container.GetSignatureForError (), mi.GetSignatureForError (), TypeManager.CSharpSignature (candidate));
+                                                       } else if ((candidate.Modifiers & Modifiers.PUBLIC) == 0) {
                                                                Report.Error (737, container.Location,
                                                                        "`{0}' does not implement interface member `{1}' and the best implementing candidate `{2}' in not public",
-                                                                       container.GetSignatureForError (), TypeManager.CSharpSignature (mi, true), TypeManager.CSharpSignature (candidate, true));
+                                                                       container.GetSignatureForError (), mi.GetSignatureForError (), candidate.GetSignatureForError ());
                                                        } else {
                                                                Report.Error (738, container.Location,
                                                                        "`{0}' does not implement interface member `{1}' and the best implementing candidate `{2}' return type `{3}' does not match interface member return type `{4}'",
-                                                                       container.GetSignatureForError (), TypeManager.CSharpSignature (mi, true), TypeManager.CSharpSignature (candidate),
+                                                                       container.GetSignatureForError (), mi.GetSignatureForError (), TypeManager.CSharpSignature (candidate),
                                                                        TypeManager.CSharpName (candidate.ReturnType), TypeManager.CSharpName (mi.ReturnType));
                                                        }
                                                } else {
                                                        Report.Error (535, container.Location, "`{0}' does not implement interface member `{1}'",
-                                                               container.GetSignatureForError (), TypeManager.CSharpSignature (mi, true));
+                                                               container.GetSignatureForError (), mi.GetSignatureForError ());
                                                }
                                        } else {
+                                               Report.SymbolRelatedToPreviousError (mi);
                                                Report.Error (534, container.Location, "`{0}' does not implement inherited abstract member `{1}'",
-                                                       container.GetSignatureForError (), TypeManager.CSharpSignature (mi, true));
+                                                       container.GetSignatureForError (), mi.GetSignatureForError ());
                                        }
                                        errors = true;
                                        j++;
@@ -630,5 +452,5 @@ namespace Mono.CSharp {
                        }
                        return errors;
                }
-       } /* end of class */
+       }
 }
index a6109dc5f72aa483e0c577ceb265811df9d8d4f0..28e9e1e8095e270fb64228e68cebb501aa1fbc41 100644 (file)
@@ -47,7 +47,7 @@ namespace Mono.CSharp
                        if (!base.VerifyClsCompliance ())
                                return false;
 
-                       if (!AttributeTester.IsClsCompliant (MemberType)) {
+                       if (!MemberType.IsCLSCompliant ()) {
                                Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
                                        GetSignatureForError ());
                        }
@@ -85,26 +85,91 @@ namespace Mono.CSharp
                }
        }
 
-       public class PropertySpec : MemberSpec
+       public class PropertySpec : MemberSpec, IInterfaceMemberSpec
        {
                PropertyInfo info;
+               TypeSpec memberType;
+               MethodSpec set, get;
 
-               public PropertySpec (MemberKind kind, IMemberDefinition definition, PropertyInfo info, Modifiers modifiers)
-                       : base (kind, definition, info.Name, modifiers)
+               public PropertySpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, PropertyInfo info, Modifiers modifiers)
+                       : base (kind, declaringType, definition, modifiers)
                {
                        this.info = info;
+                       this.memberType = memberType;
                }
 
-               public override Type DeclaringType {
-                       get { return info.DeclaringType; }
+               #region Properties
+
+               public MethodSpec Get {
+                       get {
+                               return get;
+                       }
+                       set {
+                               get = value;
+                               get.IsAccessor = true;
+                       }
+               }
+
+               public MethodSpec Set { 
+                       get {
+                               return set;
+                       }
+                       set {
+                               set = value;
+                               set.IsAccessor = true;
+                       }
+               }
+
+               public bool IsNotRealProperty {
+                       get {
+                               return (state & StateFlags.IsNotRealProperty) != 0;
+                       }
+                       set {
+                               state |= StateFlags.IsNotRealProperty;
+                       }
+               }
+
+               public bool HasDifferentAccessibility {
+                       get {
+                               return HasGet && HasSet && 
+                                       (Get.Modifiers & Modifiers.AccessibilityMask) != (Set.Modifiers & Modifiers.AccessibilityMask);
+                       }
+               }
+
+               public bool HasGet {
+                       get {
+                               return Get != null && Get.Kind != MemberKind.FakeMethod;
+                       }
+               }
+
+               public bool HasSet {
+                       get {
+                               return Set != null && Set.Kind != MemberKind.FakeMethod;
+                       }
                }
 
                public PropertyInfo MetaInfo {
-                       get { return info; }
+                       get {
+                               if ((state & StateFlags.PendingMetaInflate) != 0)
+                                       throw new NotSupportedException ();
+
+                               return info;
+                       }
+               }
+
+               public TypeSpec MemberType {
+                       get {
+                               return memberType;
+                       }
                }
 
-               public Type PropertyType {
-                       get { return info.PropertyType; }
+               #endregion
+
+               public override MemberSpec InflateMember (TypeParameterInflator inflator)
+               {
+                       var ps = (PropertySpec) base.InflateMember (inflator);
+                       ps.memberType = inflator.Inflate (memberType);
+                       return ps;
                }
        }
 
@@ -132,6 +197,8 @@ namespace Mono.CSharp
                        {
                                base.Define (parent);
 
+                               Spec = new MethodSpec (IsDummy ? MemberKind.FakeMethod : MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, null, ParameterInfo, ModFlags);
+
                                if (IsDummy)
                                        return null;
                                
@@ -140,12 +207,12 @@ namespace Mono.CSharp
                                if (!method_data.Define (parent, method.GetFullName (MemberName), Report))
                                        return null;
 
-                               Spec = new MethodSpec (MemberKind.Method, this, method_data.MethodBuilder, ParameterInfo, ModFlags);
+                               Spec.SetMetaInfo (method_data.MethodBuilder);
 
                                return method_data.MethodBuilder;
                        }
 
-                       public override Type ReturnType {
+                       public override TypeSpec ReturnType {
                                get {
                                        return method.MemberType;
                                }
@@ -174,7 +241,7 @@ namespace Mono.CSharp
                                base (method, "set_")
                        {
                                parameters = new ParametersCompiled (Compiler,
-                                       new Parameter (method.type_name, "value", Parameter.Modifier.NONE, null, Location));
+                                       new Parameter (method.type_expr, "value", Parameter.Modifier.NONE, null, Location));
                        }
 
                        public SetMethod (PropertyBase method, Accessor accessor):
@@ -183,17 +250,17 @@ namespace Mono.CSharp
                                this.parameters = accessor.Parameters;
                        }
 
-                       protected override void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+                       protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                        {
                                if (a.Target == AttributeTargets.Parameter) {
                                        if (param_attr == null)
                                                param_attr = new ImplicitParameter (method_data.MethodBuilder);
 
-                                       param_attr.ApplyAttributeBuilder (a, cb, pa);
+                                       param_attr.ApplyAttributeBuilder (a, ctor, cdata, pa);
                                        return;
                                }
 
-                               base.ApplyAttributeBuilder (a, cb, pa);
+                               base.ApplyAttributeBuilder (a, ctor, cdata, pa);
                        }
 
                        public override ParametersCompiled ParameterInfo {
@@ -208,6 +275,8 @@ namespace Mono.CSharp
                                
                                base.Define (parent);
 
+                               Spec = new MethodSpec (IsDummy ? MemberKind.FakeMethod : MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, null, ParameterInfo, ModFlags);
+
                                if (IsDummy)
                                        return null;
 
@@ -216,12 +285,12 @@ namespace Mono.CSharp
                                if (!method_data.Define (parent, method.GetFullName (MemberName), Report))
                                        return null;
 
-                               Spec = new MethodSpec (MemberKind.Method, this, method_data.MethodBuilder, ParameterInfo, ModFlags);
+                               Spec.SetMetaInfo (method_data.MethodBuilder);
 
                                return method_data.MethodBuilder;
                        }
 
-                       public override Type ReturnType {
+                       public override TypeSpec ReturnType {
                                get {
                                        return TypeManager.void_type;
                                }
@@ -260,13 +329,13 @@ namespace Mono.CSharp
                                }
                        }
 
-                       public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+                       public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                        {
                                if (a.IsInternalMethodImplAttribute) {
                                        method.is_external_implementation = true;
                                }
 
-                               base.ApplyAttributeBuilder (a, cb, pa);
+                               base.ApplyAttributeBuilder (a, ctor, cdata, pa);
                        }
 
                        public override AttributeTargets AttributeTargets {
@@ -286,12 +355,12 @@ namespace Mono.CSharp
 
                                if (IsDummy) {
                                        if (method.InterfaceType != null && parent.PartialContainer.PendingImplementations != null) {
-                                               MethodInfo mi = parent.PartialContainer.PendingImplementations.IsInterfaceMethod (
-                                                       MethodName.Name, method.InterfaceType, new MethodData (method, ModFlags, flags, this));
+                                               var mi = parent.PartialContainer.PendingImplementations.IsInterfaceMethod (
+                                                       MethodName, method.InterfaceType, new MethodData (method, ModFlags, flags, this));
                                                if (mi != null) {
                                                        Report.SymbolRelatedToPreviousError (mi);
                                                        Report.Error (551, Location, "Explicit interface implementation `{0}' is missing accessor `{1}'",
-                                                               method.GetSignatureForError (), TypeManager.CSharpSignature (mi, true));
+                                                               method.GetSignatureForError (), mi.GetSignatureForError ());
                                                }
                                        }
                                        return null;
@@ -342,34 +411,19 @@ namespace Mono.CSharp
                                }
                        }
 
-                       public override ObsoleteAttribute GetObsoleteAttribute ()
+                       public override ObsoleteAttribute GetAttributeObsolete ()
                        {
-                               return method.GetObsoleteAttribute ();
+                               return method.GetAttributeObsolete ();
                        }
 
                        public override string GetSignatureForError()
                        {
-                               return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
+                               return method.GetSignatureForError () + "." + prefix.Substring (0, 3);
                        }
 
                        void CheckModifiers (Modifiers modflags)
                        {
-                               modflags &= Modifiers.AccessibilityMask;
-                               Modifiers flags = 0;
-                               Modifiers mflags = method.ModFlags & Modifiers.AccessibilityMask;
-
-                               if ((mflags & Modifiers.PUBLIC) != 0) {
-                                       flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
-                               }
-                               else if ((mflags & Modifiers.PROTECTED) != 0) {
-                                       if ((mflags & Modifiers.INTERNAL) != 0)
-                                               flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
-
-                                       flags |= Modifiers.PRIVATE;
-                               } else if ((mflags & Modifiers.INTERNAL) != 0)
-                                       flags |= Modifiers.PRIVATE;
-
-                               if ((mflags == modflags) || (modflags & (~flags)) != 0) {
+                               if (!ModifiersExtensions.IsRestrictedModifier (modflags & Modifiers.AccessibilityMask, method.ModFlags & Modifiers.AccessibilityMask)) {
                                        Report.Error (273, Location,
                                                "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
                                                GetSignatureForError (), method.GetSignatureForError ());
@@ -381,7 +435,7 @@ namespace Mono.CSharp
                                if ((caching_flags & Flags.MethodOverloadsExist) == 0)
                                        return true;
 
-                               return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo, Report);
+                               return Parent.MemberCache.CheckExistingMembersOverloads (this, ParameterInfo);
                        }
                }
 
@@ -399,7 +453,7 @@ namespace Mono.CSharp
                         this.define_set_first = define_set_first;
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.HasSecurityAttribute) {
                                a.Error_InvalidSecurityParent ();
@@ -411,7 +465,7 @@ namespace Mono.CSharp
                                return;
                        }
 
-                       PropertyBuilder.SetCustomAttribute (cb);
+                       PropertyBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
                }
 
                public override AttributeTargets AttributeTargets {
@@ -420,19 +474,62 @@ namespace Mono.CSharp
                        }
                }
 
+               protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
+               {
+                       var ok = base.CheckOverrideAgainstBase (base_member);
+
+                       //
+                       // Check base property accessors conflict
+                       //
+                       var base_prop = (PropertySpec) base_member;
+                       if (!Get.IsDummy) {
+                               if (!base_prop.HasGet) {
+                                       Report.SymbolRelatedToPreviousError (base_prop);
+                                       Report.Error (545, Get.Location,
+                                               "`{0}': cannot override because `{1}' does not have an overridable get accessor",
+                                               Get.GetSignatureForError (), base_prop.GetSignatureForError ());
+                                       ok = false;
+                               } else if (Get.HasCustomAccessModifier || base_prop.HasDifferentAccessibility) {
+                                       if (!CheckAccessModifiers (Get, base_prop.Get)) {
+                                               Error_CannotChangeAccessModifiers (Get, base_prop.Get);
+                                               ok = false;
+                                       }
+                               }
+                       }
+
+                       if (!Set.IsDummy) {
+                               if (!base_prop.HasSet) {
+                                       Report.SymbolRelatedToPreviousError (base_prop);
+                                       Report.Error (546, Set.Location,
+                                               "`{0}': cannot override because `{1}' does not have an overridable set accessor",
+                                               Set.GetSignatureForError (), base_prop.GetSignatureForError ());
+                                       ok = false;
+                               } else if (Set.HasCustomAccessModifier || base_prop.HasDifferentAccessibility) {
+                                       if (!CheckAccessModifiers (Set, base_prop.Set)) {
+                                               Error_CannotChangeAccessModifiers (Set, base_prop.Set);
+                                               ok = false;
+                                       }
+                               }
+                       }
+
+                       if (!Set.HasCustomAccessModifier && !Get.HasCustomAccessModifier) {
+                               if (!CheckAccessModifiers (this, base_prop)) {
+                                       Error_CannotChangeAccessModifiers (this, base_prop);
+                                       ok = false;
+                               }
+                       }
+
+                       return ok;
+               }
+
                protected override void DoMemberTypeDependentChecks ()
                {
                        base.DoMemberTypeDependentChecks ();
 
                        IsTypePermitted ();
-#if MS_COMPATIBLE
-                       if (MemberType.IsGenericParameter)
-                               return;
-#endif
 
-                       if ((MemberType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
-                               Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
-                       }
+                       if (MemberType.IsStatic)
+                               Error_StaticReturnType ();
                }
 
                protected override void DoMemberTypeIndependentChecks ()
@@ -479,85 +576,33 @@ namespace Mono.CSharp
                                DefineSet (!define_set_first);
                }
 
-               protected void DefineBuilders (MemberKind kind, Type[] parameterTypes)
+               protected void DefineBuilders (MemberKind kind, ParametersCompiled parameters)
                {
                        // FIXME - PropertyAttributes.HasDefault ?
 
                        PropertyBuilder = Parent.TypeBuilder.DefineProperty (
-                               GetFullName (MemberName), PropertyAttributes.None, MemberType, parameterTypes);
+                               GetFullName (MemberName), PropertyAttributes.None, MemberType.GetMetaInfo (), parameters.GetMetaInfo ());
+
+                       PropertySpec spec;
+                       if (kind == MemberKind.Indexer)
+                               spec = new IndexerSpec (Parent.Definition, this, MemberType, parameters, PropertyBuilder, ModFlags);
+                       else
+                               spec = new PropertySpec (kind, Parent.Definition, this, MemberType, PropertyBuilder, ModFlags);
+
+                       spec.Get = Get.Spec;
+                       spec.Set = Set.Spec;
 
                        if (!Get.IsDummy) {
                                PropertyBuilder.SetGetMethod (GetBuilder);
-                               Parent.MemberCache.AddMember (GetBuilder, Get.Spec);
                        }
 
                        if (!Set.IsDummy) {
                                PropertyBuilder.SetSetMethod (SetBuilder);
-                               Parent.MemberCache.AddMember (SetBuilder, Set.Spec);
-                       }
-
-                       var spec = new PropertySpec (kind, this, PropertyBuilder, ModFlags);
-                       Parent.MemberCache.AddMember (PropertyBuilder, spec);
-               }
-
-               protected abstract PropertyInfo ResolveBaseProperty ();
-
-               // TODO: rename to Resolve......
-               protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
-               {
-                       PropertyInfo base_property = ResolveBaseProperty ();
-                       if (base_property == null)
-                               return null;
-
-                       base_ret_type = base_property.PropertyType;
-                       MethodInfo get_accessor = base_property.GetGetMethod (true);
-                       MethodInfo set_accessor = base_property.GetSetMethod (true);
-                       MethodAttributes get_accessor_access = 0, set_accessor_access = 0;
-
-                       //
-                       // Check base property accessors conflict
-                       //
-                       if ((ModFlags & (Modifiers.OVERRIDE | Modifiers.NEW)) == Modifiers.OVERRIDE) {
-                               if (get_accessor == null) {
-                                       if (Get != null && !Get.IsDummy) {
-                                               Report.SymbolRelatedToPreviousError (base_property);
-                                               Report.Error (545, Location,
-                                                       "`{0}.get': cannot override because `{1}' does not have an overridable get accessor",
-                                                       GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
-                                       }
-                               } else {
-                                       get_accessor_access = get_accessor.Attributes & MethodAttributes.MemberAccessMask;
-
-                                       if (!Get.IsDummy && !CheckAccessModifiers (
-                                               ModifiersExtensions.MethodAttr (Get.ModFlags) & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
-                                               Error_CannotChangeAccessModifiers (Get.Location, get_accessor, get_accessor_access, ".get");
-                               }
-
-                               if (set_accessor == null) {
-                                       if (Set != null && !Set.IsDummy) {
-                                               Report.SymbolRelatedToPreviousError (base_property);
-                                               Report.Error (546, Location,
-                                                       "`{0}.set': cannot override because `{1}' does not have an overridable set accessor",
-                                                       GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
-                                       }
-                               } else {
-                                       set_accessor_access = set_accessor.Attributes & MethodAttributes.MemberAccessMask;
-
-                                       if (!Set.IsDummy && !CheckAccessModifiers (
-                                               ModifiersExtensions.MethodAttr (Set.ModFlags) & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
-                                               Error_CannotChangeAccessModifiers (Set.Location, set_accessor, set_accessor_access, ".set");
-                               }
                        }
 
-                       // When one accessor does not exist and property hides base one
-                       // we need to propagate this upwards
-                       if (set_accessor == null)
-                               set_accessor = get_accessor;
-
-                       //
-                       // Get the less restrictive access
-                       //
-                       return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
+                       Parent.MemberCache.AddMember (this, Get.IsDummy ? Get.Name : GetBuilder.Name, Get.Spec);
+                       Parent.MemberCache.AddMember (this, Set.IsDummy ? Set.Name : SetBuilder.Name, Set.Spec);
+                       Parent.MemberCache.AddMember (this, PropertyBuilder.Name, spec);
                }
 
                public override void Emit ()
@@ -571,13 +616,13 @@ namespace Mono.CSharp
                                if (OptAttributes != null)
                                        OptAttributes.Emit ();
 
-                               if (TypeManager.IsDynamicType (member_type)) {
+                               if (member_type == InternalType.Dynamic) {
                                        PredefinedAttributes.Get.Dynamic.EmitAttribute (PropertyBuilder);
                                } else {
                                        var trans_flags = TypeManager.HasDynamicTypeUsed (member_type);
                                        if (trans_flags != null) {
                                                var pa = PredefinedAttributes.Get.DynamicTransform;
-                                               if (pa.Constructor != null || pa.ResolveConstructor (Location, TypeManager.bool_type.MakeArrayType ())) {
+                                               if (pa.Constructor != null || pa.ResolveConstructor (Location, ArrayContainer.MakeType (TypeManager.bool_type))) {
                                                        PropertyBuilder.SetCustomAttribute (
                                                                new CustomAttributeBuilder (pa.Constructor, new object [] { trans_flags }));
                                                }
@@ -602,8 +647,7 @@ namespace Mono.CSharp
                        return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
                }
 
-               public override bool IsUsed
-               {
+               public override bool IsUsed {
                        get {
                                if (IsExplicitImpl)
                                        return true;
@@ -641,13 +685,19 @@ namespace Mono.CSharp
                        readonly Property property;
 
                        public BackingField (Property p)
-                               : base (p.Parent, p.type_name,
+                               : base (p.Parent, p.type_expr,
                                Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (p.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
                                new MemberName ("<" + p.GetFullName (p.MemberName) + ">k__BackingField", p.Location), null)
                        {
                                this.property = p;
                        }
 
+                       public string OriginalName {
+                               get {
+                                       return property.Name;
+                               }
+                       }
+
                        public override string GetSignatureForError ()
                        {
                                return property.GetSignatureForError ();
@@ -747,8 +797,7 @@ namespace Mono.CSharp
                        if (!CheckBase ())
                                return false;
 
-                       DefineBuilders (MemberKind.Property, null);
-                       TypeManager.RegisterProperty (PropertyBuilder, this);
+                       DefineBuilders (MemberKind.Property, ParametersCompiled.EmptyReadOnlyParameters);
                        return true;
                }
 
@@ -762,160 +811,8 @@ namespace Mono.CSharp
 
                        base.Emit ();
                }
-
-               protected override PropertyInfo ResolveBaseProperty ()
-               {
-                       return Parent.PartialContainer.BaseCache.FindMemberToOverride (
-                               Parent.TypeBuilder, Name, ParametersCompiled.EmptyReadOnlyParameters, null, true) as PropertyInfo;
-               }
        }
 
-       /// </summary>
-       ///  Gigantic workaround  for lameness in SRE follows :
-       ///  This class derives from EventInfo and attempts to basically
-       ///  wrap around the EventBuilder so that FindMembers can quickly
-       ///  return this in it search for members
-       /// </summary>
-       public class MyEventBuilder : EventInfo {
-               
-               //
-               // We use this to "point" to our Builder which is
-               // not really a MemberInfo
-               //
-               EventBuilder MyBuilder;
-               
-               //
-               // We "catch" and wrap these methods
-               //
-               MethodInfo raise, remove, add;
-
-               EventAttributes attributes;
-               Type declaring_type, reflected_type, event_type;
-               string name;
-
-               Event my_event;
-
-               public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
-               {
-                       MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
-
-                       // And now store the values in our own fields.
-                       
-                       declaring_type = type_builder;
-
-                       reflected_type = type_builder;
-                       
-                       attributes = event_attr;
-                       this.name = name;
-                       my_event = ev;
-                       this.event_type = event_type;
-               }
-               
-               //
-               // Methods that you have to override.  Note that you only need 
-               // to "implement" the variants that take the argument (those are
-               // the "abstract" methods, the others (GetAddMethod()) are 
-               // regular.
-               //
-               public override MethodInfo GetAddMethod (bool nonPublic)
-               {
-                       return add;
-               }
-               
-               public override MethodInfo GetRemoveMethod (bool nonPublic)
-               {
-                       return remove;
-               }
-               
-               public override MethodInfo GetRaiseMethod (bool nonPublic)
-               {
-                       return raise;
-               }
-               
-               //
-               // These methods make "MyEventInfo" look like a Builder
-               //
-               public void SetRaiseMethod (MethodBuilder raiseMethod)
-               {
-                       raise = raiseMethod;
-                       MyBuilder.SetRaiseMethod (raiseMethod);
-               }
-
-               public void SetRemoveOnMethod (MethodBuilder removeMethod)
-               {
-                       remove = removeMethod;
-                       MyBuilder.SetRemoveOnMethod (removeMethod);
-               }
-
-               public void SetAddOnMethod (MethodBuilder addMethod)
-               {
-                       add = addMethod;
-                       MyBuilder.SetAddOnMethod (addMethod);
-               }
-
-               public void SetCustomAttribute (CustomAttributeBuilder cb)
-               {
-                       MyBuilder.SetCustomAttribute (cb);
-               }
-               
-               public override object [] GetCustomAttributes (bool inherit)
-               {
-                       // FIXME : There's nothing which can be seemingly done here because
-                       // we have no way of getting at the custom attribute objects of the
-                       // EventBuilder !
-                       return null;
-               }
-
-               public override object [] GetCustomAttributes (Type t, bool inherit)
-               {
-                       // FIXME : Same here !
-                       return null;
-               }
-
-               public override bool IsDefined (Type t, bool b)
-               {
-                       return true;
-               }
-
-               public override EventAttributes Attributes {
-                       get {
-                               return attributes;
-                       }
-               }
-
-               public override string Name {
-                       get {
-                               return name;
-                       }
-               }
-
-               public override Type DeclaringType {
-                       get {
-                               return declaring_type;
-                       }
-               }
-
-               public override Type ReflectedType {
-                       get {
-                               return reflected_type;
-                       }
-               }
-
-               public Type EventType {
-                       get {
-                               return event_type;
-                       }
-               }
-               
-               public void SetUsed ()
-               {
-                       if (my_event != null) {
-//                             my_event.SetAssigned ();
-                               my_event.SetIsUsed ();
-                       }
-               }
-       }
-       
        /// <summary>
        /// For case when event is declared like property (with add and remove accessors).
        /// </summary>
@@ -956,7 +853,7 @@ namespace Mono.CSharp
                }
 
 
-               static readonly string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
+               static readonly string[] attribute_targets = new string [] { "event" };
 
                public EventProperty (DeclSpace parent, FullNamedExpression type, Modifiers mod_flags,
                                      MemberName name,
@@ -1005,7 +902,7 @@ namespace Mono.CSharp
                                        var field_info = ((EventField) method).BackingField;
                                        FieldExpr f_expr = new FieldExpr (field_info, Location);
                                        if ((method.ModFlags & Modifiers.STATIC) == 0)
-                                               f_expr.InstanceExpression = new CompilerGeneratedThis (field_info.Spec.FieldType, Location);
+                                               f_expr.InstanceExpression = new CompilerGeneratedThis (field_info.Spec.MemberType, Location);
 
                                        block = new ToplevelBlock (Compiler, ParameterInfo, Location);
                                        block.AddStatement (new StatementExpression (
@@ -1058,22 +955,22 @@ namespace Mono.CSharp
                        Remove = new RemoveDelegateMethod (this);
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.Target == AttributeTargets.Field) {
-                               BackingField.ApplyAttributeBuilder (a, cb, pa);
+                               BackingField.ApplyAttributeBuilder (a, ctor, cdata, pa);
                                return;
                        }
 
                        if (a.Target == AttributeTargets.Method) {
                                int errors = Report.Errors;
-                               Add.ApplyAttributeBuilder (a, cb, pa);
+                               Add.ApplyAttributeBuilder (a, ctor, cdata, pa);
                                if (errors == Report.Errors)
-                                       Remove.ApplyAttributeBuilder (a, cb, pa);
+                                       Remove.ApplyAttributeBuilder (a, ctor, cdata, pa);
                                return;
                        }
 
-                       base.ApplyAttributeBuilder (a, cb, pa);
+                       base.ApplyAttributeBuilder (a, ctor, cdata, pa);
                }
 
                public override bool Define()
@@ -1155,26 +1052,26 @@ namespace Mono.CSharp
                                get { return method_data.implementing != null; }
                        }
 
-                       public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+                       public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                        {
                                if (a.IsInternalMethodImplAttribute) {
                                        method.is_external_implementation = true;
                                }
 
-                               base.ApplyAttributeBuilder (a, cb, pa);
+                               base.ApplyAttributeBuilder (a, ctor, cdata, pa);
                        }
 
-                       protected override void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+                       protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                        {
                                if (a.Target == AttributeTargets.Parameter) {
                                        if (param_attr == null)
                                                param_attr = new ImplicitParameter (method_data.MethodBuilder);
 
-                                       param_attr.ApplyAttributeBuilder (a, cb, pa);
+                                       param_attr.ApplyAttributeBuilder (a, ctor, cdata, pa);
                                        return;
                                }
 
-                               base.ApplyAttributeBuilder (a, cb, pa);
+                               base.ApplyAttributeBuilder (a, ctor, cdata, pa);
                        }
 
                        public override AttributeTargets AttributeTargets {
@@ -1198,20 +1095,21 @@ namespace Mono.CSharp
 
                                MethodBuilder mb = method_data.MethodBuilder;
                                ParameterInfo.ApplyAttributes (mb);
-                               Spec = new MethodSpec (MemberKind.Method, this, mb, ParameterInfo, method.ModFlags);
+                               Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, mb, ParameterInfo, method.ModFlags);
+                               Spec.IsAccessor = true;
 
                                return mb;
                        }
 
-                       public override Type ReturnType {
+                       public override TypeSpec ReturnType {
                                get {
                                        return TypeManager.void_type;
                                }
                        }
 
-                       public override ObsoleteAttribute GetObsoleteAttribute ()
+                       public override ObsoleteAttribute GetAttributeObsolete ()
                        {
-                               return method.GetObsoleteAttribute ();
+                               return method.GetAttributeObsolete ();
                        }
 
                        public override string[] ValidAttributeTargets {
@@ -1246,7 +1144,7 @@ namespace Mono.CSharp
                        Modifiers.NEW;
 
                public AEventAccessor Add, Remove;
-               public MyEventBuilder     EventBuilder;
+               public EventBuilder     EventBuilder;
                public MethodBuilder AddBuilder, RemoveBuilder;
 
                ParametersCompiled parameters;
@@ -1258,14 +1156,14 @@ namespace Mono.CSharp
                {
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if ((a.HasSecurityAttribute)) {
                                a.Error_InvalidSecurityParent ();
                                return;
                        }
-                       
-                       EventBuilder.SetCustomAttribute (cb);
+
+                       EventBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
                }
 
                public bool AreAccessorsDuplicateImplementation (MethodCore mc)
@@ -1279,6 +1177,18 @@ namespace Mono.CSharp
                        }
                }
 
+               protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
+               {
+                       var ok = base.CheckOverrideAgainstBase (base_member);
+
+                       if (!CheckAccessModifiers (this, base_member)) {
+                               Error_CannotChangeAccessModifiers (this, base_member);
+                               ok = false;
+                       }
+
+                       return ok;
+               }
+
                public override bool Define ()
                {
                        if (!base.Define ())
@@ -1294,21 +1204,9 @@ namespace Mono.CSharp
                        if (!CheckBase ())
                                return false;
 
-                       if (TypeManager.delegate_combine_delegate_delegate == null) {
-                               TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
-                                       TypeManager.delegate_type, "Combine", Location,
-                                       TypeManager.delegate_type, TypeManager.delegate_type);
-                       }
-                       if (TypeManager.delegate_remove_delegate_delegate == null) {
-                               TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
-                                       TypeManager.delegate_type, "Remove", Location,
-                                       TypeManager.delegate_type, TypeManager.delegate_type);
-                       }
-
                        //
                        // Now define the accessors
                        //
-
                        AddBuilder = Add.Define (Parent);
                        if (AddBuilder == null)
                                return false;
@@ -1317,20 +1215,16 @@ namespace Mono.CSharp
                        if (RemoveBuilder == null)
                                return false;
 
-                       EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);                                           
+                       EventBuilder = Parent.TypeBuilder.DefineEvent (Name, EventAttributes.None, MemberType.GetMetaInfo ());
                        EventBuilder.SetAddOnMethod (AddBuilder);
                        EventBuilder.SetRemoveOnMethod (RemoveBuilder);
 
-                       var spec = new EventSpec (this, EventBuilder, ModFlags, Add.Spec, Remove.Spec) {
-                               EventType = MemberType
-                       };
+                       var spec = new EventSpec (Parent.Definition, this, MemberType, ModFlags, Add.Spec, Remove.Spec);
 
-                       TypeManager.RegisterEventField (EventBuilder, spec);
+                       Parent.MemberCache.AddMember (this, Name, spec);
+                       Parent.MemberCache.AddMember (this, AddBuilder.Name, Add.Spec);
+                       Parent.MemberCache.AddMember (this, RemoveBuilder.Name, Remove.Spec);
 
-                       Parent.MemberCache.AddMember (EventBuilder, spec);
-                       Parent.MemberCache.AddMember (AddBuilder, Add.Spec);
-                       Parent.MemberCache.AddMember (RemoveBuilder, Remove.Spec);
-                       
                        return true;
                }
 
@@ -1346,19 +1240,6 @@ namespace Mono.CSharp
                        base.Emit ();
                }
 
-               protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
-               {
-                       MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindBaseEvent (
-                               Parent.TypeBuilder, Name);
-
-                       if (mi == null)
-                               return null;
-
-                       AParametersCollection pd = TypeManager.GetParameterData (mi);
-                       base_ret_type = pd.Types [0];
-                       return mi;
-               }
-
                //
                //   Represents header string for documentation comment.
                //
@@ -1367,41 +1248,51 @@ namespace Mono.CSharp
                }
        }
 
-       public class EventSpec : MemberSpec
+       public class EventSpec : MemberSpec, IInterfaceMemberSpec
        {
-               EventInfo info;
+               MethodSpec add, remove;
 
-               public EventSpec (IMemberDefinition definition, EventInfo info, Modifiers modifiers, MethodSpec add, MethodSpec remove)
-                       : base (MemberKind.Event, definition, info.Name, modifiers)
+               public EventSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec eventType, Modifiers modifiers, MethodSpec add, MethodSpec remove)
+                       : base (MemberKind.Event, declaringType, definition, modifiers)
                {
-                       this.info = info;
                        this.AccessorAdd = add;
                        this.AccessorRemove = remove;
-
-                       // TODO MemberCache: Remove
-                       if (TypeManager.IsBeingCompiled (info))
-                               state &= ~MemberSpec.StateFlags.Obsolete_Undetected;
+                       this.MemberType = eventType;
                }
 
-               public MethodSpec AccessorAdd { get; private set; }
-               public MethodSpec AccessorRemove { get; private set; }
+               #region Properties
 
-               public override Type DeclaringType {
-                       get { return info.DeclaringType; }
+               public MethodSpec AccessorAdd { 
+                       get {
+                               return add;
+                       }
+                       set {
+                               add = value;
+                       }
                }
 
-               public Type EventType { get; set; }
-
-               public bool IsAbstract {
-                       get { return (Modifiers & Modifiers.ABSTRACT) != 0; }
+               public MethodSpec AccessorRemove {
+                       get {
+                               return remove;
+                       }
+                       set {
+                               remove = value;
+                       }
                }
 
-               public EventInfo MetaInfo {
-                       get { return info; }
+               public TypeSpec MemberType { get; private set; }
+
+               #endregion
+
+               public override MemberSpec InflateMember (TypeParameterInflator inflator)
+               {
+                       var es = (EventSpec) base.InflateMember (inflator);
+                       es.MemberType = inflator.Inflate (MemberType);
+                       return es;
                }
        }
  
-       public class Indexer : PropertyBase
+       public class Indexer : PropertyBase, IParametersMember
        {
                public class GetIndexerMethod : GetMethod
                {
@@ -1483,7 +1374,7 @@ namespace Mono.CSharp
                const Modifiers AllowedInterfaceModifiers =
                        Modifiers.NEW;
 
-               public readonly ParametersCompiled parameters;
+               readonly ParametersCompiled parameters;
 
                public Indexer (DeclSpace parent, FullNamedExpression type, MemberName name, Modifiers mod,
                                ParametersCompiled parameters, Attributes attrs,
@@ -1505,9 +1396,25 @@ namespace Mono.CSharp
                                Set = new SetIndexerMethod (this, set_block);
                }
 
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
+               {
+                       if (a.Type == pa.IndexerName) {
+                               if (IsExplicitImpl) {
+                                       Report.Error (415, a.Location,
+                                               "The `{0}' attribute is valid only on an indexer that is not an explicit interface member declaration",
+                                               TypeManager.CSharpName (a.Type));
+                               }
+
+                               // Attribute was copied to container
+                               return;
+                       }
+
+                       base.ApplyAttributeBuilder (a, ctor, cdata, pa);
+               }
+
                protected override bool CheckForDuplications ()
                {
-                       return Parent.MemberCache.CheckExistingMembersOverloads (this, GetFullName (MemberName), parameters, Report);
+                       return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
                }
                
                public override bool Define ()
@@ -1521,32 +1428,23 @@ namespace Mono.CSharp
                        if (OptAttributes != null) {
                                Attribute indexer_attr = OptAttributes.Search (PredefinedAttributes.Get.IndexerName);
                                if (indexer_attr != null) {
-                                       // Remove the attribute from the list because it is not emitted
-                                       OptAttributes.Attrs.Remove (indexer_attr);
+                                       var compiling = indexer_attr.Type.MemberDefinition as TypeContainer;
+                                       if (compiling != null)
+                                               compiling.Define ();
 
                                        string name = indexer_attr.GetIndexerAttributeValue ();
-                                       if (name == null)
-                                               return false;
-
-                                       ShortName = name;
-
-                                       if (IsExplicitImpl) {
-                                               Report.Error (415, indexer_attr.Location,
-                                                             "The `IndexerName' attribute is valid only on an " +
-                                                             "indexer that is not an explicit interface member declaration");
-                                               return false;
-                                       }
-
                                        if ((ModFlags & Modifiers.OVERRIDE) != 0) {
                                                Report.Error (609, indexer_attr.Location,
-                                                             "Cannot set the `IndexerName' attribute on an indexer marked override");
-                                               return false;
+                                                       "Cannot set the `IndexerName' attribute on an indexer marked override");
                                        }
+
+                                       if (!string.IsNullOrEmpty (name))
+                                               ShortName = name;
                                }
                        }
 
                        if (InterfaceType != null) {
-                               string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
+                               string base_IndexerName = InterfaceType.MemberDefinition.GetAttributeDefaultMember ();
                                if (base_IndexerName != Name)
                                        ShortName = base_IndexerName;
                        }
@@ -1563,8 +1461,7 @@ namespace Mono.CSharp
                        if (!CheckBase ())
                                return false;
 
-                       DefineBuilders (MemberKind.Indexer, parameters.GetEmitTypes ());
-                       TypeManager.RegisterIndexer (PropertyBuilder, parameters);
+                       DefineBuilders (MemberKind.Indexer, parameters);
                        return true;
                }
 
@@ -1596,10 +1493,16 @@ namespace Mono.CSharp
                        return sb.ToString ();
                }
 
-               protected override PropertyInfo ResolveBaseProperty ()
-               {
-                       return Parent.PartialContainer.BaseCache.FindMemberToOverride (
-                               Parent.TypeBuilder, Name, parameters, null, true) as PropertyInfo;
+               public AParametersCollection Parameters {
+                       get {
+                               return parameters;
+                       }
+               }
+
+               public ParametersCompiled ParameterInfo {
+                       get {
+                               return parameters;
+                       }
                }
 
                protected override bool VerifyClsCompliance ()
@@ -1611,4 +1514,26 @@ namespace Mono.CSharp
                        return true;
                }
        }
+
+       public class IndexerSpec : PropertySpec, IParametersMember
+       {
+               AParametersCollection parameters;
+
+               public IndexerSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, AParametersCollection parameters, PropertyInfo info, Modifiers modifiers)
+                       : base (MemberKind.Indexer, declaringType, definition, memberType, info, modifiers)
+               {
+                       this.parameters = parameters;
+               }
+
+               public override string GetSignatureForError ()
+               {
+                       return DeclaringType.GetSignatureForError () + ".this" + parameters.GetSignatureForError ("[", "]", parameters.Count);
+               }
+
+               public AParametersCollection Parameters {
+                       get {
+                               return parameters;
+                       }
+               }
+       }
 }
index 77058a17208e6acf67e085ff7297d1028f83790c..3ca7fd681ea6c8f72c30415f38fc3327156da84d 100644 (file)
@@ -179,35 +179,17 @@ namespace Mono.CSharp {
                        SymbolRelatedToPreviousError (loc.ToString (), symbol);
                }
 
-               public void SymbolRelatedToPreviousError (MemberInfo mi)
+               public void SymbolRelatedToPreviousError (MemberSpec ms)
                {
                        if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
                                return;
 
-                       Type dt = TypeManager.DropGenericTypeArguments (mi.DeclaringType);
-                       if (TypeManager.IsDelegateType (dt)) {
-                               SymbolRelatedToPreviousError (dt);
-                               return;
-                       }                       
-                       
-                       DeclSpace temp_ds = TypeManager.LookupDeclSpace (dt);
-                       if (temp_ds == null) {
-                               SymbolRelatedToPreviousError (dt.Assembly.Location, TypeManager.GetFullNameSignature (mi));
+                       var mc = ms.MemberDefinition as MemberCore;
+                       if (mc != null) {
+                               SymbolRelatedToPreviousError (mc);
                        } else {
-                               MethodBase mb = mi as MethodBase;
-                               if (mb != null) {
-                                       mb = TypeManager.DropGenericMethodArguments (mb);
-                                       IMethodData md = TypeManager.GetMethod (mb);
-                                       if (md != null)
-                                               SymbolRelatedToPreviousError (md.Location, md.GetSignatureForError ());
-
-                                       return;
-                               }
-
-                               // FIXME: Completely wrong, it has to use FindMembers
-                               MemberCore mc = temp_ds.GetDefinition (mi.Name);
-                               if (mc != null)
-                                       SymbolRelatedToPreviousError (mc);
+                               var im = ms.MemberDefinition as ImportedMemberDefinition;
+                               SymbolRelatedToPreviousError (im.Assembly.Location, "");
                        }
                }
 
@@ -216,31 +198,6 @@ namespace Mono.CSharp {
                        SymbolRelatedToPreviousError (mc.Location, mc.GetSignatureForError ());
                }
 
-               public void SymbolRelatedToPreviousError (Type type)
-               {
-                       if (reporting_disabled > 0 || !printer.HasRelatedSymbolSupport)
-                               return;
-
-                       type = TypeManager.DropGenericTypeArguments (type);
-
-                       if (TypeManager.IsGenericParameter (type)) {
-                               TypeParameter tp = TypeManager.LookupTypeParameter (type);
-                               if (tp != null) {
-                                       SymbolRelatedToPreviousError (tp.Location, "");
-                                       return;
-                               }
-                       }
-
-                       if (type is TypeBuilder) {
-                               DeclSpace temp_ds = TypeManager.LookupDeclSpace (type);
-                               SymbolRelatedToPreviousError (temp_ds.Location, TypeManager.CSharpName (type));
-                       } else if (TypeManager.HasElementType (type)) {
-                               SymbolRelatedToPreviousError (TypeManager.GetElementType (type));
-                       } else {
-                               SymbolRelatedToPreviousError (type.Assembly.Location, TypeManager.CSharpName (type));
-                       }
-               }
-
                void SymbolRelatedToPreviousError (string loc, string symbol)
                {
                        string msg = String.Format ("{0} (Location of the symbol related to previous ", loc);
@@ -404,7 +361,7 @@ namespace Mono.CSharp {
                        Error (code, loc, String.Format (format, arg1, arg2));
                }
 
-               public void Error (int code, Location loc, string format, params object[] args)
+               public void Error (int code, Location loc, string format, params string[] args)
                {
                        Error (code, loc, String.Format (format, args));
                }
@@ -956,8 +913,8 @@ namespace Mono.CSharp {
                                        if (!first)
                                                sb.Append (", ");
                                        first = false;
-                                       
-                                       sb.Append (TypeManager.CSharpName (pi.ParameterType));
+
+                                       sb.Append (pi.ParameterType.FullName);
                                }
                                sb.Append (")\n");
                        }
index 5ef66ceeaa0dc4fee365f8e24388e9515fcad017..4c6335c0b79ab42689d99ed9f78a9572a51b8c8a 100644 (file)
@@ -117,17 +117,6 @@ namespace Mono.CSharp {
                //
                static List<string> AllDefines;
                
-               //
-               // This keeps track of the order in which classes were defined
-               // so that we can poulate them in that order.
-               //
-               // Order is important, because we need to be able to tell, by
-               // examining the list of methods of the base class, which ones are virtual
-               // or abstract as well as the parent names (to implement new, 
-               // override).
-               //
-               static List<TypeContainer> type_container_resolve_order;
-
                //
                // Holds a reference to the Private Implementation Details
                // class.
@@ -136,6 +125,8 @@ namespace Mono.CSharp {
                
                static TypeBuilder impl_details_class;
 
+               public static List<Enum> hack_corlib_enums = new List<Enum> ();
+
                //
                // Constructor
                //
@@ -151,10 +142,12 @@ namespace Mono.CSharp {
                
                public static void Reset (bool full)
                {
-                       if (full)
-                               root = null;
+                       impl_details_class = null;
+                       helper_classes = null;
+
+                       if (!full)
+                               return;
                        
-                       type_container_resolve_order = new List<TypeContainer> ();
                        EntryPoint = null;
                        Checked = false;
                        Unsafe = false;
@@ -201,11 +194,6 @@ namespace Mono.CSharp {
                        set { root = value; }
                }
 
-               public static void RegisterOrder (TypeContainer tc)
-               {
-                       type_container_resolve_order.Add (tc);
-               }
-               
                // <remarks>
                //   This function is used to resolve the hierarchy tree.
                //   It processes interfaces, structs and classes in that order.
@@ -228,10 +216,44 @@ namespace Mono.CSharp {
 
                        foreach (TypeContainer tc in root.Types)
                                tc.DefineType ();
+               }
+
+               static void HackCorlib ()
+               {
+                       if (StdLib)
+                               return;
+
+                       //
+                       // HACK: When building corlib mcs uses loaded mscorlib which
+                       // has different predefined types and this method sets mscorlib types
+                       // to be same to avoid type check errors in CreateType.
+                       //
+                       var type = typeof (Type);
+                       var system_4_type_arg = new[] { type, type, type, type };
+
+                       MethodInfo set_corlib_type_builders =
+                               typeof (System.Reflection.Emit.AssemblyBuilder).GetMethod (
+                               "SetCorlibTypeBuilders", BindingFlags.NonPublic | BindingFlags.Instance, null,
+                               system_4_type_arg, null);
+
+                       if (set_corlib_type_builders == null) {
+                               root.Compiler.Report.Warning (-26, 3, "The compilation may fail due to missing `{0}.SetCorlibTypeBuilders(...)' method",
+                                       typeof (System.Reflection.Emit.AssemblyBuilder).FullName);
+                               return;
+                       }
 
-                       if (root.Delegates != null)
-                               foreach (Delegate d in root.Delegates) 
-                                       d.DefineType ();
+                       object[] args = new object[4];
+                       args[0] = TypeManager.object_type.GetMetaInfo ();
+                       args[1] = TypeManager.value_type.GetMetaInfo ();
+                       args[2] = TypeManager.enum_type.GetMetaInfo ();
+                       args[3] = TypeManager.void_type.GetMetaInfo ();
+                       set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
+
+                       // Another Mono corlib HACK
+                       // mono_class_layout_fields requires to have enums created
+                       // before creating a class which used the enum for any of its fields
+                       foreach (var e in hack_corlib_enums)
+                               e.CloseType ();
                }
 
                // <summary>
@@ -246,26 +268,11 @@ namespace Mono.CSharp {
                // </remarks>
                static public void CloseTypes ()
                {
-                       //
-                       // We do this in two passes, first we close the structs,
-                       // then the classes, because it seems the code needs it this
-                       // way.  If this is really what is going on, we should probably
-                       // make sure that we define the structs in order as well.
-                       //
-                       foreach (TypeContainer tc in type_container_resolve_order){
-                               if (tc.Kind == MemberKind.Struct && tc.Parent == root){
-                                       tc.CloseType ();
-                               }
-                       }
+                       HackCorlib ();
 
-                       foreach (TypeContainer tc in type_container_resolve_order){
-                               if (!(tc.Kind == MemberKind.Struct && tc.Parent == root))
-                                       tc.CloseType ();                                        
+                       foreach (TypeContainer tc in root.Types){
+                               tc.CloseType ();
                        }
-                       
-                       if (root.Delegates != null)
-                               foreach (Delegate d in root.Delegates)
-                                       d.CloseType ();
 
                        if (root.CompilerGeneratedClasses != null)
                                foreach (CompilerGeneratedClass c in root.CompilerGeneratedClasses)
@@ -281,10 +288,7 @@ namespace Mono.CSharp {
                                }
                        }
                        
-                       type_container_resolve_order = null;
                        helper_classes = null;
-                       //root = null;
-                       TypeManager.CleanUp ();
                }
 
                /// <summary>
@@ -299,28 +303,6 @@ namespace Mono.CSharp {
                        helper_classes.Add (helper_class);
                }
                
-               static public DeclSpace PopulateCoreType (TypeContainer root, string name)
-               {
-                       DeclSpace ds = (DeclSpace) root.GetDefinition (name);
-                       // Core type was imported
-                       if (ds == null)
-                               return null;
-
-                       ds.Define ();
-                       return ds;
-               }
-               
-               static public void BootCorlib_PopulateCoreTypes ()
-               {
-                       // Clear -nostdlib flag when object type is imported
-                       if (PopulateCoreType (root, "System.Object") == null)
-                               RootContext.StdLib = true;
-
-                       PopulateCoreType (root, "System.ValueType");
-                       PopulateCoreType (root, "System.Attribute");
-                       PopulateCoreType (root, "System.Runtime.CompilerServices.IndexerNameAttribute");
-               }
-               
                // <summary>
                //   Populates the structs and classes with fields and methods
                // </summary>
@@ -329,52 +311,31 @@ namespace Mono.CSharp {
                // have been defined through `ResolveTree' 
                static public void PopulateTypes ()
                {
-
-                       if (type_container_resolve_order != null){
-                               foreach (TypeContainer tc in type_container_resolve_order)
-                                       tc.ResolveType ();
-                               foreach (TypeContainer tc in type_container_resolve_order) {
-                                       try {
-                                               tc.Define ();
-                                       } catch (Exception e) {
-                                               throw new InternalErrorException (tc, e);
-                                       }
+                       foreach (TypeContainer tc in ToplevelTypes.Types)
+                               tc.ResolveTypeParameters ();
+
+                       foreach (TypeContainer tc in ToplevelTypes.Types) {
+                               try {
+                                       tc.Define ();
+                               } catch (Exception e) {
+                                       throw new InternalErrorException (tc, e);
                                }
                        }
-
-                       var delegates = root.Delegates;
-                       if (delegates != null){
-                               foreach (Delegate d in delegates)
-                                       d.Define ();
-                       }
-
-                       //
-                       // Check for cycles in the struct layout
-                       //
-                       if (type_container_resolve_order != null){
-                               var seen = new Dictionary<TypeContainer, object> ();
-                               foreach (TypeContainer tc in type_container_resolve_order)
-                                       TypeManager.CheckStructCycles (tc, seen);
-                       }
                }
 
                static public void EmitCode ()
                {
-                       if (type_container_resolve_order != null) {
-                               foreach (TypeContainer tc in type_container_resolve_order)
-                                       tc.EmitType ();
+                       foreach (var tc in ToplevelTypes.Types)
+                               tc.DefineConstants ();
 
-                               if (ToplevelTypes.Compiler.Report.Errors > 0)
-                                       return;
+                       foreach (TypeContainer tc in ToplevelTypes.Types)
+                               tc.EmitType ();
 
-                               foreach (TypeContainer tc in type_container_resolve_order)
-                                       tc.VerifyMembers ();
-                       }
-                       
-                       if (root.Delegates != null) {
-                               foreach (Delegate d in root.Delegates)
-                                       d.Emit ();
-                       }                       
+                       if (ToplevelTypes.Compiler.Report.Errors > 0)
+                               return;
+
+                       foreach (TypeContainer tc in ToplevelTypes.Types)
+                               tc.VerifyMembers ();
 
                        if (root.CompilerGeneratedClasses != null)
                                foreach (CompilerGeneratedClass c in root.CompilerGeneratedClasses)
@@ -417,7 +378,7 @@ namespace Mono.CSharp {
                                impl_details_class = ToplevelTypes.Builder.DefineType (
                                        "<PrivateImplementationDetails>",
                                         TypeAttributes.NotPublic,
-                                        TypeManager.object_type);
+                                        TypeManager.object_type.GetMetaInfo ());
                                 
                                RegisterCompilerGeneratedType (impl_details_class);
                        }
index 116c3da3827a2e04a643f9acac49f2ea12fd282e..0144f0130300ae893ee1a083325b921b5d1d5350 100644 (file)
@@ -34,7 +34,7 @@ namespace Mono.CSharp
                        this.assembly = assembly;
                }
 
-               public Assembly Assembly {
+               public override Assembly Assembly {
                        get { return assembly; }
                }
 
@@ -111,7 +111,7 @@ namespace Mono.CSharp
                        return AddPartial (nextPart, nextPart.Name);
                }
 
-               public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb, PredefinedAttributes pa)
+               public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
                {
                        if (a.Type == pa.CLSCompliant) {
                                if (CodeGen.Assembly.ClsCompliantAttribute == null) {
@@ -123,7 +123,7 @@ namespace Mono.CSharp
                                }
                        }
 
-                       builder.SetCustomAttribute (cb);
+                       builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
                }
 
                public ModuleBuilder Builder {
@@ -147,11 +147,11 @@ namespace Mono.CSharp
                                OptAttributes.Emit ();
 
                        if (is_unsafe) {
-                               Type t = TypeManager.CoreLookupType (context, "System.Security", "UnverifiableCodeAttribute", MemberKind.Class, true);
+                               TypeSpec t = TypeManager.CoreLookupType (context, "System.Security", "UnverifiableCodeAttribute", MemberKind.Class, true);
                                if (t != null) {
-                                       ConstructorInfo unverifiable_code_ctor = TypeManager.GetPredefinedConstructor (t, Location.Null, Type.EmptyTypes);
+                                       var unverifiable_code_ctor = TypeManager.GetPredefinedConstructor (t, Location.Null, TypeSpec.EmptyTypes);
                                        if (unverifiable_code_ctor != null)
-                                               builder.SetCustomAttribute (new CustomAttributeBuilder (unverifiable_code_ctor, new object [0]));
+                                               builder.SetCustomAttribute (new CustomAttributeBuilder ((ConstructorInfo) unverifiable_code_ctor.GetMetaInfo (), new object[0]));
                                }
                        }
                }
@@ -176,11 +176,6 @@ namespace Mono.CSharp
                        return null;
                }
 
-               public override bool GetClsCompliantAttributeValue ()
-               {
-                       return CodeGen.Assembly.IsClsCompliant;
-               }
-
                public bool HasDefaultCharSet {
                        get {
                                return has_default_charset;
@@ -194,14 +189,14 @@ namespace Mono.CSharp
 
                public override bool IsClsComplianceRequired ()
                {
-                       return true;
+                       return CodeGen.Assembly.IsClsCompliant;
                }
 
-               protected override bool AddMemberType (DeclSpace ds)
+               protected override bool AddMemberType (TypeContainer ds)
                {
                        if (!AddToContainer (ds, ds.Name))
                                return false;
-                       ds.NamespaceEntry.NS.AddDeclSpace (ds.Basename, ds);
+                       ds.NamespaceEntry.NS.AddType (ds.Definition);
                        return true;
                }
 
@@ -259,9 +254,9 @@ namespace Mono.CSharp
                }
        }
 
-       class RootDeclSpace : DeclSpace {
+       class RootDeclSpace : TypeContainer {
                public RootDeclSpace (NamespaceEntry ns)
-                       : base (ns, null, MemberName.Null, null)
+                       : base (ns, null, MemberName.Null, null, 0)
                {
                        PartialContainer = RootContext.ToplevelTypes;
                }
@@ -280,31 +275,22 @@ namespace Mono.CSharp
                        get { throw new InternalErrorException ("should not be called"); }
                }
 
-               public override bool Define ()
-               {
-                       throw new InternalErrorException ("should not be called");
-               }
+               //public override bool Define ()
+               //{
+               //    throw new InternalErrorException ("should not be called");
+               //}
 
                public override TypeBuilder DefineType ()
                {
                        throw new InternalErrorException ("should not be called");
                }
 
-               public override MemberCache MemberCache {
-                       get { return PartialContainer.MemberCache; }
-               }
-
                public override ModuleContainer Module {
                        get {
                                return PartialContainer.Module;
                        }
                }
 
-               public override bool GetClsCompliantAttributeValue ()
-               {
-                       return PartialContainer.GetClsCompliantAttributeValue ();
-               }
-
                public override bool IsClsComplianceRequired ()
                {
                        return PartialContainer.IsClsComplianceRequired ();
index 12bd6b6977dee2cb219ee6bb34f6c54440036f05..38a7529f89242fb61d8e95671044b6ca6bc12fc9 100644 (file)
@@ -92,8 +92,6 @@ namespace Mono.CSharp {
 
                        return Clone (clonectx);
                }
-
-               public abstract void MutateHoistedGenericType (AnonymousMethodStorey storey);
        }
 
        public sealed class EmptyStatement : Statement
@@ -122,10 +120,6 @@ namespace Mono.CSharp {
                        throw new NotSupportedException ();
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-               }
-
                protected override void CloneTo (CloneContext clonectx, Statement target)
                {
                        // nothing needed.
@@ -155,14 +149,6 @@ namespace Mono.CSharp {
                        loc = l;
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       expr.MutateHoistedGenericType (storey);
-                       TrueStatement.MutateHoistedGenericType (storey);
-                       if (FalseStatement != null)
-                               FalseStatement.MutateHoistedGenericType (storey);
-               }
-
                public override bool Resolve (BlockContext ec)
                {
                        bool ok = true;
@@ -221,8 +207,7 @@ namespace Mono.CSharp {
                
                protected override void DoEmit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-                       Label false_target = ig.DefineLabel ();
+                       Label false_target = ec.DefineLabel ();
                        Label end;
 
                        //
@@ -248,19 +233,19 @@ namespace Mono.CSharp {
                        if (FalseStatement != null){
                                bool branch_emitted = false;
                                
-                               end = ig.DefineLabel ();
+                               end = ec.DefineLabel ();
                                if (!is_true_ret){
-                                       ig.Emit (OpCodes.Br, end);
+                                       ec.Emit (OpCodes.Br, end);
                                        branch_emitted = true;
                                }
 
-                               ig.MarkLabel (false_target);
+                               ec.MarkLabel (false_target);
                                FalseStatement.Emit (ec);
 
                                if (branch_emitted)
-                                       ig.MarkLabel (end);
+                                       ec.MarkLabel (end);
                        } else {
-                               ig.MarkLabel (false_target);
+                               ec.MarkLabel (false_target);
                        }
                }
 
@@ -318,17 +303,16 @@ namespace Mono.CSharp {
                
                protected override void DoEmit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-                       Label loop = ig.DefineLabel ();
+                       Label loop = ec.DefineLabel ();
                        Label old_begin = ec.LoopBegin;
                        Label old_end = ec.LoopEnd;
                        
-                       ec.LoopBegin = ig.DefineLabel ();
-                       ec.LoopEnd = ig.DefineLabel ();
+                       ec.LoopBegin = ec.DefineLabel ();
+                       ec.LoopEnd = ec.DefineLabel ();
                                
-                       ig.MarkLabel (loop);
+                       ec.MarkLabel (loop);
                        EmbeddedStatement.Emit (ec);
-                       ig.MarkLabel (ec.LoopBegin);
+                       ec.MarkLabel (ec.LoopBegin);
 
                        //
                        // Dead code elimination
@@ -338,22 +322,16 @@ namespace Mono.CSharp {
 
                                expr.EmitSideEffect (ec);
                                if (res)
-                                       ec.ig.Emit (OpCodes.Br, loop); 
+                                       ec.Emit (OpCodes.Br, loop); 
                        } else
                                expr.EmitBranchable (ec, loop, true);
                        
-                       ig.MarkLabel (ec.LoopEnd);
+                       ec.MarkLabel (ec.LoopEnd);
 
                        ec.LoopBegin = old_begin;
                        ec.LoopEnd = old_end;
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       expr.MutateHoistedGenericType (storey);
-                       EmbeddedStatement.MutateHoistedGenericType (storey);
-               }
-
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        Do target = (Do) t;
@@ -422,42 +400,41 @@ namespace Mono.CSharp {
                                return;
                        }
 
-                       ILGenerator ig = ec.ig;
                        Label old_begin = ec.LoopBegin;
                        Label old_end = ec.LoopEnd;
                        
-                       ec.LoopBegin = ig.DefineLabel ();
-                       ec.LoopEnd = ig.DefineLabel ();
+                       ec.LoopBegin = ec.DefineLabel ();
+                       ec.LoopEnd = ec.DefineLabel ();
 
                        //
                        // Inform whether we are infinite or not
                        //
                        if (expr is Constant){
                                // expr is 'true', since the 'empty' case above handles the 'false' case
-                               ig.MarkLabel (ec.LoopBegin);
+                               ec.MarkLabel (ec.LoopBegin);
                                expr.EmitSideEffect (ec);
                                Statement.Emit (ec);
-                               ig.Emit (OpCodes.Br, ec.LoopBegin);
+                               ec.Emit (OpCodes.Br, ec.LoopBegin);
                                        
                                //
                                // Inform that we are infinite (ie, `we return'), only
                                // if we do not `break' inside the code.
                                //
-                               ig.MarkLabel (ec.LoopEnd);
+                               ec.MarkLabel (ec.LoopEnd);
                        } else {
-                               Label while_loop = ig.DefineLabel ();
+                               Label while_loop = ec.DefineLabel ();
 
-                               ig.Emit (OpCodes.Br, ec.LoopBegin);
-                               ig.MarkLabel (while_loop);
+                               ec.Emit (OpCodes.Br, ec.LoopBegin);
+                               ec.MarkLabel (while_loop);
 
                                Statement.Emit (ec);
                        
-                               ig.MarkLabel (ec.LoopBegin);
+                               ec.MarkLabel (ec.LoopBegin);
                                ec.Mark (loc);
 
                                expr.EmitBranchable (ec, while_loop, true);
                                
-                               ig.MarkLabel (ec.LoopEnd);
+                               ec.MarkLabel (ec.LoopEnd);
                        }       
 
                        ec.LoopBegin = old_begin;
@@ -476,12 +453,6 @@ namespace Mono.CSharp {
                        target.expr = expr.Clone (clonectx);
                        target.Statement = Statement.Clone (clonectx);
                }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       expr.MutateHoistedGenericType (storey);
-                       Statement.MutateHoistedGenericType (storey);
-               }
        }
 
        public class For : Statement {
@@ -573,23 +544,22 @@ namespace Mono.CSharp {
                                return;
                        }
 
-                       ILGenerator ig = ec.ig;
                        Label old_begin = ec.LoopBegin;
                        Label old_end = ec.LoopEnd;
-                       Label loop = ig.DefineLabel ();
-                       Label test = ig.DefineLabel ();
+                       Label loop = ec.DefineLabel ();
+                       Label test = ec.DefineLabel ();
 
-                       ec.LoopBegin = ig.DefineLabel ();
-                       ec.LoopEnd = ig.DefineLabel ();
+                       ec.LoopBegin = ec.DefineLabel ();
+                       ec.LoopEnd = ec.DefineLabel ();
 
-                       ig.Emit (OpCodes.Br, test);
-                       ig.MarkLabel (loop);
+                       ec.Emit (OpCodes.Br, test);
+                       ec.MarkLabel (loop);
                        Statement.Emit (ec);
 
-                       ig.MarkLabel (ec.LoopBegin);
+                       ec.MarkLabel (ec.LoopBegin);
                        Increment.Emit (ec);
 
-                       ig.MarkLabel (test);
+                       ec.MarkLabel (test);
                        //
                        // If test is null, there is no test, and we are just
                        // an infinite loop
@@ -602,31 +572,19 @@ namespace Mono.CSharp {
                                //
                                if (Test is Constant) {
                                        Test.EmitSideEffect (ec);
-                                       ig.Emit (OpCodes.Br, loop);
+                                       ec.Emit (OpCodes.Br, loop);
                                } else {
                                        Test.EmitBranchable (ec, loop, true);
                                }
                                
                        } else
-                               ig.Emit (OpCodes.Br, loop);
-                       ig.MarkLabel (ec.LoopEnd);
+                               ec.Emit (OpCodes.Br, loop);
+                       ec.MarkLabel (ec.LoopEnd);
 
                        ec.LoopBegin = old_begin;
                        ec.LoopEnd = old_end;
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       if (InitStatement != null)
-                               InitStatement.MutateHoistedGenericType (storey);
-                       if (Test != null)
-                               Test.MutateHoistedGenericType (storey);
-                       if (Increment != null)
-                               Increment.MutateHoistedGenericType (storey);
-
-                       Statement.MutateHoistedGenericType (storey);
-               }
-
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        For target = (For) t;
@@ -661,11 +619,6 @@ namespace Mono.CSharp {
                        expr.EmitStatement (ec);
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       expr.MutateHoistedGenericType (storey);
-               }
-
                public override string ToString ()
                {
                        return "StatementExpression (" + expr + ")";
@@ -768,19 +721,13 @@ namespace Mono.CSharp {
                                Expr.Emit (ec);
 
                                if (unwind_protect)
-                                       ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
+                                       ec.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
                        }
 
                        if (unwind_protect)
-                               ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
+                               ec.Emit (OpCodes.Leave, ec.ReturnLabel);
                        else
-                               ec.ig.Emit (OpCodes.Ret);
-               }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       if (Expr != null)
-                               Expr.MutateHoistedGenericType (storey);
+                               ec.Emit (OpCodes.Ret);
                }
 
                protected override void CloneTo (CloneContext clonectx, Statement t)
@@ -830,11 +777,7 @@ namespace Mono.CSharp {
                        if (label == null)
                                throw new InternalErrorException ("goto emitted before target resolved");
                        Label l = label.LabelTarget (ec);
-                       ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
-               }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
+                       ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
                }
        }
 
@@ -843,7 +786,6 @@ namespace Mono.CSharp {
                bool defined;
                bool referenced;
                Label label;
-               ILGenerator ig;
 
                FlowBranching.UsageVector vectors;
                
@@ -857,10 +799,9 @@ namespace Mono.CSharp {
                {
                        if (defined)
                                return label;
-                       ig = ec.ig;
-                       label = ec.ig.DefineLabel ();
-                       defined = true;
 
+                       label = ec.DefineLabel ();
+                       defined = true;
                        return label;
                }
 
@@ -901,14 +842,8 @@ namespace Mono.CSharp {
 
                protected override void DoEmit (EmitContext ec)
                {
-                       if (ig != null && ig != ec.ig)
-                               throw new InternalErrorException ("cannot happen");
                        LabelTarget (ec);
-                       ec.ig.MarkLabel (label);
-               }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
+                       ec.MarkLabel (label);
                }
 
                public void AddReference ()
@@ -952,11 +887,7 @@ namespace Mono.CSharp {
 
                protected override void DoEmit (EmitContext ec)
                {
-                       ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
-               }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
+                       ec.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
                }
        }
 
@@ -992,7 +923,7 @@ namespace Mono.CSharp {
                                return false;
                        }
 
-                       Type type = ec.Switch.SwitchType;
+                       TypeSpec type = ec.Switch.SwitchType;
                        Constant res = c.TryReduce (ec, type, c.Location);
                        if (res == null) {
                                c.Error_ValueCannotBeConverted (ec, loc, type, true);
@@ -1019,12 +950,7 @@ namespace Mono.CSharp {
 
                protected override void DoEmit (EmitContext ec)
                {
-                       ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
-               }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       expr.MutateHoistedGenericType (storey);
+                       ec.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
                }
 
                protected override void CloneTo (CloneContext clonectx, Statement t)
@@ -1068,20 +994,14 @@ namespace Mono.CSharp {
                protected override void DoEmit (EmitContext ec)
                {
                        if (expr == null)
-                               ec.ig.Emit (OpCodes.Rethrow);
+                               ec.Emit (OpCodes.Rethrow);
                        else {
                                expr.Emit (ec);
 
-                               ec.ig.Emit (OpCodes.Throw);
+                               ec.Emit (OpCodes.Throw);
                        }
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       if (expr != null)
-                               expr.MutateHoistedGenericType (storey);
-               }
-
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        Throw target = (Throw) t;
@@ -1109,13 +1029,9 @@ namespace Mono.CSharp {
 
                protected override void DoEmit (EmitContext ec)
                {
-                       ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopEnd);
+                       ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopEnd);
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-               }
-               
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        // nothing needed
@@ -1140,11 +1056,7 @@ namespace Mono.CSharp {
 
                protected override void DoEmit (EmitContext ec)
                {
-                       ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopBegin);
-               }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
+                       ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopBegin);
                }
 
                protected override void CloneTo (CloneContext clonectx, Statement t)
@@ -1171,7 +1083,7 @@ namespace Mono.CSharp {
        public class LocalInfo : IKnownVariable, ILocalVariable {
                public readonly FullNamedExpression Type;
 
-               public Type VariableType;
+               public TypeSpec VariableType;
                public readonly string Name;
                public readonly Location Location;
                public readonly Block Block;
@@ -1208,9 +1120,9 @@ namespace Mono.CSharp {
                        Location = l;
                }
 
-               public LocalInfo (DeclSpace ds, Block block, Location l)
+               public LocalInfo (TypeContainer ds, Block block, Location l)
                {
-                       VariableType = ds.IsGeneric ? ds.CurrentType : ds.TypeBuilder;
+                       VariableType = ds.IsGeneric ? ds.CurrentType : ds.Definition;
                        Block = block;
                        Location = l;
                }
@@ -1221,23 +1133,23 @@ namespace Mono.CSharp {
                                return;
 
                        if (builder == null) {
-                               builder = ec.ig.DeclareLocal (TypeManager.TypeToReflectionType (VariableType), Pinned);
+                               builder = ec.DeclareLocal (VariableType, Pinned);
                        }
                }
 
                public void Emit (EmitContext ec)
                {
-                       ec.ig.Emit (OpCodes.Ldloc, builder);
+                       ec.Emit (OpCodes.Ldloc, builder);
                }
 
                public void EmitAssign (EmitContext ec)
                {
-                       ec.ig.Emit (OpCodes.Stloc, builder);
+                       ec.Emit (OpCodes.Stloc, builder);
                }
 
                public void EmitAddressOf (EmitContext ec)
                {
-                       ec.ig.Emit (OpCodes.Ldloca, builder);
+                       ec.Emit (OpCodes.Ldloca, builder);
                }
 
                public void EmitSymbolInfo (EmitContext ec)
@@ -1288,10 +1200,7 @@ namespace Mono.CSharp {
                                
                        VariableType = texpr.Type;
 
-                       if (TypeManager.IsGenericParameter (VariableType))
-                               return true;
-
-                       if (VariableType.IsAbstract && VariableType.IsSealed) {
+                       if (VariableType.IsStatic) {
                                FieldBase.Error_VariableOfStaticClass (Location, Name, VariableType, ec.Report);
                                return false;
                        }
@@ -1947,7 +1856,7 @@ namespace Mono.CSharp {
                        foreach (var de in variables) {
                                string name = de.Key;
                                LocalInfo vi = de.Value;
-                               Type variable_type = vi.VariableType;
+                               TypeSpec variable_type = vi.VariableType;
 
                                if (variable_type == null) {
                                        if (vi.Type is VarExpr)
@@ -1965,7 +1874,7 @@ namespace Mono.CSharp {
                                // which in turn causes the 'must be constant' error to be triggered.
                                constants.Remove (name);
 
-                               if (!Const.IsConstantTypeValid (variable_type)) {
+                               if (!variable_type.IsConstantCompatible) {
                                        Const.Error_InvalidConstantType (variable_type, loc, ec.Report);
                                        continue;
                                }
@@ -2242,14 +2151,14 @@ namespace Mono.CSharp {
 
                protected void EmitScopeInitializers (EmitContext ec)
                {
-                       SymbolWriter.OpenCompilerGeneratedBlock (ec.ig);
+                       SymbolWriter.OpenCompilerGeneratedBlock (ec);
 
                        using (ec.With (EmitContext.Options.OmitDebugInfo, true)) {
                                foreach (Statement s in scope_initializers)
                                        s.Emit (ec);
                        }
 
-                       SymbolWriter.CloseCompilerGeneratedBlock (ec.ig);
+                       SymbolWriter.CloseCompilerGeneratedBlock (ec);
                }
 
                protected virtual void EmitSymbolInfo (EmitContext ec)
@@ -2261,33 +2170,6 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       MutateVariables (storey);
-
-                       if (scope_initializers != null) {
-                               foreach (Statement s in scope_initializers)
-                                       s.MutateHoistedGenericType (storey);
-                       }
-
-                       foreach (Statement s in statements)
-                               s.MutateHoistedGenericType (storey);
-               }
-
-               void MutateVariables (AnonymousMethodStorey storey)
-               {
-                       if (variables != null) {
-                               foreach (LocalInfo vi in variables.Values) {
-                                       vi.VariableType = storey.MutateType (vi.VariableType);
-                               }
-                       }
-
-                       if (temporary_variables != null) {
-                               foreach (LocalInfo vi in temporary_variables)
-                                       vi.VariableType = storey.MutateType (vi.VariableType);
-                       }
-               }
-
                public override string ToString ()
                {
                        return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
@@ -2392,7 +2274,7 @@ namespace Mono.CSharp {
                                //
                                // Creates anonymous method storey for this block
                                //
-                               am_storey = new AnonymousMethodStorey (this, ec.CurrentTypeDefinition, mc, gm, "AnonStorey");
+                               am_storey = new AnonymousMethodStorey (this, ec.CurrentMemberDefinition.Parent.PartialContainer, mc, gm, "AnonStorey");
                        }
 
                        return am_storey;
@@ -2432,14 +2314,21 @@ namespace Mono.CSharp {
                                                while (parent.am_storey == null || parent.am_storey.Parent is AnonymousMethodStorey)
                                                        parent = parent.Parent.Explicit;
 
-                                               am_storey.AddParentStoreyReference (parent.am_storey);
+                                               am_storey.AddParentStoreyReference (ec, parent.am_storey);
                                        }
 
-                                       am_storey.ChangeParentStorey (ec.CurrentAnonymousMethod.Storey);
+                                       am_storey.SetNestedStoryParent (ec.CurrentAnonymousMethod.Storey);
+
+                                       // TODO MemberCache: Review
+                                       am_storey.Mutator = ec.CurrentAnonymousMethod.Storey.Mutator;
                                }
 
+                               am_storey.CreateType ();
+                               if (am_storey.Mutator == null && ec.CurrentTypeParameters != null)
+                                       am_storey.Mutator = new TypeParameterMutator (ec.CurrentTypeParameters, am_storey.CurrentTypeParameters);
+
                                am_storey.DefineType ();
-                               am_storey.ResolveType ();
+                               am_storey.ResolveTypeParameters ();
                                am_storey.Define ();
                                am_storey.Parent.PartialContainer.AddCompilerGeneratedClass (am_storey);
 
@@ -2448,7 +2337,7 @@ namespace Mono.CSharp {
                                        foreach (ExplicitBlock ref_block in ref_blocks) {
                                                for (ExplicitBlock b = ref_block.Explicit; b != this; b = b.Parent.Explicit) {
                                                        if (b.am_storey != null) {
-                                                               b.am_storey.AddParentStoreyReference (am_storey);
+                                                               b.am_storey.AddParentStoreyReference (ec, am_storey);
 
                                                                // Stop propagation inside same top block
                                                                if (b.Toplevel == Toplevel)
@@ -2509,7 +2398,7 @@ namespace Mono.CSharp {
                        get { return Block.Parameters [Index]; }
                }
 
-               public Type ParameterType {
+               public TypeSpec ParameterType {
                        get { return Block.Parameters.Types [Index]; }
                }
 
@@ -2573,13 +2462,6 @@ namespace Mono.CSharp {
                                block.EmitScopeInitializers (ec);
                                child.Emit (ec);
                        }
-
-                       public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-                       {
-                               type = storey.MutateType (type);
-                               child.MutateHoistedGenericType (storey);
-                               block.MutateHoistedGenericType (storey);
-                       }
                }
 
                GenericMethod generic;
@@ -2791,7 +2673,7 @@ namespace Mono.CSharp {
                //   analysis code to ensure that it's been fully initialized before control
                //   leaves the constructor.
                // </summary>
-               public LocalInfo AddThisVariable (DeclSpace ds, Location l)
+               public LocalInfo AddThisVariable (TypeContainer ds, Location l)
                {
                        if (this_variable == null) {
                                this_variable = new LocalInfo (ds, this, l);
@@ -2933,18 +2815,18 @@ namespace Mono.CSharp {
                        EmitMeta (ec);
 
                        if (ec.HasReturnLabel)
-                               ec.ReturnLabel = ec.ig.DefineLabel ();
+                               ec.ReturnLabel = ec.DefineLabel ();
 
                        base.Emit (ec);
 
                        ec.Mark (EndLocation);
 
                        if (ec.HasReturnLabel)
-                               ec.ig.MarkLabel (ec.ReturnLabel);
+                               ec.MarkLabel (ec.ReturnLabel);
 
                        if (ec.return_value != null) {
-                               ec.ig.Emit (OpCodes.Ldloc, ec.return_value);
-                               ec.ig.Emit (OpCodes.Ret);
+                               ec.Emit (OpCodes.Ldloc, ec.return_value);
+                               ec.Emit (OpCodes.Ret);
                        } else {
                                //
                                // If `HasReturnLabel' is set, then we already emitted a
@@ -2961,8 +2843,8 @@ namespace Mono.CSharp {
 
                                if (ec.HasReturnLabel || !unreachable) {
                                        if (ec.ReturnType != TypeManager.void_type)
-                                               ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
-                                       ec.ig.Emit (OpCodes.Ret);
+                                               ec.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
+                                       ec.Emit (OpCodes.Ret);
                                }
                        }
 
@@ -2979,8 +2861,6 @@ namespace Mono.CSharp {
 
                public override void EmitMeta (EmitContext ec)
                {
-                       parameters.ResolveVariable ();
-
                        // Avoid declaring an IL variable for this_variable since it is not accessed
                        // from the generated IL
                        if (this_variable != null)
@@ -3038,7 +2918,7 @@ namespace Mono.CSharp {
                public Label GetILLabel (EmitContext ec)
                {
                        if (!il_label_set){
-                               il_label = ec.ig.DefineLabel ();
+                               il_label = ec.DefineLabel ();
                                il_label_set = true;
                        }
                        return il_label;
@@ -3047,7 +2927,7 @@ namespace Mono.CSharp {
                public Label GetILLabelCode (EmitContext ec)
                {
                        if (!il_label_code_set){
-                               il_label_code = ec.ig.DefineLabel ();
+                               il_label_code = ec.DefineLabel ();
                                il_label_code_set = true;
                        }
                        return il_label_code;
@@ -3057,7 +2937,7 @@ namespace Mono.CSharp {
                // Resolves the expression, reduces it to a literal if possible
                // and then converts it to the requested type.
                //
-               public bool ResolveAndReduce (ResolveContext ec, Type required_type, bool allow_nullable)
+               public bool ResolveAndReduce (ResolveContext ec, TypeSpec required_type, bool allow_nullable)
                {       
                        Expression e = label.Resolve (ec);
 
@@ -3088,7 +2968,7 @@ namespace Mono.CSharp {
                        return true;
                }
 
-               public void Error_AlreadyOccurs (ResolveContext ec, Type switch_type, SwitchLabel collision_with)
+               public void Error_AlreadyOccurs (ResolveContext ec, TypeSpec switch_type, SwitchLabel collision_with)
                {
                        string label;
                        if (converted == null)
@@ -3142,7 +3022,7 @@ namespace Mono.CSharp {
                /// <summary>
                ///   The governing switch type
                /// </summary>
-               public Type SwitchType;
+               public TypeSpec SwitchType;
 
                //
                // Computed
@@ -3172,7 +3052,7 @@ namespace Mono.CSharp {
                // The types allowed to be implicitly cast from
                // on the governing type
                //
-               static Type [] allowed_types;
+               static TypeSpec [] allowed_types;
 
                public Switch (Expression e, List<SwitchSection> sects, Location l)
                {
@@ -3201,7 +3081,7 @@ namespace Mono.CSharp {
                //
                Expression SwitchGoverningType (ResolveContext ec, Expression expr)
                {
-                       Type t = expr.Type;
+                       TypeSpec t = expr.Type;
 
                        if (t == TypeManager.byte_type ||
                            t == TypeManager.sbyte_type ||
@@ -3218,7 +3098,7 @@ namespace Mono.CSharp {
                                return expr;
 
                        if (allowed_types == null){
-                               allowed_types = new Type [] {
+                               allowed_types = new TypeSpec [] {
                                        TypeManager.sbyte_type,
                                        TypeManager.byte_type,
                                        TypeManager.short_type,
@@ -3239,7 +3119,7 @@ namespace Mono.CSharp {
                        // conversions, we have to report an error
                        //
                        Expression converted = null;
-                       foreach (Type tt in allowed_types){
+                       foreach (TypeSpec tt in allowed_types){
                                Expression e;
                                
                                e = Convert.ImplicitUserConversion (ec, expr, tt, loc);
@@ -3306,50 +3186,50 @@ namespace Mono.CSharp {
                        return !error;
                }
 
-               void EmitObjectInteger (ILGenerator ig, object k)
+               void EmitObjectInteger (EmitContext ec, object k)
                {
                        if (k is int)
-                               IntConstant.EmitInt (ig, (int) k);
+                               ec.EmitInt ((int) k);
                        else if (k is Constant) {
-                               EmitObjectInteger (ig, ((Constant) k).GetValue ());
+                               EmitObjectInteger (ec, ((Constant) k).GetValue ());
                        } 
                        else if (k is uint)
-                               IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
+                               ec.EmitInt (unchecked ((int) (uint) k));
                        else if (k is long)
                        {
                                if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
                                {
-                                       IntConstant.EmitInt (ig, (int) (long) k);
-                                       ig.Emit (OpCodes.Conv_I8);
+                                       ec.EmitInt ((int) (long) k);
+                                       ec.Emit (OpCodes.Conv_I8);
                                }
                                else
-                                       LongConstant.EmitLong (ig, (long) k);
+                                       ec.EmitLong ((long) k);
                        }
                        else if (k is ulong)
                        {
                                ulong ul = (ulong) k;
                                if (ul < (1L<<32))
                                {
-                                       IntConstant.EmitInt (ig, unchecked ((int) ul));
-                                       ig.Emit (OpCodes.Conv_U8);
+                                       ec.EmitInt (unchecked ((int) ul));
+                                       ec.Emit (OpCodes.Conv_U8);
                                }
                                else
                                {
-                                       LongConstant.EmitLong (ig, unchecked ((long) ul));
+                                       ec.EmitLong (unchecked ((long) ul));
                                }
                        }
                        else if (k is char)
-                               IntConstant.EmitInt (ig, (int) ((char) k));
+                               ec.EmitInt ((int) ((char) k));
                        else if (k is sbyte)
-                               IntConstant.EmitInt (ig, (int) ((sbyte) k));
+                               ec.EmitInt ((int) ((sbyte) k));
                        else if (k is byte)
-                               IntConstant.EmitInt (ig, (int) ((byte) k));
+                               ec.EmitInt ((int) ((byte) k));
                        else if (k is short)
-                               IntConstant.EmitInt (ig, (int) ((short) k));
+                               ec.EmitInt ((int) ((short) k));
                        else if (k is ushort)
-                               IntConstant.EmitInt (ig, (int) ((ushort) k));
+                               ec.EmitInt ((int) ((ushort) k));
                        else if (k is bool)
-                               IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
+                               ec.EmitInt (((bool) k) ? 1 : 0);
                        else
                                throw new Exception ("Unhandled case");
                }
@@ -3458,25 +3338,24 @@ namespace Mono.CSharp {
                        key_blocks.Sort ();
 
                        // okay now we can start...
-                       ILGenerator ig = ec.ig;
-                       Label lbl_end = ig.DefineLabel ();      // at the end ;-)
+                       Label lbl_end = ec.DefineLabel ();      // at the end ;-)
                        Label lbl_default = default_target;
 
                        Type type_keys = null;
                        if (element_keys.Length > 0)
                                type_keys = element_keys [0].GetType ();        // used for conversions
 
-                       Type compare_type;
+                       TypeSpec compare_type;
                        
                        if (TypeManager.IsEnumType (SwitchType))
-                               compare_type = TypeManager.GetEnumUnderlyingType (SwitchType);
+                               compare_type = EnumSpec.GetUnderlyingType (SwitchType);
                        else
                                compare_type = SwitchType;
                        
                        for (int iBlock = key_blocks.Count - 1; iBlock >= 0; --iBlock)
                        {
                                KeyBlock kb = ((KeyBlock) key_blocks [iBlock]);
-                               lbl_default = (iBlock == 0) ? default_target : ig.DefineLabel ();
+                               lbl_default = (iBlock == 0) ? default_target : ec.DefineLabel ();
                                if (kb.Length <= 2)
                                {
                                        foreach (object key in kb.element_keys) {
@@ -3485,8 +3364,8 @@ namespace Mono.CSharp {
                                                        val.EmitBranchable (ec, sl.GetILLabel (ec), false);
                                                } else {
                                                        val.Emit (ec);
-                                                       EmitObjectInteger (ig, key);
-                                                       ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
+                                                       EmitObjectInteger (ec, key);
+                                                       ec.Emit (OpCodes.Beq, sl.GetILLabel (ec));
                                                }
                                        }
                                }
@@ -3501,20 +3380,20 @@ namespace Mono.CSharp {
 
                                                // check block range (could be > 2^31)
                                                val.Emit (ec);
-                                               EmitObjectInteger (ig, System.Convert.ChangeType (kb.first, type_keys));
-                                               ig.Emit (OpCodes.Blt, lbl_default);
+                                               EmitObjectInteger (ec, System.Convert.ChangeType (kb.first, type_keys));
+                                               ec.Emit (OpCodes.Blt, lbl_default);
                                                val.Emit (ec);
-                                               EmitObjectInteger (ig, System.Convert.ChangeType (kb.last, type_keys));
-                                               ig.Emit (OpCodes.Bgt, lbl_default);
+                                               EmitObjectInteger (ec, System.Convert.ChangeType (kb.last, type_keys));
+                                               ec.Emit (OpCodes.Bgt, lbl_default);
 
                                                // normalize range
                                                val.Emit (ec);
                                                if (kb.first != 0)
                                                {
-                                                       EmitObjectInteger (ig, System.Convert.ChangeType (kb.first, type_keys));
-                                                       ig.Emit (OpCodes.Sub);
+                                                       EmitObjectInteger (ec, System.Convert.ChangeType (kb.first, type_keys));
+                                                       ec.Emit (OpCodes.Sub);
                                                }
-                                               ig.Emit (OpCodes.Conv_I4);      // assumes < 2^31 labels!
+                                               ec.Emit (OpCodes.Conv_I4);      // assumes < 2^31 labels!
                                        }
                                        else
                                        {
@@ -3523,13 +3402,13 @@ namespace Mono.CSharp {
                                                int first = (int) kb.first;
                                                if (first > 0)
                                                {
-                                                       IntConstant.EmitInt (ig, first);
-                                                       ig.Emit (OpCodes.Sub);
+                                                       ec.EmitInt (first);
+                                                       ec.Emit (OpCodes.Sub);
                                                }
                                                else if (first < 0)
                                                {
-                                                       IntConstant.EmitInt (ig, -first);
-                                                       ig.Emit (OpCodes.Add);
+                                                       ec.EmitInt (-first);
+                                                       ec.Emit (OpCodes.Add);
                                                }
                                        }
 
@@ -3550,12 +3429,12 @@ namespace Mono.CSharp {
                                                        switch_labels [iJump] = lbl_default;
                                        }
                                        // emit the switch opcode
-                                       ig.Emit (OpCodes.Switch, switch_labels);
+                                       ec.Emit (OpCodes.Switch, switch_labels);
                                }
 
                                // mark the default for this block
                                if (iBlock != 0)
-                                       ig.MarkLabel (lbl_default);
+                                       ec.MarkLabel (lbl_default);
                        }
 
                        // TODO: find the default case and emit it here,
@@ -3564,7 +3443,7 @@ namespace Mono.CSharp {
 
                        // the last default just goes to the end
                        if (element_keys.Length > 0)
-                               ig.Emit (OpCodes.Br, lbl_default);
+                               ec.Emit (OpCodes.Br, lbl_default);
 
                        // now emit the code for the sections
                        bool found_default = false;
@@ -3572,27 +3451,27 @@ namespace Mono.CSharp {
                        foreach (SwitchSection ss in Sections) {
                                foreach (SwitchLabel sl in ss.Labels) {
                                        if (sl.Converted == SwitchLabel.NullStringCase) {
-                                               ig.MarkLabel (null_target);
+                                               ec.MarkLabel (null_target);
                                        } else if (sl.Label == null) {
-                                               ig.MarkLabel (lbl_default);
+                                               ec.MarkLabel (lbl_default);
                                                found_default = true;
                                                if (!has_null_case)
-                                                       ig.MarkLabel (null_target);
+                                                       ec.MarkLabel (null_target);
                                        }
-                                       ig.MarkLabel (sl.GetILLabel (ec));
-                                       ig.MarkLabel (sl.GetILLabelCode (ec));
+                                       ec.MarkLabel (sl.GetILLabel (ec));
+                                       ec.MarkLabel (sl.GetILLabelCode (ec));
                                }
                                ss.Block.Emit (ec);
                        }
                        
                        if (!found_default) {
-                               ig.MarkLabel (lbl_default);
+                               ec.MarkLabel (lbl_default);
                                if (!has_null_case) {
-                                       ig.MarkLabel (null_target);
+                                       ec.MarkLabel (null_target);
                                }
                        }
                        
-                       ig.MarkLabel (lbl_end);
+                       ec.MarkLabel (lbl_end);
                }
 
                SwitchSection FindSection (SwitchLabel label)
@@ -3607,12 +3486,6 @@ namespace Mono.CSharp {
                        return null;
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       foreach (SwitchSection ss in Sections)
-                               ss.Block.MutateHoistedGenericType (storey);
-               }
-
                public static void Reset ()
                {
                        unique_counter = 0;
@@ -3736,12 +3609,13 @@ namespace Mono.CSharp {
                                string_dictionary_type = new MemberAccess (system_collections_generic, "Hashtable", loc);
                        }
 
-                       Field field = new Field (ec.CurrentTypeDefinition, string_dictionary_type,
+                       var ctype = ec.CurrentMemberDefinition.Parent.PartialContainer;
+                       Field field = new Field (ctype, string_dictionary_type,
                                Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
                                new MemberName (CompilerGeneratedClass.MakeName (null, "f", "switch$map", unique_counter++), loc), null);
                        if (!field.Define ())
                                return;
-                       ec.CurrentTypeDefinition.PartialContainer.AddField (field);
+                       ctype.AddField (field);
 
                        var init = new List<Expression> ();
                        int counter = 0;
@@ -3781,8 +3655,7 @@ namespace Mono.CSharp {
 
                void DoEmitStringSwitch (LocalTemporary value, EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-                       Label l_initialized = ig.DefineLabel ();
+                       Label l_initialized = ec.DefineLabel ();
 
                        //
                        // Skip initialization when value is null
@@ -3794,7 +3667,7 @@ namespace Mono.CSharp {
                        //
                        switch_cache_field.EmitBranchable (ec, l_initialized, true);
                        string_dictionary.EmitStatement (ec);
-                       ig.MarkLabel (l_initialized);
+                       ec.MarkLabel (l_initialized);
 
                        LocalTemporary string_switch_variable = new LocalTemporary (TypeManager.int32_type);
 
@@ -3822,7 +3695,7 @@ namespace Mono.CSharp {
 
                                LocalTemporary get_item_object = new LocalTemporary (TypeManager.object_type);
                                get_item_object.EmitAssign (ec, get_item, true, false);
-                               ec.ig.Emit (OpCodes.Brfalse, default_target);
+                               ec.Emit (OpCodes.Brfalse, default_target);
 
                                ExpressionStatement get_item_int = (ExpressionStatement) new SimpleAssign (string_switch_variable,
                                        new Cast (new TypeExpression (TypeManager.int32_type, loc), get_item_object, loc)).Resolve (rc);
@@ -3837,10 +3710,8 @@ namespace Mono.CSharp {
                
                protected override void DoEmit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-
-                       default_target = ig.DefineLabel ();
-                       null_target = ig.DefineLabel ();
+                       default_target = ec.DefineLabel ();
+                       null_target = ec.DefineLabel ();
 
                        // Store variable for comparission purposes
                        // TODO: Don't duplicate non-captured VariableReference
@@ -3848,7 +3719,7 @@ namespace Mono.CSharp {
                        if (HaveUnwrap) {
                                value = new LocalTemporary (SwitchType);
                                unwrap.EmitCheck (ec);
-                               ig.Emit (OpCodes.Brfalse, null_target);
+                               ec.Emit (OpCodes.Brfalse, null_target);
                                new_expr.Emit (ec);
                                value.Store (ec);
                        } else if (!is_constant) {
@@ -3864,7 +3735,7 @@ namespace Mono.CSharp {
                        Label old_end = ec.LoopEnd;
                        Switch old_switch = ec.Switch;
                        
-                       ec.LoopEnd = ig.DefineLabel ();
+                       ec.LoopEnd = ec.DefineLabel ();
                        ec.Switch = this;
 
                        // Emit Code.
@@ -3881,7 +3752,7 @@ namespace Mono.CSharp {
                                value.Release (ec);
 
                        // Restore context state. 
-                       ig.MarkLabel (ec.LoopEnd);
+                       ec.MarkLabel (ec.LoopEnd);
 
                        //
                        // Restore the previous context
@@ -3912,7 +3783,7 @@ namespace Mono.CSharp {
                {
                        if (!prepared) {
                                prepared = true;
-                               resume_point = ec.ig.DefineLabel ();
+                               resume_point = ec.DefineLabel ();
                        }
                        return resume_point;
                }
@@ -3940,47 +3811,45 @@ namespace Mono.CSharp {
 
                protected sealed override void DoEmit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-
                        EmitPreTryBody (ec);
 
                        if (resume_points != null) {
-                               IntConstant.EmitInt (ig, (int) Iterator.State.Running);
-                               ig.Emit (OpCodes.Stloc, iter.CurrentPC);
+                               ec.EmitInt ((int) Iterator.State.Running);
+                               ec.Emit (OpCodes.Stloc, iter.CurrentPC);
                        }
 
-                       ig.BeginExceptionBlock ();
+                       ec.BeginExceptionBlock ();
 
                        if (resume_points != null) {
-                               ig.MarkLabel (resume_point);
+                               ec.MarkLabel (resume_point);
 
                                // For normal control flow, we want to fall-through the Switch
                                // So, we use CurrentPC rather than the $PC field, and initialize it to an outside value above
-                               ig.Emit (OpCodes.Ldloc, iter.CurrentPC);
-                               IntConstant.EmitInt (ig, first_resume_pc);
-                               ig.Emit (OpCodes.Sub);
+                               ec.Emit (OpCodes.Ldloc, iter.CurrentPC);
+                               ec.EmitInt (first_resume_pc);
+                               ec.Emit (OpCodes.Sub);
 
                                Label [] labels = new Label [resume_points.Count];
                                for (int i = 0; i < resume_points.Count; ++i)
                                        labels [i] = ((ResumableStatement) resume_points [i]).PrepareForEmit (ec);
-                               ig.Emit (OpCodes.Switch, labels);
+                               ec.Emit (OpCodes.Switch, labels);
                        }
 
                        EmitTryBody (ec);
 
-                       ig.BeginFinallyBlock ();
+                       ec.BeginFinallyBlock ();
 
-                       Label start_finally = ec.ig.DefineLabel ();
+                       Label start_finally = ec.DefineLabel ();
                        if (resume_points != null) {
-                               ig.Emit (OpCodes.Ldloc, iter.SkipFinally);
-                               ig.Emit (OpCodes.Brfalse_S, start_finally);
-                               ig.Emit (OpCodes.Endfinally);
+                               ec.Emit (OpCodes.Ldloc, iter.SkipFinally);
+                               ec.Emit (OpCodes.Brfalse_S, start_finally);
+                               ec.Emit (OpCodes.Endfinally);
                        }
 
-                       ig.MarkLabel (start_finally);
+                       ec.MarkLabel (start_finally);
                        EmitFinallyBody (ec);
 
-                       ig.EndExceptionBlock ();
+                       ec.EndExceptionBlock ();
                }
 
                public void SomeCodeFollows ()
@@ -4018,7 +3887,7 @@ namespace Mono.CSharp {
                {
                        if (!prepared_for_dispose) {
                                prepared_for_dispose = true;
-                               dispose_try_block = ec.ig.DefineLabel ();
+                               dispose_try_block = ec.DefineLabel ();
                        }
                        return dispose_try_block;
                }
@@ -4030,17 +3899,15 @@ namespace Mono.CSharp {
 
                        emitted_dispose = true;
 
-                       ILGenerator ig = ec.ig;
-
-                       Label end_of_try = ig.DefineLabel ();
+                       Label end_of_try = ec.DefineLabel ();
 
                        // Ensure that the only way we can get into this code is through a dispatcher
                        if (have_dispatcher)
-                               ig.Emit (OpCodes.Br, end);
+                               ec.Emit (OpCodes.Br, end);
 
-                       ig.BeginExceptionBlock ();
+                       ec.BeginExceptionBlock ();
 
-                       ig.MarkLabel (dispose_try_block);
+                       ec.MarkLabel (dispose_try_block);
 
                        Label [] labels = null;
                        for (int i = 0; i < resume_points.Count; ++i) {
@@ -4065,10 +3932,10 @@ namespace Mono.CSharp {
 
                                if (emit_dispatcher) {
                                        //SymbolWriter.StartIteratorDispatcher (ec.ig);
-                                       ig.Emit (OpCodes.Ldloc, iterator.CurrentPC);
-                                       IntConstant.EmitInt (ig, first_resume_pc);
-                                       ig.Emit (OpCodes.Sub);
-                                       ig.Emit (OpCodes.Switch, labels);
+                                       ec.Emit (OpCodes.Ldloc, iterator.CurrentPC);
+                                       ec.EmitInt (first_resume_pc);
+                                       ec.Emit (OpCodes.Sub);
+                                       ec.Emit (OpCodes.Switch, labels);
                                        //SymbolWriter.EndIteratorDispatcher (ec.ig);
                                }
 
@@ -4076,13 +3943,13 @@ namespace Mono.CSharp {
                                        s.EmitForDispose (ec, iterator, end_of_try, emit_dispatcher);
                        }
 
-                       ig.MarkLabel (end_of_try);
+                       ec.MarkLabel (end_of_try);
 
-                       ig.BeginFinallyBlock ();
+                       ec.BeginFinallyBlock ();
 
                        EmitFinallyBody (ec);
 
-                       ig.EndExceptionBlock ();
+                       ec.EndExceptionBlock ();
                }
        }
 
@@ -4119,7 +3986,7 @@ namespace Mono.CSharp {
 
                        // Avoid creating libraries that reference the internal
                        // mcs NullType:
-                       Type t = expr.Type;
+                       TypeSpec t = expr.Type;
                        if (t == TypeManager.null_type)
                                t = TypeManager.object_type;
                        
@@ -4127,7 +3994,7 @@ namespace Mono.CSharp {
                        temp.Resolve (ec);
 
                        if (TypeManager.void_monitor_enter_object == null || TypeManager.void_monitor_exit_object == null) {
-                               Type monitor_type = TypeManager.CoreLookupType (ec.Compiler, "System.Threading", "Monitor", MemberKind.Class, true);
+                               TypeSpec monitor_type = TypeManager.CoreLookupType (ec.Compiler, "System.Threading", "Monitor", MemberKind.Class, true);
                                TypeManager.void_monitor_enter_object = TypeManager.GetPredefinedMethod (
                                        monitor_type, "Enter", loc, TypeManager.object_type);
                                TypeManager.void_monitor_exit_object = TypeManager.GetPredefinedMethod (
@@ -4139,11 +4006,9 @@ namespace Mono.CSharp {
                
                protected override void EmitPreTryBody (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-
                        temp.EmitAssign (ec, expr);
                        temp.Emit (ec);
-                       ig.Emit (OpCodes.Call, (MethodInfo) TypeManager.void_monitor_enter_object.MetaInfo);
+                       ec.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
                }
 
                protected override void EmitTryBody (EmitContext ec)
@@ -4154,16 +4019,9 @@ namespace Mono.CSharp {
                protected override void EmitFinallyBody (EmitContext ec)
                {
                        temp.Emit (ec);
-                       ec.ig.Emit (OpCodes.Call, (MethodInfo) TypeManager.void_monitor_exit_object.MetaInfo);
+                       ec.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       expr.MutateHoistedGenericType (storey);
-                       temp.MutateHoistedGenericType (storey);
-                       Statement.MutateHoistedGenericType (storey);
-               }
-               
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        Lock target = (Lock) t;
@@ -4194,11 +4052,6 @@ namespace Mono.CSharp {
                                Block.Emit (ec);
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       Block.MutateHoistedGenericType (storey);
-               }
-
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        Unchecked target = (Unchecked) t;
@@ -4228,11 +4081,6 @@ namespace Mono.CSharp {
                                Block.Emit (ec);
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       Block.MutateHoistedGenericType (storey);
-               }
-
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        Checked target = (Checked) t;
@@ -4265,11 +4113,6 @@ namespace Mono.CSharp {
                        Block.Emit (ec);
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       Block.MutateHoistedGenericType (storey);
-               }
-
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        Unsafe target = (Unsafe) t;
@@ -4285,7 +4128,7 @@ namespace Mono.CSharp {
                Expression type;
                List<KeyValuePair<LocalInfo, Expression>> declarators;
                Statement statement;
-               Type expr_type;
+               TypeSpec expr_type;
                Emitter[] data;
                bool has_ret;
 
@@ -4320,8 +4163,8 @@ namespace Mono.CSharp {
 
                        public override void EmitExit (EmitContext ec)
                        {
-                               ec.ig.Emit (OpCodes.Ldc_I4_0);
-                               ec.ig.Emit (OpCodes.Conv_U);
+                               ec.Emit (OpCodes.Ldc_I4_0);
+                               ec.Emit (OpCodes.Conv_U);
                                vi.EmitAssign (ec);
                        }
                }
@@ -4358,19 +4201,19 @@ namespace Mono.CSharp {
 
                                // TODO: Should use Binary::Add
                                pinned_string.Emit (ec);
-                               ec.ig.Emit (OpCodes.Conv_I);
+                               ec.Emit (OpCodes.Conv_I);
 
                                PropertyExpr pe = new PropertyExpr (pinned_string.VariableType, TypeManager.int_get_offset_to_string_data, pinned_string.Location);
                                //pe.InstanceExpression = pinned_string;
                                pe.Resolve (new ResolveContext (ec.MemberContext)).Emit (ec);
 
-                               ec.ig.Emit (OpCodes.Add);
+                               ec.Emit (OpCodes.Add);
                                vi.EmitAssign (ec);
                        }
 
                        public override void EmitExit (EmitContext ec)
                        {
-                               ec.ig.Emit (OpCodes.Ldnull);
+                               ec.Emit (OpCodes.Ldnull);
                                pinned_string.EmitAssign (ec);
                        }
                }
@@ -4446,7 +4289,7 @@ namespace Mono.CSharp {
                                // Case 2: Array
                                //
                                if (e.Type.IsArray){
-                                       Type array_type = TypeManager.GetElementType (e.Type);
+                                       TypeSpec array_type = TypeManager.GetElementType (e.Type);
                                        
                                        //
                                        // Provided that array_type is unmanaged,
@@ -4541,12 +4384,6 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       // Fixed statement cannot be used inside anonymous methods or lambdas
-                       throw new NotSupportedException ();
-               }
-
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        Fixed target = (Fixed) t;
@@ -4568,7 +4405,7 @@ namespace Mono.CSharp {
                public Block  VarBlock;
 
                Expression type_expr;
-               Type type;
+               TypeSpec type;
                
                public Catch (Expression type, string name, Block block, Block var_block, Location l)
                {
@@ -4579,7 +4416,7 @@ namespace Mono.CSharp {
                        loc = l;
                }
 
-               public Type CatchType {
+               public TypeSpec CatchType {
                        get {
                                return type;
                        }
@@ -4593,12 +4430,10 @@ namespace Mono.CSharp {
 
                protected override void DoEmit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-
                        if (CatchType != null)
-                               ig.BeginCatchBlock (CatchType);
+                               ec.BeginCatchBlock (CatchType);
                        else
-                               ig.BeginCatchBlock (TypeManager.object_type);
+                               ec.BeginCatchBlock (TypeManager.object_type);
 
                        if (VarBlock != null)
                                VarBlock.Emit (ec);
@@ -4610,7 +4445,7 @@ namespace Mono.CSharp {
                                
                                // Only to make verifier happy
                                if (TypeManager.IsGenericParameter (lvr.Type))
-                                       ig.Emit (OpCodes.Unbox_Any, lvr.Type);
+                                       ec.Emit (OpCodes.Unbox_Any, lvr.Type);
 
                                Expression source;
                                if (lvr.IsHoisted) {
@@ -4624,7 +4459,7 @@ namespace Mono.CSharp {
 
                                lvr.EmitAssign (ec, source, false, false);
                        } else
-                               ig.Emit (OpCodes.Pop);
+                               ec.Emit (OpCodes.Pop);
 
                        Block.Emit (ec);
                }
@@ -4658,15 +4493,6 @@ namespace Mono.CSharp {
                        }
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       if (type != null)
-                               type = storey.MutateType (type);
-                       if (VarBlock != null)
-                               VarBlock.MutateHoistedGenericType (storey);
-                       Block.MutateHoistedGenericType (storey);
-               }
-
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        Catch target = (Catch) t;
@@ -4727,12 +4553,6 @@ namespace Mono.CSharp {
                        fini.Emit (ec);
                }
 
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       stmt.MutateHoistedGenericType (storey);
-                       fini.MutateHoistedGenericType (storey);
-               }
-
                protected override void CloneTo (CloneContext clonectx, Statement t)
                {
                        TryFinally target = (TryFinally) t;
@@ -4773,7 +4593,7 @@ namespace Mono.CSharp {
                        if (!Block.Resolve (ec))
                                ok = false;
 
-                       Type[] prev_catches = new Type [Specific.Count];
+                       TypeSpec[] prev_catches = new TypeSpec [Specific.Count];
                        int last_index = 0;
                        foreach (Catch c in Specific){
                                ec.CurrentBranching.CreateSibling (c.Block, FlowBranching.SiblingType.Catch);
@@ -4791,7 +4611,7 @@ namespace Mono.CSharp {
                                        continue;
                                }
 
-                               Type resolved_type = c.CatchType;
+                               TypeSpec resolved_type = c.CatchType;
                                for (int ii = 0; ii < last_index; ++ii) {
                                        if (resolved_type == prev_catches [ii] || TypeManager.IsSubclassOf (resolved_type, prev_catches [ii])) {
                                                ec.Report.Error (160, c.loc,
@@ -4836,10 +4656,8 @@ namespace Mono.CSharp {
                
                protected override void DoEmit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-
                        if (!inside_try_finally)
-                               ig.BeginExceptionBlock ();
+                               ec.BeginExceptionBlock ();
 
                        Block.Emit (ec);
 
@@ -4850,19 +4668,7 @@ namespace Mono.CSharp {
                                General.Emit (ec);
 
                        if (!inside_try_finally)
-                               ig.EndExceptionBlock ();
-               }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       Block.MutateHoistedGenericType (storey);
-
-                       if (General != null)
-                               General.MutateHoistedGenericType (storey);
-                       if (Specific != null) {
-                               foreach (Catch c in Specific)
-                                       c.MutateHoistedGenericType (storey);
-                       }
+                               ec.EndExceptionBlock ();
                }
 
                protected override void CloneTo (CloneContext clonectx, Statement t)
@@ -4885,7 +4691,7 @@ namespace Mono.CSharp {
                TemporaryVariable local_copy;
                public Statement Statement;
                Expression expr;
-               Type expr_type;
+               TypeSpec expr_type;
 
                public UsingTemporary (Expression expr, Statement stmt, Location l)
                {
@@ -4902,9 +4708,9 @@ namespace Mono.CSharp {
 
                        expr_type = expr.Type;
 
-                       if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type) &&
+                       if (!expr_type.ImplementsInterface (TypeManager.idisposable_type) &&
                                Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
-                               if (!TypeManager.IsDynamicType (expr_type)) {
+                               if (expr_type != InternalType.Dynamic) {
                                        Using.Error_IsNotConvertibleToIDisposable (ec, expr);
                                        return false;
                                }
@@ -4926,7 +4732,7 @@ namespace Mono.CSharp {
 
                        if (TypeManager.void_dispose_void == null) {
                                TypeManager.void_dispose_void = TypeManager.GetPredefinedMethod (
-                                       TypeManager.idisposable_type, "Dispose", loc, Type.EmptyTypes);
+                                       TypeManager.idisposable_type, "Dispose", loc, TypeSpec.EmptyTypes);
                        }
 
                        return ok;
@@ -4944,51 +4750,29 @@ namespace Mono.CSharp {
 
                protected override void EmitFinallyBody (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
                        if (!TypeManager.IsStruct (expr_type)) {
-                               Label skip = ig.DefineLabel ();
+                               Label skip = ec.DefineLabel ();
                                local_copy.Emit (ec);
-                               ig.Emit (OpCodes.Brfalse, skip);
+                               ec.Emit (OpCodes.Brfalse, skip);
                                local_copy.Emit (ec);
-                               ig.Emit (OpCodes.Callvirt, (MethodInfo) TypeManager.void_dispose_void.MetaInfo);
-                               ig.MarkLabel (skip);
+                               ec.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
+                               ec.MarkLabel (skip);
                                return;
                        }
 
-                       Expression ml = Expression.MemberLookup (RootContext.ToplevelTypes.Compiler,
-                               ec.CurrentType, TypeManager.idisposable_type, expr_type,
-                               "Dispose", Location.Null);
+                       MethodSpec ms = MemberCache.FindMember (expr_type,
+                               MemberFilter.Method ("Dispose", 0, ParametersCompiled.EmptyReadOnlyParameters, TypeManager.void_type),
+                               BindingRestriction.InstanceOnly) as MethodSpec;
 
-                       if (!(ml is MethodGroupExpr)) {
+                       if (ms == null) {
                                local_copy.Emit (ec);
-                               ig.Emit (OpCodes.Box, expr_type);
-                               ig.Emit (OpCodes.Callvirt, (MethodInfo) TypeManager.void_dispose_void.MetaInfo);
-                               return;
-                       }
-
-                       MethodSpec mi = null;
-
-                       foreach (var mk in ((MethodGroupExpr) ml).Methods) {
-                               if (mk.Parameters.IsEmpty) {
-                                       mi = mk;
-                                       break;
-                               }
-                       }
-
-                       if (mi == null) {
-                               ec.Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
+                               ec.Emit (OpCodes.Box, expr_type);
+                               ec.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
                                return;
                        }
 
                        local_copy.AddressOf (ec, AddressOp.Load);
-                       ig.Emit (OpCodes.Call, (MethodInfo) mi.MetaInfo);
-               }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       expr_type = storey.MutateType (expr_type);
-                       local_copy.MutateHoistedGenericType (storey);
-                       Statement.MutateHoistedGenericType (storey);
+                       ec.Emit (OpCodes.Call, ms);
                }
 
                protected override void CloneTo (CloneContext clonectx, Statement t)
@@ -5038,26 +4822,18 @@ namespace Mono.CSharp {
 
                protected override void EmitFinallyBody (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-                       Label skip = ig.DefineLabel ();
+                       Label skip = ec.DefineLabel ();
 
                        bool emit_null_check = !TypeManager.IsValueType (var.Type);
                        if (emit_null_check) {
                                var.Emit (ec);
-                               ig.Emit (OpCodes.Brfalse, skip);
+                               ec.Emit (OpCodes.Brfalse, skip);
                        }
 
                        Invocation.EmitCall (ec, false, var, TypeManager.void_dispose_void, null, loc);
 
                        if (emit_null_check)
-                               ig.MarkLabel (skip);
-               }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       assign.MutateHoistedGenericType (storey);
-                       var.MutateHoistedGenericType (storey);
-                       stmt.MutateHoistedGenericType (storey);
+                               ec.MarkLabel (skip);
                }
 
                public override bool Resolve (BlockContext ec)
@@ -5075,7 +4851,7 @@ namespace Mono.CSharp {
 
                        if (TypeManager.void_dispose_void == null) {
                                TypeManager.void_dispose_void = TypeManager.GetPredefinedMethod (
-                                       TypeManager.idisposable_type, "Dispose", loc, Type.EmptyTypes);
+                                       TypeManager.idisposable_type, "Dispose", loc, TypeSpec.EmptyTypes);
                        }
 
                        return ok;
@@ -5088,14 +4864,13 @@ namespace Mono.CSharp {
                        if (assign == null)
                                return false;
 
-                       if (assign.Type == TypeManager.idisposable_type ||
-                               TypeManager.ImplementsInterface (assign.Type, TypeManager.idisposable_type)) {
+                       if (assign.Type == TypeManager.idisposable_type || assign.Type.ImplementsInterface (TypeManager.idisposable_type)) {
                                return true;
                        }
 
                        Expression e = Convert.ImplicitConversionStandard (ec, assign, TypeManager.idisposable_type, var.Location);
                        if (e == null) {
-                               if (TypeManager.IsDynamicType (assign.Type)) {
+                               if (assign.Type == InternalType.Dynamic) {
                                        e = Convert.ImplicitConversionRequired (ec, assign, TypeManager.idisposable_type, loc);
                                        var = new TemporaryVariable (e.Type, loc);
                                        assign = new SimpleAssign (var, e, loc).ResolveStatement (ec);
@@ -5248,8 +5023,6 @@ namespace Mono.CSharp {
 
                        protected override void DoEmit (EmitContext ec)
                        {
-                               ILGenerator ig = ec.ig;
-
                                copy.EmitAssign (ec, for_each.expr);
 
                                int rank = length_exprs.Length;
@@ -5257,8 +5030,8 @@ namespace Mono.CSharp {
                                Label[] loop = new Label [rank];
 
                                for (int i = 0; i < rank; i++) {
-                                       test [i] = ig.DefineLabel ();
-                                       loop [i] = ig.DefineLabel ();
+                                       test [i] = ec.DefineLabel ();
+                                       loop [i] = ec.DefineLabel ();
 
                                        if (lengths != null)
                                                lengths [i].EmitAssign (ec, length_exprs [i]);
@@ -5268,20 +5041,20 @@ namespace Mono.CSharp {
                                for (int i = 0; i < rank; i++) {
                                        counter [i].EmitAssign (ec, zero);
 
-                                       ig.Emit (OpCodes.Br, test [i]);
-                                       ig.MarkLabel (loop [i]);
+                                       ec.Emit (OpCodes.Br, test [i]);
+                                       ec.MarkLabel (loop [i]);
                                }
 
                                ((IAssignMethod) for_each.variable).EmitAssign (ec, conv, false, false);
 
                                statement.Emit (ec);
 
-                               ig.MarkLabel (ec.LoopBegin);
+                               ec.MarkLabel (ec.LoopBegin);
 
                                for (int i = rank - 1; i >= 0; i--){
                                        counter [i].EmitIncrement (ec);
 
-                                       ig.MarkLabel (test [i]);
+                                       ec.MarkLabel (test [i]);
                                        counter [i].Emit (ec);
 
                                        if (lengths != null)
@@ -5289,25 +5062,10 @@ namespace Mono.CSharp {
                                        else
                                                length_exprs [i].Emit (ec);
 
-                                       ig.Emit (OpCodes.Blt, loop [i]);
+                                       ec.Emit (OpCodes.Blt, loop [i]);
                                }
 
-                               ig.MarkLabel (ec.LoopEnd);
-                       }
-
-                       public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-                       {
-                               for_each.expr.MutateHoistedGenericType (storey);
-
-                               copy.MutateHoistedGenericType (storey);
-                               conv.MutateHoistedGenericType (storey);
-                               statement.MutateHoistedGenericType (storey);
-
-                               for (int i = 0; i < counter.Length; i++) {
-                                       counter [i].MutateHoistedGenericType (storey);
-                                       if (lengths != null)
-                                               lengths [i].MutateHoistedGenericType (storey);
-                               }
+                               ec.MarkLabel (ec.LoopEnd);
                        }
                }
 
@@ -5315,12 +5073,12 @@ namespace Mono.CSharp {
                {
                        class CollectionForeachStatement : Statement
                        {
-                               Type type;
+                               TypeSpec type;
                                Expression variable, current, conv;
                                Statement statement;
                                Assign assign;
 
-                               public CollectionForeachStatement (Type type, Expression variable,
+                               public CollectionForeachStatement (TypeSpec type, Expression variable,
                                                                   Expression current, Statement statement,
                                                                   Location loc)
                                {
@@ -5361,12 +5119,6 @@ namespace Mono.CSharp {
                                        assign.EmitStatement (ec);
                                        statement.Emit (ec);
                                }
-
-                               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-                               {
-                                       assign.MutateHoistedGenericType (storey);
-                                       statement.MutateHoistedGenericType (storey);
-                               }
                        }
 
                        Expression variable, expr;
@@ -5381,7 +5133,7 @@ namespace Mono.CSharp {
                        PropertyExpr get_current;
                        MethodSpec move_next;
                        Expression var_type;
-                       Type enumerator_type;
+                       TypeSpec enumerator_type;
                        bool enumerator_found;
 
                        public CollectionForeach (Expression var_type, Expression var,
@@ -5401,7 +5153,7 @@ namespace Mono.CSharp {
 
                        bool GetEnumeratorFilter (ResolveContext ec, MethodSpec mi)
                        {
-                               Type return_type = mi.ReturnType;
+                               TypeSpec return_type = mi.ReturnType;
 
                                //
                                // Ok, we can access it, now make sure that we can do something
@@ -5409,7 +5161,7 @@ namespace Mono.CSharp {
                                //
 
                                if (return_type == TypeManager.ienumerator_type ||
-                                       TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type)) {
+                                       return_type.ImplementsInterface (TypeManager.ienumerator_type)) {
                                        //
                                        // If it is not an interface, lets try to find the methods ourselves.
                                        // For example, if we have:
@@ -5426,7 +5178,7 @@ namespace Mono.CSharp {
 
                                        if (TypeManager.bool_movenext_void == null) {
                                                TypeManager.bool_movenext_void = TypeManager.GetPredefinedMethod (
-                                                       TypeManager.ienumerator_type, "MoveNext", loc, Type.EmptyTypes);
+                                                       TypeManager.ienumerator_type, "MoveNext", loc, TypeSpec.EmptyTypes);
                                        }
 
                                        if (TypeManager.ienumerator_getcurrent == null) {
@@ -5477,37 +5229,23 @@ namespace Mono.CSharp {
                        //
                        // Retrieves a `public bool MoveNext ()' method from the Type `t'
                        //
-                       bool FetchMoveNext (Type t)
+                       bool FetchMoveNext (TypeSpec t)
                        {
-                               MemberInfo[] move_next_list = TypeManager.MemberLookup (null, null, t,
-                                       MemberTypes.Method,
-                                       BindingFlags.Public | BindingFlags.Instance,
-                                       "MoveNext", null);
-
-                               if (move_next_list == null)
-                                       return false;
+                               move_next = MemberCache.FindMember (t,
+                                       MemberFilter.Method ("MoveNext", 0, ParametersCompiled.EmptyReadOnlyParameters, TypeManager.bool_type),
+                                       BindingRestriction.InstanceOnly) as MethodSpec;
 
-                               foreach (MemberInfo m in move_next_list){
-                                       MethodInfo mi = (MethodInfo) m;
-                               
-                                       if ((TypeManager.GetParameterData (mi).Count == 0) &&
-                                           TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
-                                               move_next = Import.CreateMethod (mi);
-                                               return true;
-                                       }
-                               }
-
-                               return false;
+                               return move_next != null && (move_next.Modifiers & Modifiers.PUBLIC) != 0;
                        }
                
                        //
                        // Retrieves a `public T get_Current ()' method from the Type `t'
                        //
-                       bool FetchGetCurrent (ResolveContext ec, Type t)
+                       bool FetchGetCurrent (ResolveContext ec, TypeSpec t)
                        {
                                PropertyExpr pe = Expression.MemberLookup (ec.Compiler,
-                                       ec.CurrentType, t, "Current", MemberTypes.Property,
-                                       Expression.AllBindingFlags, loc) as PropertyExpr;
+                                       ec.CurrentType, t, "Current", 0, MemberKind.Property,
+                                       BindingRestriction.AccessibleOnly, loc) as PropertyExpr;
                                if (pe == null)
                                        return false;
 
@@ -5526,41 +5264,24 @@ namespace Mono.CSharp {
                                        TypeManager.CSharpName (expr.Type));
                        }
 
-                       bool IsOverride (MethodSpec ms)
+                       bool TryType (ResolveContext ec, TypeSpec t)
                        {
-                               MethodInfo m = (MethodInfo) ms.MetaInfo;
-                               m = (MethodInfo) TypeManager.DropGenericMethodArguments (m);
-
-                               if (!m.IsVirtual || ((m.Attributes & MethodAttributes.NewSlot) != 0))
-                                       return false;
-                               if (m is MethodBuilder)
-                                       return true;
-
-                               MethodInfo base_method = m.GetBaseDefinition ();
-                               return base_method != m;
-                       }
+                               var mg = Expression.MemberLookup (ec.Compiler, ec.CurrentType, null, t, "GetEnumerator", 0,
+                                       MemberKind.Method, BindingRestriction.NoOverrides | BindingRestriction.InstanceOnly, loc) as MethodGroupExpr;
 
-                       bool TryType (ResolveContext ec, Type t)
-                       {
-                               MethodGroupExpr mg = Expression.MemberLookup (ec.Compiler,
-                                       ec.CurrentType, t, "GetEnumerator", MemberTypes.Method,
-                                       Expression.AllBindingFlags, loc) as MethodGroupExpr;
                                if (mg == null)
                                        return false;
 
                                MethodSpec result = null;
                                MethodSpec tmp_move_next = null;
                                PropertyExpr tmp_get_cur = null;
-                               Type tmp_enumerator_type = enumerator_type;
-                               foreach (var mi in mg.Methods) {
+                               TypeSpec tmp_enumerator_type = enumerator_type;
+                               foreach (MethodSpec mi in mg.Methods) {
                                        if (!mi.Parameters.IsEmpty)
                                                continue;
                        
                                        // Check whether GetEnumerator is public
-                                       if ((mi.MetaInfo.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
-                                               continue;
-
-                                       if (IsOverride (mi))
+                                       if ((mi.Modifiers & Modifiers.AccessibilityMask) != Modifiers.PUBLIC)
                                                continue;
 
                                        enumerator_found = true;
@@ -5573,24 +5294,23 @@ namespace Mono.CSharp {
                                                        if (!TypeManager.IsGenericType (mi.ReturnType))
                                                                continue;
 
-                                                       MethodBase mb = TypeManager.DropGenericMethodArguments (mi);
                                                        ec.Report.SymbolRelatedToPreviousError (t);
                                                        ec.Report.Error(1640, loc, "foreach statement cannot operate on variables of type `{0}' " +
-                                                                    "because it contains multiple implementation of `{1}'. Try casting to a specific implementation",
-                                                                    TypeManager.CSharpName (t), TypeManager.CSharpSignature (mb));
+                                                                        "because it contains multiple implementation of `{1}'. Try casting to a specific implementation",
+                                                                        TypeManager.CSharpName (t), TypeManager.generic_ienumerable_type.GetSignatureForError ());
                                                        return false;
                                                }
 
                                                // Always prefer generics enumerators
                                                if (!TypeManager.IsGenericType (mi.ReturnType)) {
-                                                       if (TypeManager.ImplementsInterface (mi.DeclaringType, result.DeclaringType) ||
-                                                           TypeManager.ImplementsInterface (result.DeclaringType, mi.DeclaringType))
+                                                       if (mi.DeclaringType.ImplementsInterface (result.DeclaringType) ||
+                                                               result.DeclaringType.ImplementsInterface (mi.DeclaringType))
                                                                continue;
 
-                                                       ec.Report.SymbolRelatedToPreviousError (result.MetaInfo);
-                                                       ec.Report.SymbolRelatedToPreviousError (mi.MetaInfo);
+                                                       ec.Report.SymbolRelatedToPreviousError (result);
+                                                       ec.Report.SymbolRelatedToPreviousError (mi);
                                                        ec.Report.Warning (278, 2, loc, "`{0}' contains ambiguous implementation of `{1}' pattern. Method `{2}' is ambiguous with method `{3}'",
-                                                                       TypeManager.CSharpName (t), "enumerable", TypeManager.CSharpSignature (result.MetaInfo), TypeManager.CSharpSignature (mi.MetaInfo));
+                                                                       TypeManager.CSharpName (t), "enumerable", result.GetSignatureForError (), mi.GetSignatureForError ());
                                                        return false;
                                                }
                                        }
@@ -5606,8 +5326,7 @@ namespace Mono.CSharp {
                                        move_next = tmp_move_next;
                                        get_current = tmp_get_cur;
                                        enumerator_type = tmp_enumerator_type;
-                                       var mi = new [] { result };
-                                       get_enumerator = new MethodGroupExpr (mi, enumerator_type, loc);
+                                       get_enumerator = new MethodGroupExpr (result, enumerator_type, loc);
 
                                        if (t != expr.Type) {
                                                expr = Convert.ExplicitConversion (
@@ -5625,10 +5344,10 @@ namespace Mono.CSharp {
                                return false;
                        }
 
-                       bool ProbeCollectionType (ResolveContext ec, Type t)
+                       bool ProbeCollectionType (ResolveContext ec, TypeSpec t)
                        {
                                int errors = ec.Report.Errors;
-                               for (Type tt = t; tt != null && tt != TypeManager.object_type;){
+                               for (TypeSpec tt = t; tt != null && tt != TypeManager.object_type;){
                                        if (TryType (ec, tt))
                                                return true;
                                        tt = tt.BaseType;
@@ -5640,10 +5359,14 @@ namespace Mono.CSharp {
                                //
                                // Now try to find the method in the interfaces
                                //
-                               Type [] ifaces = TypeManager.GetInterfaces (t);
-                               foreach (Type i in ifaces){
-                                       if (TryType (ec, i))
-                                               return true;
+                               for (TypeSpec tt = t; tt != null && tt != TypeManager.object_type; ) {
+                                       if (tt.Interfaces != null) {
+                                               foreach (TypeSpec i in tt.Interfaces) {
+                                                       if (TryType (ec, i))
+                                                               return true;
+                                               }
+                                       }
+                                       tt = tt.BaseType;
                                }
 
                                return false;
@@ -5653,7 +5376,7 @@ namespace Mono.CSharp {
                        {
                                enumerator_type = TypeManager.ienumerator_type;
 
-                               bool is_dynamic = TypeManager.IsDynamicType (expr.Type);
+                               bool is_dynamic = expr.Type == InternalType.Dynamic;
                                if (is_dynamic)
                                        expr = Convert.ImplicitConversionRequired (ec, expr, TypeManager.ienumerable_type, loc);
                                
@@ -5666,7 +5389,7 @@ namespace Mono.CSharp {
                                if (ve != null) {
                                        // Infer implicitly typed local variable from foreach enumerable type
                                        var_type = new TypeExpression (
-                                               is_dynamic ? InternalType.Dynamic : get_current.PropertyInfo.PropertyType,
+                                               is_dynamic ? InternalType.Dynamic : get_current.Type,
                                                var_type.Location);
                                }
 
@@ -5684,7 +5407,7 @@ namespace Mono.CSharp {
 
                                Expression move_next_expr;
                                {
-                                       var mi = new [] { move_next };
+                                       var mi = new List<MemberSpec> (1) { move_next };
                                        MethodGroupExpr mg = new MethodGroupExpr (mi, var_type.Type, loc);
                                        mg.InstanceExpression = enumerator;
 
@@ -5699,7 +5422,7 @@ namespace Mono.CSharp {
                                loop = new While (new BooleanExpression (move_next_expr), block, loc);
 
 
-                               bool implements_idisposable = TypeManager.ImplementsInterface (enumerator_type, TypeManager.idisposable_type);
+                               bool implements_idisposable = enumerator_type.ImplementsInterface (TypeManager.idisposable_type);
                                if (implements_idisposable || !enumerator_type.IsSealed) {
                                        wrapper = new DisposableWrapper (this, implements_idisposable);
                                } else {
@@ -5737,11 +5460,6 @@ namespace Mono.CSharp {
                                        parent.EmitLoopInit (ec);
                                        parent.EmitLoopBody (ec);
                                }
-
-                               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-                               {
-                                       throw new NotSupportedException ();
-                               }
                        }
 
                        sealed class DisposableWrapper : ExceptionStatement
@@ -5775,7 +5493,7 @@ namespace Mono.CSharp {
 
                                        if (TypeManager.void_dispose_void == null) {
                                                TypeManager.void_dispose_void = TypeManager.GetPredefinedMethod (
-                                                       TypeManager.idisposable_type, "Dispose", loc, Type.EmptyTypes);
+                                                       TypeManager.idisposable_type, "Dispose", loc, TypeSpec.EmptyTypes);
                                        }
                                        return ok;
                                }
@@ -5794,34 +5512,28 @@ namespace Mono.CSharp {
                                {
                                        Expression instance = parent.enumerator;
                                        if (!TypeManager.IsValueType (parent.enumerator_type)) {
-                                               ILGenerator ig = ec.ig;
 
                                                parent.enumerator.Emit (ec);
 
-                                               Label call_dispose = ig.DefineLabel ();
+                                               Label call_dispose = ec.DefineLabel ();
 
                                                if (!implements_idisposable) {
-                                                       ec.ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
+                                                       ec.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
                                                        LocalTemporary temp = new LocalTemporary (TypeManager.idisposable_type);
                                                        temp.Store (ec);
                                                        temp.Emit (ec);
                                                        instance = temp;
                                                }
                                                
-                                               ig.Emit (OpCodes.Brtrue_S, call_dispose);
+                                               ec.Emit (OpCodes.Brtrue_S, call_dispose);
 
                                                // using 'endfinally' to empty the evaluation stack
-                                               ig.Emit (OpCodes.Endfinally);
-                                               ig.MarkLabel (call_dispose);
+                                               ec.Emit (OpCodes.Endfinally);
+                                               ec.MarkLabel (call_dispose);
                                        }
 
                                        Invocation.EmitCall (ec, false, instance, TypeManager.void_dispose_void, null, loc);
                                }
-
-                               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-                               {
-                                       throw new NotSupportedException ();
-                               }
                        }
 
                        bool ResolveLoop (BlockContext ec)
@@ -5838,13 +5550,6 @@ namespace Mono.CSharp {
                        {
                                loop.Emit (ec);
                        }
-
-                       public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-                       {
-                               enumerator_type = storey.MutateType (enumerator_type);
-                               init.MutateHoistedGenericType (storey);
-                               loop.MutateHoistedGenericType (storey);
-                       }
                }
 
                Expression type;
@@ -5879,8 +5584,8 @@ namespace Mono.CSharp {
 
                        if (expr.Type == TypeManager.string_type) {
                                statement = new ArrayForeach (this, 1);
-                       } else if (expr.Type.IsArray) {
-                               statement = new ArrayForeach (this, expr.Type.GetArrayRank ());
+                       } else if (expr.Type is ArrayContainer) {
+                               statement = new ArrayForeach (this, ((ArrayContainer) expr.Type).Rank);
                        } else {
                                if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethodExpression) {
                                        ec.Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
@@ -5896,11 +5601,9 @@ namespace Mono.CSharp {
 
                protected override void DoEmit (EmitContext ec)
                {
-                       ILGenerator ig = ec.ig;
-
                        Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
-                       ec.LoopBegin = ig.DefineLabel ();
-                       ec.LoopEnd = ig.DefineLabel ();
+                       ec.LoopBegin = ec.DefineLabel ();
+                       ec.LoopEnd = ec.DefineLabel ();
 
                        statement.Emit (ec);
 
@@ -5917,10 +5620,5 @@ namespace Mono.CSharp {
                        target.expr = expr.Clone (clonectx);
                        target.statement = statement.Clone (clonectx);
                }
-
-               public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
-               {
-                       statement.MutateHoistedGenericType (storey);
-               }
        }
 }
index 8cca4a54b9cc289ce859f3cf9035be9749adc697..8fcb5bf6081b058042eb984fdb684167c9412570 100644 (file)
@@ -20,7 +20,7 @@ using System.Collections.Generic;
 
 namespace Mono.CSharp {
 
-       class ReferenceEquality<T> : IEqualityComparer<T> where T : class
+       sealed class ReferenceEquality<T> : IEqualityComparer<T> where T : class
        {
                public static readonly IEqualityComparer<T> Default = new ReferenceEquality<T> ();
 
@@ -39,7 +39,7 @@ namespace Mono.CSharp {
                }
        }
 
-       class Tuple<T1, T2>
+       class Tuple<T1, T2> : IEquatable<Tuple<T1, T2>>
        {
                public Tuple (T1 item1, T2 item2)
                {
@@ -49,6 +49,29 @@ namespace Mono.CSharp {
 
                public T1 Item1 { get; private set; }
                public T2 Item2 { get; private set; }
+
+               public override int GetHashCode ()
+               {
+                       return Item1.GetHashCode () ^ Item2.GetHashCode ();
+               }
+
+               #region IEquatable<Tuple<T1,T2>> Members
+
+               public bool Equals (Tuple<T1, T2> other)
+               {
+                       return EqualityComparer<T1>.Default.Equals (Item1, other.Item1) &&
+                               EqualityComparer<T2>.Default.Equals (Item2, other.Item2);
+               }
+
+               #endregion
+       }
+
+       static class Tuple
+       {
+               public static Tuple<T1, T2> Create<T1, T2> (T1 item1, T2 item2)
+               {
+                       return new Tuple<T1, T2> (item1, item2);
+               }
        }
 
        public class Accessors {
@@ -254,489 +277,6 @@ namespace Mono.CSharp {
                }
        }
 
-       class PartialMethodDefinitionInfo : MethodInfo
-       {
-               MethodOrOperator mc;
-               MethodAttributes attrs;
-
-               public PartialMethodDefinitionInfo (MethodOrOperator mc)
-               {
-                       this.mc = mc;
-                       if ((mc.ModFlags & Modifiers.STATIC) != 0)
-                               attrs = MethodAttributes.Static;
-               }
-
-               public override MethodInfo GetBaseDefinition ()
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override ICustomAttributeProvider ReturnTypeCustomAttributes
-               {
-                       get { throw new NotImplementedException (); }
-               }
-
-               public override MethodAttributes Attributes
-               {
-                       get { return attrs; }
-               }
-
-               public override MethodImplAttributes GetMethodImplementationFlags ()
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override ParameterInfo [] GetParameters ()
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override object Invoke (object obj, BindingFlags invokeAttr, Binder binder, object [] parameters, CultureInfo culture)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override RuntimeMethodHandle MethodHandle
-               {
-                       get { throw new NotImplementedException (); }
-               }
-
-               public override Type DeclaringType
-               {
-                       get { return mc.Parent.TypeBuilder; }
-               }
-
-               public override object [] GetCustomAttributes (Type attributeType, bool inherit)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override object [] GetCustomAttributes (bool inherit)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override Type ReturnType {
-                       get {
-                               return mc.MemberType;
-                       }
-               }
-
-               public override bool IsDefined (Type attributeType, bool inherit)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override string Name
-               {
-                       get { return mc.Name; }
-               }
-
-               public override Type ReflectedType
-               {
-                       get { throw new NotImplementedException (); }
-               }
-       }
-
-#if NET_4_0 || MS_COMPATIBLE
-       [System.Diagnostics.DebuggerDisplay ("Dynamic type")]
-#endif
-       class DynamicType : Type
-       {
-               public override Assembly Assembly {
-                       get { return CodeGen.Assembly.Builder; }
-               }
-
-               public override string AssemblyQualifiedName {
-                       get { throw new NotImplementedException (); }
-               }
-
-               public override Type BaseType {
-                       get { return null; }
-               }
-
-               public override string FullName {
-                       get { return UnderlyingSystemType.FullName; }
-               }
-
-               public override Guid GUID {
-                       get { throw new NotImplementedException (); }
-               }
-
-               protected override TypeAttributes GetAttributeFlagsImpl ()
-               {
-                       return UnderlyingSystemType.Attributes;
-               }
-
-               protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override Type GetElementType ()
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override EventInfo GetEvent (string name, BindingFlags bindingAttr)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override EventInfo[] GetEvents (BindingFlags bindingAttr)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override FieldInfo GetField (string name, BindingFlags bindingAttr)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override FieldInfo[] GetFields (BindingFlags bindingAttr)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override Type GetInterface (string name, bool ignoreCase)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override Type[] GetInterfaces ()
-               {
-                       return Type.EmptyTypes;
-               }
-
-               public override MemberInfo[] GetMembers (BindingFlags bindingAttr)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override MethodInfo[] GetMethods (BindingFlags bindingAttr)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override Type GetNestedType (string name, BindingFlags bindingAttr)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override Type[] GetNestedTypes (BindingFlags bindingAttr)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override PropertyInfo[] GetProperties (BindingFlags bindingAttr)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               protected override bool HasElementTypeImpl ()
-               {
-                       return false;
-               }
-
-               public override object InvokeMember (string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               protected override bool IsArrayImpl ()
-               {
-                       return false;
-               }
-
-               protected override bool IsByRefImpl ()
-               {
-                       return false;
-               }
-
-               protected override bool IsCOMObjectImpl ()
-               {
-                       return false;
-               }
-
-               protected override bool IsPointerImpl ()
-               {
-                       return false;
-               }
-
-               protected override bool IsPrimitiveImpl ()
-               {
-                       return false;
-               }
-
-               public override Module Module {
-                       get { return UnderlyingSystemType.Module; }
-               }
-
-               public override string Namespace {
-                       get { return UnderlyingSystemType.Namespace; }
-               }
-
-               public override Type UnderlyingSystemType {
-                       get { return TypeManager.object_type; }
-               }
-
-               public override object[] GetCustomAttributes (Type attributeType, bool inherit)
-               {
-                       return new object [0];
-               }
-
-               public override object[] GetCustomAttributes (bool inherit)
-               {
-                       return new object [0];
-               }
-
-               public override bool IsDefined (Type attributeType, bool inherit)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override string Name {
-                       get { return UnderlyingSystemType.Name; }
-               }
-
-               public override string ToString ()
-               {
-                       return UnderlyingSystemType.ToString ();
-               }
-
-               public override RuntimeTypeHandle TypeHandle {
-                       get { return UnderlyingSystemType.TypeHandle; }
-               }
-
-               public override Type MakeByRefType ()
-               {
-                       // TODO: Wrong, hides dynamic type
-                       return UnderlyingSystemType.MakeByRefType ();
-               }
-       }
-
-#if NET_4_0 || MS_COMPATIBLE
-       [System.Diagnostics.DebuggerDisplay ("Dynamic array type")]
-#endif
-       class DynamicArrayType : Type
-       {
-               readonly int rank;
-               Type reflection_type;
-
-               public DynamicArrayType (int rank)
-               {
-                       this.rank = rank;
-               }
-
-               public override Assembly Assembly {
-                       get { return UnderlyingSystemType.Assembly; }
-               }
-
-               public override string AssemblyQualifiedName {
-                       get { throw new NotImplementedException (); }
-               }
-
-               public override Type BaseType {
-                       get { return TypeManager.array_type; }
-               }
-
-               public override string FullName {
-                       get { return UnderlyingSystemType.FullName; }
-               }
-
-               public override Guid GUID {
-                       get { throw new NotImplementedException (); }
-               }
-
-               protected override TypeAttributes GetAttributeFlagsImpl ()
-               {
-                       return UnderlyingSystemType.Attributes;
-               }
-
-               public override int GetArrayRank ()
-               {
-                       return rank;
-               }
-
-               protected override ConstructorInfo GetConstructorImpl (BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override ConstructorInfo[] GetConstructors (BindingFlags bindingAttr)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override Type GetElementType ()
-               {
-                       return InternalType.Dynamic;
-               }
-
-               public override EventInfo GetEvent (string name, BindingFlags bindingAttr)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override EventInfo[] GetEvents (BindingFlags bindingAttr)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override FieldInfo GetField (string name, BindingFlags bindingAttr)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override FieldInfo[] GetFields (BindingFlags bindingAttr)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override Type GetInterface (string name, bool ignoreCase)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override Type[] GetInterfaces ()
-               {
-                       return Type.EmptyTypes;
-               }
-
-               public override MemberInfo[] GetMembers (BindingFlags bindingAttr)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               protected override MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override MethodInfo[] GetMethods (BindingFlags bindingAttr)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override Type GetNestedType (string name, BindingFlags bindingAttr)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override Type[] GetNestedTypes (BindingFlags bindingAttr)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override PropertyInfo[] GetProperties (BindingFlags bindingAttr)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               protected override PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               protected override bool HasElementTypeImpl ()
-               {
-                       return true;
-               }
-
-               public override object InvokeMember (string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               protected override bool IsArrayImpl ()
-               {
-                       return true;
-               }
-
-               protected override bool IsByRefImpl ()
-               {
-                       return false;
-               }
-
-               protected override bool IsCOMObjectImpl ()
-               {
-                       return false;
-               }
-
-               protected override bool IsPointerImpl ()
-               {
-                       return false;
-               }
-
-               protected override bool IsPrimitiveImpl ()
-               {
-                       return false;
-               }
-
-               public override Module Module {
-                       get { return UnderlyingSystemType.Module; }
-               }
-
-               public override string Namespace {
-                       get { return UnderlyingSystemType.Namespace; }
-               }
-
-               public override Type UnderlyingSystemType {
-                       get {
-                               if (reflection_type == null) {
-                                       reflection_type = rank == 1 ?
-                                               TypeManager.object_type.MakeArrayType () :
-                                               TypeManager.object_type.MakeArrayType (rank);
-                               }
-
-                               return reflection_type;
-                       }
-               }
-
-               public override object[] GetCustomAttributes (Type attributeType, bool inherit)
-               {
-                       return new object [0];
-               }
-
-               public override object[] GetCustomAttributes (bool inherit)
-               {
-                       return new object [0];
-               }
-
-               public override bool IsDefined (Type attributeType, bool inherit)
-               {
-                       throw new NotImplementedException ();
-               }
-
-               public override string Name {
-                       get { return UnderlyingSystemType.Name; }
-               }
-
-               public override string ToString ()
-               {
-                       return UnderlyingSystemType.ToString ();
-               }
-
-               public override RuntimeTypeHandle TypeHandle {
-                       get { return UnderlyingSystemType.TypeHandle; }
-               }
-       }
-
        public class UnixUtils {
                [System.Runtime.InteropServices.DllImport ("libc", EntryPoint="isatty")]
                extern static int _isatty (int fd);
index acdaff64e7c6b286082178617bebf8183885ffd9..5159f73d0bfa97257b8ddbb4a305a6a7123db94b 100644 (file)
@@ -181,50 +181,50 @@ namespace Mono.CSharp {
                                symwriter.DefineCapturedScope (scope_id, id, captured_name);
                }
 
-               public static void OpenCompilerGeneratedBlock (ILGenerator ig)
+               public static void OpenCompilerGeneratedBlock (EmitContext ec)
                {
                        if (symwriter != null) {
-                               int offset = symwriter.GetILOffset (ig);
+                               int offset = symwriter.GetILOffset (ec.ig);
                                symwriter.OpenCompilerGeneratedBlock (offset);
                        }
                }
 
-               public static void CloseCompilerGeneratedBlock (ILGenerator ig)
+               public static void CloseCompilerGeneratedBlock (EmitContext ec)
                {
                        if (symwriter != null) {
-                               int offset = symwriter.GetILOffset (ig);
+                               int offset = symwriter.GetILOffset (ec.ig);
                                symwriter.CloseCompilerGeneratedBlock (offset);
                        }
                }
 
-               public static void StartIteratorBody (ILGenerator ig)
+               public static void StartIteratorBody (EmitContext ec)
                {
                        if (symwriter != null) {
-                               int offset = symwriter.GetILOffset (ig);
+                               int offset = symwriter.GetILOffset (ec.ig);
                                symwriter.StartIteratorBody (offset);
                        }
                }
 
-               public static void EndIteratorBody (ILGenerator ig)
+               public static void EndIteratorBody (EmitContext ec)
                {
                        if (symwriter != null) {
-                               int offset = symwriter.GetILOffset (ig);
+                               int offset = symwriter.GetILOffset (ec.ig);
                                symwriter.EndIteratorBody (offset);
                        }
                }
 
-               public static void StartIteratorDispatcher (ILGenerator ig)
+               public static void StartIteratorDispatcher (EmitContext ec)
                {
                        if (symwriter != null) {
-                               int offset = symwriter.GetILOffset (ig);
+                               int offset = symwriter.GetILOffset (ec.ig);
                                symwriter.StartIteratorDispatcher (offset);
                        }
                }
 
-               public static void EndIteratorDispatcher (ILGenerator ig)
+               public static void EndIteratorDispatcher (EmitContext ec)
                {
                        if (symwriter != null) {
-                               int offset = symwriter.GetILOffset (ig);
+                               int offset = symwriter.GetILOffset (ec.ig);
                                symwriter.EndIteratorDispatcher (offset);
                        }
                }
index ddd960106782ca8df1a7426ae02332fdd0b4f422..a41f4d742e095353d0fe94942cece224fde4cf67 100644 (file)
 // Copyright 2003-2008 Novell, Inc.
 //
 
-//
-// We will eventually remove the SIMPLE_SPEEDUP, and should never change 
-// the behavior of the compilation.  This can be removed if we rework
-// the code to get a list of namespaces available.
-//
-#define SIMPLE_SPEEDUP
-
 using System;
 using System.IO;
 using System.Globalization;
@@ -27,6 +20,7 @@ using System.Reflection.Emit;
 using System.Text;
 using System.Runtime.CompilerServices;
 using System.Diagnostics;
+using System.Linq;
 
 namespace Mono.CSharp {
 
@@ -34,74 +28,75 @@ namespace Mono.CSharp {
        //
        // A list of core types that the compiler requires or uses
        //
-       static public Type object_type;
-       static public Type value_type;
-       static public Type string_type;
-       static public Type int32_type;
-       static public Type uint32_type;
-       static public Type int64_type;
-       static public Type uint64_type;
-       static public Type float_type;
-       static public Type double_type;
-       static public Type char_type;
-       static public Type short_type;
-       static public Type decimal_type;
-       static public Type bool_type;
-       static public Type sbyte_type;
-       static public Type byte_type;
-       static public Type ushort_type;
-       static public Type enum_type;
-       static public Type delegate_type;
-       static public Type multicast_delegate_type;
-       static public Type void_type;
-       static public Type null_type;
-       static public Type array_type;
-       static public Type runtime_handle_type;
-       static public Type type_type;
-       static public Type ienumerator_type;
-       static public Type ienumerable_type;
-       static public Type idisposable_type;
-       static public Type iasyncresult_type;
-       static public Type asynccallback_type;
-       static public Type intptr_type;
-       static public Type uintptr_type;
-       static public Type runtime_field_handle_type;
-       static public Type runtime_argument_handle_type;
-       static public Type attribute_type;
-       static public Type void_ptr_type;
-       static public Type exception_type;
-
-       static public Type typed_reference_type;
-       static public Type arg_iterator_type;
-       static public Type mbr_type;
-       public static Type runtime_helpers_type;
+       static public PredefinedTypeSpec object_type;
+       static public PredefinedTypeSpec value_type;
+       static public PredefinedTypeSpec string_type;
+       static public PredefinedTypeSpec int32_type;
+       static public PredefinedTypeSpec uint32_type;
+       static public PredefinedTypeSpec int64_type;
+       static public PredefinedTypeSpec uint64_type;
+       static public PredefinedTypeSpec float_type;
+       static public PredefinedTypeSpec double_type;
+       static public PredefinedTypeSpec char_type;
+       static public PredefinedTypeSpec short_type;
+       static public PredefinedTypeSpec decimal_type;
+       static public PredefinedTypeSpec bool_type;
+       static public PredefinedTypeSpec sbyte_type;
+       static public PredefinedTypeSpec byte_type;
+       static public PredefinedTypeSpec ushort_type;
+       static public PredefinedTypeSpec enum_type;
+       static public PredefinedTypeSpec delegate_type;
+       static public PredefinedTypeSpec multicast_delegate_type;
+       static public PredefinedTypeSpec void_type;
+       static public PredefinedTypeSpec array_type;
+       static public PredefinedTypeSpec runtime_handle_type;
+       static public PredefinedTypeSpec type_type;
+       static public PredefinedTypeSpec ienumerator_type;
+       static public PredefinedTypeSpec ienumerable_type;
+       static public PredefinedTypeSpec idisposable_type;
+       static public PredefinedTypeSpec intptr_type;
+       static public PredefinedTypeSpec uintptr_type;
+       static public PredefinedTypeSpec runtime_field_handle_type;
+       static public PredefinedTypeSpec attribute_type;
+       static public PredefinedTypeSpec exception_type;
+
+
+       static public TypeSpec null_type;
+       static public TypeSpec typed_reference_type;
+       static public TypeSpec arg_iterator_type;
+       static public TypeSpec mbr_type;
+       public static TypeSpec runtime_helpers_type;
+       static public TypeSpec iasyncresult_type;
+       static public TypeSpec asynccallback_type;
+       static public TypeSpec runtime_argument_handle_type;
+       static public TypeSpec void_ptr_type;
 
        // 
        // C# 2.0
        //
-       static internal Type isvolatile_type;
-       static public Type generic_ilist_type;
-       static public Type generic_icollection_type;
-       static public Type generic_ienumerator_type;
-       static public Type generic_ienumerable_type;
-       static public Type generic_nullable_type;
+       static internal TypeSpec isvolatile_type;
+       static public TypeSpec generic_ilist_type;
+       static public TypeSpec generic_icollection_type;
+       static public TypeSpec generic_ienumerator_type;
+       static public TypeSpec generic_ienumerable_type;
+       static public TypeSpec generic_nullable_type;
 
        //
        // C# 3.0
        //
-       static internal Type expression_type;
-       public static Type parameter_expression_type;
-       public static Type fieldinfo_type;
-       public static Type methodinfo_type;
-       public static Type ctorinfo_type;
+       static internal TypeSpec expression_type;
+       public static TypeSpec parameter_expression_type;
+       public static TypeSpec fieldinfo_type;
+       public static TypeSpec methodinfo_type;
+       public static TypeSpec ctorinfo_type;
 
        //
        // C# 4.0
        //
-       public static Type call_site_type;
-       public static Type generic_call_site_type;
+       public static TypeSpec call_site_type;
+       public static TypeSpec generic_call_site_type;
        public static TypeExpr binder_type;
-       public static Type binder_flags;
+       public static TypeSpec binder_flags;
 
        // 
        // Expressions representing the internal types.  Used during declaration
@@ -116,14 +111,13 @@ namespace Mono.CSharp {
        static public TypeExpr system_int64_expr, system_uint64_expr;
        static public TypeExpr system_char_expr, system_void_expr;
        static public TypeExpr system_valuetype_expr;
-       static public TypeExpr system_intptr_expr;
        public static TypeExpr expression_type_expr;
 
 
        //
        // These methods are called by code generated by the compiler
        //
-       static public FieldInfo string_empty;
+       static public FieldSpec string_empty;
        static public MethodSpec system_type_get_type_from_handle;
        static public MethodSpec bool_movenext_void;
        static public MethodSpec void_dispose_void;
@@ -144,93 +138,35 @@ namespace Mono.CSharp {
        //
        // The constructors.
        //
-       static public ConstructorInfo void_decimal_ctor_five_args;
-       static public ConstructorInfo void_decimal_ctor_int_arg;
-       public static ConstructorInfo void_decimal_ctor_long_arg;
-
-       static Dictionary<TypeBuilder, DeclSpace> builder_to_declspace;
-
-       static Dictionary<Type, MemberCache> builder_to_member_cache;
-
-       // <remarks>
-       //   Tracks the interfaces implemented by typebuilders.  We only
-       //   enter those who do implement or or more interfaces
-       // </remarks>
-       static Dictionary<Type, Type[]> builder_to_ifaces;
-
-       // <remarks>
-       //   Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
-       // <remarks>
-       static Dictionary<MemberInfo, AParametersCollection> method_params;
-
-       // <remarks>
-       //  A hash table from override methods to their base virtual method.
-       // <remarks>
-       static Dictionary<MethodBase, MethodBase> method_overrides;
-
-       // <remarks>
-       //  Keeps track of methods
-       // </remarks>
-
-       static Dictionary<MethodBase, IMethodData> builder_to_method;
-
-       // <remarks>
-       //  Contains all public types from referenced assemblies.
-       //  This member is used only if CLS Compliance verification is required.
-       // </remarks>
-       public static Dictionary<string, object> AllClsTopLevelTypes;
-
-       static Dictionary<FieldInfo, FieldBase> fieldbuilders_to_fields;
-       static Dictionary<PropertyInfo, PropertyBase> propertybuilder_to_property;
-       static Dictionary<FieldInfo, ConstSpec> fields;
-       static Dictionary<EventInfo, EventSpec> events;
-       static Dictionary<Assembly, bool> assembly_internals_vis_attrs;
-       static Dictionary<GenericTypeParameterBuilder, TypeParameter> builder_to_type_param;
-       static Dictionary<Type, Type[]> iface_cache;
+       static public MethodSpec void_decimal_ctor_five_args;
+       static public MethodSpec void_decimal_ctor_int_arg;
+       public static MethodSpec void_decimal_ctor_long_arg;
 
-       public static void CleanUp ()
-       {
-               // Lets get everything clean so that we can collect before generating code
-               builder_to_declspace = null;
-               builder_to_member_cache = null;
-               builder_to_ifaces = null;
-               builder_to_type_param = null;
-               method_params = null;
-               builder_to_method = null;
-               iface_cache = null;
-               
-               fields = null;
-               events = null;
-               type_hash = null;
-               propertybuilder_to_property = null;
-
-               TypeHandle.CleanUp ();
-       }
+       static Dictionary<Assembly, bool> assembly_internals_vis_attrs;
 
        //
        // These are expressions that represent some of the internal data types, used
        // elsewhere
        //
-       static void InitExpressionTypes ()
-       {
-               system_object_expr  = new TypeLookupExpression ("System", "Object");
-               system_string_expr  = new TypeLookupExpression ("System", "String");
-               system_boolean_expr = new TypeLookupExpression ("System", "Boolean");
-               system_decimal_expr = new TypeLookupExpression ("System", "Decimal");
-               system_single_expr  = new TypeLookupExpression ("System", "Single");
-               system_double_expr  = new TypeLookupExpression ("System", "Double");
-               system_sbyte_expr   = new TypeLookupExpression ("System", "SByte");
-               system_byte_expr    = new TypeLookupExpression ("System", "Byte");
-               system_int16_expr   = new TypeLookupExpression ("System", "Int16");
-               system_uint16_expr  = new TypeLookupExpression ("System", "UInt16");
-               system_int32_expr   = new TypeLookupExpression ("System", "Int32");
-               system_uint32_expr  = new TypeLookupExpression ("System", "UInt32");
-               system_int64_expr   = new TypeLookupExpression ("System", "Int64");
-               system_uint64_expr  = new TypeLookupExpression ("System", "UInt64");
-               system_char_expr    = new TypeLookupExpression ("System", "Char");
-               system_void_expr    = new TypeLookupExpression ("System", "Void");
-               system_valuetype_expr  = new TypeLookupExpression ("System", "ValueType");
-               system_intptr_expr  = new TypeLookupExpression ("System", "IntPtr");
+       public static void InitExpressionTypes ()
+       {
+               system_object_expr  = new TypeLookupExpression (object_type);
+               system_string_expr  = new TypeLookupExpression (string_type);
+               system_boolean_expr = new TypeLookupExpression (bool_type);
+               system_decimal_expr = new TypeLookupExpression (decimal_type);
+               system_single_expr  = new TypeLookupExpression (float_type);
+               system_double_expr  = new TypeLookupExpression (double_type);
+               system_sbyte_expr   = new TypeLookupExpression (sbyte_type);
+               system_byte_expr    = new TypeLookupExpression (byte_type);
+               system_int16_expr   = new TypeLookupExpression (short_type);
+               system_uint16_expr  = new TypeLookupExpression (ushort_type);
+               system_int32_expr   = new TypeLookupExpression (int32_type);
+               system_uint32_expr  = new TypeLookupExpression (uint32_type);
+               system_int64_expr   = new TypeLookupExpression (int64_type);
+               system_uint64_expr  = new TypeLookupExpression (uint64_type);
+               system_char_expr    = new TypeLookupExpression (char_type);
+               system_void_expr    = new TypeLookupExpression (void_type);
+               system_valuetype_expr  = new TypeLookupExpression (value_type);
        }
 
        static TypeManager ()
@@ -240,28 +176,11 @@ namespace Mono.CSharp {
 
        static public void Reset ()
        {
-               object_type = null;
-
-               InitExpressionTypes ();
-               
-               builder_to_declspace = new Dictionary<TypeBuilder, DeclSpace> (ReferenceEquality<TypeBuilder>.Default);
-               builder_to_member_cache = new Dictionary<Type, MemberCache> (ReferenceEquality<Type>.Default);
-               builder_to_method = new Dictionary<MethodBase, IMethodData> (ReferenceEquality<MethodBase>.Default);
-               builder_to_type_param = new Dictionary<GenericTypeParameterBuilder, TypeParameter> (ReferenceEquality<GenericTypeParameterBuilder>.Default);
-               method_params = new Dictionary<MemberInfo, AParametersCollection> (ReferenceEquality<MemberInfo>.Default);
-               method_overrides = new Dictionary<MethodBase, MethodBase> (ReferenceEquality<MethodBase>.Default);
-               builder_to_ifaces = new Dictionary<Type, Type[]> (ReferenceEquality<Type>.Default);
-
-               fieldbuilders_to_fields = new Dictionary<FieldInfo, FieldBase> (ReferenceEquality<FieldInfo>.Default);
-               propertybuilder_to_property = new Dictionary<PropertyInfo, PropertyBase> (ReferenceEquality<PropertyInfo>.Default);
-               fields = new Dictionary<FieldInfo, ConstSpec> (ReferenceEquality<FieldInfo>.Default);
+//             object_type = null;
+       
                type_hash = new DoubleHash ();
                assembly_internals_vis_attrs = new Dictionary<Assembly, bool> ();
-               iface_cache = new Dictionary<Type, Type[]> (ReferenceEquality<Type>.Default);
                
-               closure = new Closure ();
-               FilterWithClosure_delegate = new MemberFilter (closure.Filter);
-
                // TODO: I am really bored by all this static stuff
                system_type_get_type_from_handle =
                bool_movenext_void =
@@ -285,7 +204,7 @@ namespace Mono.CSharp {
                void_decimal_ctor_int_arg =
                void_decimal_ctor_long_arg = null;
 
-               isvolatile_type = null;
+               string_empty = null;
 
                call_site_type =
                generic_call_site_type =
@@ -293,112 +212,14 @@ namespace Mono.CSharp {
 
                binder_type = null;
 
-               // to uncover regressions
-               AllClsTopLevelTypes = null;
-       }
-
-       public static void AddUserType (DeclSpace ds)
-       {
-               builder_to_declspace.Add (ds.TypeBuilder, ds);
-       }
-
-       //
-       // This entry point is used by types that we define under the covers
-       // 
-       public static void RegisterBuilder (Type tb, Type [] ifaces)
-       {
-               if (ifaces != null)
-                       builder_to_ifaces [tb] = ifaces;
-       }       
-
-       public static void AddMethod (MethodBase builder, IMethodData method)
-       {
-               builder_to_method.Add (builder, method);
-               method_params.Add (builder, method.ParameterInfo);
-       }
-
-       public static IMethodData GetMethod (MethodBase builder)
-       {
-               IMethodData md;
-               if (builder_to_method.TryGetValue (builder, out md))
-                       return md;
-               return null;
-       }
-
-       /// <summary>
-       ///   Returns the DeclSpace whose Type is `t' or null if there is no
-       ///   DeclSpace for `t' (ie, the Type comes from a library)
-       /// </summary>
-       public static DeclSpace LookupDeclSpace (Type t)
-       {
-               DeclSpace ds;
-               var tb = t as TypeBuilder;
-               if (tb != null && builder_to_declspace.TryGetValue (tb, out ds))
-                       return ds;
-
-               return null;
-       }
-
-       /// <summary>
-       ///   Returns the TypeContainer whose Type is `t' or null if there is no
-       ///   TypeContainer for `t' (ie, the Type comes from a library)
-       /// </summary>
-       public static TypeContainer LookupTypeContainer (Type t)
-       {
-               return LookupDeclSpace (t) as TypeContainer;
-       }
-
-       public static MemberCache LookupMemberCache (Type t)
-       {
-               if (IsBeingCompiled (t)) {
-                       DeclSpace container = LookupDeclSpace (t);
-                       if (container != null)
-                               return container.MemberCache;
-               }
-
-               if (t is GenericTypeParameterBuilder) {
-                       TypeParameter container;
-                       if (builder_to_type_param.TryGetValue ((GenericTypeParameterBuilder) t, out container))
-                               return container.MemberCache;
-               }
-
-               return TypeHandle.GetMemberCache (t);
-       }
-
-       public static MemberCache LookupBaseInterfacesCache (Type t)
-       {
-               Type [] ifaces = GetInterfaces (t);
-
-               if (ifaces != null && ifaces.Length == 1)
-                       return LookupMemberCache (ifaces [0]);
-
-               // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
-               MemberCache cache;
-               if (builder_to_member_cache.TryGetValue (t, out cache))
-                       return cache;
-
-               cache = new MemberCache (ifaces);
-               builder_to_member_cache.Add (t, cache);
-               return cache;
-       }
-
-       public static TypeContainer LookupInterface (Type t)
-       {
-               TypeContainer tc = LookupTypeContainer (t);
-               if ((tc == null) || (tc.Kind != MemberKind.Interface))
-                       return null;
-
-               return tc;
-       }
+               typed_reference_type = arg_iterator_type = mbr_type =
+               runtime_helpers_type = iasyncresult_type = asynccallback_type =
+               runtime_argument_handle_type = void_ptr_type = isvolatile_type =
+               generic_ilist_type = generic_icollection_type = generic_ienumerator_type =
+               generic_ienumerable_type = generic_nullable_type = expression_type =
+               parameter_expression_type = fieldinfo_type = methodinfo_type = ctorinfo_type = null;
 
-       public static Delegate LookupDelegate (Type t)
-       {
-               return LookupDeclSpace (t) as Delegate;
-       }
-
-       public static Class LookupClass (Type t)
-       {
-               return LookupDeclSpace (t) as Class;
+               expression_type_expr = null;
        }
 
        //
@@ -416,466 +237,120 @@ namespace Mono.CSharp {
        //
        // Gets the reference to T version of the Type (T&)
        //
-       public static Type GetReferenceType (Type t)
+       public static Type GetReferenceType (TypeSpec t)
        {
-               return t.MakeByRefType ();
+               return t.GetMetaInfo ().MakeByRefType ();
        }
 
-       //
-       // Gets the pointer to T version of the Type  (T*)
-       //
-       public static Type GetPointerType (Type t)
-       {
-               return GetConstructedType (t, "*");
-       }
-
-       public static Type GetConstructedType (Type t, string dim)
+       public static TypeSpec GetConstructedType (TypeSpec t, string dim)
        {
                object ret = null;
                if (type_hash.Lookup (t, dim, out ret))
-                       return (Type) ret;
-
-               if (IsDynamicType (t)) {
-                       ret = new DynamicArrayType (dim.Length - 1);
-                       type_hash.Insert (t, dim, ret);
-                       return (Type) ret;
-               }
-
-               ret = t.Module.GetType (t.ToString () + dim);
-               if (ret != null) {
-                       type_hash.Insert (t, dim, ret);
-                       return (Type) ret;
-               }
-
-               if (dim == "&") {
-                       ret = GetReferenceType (t);
-                       type_hash.Insert (t, dim, ret);
-                       return (Type) ret;
-               }
-
-               if (t.IsGenericParameter || t.IsGenericType) {
-                       int pos = 0;
-                       Type result = t;
-                       while ((pos < dim.Length) && (dim [pos] == '[')) {
-                               pos++;
-
-                               if (dim [pos] == ']') {
-                                       result = result.MakeArrayType ();
-                                       pos++;
-
-                                       if (pos < dim.Length)
-                                               continue;
-
-                                       type_hash.Insert (t, dim, result);
-                                       return result;
-                               }
-
-                               int rank = 0;
-                               while (dim [pos] == ',') {
-                                       pos++; rank++;
-                               }
-
-                               if ((dim [pos] != ']') || (pos != dim.Length-1))
-                                       break;
-
-                               result = result.MakeArrayType (rank + 1);
-                               type_hash.Insert (t, dim, result);
-                               return result;
+                       return (TypeSpec) ret;
+
+               TypeSpec ds;
+               if (dim.Length == 1) {
+                       if (dim[0] == '*') {
+                               ds = PointerContainer.MakeType (t);
+                       } else if (dim[0] == '&') {
+                               ds = ReferenceContainer.MakeType (t);
+                       } else {
+                               throw new NotImplementedException ("net");
                        }
-               }
-
-               type_hash.Insert (t, dim, null);
-               return null;
-       }
+               } else if (dim.Length == 2) {   // optimizes common "[]"
+                       ds = ArrayContainer.MakeType (t);
+               } else {
+                       int rank = dim.IndexOf (']');
+                       if (rank + 1 != dim.Length)
+                               t = GetConstructedType (t, dim.Substring (rank + 1));
 
-       public static Type GetNestedType (Type t, string name)
-       {
-               object ret = null;
-               if (!type_hash.Lookup (t, name, out ret)) {
-                       ret = t.GetNestedType (name,
-                              BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
-                       type_hash.Insert (t, name, ret);
+                       ds = ArrayContainer.MakeType (t, rank);
                }
-               return (Type) ret;
-       }
 
-       /// <summary>
-       /// Fills static table with exported types from all referenced assemblies.
-       /// This information is required for CLS Compliance tests.
-       /// </summary>
-       public static void LoadAllImportedTypes ()
-       {
-               AllClsTopLevelTypes = new Dictionary<string, object> (1500);
-               foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies) {
-                       foreach (Type t in a.GetExportedTypes ()) {
-                               AllClsTopLevelTypes [t.FullName.ToLower (System.Globalization.CultureInfo.InvariantCulture)] = null;
-                       }
-               }
+               type_hash.Insert (t, dim, ds);
+               return ds;
        }
 
        /// <summary>
        ///   Returns the C# name of a type if possible, or the full type name otherwise
        /// </summary>
-       static public string CSharpName (Type t)
-       {
-               if (t == null_type)
-                       return "null";
-
-               if (t == typeof (ArglistAccess))
-                       return "__arglist";
-                       
-               if (t == typeof (AnonymousMethodBody))
-                       return "anonymous method";
-
-               if (t == typeof (MethodGroupExpr))
-                       return "method group";
-
-               if (IsDynamicType (t))
-                       return "dynamic";
-
-               if (t == null)
-                       return "internal error";
-
-               return CSharpName (GetFullName (t), t);
-       }
-
-       static readonly char [] elements = new char [] { '*', '[' };
-
-       public static string CSharpName (string name, Type type)
+       static public string CSharpName (TypeSpec t)
        {
-               if (name.Length > 10) {
-                       string s;
-                       switch (name) {
-                       case "System.Int32": s = "int"; break;
-                       case "System.Int64": s = "long"; break;
-                       case "System.String": s = "string"; break;
-                       case "System.Boolean": s = "bool"; break;
-                       case "System.Void": s = "void"; break;
-                       case "System.Object": s = "object"; break;
-                       case "System.UInt32": s = "uint"; break;
-                       case "System.Int16": s = "short"; break;
-                       case "System.UInt16": s = "ushort"; break;
-                       case "System.UInt64": s = "ulong"; break;
-                       case "System.Single": s = "float"; break;
-                       case "System.Double": s = "double"; break;
-                       case "System.Decimal": s = "decimal"; break;
-                       case "System.Char": s = "char"; break;
-                       case "System.Byte": s = "byte"; break;
-                       case "System.SByte": s = "sbyte"; break;
-                       default: s = null; break;
-                       }
-
-                       if (s != null) {
-                               //
-                               // Predefined names can come from mscorlib only
-                               //
-                               if (type == null || type.Module.Name == "mscorlib.dll" || !RootContext.StdLib)
-                                       return s;
-                                       
-                               return name;
-                       }
-
-                       if (name [0] == AnonymousTypeClass.ClassNamePrefix [0] && name.StartsWith (AnonymousTypeClass.ClassNamePrefix))
-                               return AnonymousTypeClass.SignatureForError;
-
-                       int idx = name.IndexOfAny (elements, 10);
-                       if (idx > 0)
-                               return CSharpName (name.Substring (0, idx), type) + name.Substring (idx);
-               }
-
-               return name.Replace ('+', '.');
+               return t.GetSignatureForError ();
        }
 
-       static public string CSharpName (Type[] types)
+       static public string CSharpName (IList<TypeSpec> types)
        {
-               if (types.Length == 0)
+               if (types.Count == 0)
                        return string.Empty;
 
                StringBuilder sb = new StringBuilder ();
-               for (int i = 0; i < types.Length; ++i) {
+               for (int i = 0; i < types.Count; ++i) {
                        if (i > 0)
-                               sb.Append (", ");
+                               sb.Append (",");
 
                        sb.Append (CSharpName (types [i]));
                }
                return sb.ToString ();
        }
 
-       /// <summary>
-       ///  Returns the signature of the method with full namespace classification
-       /// </summary>
-       static public string GetFullNameSignature (MemberInfo mi)
-       {
-               PropertyInfo pi = mi as PropertyInfo;
-               if (pi != null) {
-                       MethodBase pmi = pi.GetGetMethod (true);
-                       if (pmi == null)
-                               pmi = pi.GetSetMethod (true);
-                       if (GetParameterData (pmi).Count > 0)
-                               mi = pmi;
-               }
-               return (mi is MethodBase)
-                       ? CSharpSignature (mi as MethodBase) 
-                       : CSharpName (mi.DeclaringType) + '.' + mi.Name;
-       }
-
-       private static int GetFullName (Type t, StringBuilder sb)
-       {
-               int pos = 0;
-
-               if (!t.IsGenericType) {
-                       sb.Append (t.FullName);
-                       return 0;
-               }
-
-               if (t.DeclaringType != null) {
-                       pos = GetFullName (t.DeclaringType, sb);
-                       sb.Append ('.');
-               } else if (t.Namespace != null && t.Namespace.Length != 0) {
-                       sb.Append (t.Namespace);
-                       sb.Append ('.');
-               }
-               sb.Append (RemoveGenericArity (t.Name));
-
-               Type[] this_args = GetTypeArguments (t);
-
-               if (this_args.Length < pos)
-                       throw new InternalErrorException (
-                               "Enclosing class " + t.DeclaringType + " has more type arguments than " + t);
-               if (this_args.Length == pos)
-                       return pos;
-
-               sb.Append ('<');
-               for (;;) {
-                       sb.Append (CSharpName (this_args [pos++]));
-                       if (pos == this_args.Length)
-                               break;
-                       sb.Append (',');
-               }
-               sb.Append ('>');
-               return pos;
-       }
-
-       static string GetFullName (Type t)
-       {
-               if (t.IsArray) {
-                       string dimension = t.Name.Substring (t.Name.LastIndexOf ('['));
-                       return GetFullName (GetElementType (t)) + dimension;
-               }
-
-               if (IsNullableType (t) && !t.IsGenericTypeDefinition) {
-                       t = TypeToCoreType (GetTypeArguments (t)[0]);
-                       return CSharpName (t) + "?";
-               }
-
-               if (t.IsGenericParameter)
-                       return t.Name;
-               if (!t.IsGenericType)
-                       return t.FullName;
-
-               StringBuilder sb = new StringBuilder ();
-               int pos = GetFullName (t, sb);
-               if (pos <= 0)
-                       throw new InternalErrorException ("Generic Type " + t + " doesn't have type arguments");
-               return sb.ToString ();
-       }
-
-       public static string RemoveGenericArity (string from)
-       {
-               int i = from.IndexOf ('`');
-               if (i > 0)
-                       return from.Substring (0, i);
-               return from;
-       }
-
-       /// <summary>
-       /// When we need to report accessors as well
-       /// </summary>
-       static public string CSharpSignature (MethodBase mb)
-       {
-               return CSharpSignature (mb, false);
-       }
-
-       static public string CSharpSignature (MethodSpec ms)
-       {
-               return CSharpSignature (ms.MetaInfo);
-       }
-
-       /// <summary>
-       ///   Returns the signature of the method
-       /// </summary>
-       static public string CSharpSignature (MethodBase mb, bool show_accessor)
-       {
-               StringBuilder sig = new StringBuilder (CSharpName (mb.DeclaringType));
-               sig.Append ('.');
-
-               AParametersCollection iparams = GetParameterData (mb);
-               string parameters = iparams.GetSignatureForError ();
-               int accessor_end = 0;
-
-               if (!mb.IsConstructor && TypeManager.IsSpecialMethod (mb)) {
-                       string op_name = Operator.GetName (mb.Name);
-                       if (op_name != null) {
-                               if (op_name == "explicit" || op_name == "implicit") {
-                                       sig.Append (op_name);
-                                       sig.Append (" operator ");
-                                       sig.Append (CSharpName (((MethodInfo)mb).ReturnType));
-                               } else {
-                                       sig.Append ("operator ");
-                                       sig.Append (op_name);
-                               }
-                               sig.Append (parameters);
-                               return sig.ToString ();
-                       }
-
-                       bool is_getter = mb.Name.StartsWith ("get_");
-                       bool is_setter = mb.Name.StartsWith ("set_");
-                       if (is_getter || is_setter || mb.Name.StartsWith ("add_")) {
-                               accessor_end = 3;
-                       } else if (mb.Name.StartsWith ("remove_")) {
-                               accessor_end = 6;
-                       }
-
-                       // Is indexer
-                       if (iparams.Count > (is_getter ? 0 : 1)) {
-                               sig.Append ("this[");
-                               if (is_getter)
-                                       sig.Append (parameters.Substring (1, parameters.Length - 2));
-                               else
-                                       sig.Append (parameters.Substring (1, parameters.LastIndexOf (',') - 1));
-                               sig.Append (']');
-                       } else {
-                               sig.Append (mb.Name.Substring (accessor_end + 1));
-                       }
-               } else {
-                       if (mb.Name == ".ctor")
-                               sig.Append (RemoveGenericArity (mb.DeclaringType.Name));
-                       else {
-                               sig.Append (mb.Name);
-
-                               if (IsGenericMethod (mb)) {
-                                       Type[] args = GetGenericArguments (mb);
-                                       sig.Append ('<');
-                                       for (int i = 0; i < args.Length; i++) {
-                                               if (i > 0)
-                                                       sig.Append (',');
-                                               sig.Append (CSharpName (args [i]));
-                                       }
-                                       sig.Append ('>');
-                               }
-                       }
-
-                       sig.Append (parameters);
-               }
-
-               if (show_accessor && accessor_end > 0) {
-                       sig.Append ('.');
-                       sig.Append (mb.Name.Substring (0, accessor_end));
-               }
-
-               return sig.ToString ();
-       }
-
-       public static string GetMethodName (MethodInfo m)
+       static public string GetFullNameSignature (MemberSpec mi)
        {
-               if (!IsGenericMethodDefinition (m) && !IsGenericMethod (m))
-                       return m.Name;
-
-               return MemberName.MakeName (m.Name, TypeManager.GetGenericArguments (m).Length);
+               return mi.GetSignatureForError ();
        }
 
-       static public string CSharpSignature (EventInfo ei)
+       static public string CSharpSignature (MemberSpec mb)
        {
-               return CSharpName (ei.DeclaringType) + "." + ei.Name;
+               return mb.GetSignatureForError ();
        }
 
        //
        // Looks up a type, and aborts if it is not found.  This is used
        // by predefined types required by the compiler
        //
-       public static Type CoreLookupType (CompilerContext ctx, string ns_name, string name, MemberKind type_kind, bool required)
+       public static TypeSpec CoreLookupType (CompilerContext ctx, string ns_name, string name, MemberKind kind, bool required)
+       {
+               return CoreLookupType (ctx, ns_name, name, 0, kind, required);
+       }
+
+       public static TypeSpec CoreLookupType (CompilerContext ctx, string ns_name, string name, int arity, MemberKind kind, bool required)
        {
                Namespace ns = GlobalRootNamespace.Instance.GetNamespace (ns_name, true);
-               Expression expr = ns.Lookup (ctx, name, Location.Null);
+               var te = ns.Lookup (ctx, name, arity, Location.Null);
+               var ts = te == null ? null : te.Type;
 
-               if (expr == null) {
-                       if (required) {
-                               ctx.Report.Error (518, "The predefined type `{0}.{1}' is not defined or imported",
-                                       ns_name, name);
-                       }
+               if (!required)
+                       return ts;
+
+               if (ts == null) {
+                       ctx.Report.Error (518, "The predefined type `{0}.{1}' is not defined or imported",
+                               ns_name, name);
                        return null;
                }
 
-               Type t = expr.Type;
-               if (RootContext.StdLib || t == null || !required)
-                       return t;
-
-               // TODO: All predefined imported types have to have correct signature
-               if (!IsBeingCompiled (t))
-                       return t;
-
-               DeclSpace ds = (DeclSpace)RootContext.ToplevelTypes.GetDefinition (t.FullName);
-               if (ds is Delegate) {
-                       if (type_kind == MemberKind.Delegate)
-                               return t;
-               } else {
-                       TypeContainer tc = (TypeContainer)ds;
-                       if (tc.Kind == type_kind)
-                               return t;
+               if (ts.Kind != kind) {
+                       ctx.Report.Error (520, "The predefined type `{0}.{1}' is not declared correctly",
+                               ns_name, name);
+                       return null;
                }
 
-               ctx.Report.Error (520, ds.Location, "The predefined type `{0}.{1}' is not declared correctly",
-                       ns_name, name);
-               return null;
+               return ts;
        }
 
-       static MemberInfo GetPredefinedMember (Type t, string name, MemberTypes mt, Location loc, params Type [] args)
+       static MemberSpec GetPredefinedMember (TypeSpec t, MemberFilter filter, Location loc)
        {
-               const BindingFlags flags = instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly;
-
-               MemberInfo [] members = MemberLookup (null, null, t, mt, flags, name, null);
-               if (members != null) {
-                       for (int i = 0; i < members.Length; ++i) {
-                               MemberInfo member = members [i];
-                               if (mt == MemberTypes.Method || mt == MemberTypes.Constructor) {
-                                       MethodBase mb = member as MethodBase;
-                                       if (mb == null)
-                                               continue;
-
-                                       AParametersCollection pd = TypeManager.GetParameterData (mb);
-                                       if (IsEqual (pd.Types, args))
-                                               return member;
-                               }
-                               if (mt == MemberTypes.Field) {
-                                       FieldInfo fi = member as FieldInfo;
-                                       if (fi == null)
-                                               continue;
-
-                                       if (args.Length >= 1 && !IsEqual (TypeToCoreType (fi.FieldType), args [0]))
-                                               continue;
-
-                                       return member;
-                               }
-
-                               if (mt == MemberTypes.Property) {
-                                       PropertyInfo pi = member as PropertyInfo;
-                                       if (pi == null)
-                                               continue;
+               const BindingRestriction restrictions = BindingRestriction.AccessibleOnly | BindingRestriction.DeclaredOnly;
+               var member = MemberCache.FindMember (t, filter, restrictions);
 
-                                       if (args.Length >= 1 && !IsEqual (TypeToCoreType (pi.PropertyType), args [0]))
-                                               continue;
-
-                                       return member;
-                               }
-                       }
-               }
+               if (member != null)
+                       return member;
 
                string method_args = null;
-               if (mt == MemberTypes.Method || mt == MemberTypes.Constructor)
-                       method_args = "(" + TypeManager.CSharpName (args) + ")";
+               if (filter.Parameters != null)
+                       method_args = filter.Parameters.GetSignatureForError ();
 
                RootContext.ToplevelTypes.Compiler.Report.Error (656, loc, "The compiler required member `{0}.{1}{2}' could not be found or is inaccessible",
-                       TypeManager.CSharpName (t), name, method_args);
+                       TypeManager.CSharpName (t), filter.Name, method_args);
 
                return null;
        }
@@ -883,35 +358,78 @@ namespace Mono.CSharp {
        //
        // Returns the ConstructorInfo for "args"
        //
-       public static ConstructorInfo GetPredefinedConstructor (Type t, Location loc, params Type [] args)
+       public static MethodSpec GetPredefinedConstructor (TypeSpec t, Location loc, params TypeSpec [] args)
        {
-               return (ConstructorInfo) GetPredefinedMember (t, ConstructorInfo.ConstructorName, MemberTypes.Constructor, loc, args);
+               var pc = ParametersCompiled.CreateFullyResolved (args);
+               return GetPredefinedMember (t, MemberFilter.Constructor (pc), loc) as MethodSpec;
        }
 
        //
-       // Returns the MethodInfo for a method named `name' defined
+       // Returns the method specification for a method named `name' defined
        // in type `t' which takes arguments of types `args'
        //
-       public static MethodSpec GetPredefinedMethod (Type t, string name, Location loc, params Type [] args)
+       public static MethodSpec GetPredefinedMethod (TypeSpec t, string name, Location loc, params TypeSpec [] args)
        {
-               var m = GetPredefinedMember (t, name, MemberTypes.Method, loc, args) as MethodBase;
-               if (m == null)
-                       return null;
+               var pc = ParametersCompiled.CreateFullyResolved (args);
+               return GetPredefinedMethod (t, MemberFilter.Method (name, 0, pc, null), loc);
+       }
 
-               return Import.CreateMethod (m);
+       public static MethodSpec GetPredefinedMethod (TypeSpec t, MemberFilter filter, Location loc)
+       {
+               return GetPredefinedMember (t, filter, loc) as MethodSpec;
        }
 
-       public static FieldInfo GetPredefinedField (Type t, string name, Location loc, params Type [] args)
+       public static FieldSpec GetPredefinedField (TypeSpec t, string name, Location loc, TypeSpec type)
        {
-               return (FieldInfo) GetPredefinedMember (t, name, MemberTypes.Field, loc, args);
+               return GetPredefinedMember (t, MemberFilter.Field (name, type), loc) as FieldSpec;
        }
 
-       public static PropertySpec GetPredefinedProperty (Type t, string name, Location loc, params Type [] args)
+       public static PropertySpec GetPredefinedProperty (TypeSpec t, string name, Location loc, TypeSpec type)
        {
-               var p = GetPredefinedMember (t, name, MemberTypes.Property, loc, args) as PropertyInfo;
-               if (p == null)
-                       return null;
-               return Import.CreateProperty (p);
+               return GetPredefinedMember (t, MemberFilter.Property (name, type), loc) as PropertySpec;
+       }
+
+       public static IList<PredefinedTypeSpec> InitCoreTypes ()
+       {
+               var core_types = new PredefinedTypeSpec[] {
+                       object_type = new PredefinedTypeSpec (MemberKind.Class, "System", "Object"),
+                       value_type = new PredefinedTypeSpec (MemberKind.Class, "System", "ValueType"),
+                       attribute_type = new PredefinedTypeSpec (MemberKind.Class, "System", "Attribute"),
+
+                       int32_type = new PredefinedTypeSpec (MemberKind.Struct, "System", "Int32"),
+                       int64_type = new PredefinedTypeSpec (MemberKind.Struct, "System", "Int64"),
+                       uint32_type = new PredefinedTypeSpec (MemberKind.Struct, "System", "UInt32"),
+                       uint64_type = new PredefinedTypeSpec (MemberKind.Struct, "System", "UInt64"),
+                       byte_type = new PredefinedTypeSpec (MemberKind.Struct, "System", "Byte"),
+                       sbyte_type = new PredefinedTypeSpec (MemberKind.Struct, "System", "SByte"),
+                       short_type = new PredefinedTypeSpec (MemberKind.Struct, "System", "Int16"),
+                       ushort_type = new PredefinedTypeSpec (MemberKind.Struct, "System", "UInt16"),
+
+                       ienumerator_type = new PredefinedTypeSpec (MemberKind.Interface, "System.Collections", "IEnumerator"),
+                       ienumerable_type = new PredefinedTypeSpec (MemberKind.Interface, "System.Collections", "IEnumerable"),
+                       idisposable_type = new PredefinedTypeSpec (MemberKind.Interface, "System", "IDisposable"),
+
+                       char_type = new PredefinedTypeSpec (MemberKind.Struct, "System", "Char"),
+                       string_type = new PredefinedTypeSpec (MemberKind.Class, "System", "String"),
+                       float_type = new PredefinedTypeSpec (MemberKind.Struct, "System", "Single"),
+                       double_type = new PredefinedTypeSpec (MemberKind.Struct, "System", "Double"),
+                       decimal_type = new PredefinedTypeSpec (MemberKind.Struct, "System", "Decimal"),
+                       bool_type = new PredefinedTypeSpec (MemberKind.Struct, "System", "Boolean"),
+                       intptr_type = new PredefinedTypeSpec (MemberKind.Struct, "System", "IntPtr"),
+                       uintptr_type = new PredefinedTypeSpec (MemberKind.Struct, "System", "UIntPtr"),
+
+                       multicast_delegate_type = new PredefinedTypeSpec (MemberKind.Class, "System", "MulticastDelegate"),
+                       delegate_type = new PredefinedTypeSpec (MemberKind.Class, "System", "Delegate"),
+                       enum_type = new PredefinedTypeSpec (MemberKind.Class, "System", "Enum"),
+                       array_type = new PredefinedTypeSpec (MemberKind.Class, "System", "Array"),
+                       void_type = new PredefinedTypeSpec (MemberKind.Struct, "System", "Void"),
+                       type_type = new PredefinedTypeSpec (MemberKind.Class, "System", "Type"),
+                       exception_type = new PredefinedTypeSpec (MemberKind.Class, "System", "Exception"),
+                       runtime_field_handle_type = new PredefinedTypeSpec (MemberKind.Struct, "System", "RuntimeFieldHandle"),
+                       runtime_handle_type = new PredefinedTypeSpec (MemberKind.Struct, "System", "RuntimeTypeHandle"),
+               };
+
+               return core_types;
        }
 
        /// <remarks>
@@ -919,66 +437,22 @@ namespace Mono.CSharp {
        ///   population of the type has happened (for example, to
        ///   bootstrap the corlib.dll
        /// </remarks>
-       public static bool InitCoreTypes (CompilerContext ctx)
+       public static bool InitCoreTypes (CompilerContext ctx, IList<PredefinedTypeSpec> predefined)
        {
-               object_type   = CoreLookupType (ctx, "System", "Object", MemberKind.Class, true);
-               system_object_expr.Type = object_type;
-               value_type    = CoreLookupType (ctx, "System", "ValueType", MemberKind.Class, true);
-               system_valuetype_expr.Type = value_type;
-               attribute_type = CoreLookupType (ctx, "System", "Attribute", MemberKind.Class, true);
-
-               int32_type    = CoreLookupType (ctx, "System", "Int32", MemberKind.Struct, true);
-               system_int32_expr.Type = int32_type;
-               int64_type    = CoreLookupType (ctx, "System", "Int64", MemberKind.Struct, true);
-               system_int64_expr.Type = int64_type;
-               uint32_type   = CoreLookupType (ctx, "System", "UInt32", MemberKind.Struct, true);
-               system_uint32_expr.Type = uint32_type;
-               uint64_type   = CoreLookupType (ctx, "System", "UInt64", MemberKind.Struct, true);
-               system_uint64_expr.Type = uint64_type;
-               byte_type     = CoreLookupType (ctx, "System", "Byte", MemberKind.Struct, true);
-               system_byte_expr.Type = byte_type;
-               sbyte_type    = CoreLookupType (ctx, "System", "SByte", MemberKind.Struct, true);
-               system_sbyte_expr.Type = sbyte_type;
-               short_type    = CoreLookupType (ctx, "System", "Int16", MemberKind.Struct, true);
-               system_int16_expr.Type = short_type;
-               ushort_type   = CoreLookupType (ctx, "System", "UInt16", MemberKind.Struct, true);
-               system_uint16_expr.Type = ushort_type;
-
-               ienumerator_type     = CoreLookupType (ctx, "System.Collections", "IEnumerator", MemberKind.Interface, true);
-               ienumerable_type     = CoreLookupType (ctx, "System.Collections", "IEnumerable", MemberKind.Interface, true);
-               idisposable_type     = CoreLookupType (ctx, "System", "IDisposable", MemberKind.Interface, true);
-
-               // HACK: DefineType immediately resolves iterators (very wrong)
-               generic_ienumerator_type = CoreLookupType (ctx, "System.Collections.Generic", "IEnumerator`1", MemberKind.Interface, false);
-
-               char_type     = CoreLookupType (ctx, "System", "Char", MemberKind.Struct, true);
-               system_char_expr.Type = char_type;
-               string_type   = CoreLookupType (ctx, "System", "String", MemberKind.Class, true);
-               system_string_expr.Type = string_type;
-               float_type    = CoreLookupType (ctx, "System", "Single", MemberKind.Struct, true);
-               system_single_expr.Type = float_type;
-               double_type   = CoreLookupType (ctx, "System", "Double", MemberKind.Struct, true);
-               system_double_expr.Type = double_type;
-               decimal_type  = CoreLookupType (ctx, "System", "Decimal", MemberKind.Struct, true);
-               system_decimal_expr.Type = decimal_type;
-               bool_type     = CoreLookupType (ctx, "System", "Boolean", MemberKind.Struct, true);
-               system_boolean_expr.Type = bool_type;
-               intptr_type = CoreLookupType (ctx, "System", "IntPtr", MemberKind.Struct, true);
-               system_intptr_expr.Type = intptr_type;
-               uintptr_type = CoreLookupType (ctx, "System", "UIntPtr", MemberKind.Struct, true);
-
-               multicast_delegate_type = CoreLookupType (ctx, "System", "MulticastDelegate", MemberKind.Class, true);
-               delegate_type           = CoreLookupType (ctx, "System", "Delegate", MemberKind.Class, true);
-
-               enum_type       = CoreLookupType (ctx, "System", "Enum", MemberKind.Class, true);
-               array_type      = CoreLookupType (ctx, "System", "Array", MemberKind.Class, true);
-               void_type       = CoreLookupType (ctx, "System", "Void", MemberKind.Struct, true);
-               system_void_expr.Type = void_type;
-               type_type       = CoreLookupType (ctx, "System", "Type", MemberKind.Class, true);
-               exception_type = CoreLookupType (ctx, "System", "Exception", MemberKind.Class, true);
-
-               runtime_field_handle_type = CoreLookupType (ctx, "System", "RuntimeFieldHandle", MemberKind.Struct, true);
-               runtime_handle_type = CoreLookupType (ctx, "System", "RuntimeTypeHandle", MemberKind.Struct, true);
+               foreach (var p in predefined) {
+                       var found = CoreLookupType (ctx, p.Namespace, p.Name, p.Kind, true);
+                       if (found == null || found == p)
+                               continue;
+
+                       if (!RootContext.StdLib) {
+                               var ns = GlobalRootNamespace.Instance.GetNamespace (p.Namespace, false);
+                               ns.ReplaceTypeWithPredefined (found, p);
+
+                               var tc = found.MemberDefinition as TypeContainer;
+                               tc.SetPredefinedSpec (p);
+                               p.SetDefinition (found);
+                       }
+               }
 
                PredefinedAttributes.Get.ParamArray.Initialize (ctx, false);
                PredefinedAttributes.Get.Out.Initialize (ctx, false);
@@ -994,9 +468,9 @@ namespace Mono.CSharp {
                //
                // These are only used for compare purposes
                //
-               null_type = typeof (NullLiteral);
-               
-               void_ptr_type = GetPointerType (void_type);
+               null_type = InternalType.Null;
+
+               void_ptr_type = PointerContainer.MakeType (void_type);
 
                //
                // Initialize InternalsVisibleTo as the very first optional type. Otherwise we would populate
@@ -1011,19 +485,11 @@ namespace Mono.CSharp {
                arg_iterator_type = CoreLookupType (ctx, "System", "ArgIterator", MemberKind.Struct, false);
                mbr_type = CoreLookupType (ctx, "System", "MarshalByRefObject", MemberKind.Class, false);
 
-               //
-               // Optional attributes, used for error reporting only
-               //
-               //if (PredefinedAttributes.Get.Obsolete.IsDefined) {
-               //    Class c = TypeManager.LookupClass (PredefinedAttributes.Get.Obsolete.Type);
-               //    if (c != null)
-               //        c.Define ();
-               //}
-
-               generic_ilist_type = CoreLookupType (ctx, "System.Collections.Generic", "IList`1", MemberKind.Interface, false);
-               generic_icollection_type = CoreLookupType (ctx, "System.Collections.Generic", "ICollection`1", MemberKind.Interface, false);
-               generic_ienumerable_type = CoreLookupType (ctx, "System.Collections.Generic", "IEnumerable`1", MemberKind.Interface, false);
-               generic_nullable_type = CoreLookupType (ctx, "System", "Nullable`1", MemberKind.Struct, false);
+               generic_ienumerator_type = CoreLookupType (ctx, "System.Collections.Generic", "IEnumerator", 1, MemberKind.Interface, false);
+               generic_ilist_type = CoreLookupType (ctx, "System.Collections.Generic", "IList", 1, MemberKind.Interface, false);
+               generic_icollection_type = CoreLookupType (ctx, "System.Collections.Generic", "ICollection", 1, MemberKind.Interface, false);
+               generic_ienumerable_type = CoreLookupType (ctx, "System.Collections.Generic", "IEnumerable", 1, MemberKind.Interface, false);
+               generic_nullable_type = CoreLookupType (ctx, "System", "Nullable", 1, MemberKind.Struct, false);
 
                //
                // Optional types which are used as types and for member lookup
@@ -1032,324 +498,61 @@ namespace Mono.CSharp {
 
                // New in .NET 3.5
                // Note: extension_attribute_type is already loaded
-               expression_type = CoreLookupType (ctx, "System.Linq.Expressions", "Expression`1", MemberKind.Class, false);
+               expression_type = CoreLookupType (ctx, "System.Linq.Expressions", "Expression", 1, MemberKind.Class, false);
+       }
 
-               if (!RootContext.StdLib) {
-                       //
-                       // HACK: When building Mono corlib mcs uses loaded mscorlib which
-                       // has different predefined types and this method sets mscorlib types
-                       // to be same to avoid any type check errors.
-                       //
+       public static bool IsBuiltinType (TypeSpec t)
+       {
+               if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
+                   t == int64_type || t == uint64_type || t == float_type || t == double_type ||
+                   t == char_type || t == short_type || t == decimal_type || t == bool_type ||
+                   t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
+                       return true;
+               else
+                       return false;
+       }
 
-                       Type type = typeof (Type);
-                       Type [] system_4_type_arg = { type, type, type, type };
-                               
-                       MethodInfo set_corlib_type_builders = 
-                               typeof (System.Reflection.Emit.AssemblyBuilder).GetMethod (
-                               "SetCorlibTypeBuilders", BindingFlags.NonPublic | BindingFlags.Instance, null,
-                               system_4_type_arg, null);
-
-                       if (set_corlib_type_builders != null) {
-                               object[] args = new object [4];
-                               args [0] = object_type;
-                               args [1] = value_type;
-                               args [2] = enum_type;
-                               args [3] = void_type;
-                               
-                               set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
-                       } else {
-                               ctx.Report.Warning (-26, 3, "The compilation may fail due to missing `{0}.SetCorlibTypeBuilders({1})' method",
-                                       TypeManager.CSharpName (typeof (System.Reflection.Emit.AssemblyBuilder)),
-                                       TypeManager.CSharpName (system_4_type_arg));
-                       }
-               }
+       //
+       // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
+       // the pieces in the code where we use IsBuiltinType and special case decimal_type.
+       // 
+       public static bool IsPrimitiveType (TypeSpec t)
+       {
+               return (t == int32_type || t == uint32_type ||
+                   t == int64_type || t == uint64_type || t == float_type || t == double_type ||
+                   t == char_type || t == short_type || t == bool_type ||
+                   t == sbyte_type || t == byte_type || t == ushort_type);
        }
 
-       const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
+       // Obsolete
+       public static bool IsDelegateType (TypeSpec t)
+       {
+               return t.IsDelegate;
+       }
 
-       /// <remarks>
-       ///   This is the "old", non-cache based FindMembers() function.  We cannot use
-       ///   the cache here because there is no member name argument.
-       /// </remarks>
-       public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
-                                             MemberFilter filter, object criteria)
+       //
+       // When any element of the type is a dynamic type
+       //
+       // This method builds a transformation array for dynamic types
+       // used in places where DynamicAttribute cannot be applied to.
+       // It uses bool flag when type is of dynamic type and each
+       // section always starts with "false" for some reason.
+       //
+       // LAMESPEC: This should be part of C# specification !
+       // 
+       // Example: Func<dynamic, int, dynamic[]>
+       // Transformation: { false, true, false, false, true }
+       //
+       public static bool[] HasDynamicTypeUsed (TypeSpec t)
        {
-#if MS_COMPATIBLE
-               if (t.IsGenericType)
-                       t = t.GetGenericTypeDefinition ();
-#endif
+               var ac = t as ArrayContainer;
+               if (ac != null) {
+                       if (HasDynamicTypeUsed (ac.Element) != null)
+                               return new bool[] { false, true };
 
-               DeclSpace decl = LookupDeclSpace (t);
-
-               //
-               // `builder_to_declspace' contains all dynamic types.
-               //
-               if (decl != null) {
-                       MemberList list;
-                       Timer.StartTimer (TimerType.FindMembers);
-                       list = decl.FindMembers (mt, bf, filter, criteria);
-                       Timer.StopTimer (TimerType.FindMembers);
-                       return list;
-               }
-
-               //
-               // We have to take care of arrays specially, because GetType on
-               // a TypeBuilder array will return a Type, not a TypeBuilder,
-               // and we can not call FindMembers on this type.
-               //
-               if (
-#if MS_COMPATIBLE
-                       !t.IsGenericType &&
-#endif
-                       t.IsSubclassOf (TypeManager.array_type))
-                       return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
-
-               if (t is GenericTypeParameterBuilder) {
-                       TypeParameter tparam = builder_to_type_param [(GenericTypeParameterBuilder) t];
-
-                       Timer.StartTimer (TimerType.FindMembers);
-                       MemberList list = tparam.FindMembers (
-                               mt, bf | BindingFlags.DeclaredOnly, filter, criteria);
-                       Timer.StopTimer (TimerType.FindMembers);
-                       return list;
-               }
-
-               //
-               // Since FindMembers will not lookup both static and instance
-               // members, we emulate this behaviour here.
-               //
-               if ((bf & instance_and_static) == instance_and_static){
-                       MemberInfo [] i_members = t.FindMembers (
-                               mt, bf & ~BindingFlags.Static, filter, criteria);
-
-                       int i_len = i_members.Length;
-                       if (i_len == 1){
-                               MemberInfo one = i_members [0];
-
-                               //
-                               // If any of these are present, we are done!
-                               //
-                               if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
-                                       return new MemberList (i_members);
-                       }
-                               
-                       MemberInfo [] s_members = t.FindMembers (
-                               mt, bf & ~BindingFlags.Instance, filter, criteria);
-
-                       int s_len = s_members.Length;
-                       if (i_len > 0 || s_len > 0)
-                               return new MemberList (i_members, s_members);
-                       else {
-                               if (i_len > 0)
-                                       return new MemberList (i_members);
-                               else
-                                       return new MemberList (s_members);
-                       }
-               }
-
-               return new MemberList (t.FindMembers (mt, bf, filter, criteria));
-       }
-
-
-       /// <summary>
-       ///   This method is only called from within MemberLookup.  It tries to use the member
-       ///   cache if possible and falls back to the normal FindMembers if not.  The `used_cache'
-       ///   flag tells the caller whether we used the cache or not.  If we used the cache, then
-       ///   our return value will already contain all inherited members and the caller don't need
-       ///   to check base classes and interfaces anymore.
-       /// </summary>
-       private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
-                                                              string name, out bool used_cache)
-       {
-               MemberCache cache;
-
-               //
-               // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
-               // and we can ask the DeclSpace for the MemberCache.
-               //
-#if MS_COMPATIBLE
-               if (t.Assembly == CodeGen.Assembly.Builder) {
-                       if (t.IsGenericParameter) {
-                               TypeParameter tparam = builder_to_type_param [(GenericTypeParameterBuilder) t];
-
-                               used_cache = true;
-                               if (tparam.MemberCache == null)
-                                       return new MemberInfo[0];
-
-                               return tparam.MemberCache.FindMembers (
-                                       mt, bf, name, FilterWithClosure_delegate, null);
-                       }
-
-                       //
-                       // We have to take care of arrays specially, because GetType on
-                       // a TypeBuilder array will return a Type, not a TypeBuilder,
-                       // and we can not call FindMembers on this type.
-                       //
-                       if (t.IsArray) {
-                               used_cache = true;
-                               return TypeHandle.ArrayType.MemberCache.FindMembers (
-                                       mt, bf, name, FilterWithClosure_delegate, null);
-                       }
-
-                       if (t.IsGenericType && !t.IsGenericTypeDefinition)
-                               t = t.GetGenericTypeDefinition ();
-#else
-               if (t is TypeBuilder) {
-#endif
-                       DeclSpace decl = LookupDeclSpace (t);
-                       cache = decl.MemberCache;
-
-                       //
-                       // If this DeclSpace has a MemberCache, use it.
-                       //
-
-                       if (cache != null) {
-                               used_cache = true;
-                               return cache.FindMembers (
-                                       mt, bf, name, FilterWithClosure_delegate, null);
-                       }
-
-                       // If there is no MemberCache, we need to use the "normal" FindMembers.
-                       // Note, this is a VERY uncommon route!
-
-                       MemberList list;
-                       Timer.StartTimer (TimerType.FindMembers);
-                       list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
-                                                FilterWithClosure_delegate, name);
-                       Timer.StopTimer (TimerType.FindMembers);
-                       used_cache = false;
-                       return (MemberInfo []) list;
-               }
-
-               //
-               // We have to take care of arrays specially, because GetType on
-               // a TypeBuilder array will return a Type, not a TypeBuilder,
-               // and we can not call FindMembers on this type.
-               //
-               if (t.IsArray) {
-                       used_cache = true;
-                       return TypeHandle.ArrayType.MemberCache.FindMembers (
-                               mt, bf, name, FilterWithClosure_delegate, null);
-               }
-
-               if (t is GenericTypeParameterBuilder) {
-                       TypeParameter tparam = builder_to_type_param [(GenericTypeParameterBuilder) t];
-
-                       used_cache = true;
-                       if (tparam.MemberCache == null)
-                               return new MemberInfo [0];
-
-                       return tparam.MemberCache.FindMembers (
-                               mt, bf, name, FilterWithClosure_delegate, null);
-               }
-
-               if (IsGenericType (t) && (mt == MemberTypes.NestedType)) {
-                       //
-                       // This happens if we're resolving a class'es base class and interfaces
-                       // in TypeContainer.DefineType().  At this time, the types aren't
-                       // populated yet, so we can't use the cache.
-                       //
-                       MemberInfo[] info = t.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
-                                                          FilterWithClosure_delegate, name);
-                       used_cache = false;
-                       return info;
+                       return null;
                }
 
-               //
-               // This call will always succeed.  There is exactly one TypeHandle instance per
-               // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
-               // the corresponding MemberCache.
-               //
-               cache = TypeHandle.GetMemberCache (t);
-
-               used_cache = true;
-               return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
-       }
-
-       //
-       // Return true for SRE dynamic/unclosed members
-       //
-       public static bool IsBeingCompiled (MemberInfo mi)
-       {
-               return mi.Module.Assembly == CodeGen.Assembly.Builder;
-       }
-
-       public static bool IsBuiltinType (Type t)
-       {
-               t = TypeToCoreType (t);
-               if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
-                   t == int64_type || t == uint64_type || t == float_type || t == double_type ||
-                   t == char_type || t == short_type || t == decimal_type || t == bool_type ||
-                   t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
-                       return true;
-               else
-                       return false;
-       }
-
-       //
-       // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
-       // the pieces in the code where we use IsBuiltinType and special case decimal_type.
-       // 
-       public static bool IsPrimitiveType (Type t)
-       {
-               return (t == int32_type || t == uint32_type ||
-                   t == int64_type || t == uint64_type || t == float_type || t == double_type ||
-                   t == char_type || t == short_type || t == bool_type ||
-                   t == sbyte_type || t == byte_type || t == ushort_type);
-       }
-
-       public static bool IsDelegateType (Type t)
-       {
-               if (TypeManager.IsGenericParameter (t))
-                       return false;
-
-               if (t == TypeManager.delegate_type || t == TypeManager.multicast_delegate_type)
-                       return false;
-
-               t = DropGenericTypeArguments (t);
-               return IsSubclassOf (t, TypeManager.delegate_type);
-       }
-
-       //
-       // Is a type of dynamic type
-       //
-       public static bool IsDynamicType (Type t)
-       {
-               if (object.ReferenceEquals (InternalType.Dynamic, t))
-                       return true;
-
-               if (t != object_type)
-                       return false;
-
-               if (IsBeingCompiled (t))
-                       return false;
-
-               PredefinedAttribute pa = PredefinedAttributes.Get.Dynamic;
-               if (pa == null || IsBeingCompiled (pa.Type))
-                       return false;
-
-               object[] res = t.GetCustomAttributes (pa.Type, false);
-               return res != null && res.Length != 0;
-       }
-
-       //
-       // When any element of the type is a dynamic type
-       //
-       // This method builds a transformation array for dynamic types
-       // used in places where DynamicAttribute cannnot be applied to.
-       // It uses bool flag when type is of dynamic type and each
-       // section always starts with "false" for some reason.
-       //
-       // LAMESPEC: This should be part of C# specification !
-       // 
-       // Example: Func<dynamic, int, dynamic[]>
-       // Transformation: { false, true, false, false, true }
-       //
-       public static bool[] HasDynamicTypeUsed (Type t)
-       {
-               if (t is DynamicArrayType)
-                       return new bool[] { false, true };
-
                if (t == null)
                        return null;
 
@@ -1381,13 +584,13 @@ namespace Mono.CSharp {
                return null;
        }
        
-       public static bool IsEnumType (Type t)
+       // Obsolete
+       public static bool IsEnumType (TypeSpec t)
        {
-               t = DropGenericTypeArguments (t);
-               return t.BaseType == TypeManager.enum_type;
+               return t.IsEnum;
        }
 
-       public static bool IsBuiltinOrEnum (Type t)
+       public static bool IsBuiltinOrEnum (TypeSpec t)
        {
                if (IsBuiltinType (t))
                        return true;
@@ -1398,28 +601,19 @@ namespace Mono.CSharp {
                return false;
        }
 
-       public static bool IsAttributeType (Type t)
-       {
-               return t == attribute_type && t.BaseType != null || IsSubclassOf (t, attribute_type);
-       }
-       
        //
        // Whether a type is unmanaged.  This is used by the unsafe code (25.2)
        //
-       // mcs4: delete, DeclSpace.IsUnmanagedType is replacement
-       public static bool IsUnmanagedType (Type t)
+       public static bool IsUnmanagedType (TypeSpec t)
        {
-               DeclSpace ds = TypeManager.LookupDeclSpace (t);
+               var ds = t.MemberDefinition as DeclSpace;
                if (ds != null)
                        return ds.IsUnmanagedType ();
 
-               // builtins that are not unmanaged types
+               // some builtins that are not unmanaged types
                if (t == TypeManager.object_type || t == TypeManager.string_type)
                        return false;
 
-               if (IsGenericType (t) || IsGenericParameter (t))
-                       return false;
-
                if (IsBuiltinOrEnum (t))
                        return true;
 
@@ -1427,100 +621,43 @@ namespace Mono.CSharp {
                if (t.IsPointer)
                        return IsUnmanagedType (GetElementType (t));
 
-               // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
-               if (t.IsArray)
-                       return false;
-
                if (!IsValueType (t))
                        return false;
 
-               for (Type p = t.DeclaringType; p != null; p = p.DeclaringType) {
-                       if (IsGenericTypeDefinition (p))
-                               return false;
-               }
-
-               bool retval = true;
-               {
-                       FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
-                       
-                       foreach (FieldInfo f in fields){
-                               if (!IsUnmanagedType (f.FieldType)){
-                                       retval = false;
-                               }
-                       }
-               }
+               if (t.IsNested && t.DeclaringType.IsGenericOrParentIsGeneric)
+                       return false;
 
-               return retval;
+               return true;
        }
 
        //
        // Null is considered to be a reference type
        //                      
-       public static bool IsReferenceType (Type t)
+       public static bool IsReferenceType (TypeSpec t)
        {
-               if (TypeManager.IsGenericParameter (t)) {
-                       GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
-                       if (constraints == null)
-                               return false;
-
-                       return constraints.IsReferenceType;
-               }
+               if (t.IsGenericParameter)
+                       return ((TypeParameterSpec) t).IsReferenceType;
 
-               return !IsStruct (t) && !IsEnumType (t);
+               return !t.IsStruct && !IsEnumType (t);
        }                       
                
-       public static bool IsValueType (Type t)
+       public static bool IsValueType (TypeSpec t)
        {
-               if (TypeManager.IsGenericParameter (t)) {
-                       GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
-                       if (constraints == null)
-                               return false;
-
-                       return constraints.IsValueType;
-               }
+               if (t.IsGenericParameter)
+                       return ((TypeParameterSpec) t).IsValueType;
 
-               return IsStruct (t) || IsEnumType (t);
+               return t.IsStruct || IsEnumType (t);
        }
 
-       public static bool IsStruct (Type t)
+       public static bool IsStruct (TypeSpec t)
        {
-               return t.BaseType == value_type && t != enum_type && t.IsSealed;
-       }
-       
-       public static bool IsInterfaceType (Type t)
-       {
-               TypeContainer tc = LookupTypeContainer (t);
-               if (tc == null)
-                       return false;
-
-               return tc.Kind == MemberKind.Interface;
+               return t.IsStruct;
        }
 
-       public static bool IsSubclassOf (Type type, Type base_type)
+       public static bool IsSubclassOf (TypeSpec type, TypeSpec base_type)
        {
-               TypeParameter tparam = LookupTypeParameter (type);
-               TypeParameter pparam = LookupTypeParameter (base_type);
-
-               if ((tparam != null) && (pparam != null)) {
-                       if (tparam == pparam)
-                               return true;
-
-                       return tparam.IsSubclassOf (base_type);
-               }
-
-#if MS_COMPATIBLE
-               if (tparam != pparam)
-                       return false;
-
-               if (type.IsGenericType)
-                       type = type.GetGenericTypeDefinition ();
-#endif
-
-               if (type.IsSubclassOf (base_type))
-                       return true;
-
                do {
-                       if (IsEqual (type, base_type))
+                       if (type == base_type)
                                return true;
 
                        type = type.BaseType;
@@ -1529,27 +666,17 @@ namespace Mono.CSharp {
                return false;
        }
 
-       public static bool IsPrivateAccessible (Type type, Type parent)
-       {
-               if (type == null)
-                       return false;
-
-               if (type.Equals (parent))
-                       return true;
-
-               return DropGenericTypeArguments (type) == DropGenericTypeArguments (parent);
-       }
-
-       public static bool IsFamilyAccessible (Type type, Type parent)
+       public static bool IsFamilyAccessible (TypeSpec type, TypeSpec parent)
        {
-               TypeParameter tparam = LookupTypeParameter (type);
-               TypeParameter pparam = LookupTypeParameter (parent);
+//             TypeParameter tparam = LookupTypeParameter (type);
+//             TypeParameter pparam = LookupTypeParameter (parent);
 
-               if ((tparam != null) && (pparam != null)) {
-                       if (tparam == pparam)
+               if (type.Kind == MemberKind.TypeParameter && parent.Kind == MemberKind.TypeParameter) { // (tparam != null) && (pparam != null)) {
+                       if (type == parent)
                                return true;
 
-                       return tparam.IsSubclassOf (parent);
+                       throw new NotImplementedException ("net");
+//                     return tparam.IsSubclassOf (parent);
                }
 
                do {
@@ -1565,7 +692,7 @@ namespace Mono.CSharp {
        //
        // Checks whether `type' is a subclass or nested child of `base_type'.
        //
-       public static bool IsNestedFamilyAccessible (Type type, Type base_type)
+       public static bool IsNestedFamilyAccessible (TypeSpec type, TypeSpec base_type)
        {
                do {
                        if (IsFamilyAccessible (type, base_type))
@@ -1581,20 +708,20 @@ namespace Mono.CSharp {
        //
        // Checks whether `type' is a nested child of `parent'.
        //
-       public static bool IsNestedChildOf (Type type, Type parent)
+       public static bool IsNestedChildOf (TypeSpec type, TypeSpec parent)
        {
                if (type == null)
                        return false;
 
-               type = DropGenericTypeArguments (type);
-               parent = DropGenericTypeArguments (parent);
+               type = type.GetDefinition (); // DropGenericTypeArguments (type);
+               parent = parent.GetDefinition (); // DropGenericTypeArguments (parent);
 
                if (IsEqual (type, parent))
                        return false;
 
                type = type.DeclaringType;
                while (type != null) {
-                       if (IsEqual (type, parent))
+                       if (IsEqual (type.GetDefinition (), parent))
                                return true;
 
                        type = type.DeclaringType;
@@ -1603,7 +730,7 @@ namespace Mono.CSharp {
                return false;
        }
 
-       public static bool IsSpecialType (Type t)
+       public static bool IsSpecialType (TypeSpec t)
        {
                return t == arg_iterator_type || t == typed_reference_type;
        }
@@ -1630,15 +757,7 @@ namespace Mono.CSharp {
                if (assembly_internals_vis_attrs.TryGetValue (assembly, out value))
                        return value;
 
-               PredefinedAttribute pa = PredefinedAttributes.Get.InternalsVisibleTo;
-               // HACK: Do very early resolve of SRE type checking
-               if (pa.Type == null)
-                       pa.Resolve (true);
-
-               if (!pa.IsDefined)
-                       return false;
-               
-               object [] attrs = assembly.GetCustomAttributes (pa.Type, false);
+               object[] attrs = assembly.GetCustomAttributes (typeof (InternalsVisibleToAttribute), false);
                if (attrs.Length == 0) {
                        assembly_internals_vis_attrs.Add (assembly, false);
                        return false;
@@ -1647,6 +766,9 @@ namespace Mono.CSharp {
                bool is_friend = false;
 
                AssemblyName this_name = CodeGen.Assembly.Name;
+               if (this_name == null)
+                       return false;
+
                byte [] this_token = this_name.GetPublicKeyToken ();
                foreach (InternalsVisibleToAttribute attr in attrs) {
                        if (attr.AssemblyName == null || attr.AssemblyName.Length == 0)
@@ -1698,1247 +820,191 @@ namespace Mono.CSharp {
                        other_name, CodeGen.Assembly.Name.FullName);
        }
 
-        //
-        // Do the right thing when returning the element type of an
-        // array type based on whether we are compiling corlib or not
-        //
-        public static Type GetElementType (Type t)
-        {
-                if (RootContext.StdLib)
-                        return t.GetElementType ();
-                else
-                        return TypeToCoreType (t.GetElementType ());
-        }
+       public static TypeSpec GetElementType (TypeSpec t)
+       {
+               return ((ElementTypeSpec)t).Element;
+       }
 
        /// <summary>
        /// This method is not implemented by MS runtime for dynamic types
        /// </summary>
-       public static bool HasElementType (Type t)
+       public static bool HasElementType (TypeSpec t)
        {
-               return t.IsArray || t.IsPointer || t.IsByRef;
+               return t is ElementTypeSpec;
        }
 
-       public static Type GetEnumUnderlyingType (Type t)
+       static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
+
+       // This is a custom version of Convert.ChangeType() which works
+       // with the TypeBuilder defined types when compiling corlib.
+       public static object ChangeType (object value, TypeSpec targetType, out bool error)
        {
-               t = DropGenericTypeArguments (t);
-               Enum e = LookupTypeContainer (t) as Enum;
-               if (e != null)
-                       return e.UnderlyingType;
+               IConvertible convert_value = value as IConvertible;
+               
+               if (convert_value == null){
+                       error = true;
+                       return null;
+               }
+               
+               //
+               // We cannot rely on build-in type conversions as they are
+               // more limited than what C# supports.
+               // See char -> float/decimal/double conversion
+               //
+               error = false;
+               try {
+                       if (targetType == TypeManager.bool_type)
+                               return convert_value.ToBoolean (nf_provider);
+                       if (targetType == TypeManager.byte_type)
+                               return convert_value.ToByte (nf_provider);
+                       if (targetType == TypeManager.char_type)
+                               return convert_value.ToChar (nf_provider);
+                       if (targetType == TypeManager.short_type)
+                               return convert_value.ToInt16 (nf_provider);
+                       if (targetType == TypeManager.int32_type)
+                               return convert_value.ToInt32 (nf_provider);
+                       if (targetType == TypeManager.int64_type)
+                               return convert_value.ToInt64 (nf_provider);
+                       if (targetType == TypeManager.sbyte_type)
+                               return convert_value.ToSByte (nf_provider);
+
+                       if (targetType == TypeManager.decimal_type) {
+                               if (convert_value.GetType () == typeof (char))
+                                       return (decimal) convert_value.ToInt32 (nf_provider);
+                               return convert_value.ToDecimal (nf_provider);
+                       }
+
+                       if (targetType == TypeManager.double_type) {
+                               if (convert_value.GetType () == typeof (char))
+                                       return (double) convert_value.ToInt32 (nf_provider);
+                               return convert_value.ToDouble (nf_provider);
+                       }
+
+                       if (targetType == TypeManager.float_type) {
+                               if (convert_value.GetType () == typeof (char))
+                                       return (float)convert_value.ToInt32 (nf_provider);
+                               return convert_value.ToSingle (nf_provider);
+                       }
 
-               // TODO: cache it ?
-               FieldInfo fi = GetPredefinedField (t, Enum.UnderlyingValueField, Location.Null, Type.EmptyTypes);
-               if (fi == null)
-                       return TypeManager.int32_type;
+                       if (targetType == TypeManager.string_type)
+                               return convert_value.ToString (nf_provider);
+                       if (targetType == TypeManager.ushort_type)
+                               return convert_value.ToUInt16 (nf_provider);
+                       if (targetType == TypeManager.uint32_type)
+                               return convert_value.ToUInt32 (nf_provider);
+                       if (targetType == TypeManager.uint64_type)
+                               return convert_value.ToUInt64 (nf_provider);
+                       if (targetType == TypeManager.object_type)
+                               return value;
 
-               return TypeToCoreType (fi.FieldType);
+                       error = true;
+               } catch {
+                       error = true;
+               }
+               return null;
        }
-       
+
        /// <summary>
-       ///   Gigantic work around for missing features in System.Reflection.Emit follows.
+       ///   Utility function that can be used to probe whether a type
+       ///   is managed or not.  
        /// </summary>
-       ///
-       /// <remarks>
-       ///   Since System.Reflection.Emit can not return MethodBase.GetParameters
-       ///   for anything which is dynamic, and we need this in a number of places,
-       ///   we register this information here, and use it afterwards.
-       /// </remarks>
-       static public void RegisterMethod (MethodBase mb, AParametersCollection ip)
+       public static bool VerifyUnmanaged (CompilerContext ctx, TypeSpec t, Location loc)
        {
-               method_params.Add (mb, ip);
-       }
+               while (t.IsPointer)
+                       t = GetElementType (t);
 
-       static public void RegisterIndexer (PropertyBuilder pb, AParametersCollection p)
-       {
-               method_params.Add (pb, p);
+               if (IsUnmanagedType (t))
+                       return true;
+
+               ctx.Report.SymbolRelatedToPreviousError (t);
+               ctx.Report.Error (208, loc,
+                       "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
+                       CSharpName (t));
+
+               return false;   
        }
        
-       static public AParametersCollection GetParameterData (MethodBase mb)
+       //
+       // Returns whether the array of memberinfos contains the given method
+       //
+       public static bool ArrayContainsMethod (List<MemberSpec> array, MethodSpec new_method, bool ignoreDeclType)
        {
-               AParametersCollection pd;
-               if (!method_params.TryGetValue (mb, out pd)) {
-#if MS_COMPATIBLE
-                       if (mb.IsGenericMethod && !mb.IsGenericMethodDefinition) {
-                               MethodInfo mi = ((MethodInfo) mb).GetGenericMethodDefinition ();
-                               pd = GetParameterData (mi);
-                               /*
-                               if (mi.IsGenericMethod)
-                                       pd = pd.InflateTypes (mi.GetGenericArguments (), mb.GetGenericArguments ());
-                               else
-                                       pd = pd.InflateTypes (mi.DeclaringType.GetGenericArguments (), mb.GetGenericArguments ());
-                               */
-                               method_params.Add (mb, pd);
-                               return pd;
-                       }
+               AParametersCollection new_args = new_method.Parameters;
 
-                       if (mb.DeclaringType.Assembly == CodeGen.Assembly.Builder) {
-                               throw new InternalErrorException ("Parameters are not registered for method `{0}'",
-                                       TypeManager.CSharpName (mb.DeclaringType) + "." + mb.Name);
-                       }
+               foreach (MethodSpec method in array) {
+                       if (!ignoreDeclType && method.DeclaringType != new_method.DeclaringType)
+                               continue;
 
-                       pd = ParametersImported.Create (mb);
-#else
-                       MethodBase generic = TypeManager.DropGenericMethodArguments (mb);
-                       if (generic != mb) {
-                               pd = TypeManager.GetParameterData (generic);
-                               pd = ParametersImported.Create (pd, mb);
-                       } else {
-                               pd = ParametersImported.Create (mb);
-                       }
-#endif
-                       method_params.Add (mb, pd);
-               }
-               return pd;
-       }
+                       if (method.Name != new_method.Name)
+                               continue;
 
-       public static AParametersCollection GetParameterData (PropertyInfo pi)
-       {
-               AParametersCollection pd;
-               if (!method_params.TryGetValue (pi, out pd)) {
-                       if (pi is PropertyBuilder)
-                               return ParametersCompiled.EmptyReadOnlyParameters;
+                       if (!TypeSpecComparer.Override.IsEqual (method.ReturnType, new_method.ReturnType))
+                               continue;
 
-                       ParameterInfo [] p = pi.GetIndexParameters ();
-                       if (p == null)
-                               return ParametersCompiled.EmptyReadOnlyParameters;
+                       AParametersCollection old_args = method.Parameters;
+                       int old_count = old_args.Count;
+                       int i;
+
+                       if (new_args.Count != old_count)
+                               continue;
+
+                       for (i = 0; i < old_count; i++) {
+                               if (!TypeSpecComparer.Override.IsEqual (old_args.Types[i], new_args.Types[i]))
+                                       break;
+                       }
+                       if (i != old_count)
+                               continue;
 
-                       pd = ParametersImported.Create (p, null);
-                       method_params.Add (pi, pd);
+                       return true;
                }
 
-               return pd;
+               return false;
        }
-
-       public static AParametersCollection GetDelegateParameters (ResolveContext ec, Type t)
+#region Generics
+       // This method always return false for non-generic compiler,
+       // while Type.IsGenericParameter is returned if it is supported.
+       public static bool IsGenericParameter (TypeSpec type)
        {
-               Delegate d = LookupDelegate (t);
-               if (d != null)
-                       return d.Parameters;
-
-               var invoke_mb = Delegate.GetInvokeMethod (ec.Compiler, t, t);
-               return invoke_mb.Parameters;
+               return type.IsGenericParameter;
        }
 
-       static public void RegisterOverride (MethodBase override_method, MethodBase base_method)
+       public static bool IsGenericType (TypeSpec type)
        {
-               if (!method_overrides.ContainsKey (override_method))
-                       method_overrides [override_method] = base_method;
-               if (method_overrides [override_method] != base_method)
-                       throw new InternalErrorException ("Override mismatch: " + override_method);
+               return type.IsGeneric;
        }
 
-       static public bool IsOverride (MethodSpec ms)
+       // TODO: Implement correctly
+       public static bool ContainsGenericParameters (TypeSpec type)
        {
-               MethodBase m = ms.MetaInfo;
-               m = DropGenericMethodArguments (m);
-
-               return m.IsVirtual &&
-                       (m.Attributes & MethodAttributes.NewSlot) == 0 &&
-                       (m is MethodBuilder || method_overrides.ContainsKey (m));
+               return type.GetMetaInfo ().ContainsGenericParameters;
        }
 
-       static public MethodBase TryGetBaseDefinition (MethodBase m)
+       public static bool IsEqual (TypeSpec a, TypeSpec b)
        {
-               m = DropGenericMethodArguments (m);
-               MethodBase mb;
-               if (method_overrides.TryGetValue (m, out mb))
-                       return mb;
+               return a == b && !(a is InternalType);
+       }
 
-               return null;
+       public static TypeSpec[] GetTypeArguments (TypeSpec t)
+       {
+               // TODO: return empty array !!
+               return t.TypeArguments;
        }
 
-       public static void RegisterConstant (FieldInfo fb, ConstSpec ic)
+       /// <summary>
+       ///   Check whether `type' and `parent' are both instantiations of the same
+       ///   generic type.  Note that we do not check the type parameters here.
+       /// </summary>
+       public static bool IsInstantiationOfSameGenericType (TypeSpec type, TypeSpec parent)
        {
-               fields.Add (fb, ic);
+               return type == parent || type.MemberDefinition == parent.MemberDefinition;
        }
 
-       public static ConstSpec GetConstant (FieldInfo fb)
+       public static bool IsNullableType (TypeSpec t)
        {
-               if (fb == null)
-                       return null;
-
-               ConstSpec ic;
-               if (fields.TryGetValue (fb, out ic))
-                       return ic;
-
-               return null;
-       }
-
-       public static void RegisterProperty (PropertyInfo pi, PropertyBase pb)
-       {
-               propertybuilder_to_property.Add (pi, pb);
-       }
-
-       public static PropertyBase GetProperty (PropertyInfo pi)
-       {
-               PropertyBase pb;
-               if (propertybuilder_to_property.TryGetValue (pi, out pb))
-                       return pb;
-
-               return null;
-       }
-
-       static public void RegisterFieldBase (FieldBuilder fb, FieldBase f)
-       {
-               fieldbuilders_to_fields.Add (fb, f);
-       }
-
-       //
-       // The return value can be null;  This will be the case for
-       // auxiliary FieldBuilders created by the compiler that have no
-       // real field being declared on the source code
-       //
-       static public FieldBase GetField (FieldInfo fb)
-       {
-               return GetFieldCore (GetGenericFieldDefinition (fb));
-       }
-
-       static public FieldBase GetFieldCore (FieldInfo fb)
-       {
-               FieldBase f;
-               if (fieldbuilders_to_fields.TryGetValue (fb, out f))
-                       return f;
-
-               return null;
-       }
-
-       static public MethodInfo GetAddMethod (EventInfo ei)
-       {
-               if (ei is MyEventBuilder) {
-                       return ((MyEventBuilder)ei).GetAddMethod (true);
-               }
-               return ei.GetAddMethod (true);
-       }
-
-       static public MethodInfo GetRemoveMethod (EventInfo ei)
-       {
-               if (ei is MyEventBuilder) {
-                       return ((MyEventBuilder)ei).GetRemoveMethod (true);
-               }
-               return ei.GetRemoveMethod (true);
-       }
-
-       static public void RegisterEventField (EventInfo einfo, EventSpec e)
-       {
-               if (events == null)
-                       events = new Dictionary<EventInfo, EventSpec> (ReferenceEquality<EventInfo>.Default);
-
-               events.Add (einfo, e);
-       }
-
-       static public EventSpec GetEventField (EventInfo ei)
-       {
-               if (events == null)
-                       return null;
-
-               EventSpec value;
-               if (events.TryGetValue (ei, out value))
-                       return value;
-
-               return null;
-       }
-
-       public static bool CheckStructCycles (TypeContainer tc, Dictionary<TypeContainer, object> seen)
-       {
-               var hash = new Dictionary<TypeContainer, object> ();
-               return CheckStructCycles (tc, seen, hash);
-       }
-
-       public static bool CheckStructCycles (TypeContainer tc, Dictionary<TypeContainer, object> seen,
-                                                 Dictionary<TypeContainer, object> hash)
-       {
-               if ((tc.Kind != MemberKind.Struct) || IsBuiltinType (tc.TypeBuilder))
-                       return true;
-
-               //
-               // `seen' contains all types we've already visited.
-               //
-               if (seen.ContainsKey (tc))
-                       return true;
-               seen.Add (tc, null);
-
-               if (tc.Fields == null)
-                       return true;
-
-               foreach (FieldBase field in tc.Fields) {
-                       if (field.Spec == null || field.Spec.IsStatic)
-                               continue;
-
-                       Type ftype = field.Spec.FieldType;
-                       TypeContainer ftc = LookupTypeContainer (ftype);
-                       if (ftc == null)
-                               continue;
-
-                       if (hash.ContainsKey (ftc)) {
-                               tc.Compiler.Report.Error (523, tc.Location,
-                                             "Struct member `{0}.{1}' of type `{2}' " +
-                                             "causes a cycle in the struct layout",
-                                             tc.Name, field.Name, ftc.Name);
-                               return false;
-                       }
-
-                       //
-                       // `hash' contains all types in the current path.
-                       //
-                       hash.Add (tc, null);
-
-                       bool ok = CheckStructCycles (ftc, seen, hash);
-
-                       hash.Remove (tc);
-
-                       if (!ok)
-                               return false;
-
-                       if (!seen.ContainsKey (ftc))
-                               seen.Add (ftc, null);
-               }
-
-               return true;
-       }
-
-       /// <summary>
-       ///   Given an array of interface types, expand and eliminate repeated ocurrences
-       ///   of an interface.  
-       /// </summary>
-       ///
-       /// <remarks>
-       ///   This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
-       ///   be IA, IB, IC.
-       /// </remarks>
-       public static Type[] ExpandInterfaces (TypeExpr [] base_interfaces)
-       {
-               var new_ifaces = new List<Type> ();
-
-               foreach (TypeExpr iface in base_interfaces){
-                       Type itype = iface.Type;
-
-                       if (new_ifaces.Contains (itype))
-                               continue;
-
-                       new_ifaces.Add (itype);
-                       
-                       Type [] implementing = GetInterfaces (itype);
-
-                       foreach (Type imp in implementing){
-                               if (!new_ifaces.Contains (imp))
-                                       new_ifaces.Add (imp);
-                       }
-               }
-
-               return new_ifaces.ToArray ();
-       }
-
-       public static Type[] ExpandInterfaces (Type [] base_interfaces)
-       {
-               var new_ifaces = new List<Type> ();
-
-               foreach (Type itype in base_interfaces){
-                       if (new_ifaces.Contains (itype))
-                               continue;
-
-                       new_ifaces.Add (itype);
-                       
-                       Type [] implementing = GetInterfaces (itype);
-
-                       foreach (Type imp in implementing){
-                               if (!new_ifaces.Contains (imp))
-                                       new_ifaces.Add (imp);
-                       }
-               }
-
-               return new_ifaces.ToArray ();
-       }
-               
-       /// <summary>
-       ///   This function returns the interfaces in the type `t'.  Works with
-       ///   both types and TypeBuilders.
-       /// </summary>
-       public static Type [] GetInterfaces (Type t)
-       {
-               Type [] cached;
-               if (iface_cache.TryGetValue (t, out cached))
-               if (cached != null)
-                       return cached;
-               
-               //
-               // The reason for catching the Array case is that Reflection.Emit
-               // will not return a TypeBuilder for Array types of TypeBuilder types,
-               // but will still throw an exception if we try to call GetInterfaces
-               // on the type.
-               //
-               // Since the array interfaces are always constant, we return those for
-               // the System.Array
-               //
-               
-               if (t.IsArray)
-                       t = TypeManager.array_type;
-               
-               if ((t is TypeBuilder) || IsGenericType (t)) {
-                       Type [] base_ifaces;
-                       
-                       if (t.BaseType == null)
-                               base_ifaces = Type.EmptyTypes;
-                       else
-                               base_ifaces = GetInterfaces (t.BaseType);
-                       Type[] type_ifaces;
-                       if (IsGenericType (t))
-#if MS_COMPATIBLE
-                               type_ifaces = t.GetGenericTypeDefinition().GetInterfaces ();
-#else
-                               type_ifaces = t.GetInterfaces ();
-#endif
-                       else
-                               type_ifaces = GetExplicitInterfaces (t);
-                       if (type_ifaces == null || type_ifaces.Length == 0)
-                               type_ifaces = Type.EmptyTypes;
-
-                       int base_count = base_ifaces.Length;
-                       Type [] result = new Type [base_count + type_ifaces.Length];
-                       base_ifaces.CopyTo (result, 0);
-                       type_ifaces.CopyTo (result, base_count);
-
-                       iface_cache [t] = result;
-                       return result;
-               } else if (t is GenericTypeParameterBuilder){
-                       Type[] type_ifaces = GetExplicitInterfaces (t);
-                       if (type_ifaces == null || type_ifaces.Length == 0)
-                               type_ifaces = Type.EmptyTypes;
-
-                       iface_cache [t] = type_ifaces;
-                       return type_ifaces;
-               } else {
-                       Type[] ifaces = t.GetInterfaces ();
-                       iface_cache [t] = ifaces;
-                       return ifaces;
-               }
-       }
-       
-       //
-       // gets the interfaces that are declared explicitly on t
-       //
-       public static Type[] GetExplicitInterfaces (Type t)
-       {
-               Type[] ifaces;
-               if (builder_to_ifaces.TryGetValue (t, out ifaces))
-                       return ifaces;
-
-               return null;
-       }
-       
-       /// <remarks>
-       ///  The following is used to check if a given type implements an interface.
-       ///  The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
-       /// </remarks>
-       public static bool ImplementsInterface (Type t, Type iface)
-       {
-               Type [] interfaces;
-
-               //
-               // FIXME OPTIMIZATION:
-               // as soon as we hit a non-TypeBuiler in the interface
-               // chain, we could return, as the `Type.GetInterfaces'
-               // will return all the interfaces implement by the type
-               // or its bases.
-               //
-               do {
-                       interfaces = GetInterfaces (t);
-
-                       if (interfaces != null){
-                               foreach (Type i in interfaces){
-                                       if (i == iface || IsVariantOf (i, iface))
-                                               return true;
-                               }
-                       }
-                       
-                       t = t.BaseType;
-               } while (t != null);
-               
-               return false;
-       }
-
-       static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
-
-       // This is a custom version of Convert.ChangeType() which works
-       // with the TypeBuilder defined types when compiling corlib.
-       public static object ChangeType (object value, Type conversionType, out bool error)
-       {
-               IConvertible convert_value = value as IConvertible;
-               
-               if (convert_value == null){
-                       error = true;
-                       return null;
-               }
-               
-               //
-               // NOTE 1:
-               // We must use Type.Equals() here since `conversionType' is
-               // the TypeBuilder created version of a system type and not
-               // the system type itself.  You cannot use Type.GetTypeCode()
-               // on such a type - it'd always return TypeCode.Object.
-               //
-               // NOTE 2:
-               // We cannot rely on build-in type conversions as they are
-               // more limited than what C# supports.
-               // See char -> float/decimal/double conversion
-               //
-
-               error = false;
-               try {
-                       if (conversionType.Equals (typeof (Boolean)))
-                               return (object)(convert_value.ToBoolean (nf_provider));
-                       if (conversionType.Equals (typeof (Byte)))
-                               return (object)(convert_value.ToByte (nf_provider));
-                       if (conversionType.Equals (typeof (Char)))
-                               return (object)(convert_value.ToChar (nf_provider));
-                       if (conversionType.Equals (typeof (DateTime)))
-                               return (object)(convert_value.ToDateTime (nf_provider));
-
-                       if (conversionType.Equals (decimal_type)) {
-                               if (convert_value.GetType () == TypeManager.char_type)
-                                       return (decimal)convert_value.ToInt32 (nf_provider);
-                               return convert_value.ToDecimal (nf_provider);
-                       }
-
-                       if (conversionType.Equals (typeof (Double))) {
-                               if (convert_value.GetType () == TypeManager.char_type)
-                                       return (double)convert_value.ToInt32 (nf_provider);
-                               return convert_value.ToDouble (nf_provider);
-                       }
-
-                       if (conversionType.Equals (typeof (Int16)))
-                               return (object)(convert_value.ToInt16 (nf_provider));
-                       if (conversionType.Equals (int32_type))
-                               return (object)(convert_value.ToInt32 (nf_provider));
-                       if (conversionType.Equals (int64_type))
-                               return (object)(convert_value.ToInt64 (nf_provider));
-                       if (conversionType.Equals (typeof (SByte)))
-                               return (object)(convert_value.ToSByte (nf_provider));
-
-                       if (conversionType.Equals (typeof (Single))) {
-                               if (convert_value.GetType () == TypeManager.char_type)
-                                       return (float)convert_value.ToInt32 (nf_provider);
-                               return convert_value.ToSingle (nf_provider);
-                       }
-
-                       if (conversionType.Equals (typeof (String)))
-                               return (object)(convert_value.ToString (nf_provider));
-                       if (conversionType.Equals (typeof (UInt16)))
-                               return (object)(convert_value.ToUInt16 (nf_provider));
-                       if (conversionType.Equals (typeof (UInt32)))
-                               return (object)(convert_value.ToUInt32 (nf_provider));
-                       if (conversionType.Equals (typeof (UInt64)))
-                               return (object)(convert_value.ToUInt64 (nf_provider));
-                       if (conversionType.Equals (typeof (Object)))
-                               return (object)(value);
-                       else 
-                               error = true;
-               } catch {
-                       error = true;
-               }
-               return null;
-       }
-
-       //
-       // When compiling with -nostdlib and the type is imported from an external assembly
-       // SRE uses "wrong" type and we have to convert it to the right compiler instance.
-       //
-       public static Type TypeToCoreType (Type t)
-       {
-               if (RootContext.StdLib || t.Module != typeof (object).Module)
-                       return t;
-                       
-               // TODO: GetTypeCode returns underlying type for enums !!
-               TypeCode tc = Type.GetTypeCode (t);
-
-               switch (tc){
-               case TypeCode.Boolean:
-                       return TypeManager.bool_type;
-               case TypeCode.Byte:
-                       return TypeManager.byte_type;
-               case TypeCode.SByte:
-                       return TypeManager.sbyte_type;
-               case TypeCode.Char:
-                       return TypeManager.char_type;
-               case TypeCode.Int16:
-                       return TypeManager.short_type;
-               case TypeCode.UInt16:
-                       return TypeManager.ushort_type;
-               case TypeCode.Int32:
-                       return TypeManager.int32_type;
-               case TypeCode.UInt32:
-                       return TypeManager.uint32_type;
-               case TypeCode.Int64:
-                       return TypeManager.int64_type;
-               case TypeCode.UInt64:
-                       return TypeManager.uint64_type;
-               case TypeCode.Single:
-                       return TypeManager.float_type;
-               case TypeCode.Double:
-                       return TypeManager.double_type;
-               case TypeCode.String:
-                       return TypeManager.string_type;
-               case TypeCode.Decimal:
-                       return TypeManager.decimal_type;
-               }
-
-               if (t == typeof (void))
-                       return TypeManager.void_type;
-               if (t == typeof (object))
-                       return TypeManager.object_type;
-               if (t == typeof (System.Type))
-                       return TypeManager.type_type;
-               if (t == typeof (System.IntPtr))
-                       return TypeManager.intptr_type;
-               if (t == typeof (System.UIntPtr))
-                       return TypeManager.uintptr_type;
-
-               if (t.IsArray) {
-                       int dim = t.GetArrayRank ();
-                       t = GetElementType (t);
-                       return t.MakeArrayType (dim);
-               }
-               if (t.IsByRef) {
-                       t = GetElementType (t);
-                       return t.MakeByRefType ();
-               }
-               if (t.IsPointer) {
-                       t = GetElementType (t);
-                       return t.MakePointerType ();
-               }
-
-               return t;
-       }
-
-       //
-       // Converts any type to reflection supported type
-       //
-       public static Type TypeToReflectionType (Type type)
-       {
-               // TODO: Very lame and painful, GetReference () is enough for mcs-cecil
-               if (IsDynamicType (type))
-                       return object_type;
-
-               if (type is DynamicArrayType)
-                       return type.UnderlyingSystemType;
-
-               return type;
-       }
-
-       /// <summary>
-       ///   Utility function that can be used to probe whether a type
-       ///   is managed or not.  
-       /// </summary>
-       public static bool VerifyUnmanaged (CompilerContext ctx, Type t, Location loc)
-       {
-               if (IsUnmanagedType (t))
-                       return true;
-
-               while (t.IsPointer)
-                       t = GetElementType (t);
-
-               ctx.Report.SymbolRelatedToPreviousError (t);
-               ctx.Report.Error (208, loc,
-                       "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
-                       CSharpName (t));
-
-               return false;   
-       }
-       
-       /// <summary>
-       ///   Returns the name of the indexer in a given type.
-       /// </summary>
-       /// <remarks>
-       ///   The default is not always `Item'.  The user can change this behaviour by
-       ///   using the IndexerNameAttribute in the container.
-       ///   For example, the String class indexer is named `Chars' not `Item' 
-       /// </remarks>
-       public static string IndexerPropertyName (Type t)
-       {
-               t = DropGenericTypeArguments (t);
-               if (t is TypeBuilder) {
-                       TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
-                       return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
-               }
-
-               PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
-               if (pa.IsDefined) {
-                       System.Attribute attr = System.Attribute.GetCustomAttribute (
-                               t, pa.Type);
-                       if (attr != null) {
-                               DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
-                               return dma.MemberName;
-                       }
-               }
-
-               return TypeContainer.DefaultIndexerName;
-       }
-
-       private static bool IsSignatureEqual (Type a, Type b)
-       {
-               ///
-               /// Consider the following example (bug #77674):
-               ///
-               ///     public abstract class A
-               ///     {
-               ///        public abstract T Foo<T> ();
-               ///     }
-               ///
-               ///     public abstract class B : A
-               ///     {
-               ///        public override U Foo<T> ()
-               ///        { return default (U); }
-               ///     }
-               ///
-               /// Here, `T' and `U' are method type parameters from different methods
-               /// (A.Foo and B.Foo), so both `==' and Equals() will fail.
-               ///
-               /// However, since we're determining whether B.Foo() overrides A.Foo(),
-               /// we need to do a signature based comparision and consider them equal.
-
-               if (a == b)
-                       return true;
-
-               if (a.IsGenericParameter && b.IsGenericParameter &&
-                   (a.DeclaringMethod != null) && (b.DeclaringMethod != null)) {
-                       return a.GenericParameterPosition == b.GenericParameterPosition;
-               }
-
-               if (a.IsArray && b.IsArray) {
-                       if (a.GetArrayRank () != b.GetArrayRank ())
-                               return false;
-
-                       return IsSignatureEqual (GetElementType (a), GetElementType (b));
-               }
-
-               if (a.IsByRef && b.IsByRef)
-                       return IsSignatureEqual (GetElementType (a), GetElementType (b));
-
-               if (IsGenericType (a) && IsGenericType (b)) {
-                       if (DropGenericTypeArguments (a) != DropGenericTypeArguments (b))
-                               return false;
-
-                       Type[] aargs = GetTypeArguments (a);
-                       Type[] bargs = GetTypeArguments (b);
-
-                       if (aargs.Length != bargs.Length)
-                               return false;
-
-                       for (int i = 0; i < aargs.Length; i++) {
-                               if (!IsSignatureEqual (aargs [i], bargs [i]))
-                                       return false;
-                       }
-
-                       return true;
-               }
-
-               return false;
-       }
-
-       //
-       // Returns whether the array of memberinfos contains the given method
-       //
-       public static bool ArrayContainsMethod (MethodBase [] array, MethodBase new_method, bool ignoreDeclType)
-       {
-               Type [] new_args = TypeManager.GetParameterData (new_method).Types;
-               
-               foreach (MethodBase method in array) {
-                       if (!ignoreDeclType && method.DeclaringType != new_method.DeclaringType)
-                               continue;
-               
-                       if (method.Name != new_method.Name)
-                               continue;
-
-                       if (method is MethodInfo && new_method is MethodInfo &&
-                               !IsSignatureEqual (
-                                       TypeToCoreType (((MethodInfo) method).ReturnType),
-                                       TypeToCoreType (((MethodInfo) new_method).ReturnType)))
-                               continue;
-                        
-                       Type [] old_args = TypeManager.GetParameterData (method).Types;
-                       int old_count = old_args.Length;
-                       int i;
-                       
-                       if (new_args.Length != old_count)
-                               continue;
-                       
-                       for (i = 0; i < old_count; i++){
-                               if (!IsSignatureEqual (old_args [i], new_args [i]))
-                                       break;
-                       }
-                       if (i != old_count)
-                               continue;
-
-                       return true;
-               }
-                
-               return false;
-       }
-       
-       //
-       // We copy methods from `new_members' into `target_list' if the signature
-       // for the method from in the new list does not exist in the target_list
-       //
-       // The name is assumed to be the same.
-       //
-       public static List<MethodBase> CopyNewMethods (List<MethodBase> target_list, IList<MemberInfo> new_members)
-       {
-               if (target_list == null){
-                       target_list = new List<MethodBase> ();
-
-                       foreach (MemberInfo mi in new_members){
-                               if (mi is MethodBase)
-                                       target_list.Add ((MethodBase) mi);
-                       }
-                       return target_list;
-               }
-
-               MethodBase[] target_array = new MethodBase[target_list.Count];
-               target_list.CopyTo (target_array, 0);
-               
-               foreach (MemberInfo mi in new_members){
-                       MethodBase new_method = (MethodBase) mi;
-                       
-                       if (!ArrayContainsMethod (target_array, new_method, true))
-                               target_list.Add (new_method);
-               }
-               return target_list;
-       }
-
-#region Generics
-       // <remarks>
-       //   Tracks the generic parameters.
-       // </remarks>
-
-       public static void AddTypeParameter (GenericTypeParameterBuilder t, TypeParameter tparam)
-       {
-               builder_to_type_param [t] = tparam;
-       }
-
-       public static TypeParameter LookupTypeParameter (Type t)
-       {
-               TypeParameter tp;
-               var gtp = t as GenericTypeParameterBuilder;
-               if (gtp != null && builder_to_type_param.TryGetValue (gtp, out tp))
-                       return tp;
-
-               return null;
-       }
-
-       // This method always return false for non-generic compiler,
-       // while Type.IsGenericParameter is returned if it is supported.
-       public static bool IsGenericParameter (Type type)
-       {
-               return type.IsGenericParameter;
-       }
-
-       public static int GenericParameterPosition (Type type)
-       {
-               return type.GenericParameterPosition;
-       }
-
-       public static bool IsGenericType (Type type)
-       {
-               return type.IsGenericType;
-       }
-
-       public static bool IsGenericTypeDefinition (Type type)
-       {
-               return type.IsGenericTypeDefinition;
-       }
-
-       public static bool ContainsGenericParameters (Type type)
-       {
-               return type.ContainsGenericParameters;
-       }
-
-       public static FieldInfo GetGenericFieldDefinition (FieldInfo fi)
-       {
-               if (fi.DeclaringType.IsGenericTypeDefinition ||
-                   !fi.DeclaringType.IsGenericType)
-                       return fi;
-
-               Type t = fi.DeclaringType.GetGenericTypeDefinition ();
-               BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
-                       BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
-
-               // TODO: use CodeGen.Module.Builder.ResolveField (fi.MetadataToken);
-               foreach (FieldInfo f in t.GetFields (bf))
-                       if (f.MetadataToken == fi.MetadataToken)
-                               return f;
-
-               return fi;
-       }
-
-       public static bool IsEqual (Type a, Type b)
-       {
-               if (a.Equals (b)) {
-                       // MS BCL returns true even if enum types are different
-                       if (a.BaseType == TypeManager.enum_type || b.BaseType == TypeManager.enum_type)
-                               return a.FullName == b.FullName;
-
-                       // Some types are never equal
-                       if (a == TypeManager.null_type || a == InternalType.AnonymousMethod)
-                               return false;
-
-                       return true;
-               }
-
-               if (IsGenericParameter (a) && IsGenericParameter (b)) {
-                       // TODO: needs more testing before cleaning up
-                       //if (a.DeclaringMethod != b.DeclaringMethod &&
-                       //    (a.DeclaringMethod == null || b.DeclaringMethod == null))
-                       //      return false;
-                       return a.GenericParameterPosition == b.GenericParameterPosition;
-               }
-
-               if (a.IsArray && b.IsArray) {
-                       if (a.GetArrayRank () != b.GetArrayRank ())
-                               return false;
-                       return IsEqual (GetElementType (a), GetElementType (b));
-               }
-
-               if (a.IsByRef && b.IsByRef)
-                       return IsEqual (a.GetElementType (), b.GetElementType ());
-
-               if (IsGenericType (a) && IsGenericType (b)) {
-                       Type adef = DropGenericTypeArguments (a);
-                       Type bdef = DropGenericTypeArguments (b);
-
-                       if (adef != bdef)
-                               return false;
-
-                       if (adef.IsEnum && bdef.IsEnum)
-                               return true;
-
-                       Type[] aargs = GetTypeArguments (a);
-                       Type[] bargs = GetTypeArguments (b);
-
-                       if (aargs.Length != bargs.Length)
-                               return false;
-
-                       for (int i = 0; i < aargs.Length; i++) {
-                               if (!IsEqual (aargs [i], bargs [i]))
-                                       return false;
-                       }
-
-                       return true;
-               }
-
-               return false;
-       }
-
-       public static bool IsEqual (Type[] a, Type[] b)
-       {
-               if (a == null || b == null || a.Length != b.Length)
-                       return false;
-
-               for (int i = 0; i < a.Length; ++i) {
-                       if (a [i] == null || b [i] == null) {
-                               if (a [i] == b [i])
-                                       continue;
-
-                               return false;
-                       }
-               
-                       if (!IsEqual (a [i], b [i]))
-                               return false;
-               }
-
-               return true;
-       }
-
-       public static Type DropGenericTypeArguments (Type t)
-       {
-               if (!t.IsGenericType)
-                       return t;
-               // Micro-optimization: a generic typebuilder is always a generic type definition
-               if (t is TypeBuilder)
-                       return t;
-               return t.GetGenericTypeDefinition ();
-       }
-
-       public static MethodBase DropGenericMethodArguments (MethodSpec m)
-       {
-               return DropGenericMethodArguments (m.MetaInfo);
-       }
-
-       public static MethodBase DropGenericMethodArguments (MethodBase m)
-       {
-               if (m.IsGenericMethod)
-                 m = ((MethodInfo) m).GetGenericMethodDefinition ();
-
-               Type t = m.DeclaringType;
-               if (!t.IsGenericType || t.IsGenericTypeDefinition)
-                       return m;
-
-               t = t.GetGenericTypeDefinition ();
-               BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
-                       BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
-
-#if MS_COMPATIBLE
-               // TODO: use CodeGen.Module.Builder.ResolveMethod ()
-               return m;
-#endif
-
-               if (m is ConstructorInfo) {
-                       foreach (ConstructorInfo c in t.GetConstructors (bf))
-                               if (c.MetadataToken == m.MetadataToken)
-                                       return c;
-               } else {
-                       foreach (MethodBase mb in t.GetMethods (bf))
-                               if (mb.MetadataToken == m.MetadataToken)
-                                       return mb;
-               }
-
-               return m;
-       }
-
-       public static Type[] GetGenericArguments (MethodBase mi)
-       {
-               return mi.GetGenericArguments () ?? Type.EmptyTypes;
-       }
-
-       public static Type[] GetTypeArguments (Type t)
-       {
-               DeclSpace tc = LookupDeclSpace (t);
-               if (tc != null) {
-                       if (!tc.IsGeneric)
-                               return Type.EmptyTypes;
-
-                       TypeParameter[] tparam = tc.TypeParameters;
-                       Type[] ret = new Type [tparam.Length];
-                       for (int i = 0; i < tparam.Length; i++) {
-                               ret [i] = tparam [i].Type;
-                               if (ret [i] == null)
-                                       throw new InternalErrorException ();
-                       }
-
-                       return ret;
-               } else
-                       return t.GetGenericArguments ();
-       }
-                       
-       public static GenericConstraints GetTypeParameterConstraints (Type t)
-       {
-               if (!t.IsGenericParameter)
-                       throw new InvalidOperationException ();
-
-               TypeParameter tparam = LookupTypeParameter (t);
-               if (tparam != null)
-                       return tparam.GenericConstraints;
-
-               return ReflectionConstraints.GetConstraints (t);
-       }
-
-       public static bool HasGenericArguments (Type t)
-       {
-               return GetNumberOfTypeArguments (t) > 0;
-       }
-
-       public static int GetNumberOfTypeArguments (Type t)
-       {
-               if (t.IsGenericParameter)
-                       return 0;
-               DeclSpace tc = LookupDeclSpace (t);
-               if (tc != null)
-                       return tc.IsGeneric ? tc.CountTypeParameters : 0;
-               else
-                       return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
-       }
-
-       /// <summary>
-       ///   Check whether `type' and `parent' are both instantiations of the same
-       ///   generic type.  Note that we do not check the type parameters here.
-       /// </summary>
-       public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
-       {
-               int tcount = GetNumberOfTypeArguments (type);
-               int pcount = GetNumberOfTypeArguments (parent);
-
-               if (tcount != pcount)
-                       return false;
-
-               type = DropGenericTypeArguments (type);
-               parent = DropGenericTypeArguments (parent);
-
-               return type.Equals (parent);
-       }
-
-       /// <summary>
-       ///   Whether `mb' is a generic method definition.
-       /// </summary>
-       public static bool IsGenericMethodDefinition (MethodBase mb)
-       {
-               if (mb.DeclaringType is TypeBuilder) {
-                       IMethodData method = GetMethod (mb);
-                       if (method == null)
-                               return false;
-
-                       return method.GenericMethod != null;
-               }
-
-               return mb.IsGenericMethodDefinition;
-       }
-
-       /// <summary>
-       ///   Whether `mb' is a generic method.
-       /// </summary>
-       public static bool IsGenericMethod (MethodBase mb)
-       {
-               return mb.IsGenericMethod;
-       }
-
-       public static bool IsNullableType (Type t)
-       {
-               return generic_nullable_type == DropGenericTypeArguments (t);
-       }
-
-       public static MethodInfo MakeGenericMethod (MethodInfo gmd, Type[] methodArguments) 
-       {
-               if (!gmd.IsGenericMethodDefinition)
-                       gmd = gmd.GetGenericMethodDefinition ();
-               return gmd.MakeGenericMethod (methodArguments);         
+               return generic_nullable_type == t.GetDefinition ();
        }
 #endregion
 
-#region MemberLookup implementation
-       
-       //
-       // Whether we allow private members in the result (since FindMembers
-       // uses NonPublic for both protected and private), we need to distinguish.
-       //
-
-       internal class Closure {
-               internal bool     private_ok;
-
-               // Who is invoking us and which type is being queried currently.
-               internal Type     invocation_type;
-               internal Type     qualifier_type;
-
-               // The assembly that defines the type is that is calling us
-               internal Assembly invocation_assembly;
-               internal IList<MemberInfo> almost_match;
-
-               private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
-               {
-                       if (invocation_type == null)
-                               return false;
-
-                       if (is_static && qualifier_type == null)
-                               // It resolved from a simple name, so it should be visible.
-                               return true;
-
-                       if (IsNestedChildOf (invocation_type, m.DeclaringType))
-                               return true;
-
-                       for (Type t = invocation_type; t != null; t = t.DeclaringType) {
-                               if (!IsFamilyAccessible (t, m.DeclaringType))
-                                       continue;
-
-                               // Although a derived class can access protected members of its base class
-                               // it cannot do so through an instance of the base class (CS1540).
-                               // => Ancestry should be: declaring_type ->* invocation_type ->*  qualified_type
-                               if (is_static || qualifier_type == null ||
-                                   IsInstantiationOfSameGenericType (t, qualifier_type) ||
-                                   IsFamilyAccessible (qualifier_type, t))
-                                       return true;
-                       }
-
-                       if (almost_match != null)
-                               almost_match.Add (m);
-
-                       return false;
-               }
-               
-               //
-               // This filter filters by name + whether it is ok to include private
-               // members in the search
-               //
-               internal bool Filter (MemberInfo m, object filter_criteria)
-               {
-                       //
-                       // Hack: we know that the filter criteria will always be in the
-                       // `closure' // fields. 
-                       //
-
-                       if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
-                               return false;
-
-                       if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
-                           (invocation_type != null) &&
-                           IsPrivateAccessible (m.DeclaringType, invocation_type))
-                               return true;
-
-                       //
-                       // Ugly: we need to find out the type of `m', and depending
-                       // on this, tell whether we accept or not
-                       //
-                       if (m is MethodBase){
-                               MethodBase mb = (MethodBase) m;
-                               MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
-
-                               if (ma == MethodAttributes.Public)
-                                       return true;
-
-                               if (ma == MethodAttributes.PrivateScope)
-                                       return false;
-
-                               if (ma == MethodAttributes.Private)
-                                       return private_ok ||
-                                               IsPrivateAccessible (invocation_type, m.DeclaringType) ||
-                                               IsNestedChildOf (invocation_type, m.DeclaringType);
-
-                               if (TypeManager.IsThisOrFriendAssembly (invocation_assembly, mb.DeclaringType.Assembly)) {
-                                       if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
-                                               return true;
-                               } else {
-                                       if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
-                                               return false;
-                               }
-
-                               // Family, FamORAssem or FamANDAssem
-                               return CheckValidFamilyAccess (mb.IsStatic, m);
-                       }
-                       
-                       if (m is FieldInfo){
-                               FieldInfo fi = (FieldInfo) m;
-                               FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
-
-                               if (fa == FieldAttributes.Public)
-                                       return true;
-
-                               if (fa == FieldAttributes.PrivateScope)
-                                       return false;
-
-                               if (fa == FieldAttributes.Private)
-                                       return private_ok ||
-                                               IsPrivateAccessible (invocation_type, m.DeclaringType) ||
-                                               IsNestedChildOf (invocation_type, m.DeclaringType);
-
-                               if (TypeManager.IsThisOrFriendAssembly (invocation_assembly, fi.DeclaringType.Assembly)) {
-                                       if ((fa == FieldAttributes.Assembly) ||
-                                           (fa == FieldAttributes.FamORAssem))
-                                               return true;
-                               } else {
-                                       if ((fa == FieldAttributes.Assembly) ||
-                                           (fa == FieldAttributes.FamANDAssem))
-                                               return false;
-                               }
-
-                               // Family, FamORAssem or FamANDAssem
-                               return CheckValidFamilyAccess (fi.IsStatic, m);
-                       }
-
-                       //
-                       // EventInfos and PropertyInfos, return true because they lack
-                       // permission information, so we need to check later on the methods.
-                       //
-                       return true;
-               }
-       }
-
-       static Closure closure;
-       static MemberFilter FilterWithClosure_delegate;
-
        //
        // Looks up a member called `name' in the `queried_type'.  This lookup
        // is done by code that is contained in the definition for `invocation_type'
@@ -2969,485 +1035,31 @@ namespace Mono.CSharp {
        // Returns an array of a single element for everything but Methods/Constructors
        // that might return multiple matches.
        //
-       public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
-                                                 Type queried_type, MemberTypes mt,
-                                                 BindingFlags original_bf, string name, IList<MemberInfo> almost_match)
+       public static IList<MemberSpec> MemberLookup (TypeSpec invocation_type, TypeSpec qualifier_type,
+                                                 TypeSpec queried_type, MemberKind mt,
+                                                 BindingRestriction opt, string name, int arity, IList<MemberSpec> almost_match)
        {
                Timer.StartTimer (TimerType.MemberLookup);
 
-               MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
-                                                       queried_type, mt, original_bf, name, almost_match);
+               var retval = RealMemberLookup (invocation_type, qualifier_type,
+                                                       queried_type, mt, opt, name, arity, almost_match);
 
                Timer.StopTimer (TimerType.MemberLookup);
 
                return retval;
        }
 
-       static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
-                                              Type queried_type, MemberTypes mt,
-                                              BindingFlags original_bf, string name, IList<MemberInfo> almost_match)
-       {
-               BindingFlags bf = original_bf;
-               
-               List<MethodBase> method_list = null;
-               Type current_type = queried_type;
-               bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
-               bool skip_iface_check = true, used_cache = false;
-               bool always_ok_flag = invocation_type != null && IsNestedChildOf (invocation_type, queried_type);
-
-               closure.invocation_type = invocation_type;
-               closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
-               closure.qualifier_type = qualifier_type;
-               closure.almost_match = almost_match;
-
-               // This is from the first time we find a method
-               // in most cases, we do not actually find a method in the base class
-               // so we can just ignore it, and save the arraylist allocation
-               MemberInfo [] first_members_list = null;
-               bool use_first_members_list = false;
-               
-               do {
-                       MemberInfo [] list;
-
-                       //
-                       // `NonPublic' is lame, because it includes both protected and
-                       // private methods, so we need to control this behavior by
-                       // explicitly tracking if a private method is ok or not.
-                       //
-                       // The possible cases are:
-                       //    public, private and protected (internal does not come into the
-                       //    equation)
-                       //
-                       if ((invocation_type != null) &&
-                           ((invocation_type == current_type) ||
-                            IsNestedChildOf (invocation_type, current_type)) ||
-                           always_ok_flag)
-                               bf = original_bf | BindingFlags.NonPublic;
-                       else
-                               bf = original_bf;
-
-                       closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
-
-                       Timer.StopTimer (TimerType.MemberLookup);
-
-                       list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
-
-                       Timer.StartTimer (TimerType.MemberLookup);
-
-                       //
-                       // When queried for an interface type, the cache will automatically check all
-                       // inherited members, so we don't need to do this here.  However, this only
-                       // works if we already used the cache in the first iteration of this loop.
-                       //
-                       // If we used the cache in any further iteration, we can still terminate the
-                       // loop since the cache always looks in all base classes.
-                       //
-
-                       if (used_cache)
-                               searching = false;
-                       else
-                               skip_iface_check = false;
-
-                       if (current_type == TypeManager.object_type)
-                               searching = false;
-                       else {
-                               current_type = current_type.BaseType;
-                               
-                               //
-                               // This happens with interfaces, they have a null
-                               // basetype.  Look members up in the Object class.
-                               //
-                               if (current_type == null) {
-                                       current_type = TypeManager.object_type;
-                                       searching = true;
-                               }
-                       }
-                       
-                       if (list.Length == 0)
-                               continue;
-
-                       //
-                       // Events and types are returned by both `static' and `instance'
-                       // searches, which means that our above FindMembers will
-                       // return two copies of the same.
-                       //
-                       if (list.Length == 1 && !(list [0] is MethodBase)){
-                               return list;
-                       }
-
-                       //
-                       // Multiple properties: we query those just to find out the indexer
-                       // name
-                       //
-                       if (list [0] is PropertyInfo)
-                               return list;
-
-                       //
-                       // We found an event: the cache lookup returns both the event and
-                       // its private field.
-                       //
-                       if (list [0] is EventInfo) {
-                               if ((list.Length == 2) && (list [1] is FieldInfo))
-                                       return new MemberInfo [] { list [0] };
-
-                               return list;
-                       }
-
-                       //
-                       // We found methods, turn the search into "method scan"
-                       // mode.
-                       //
-
-                       if (first_members_list != null) {
-                               if (use_first_members_list) {
-                                       method_list = CopyNewMethods (method_list, first_members_list);
-                                       use_first_members_list = false;
-                               }
-                               
-                               method_list = CopyNewMethods (method_list, list);
-                       } else {
-                               first_members_list = list;
-                               use_first_members_list = true;
-                               mt &= (MemberTypes.Method | MemberTypes.Constructor);
-                       }
-               } while (searching);
-
-               if (use_first_members_list)
-                       return first_members_list;
-
-               if (method_list != null && method_list.Count > 0) {
-                       return method_list.ToArray ();
-               }
-               //
-               // This happens if we already used the cache in the first iteration, in this case
-               // the cache already looked in all interfaces.
-               //
-               if (skip_iface_check)
-                       return null;
-
-               //
-               // Interfaces do not list members they inherit, so we have to
-               // scan those.
-               // 
-               if (!queried_type.IsInterface)
-                       return null;
-
-               if (queried_type.IsArray)
-                       queried_type = TypeManager.array_type;
-               
-               Type [] ifaces = GetInterfaces (queried_type);
-               if (ifaces == null)
-                       return null;
-               
-               foreach (Type itype in ifaces){
-                       MemberInfo [] x;
-
-                       x = MemberLookup (null, null, itype, mt, bf, name, null);
-                       if (x != null)
-                               return x;
-               }
-                                       
-               return null;
-       }
-
-       public const BindingFlags AllMembers = BindingFlags.Public | BindingFlags.NonPublic |
-                                                                       BindingFlags.Static | BindingFlags.Instance | 
-                                                                       BindingFlags.DeclaredOnly;
-
-       // Currently is designed to work with external types only
-       public static PropertyInfo GetPropertyFromAccessor (MethodBase mb)
-       {
-               if (!mb.IsSpecialName)
-                       return null;
-
-               string name = mb.Name;
-               if (name.Length < 5)
-                       return null;
-
-               if (name [3] != '_')
-                       return null;
-
-               if (name.StartsWith ("get") || name.StartsWith ("set")) {
-                       MemberInfo[] pi = mb.DeclaringType.FindMembers (MemberTypes.Property, AllMembers,
-                               Type.FilterName, name.Substring (4));
-
-                       if (pi == null)
-                               return null;
-
-                       // This can happen when property is indexer (it can have same name but different parameters)
-                       foreach (PropertyInfo p in pi) {
-                               foreach (MethodInfo p_mi in p.GetAccessors (true)) {
-                                       if (p_mi == mb || TypeManager.GetParameterData (p_mi).Equals (TypeManager.GetParameterData (mb)))
-                                               return p;
-                               }
-                       }
-               }
-
-               return null;
-       }
-
-       // Currently is designed to work with external types only
-       public static MemberInfo GetEventFromAccessor (MethodBase mb)
-       {
-               if (!mb.IsSpecialName)
-                       return null;
-
-               string name = mb.Name;
-               if (name.Length < 5)
-                       return null;
-
-               if (name.StartsWith ("add_"))
-                       return mb.DeclaringType.GetEvent (name.Substring (4), AllMembers);
-
-               if (name.StartsWith ("remove_"))
-                       return mb.DeclaringType.GetEvent (name.Substring (7), AllMembers);
-
-               return null;
-       }
-
-       // Tests whether external method is really special
-       public static bool IsSpecialMethod (MethodBase mb)
-       {
-               if (!mb.IsSpecialName)
-                       return false;
-
-               IMethodData md = TypeManager.GetMethod (mb);
-               if (md != null) 
-                       return (md is AbstractPropertyEventMethod || md is Operator);
-
-               PropertyInfo pi = GetPropertyFromAccessor (mb);
-               if (pi != null)
-                       return IsValidProperty (pi);
-                               
-               if (GetEventFromAccessor (mb) != null)
-                       return true;
-
-               string name = mb.Name;
-               if (name.StartsWith ("op_"))
-                       return Operator.GetName (name) != null;
-
-               return false;
-       }
-
-       // Tests whether imported property is valid C# property.
-       // TODO: It seems to me that we should do a lot of sanity tests before
-       // we accept property as C# property
-       static bool IsValidProperty (PropertyInfo pi)
+       static IList<MemberSpec> RealMemberLookup (TypeSpec invocation_type, TypeSpec qualifier_type,
+                                                  TypeSpec queried_type, MemberKind mt,
+                                                  BindingRestriction bf, string name, int arity, IList<MemberSpec> almost_match)
        {
-               MethodInfo get_method = pi.GetGetMethod (true);
-               MethodInfo set_method = pi.GetSetMethod (true);
-               int g_count = 0;
-               int s_count = 0;
-               if (get_method != null && set_method != null) {
-                       g_count = get_method.GetParameters ().Length;
-                       s_count = set_method.GetParameters ().Length;
-                       if (g_count + 1 != s_count)
-                               return false;
-               } else if (get_method != null) {
-                       g_count = get_method.GetParameters ().Length;
-               } else if (set_method != null) {
-                       s_count = set_method.GetParameters ().Length;
-               }
-
-               //
-               // DefaultMemberName and indexer name has to match to identify valid C# indexer
-               //
-               PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
-               if ((s_count > 1 || g_count > 0) && pa.IsDefined) {
-                       object[] o = pi.DeclaringType.GetCustomAttributes (pa.Type, false);
-                       if (o.Length == 0)
-                               return false;
-                       
-                       DefaultMemberAttribute dma = (DefaultMemberAttribute) o [0];
-                       if (dma.MemberName != pi.Name)
-                               return false;
-                       if (get_method != null && "get_" + dma.MemberName != get_method.Name)
-                               return false;
-                       if (set_method != null && "set_" + dma.MemberName != set_method.Name)
-                               return false;
+               MemberFilter filter = new MemberFilter (name, arity, mt, null, null);
+               if ((bf & BindingRestriction.AccessibleOnly) != 0) {
+                       filter.InvocationType = invocation_type ?? InternalType.FakeInternalType;
                }
 
-               return true;
-       }
-
-#endregion
-       
+               return MemberCache.FindMembers (queried_type, filter, bf);
+       }       
 }
 
-       class InternalType
-       {
-               public static readonly Type AnonymousMethod = typeof (AnonymousMethodBody);
-               public static readonly Type Arglist = typeof (ArglistAccess);
-               public static readonly Type Dynamic = new DynamicType ();
-               public static readonly Type MethodGroup = typeof (MethodGroupExpr);
-       }
-
-/// <summary>
-///   There is exactly one instance of this class per type.
-/// </summary>
-sealed class TypeHandle : IMemberContainer {
-       public readonly IMemberContainer BaseType;
-
-       readonly int id = ++next_id;
-       static int next_id = 0;
-
-       static TypeHandle ()
-       {
-               Reset ();
-       }
-
-       /// <summary>
-       ///   Lookup a TypeHandle instance for the given type.  If the type doesn't have
-       ///   a TypeHandle yet, a new instance of it is created.  This static method
-       ///   ensures that we'll only have one TypeHandle instance per type.
-       /// </summary>
-       private static TypeHandle GetTypeHandle (Type t)
-       {
-               TypeHandle handle;
-               if (type_hash.TryGetValue (t, out handle))
-                       return handle;
-
-               handle = new TypeHandle (t);
-               type_hash.Add (t, handle);
-               return handle;
-       }
-
-       public static MemberCache GetMemberCache (Type t)
-       {
-               return GetTypeHandle (t).MemberCache;
-       }
-       
-       public static void CleanUp ()
-       {
-               type_hash = null;
-       }
-
-       public static void Reset ()
-       {
-               type_hash = new Dictionary<Type, TypeHandle> (ReferenceEquality<Type>.Default);
-       }
-
-       /// <summary>
-       ///   Returns the TypeHandle for TypeManager.object_type.
-       /// </summary>
-       public static IMemberContainer ObjectType {
-               get {
-                       if (object_type != null)
-                               return object_type;
-
-                       object_type = GetTypeHandle (TypeManager.object_type);
-
-                       return object_type;
-               }
-       }
-
-       /// <summary>
-       ///   Returns the TypeHandle for TypeManager.array_type.
-       /// </summary>
-       public static TypeHandle ArrayType {
-               get {
-                       if (array_type != null)
-                               return array_type;
-
-                       array_type = GetTypeHandle (TypeManager.array_type);
-
-                       return array_type;
-               }
-       }
-
-       static Dictionary<Type, TypeHandle> type_hash;
-
-       private static TypeHandle object_type;
-       private static TypeHandle array_type;
-
-       private Type type;
-       private string full_name;
-       private bool is_interface;
-       private MemberCache member_cache;
-       private MemberCache base_cache;
-
-       private TypeHandle (Type type)
-       {
-               this.type = type;
-               full_name = type.FullName != null ? type.FullName : type.Name;
-               if (type.BaseType != null) {
-                       base_cache = TypeManager.LookupMemberCache (type.BaseType);
-                       BaseType = base_cache.Container;
-               } else if (type.IsInterface)
-                       base_cache = TypeManager.LookupBaseInterfacesCache (type);
-               this.is_interface = type.IsInterface || TypeManager.IsGenericParameter (type);
-               this.member_cache = new MemberCache (this);
-       }
-
-       // IMemberContainer methods
-
-       public string Name {
-               get {
-                       return full_name;
-               }
-       }
-
-       public Type Type {
-               get {
-                       return type;
-               }
-       }
-
-       public MemberCache BaseCache {
-               get {
-                       return base_cache;
-               }
-       }
-
-       public bool IsInterface {
-               get {
-                       return is_interface;
-               }
-       }
-
-       public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
-       {
-               MemberInfo [] members;
-
-               if (type is GenericTypeParameterBuilder)
-                       return MemberList.Empty;
-
-#if MS_COMPATIBLE
-               type = TypeManager.DropGenericTypeArguments (type);
-#endif
-               if (mt == MemberTypes.Event)
-                       members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
-               else
-                       members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
-                                                                               null, null);
-
-               if (members.Length == 0)
-                       return MemberList.Empty;
-
-               Array.Reverse (members);
-               return new MemberList (members);
-       }
-
-       // IMemberFinder methods
-
-       public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
-                                      MemberFilter filter, object criteria)
-       {
-               return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
-       }
-
-       public MemberCache MemberCache {
-               get {
-                       return member_cache;
-               }
-       }
-
-       public override string ToString ()
-       {
-               if (BaseType != null)
-                       return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
-               else
-                       return "TypeHandle (" + id + "," + Name + ")";
-       }
-}
 }
index 641e37707edcfd092597ffc06913e1c588590e55..2a4b8a06bad466ffe48cbad1d1739a31263082b3 100644 (file)
 
 using System;
 using System.Collections.Generic;
+using System.Text;
+using System.Linq;
 
 namespace Mono.CSharp
 {
        public class TypeSpec : MemberSpec
        {
-               Type info;
+               protected Type info;
                protected MemberCache cache;
+               protected IList<TypeSpec> ifaces;
+               TypeSpec base_type;
 
-               public TypeSpec (MemberKind kind, ITypeDefinition definition, Type info, string name, Modifiers modifiers)
-                       : base (kind, definition, name, modifiers)
+               Dictionary<TypeSpec[], InflatedTypeSpec> inflated_instances;
+
+               public static readonly TypeSpec[] EmptyTypes = new TypeSpec[0];
+
+               // Reflection Emit hacking
+               static Type TypeBuilder;
+               static Type GenericTypeBuilder;
+
+               static TypeSpec ()
+               {
+                       var assembly = typeof (object).Assembly;
+                       TypeBuilder = assembly.GetType ("System.Reflection.Emit.TypeBuilder");
+                       GenericTypeBuilder = assembly.GetType ("System.Reflection.MonoGenericClass");
+                       if (GenericTypeBuilder == null)
+                               GenericTypeBuilder = assembly.GetType ("System.Reflection.Emit.TypeBuilderInstantiation");
+               }
+
+               public TypeSpec (MemberKind kind, TypeSpec declaringType, ITypeDefinition definition, Type info, Modifiers modifiers)
+                       : base (kind, declaringType, definition, modifiers)
                {
+                       this.declaringType = declaringType;
                        this.info = info;
+
+                       if (definition != null && definition.TypeParametersCount > 0)
+                               state |= StateFlags.IsGeneric;
+               }
+
+               #region Properties
+
+               public override int Arity {
+                       get {
+                               return MemberDefinition.TypeParametersCount;
+                       }
+               }
+
+               public virtual TypeSpec BaseType {
+                       get {
+                               return base_type;
+                       }
+                       set {
+                               base_type = value;
+                       }
+               }
+
+               public virtual IList<TypeSpec> Interfaces {
+                       get {
+                               return ifaces;
+                       }
+                       set {
+                               ifaces = value;
+                       }
+               }
+
+               public bool IsArray {
+                       get { return this is ArrayContainer; }
+               }
+
+               public bool IsAttribute {
+                       get {
+                               if (!IsClass)
+                                       return false;
+
+                               var type = this;
+                               do {
+                                       if (type.IsGeneric)
+                                               return false;
+
+                                       if (type == TypeManager.attribute_type)
+                                               return true;
+                                       
+                                       type = type.base_type;
+                               } while (type != null);
+
+                               return false;
+                       }
+               }
+
+               public bool IsInterface {
+                       get {
+                               return Kind == MemberKind.Interface;
+                       }
+               }
+
+               public bool IsClass {
+                       get {
+                               return Kind == MemberKind.Class;
+                       }
+               }
+
+               public bool IsConstantCompatible {
+                       get {
+                               if ((Kind & (MemberKind.Enum | MemberKind.Class | MemberKind.Interface | MemberKind.Delegate)) != 0)
+                                       return true;
+
+                               return TypeManager.IsPrimitiveType (this) || this == TypeManager.decimal_type || this == InternalType.Dynamic;
+                       }
+               }
+
+               public bool IsDelegate {
+                       get {
+                               return Kind == MemberKind.Delegate;
+                       }
                }
 
-               public TypeSpec BaseType { get; set; }
+               public bool IsEnum {
+                       get { return Kind == MemberKind.Enum; }
+               }
+
+               // TODO: Should probably do
+               // IsGenericType -- recursive
+               // HasTypeParameter -- non-recursive
+               public bool IsGenericOrParentIsGeneric {
+                       get {
+                               var ts = this;
+                               do {
+                                       if (ts.IsGeneric)
+                                               return true;
+                                       ts = ts.declaringType;
+                               } while (ts != null);
+
+                               return false;
+                       }
+               }
+
+               public bool IsGenericParameter {
+                       get { return Kind == MemberKind.TypeParameter; }
+               }
+
+               public bool IsNested {
+                       get { return declaringType != null && Kind != MemberKind.TypeParameter; }
+               }
+
+               public bool IsPointer {
+                       get {
+                               return Kind == MemberKind.PointerType;
+                       }
+               }
+
+               public bool IsSealed {
+                       get { return (Modifiers & Modifiers.SEALED) != 0; }
+               }
 
-               public override Type DeclaringType {
-                       get { return info.DeclaringType; }
+               public bool IsStruct {
+                       get { 
+                               return Kind == MemberKind.Struct;
+                       }
                }
 
-               public Type MetaInfo {
-                       get { return info; }
+               public bool IsTypeBuilder {
+                       get {
+                               var meta = GetMetaInfo().GetType ();
+                               return meta == TypeBuilder || meta == GenericTypeBuilder;
+                       }
                }
 
                public MemberCache MemberCache {
                        get {
-                               if (cache == null) {
-//                                     cache = new MemberCache (BaseType);
+                               if (cache == null || (state & StateFlags.PendingMemberCacheMembers) != 0)
+                                       InitializeMemberCache (false);
+
+                               return cache;
+                       }
+                       set {
+                               if (cache != null)
+                                       throw new InternalErrorException ("Membercache reset");
+
+                               cache = value;
+                       }
+               }
+
+               public virtual MemberCache MemberCacheTypes {
+                       get {
+                               return MemberCache;
+                       }
+               }       
+
+               public new ITypeDefinition MemberDefinition {
+                       get {
+                               return (ITypeDefinition) definition;
+                       }
+               }
+
+               // TODO: Wouldn't be better to rely on cast to InflatedTypeSpec and
+               // remove the property, YES IT WOULD !!!
+               public virtual TypeSpec[] TypeArguments {
+                       get { return TypeSpec.EmptyTypes; }
+               }
+
+               #endregion
+
+               public bool AddInterface (TypeSpec iface)
+               {
+                       if ((state & StateFlags.InterfacesExpanded) != 0)
+                               throw new InternalErrorException ("Modifying expanded interface list");
+
+                       if (ifaces == null) {
+                               ifaces = new List<TypeSpec> () { iface };
+                               return true;
+                       }
+
+                       if (!ifaces.Contains (iface)) {
+                               ifaces.Add (iface);
+                               return true;
+                       }
+
+                       return false;
+               }
+
+               public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
+               {
+                       if (Kind != MemberKind.Class)
+                               throw new InternalErrorException ();
+
+                       if (!pa.IsDefined)
+                               return Attribute.DefaultUsageAttribute;
+
+                       var aua = MemberDefinition.GetAttributeUsage (pa);
+                       return aua ?? Attribute.DefaultUsageAttribute;
+               }
 
-//                                     ((ITypeDefinition) definition).LoadMembers (cache);
+               public virtual Type GetMetaInfo ()
+               {
+                       return info;
+               }
+
+               public virtual TypeSpec GetDefinition ()
+               {
+                       return this;
+               }
+
+               public override string GetSignatureForError ()
+               {
+                       string s;
+
+                       if (IsNested) {
+                               s = DeclaringType.GetSignatureForError ();
+                       } else {
+                               s = MemberDefinition.Namespace;
+                       }
+
+                       if (!string.IsNullOrEmpty (s))
+                               s += ".";
+
+                       return s + Name + GetTypeNameSignature ();
+               }
+
+               protected virtual string GetTypeNameSignature ()
+               {
+                       if (!IsGeneric)
+                               return null;
+
+                       return "<" + TypeManager.CSharpName (MemberDefinition.TypeParameters) + ">";
+               }
+
+               public bool ImplementsInterface (TypeSpec iface)
+               {
+                       var t = this;
+                       do {
+                               if (t.Interfaces != null) {     // TODO: Try t.iface
+                                       foreach (TypeSpec i in t.Interfaces) {
+                                               if (i == iface || TypeSpecComparer.Variant.IsEqual (i, iface))
+                                                       return true;
+                                       }
                                }
 
-                               return cache;
+                               t = t.BaseType;
+                       } while (t != null);
+
+                       return false;
+               }
+
+               protected virtual void InitializeMemberCache (bool onlyTypes)
+               {
+                       //
+                       // Not interested in members of nested private types
+                       //
+                       if (IsPrivate) {
+                               cache = new MemberCache (0);
+                       } else {
+                               cache = MemberDefinition.LoadMembers (this);
+                       }
+               }
+
+               public override MemberSpec InflateMember (TypeParameterInflator inflator)
+               {
+                       var targs = IsGeneric ? MemberDefinition.TypeParameters : TypeSpec.EmptyTypes;
+
+                       //
+                       // When inflating nested type from inside the type instance will be same
+                       // because type parameters are same for all nested types
+                       //
+                       if (DeclaringType == inflator.TypeInstance)
+                               return MakeGenericType (targs);
+
+                       return new InflatedTypeSpec (this, inflator.TypeInstance, targs);
+               }
+
+               public InflatedTypeSpec MakeGenericType (TypeSpec[] targs)
+               {
+                       if (targs.Length == 0 && !IsNested)
+                               throw new ArgumentException ("Empty type arguments");
+
+                       InflatedTypeSpec instance;
+
+                       if (inflated_instances == null)
+                               inflated_instances = new Dictionary<TypeSpec[], InflatedTypeSpec> (TypeSpecComparer.Default);
+
+                       if (!inflated_instances.TryGetValue (targs, out instance)) {
+                               if (GetDefinition () != this && !IsNested)
+                                       throw new InternalErrorException ("Only type definition or nested non-inflated types can be used to call MakeGenericType");
+
+                               instance = new InflatedTypeSpec (this, declaringType, targs);
+                               inflated_instances.Add (targs, instance);
+                       }
+
+                       return instance;
+               }
+
+               public virtual TypeSpec Mutate (TypeParameterMutator mutator)
+               {
+                       return this;
+               }
+
+               public void SetMetaInfo (Type info)
+               {
+                       if (this.info != null)
+                               throw new InternalErrorException ("MetaInfo reset");
+
+                       this.info = info;
+               }
+
+               public void SetExtensionMethodContainer ()
+               {
+                       modifiers |= Modifiers.METHOD_EXTENSION;
+               }
+       }
+
+       public class PredefinedTypeSpec : TypeSpec
+       {
+               string name;
+               string ns;
+
+               public PredefinedTypeSpec (MemberKind kind, string ns, string name)
+                       : base (kind, null, null, null, Modifiers.PUBLIC)
+               {
+                       this.name = name;
+                       this.ns = ns;
+               }
+
+               public override int Arity {
+                       get {
+                               return 0;
+                       }
+               }
+
+               public override string Name {
+                       get {
+                               return name;
+                       }
+               }
+
+               public string Namespace {
+                       get {
+                               return ns;
+                       }
+               }
+
+               public override string GetSignatureForError ()
+               {
+                       switch (name) {
+                       case "Int32": return "int";
+                       case "Int64": return "long";
+                       case "String": return "string";
+                       case "Boolean": return "bool";
+                       case "Void": return "void";
+                       case "Object": return "object";
+                       case "UInt32": return "uint";
+                       case "Int16": return "short";
+                       case "UInt16": return "ushort";
+                       case "UInt64": return "ulong";
+                       case "Single": return "float";
+                       case "Double": return "double";
+                       case "Decimal": return "decimal";
+                       case "Char": return "char";
+                       case "Byte": return "byte";
+                       case "SByte": return "sbyte";
+                       }
+
+                       return ns + "." + name;
+               }
+
+               public void SetDefinition (ITypeDefinition td, Type type)
+               {
+                       this.definition = td;
+                       this.info = type;
+               }
+
+               public void SetDefinition (TypeSpec ts)
+               {
+                       this.definition = ts.MemberDefinition;
+                       this.info = ts.GetMetaInfo ();
+                       this.BaseType = ts.BaseType;
+                       this.Interfaces = ts.Interfaces;
+               }
+       }
+
+       static class TypeSpecComparer
+       {
+               //
+               // Default reference comparison
+               //
+               public static readonly DefaultImpl Default = new DefaultImpl ();
+
+               public class DefaultImpl : IEqualityComparer<TypeSpec[]>, IEqualityComparer<Tuple<TypeSpec, TypeSpec[]>>
+               {
+                       #region IEqualityComparer<TypeSpec[]> Members
+
+                       public bool Equals (TypeSpec[] x, TypeSpec[] y)
+                       {
+                               if (x.Length != y.Length)
+                                       return false;
+
+                               if (x == y)
+                                       return true;
+
+                               for (int i = 0; i < x.Length; ++i)
+                                       if (x[i] != y[i])
+                                               return false;
+
+                               return true;
+                       }
+
+                       public int GetHashCode (TypeSpec[] obj)
+                       {
+                               int hash = 0;
+                               for (int i = 0; i < obj.Length; ++i)
+                                       hash = (hash << 5) - hash + obj[i].GetHashCode ();
+
+                               return hash;
+                       }
+
+                       #endregion
+
+                       #region IEqualityComparer<Tuple<TypeSpec,TypeSpec[]>> Members
+
+                       bool IEqualityComparer<Tuple<TypeSpec, TypeSpec[]>>.Equals (Tuple<TypeSpec, TypeSpec[]> x, Tuple<TypeSpec, TypeSpec[]> y)
+                       {
+                               return Equals (x.Item2, y.Item2) && x.Item1 == y.Item1;
+                       }
+
+                       int IEqualityComparer<Tuple<TypeSpec, TypeSpec[]>>.GetHashCode (Tuple<TypeSpec, TypeSpec[]> obj)
+                       {
+                               return GetHashCode (obj.Item2) ^ obj.Item1.GetHashCode ();
+                       }
+
+                       #endregion
+               }
+
+               //
+               // When comparing type signature of overrides or overloads
+               // this version tolerates different MVARs at same position
+               //
+               public static class Override
+               {
+                       public static bool IsEqual (TypeSpec a, TypeSpec b)
+                       {
+                               if (a == b)
+                                       return true;
+
+                               //
+                               // Consider the following example:
+                               //
+                               //     public abstract class A
+                               //     {
+                               //        public abstract T Foo<T>();
+                               //     }
+                               //
+                               //     public class B : A
+                               //     {
+                               //        public override U Foo<T>() { return default (U); }
+                               //     }
+                               //
+                               // Here, `T' and `U' are method type parameters from different methods
+                               // (A.Foo and B.Foo), so both `==' and Equals() will fail.
+                               //
+                               // However, since we're determining whether B.Foo() overrides A.Foo(),
+                               // we need to do a signature based comparision and consider them equal.
+                               //
+
+                               var tp_a = a as TypeParameterSpec;
+                               if (tp_a != null) {
+                                       var tp_b = b as TypeParameterSpec;
+                                       return tp_b != null && tp_a.IsMethodOwned == tp_b.IsMethodOwned && tp_a.DeclaredPosition == tp_b.DeclaredPosition;
+                               }
+
+                               if (a.TypeArguments.Length != b.TypeArguments.Length)
+                                       return false;
+
+                               if (a.TypeArguments.Length != 0) {
+                                       if (a.MemberDefinition != b.MemberDefinition)
+                                               return false;
+
+                                       for (int i = 0; i < a.TypeArguments.Length; ++i) {
+                                               if (!IsEqual (a.TypeArguments[i], b.TypeArguments[i]))
+                                                       return false;
+                                       }
+
+                                       return true;
+                               }
+
+                               var ac_a = a as ArrayContainer;
+                               if (ac_a != null) {
+                                       var ac_b = b as ArrayContainer;
+                                       return ac_b != null && ac_a.Rank == ac_b.Rank && IsEqual (ac_a.Element, ac_b.Element);
+                               }
+
+                               if (a == InternalType.Dynamic || b == InternalType.Dynamic)
+                                       return b == TypeManager.object_type || a == TypeManager.object_type;
+
+                               return false;
+                       }
+
+                       //
+                       // Compares unordered arrays
+                       //
+                       public static bool IsSame (TypeSpec[] a, TypeSpec[] b)
+                       {
+                               if (a == b)
+                                       return true;
+
+                               if (a == null || b == null || a.Length != b.Length)
+                                       return false;
+
+                               for (int ai = 0; ai < a.Length; ++ai) {
+                                       bool found = false;
+                                       for (int bi = 0; bi < b.Length; ++bi) {
+                                               if (IsEqual (a[ai], b[bi])) {
+                                                       found = true;
+                                                       break;
+                                               }
+                                       }
+
+                                       if (!found)
+                                               return false;
+                               }
+
+                               return true;
+                       }
+
+                       public static bool IsEqual (AParametersCollection a, AParametersCollection b)
+                       {
+                               if (a == b)
+                                       return true;
+
+                               if (a.Count != b.Count)
+                                       return false;
+
+                               for (int i = 0; i < a.Count; ++i) {
+                                       if (!IsEqual (a.Types[i], b.Types[i]))
+                                               return false;
+
+                                       const Parameter.Modifier ref_out = Parameter.Modifier.REF | Parameter.Modifier.OUT;
+                                       if ((a.FixedParameters[i].ModFlags & ref_out) != (b.FixedParameters[i].ModFlags & ref_out))
+                                               return false;
+                               }
+
+                               return true;
+                       }
+               }
+
+               //
+               // Type variance equality comparison
+               //
+               public static class Variant
+               {
+                       public static bool IsEqual (TypeSpec type1, TypeSpec type2)
+                       {
+                               if (!type1.IsGeneric || !type2.IsGeneric)
+                                       return false;
+
+                               var target_type_def = type2.MemberDefinition;
+                               if (type1.MemberDefinition != target_type_def)
+                                       return false;
+
+                               if (!type1.IsInterface && !type1.IsDelegate)
+                                       return false;
+
+                               var t1_targs = type1.TypeArguments;
+                               var t2_targs = type2.TypeArguments;
+                               var targs_definition = target_type_def.TypeParameters;
+                               for (int i = 0; i < targs_definition.Length; ++i) {
+                                       Variance v = targs_definition[i].Variance;
+                                       if (v == Variance.None) {
+                                               if (t1_targs[i] == t2_targs[i])
+                                                       continue;
+                                               return false;
+                                       }
+
+                                       if (v == Variance.Covariant) {
+                                               if (!Convert.ImplicitReferenceConversionExists (new EmptyExpression (t1_targs[i]), t2_targs[i]))
+                                                       return false;
+                                       } else if (!Convert.ImplicitReferenceConversionExists (new EmptyExpression (t2_targs[i]), t1_targs[i])) {
+                                               return false;
+                                       }
+                               }
+
+                               return true;
+                       }
+               }
+
+               //
+               // Checks whether two generic instances may become equal for some
+               // particular instantiation (26.3.1).
+               //
+               public static class Unify
+               {
+                       //
+                       // Either @a or @b must be generic type
+                       //
+                       public static bool IsEqual (TypeSpec a, TypeSpec b)
+                       {
+                               if (a.MemberDefinition != b.MemberDefinition)
+                                       return false;
+
+                               var ta = a.TypeArguments;
+                               var tb = b.TypeArguments;
+                               for (int i = 0; i < ta.Length; i++) {
+                                       if (!MayBecomeEqualGenericTypes (ta[i], tb[i]))
+                                               return false;
+                               }
+
+                               return true;
+                       }
+
+                       /// <summary>
+                       ///   Check whether `a' and `b' may become equal generic types.
+                       ///   The algorithm to do that is a little bit complicated.
+                       /// </summary>
+                       static bool MayBecomeEqualGenericTypes (TypeSpec a, TypeSpec b)
+                       {
+                               if (a.IsGenericParameter) {
+                                       //
+                                       // If a is an array of a's type, they may never
+                                       // become equal.
+                                       //
+                                       if (b.IsArray)
+                                               return false;
+
+                                       //
+                                       // If b is a generic parameter or an actual type,
+                                       // they may become equal:
+                                       //
+                                       //    class X<T,U> : I<T>, I<U>
+                                       //    class X<T> : I<T>, I<float>
+                                       // 
+                                       if (b.IsGenericParameter)
+                                               return a.DeclaringType == b.DeclaringType;
+
+                                       //
+                                       // We're now comparing a type parameter with a
+                                       // generic instance.  They may become equal unless
+                                       // the type parameter appears anywhere in the
+                                       // generic instance:
+                                       //
+                                       //    class X<T,U> : I<T>, I<X<U>>
+                                       //        -> error because you could instanciate it as
+                                       //           X<X<int>,int>
+                                       //
+                                       //    class X<T> : I<T>, I<X<T>> -> ok
+                                       //
+
+                                       TypeSpec[] bargs = b.TypeArguments;
+                                       for (int i = 0; i < bargs.Length; i++) {
+                                               if (a.Equals (bargs[i]))
+                                                       return false;
+                                       }
+
+                                       return true;
+                               }
+
+                               if (b.IsGenericParameter)
+                                       return MayBecomeEqualGenericTypes (b, a);
+
+                               //
+                               // At this point, neither a nor b are a type parameter.
+                               //
+                               // If one of them is a generic instance, compare them (if the
+                               // other one is not a generic instance, they can never
+                               // become equal).
+                               //
+                               if (TypeManager.IsGenericType (a) || TypeManager.IsGenericType (b))
+                                       return IsEqual (a, b);
+
+                               //
+                               // If both of them are arrays.
+                               //
+                               var a_ac = a as ArrayContainer;
+                               if (a_ac != null) {
+                                       var b_ac = b as ArrayContainer;
+                                       if (b_ac == null || a_ac.Rank != b_ac.Rank)
+                                               return false;
+
+                                       return MayBecomeEqualGenericTypes (a_ac.Element, b_ac.Element);
+                               }
+
+                               //
+                               // Ok, two ordinary types.
+                               //
+                               return false;
                        }
                }
        }
 
        public interface ITypeDefinition : IMemberDefinition
        {
-               void LoadMembers (MemberCache cache);
+               string Namespace { get; }
+               int TypeParametersCount { get; }
+               TypeParameterSpec[] TypeParameters { get; }
+
+               TypeSpec GetAttributeCoClass ();
+               string GetAttributeDefaultMember ();
+               AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa);
+               MemberCache LoadMembers (TypeSpec declaringType);
        }
-/*
+
        class InternalType : TypeSpec
        {
+               private class DynamicType : InternalType
+               {
+                       public DynamicType ()
+                               : base ("dynamic")
+                       {
+                       }
+
+                       public override Type GetMetaInfo ()
+                       {
+                               return typeof (object);
+                       }
+               }
+
                public static readonly TypeSpec AnonymousMethod = new InternalType ("anonymous method");
                public static readonly TypeSpec Arglist = new InternalType ("__arglist");
-//             public static readonly TypeSpec Dynamic = new DynamicType ();
+               public static readonly TypeSpec Dynamic = new DynamicType ();
                public static readonly TypeSpec MethodGroup = new InternalType ("method group");
+               public static readonly TypeSpec Null = new InternalType ("null");
+               public static readonly TypeSpec FakeInternalType = new InternalType ("<fake$type>");
+
+               readonly string name;
 
                protected InternalType (string name)
-                       : base (null, null, name, Modifiers.PUBLIC)
+                       : base (MemberKind.InternalCompilerType, null, null, null, Modifiers.PUBLIC)
+               {
+                       this.name = name;
+                       cache = MemberCache.Empty;
+
+                       // Make all internal types CLS-compliant, non-obsolete
+                       state = (state & ~(StateFlags.CLSCompliant_Undetected | StateFlags.Obsolete_Undetected)) | StateFlags.CLSCompliant;
+               }
+
+               public override string GetSignatureForError ()
+               {
+                       return name;
+               }
+       }
+
+       public abstract class ElementTypeSpec : TypeSpec
+       {
+               protected ElementTypeSpec (MemberKind kind, TypeSpec element, Type info)
+                       : base (kind, element.DeclaringType, element.MemberDefinition, info, element.Modifiers)
+               {
+                       this.Element = element;
+                       cache = MemberCache.Empty;
+               }
+
+               #region Properties
+
+               public TypeSpec Element { get; private set; }
+
+               public override string Name {
+                       get {
+                               throw new NotSupportedException ();
+                       }
+               }
+
+               #endregion
+
+               public override ObsoleteAttribute GetAttributeObsolete ()
+               {
+                       return Element.GetAttributeObsolete ();
+               }
+
+               protected virtual string GetPostfixSignature ()
+               {
+                       return null;
+               }
+
+               public override string GetSignatureForError ()
+               {
+                       return Element.GetSignatureForError () + GetPostfixSignature ();
+               }
+
+               public override TypeSpec Mutate (TypeParameterMutator mutator)
+               {
+                       var me = Element.Mutate (mutator);
+                       if (me == Element)
+                               return this;
+
+                       var mutated = (ElementTypeSpec) MemberwiseClone ();
+                       mutated.Element = me;
+                       mutated.info = null;
+                       return mutated;
+               }
+       }
+
+       public class ArrayContainer : ElementTypeSpec
+       {
+               readonly int rank;
+               static Dictionary<Tuple<TypeSpec, int>, ArrayContainer> instances = new Dictionary<Tuple<TypeSpec, int>, ArrayContainer> ();
+
+               private ArrayContainer (TypeSpec element, int rank)
+                       : base (MemberKind.Class, element, null)
+               {
+                       this.rank = rank;
+               }
+
+               public int Rank {
+                       get {
+                               return rank;
+                       }
+               }
+
+               public System.Reflection.MethodInfo GetConstructor ()
+               {
+                       var mb = RootContext.ToplevelTypes.Builder;
+
+                       var arg_types = new Type[rank];
+                       for (int i = 0; i < rank; i++)
+                               arg_types[i] = TypeManager.int32_type.GetMetaInfo ();
+
+                       var ctor = mb.GetArrayMethod (
+                               GetMetaInfo (), ".ctor",
+                               System.Reflection.CallingConventions.HasThis,
+                               null, arg_types);
+
+                       return ctor;
+               }
+
+               public System.Reflection.MethodInfo GetGetMethod ()
+               {
+                       var mb = RootContext.ToplevelTypes.Builder;
+
+                       var arg_types = new Type[rank];
+                       for (int i = 0; i < rank; i++)
+                               arg_types[i] = TypeManager.int32_type.GetMetaInfo ();
+
+                       var get = mb.GetArrayMethod (
+                               GetMetaInfo (), "Get",
+                               System.Reflection.CallingConventions.HasThis | System.Reflection.CallingConventions.Standard,
+                               Element.GetMetaInfo (), arg_types);
+
+                       return get;
+               }
+
+               public System.Reflection.MethodInfo GetSetMethod ()
+               {
+                       var mb = RootContext.ToplevelTypes.Builder;
+
+                       var arg_types = new Type[rank + 1];
+                       for (int i = 0; i < rank; i++)
+                               arg_types[i] = TypeManager.int32_type.GetMetaInfo ();
+
+                       arg_types[rank] = Element.GetMetaInfo ();
+
+                       var set = mb.GetArrayMethod (
+                               GetMetaInfo (), "Set",
+                               System.Reflection.CallingConventions.HasThis | System.Reflection.CallingConventions.Standard,
+                               TypeManager.void_type.GetMetaInfo (), arg_types);
+
+                       return set;
+               }
+
+               public override Type GetMetaInfo ()
+               {
+                       if (info == null) {
+                               if (rank == 1)
+                                       info = Element.GetMetaInfo ().MakeArrayType ();
+                               else
+                                       info = Element.GetMetaInfo ().MakeArrayType (rank);
+                       }
+
+                       return info;
+               }
+
+               protected override string GetPostfixSignature()
+               {
+                       StringBuilder sb = new StringBuilder ();
+                       sb.Append ("[");
+                       for (int i = 1; i < rank; i++) {
+                               sb.Append (",");
+                       }
+                       sb.Append ("]");
+
+                       return sb.ToString ();
+               }
+
+               public static ArrayContainer MakeType (TypeSpec element)
+               {
+                       return MakeType (element, 1);
+               }
+
+               public static ArrayContainer MakeType (TypeSpec element, int rank)
+               {
+                       ArrayContainer ac;
+                       var key = Tuple.Create (element, rank);
+                       if (!instances.TryGetValue (key, out ac)) {
+                               ac = new ArrayContainer (element, rank) {
+                                       BaseType = TypeManager.array_type
+                               };
+
+                               instances.Add (key, ac);
+                       }
+
+                       return ac;
+               }
+
+               public static void Reset ()
+               {
+                       instances = new Dictionary<Tuple<TypeSpec, int>, ArrayContainer> ();
+               }
+       }
+
+       class ReferenceContainer : ElementTypeSpec
+       {
+               static Dictionary<TypeSpec, ReferenceContainer> instances = new Dictionary<TypeSpec, ReferenceContainer> ();
+
+               private ReferenceContainer (TypeSpec element)
+                       : base (MemberKind.Class, element, null)        // TODO: Kind.Class is most likely wrong
+               {
+               }
+
+               public override Type GetMetaInfo ()
+               {
+                       if (info == null) {
+                               info = Element.GetMetaInfo ().MakeByRefType ();
+                       }
+
+                       return info;
+               }
+
+               public static ReferenceContainer MakeType (TypeSpec element)
+               {
+                       ReferenceContainer pc;
+                       if (!instances.TryGetValue (element, out pc)) {
+                               pc = new ReferenceContainer (element);
+                               instances.Add (element, pc);
+                       }
+
+                       return pc;
+               }
+
+               public static void Reset ()
+               {
+                       instances = new Dictionary<TypeSpec, ReferenceContainer> ();
+               }
+       }
+
+       class PointerContainer : ElementTypeSpec
+       {
+               static Dictionary<TypeSpec, PointerContainer> instances = new Dictionary<TypeSpec, PointerContainer> ();
+
+               private PointerContainer (TypeSpec element)
+                       : base (MemberKind.PointerType, element, null)
+               {
+                       // It's never CLS-Compliant
+                       state &= ~StateFlags.CLSCompliant_Undetected;
+               }
+
+               public override Type GetMetaInfo ()
+               {
+                       if (info == null) {
+                               info = Element.GetMetaInfo ().MakePointerType ();
+                       }
+
+                       return info;
+               }
+
+               protected override string GetPostfixSignature()
+               {
+                       return "*";
+               }
+
+               public static PointerContainer MakeType (TypeSpec element)
+               {
+                       PointerContainer pc;
+                       if (!instances.TryGetValue (element, out pc)) {
+                               pc = new PointerContainer (element);
+                               instances.Add (element, pc);
+                       }
+
+                       return pc;
+               }
+
+               public static void Reset ()
                {
-//                     cache = MemberCache.Empty;
+                       instances = new Dictionary<TypeSpec, PointerContainer> ();
                }
        }
-*/ 
 }
index c9dca4ac6f8e8464e77344bf597f9f77880f245e..6fd193ddf477b0c4fe8e776e002e09bc597295c1 100644 (file)
@@ -1,3 +1,15 @@
+2010-04-02  Raja R Harinath  <harinath@hurrynot.org>
+
+       * Makefile (DEFINES) [moonlight, net_4_0]: New.
+       (check): Use it.
+       * gtest-284.cs [NET_4_0]: Don't complain about
+       IStructuralEquatable and IStructuralComparable array interfaces.
+
+2010-03-30  Zoltan Varga  <vargaz@gmail.com>
+
+       * test-106.cs: Move the wait for cb_state == 1 out of the try block so this
+       test becomes deterministic.
+
 2009-11-11  Scott Peterson  <lunchtimemama@gmail.com>
 
        * gtest-469.cs: Added test for BGO 553655.
index 4ddeabc7ca84c6ba023a57e5bf10227816956c0e..9170cb295323a2b85a0d6faf37793b25bbd86932 100644 (file)
@@ -19,7 +19,7 @@ USE_MCS_FLAGS :=
 # mention all targets
 all-local $(STD_TARGETS:=-local):
 
-VALID_PROFILE := $(filter net_2_0 net_2_1 net_4_0, $(PROFILE))
+VALID_PROFILE := $(filter net_2_0 moonlight net_4_0, $(PROFILE))
 ifdef VALID_PROFILE
 # casts
 bootstrap-cast.exe: gen-cast-test.cs
@@ -50,12 +50,14 @@ ifeq (net_4_0, $(PROFILE))
 COMPILER_NAME = dmcs
 TEST_PATTERN = 'v4'
 LOCAL_RUNTIME_FLAGS = --verify-all
+DEFINES = -compiler-options:"-d:NET_4_0"
 #TOPTIONS += '-il:ver-il-dmcs.xml'
 endif
-ifeq (net_2_1, $(PROFILE))
+ifeq (moonlight, $(PROFILE))
 COMPILER_NAME = smcs
 TEST_PATTERN = 'v2'
 LOCAL_RUNTIME_FLAGS = --security=temporary-smcs-hack
+DEFINES = -compiler-options:"-d:MOONLIGHT"
 endif
 ifeq (net_2_0, $(PROFILE))
 COMPILER_NAME = gmcs
@@ -72,28 +74,18 @@ TEST_ILS := $(wildcard *-lib.il)
 eval-test: 
        $(CSCOMPILE) eval-test.cs -r:Mono.CSharp.dll
        $(with_mono_path) $(RUNTIME) $(RUNTIME_FLAGS) eval-test.exe
-       
+
 build-compiler-lib:
        cd ../class/Mono.CSharp && $(MAKE) NO_DIR_CHECK=yes
 
-check: build-compiler-lib eval-test
-       $(TESTER) -mode:pos -files:$(TEST_PATTERN) -compiler:$(COMPILER) -issues:known-issues-$(COMPILER_NAME) -log:$(COMPILER_NAME).log $(TOPTIONS)
+qcheck: build-compiler-lib eval-test
+       $(TESTER) -mode:pos -files:$(TEST_PATTERN) -compiler:$(COMPILER) -issues:known-issues-$(COMPILER_NAME) -log:$(COMPILER_NAME).log $(TOPTIONS) $(DEFINES)
 
 test-local:
        @:
 
 run-test-local: $(TEST_ILS:.il=.dll) setup check
 
-# Temporary testing targets
-cecil:
-       rm -f *.mdb
-       $(TESTER) -mode:pos -files:'test-*.cs' -compiler:gmcs.exe -issues:known-issues-$(COMPILER_NAME) -log:$(COMPILER_NAME).log -verbose
-
-cecil2:
-       rm -f *.mdb
-       $(TESTER) -mode:pos -files:'*test-*.cs' -compiler:gmcs.exe -issues:known-issues-$(COMPILER_NAME) -log:$(COMPILER_NAME).log -verbose
-# End  
-
 endif
 
 clean-local:
@@ -111,7 +103,7 @@ csproj-local:
 
 %-lib.dll: %-lib.il
        $(ILASM) /dll /out:$@ $<
-       
+
 setup:
        $(ILASM) /dll property-il.il
        $(CSCOMPILE) /r:property-il.dll property-main.cs /out:property-main.exe
index 3a710ffaf65da3e99731d3d404eec47670104504..c9433a4f262f7d6d8b19115f4554c5e94e2d567a 100644 (file)
@@ -57,8 +57,8 @@ public class MyTest {
                }
 
                res = Evaluator.GetCompletions ("Converte", out prefix);
-               if (res [0] != "r<"){
-                       throw new Exception ("Expected one completion for Conveter<");
+               if (res [0] != "r"){
+                       throw new Exception ("Expected one completion for Converter");
                }
 
                res = Evaluator.GetCompletions ("Sys", out prefix);
@@ -77,7 +77,7 @@ public class MyTest {
                }
 
                res = Evaluator.GetCompletions ("new System.Text.StringBuilder () { ", out prefix);
-               if (res.Length != 4){
+               if (res.Length != 3){
                        throw new Exception ("Epxected 4 completions (Capacity Chars Length MaxCapacity)");
                }
 
diff --git a/mcs/tests/gtest-232.cs b/mcs/tests/gtest-232.cs
deleted file mode 100644 (file)
index 8b01949..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-public class H
-{
-       public static void Main(String[] args) { }
-
-       public static IEnumerable<T> Merge<T> (IEnumerator<T> xEtor)
-               where T : IComparable<T>
-       {
-               int order = xEtor.Current.CompareTo (xEtor.Current);
-               yield return xEtor.Current;
-       }
-}
index 51a31a954bbe7c78d2f0bd8ed9b1ae4487166d3d..9a71d8b6accb4c03b7e0d239b99cfd4e907f9ad5 100644 (file)
@@ -3,11 +3,18 @@ using System.Reflection;
 using System.Runtime.InteropServices;
 
 public class Test {
+       public enum ParamEnum {
+               None = 0,
+               Foo = 1,
+               Bar = 2
+       };
+       
        public void f1 ([System.Runtime.InteropServices.DefaultParameterValue (null)] object x) {}
        public void f2 ([System.Runtime.InteropServices.DefaultParameterValue (null)] string x) {}
        public void f3 ([System.Runtime.InteropServices.DefaultParameterValue (null)] Test x) {}
        public void f4 ([System.Runtime.InteropServices.DefaultParameterValue (1)] int x) {}
        public void f5 ([System.Runtime.InteropServices.DefaultParameterValue ((short) 1)] short x) {}
+       public void f6 ([DefaultParameterValue (ParamEnum.Foo)] ParamEnum n) {}
 
        static void Main ()
        {
index c6c15910659ad20e64b9de8399df1b5b9549a519..e5aac17e1a4a32f7dbeaf68b1b0f7de3221c4067 100644 (file)
@@ -147,6 +147,10 @@ public static class InterfaceTester
        static readonly Type generic_icollection_type;
        static readonly Type generic_ienumerable_type;
        static readonly Type icloneable_type;
+#if NET_4_0
+       static readonly Type istructuralequatable_type = typeof (IStructuralEquatable);
+       static readonly Type istructuralcomparable_type = typeof (IStructuralComparable);
+#endif
 
        static InterfaceTester ()
        {
@@ -172,6 +176,10 @@ public static class InterfaceTester
                ifaces.Add (icollection_type, State.Missing);
                ifaces.Add (ienumerable_type, State.Missing);
                ifaces.Add (icloneable_type, State.Missing);
+#if NET_4_0
+               ifaces.Add (istructuralequatable_type, State.Missing);
+               ifaces.Add (istructuralcomparable_type, State.Missing);
+#endif
 
                Type array_type = t.MakeArrayType ();
 
index ca1f8faa1d35e207026fcc1f7c09c53049a869d5..b2139bf8546735816c3416569440203b849a96b2 100644 (file)
@@ -3,8 +3,11 @@ using System;
 
 class X
 {
-       static void Main ()
-       { }
+       static int Main ()
+       {
+               new Derived ().Method<Foo> ();
+               return 0;
+       }
 }
 
 class Foo
diff --git a/mcs/tests/gtest-473.cs b/mcs/tests/gtest-473.cs
new file mode 100644 (file)
index 0000000..d5aa66a
--- /dev/null
@@ -0,0 +1,22 @@
+class A<X>
+{
+       public virtual void Foo<T> () where T : A<T>
+       {
+       }
+}
+
+class B : A<int>
+{
+       public override void Foo<T> ()
+       {
+       }
+}
+
+class C
+{
+       public static int Main ()
+       {
+               new B ();
+               return 0;
+       }
+}
\ No newline at end of file
diff --git a/mcs/tests/gtest-474.cs b/mcs/tests/gtest-474.cs
new file mode 100644 (file)
index 0000000..11d7ada
--- /dev/null
@@ -0,0 +1,17 @@
+class A<X>
+{
+       public const A<int> Value = B<int>.Value;
+}
+
+class B<T>
+{
+       public const A<T> Value = default (A<T>);
+}
+
+class C
+{
+       public static void Main ()
+       {
+               new B<int> ();
+       }
+}
diff --git a/mcs/tests/gtest-475.cs b/mcs/tests/gtest-475.cs
new file mode 100644 (file)
index 0000000..f9e6926
--- /dev/null
@@ -0,0 +1,30 @@
+using System;
+
+class Value<T>
+{
+       public static Value<T> Default = null;
+}
+
+class Test<T, U>
+{
+       public Value<T> Value {
+               get { return null; }
+       }
+
+       public class B
+       {
+               public B (Value<U> arg)
+               {
+               }
+               
+               public static B Default = new B (Value<U>.Default);
+       }
+}
+
+class C
+{
+       public static void Main ()
+       {
+               var v = Test<int, string>.B.Default;
+       }
+}
diff --git a/mcs/tests/gtest-476.cs b/mcs/tests/gtest-476.cs
new file mode 100644 (file)
index 0000000..d556a90
--- /dev/null
@@ -0,0 +1,32 @@
+using System;
+
+// Obsolete attribute cased early inflation of B without IFoo being defined for it
+
+interface IFoo
+{
+}
+
+class Test<T> : IFoo
+{
+       public B First ()
+       {
+               return new B ();
+       }
+       
+       public IFoo Second ()
+       {
+               return new B ();
+       }
+
+       [Obsolete]
+       public struct B : IFoo
+       {
+       }
+}
+
+class C
+{
+       public static void Main ()
+       {
+       }
+}
diff --git a/mcs/tests/gtest-477.cs b/mcs/tests/gtest-477.cs
new file mode 100644 (file)
index 0000000..05b231e
--- /dev/null
@@ -0,0 +1,26 @@
+using System;
+
+class B<T> : A<T>
+{
+       protected class BNested : ANested
+       {
+       }
+}
+
+class A<T> : AA<T>
+{
+}
+
+class AA<T>
+{
+       protected class ANested
+       {
+       }
+}
+
+class M
+{
+       public static void Main ()
+       {
+       }
+}
diff --git a/mcs/tests/gtest-478.cs b/mcs/tests/gtest-478.cs
new file mode 100644 (file)
index 0000000..fa1052f
--- /dev/null
@@ -0,0 +1,28 @@
+using System;
+
+interface IA
+{
+       void Foo ();
+}
+
+interface IG<T> : IA
+{
+       void GenFoo ();
+}
+
+class M : IG<int>
+{
+       public void Foo ()
+       {
+       }
+       
+       public void GenFoo ()
+       {
+       }
+       
+       public static void Main ()
+       {
+               IG<int> v = new M ();
+               v.Foo ();
+       }
+}
diff --git a/mcs/tests/gtest-479.cs b/mcs/tests/gtest-479.cs
new file mode 100644 (file)
index 0000000..5ad555b
--- /dev/null
@@ -0,0 +1,26 @@
+using System;
+
+interface I<T>
+{
+}
+
+class A : I<int>
+{
+}
+
+class B : A
+{
+}
+
+class M
+{
+       static void Test<T> (I<T> f)
+       {
+       }
+       
+       public static void Main ()
+       {
+               Test (new A ());
+               Test (new B ());
+       }
+}
diff --git a/mcs/tests/gtest-480.cs b/mcs/tests/gtest-480.cs
new file mode 100644 (file)
index 0000000..737e0e0
--- /dev/null
@@ -0,0 +1,22 @@
+using System;
+using System.Collections.Generic;
+
+interface I<T> : ICollection<T>, IEnumerable<T>
+{
+}
+
+class C
+{
+       void Foo ()
+       {
+               I<object> o = null;
+               foreach (var v in o)
+                       Console.WriteLine (v);
+       }
+       
+       public static void Main ()
+       {
+               IList<int> list = new List<int> { 1, 3 };
+               var g = list.GetEnumerator ();
+       }
+}
diff --git a/mcs/tests/gtest-481.cs b/mcs/tests/gtest-481.cs
new file mode 100644 (file)
index 0000000..6a51fe7
--- /dev/null
@@ -0,0 +1,21 @@
+public class TestClass<T>
+{
+       private T[][] m_data;
+
+       public TestClass (int arrSize)
+       {
+               Add (ref m_data);
+       }
+
+       private static void Add (ref T[][] arr)
+       {
+       }
+}
+
+class C
+{
+       public static void Main ()
+       {
+               new TestClass<decimal> (4);
+       }
+}
index 6bd016b19941a412e2b2dd0920f4a94cbc4e1022..0c24a68174def16754a0c7fe103df009f3947330 100644 (file)
@@ -16,6 +16,7 @@ public class Test<R>
                Foo foo = delegate {
                        World (u, v);
                };
+               foo ();
        }
 }
 
index 8c97345554f85b719cde1149a20e0b2572da7504..103ba8d0537fc87baa348a1b8927e296b203322f 100644 (file)
@@ -14,6 +14,15 @@ interface IFoo<TOne,TTwo>
 {
 }
 
+class CA<T>
+{
+       public struct Nested
+       {
+               public static readonly T Value;
+               public readonly T Value2;
+       }
+}
+
 class Test
 {
        static Func<T[]> For<T> (List<T> list)
@@ -153,6 +162,14 @@ class Test
                };
        }
        
+       static Func<T[]> NestedTypeMutate<T> ()
+       {
+               var local = new CA<T>.Nested ();
+               return () => {
+                       return new [] { CA<T>.Nested.Value, local.Value2 };
+               };
+       }
+       
        public static int Main ()
        {
                if (For (new List<int> { 5, 10 })() [1] != 10)
@@ -201,6 +218,10 @@ class Test
                var t11 = TypeOf ("b");
                if (t11 () != typeof (string))
                        return 11;
+               
+               var t12 = NestedTypeMutate<ulong> ()();
+               if (t12 [0] != 0 || t12 [1] != 0)
+                       return 12;
 
                Console.WriteLine ("OK");
                return 0;
diff --git a/mcs/tests/gtest-anon-59.cs b/mcs/tests/gtest-anon-59.cs
new file mode 100644 (file)
index 0000000..39832ee
--- /dev/null
@@ -0,0 +1,44 @@
+using System;
+
+namespace TestGenericsSubtypeMatching
+{
+       public class Sender<T> : IDisposable
+       {
+               public void DoSend<TMessage> (Action<T> action)
+               {
+                       using (Sender<T> sub = new Sender<T> ())
+                       {
+                               Send (t =>
+                               {
+                                       action(t);
+                                       sub.ActionOnObject (t);
+                               });
+                       }
+               }
+               
+               private static void Send (Action<T> action)
+               {
+               }
+               
+               void ActionOnObject (object o)
+               {
+                       o.ToString ();
+               }
+       
+               #region IDisposable implementation
+               public void Dispose ()
+               {
+                       Console.WriteLine ("Dispose!");
+               }
+               
+               #endregion
+       }
+       
+       public class C
+       {
+               public static void Main ()
+               {
+                       new Sender<string> ().DoSend<bool>(l => Console.WriteLine (l));
+               }
+       }
+}
diff --git a/mcs/tests/gtest-exmethod-30.cs b/mcs/tests/gtest-exmethod-30.cs
new file mode 100644 (file)
index 0000000..19cc97c
--- /dev/null
@@ -0,0 +1,35 @@
+using System.Linq;
+using System.Collections;
+using System.Collections.Generic;
+
+class Test : IEnumerable<int>
+{
+       public int First {
+               get {
+                       return 1;
+               }
+       }
+       
+       IEnumerator IEnumerable.GetEnumerator ()
+       {
+               return null;
+       }
+       
+       public IEnumerator<int> GetEnumerator ()
+       {
+               return null;
+       }
+}
+
+class C
+{
+       public void Test ()
+       {
+               var t = new Test ();
+               var v = t.First ();             
+       }
+       
+       public static void Main ()
+       {
+       }
+}
diff --git a/mcs/tests/gtest-exmethod-31.cs b/mcs/tests/gtest-exmethod-31.cs
new file mode 100644 (file)
index 0000000..9ef1ad1
--- /dev/null
@@ -0,0 +1,36 @@
+using System;
+using System.Collections.Generic;
+using N2;
+
+namespace N
+{
+       static class S
+       {
+               internal static void Map<T>(this int i, Func<T, string> f)
+               {
+               }
+       }
+}
+
+namespace N2
+{
+       static class S2
+       {
+               internal static void Map(this int i, int k)
+               {
+               }
+       }
+}
+
+namespace M
+{
+       using N;
+       
+       class C
+       {
+               public static void Main ()
+               {
+                       1.Map(2);
+               }
+       }
+}
diff --git a/mcs/tests/gtest-iter-12.cs b/mcs/tests/gtest-iter-12.cs
new file mode 100644 (file)
index 0000000..8b01949
--- /dev/null
@@ -0,0 +1,14 @@
+using System;
+using System.Collections.Generic;
+
+public class H
+{
+       public static void Main(String[] args) { }
+
+       public static IEnumerable<T> Merge<T> (IEnumerator<T> xEtor)
+               where T : IComparable<T>
+       {
+               int order = xEtor.Current.CompareTo (xEtor.Current);
+               yield return xEtor.Current;
+       }
+}
diff --git a/mcs/tests/gtest-iter-13.cs b/mcs/tests/gtest-iter-13.cs
new file mode 100644 (file)
index 0000000..de07d15
--- /dev/null
@@ -0,0 +1,27 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+
+class C<T>
+{
+       public IEnumerator GetEnumerator ()
+       {
+               return new T[0].GetEnumerator ();
+       }
+
+       public IEnumerable<T> Filter (Func<T, bool> predicate)
+       {
+               foreach (T item in this)
+                       if (predicate (item))
+                               yield return item;
+       }
+}
+
+class M
+{
+       public static void Main ()
+       {
+               foreach (var v in new C<long>().Filter(null)) {
+               }
+       }
+}
diff --git a/mcs/tests/gtest-optional-08.cs b/mcs/tests/gtest-optional-08.cs
new file mode 100644 (file)
index 0000000..d148076
--- /dev/null
@@ -0,0 +1,22 @@
+public class Tests
+{
+       string s;
+       
+       private Tests (string arg = "long")
+       {
+               this.s = arg;
+       }
+       
+       public Tests (int other)
+       {
+       }
+       
+       public static int Main ()
+       {
+               var v = new Tests ();
+               if (v.s != "long")
+                       return 1;
+               
+               return 0;
+       }
+}
index 58cc9c7e589e1c5d0d216ebfa6c953ce78d7de05..66a19f887efe742dbcd93d19efdadd70defc471b 100644 (file)
@@ -7,11 +7,19 @@
 test-xml-027.cs
 
 gtest-230.cs
+gtest-316.cs verifier
 gtest-437.cs
+gtest-anon-47.cs
 
 test-416.cs bug #504085
 test-418.cs bug #504085
+test-454.cs bug #593342
+test-468.cs
+test-184.cs
 test-682.cs bug #530861
 test-704.cs IGNORE #472845
 test-715.cs bug #504085
 test-733.cs
+
+test-xml-030.cs
+
index 58cc9c7e589e1c5d0d216ebfa6c953ce78d7de05..575dc76762f5d700128c4479a3eb3807644f8b04 100644 (file)
@@ -7,11 +7,15 @@
 test-xml-027.cs
 
 gtest-230.cs
+gtest-316.cs verifier
 gtest-437.cs
+gtest-anon-47.cs
 
 test-416.cs bug #504085
 test-418.cs bug #504085
+test-454.cs bug #593342
 test-682.cs bug #530861
 test-704.cs IGNORE #472845
 test-715.cs bug #504085
-test-733.cs
+
+test-xml-030.cs
index 4b6c0530ed37d06574283d216fdb9eebb5d5b511..6bdd6c1fadea26ec8c97cde4680eb8d3c03f6a04 100644 (file)
@@ -30,16 +30,15 @@ class Test {
                ar1.AsyncWaitHandle.WaitOne ();
 
                try {
-                       res = d.EndInvoke (ar1);
-                       
-                       while (cb_state == 0)
-                               Thread.Sleep (0);
-                       
+                       res = d.EndInvoke (ar1);                        
                } catch (NotImplementedException) {
                        res = 1;
                        Console.WriteLine ("received exception ... OK");
                }
 
+               while (cb_state == 0)
+                       Thread.Sleep (0);
+
                if (cb_state != 1)
                        return 1;
                
diff --git a/mcs/tests/test-450.cs b/mcs/tests/test-450.cs
deleted file mode 100644 (file)
index 137e4a4..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-//
-// This is a test for as expression
-// in custom attribute constructors
-//
-
-using System;
-
-class MyAttribute : Attribute {
-
-       public MyAttribute (string s)
-       {
-       }
-}
-
-[My (null as string)]
-class X {
-
-       static void Main ()
-       {
-       }
-}
index 20c0857a800dccaa9de481fa02fcfa129d2eb742..1131908f089a31fa48feb00293aabea1f12f9f84 100644 (file)
@@ -7,8 +7,9 @@ public class Test
                float a = 1f / 3;
                float b = (float) Math.Acos ((float) (a * 3));
                Console.WriteLine (b);
-               if (b != 0 && b != float.NaN)
-                       return 1;
+               if (b != 0 && !float.IsNaN (b)) {
+                       throw new ApplicationException (b.ToString () + b.GetType ().ToString ());
+               }
 
                return 0;
        }
diff --git a/mcs/tests/test-743-lib.cs b/mcs/tests/test-743-lib.cs
new file mode 100644 (file)
index 0000000..5451849
--- /dev/null
@@ -0,0 +1,18 @@
+// Compiler options: -t:library
+
+public class A
+{
+       public int Prop {
+               get {
+                       return 1;
+               }
+               private set { }
+       }
+       
+       protected internal string this [int i] {
+               private get {
+                       return null;
+               }
+               set { }
+       }
+}
\ No newline at end of file
diff --git a/mcs/tests/test-743.cs b/mcs/tests/test-743.cs
new file mode 100644 (file)
index 0000000..9300166
--- /dev/null
@@ -0,0 +1,18 @@
+// Compiler options: -r:test-743-lib.dll
+
+using System;
+
+public class C : A
+{
+       public static void Main ()
+       {
+               new C ().Test ();
+       }
+       
+       void Test ()
+       {
+               var a = new C ();
+               Console.WriteLine (a.Prop);
+               a [5] = "2";
+       }
+}
\ No newline at end of file
diff --git a/mcs/tests/test-744.cs b/mcs/tests/test-744.cs
new file mode 100644 (file)
index 0000000..cd3b7fa
--- /dev/null
@@ -0,0 +1,37 @@
+class M
+{
+       sealed class Nested : C
+       {
+               protected override void Extra ()
+               {
+               }
+       }
+       
+       public static void Main ()
+       {
+               new Nested ();
+       }
+}
+
+abstract class A
+{
+       protected abstract void AMethod ();
+}
+
+abstract class B : A
+{
+       protected abstract void BMethod ();
+}
+
+abstract class C : B
+{
+       protected override void AMethod ()
+       {
+       }
+       
+       protected override void BMethod ()
+       {
+       }
+       
+       protected abstract void Extra ();
+}
diff --git a/mcs/tests/test-745.cs b/mcs/tests/test-745.cs
new file mode 100644 (file)
index 0000000..73a8c03
--- /dev/null
@@ -0,0 +1,17 @@
+using System;
+
+interface ITest
+{
+}
+
+class C : ITest
+{
+       public static void Main ()
+       {
+               ITest it = new C ();
+               it.GetType ();
+
+               IConvertible ic = 1 as IConvertible;
+               var t = ic.GetType ();
+       }
+}
diff --git a/mcs/tests/test-746.cs b/mcs/tests/test-746.cs
new file mode 100644 (file)
index 0000000..49c1d88
--- /dev/null
@@ -0,0 +1,34 @@
+// Compiler options: -warnaserror -warn:4\r
+
+using System;
+
+interface IList \r
+{
+       int Count { get; set; }
+}
+
+interface ICounter\r
+{\r
+       void Count (int i);
+}
+\r
+interface IEx\r
+{\r
+       void Count (params int[] i);\r
+}\r
+
+interface IListCounter: IEx, IList, ICounter\r
+{\r
+}
+
+class Test\r
+{
+       static void Foo (IListCounter t)
+       {
+               t.Count (1); 
+       }
+       
+       public static void Main ()
+       {
+       }
+}
diff --git a/mcs/tests/test-747.cs b/mcs/tests/test-747.cs
new file mode 100644 (file)
index 0000000..b0a7371
--- /dev/null
@@ -0,0 +1,26 @@
+using System;
+
+class B : A
+{
+       protected class BNested : ANested
+       {
+       }
+}
+
+class A : AA
+{
+}
+
+class AA
+{
+       protected class ANested
+       {
+       }
+}
+
+class M
+{
+       public static void Main ()
+       {
+       }
+}
diff --git a/mcs/tests/test-748-lib.cs b/mcs/tests/test-748-lib.cs
new file mode 100644 (file)
index 0000000..e2187ba
--- /dev/null
@@ -0,0 +1,8 @@
+// Compiler options: -target:library
+
+namespace Test
+{
+       class Foo
+       {
+       }
+}
\ No newline at end of file
diff --git a/mcs/tests/test-748.cs b/mcs/tests/test-748.cs
new file mode 100644 (file)
index 0000000..8210c92
--- /dev/null
@@ -0,0 +1,35 @@
+// Compiler options: -r:test-748-lib.dll
+
+using System;
+using Test;
+using RealTest;
+
+class M
+{
+       Foo Test ()
+       {
+               return new RealTest.Foo ();
+       }
+       
+       public static void Main ()
+       {
+       }
+}
+
+namespace Test.Local
+{
+       class M
+       {
+               Foo Test ()
+               {
+                       return new RealTest.Foo ();
+               }
+       }
+}
+
+namespace RealTest
+{
+       class Foo
+       {
+       }
+}
diff --git a/mcs/tests/test-749-lib.cs b/mcs/tests/test-749-lib.cs
new file mode 100644 (file)
index 0000000..176fc7e
--- /dev/null
@@ -0,0 +1,16 @@
+// Compiler options: -target:library
+
+public class B : A
+{
+       public override int Prop {
+               get { return 3; }
+       }
+}
+
+public class A
+{
+       public virtual int Prop {
+               get { return 1; }
+               set {}
+       }
+}
diff --git a/mcs/tests/test-749.cs b/mcs/tests/test-749.cs
new file mode 100644 (file)
index 0000000..0e00d44
--- /dev/null
@@ -0,0 +1,12 @@
+// Compiler options: -r:test-749-lib.dll
+
+using System;
+
+class M
+{
+       public static void Main ()
+       {
+               B b = new B ();
+               b.Prop = 2;
+       }
+}
diff --git a/mcs/tests/test-750.cs b/mcs/tests/test-750.cs
new file mode 100644 (file)
index 0000000..40389be
--- /dev/null
@@ -0,0 +1,21 @@
+// Compiler options: -warnaserror -warn:4
+using System;
+
+public interface IA
+{
+       string this[int index] { get; set; }
+}
+
+public interface IB : IA
+{
+       int this[string name] { get; set; }
+       new int this[int index] { get; set; }
+       int this[string namespaceURI, string localName] {get; set;}
+}
+
+class M
+{
+       public static void Main ()
+       {
+       }
+}
\ No newline at end of file
diff --git a/mcs/tests/test-751.cs b/mcs/tests/test-751.cs
new file mode 100644 (file)
index 0000000..5097a7c
--- /dev/null
@@ -0,0 +1,29 @@
+using SomeOtherNS;
+using LocalNS;
+using OneMoreNS;
+
+namespace SomeOtherNS.Compiler
+{
+}
+
+namespace OneMoreNS.Compiler
+{
+}
+
+namespace LocalNS
+{
+       public class Compiler
+       {
+       }
+}
+
+namespace System.Local
+{
+       class M
+       {
+               public static void Main ()
+               {
+                       Compiler c = new LocalNS.Compiler ();
+               }
+       }
+}
\ No newline at end of file
diff --git a/mcs/tests/test-752-lib.cs b/mcs/tests/test-752-lib.cs
new file mode 100644 (file)
index 0000000..2d71968
--- /dev/null
@@ -0,0 +1,11 @@
+// Compiler options: -target:library
+
+public abstract class A
+{
+       public abstract bool IsNode { get; }
+}
+
+public abstract class B : A
+{
+       public override sealed bool IsNode { get { return true; } }
+}
diff --git a/mcs/tests/test-752.cs b/mcs/tests/test-752.cs
new file mode 100644 (file)
index 0000000..378a5ff
--- /dev/null
@@ -0,0 +1,8 @@
+// Compiler options: -r:test-752-lib.dll
+
+class M : B
+{
+       public static void Main ()
+       {
+       }
+}
\ No newline at end of file
index f02c01910401e3926f8e09b0c7d607373795917f..259b8bfde02e19438baf2aeab0db82f410537e27 100644 (file)
     </type>
     <type name="Fault">
       <method name="Void Main()">
-        <size>45</size>
+        <size>47</size>
       </method>
       <method name="System.String ToString()">
         <size>6</size>
       </method>
     </type>
   </test>
-  <test name="gtest-232.cs">
-    <type name="H">
-      <method name="Void .ctor()">
-        <size>7</size>
-      </method>
-      <method name="IEnumerable`1 Merge[T](IEnumerator`1)">
-        <size>30</size>
-      </method>
-      <method name="Void Main(System.String[])">
-        <size>1</size>
-      </method>
-    </type>
-    <type name="H+&lt;Merge&gt;c__Iterator0`1[T]">
-      <method name="Void .ctor()">
-        <size>7</size>
-      </method>
-      <method name="System.Object System.Collections.IEnumerator.get_Current()">
-        <size>12</size>
-      </method>
-      <method name="IEnumerator System.Collections.IEnumerable.GetEnumerator()">
-        <size>7</size>
-      </method>
-      <method name="Boolean MoveNext()">
-        <size>117</size>
-      </method>
-      <method name="Void Dispose()">
-        <size>8</size>
-      </method>
-      <method name="Void Reset()">
-        <size>6</size>
-      </method>
-      <method name="T System.Collections.Generic.IEnumerator&lt;T&gt;.get_Current()">
-        <size>7</size>
-      </method>
-      <method name="IEnumerator`1 System.Collections.Generic.IEnumerable&lt;T&gt;.GetEnumerator()">
-        <size>40</size>
-      </method>
-    </type>
-  </test>
   <test name="gtest-233.cs">
     <type name="Program">
       <method name="Void .ctor()">
       <method name="Void Main()">
         <size>163</size>
       </method>
+      <method name="Void f6(ParamEnum)">
+        <size>1</size>
+      </method>
     </type>
   </test>
   <test name="gtest-263.cs">
       </method>
     </type>
   </test>
-  <test name="gtest-316.cs">
-    <type name="X">
-      <method name="Void .ctor()">
-        <size>7</size>
-      </method>
-      <method name="Void Main()">
-        <size>1</size>
-      </method>
-    </type>
-    <type name="Foo">
-      <method name="Void .ctor()">
-        <size>7</size>
-      </method>
-    </type>
-    <type name="Base">
-      <method name="Void .ctor()">
-        <size>7</size>
-      </method>
-      <method name="Void Method[R]()">
-        <size>0</size>
-      </method>
-    </type>
-    <type name="Derived">
-      <method name="Void .ctor()">
-        <size>7</size>
-      </method>
-      <method name="Void Method[S]()">
-        <size>7</size>
-      </method>
-      <method name="Void Method2[T]()">
-        <size>18</size>
-      </method>
-    </type>
-  </test>
   <test name="gtest-317.cs">
     <type name="Foo`1[K]">
       <method name="Void .ctor()">
       </method>
     </type>
   </test>
+  <test name="gtest-473.cs">
+    <type name="A`1[X]">
+      <method name="Void Foo[T]()">
+        <size>1</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="B">
+      <method name="Void Foo[T]()">
+        <size>1</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="C">
+      <method name="Int32 Main()">
+        <size>8</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
+  <test name="gtest-474.cs">
+    <type name="A`1[X]">
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="B`1[T]">
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="C">
+      <method name="Void Main()">
+        <size>7</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
+  <test name="gtest-475.cs">
+    <type name="Value`1[T]">
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+      <method name="Void .cctor()">
+        <size>1</size>
+      </method>
+    </type>
+    <type name="Test`2[T,U]">
+      <method name="Value`1[T] get_Value()">
+        <size>2</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="Test`2+B[T,U]">
+      <method name="Void .ctor(Value`1)">
+        <size>7</size>
+      </method>
+      <method name="Void .cctor()">
+        <size>16</size>
+      </method>
+    </type>
+    <type name="C">
+      <method name="Void Main()">
+        <size>7</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
+  <test name="gtest-476.cs">
+    <type name="Test`1[T]">
+      <method name="B First()">
+        <size>10</size>
+      </method>
+      <method name="IFoo Second()">
+        <size>15</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="C">
+      <method name="Void Main()">
+        <size>1</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
+  <test name="gtest-477.cs">
+    <type name="B`1[T]">
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="B`1+BNested[T]">
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="A`1[T]">
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="AA`1[T]">
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="AA`1+ANested[T]">
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="M">
+      <method name="Void Main()">
+        <size>1</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
+  <test name="gtest-478.cs">
+    <type name="M">
+      <method name="Void Foo()">
+        <size>1</size>
+      </method>
+      <method name="Void GenFoo()">
+        <size>1</size>
+      </method>
+      <method name="Void Main()">
+        <size>13</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
+  <test name="gtest-479.cs">
+    <type name="A">
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="B">
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="M">
+      <method name="Void Test[T](I`1)">
+        <size>1</size>
+      </method>
+      <method name="Void Main()">
+        <size>21</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
+  <test name="gtest-480.cs">
+    <type name="C">
+      <method name="Void Foo()">
+        <size>55</size>
+      </method>
+      <method name="Void Main()">
+        <size>30</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
+  <test name="gtest-481.cs">
+    <type name="TestClass`1[T]">
+      <method name="Void Add(T[][] ByRef)">
+        <size>1</size>
+      </method>
+      <method name="Void .ctor(Int32)">
+        <size>18</size>
+      </method>
+    </type>
+    <type name="C">
+      <method name="Void Main()">
+        <size>8</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
   <test name="gtest-anon-1.cs">
     <type name="X">
       <method name="Void .ctor()">
         <size>1</size>
       </method>
       <method name="Void Hello[U,V](U, V)">
-        <size>41</size>
+        <size>47</size>
       </method>
     </type>
     <type name="X">
         <size>26</size>
       </method>
       <method name="Int32 Main()">
-        <size>468</size>
+        <size>501</size>
       </method>
     </type>
     <type name="Test+&lt;For&gt;c__AnonStorey0`1[T]">
         <size>7</size>
       </method>
     </type>
+    <type name="CA`1[T]">
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="Test">
+      <method name="System.Func`1[T[]] NestedTypeMutate[T]()">
+        <size>34</size>
+      </method>
+    </type>
+    <type name="Test+&lt;NestedTypeMutate&gt;c__AnonStoreyC`1[T]">
+      <method name="T[] &lt;&gt;m__C()">
+        <size>37</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
   </test>
   <test name="gtest-anon-25.cs">
     <type name="HS`1[T]">
       </method>
     </type>
   </test>
-  <test name="gtest-anon-47.cs">
-    <type name="C">
-      <method name="System.Func`2[T1,System.Func`2[T2,System.Action`1[T3]]] Curry[T1,T2,T3](System.Action`3[T1,T2,T3])">
-        <size>26</size>
-      </method>
-    </type>
-    <type name="Test">
-      <method name="Void .ctor()">
-        <size>7</size>
-      </method>
-      <method name="Int32 Main()">
-        <size>59</size>
-      </method>
-      <method name="Void &lt;Main&gt;m__3(Int32, Int32, Int32)">
-        <size>23</size>
-      </method>
-    </type>
-    <type name="C+&lt;Curry&gt;c__AnonStorey0`3[T1,T2,T3]">
-      <method name="Void .ctor()">
-        <size>7</size>
-      </method>
-      <method name="System.Func`2[T2,System.Action`1[T3]] &lt;&gt;m__0(T1)">
-        <size>33</size>
-      </method>
-    </type>
-    <type name="C+&lt;Curry&gt;c__AnonStorey0`3+&lt;Curry&gt;c__AnonStorey1`3[T1,T2,T3]">
-      <method name="Void .ctor()">
-        <size>7</size>
-      </method>
-      <method name="System.Action`1[T3] &lt;&gt;m__1(T2)">
-        <size>45</size>
-      </method>
-    </type>
-    <type name="C+&lt;Curry&gt;c__AnonStorey0`3+&lt;Curry&gt;c__AnonStorey1`3+&lt;Curry&gt;c__AnonStorey2`3[T1,T2,T3]">
-      <method name="Void .ctor()">
-        <size>7</size>
-      </method>
-      <method name="Void &lt;&gt;m__2(T3)">
-        <size>35</size>
-      </method>
-    </type>
-  </test>
   <test name="gtest-anon-48.cs">
     <type name="GeneratorEnumerable`1[T]">
       <method name="Void .ctor(Func`1)">
       </method>
     </type>
   </test>
+  <test name="gtest-anon-59.cs">
+    <type name="TestGenericsSubtypeMatching.Sender`1[T]">
+      <method name="Void DoSend[TMessage](System.Action`1[T])">
+        <size>83</size>
+      </method>
+      <method name="Void Send(System.Action`1[T])">
+        <size>1</size>
+      </method>
+      <method name="Void ActionOnObject(System.Object)">
+        <size>8</size>
+      </method>
+      <method name="Void Dispose()">
+        <size>11</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="TestGenericsSubtypeMatching.C">
+      <method name="Void Main()">
+        <size>40</size>
+      </method>
+      <method name="Void &lt;Main&gt;m__1(System.String)">
+        <size>7</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="TestGenericsSubtypeMatching.Sender`1+&lt;DoSend&gt;c__AnonStorey0`1[T,TMessage]">
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="TestGenericsSubtypeMatching.Sender`1+&lt;DoSend&gt;c__AnonStorey1`1[T,TMessage]">
+      <method name="Void &lt;&gt;m__0(T)">
+        <size>35</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
   <test name="gtest-anon-6.cs">
     <type name="X">
       <method name="Void .ctor()">
       </method>
     </type>
   </test>
+  <test name="gtest-exmethod-30.cs">
+    <type name="Test">
+      <method name="IEnumerator System.Collections.IEnumerable.GetEnumerator()">
+        <size>2</size>
+      </method>
+      <method name="Int32 get_First()">
+        <size>2</size>
+      </method>
+      <method name="IEnumerator`1 GetEnumerator()">
+        <size>2</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="C">
+      <method name="Void Test()">
+        <size>14</size>
+      </method>
+      <method name="Void Main()">
+        <size>1</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
+  <test name="gtest-exmethod-31.cs">
+    <type name="N.S">
+      <method name="Void Map[T](Int32, System.Func`2[T,System.String])">
+        <size>1</size>
+      </method>
+    </type>
+    <type name="N2.S2">
+      <method name="Void Map(Int32, Int32)">
+        <size>1</size>
+      </method>
+    </type>
+    <type name="M.C">
+      <method name="Void Main()">
+        <size>8</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
   <test name="gtest-friend-01.cs">
     <type name="Test">
       <method name="Void .ctor()">
         <size>7</size>
       </method>
       <method name="Boolean MoveNext()">
-        <size>183</size>
+        <size>184</size>
       </method>
       <method name="Void Dispose()">
         <size>8</size>
       </method>
     </type>
   </test>
+  <test name="gtest-iter-12.cs">
+    <type name="H">
+      <method name="Void Main(System.String[])">
+        <size>1</size>
+      </method>
+      <method name="IEnumerable`1 Merge[T](IEnumerator`1)">
+        <size>30</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="H+&lt;Merge&gt;c__Iterator0`1[T]">
+      <method name="T System.Collections.Generic.IEnumerator&lt;T&gt;.get_Current()">
+        <size>7</size>
+      </method>
+      <method name="System.Object System.Collections.IEnumerator.get_Current()">
+        <size>12</size>
+      </method>
+      <method name="IEnumerator System.Collections.IEnumerable.GetEnumerator()">
+        <size>7</size>
+      </method>
+      <method name="IEnumerator`1 System.Collections.Generic.IEnumerable&lt;T&gt;.GetEnumerator()">
+        <size>40</size>
+      </method>
+      <method name="Boolean MoveNext()">
+        <size>117</size>
+      </method>
+      <method name="Void Dispose()">
+        <size>8</size>
+      </method>
+      <method name="Void Reset()">
+        <size>6</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
+  <test name="gtest-iter-13.cs">
+    <type name="C`1[T]">
+      <method name="IEnumerator GetEnumerator()">
+        <size>12</size>
+      </method>
+      <method name="IEnumerable`1 Filter(System.Func`2[T,System.Boolean])">
+        <size>37</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="M">
+      <method name="Void Main()">
+        <size>57</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="C`1+&lt;Filter&gt;c__Iterator0[T]">
+      <method name="T System.Collections.Generic.IEnumerator&lt;T&gt;.get_Current()">
+        <size>7</size>
+      </method>
+      <method name="System.Object System.Collections.IEnumerator.get_Current()">
+        <size>12</size>
+      </method>
+      <method name="IEnumerator System.Collections.IEnumerable.GetEnumerator()">
+        <size>7</size>
+      </method>
+      <method name="IEnumerator`1 System.Collections.Generic.IEnumerable&lt;T&gt;.GetEnumerator()">
+        <size>52</size>
+      </method>
+      <method name="Boolean MoveNext()">
+        <size>203</size>
+      </method>
+      <method name="Void Dispose()">
+        <size>62</size>
+      </method>
+      <method name="Void Reset()">
+        <size>6</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
   <test name="gtest-lambda-01.cs">
     <type name="X">
       <method name="Int32 Main()">
       </method>
     </type>
   </test>
+  <test name="gtest-optional-08.cs">
+    <type name="Tests">
+      <method name="Int32 Main()">
+        <size>36</size>
+      </method>
+      <method name="Void .ctor(String)">
+        <size>14</size>
+      </method>
+      <method name="Void .ctor(Int32)">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
   <test name="gtest-partial-01.cs">
     <type name="B`1[U]">
       <method name="Void .ctor()">
         <size>12</size>
       </method>
       <method name="Int32 Main()">
-        <size>25</size>
+        <size>29</size>
       </method>
     </type>
   </test>
       </method>
     </type>
   </test>
-  <test name="test-450.cs">
-    <type name="MyAttribute">
-      <method name="Void .ctor(String)">
-        <size>7</size>
-      </method>
-    </type>
-    <type name="X">
-      <method name="Void .ctor()">
-        <size>7</size>
-      </method>
-      <method name="Void Main()">
-        <size>1</size>
-      </method>
-    </type>
-  </test>
   <test name="test-451.cs">
     <type name="Test">
       <method name="Void .ctor()">
       </method>
     </type>
   </test>
-  <test name="test-454.cs">
-    <type name="FooAttribute">
-      <method name="Void .ctor()">
-        <size>7</size>
-      </method>
-    </type>
-    <type name="Test">
-      <method name="Void .ctor()">
-        <size>7</size>
-      </method>
-      <method name="Int32 Main()">
-        <size>237</size>
-      </method>
-    </type>
-  </test>
   <test name="test-455.cs">
     <type name="Test">
       <method name="Void .ctor()">
         <size>7</size>
       </method>
       <method name="Void Main()">
-        <size>21</size>
+        <size>25</size>
       </method>
     </type>
     <type name="Foo">
         <size>7</size>
       </method>
       <method name="Int32 Main()">
-        <size>61</size>
+        <size>65</size>
       </method>
     </type>
   </test>
   <test name="test-733.cs">
     <type name="Test">
       <method name="Int32 Main()">
-        <size>54</size>
+        <size>86</size>
       </method>
       <method name="Void .ctor()">
         <size>7</size>
   <test name="test-740.cs">
     <type name="FixedTest">
       <method name="Int32 Main()">
-        <size>318</size>
+        <size>348</size>
       </method>
       <method name="Void .ctor()">
         <size>7</size>
       </method>
     </type>
   </test>
+  <test name="test-741.cs">
+    <type name="Test">
+      <method name="Void test()">
+        <size>18</size>
+      </method>
+      <method name="Void Main()">
+        <size>1</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
+  <test name="test-742.cs">
+    <type name="Test">
+      <method name="Test Set(C)">
+        <size>20</size>
+      </method>
+    </type>
+    <type name="C">
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="Driver">
+      <method name="Int32 Main()">
+        <size>41</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
+  <test name="test-743.cs">
+    <type name="C">
+      <method name="Void Main()">
+        <size>11</size>
+      </method>
+      <method name="Void Test()">
+        <size>30</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
+  <test name="test-744.cs">
+    <type name="M">
+      <method name="Void Main()">
+        <size>7</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="M+Nested">
+      <method name="Void Extra()">
+        <size>1</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="A">
+      <method name="Void AMethod()">
+        <size>0</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="B">
+      <method name="Void BMethod()">
+        <size>0</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="C">
+      <method name="Void AMethod()">
+        <size>1</size>
+      </method>
+      <method name="Void BMethod()">
+        <size>1</size>
+      </method>
+      <method name="Void Extra()">
+        <size>0</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
+  <test name="test-745.cs">
+    <type name="C">
+      <method name="Void Main()">
+        <size>28</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
+  <test name="test-746.cs">
+    <type name="Test">
+      <method name="Void Foo(IListCounter)">
+        <size>8</size>
+      </method>
+      <method name="Void Main()">
+        <size>1</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
+  <test name="test-747.cs">
+    <type name="B">
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="B+BNested">
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="A">
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="AA">
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="AA+ANested">
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="M">
+      <method name="Void Main()">
+        <size>1</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
+  <test name="test-748.cs">
+    <type name="M">
+      <method name="RealTest.Foo Test()">
+        <size>6</size>
+      </method>
+      <method name="Void Main()">
+        <size>1</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="Test.Local.M">
+      <method name="RealTest.Foo Test()">
+        <size>6</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="RealTest.Foo">
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
+  <test name="test-749.cs">
+    <type name="M">
+      <method name="Void Main()">
+        <size>14</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
   <test name="test-75.cs">
     <type name="X">
       <method name="Void .ctor()">
       </method>
     </type>
   </test>
+  <test name="test-750.cs">
+    <type name="M">
+      <method name="Void Main()">
+        <size>1</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
+  <test name="test-751.cs">
+    <type name="LocalNS.Compiler">
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="System.Local.M">
+      <method name="Void Main()">
+        <size>7</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
+  <test name="test-752.cs">
+    <type name="M">
+      <method name="Void Main()">
+        <size>1</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
   <test name="test-76.cs">
     <type name="foo">
       <method name="Void .ctor()">
       </method>
     </type>
   </test>
+  <test name="test-cls-19.cs">
+    <type name="A">
+      <method name="Void Main()">
+        <size>1</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+    <type name="A+PartialClass">
+      <method name="Void Method1(Int32)">
+        <size>1</size>
+      </method>
+      <method name="Void Method2(UInt32)">
+        <size>1</size>
+      </method>
+      <method name="Void Method3(UInt32)">
+        <size>1</size>
+      </method>
+      <method name="Void .ctor()">
+        <size>7</size>
+      </method>
+    </type>
+  </test>
   <test name="test-externalias-01.cs">
     <type name="Test">
       <method name="Void .ctor()">
index c30da1899780202f720c6e9cbfe83c929be451c1..5916d229aeb1274ed5a42e7155ea3d156ab68c1f 100644 (file)
@@ -1,3 +1,21 @@
+2010-04-07  Raja R Harinath  <harinath@hurrynot.org>
+
+       * Makefile (DISTFILES): Remove gensources.sh.
+       * gensources.sh: Remove.
+
+2010-04-03  Ankit Jain  <jankit@novell.com>
+
+       * Makefile: Move xbuild from net_4_0_dirs to per_profile_dirs.
+
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * Makefile: rename the net_2_1 profile to moonlight.
+
+2010-03-15  Andrew Jorgensen  <ajorgensen@novell.com>
+
+       * Makefile: Add DIST_SUBDIRS with SUBDIRS and net_4_0_dirs so that all
+       that stuff gets dist'd
+
 2010-03-03  Rolf Bjarne Kvinge  <RKvinge@novell.com>
 
        * gensources.sh: Reverted to plain bash, cygwin/make seems to end up confused
index dd44aad6b0a9b342d008448d5ee04d7eacd8e5cf..970ac6d2e1a49fe4380c998da72b604345421969 100644 (file)
@@ -13,13 +13,13 @@ per_profile_dirs = \
        mono-service    \
        mono-xsd        \
        resgen          \
-       wsdl
+       wsdl            \
+       xbuild
 
 net_4_0_dirs := \
        $(per_profile_dirs) \
        corcompare      \
        mono-xmltool    \
-       xbuild          \
        mdoc            \
        mono-shlib-cop  \
        sgen            \
@@ -48,18 +48,19 @@ net_2_0_dirs := \
        monodoc         \
        compiler-tester
 
-net_2_1_dirs := \
+moonlight_dirs := \
        compiler-tester
 
 basic_SUBDIRS = gacutil security
 net_2_0_bootstrap_SUBDIRS = resgen culevel
 net_2_0_SUBDIRS := $(basic_SUBDIRS) $(net_2_0_dirs)
-net_2_1_raw_SUBDIRS := $(net_2_1_dirs)
-net_2_1_SUBDIRS := $(net_2_1_dirs)
+moonlight_raw_SUBDIRS := $(moonlight_dirs)
+moonlight_SUBDIRS := $(moonlight_dirs)
 net_4_0_bootstrap_SUBDIRS = resgen culevel
 net_4_0_SUBDIRS := $(net_4_0_dirs) $(basic_SUBDIRS)
 
-SUBDIRS = $(basic_SUBDIRS) $(net_2_0_bootstrap_SUBDIRS) $(net_2_0_SUBDIRS) $(net_2_1_SUBDIRS)
+SUBDIRS = $(basic_SUBDIRS) $(net_2_0_bootstrap_SUBDIRS) $(net_2_0_SUBDIRS) $(moonlight_SUBDIRS)
+DIST_SUBDIRS = $(SUBDIRS) $(net_4_0_dirs)
 
 include ../build/rules.make
 
@@ -71,7 +72,6 @@ DISTFILES = \
        scan-tests.pl                   \
        tinderbox/smtp.c                \
        tinderbox/tinderbox.sh          \
-       gensources.sh                   \
        removecomments.sh
 
 test-local csproj-local run-test-local run-test-ondotnet-local all-local install-local uninstall-local doc-update-local:
index ac3dd5e358dbbf6df8cdd155f87d1a8d79822000..062bc5acaa6bd6e2badb291eff5d483546c392fa 100644 (file)
@@ -5,14 +5,14 @@ include ../../build/rules.make
 PROGRAM = $(topdir)/class/lib/$(PROFILE)/compiler-tester.exe
 NO_INSTALL = yes
 
-ifeq (net_2_1, $(PROFILE))
+ifeq (moonlight, $(PROFILE))
 
 all-local: $(PROGRAM)
 clean-local:
        rm -f $(PROGRAM)
 
 $(PROGRAM): $(dir $(PROGRAM))/.stamp
-$(PROGRAM): $(topdir)/class/lib/net_2_1_raw/compiler-tester.exe
+$(PROGRAM): $(topdir)/class/lib/moonlight_raw/compiler-tester.exe
        cp $< $@
 
 dist-local: dist-default
index 82eb5b431617d6e0d2a7c9788a40ebca215a0a2a..1d83160d2b7f9f1ed844decfb1300de2c78c9d3b 100644 (file)
@@ -1,3 +1,8 @@
+2010-04-16  C.J. Adams-Collier <cjac@colliertech.org>
+
+       * mono-api-diff.cs: revived from the mono-2-2 branch and applied
+       patch from debian package, noted that I'll handle maintenance
+       
 2010-02-10  Marek Habersack  <mhabersack@novell.com>
 
        * mono-api-info.cs: added support for extracting and generating
diff --git a/mcs/tools/corcompare/mono-api-diff.cs b/mcs/tools/corcompare/mono-api-diff.cs
new file mode 100644 (file)
index 0000000..c5d2ac1
--- /dev/null
@@ -0,0 +1,1861 @@
+//
+// mono-api-diff.cs - Compares 2 xml files produced by mono-api-info and
+//                   produces a file suitable to build class status pages.
+//
+// Authors:
+//     Gonzalo Paniagua Javier (gonzalo@ximian.com)
+//     Marek Safar             (marek.safar@gmail.com)
+//
+// Maintainer:
+//     C.J. Adams-Collier      (cjac@colliertech.org)
+//
+// (C) 2003 Novell, Inc (http://www.novell.com)
+// (C) 2009,2010 Collier Technologies (http://www.colliertech.org)
+
+using System;
+using System.Collections;
+using System.IO;
+using System.Reflection;
+using System.Text;
+using System.Xml;
+
+namespace Mono.AssemblyCompare
+{
+       class Driver
+       {
+               static int Main (string [] args)
+               {
+                       if (args.Length != 2) {
+                               Console.WriteLine ("Usage: mono mono-api-diff.exe <assembly 1 xml> <assembly 2 xml>");
+                               return 1;
+                       }
+
+                       XMLAssembly ms = CreateXMLAssembly (args [0]);
+                       XMLAssembly mono = CreateXMLAssembly (args [1]);
+                       XmlDocument doc = ms.CompareAndGetDocument (mono);
+
+                       XmlTextWriter writer = new XmlTextWriter (Console.Out);
+                       writer.Formatting = Formatting.Indented;
+                       doc.WriteTo (writer);
+
+                       return 0;
+               }
+
+               static XMLAssembly CreateXMLAssembly (string file)
+               {
+                       XmlDocument doc = new XmlDocument ();
+                       doc.Load (File.OpenRead (file));
+
+                       XmlNode node = doc.SelectSingleNode ("/assemblies/assembly");
+                       XMLAssembly result = new XMLAssembly ();
+                       try {
+                               result.LoadData (node);
+                       } catch (Exception e) {
+                               Console.Error.WriteLine ("Error loading {0}: {1}\n{2}", file, e.Message, e);
+                               Environment.Exit (1);
+                       }
+
+                       return result;
+               }
+       }
+
+       class Counters
+       {
+               public int Present;
+               public int PresentTotal;
+               public int Missing;
+               public int MissingTotal;
+               public int Todo;
+               public int TodoTotal;
+
+               public int Extra;
+               public int ExtraTotal;
+               public int Warning;
+               public int WarningTotal;
+               public int ErrorTotal;
+
+               public Counters ()
+               {
+               }
+
+               public void AddPartialToPartial (Counters other)
+               {
+                       Present += other.Present;
+                       Extra += other.Extra;
+                       Missing += other.Missing;
+
+                       Todo += other.Todo;
+                       Warning += other.Warning;
+                       AddPartialToTotal (other);
+               }
+
+               public void AddPartialToTotal (Counters other)
+               {
+                       PresentTotal += other.Present;
+                       ExtraTotal += other.Extra;
+                       MissingTotal += other.Missing;
+
+                       TodoTotal += other.Todo;
+                       WarningTotal += other.Warning;
+               }
+
+               public void AddTotalToPartial (Counters other)
+               {
+                       Present += other.PresentTotal;
+                       Extra += other.ExtraTotal;
+                       Missing += other.MissingTotal;
+
+                       Todo += other.TodoTotal;
+                       Warning += other.WarningTotal;
+                       AddTotalToTotal (other);
+               }
+
+               public void AddTotalToTotal (Counters other)
+               {
+                       PresentTotal += other.PresentTotal;
+                       ExtraTotal += other.ExtraTotal;
+                       MissingTotal += other.MissingTotal;
+
+                       TodoTotal += other.TodoTotal;
+                       WarningTotal += other.WarningTotal;
+                       ErrorTotal += other.ErrorTotal;
+               }
+
+               public int Total {
+                       get { return Present + Missing; }
+               }
+
+               public int AbsTotal {
+                       get { return PresentTotal + MissingTotal; }
+               }
+
+               public int Ok {
+                       get { return Present - Todo; }
+               }
+
+               public int OkTotal {
+                       get { return PresentTotal - TodoTotal - ErrorTotal; }
+               }
+
+               public override string ToString ()
+               {
+                       StringWriter sw = new StringWriter ();
+                       sw.WriteLine ("Present: {0}", Present);
+                       sw.WriteLine ("PresentTotal: {0}", PresentTotal);
+                       sw.WriteLine ("Missing: {0}", Missing);
+                       sw.WriteLine ("MissingTotal: {0}", MissingTotal);
+                       sw.WriteLine ("Todo: {0}", Todo);
+                       sw.WriteLine ("TodoTotal: {0}", TodoTotal);
+                       sw.WriteLine ("Extra: {0}", Extra);
+                       sw.WriteLine ("ExtraTotal: {0}", ExtraTotal);
+                       sw.WriteLine ("Warning: {0}", Warning);
+                       sw.WriteLine ("WarningTotal: {0}", WarningTotal);
+                       sw.WriteLine ("ErrorTotal: {0}", ErrorTotal);
+                       sw.WriteLine ("--");
+                       return sw.GetStringBuilder ().ToString ();
+               }
+       }
+
+       abstract class XMLData
+       {
+               protected XmlDocument document;
+               protected Counters counters;
+               bool haveWarnings;
+
+               public XMLData ()
+               {
+                       counters = new Counters ();
+               }
+
+               public virtual void LoadData (XmlNode node)
+               {
+               }
+
+               protected object [] LoadRecursive (XmlNodeList nodeList, Type type)
+               {
+                       ArrayList list = new ArrayList ();
+                       foreach (XmlNode node in nodeList) {
+                               XMLData data = (XMLData) Activator.CreateInstance (type);
+                               data.LoadData (node);
+                               list.Add (data);
+                       }
+
+                       return (object []) list.ToArray (type);
+               }
+
+               public static bool IsMeaninglessAttribute (string s)
+               {
+                       if (s == null)
+                               return false;
+                       if (s == "System.Runtime.CompilerServices.CompilerGeneratedAttribute")
+                               return true;
+                       return false;
+               }
+
+               public static bool IsMonoTODOAttribute (string s)
+               {
+                       if (s == null)
+                               return false;
+                       if (//s.EndsWith ("MonoTODOAttribute") ||
+                           s.EndsWith ("MonoDocumentationNoteAttribute") ||
+                           s.EndsWith ("MonoExtensionAttribute") ||
+//                         s.EndsWith ("MonoInternalNoteAttribute") ||
+                           s.EndsWith ("MonoLimitationAttribute") ||
+                           s.EndsWith ("MonoNotSupportedAttribute"))
+                               return true;
+                       return s.EndsWith ("TODOAttribute");
+               }
+
+               protected void AddAttribute (XmlNode node, string name, string value)
+               {
+                       XmlAttribute attr = document.CreateAttribute (name);
+                       attr.Value = value;
+                       node.Attributes.Append (attr);
+               }
+
+               protected void AddExtra (XmlNode node)
+               {
+                       //TODO: count all the subnodes?
+                       AddAttribute (node, "presence", "extra");
+                       AddAttribute (node, "ok", "1");
+                       AddAttribute (node, "ok_total", "1");
+                       AddAttribute (node, "extra", "1");
+                       AddAttribute (node, "extra_total", "1");
+               }
+
+               public void AddCountersAttributes (XmlNode node)
+               {
+                       if (counters.Missing > 0)
+                               AddAttribute (node, "missing", counters.Missing.ToString ());
+
+                       if (counters.Present > 0)
+                               AddAttribute (node, "present", counters.Present.ToString ());
+
+                       if (counters.Extra > 0)
+                               AddAttribute (node, "extra", counters.Extra.ToString ());
+
+                       if (counters.Ok > 0)
+                               AddAttribute (node, "ok", counters.Ok.ToString ());
+
+                       if (counters.Total > 0) {
+                               int percent = (100 * counters.Ok / counters.Total);
+                               AddAttribute (node, "complete", percent.ToString ());
+                       }
+
+                       if (counters.Todo > 0)
+                               AddAttribute (node, "todo", counters.Todo.ToString ());
+
+                       if (counters.Warning > 0)
+                               AddAttribute (node, "warning", counters.Warning.ToString ());
+
+                       if (counters.MissingTotal > 0)
+                               AddAttribute (node, "missing_total", counters.MissingTotal.ToString ());
+
+                       if (counters.PresentTotal > 0)
+                               AddAttribute (node, "present_total", counters.PresentTotal.ToString ());
+
+                       if (counters.ExtraTotal > 0)
+                               AddAttribute (node, "extra_total", counters.ExtraTotal.ToString ());
+
+                       if (counters.OkTotal > 0)
+                               AddAttribute (node, "ok_total", counters.OkTotal.ToString ());
+
+                       if (counters.AbsTotal > 0) {
+                               int percent = (100 * counters.OkTotal / counters.AbsTotal);
+                               AddAttribute (node, "complete_total", percent.ToString ());
+                       }
+
+                       if (counters.TodoTotal > 0) {
+                               AddAttribute (node, "todo_total", counters.TodoTotal.ToString ());
+                               //TODO: should be different on error. check error cases in corcompare.
+                               AddAttribute (node, "error_total", counters.Todo.ToString ());
+                       }
+
+                       if (counters.WarningTotal > 0)
+                               AddAttribute (node, "warning_total", counters.WarningTotal.ToString ());
+
+               }
+
+               protected void AddWarning (XmlNode parent, string fmt, params object [] args)
+               {
+                       counters.Warning++;
+                       haveWarnings = true;
+                       XmlNode warnings = parent.SelectSingleNode ("warnings");
+                       if (warnings == null) {
+                               warnings = document.CreateElement ("warnings", null);
+                               parent.AppendChild (warnings);
+                       }
+
+                       AddAttribute (parent, "error", "warning");
+                       XmlNode warning = document.CreateElement ("warning", null);
+                       AddAttribute (warning, "text", String.Format (fmt, args));
+                       warnings.AppendChild (warning);
+               }
+
+               public bool HaveWarnings {
+                       get { return haveWarnings; }
+               }
+               
+               public Counters Counters {
+                       get { return counters; }
+               }
+               
+               public abstract void CompareTo (XmlDocument doc, XmlNode parent, object other);
+       }
+       
+       abstract class XMLNameGroup : XMLData
+       {
+               protected XmlNode group;
+               protected Hashtable keys;
+
+               public override void LoadData (XmlNode node)
+               {
+                       if (node == null)
+                               throw new ArgumentNullException ("node");
+
+                       if (node.Name != GroupName)
+                               throw new FormatException (String.Format ("Expecting <{0}>", GroupName));
+
+                       keys = new Hashtable ();
+                       foreach (XmlNode n in node.ChildNodes) {
+                               string name = n.Attributes ["name"].Value;
+                               if (CheckIfAdd (name, n)) {
+                                       string key = GetNodeKey (name, n);
+                                       //keys.Add (key, name);
+                                       keys [key] = name;
+                                       LoadExtraData (key, n);
+                               }
+                       }
+               }
+
+               protected virtual bool CheckIfAdd (string value, XmlNode node)
+               {
+                       return true;
+               }
+
+               protected virtual void LoadExtraData (string name, XmlNode node)
+               {
+               }
+
+               public override void CompareTo (XmlDocument doc, XmlNode parent, object other)
+               {
+                       this.document = doc;
+                       if (group == null)
+                               group = doc.CreateElement (GroupName, null);
+
+                       Hashtable okeys = null;
+                       if (other != null && ((XMLNameGroup) other).keys != null) {
+                               okeys = ((XMLNameGroup) other).keys;
+                       }
+
+                       XmlNode node = null;
+                       bool onull = (okeys == null);
+                       if (keys != null) {
+                               foreach (DictionaryEntry entry in keys) {
+                                       node = doc.CreateElement (Name, null);
+                                       group.AppendChild (node);
+                                       string key = (string) entry.Key;
+                                       string name = (string) entry.Value;
+                                       AddAttribute (node, "name", name);
+
+                                       if (!onull && HasKey (key, okeys)) {
+                                               CompareToInner (key, node, (XMLNameGroup) other);
+                                               okeys.Remove (key);
+                                               counters.Present++;
+                                       } else {
+                                               AddAttribute (node, "presence", "missing");
+                                               counters.Missing++;
+                                       }
+                               }
+                       }
+
+                       if (!onull && okeys.Count != 0) {
+                               foreach (string value in okeys.Values) {
+                                       node = doc.CreateElement (Name, null);
+                                       AddAttribute (node, "name", (string) value);
+                                       AddAttribute (node, "presence", "extra");
+                                       group.AppendChild (node);
+                                       counters.Extra++;
+                               }
+                       }
+
+                       if (group.HasChildNodes)
+                               parent.AppendChild (group);
+               }
+
+               protected virtual void CompareToInner (string name, XmlNode node, XMLNameGroup other)
+               {
+               }
+
+               public virtual string GetNodeKey (string name, XmlNode node)
+               {
+                       return name;
+               }
+
+               public virtual bool HasKey (string key, Hashtable other)
+               {
+                       return other.ContainsKey (key);
+               }
+
+               public abstract string GroupName { get; }
+               public abstract string Name { get; }
+       }
+
+       class XMLAssembly : XMLData
+       {
+               XMLAttributes attributes;
+               XMLNamespace [] namespaces;
+               string name;
+               string version;
+
+               public override void LoadData (XmlNode node)
+               {
+                       if (node == null)
+                               throw new ArgumentNullException ("node");
+
+                       name = node.Attributes ["name"].Value;
+                       version = node.Attributes  ["version"].Value;
+                       XmlNode atts = node.FirstChild;
+                       attributes = new XMLAttributes ();
+                       if (atts.Name == "attributes") {
+                               attributes.LoadData (atts);
+                               atts = atts.NextSibling;
+                       }
+
+                       if (atts == null || atts.Name != "namespaces") {
+                               Console.Error.WriteLine ("Warning: no namespaces found!");
+                               return;
+                       }
+
+                       namespaces = (XMLNamespace []) LoadRecursive (atts.ChildNodes, typeof (XMLNamespace));
+               }
+
+               public override void CompareTo (XmlDocument doc, XmlNode parent, object other)
+               {
+                       XMLAssembly assembly = (XMLAssembly) other;
+
+                       XmlNode childA = doc.CreateElement ("assembly", null);
+                       AddAttribute (childA, "name", name);
+                       AddAttribute (childA, "version", version);
+                       if (name != assembly.name)
+                               AddWarning (childA, "Assembly names not equal: {0}, {1}", name, assembly.name);
+
+                       if (version != assembly.version)
+                               AddWarning (childA, "Assembly version not equal: {0}, {1}", version, assembly.version);
+
+                       parent.AppendChild (childA);
+
+                       attributes.CompareTo (doc, childA, assembly.attributes);
+                       counters.AddPartialToPartial (attributes.Counters);
+
+                       CompareNamespaces (childA, assembly.namespaces);
+                       if (assembly.attributes != null && assembly.attributes.IsTodo) {
+                               counters.Todo++;
+                               counters.TodoTotal++;
+                               counters.ErrorTotal++;
+                               AddAttribute (childA, "error", "todo");
+                               if (assembly.attributes.Comment != null)
+                                       AddAttribute (childA, "comment", assembly.attributes.Comment);
+                       }
+
+                       AddCountersAttributes (childA);
+               }
+
+               void CompareNamespaces (XmlNode parent, XMLNamespace [] other)
+               {
+                       ArrayList newNS = new ArrayList ();
+                       XmlNode group = document.CreateElement ("namespaces", null);
+                       parent.AppendChild (group);
+
+                       Hashtable oh = CreateHash (other);
+                       XmlNode node = null;
+                       int count = (namespaces == null) ? 0 : namespaces.Length;
+                       for (int i = 0; i < count; i++) {
+                               XMLNamespace xns = namespaces [i];
+
+                               node = document.CreateElement ("namespace", null);
+                               newNS.Add (node);
+                               AddAttribute (node, "name", xns.Name);
+
+                               int idx = -1;
+                               if (oh.ContainsKey (xns.Name))
+                                       idx = (int) oh [xns.Name];
+                               XMLNamespace ons = idx >= 0 ? (XMLNamespace) other [idx] : null;
+                               xns.CompareTo (document, node, ons);
+                               if (idx >= 0)
+                                       other [idx] = null;
+                               xns.AddCountersAttributes (node);
+                               counters.Present++;
+                               counters.PresentTotal++;
+                               counters.AddPartialToTotal (xns.Counters);
+                       }
+
+                       if (other != null) {
+                               count = other.Length;
+                               for (int i = 0; i < count; i++) {
+                                       XMLNamespace n = other [i];
+                                       if (n == null)
+                                               continue;
+
+                                       node = document.CreateElement ("namespace", null);
+                                       newNS.Add (node);
+                                       AddAttribute (node, "name", n.Name);
+                                       AddExtra (node);
+                                       counters.ExtraTotal++;
+                               }
+                       }
+
+                       XmlNode [] nodes = (XmlNode []) newNS.ToArray (typeof (XmlNode));
+                       Array.Sort (nodes, XmlNodeComparer.Default);
+                       foreach (XmlNode nn in nodes)
+                               group.AppendChild (nn);
+               }
+
+               static Hashtable CreateHash (XMLNamespace [] other)
+               {
+                       Hashtable result = new Hashtable ();
+                       if (other != null) {
+                               int i = 0;
+                               foreach (XMLNamespace n in other) {
+                                       result [n.Name] = i++;
+                               }
+                       }
+
+                       return result;
+               }
+
+               public XmlDocument CompareAndGetDocument (XMLAssembly other)
+               {
+                       XmlDocument doc = new XmlDocument ();
+                       this.document = doc;
+                       XmlNode parent = doc.CreateElement ("assemblies", null);
+                       doc.AppendChild (parent);
+                       
+                       CompareTo (doc, parent, other);
+
+                       XmlNode decl = doc.CreateXmlDeclaration ("1.0", null, null);
+                       doc.InsertBefore (decl, doc.DocumentElement);
+
+                       return doc;
+               }
+       }
+
+       class XMLNamespace : XMLData
+       {
+               string name;
+               XMLClass [] types;
+
+               public override void LoadData (XmlNode node)
+               {
+                       if (node == null)
+                               throw new ArgumentNullException ("node");
+
+                       if (node.Name != "namespace")
+                               throw new FormatException ("Expecting <namespace>");
+
+                       name = node.Attributes  ["name"].Value;
+                       XmlNode classes = node.FirstChild;
+                       if (classes == null) {
+                               Console.Error.WriteLine ("Warning: no classes for {0}", node.Attributes  ["name"]);
+                               return;
+                       }
+
+                       if (classes.Name != "classes")
+                               throw new FormatException ("Expecting <classes>. Got <" + classes.Name + ">");
+
+                       types = (XMLClass []) LoadRecursive (classes.ChildNodes, typeof (XMLClass));
+               }
+
+               public override void CompareTo (XmlDocument doc, XmlNode parent, object other)
+               {
+                       this.document = doc;
+                       XMLNamespace nspace = (XMLNamespace) other;
+
+                       XmlNode childA = doc.CreateElement ("classes", null);
+                       parent.AppendChild (childA);
+
+                       CompareTypes (childA, nspace != null ? nspace.types : new XMLClass [0]);
+               }
+
+               void CompareTypes (XmlNode parent, XMLClass [] other)
+               {
+                       ArrayList newNodes = new ArrayList ();
+                       Hashtable oh = CreateHash (other);
+                       XmlNode node = null;
+                       int count = (types == null) ? 0 : types.Length;
+                       for (int i = 0; i < count; i++) {
+                               XMLClass xclass = types [i];
+
+                               node = document.CreateElement ("class", null);
+                               newNodes.Add (node);
+                               AddAttribute (node, "name", xclass.Name);
+                               AddAttribute (node, "type", xclass.Type);
+
+                               int idx = -1;
+                               if (oh.ContainsKey (xclass.Name))
+                                       idx = (int) oh [xclass.Name];
+                               xclass.CompareTo (document, node, idx >= 0 ? other [idx] : new XMLClass ());
+                               if (idx >= 0)
+                                       other [idx] = null;
+                               counters.AddPartialToPartial (xclass.Counters);
+                       }
+
+                       if (other != null) {
+                               count = other.Length;
+                               for (int i = 0; i < count; i++) {
+                                       XMLClass c = other [i];
+                                       if (c == null || IsMonoTODOAttribute (c.Name))
+                                               continue;
+
+                                       node = document.CreateElement ("class", null);
+                                       newNodes.Add (node);
+                                       AddAttribute (node, "name", c.Name);
+                                       AddAttribute (node, "type", c.Type);
+                                       AddExtra (node);
+                                       counters.Extra++;
+                                       counters.ExtraTotal++;
+                               }
+                       }
+
+                       XmlNode [] nodes = (XmlNode []) newNodes.ToArray (typeof (XmlNode));
+                       Array.Sort (nodes, XmlNodeComparer.Default);
+                       foreach (XmlNode nn in nodes)
+                               parent.AppendChild (nn);
+               }
+
+               static Hashtable CreateHash (XMLClass [] other)
+               {
+                       Hashtable result = new Hashtable ();
+                       if (other != null) {
+                               int i = 0;
+                               foreach (XMLClass c in other) {
+                                       result [c.Name] = i++;
+                               }
+                       }
+
+                       return result;
+               }
+
+               public string Name {
+                       get { return name; }
+               }
+       }
+
+       class XMLClass : XMLData
+       {
+               string name;
+               string type;
+               string baseName;
+               bool isSealed;
+               bool isSerializable;
+               bool isAbstract;
+               string charSet;
+               string layout;
+               XMLAttributes attributes;
+               XMLInterfaces interfaces;
+               XMLGenericTypeConstraints genericConstraints;
+               XMLFields fields;
+               XMLConstructors constructors;
+               XMLProperties properties;
+               XMLEvents events;
+               XMLMethods methods;
+               XMLClass [] nested;
+               
+               public override void LoadData (XmlNode node)
+               {
+                       if (node == null)
+                               throw new ArgumentNullException ("node");
+
+                       name = node.Attributes ["name"].Value;
+                       type = node.Attributes  ["type"].Value;
+                       XmlAttribute xatt = node.Attributes ["base"];
+                       if (xatt != null)
+                               baseName = xatt.Value;
+
+                       xatt = node.Attributes ["sealed"];
+                       isSealed = (xatt != null && xatt.Value == "true");
+
+                       xatt = node.Attributes ["abstract"];
+                       isAbstract = (xatt != null && xatt.Value == "true");
+
+                       xatt = node.Attributes["serializable"];
+                       isSerializable = (xatt != null && xatt.Value == "true");
+
+                       xatt = node.Attributes["charset"];
+                       if (xatt != null)
+                               charSet = xatt.Value;
+
+                       xatt = node.Attributes["layout"];
+                       if (xatt != null)
+                               layout = xatt.Value;
+
+                       XmlNode child = node.FirstChild;
+                       if (child == null) {
+                               // Console.Error.WriteLine ("Empty class {0} {1}", name, type);
+                               return;
+                       }
+                               
+                       if (child.Name == "attributes") {
+                               attributes = new XMLAttributes ();
+                               attributes.LoadData (child);
+                               child = child.NextSibling;
+                       }
+
+                       if (child != null && child.Name == "interfaces") {
+                               interfaces = new XMLInterfaces ();
+                               interfaces.LoadData (child);
+                               child = child.NextSibling;
+                       }
+
+                       if (child != null && child.Name == "generic-type-constraints") {
+                               genericConstraints = new XMLGenericTypeConstraints ();
+                               genericConstraints.LoadData (child);
+                               child = child.NextSibling;
+                       }
+
+                       if (child != null && child.Name == "fields") {
+                               fields = new XMLFields ();
+                               fields.LoadData (child);
+                               child = child.NextSibling;
+                       }
+
+                       if (child != null && child.Name == "constructors") {
+                               constructors = new XMLConstructors ();
+                               constructors.LoadData (child);
+                               child = child.NextSibling;
+                       }
+
+                       if (child != null && child.Name == "properties") {
+                               properties = new XMLProperties ();
+                               properties.LoadData (child);
+                               child = child.NextSibling;
+                       }
+
+                       if (child != null && child.Name == "events") {
+                               events = new XMLEvents ();
+                               events.LoadData (child);
+                               child = child.NextSibling;
+                       }
+
+                       if (child != null && child.Name == "methods") {
+                               methods = new XMLMethods ();
+                               methods.LoadData (child);
+                               child = child.NextSibling;
+                       }
+
+                       if (child != null && child.Name == "generic-parameters") {
+                               // HACK: ignore this tag as it doesn't seem to
+                               // add any value when checking for differences
+                               return;
+                       }
+
+                       if (child == null)
+                               return;
+
+                       if (child.Name != "classes") {
+                               Console.WriteLine ("name: {0} type: {1} {2}", name, type, child.NodeType);
+                               throw new FormatException ("Expecting <classes>. Got <" + child.Name + ">");
+                       }
+
+                       nested = (XMLClass []) LoadRecursive (child.ChildNodes, typeof (XMLClass));
+               }
+
+               public override void CompareTo (XmlDocument doc, XmlNode parent, object other)
+               {
+                       this.document = doc;
+                       XMLClass oclass = (XMLClass) other;
+
+                       if (attributes != null || oclass.attributes != null) {
+                               if (attributes == null)
+                                       attributes = new XMLAttributes ();
+
+                               attributes.CompareTo (doc, parent, oclass.attributes);
+                               counters.AddPartialToPartial (attributes.Counters);
+                               if (oclass.attributes != null && oclass.attributes.IsTodo) {
+                                       counters.Todo++;
+                                       counters.TodoTotal++;
+                                       counters.ErrorTotal++;
+                                       AddAttribute (parent, "error", "todo");
+                                       if (oclass.attributes.Comment != null)
+                                               AddAttribute (parent, "comment", oclass.attributes.Comment);
+                               }
+                       }
+
+                       if (type != oclass.type)
+                               AddWarning (parent, "Class type is wrong: {0} != {1}", type, oclass.type);
+
+                       if (baseName != oclass.baseName)
+                               AddWarning (parent, "Base class is wrong: {0} != {1}", baseName, oclass.baseName);
+
+                       if (isAbstract != oclass.isAbstract || isSealed != oclass.isSealed) {
+                               if ((isAbstract && isSealed) || (oclass.isAbstract && oclass.isSealed))
+                                       AddWarning (parent, "Should {0}be static", (isAbstract && isSealed) ? "" : "not ");
+                               else if (isAbstract != oclass.isAbstract)
+                                       AddWarning (parent, "Should {0}be abstract", isAbstract ? "" : "not ");
+                               else if (isSealed != oclass.isSealed)
+                                       AddWarning (parent, "Should {0}be sealed", isSealed ? "" : "not ");
+                       }
+
+                       if (isSerializable != oclass.isSerializable)
+                               AddWarning (parent, "Should {0}be serializable", isSerializable ? "" : "not ");
+
+                       if (charSet != oclass.charSet)
+                               AddWarning (parent, "CharSet is wrong: {0} != {1}", charSet, oclass.charSet);
+
+                       if (layout != oclass.layout)
+                               AddWarning (parent, "Layout is wrong: {0} != {1}", layout, oclass.layout);
+
+                       if (interfaces != null || oclass.interfaces != null) {
+                               if (interfaces == null)
+                                       interfaces = new XMLInterfaces ();
+
+                               interfaces.CompareTo (doc, parent, oclass.interfaces);
+                               counters.AddPartialToPartial (interfaces.Counters);
+                       }
+
+                       if (genericConstraints != null || oclass.genericConstraints != null) {
+                               if (genericConstraints == null)
+                                       genericConstraints = new XMLGenericTypeConstraints ();
+
+                               genericConstraints.CompareTo (doc, parent, oclass.genericConstraints);
+                               counters.AddPartialToPartial (genericConstraints.Counters);
+                       }
+
+                       if (fields != null || oclass.fields != null) {
+                               if (fields == null)
+                                       fields = new XMLFields ();
+
+                               fields.CompareTo (doc, parent, oclass.fields);
+                               counters.AddPartialToPartial (fields.Counters);
+                       }
+
+                       if (constructors != null || oclass.constructors != null) {
+                               if (constructors == null)
+                                       constructors = new XMLConstructors ();
+
+                               constructors.CompareTo (doc, parent, oclass.constructors);
+                               counters.AddPartialToPartial (constructors.Counters);
+                       }
+
+                       if (properties != null || oclass.properties != null) {
+                               if (properties == null)
+                                       properties = new XMLProperties ();
+
+                               properties.CompareTo (doc, parent, oclass.properties);
+                               counters.AddPartialToPartial (properties.Counters);
+                       }
+
+                       if (events != null || oclass.events != null) {
+                               if (events == null)
+                                       events = new XMLEvents ();
+
+                               events.CompareTo (doc, parent, oclass.events);
+                               counters.AddPartialToPartial (events.Counters);
+                       }
+
+                       if (methods != null || oclass.methods != null) {
+                               if (methods == null)
+                                       methods = new XMLMethods ();
+
+                               methods.CompareTo (doc, parent, oclass.methods);
+                               counters.AddPartialToPartial (methods.Counters);
+                       }
+
+                       if (nested != null || oclass.nested != null) {
+                               XmlNode n = doc.CreateElement ("classes", null);
+                               parent.AppendChild (n);
+                               CompareTypes (n, oclass.nested);
+                       }
+
+                       AddCountersAttributes (parent);
+               }
+
+               void CompareTypes (XmlNode parent, XMLClass [] other)
+               {
+                       ArrayList newNodes = new ArrayList ();
+                       Hashtable oh = CreateHash (other);
+                       XmlNode node = null;
+                       int count = (nested == null) ? 0 : nested.Length;
+                       for (int i = 0; i < count; i++) {
+                               XMLClass xclass = nested [i];
+
+                               node = document.CreateElement ("class", null);
+                               newNodes.Add (node);
+                               AddAttribute (node, "name", xclass.Name);
+                               AddAttribute (node, "type", xclass.Type);
+
+                               if (oh.ContainsKey (xclass.Name)) {
+                                       int idx = (int) oh [xclass.Name];
+                                       xclass.CompareTo (document, node, other [idx]);
+                                       other [idx] = null;
+                                       counters.AddPartialToPartial (xclass.Counters);
+                               } else {
+                                       // TODO: Should I count here?
+                                       AddAttribute (node, "presence", "missing");
+                                       counters.Missing++;
+                                       counters.MissingTotal++;
+                               }
+                       }
+
+                       if (other != null) {
+                               count = other.Length;
+                               for (int i = 0; i < count; i++) {
+                                       XMLClass c = other [i];
+                                       if (c == null || IsMonoTODOAttribute (c.Name))
+                                               continue;
+
+                                       node = document.CreateElement ("class", null);
+                                       newNodes.Add (node);
+                                       AddAttribute (node, "name", c.Name);
+                                       AddAttribute (node, "type", c.Type);
+                                       AddExtra (node);
+                                       counters.Extra++;
+                                       counters.ExtraTotal++;
+                               }
+                       }
+
+                       XmlNode [] nodes = (XmlNode []) newNodes.ToArray (typeof (XmlNode));
+                       Array.Sort (nodes, XmlNodeComparer.Default);
+                       foreach (XmlNode nn in nodes)
+                               parent.AppendChild (nn);
+               }
+
+               static Hashtable CreateHash (XMLClass [] other)
+               {
+                       Hashtable result = new Hashtable ();
+                       if (other != null) {
+                               int i = 0;
+                               foreach (XMLClass c in other) {
+                                       result [c.Name] = i++;
+                               }
+                       }
+
+                       return result;
+               }
+
+               public string Name {
+                       get { return name; }
+               }
+
+               public string Type {
+                       get { return type; }
+               }
+       }
+
+       class XMLParameter : XMLData
+       {
+               string name;
+               string type;
+               string attrib;
+               string direction;
+               bool isUnsafe;
+               bool isOptional;
+               string defaultValue;
+               XMLAttributes attributes;
+
+               public override void LoadData (XmlNode node)
+               {
+                       if (node == null)
+                               throw new ArgumentNullException ("node");
+
+                       if (node.Name != "parameter")
+                               throw new ArgumentException ("Expecting <parameter>");
+
+                       name = node.Attributes["name"].Value;
+                       type = node.Attributes["type"].Value;
+                       attrib = node.Attributes["attrib"].Value;
+                       if (node.Attributes ["direction"] != null)
+                               direction = node.Attributes["direction"].Value;
+                       if (node.Attributes["unsafe"] != null)
+                               isUnsafe = bool.Parse (node.Attributes["unsafe"].Value);
+                       if (node.Attributes["optional"] != null)
+                               isOptional = bool.Parse (node.Attributes["optional"].Value);
+                       if (node.Attributes["defaultValue"] != null)
+                               defaultValue = node.Attributes["defaultValue"].Value;
+
+                       XmlNode child = node.FirstChild;
+                       if (child == null)
+                               return;
+
+                       if (child.Name == "attributes") {
+                               attributes = new XMLAttributes ();
+                               attributes.LoadData (child);
+                               child = child.NextSibling;
+                       }
+               }
+
+               public override void CompareTo (XmlDocument doc, XmlNode parent, object other)
+               {
+                       this.document = doc;
+
+                       XMLParameter oparm = (XMLParameter) other;
+
+                       if (name != oparm.name)
+                               AddWarning (parent, "Parameter name is wrong: {0} != {1}", name, oparm.name);
+
+                       if (type != oparm.type)
+                               AddWarning (parent, "Parameter type is wrong: {0} != {1}", type, oparm.type);
+                       
+                       if (attrib != oparm.attrib)
+                               AddWarning (parent, "Parameter attributes wrong: {0} != {1}", attrib, oparm.attrib);
+
+                       if (direction != oparm.direction)
+                               AddWarning (parent, "Parameter direction wrong: {0} != {1}", direction, oparm.direction);
+
+                       if (isUnsafe != oparm.isUnsafe)
+                               AddWarning (parent, "Parameter unsafe wrong: {0} != {1}", isUnsafe, oparm.isUnsafe);
+
+                       if (isOptional != oparm.isOptional)
+                               AddWarning (parent, "Parameter optional wrong: {0} != {1}", isOptional, oparm.isOptional);
+
+                       if (defaultValue != oparm.defaultValue)
+                               AddWarning (parent, "Parameter default value wrong: {0} != {1}", (defaultValue == null) ? "(no default value)" : defaultValue, (oparm.defaultValue == null) ? "(no default value)" : oparm.defaultValue);
+
+                       if (attributes != null || oparm.attributes != null) {
+                               if (attributes == null)
+                                       attributes = new XMLAttributes ();
+
+                               attributes.CompareTo (doc, parent, oparm.attributes);
+                               counters.AddPartialToPartial (attributes.Counters);
+                               if (oparm.attributes != null && oparm.attributes.IsTodo) {
+                                       counters.Todo++;
+                                       counters.TodoTotal++;
+                                       counters.ErrorTotal++;
+                                       AddAttribute (parent, "error", "todo");
+                                       if (oparm.attributes.Comment != null)
+                                               AddAttribute (parent, "comment", oparm.attributes.Comment);
+                               }
+                       }
+               }
+
+               public string Name {
+                       get { return name; }
+               }
+       }
+
+       class XMLAttributeProperties: XMLNameGroup
+       {
+               static Hashtable ignored_properties;
+               static XMLAttributeProperties ()
+               {
+                       ignored_properties = new Hashtable ();
+                       ignored_properties.Add ("System.Reflection.AssemblyKeyFileAttribute", "KeyFile");
+                       ignored_properties.Add ("System.Reflection.AssemblyCompanyAttribute", "Company");
+                       ignored_properties.Add ("System.Reflection.AssemblyConfigurationAttribute", "Configuration");
+                       ignored_properties.Add ("System.Reflection.AssemblyCopyrightAttribute", "Copyright");
+                       ignored_properties.Add ("System.Reflection.AssemblyProductAttribute", "Product");
+                       ignored_properties.Add ("System.Reflection.AssemblyTrademarkAttribute", "Trademark");
+                       ignored_properties.Add ("System.Reflection.AssemblyInformationalVersionAttribute", "InformationalVersion");
+
+                       ignored_properties.Add ("System.ObsoleteAttribute", "Message");
+                       ignored_properties.Add ("System.IO.IODescriptionAttribute", "Description");
+                       ignored_properties.Add ("System.Diagnostics.MonitoringDescriptionAttribute", "Description");
+               }
+
+               Hashtable properties = new Hashtable ();
+               string attribute;
+
+               public XMLAttributeProperties (string attribute)
+               {
+                       this.attribute = attribute;
+               }
+
+               public override void LoadData(XmlNode node)
+               {
+                       if (node == null)
+                               throw new ArgumentNullException ("node");
+
+                       if (node.ChildNodes == null)
+                               return;
+
+                       string ignored = ignored_properties [attribute] as string;
+
+                       foreach (XmlNode n in node.ChildNodes) {
+                               string name = n.Attributes ["name"].Value;
+                               if (ignored == name)
+                                       continue;
+
+                               if (n.Attributes ["null"] != null) {
+                                       properties.Add (name, null);
+                                       continue;
+                               }
+                               string value = n.Attributes ["value"].Value;
+                               properties.Add (name, value);
+                       }
+               }
+
+               public override void CompareTo (XmlDocument doc, XmlNode parent, object other)
+               {
+                       this.document = doc;
+
+                       Hashtable other_properties = ((XMLAttributeProperties)other).properties;
+                       foreach (DictionaryEntry de in other_properties) {
+                               object other_value = properties [de.Key];
+
+                               if (de.Value == null) {
+                                       if (other_value != null)
+                                               AddWarning (parent, "Property '{0}' is 'null' and should be '{1}'", de.Key, other_value);
+                                       continue;
+                               }
+
+                               if (de.Value.Equals (other_value))
+                                       continue;
+
+                               AddWarning (parent, "Property '{0}' is '{1}' and should be '{2}'", 
+                                       de.Key, de.Value, other_value == null ? "null" : other_value);
+                       }
+               }
+
+               public override string GroupName {
+                       get {
+                               return "properties";
+                       }
+               }
+
+               public override string Name {
+                       get {
+                               return "";
+                       }
+               }
+       }
+
+       class XMLAttributes : XMLNameGroup
+       {
+               Hashtable properties = new Hashtable ();
+
+               bool isTodo;
+               string comment;
+
+               protected override bool CheckIfAdd (string value, XmlNode node)
+               {
+                       if (IsMonoTODOAttribute (value)) {
+                               isTodo = true;
+
+                               XmlNode pNode = node.SelectSingleNode ("properties");
+                               if (pNode != null && pNode.ChildNodes.Count > 0 && pNode.ChildNodes [0].Attributes ["value"] != null) {
+                                       comment = pNode.ChildNodes [0].Attributes ["value"].Value;
+                               }
+                               return false;
+                       }
+
+                       return !IsMeaninglessAttribute (value);
+               }
+
+               protected override void CompareToInner (string name, XmlNode node, XMLNameGroup other)
+               {
+                       XMLAttributeProperties other_prop = ((XMLAttributes)other).properties [name] as XMLAttributeProperties;
+                       XMLAttributeProperties this_prop = properties [name] as XMLAttributeProperties;
+                       if (other_prop == null || this_prop == null)
+                               return;
+
+                       this_prop.CompareTo (document, node, other_prop);
+                       counters.AddPartialToPartial (this_prop.Counters);
+               }
+
+               public override string GetNodeKey (string name, XmlNode node)
+               {
+                       string key = null;
+
+                       // if multiple attributes with the same name (type) exist, then we 
+                       // cannot be sure which attributes correspond, so we must use the
+                       // name of the attribute (type) and the name/value of its properties
+                       // as key
+
+                       XmlNodeList attributes = node.ParentNode.SelectNodes("attribute[@name='" + name + "']");
+                       if (attributes.Count > 1) {
+                               ArrayList keyParts = new ArrayList ();
+
+                               XmlNodeList properties = node.SelectNodes ("properties/property");
+                               foreach (XmlNode property in properties) {
+                                       XmlAttributeCollection attrs = property.Attributes;
+                                       if (attrs["value"] != null) {
+                                               keyParts.Add (attrs["name"].Value + "=" + attrs["value"].Value);
+                                       } else {
+                                               keyParts.Add (attrs["name"].Value + "=");
+                                       }
+                               }
+
+                               // sort properties by name, as order of properties in XML is 
+                               // undefined
+                               keyParts.Sort ();
+
+                               // insert name (type) of attribute
+                               keyParts.Insert (0, name);
+
+                               StringBuilder sb = new StringBuilder ();
+                               foreach (string value in keyParts) {
+                                       sb.Append (value);
+                                       sb.Append (';');
+                               }
+                               key = sb.ToString ();
+                       } else {
+                               key = name;
+                       }
+
+                       return key;
+               }
+
+               protected override void LoadExtraData(string name, XmlNode node)
+               {
+                       XmlNode pNode = node.SelectSingleNode ("properties");
+
+                       if (IsMonoTODOAttribute (name)) {
+                               isTodo = true;
+                               if (pNode.ChildNodes [0].Attributes ["value"] != null) {
+                                       comment = pNode.ChildNodes [0].Attributes ["value"].Value;
+                               }
+                               return;
+                       }
+
+                       if (pNode != null) {
+                               XMLAttributeProperties p = new XMLAttributeProperties (name);
+                               p.LoadData (pNode);
+
+                               properties[name] = p;
+                       }
+               }
+
+               public override string GroupName {
+                       get { return "attributes"; }
+               }
+
+               public override string Name {
+                       get { return "attribute"; }
+               }
+
+               public bool IsTodo {
+                       get { return isTodo; }
+               }
+
+               public string Comment {
+                       get { return comment; }
+               }
+       }
+
+       class XMLInterfaces : XMLNameGroup
+       {
+               public override string GroupName {
+                       get { return "interfaces"; }
+               }
+
+               public override string Name {
+                       get { return "interface"; }
+               }
+       }
+
+       abstract class XMLGenericGroup : XMLNameGroup
+       {
+               string attributes;
+
+               protected override void LoadExtraData (string name, XmlNode node)
+               {
+                       attributes = ((XmlElement) node).GetAttribute ("generic-attribute");
+               }
+
+               protected override void CompareToInner (string name, XmlNode parent, XMLNameGroup other)
+               {
+                       base.CompareToInner (name, parent, other);
+
+                       XMLGenericGroup g = (XMLGenericGroup) other;
+                       if (attributes != g.attributes)
+                               AddWarning (parent, "Incorrect generic attributes: '{0}' != '{1}'", attributes, g.attributes);
+               }
+       }
+
+       class XMLGenericTypeConstraints : XMLGenericGroup
+       {
+               public override string GroupName {
+                       get { return "generic-type-constraints"; }
+               }
+
+               public override string Name {
+                       get { return "generic-type-constraint"; }
+               }
+       }
+
+       class XMLGenericMethodConstraints : XMLGenericGroup
+       {
+               public override string GroupName {
+                       get { return "generic-method-constraints"; }
+               }
+
+               public override string Name {
+                       get { return "generic-method-constraint"; }
+               }
+       }
+
+       abstract class XMLMember : XMLNameGroup
+       {
+               Hashtable attributeMap;
+               Hashtable access = new Hashtable ();
+
+               protected override void LoadExtraData (string name, XmlNode node)
+               {
+                       XmlAttribute xatt = node.Attributes ["attrib"];
+                       if (xatt != null)
+                               access [name] = xatt.Value;
+                       
+                       XmlNode orig = node;
+
+                       node = node.FirstChild;
+                       while (node != null) {
+                               if (node != null && node.Name == "attributes") {
+                                       XMLAttributes a = new XMLAttributes ();
+                                       a.LoadData (node);
+                                       if (attributeMap == null)
+                                               attributeMap = new Hashtable ();
+
+                                       attributeMap [name] = a;
+                                       break;
+                               }
+                               node = node.NextSibling;
+                       }
+
+                       base.LoadExtraData (name, orig);
+               }
+
+               protected override void CompareToInner (string name, XmlNode parent, XMLNameGroup other)
+               {
+                       base.CompareToInner (name, parent, other);
+                       XMLMember mb = other as XMLMember;
+                       XMLAttributes att = null;
+                       XMLAttributes oatt = null;
+                       if (attributeMap != null)
+                               att = attributeMap [name] as XMLAttributes;
+
+                       if (mb != null && mb.attributeMap != null)
+                               oatt = mb.attributeMap [name] as XMLAttributes;
+
+                       if (att != null || oatt != null) {
+                               if (att == null)
+                                       att = new XMLAttributes ();
+
+                               att.CompareTo (document, parent, oatt);
+                               counters.AddPartialToPartial(att.Counters);
+                               if (oatt != null && oatt.IsTodo) {
+                                       counters.Todo++;
+                                       counters.ErrorTotal++;
+                                       AddAttribute (parent, "error", "todo");
+                                       if (oatt.Comment != null)
+                                               AddAttribute (parent, "comment", oatt.Comment);
+                               }
+                       }
+
+                       XMLMember member = (XMLMember) other;
+                       string acc = access [name] as string;
+                       if (acc == null)
+                               return;
+
+                       string oacc = null;
+                       if (member.access != null)
+                               oacc = member.access [name] as string;
+
+                       string accName = ConvertToString (Int32.Parse (acc));
+                       string oaccName = "";
+                       if (oacc != null)
+                               oaccName = ConvertToString (Int32.Parse (oacc));
+
+                       if (accName != oaccName)
+                               AddWarning (parent, "Incorrect attributes: '{0}' != '{1}'", accName, oaccName);
+               }
+
+               protected virtual string ConvertToString (int att)
+               {
+                       return null;
+               }
+       }
+       
+       class XMLFields : XMLMember
+       {
+               Hashtable fieldTypes;
+               Hashtable fieldValues;
+
+               protected override void LoadExtraData (string name, XmlNode node)
+               {
+                       XmlAttribute xatt = node.Attributes ["fieldtype"];
+                       if (xatt != null) {
+                               if (fieldTypes == null)
+                                       fieldTypes = new Hashtable ();
+
+                               fieldTypes [name] = xatt.Value;
+                       }
+
+                       xatt = node.Attributes ["value"];
+                       if (xatt != null) {
+                               if (fieldValues == null)
+                                       fieldValues = new Hashtable ();
+
+                               fieldValues[name] = xatt.Value;
+                       }
+
+                       base.LoadExtraData (name, node);
+               }
+
+               protected override void CompareToInner (string name, XmlNode parent, XMLNameGroup other)
+               {
+                       base.CompareToInner (name, parent, other);
+                       XMLFields fields = (XMLFields) other;
+                       if (fieldTypes != null) {
+                               string ftype = fieldTypes [name] as string;
+                               string oftype = null;
+                               if (fields.fieldTypes != null)
+                                       oftype = fields.fieldTypes [name] as string;
+
+                               if (ftype != oftype)
+                                       AddWarning (parent, "Field type is {0} and should be {1}", oftype, ftype);
+                       }
+                       if (fieldValues != null) {
+                               string fvalue = fieldValues [name] as string;
+                               string ofvalue = null;
+                               if (fields.fieldValues != null)
+                                       ofvalue = fields.fieldValues [name] as string;
+
+                               if (fvalue != ofvalue)
+                                       AddWarning (parent, "Field value is {0} and should be {1}", ofvalue, fvalue);
+                       }
+               }
+
+               protected override string ConvertToString (int att)
+               {
+                       FieldAttributes fa = (FieldAttributes) att;
+                       return fa.ToString ();
+               }
+
+               public override string GroupName {
+                       get { return "fields"; }
+               }
+
+               public override string Name {
+                       get { return "field"; }
+               }
+       }
+
+       class XMLParameters : XMLNameGroup
+       {
+               public override void LoadData (XmlNode node)
+               {
+                       if (node == null)
+                               throw new ArgumentNullException ("node");
+
+                       if (node.Name != GroupName)
+                               throw new FormatException (String.Format ("Expecting <{0}>", GroupName));
+
+                       keys = new Hashtable ();
+                       foreach (XmlNode n in node.ChildNodes) {
+                               string name = n.Attributes["name"].Value;
+                               string key = GetNodeKey (name, n);
+                               XMLParameter parm = new XMLParameter ();
+                               parm.LoadData (n);
+                               keys.Add (key, parm);
+                               LoadExtraData (key, n);
+                       }
+               }
+
+               public override string GroupName {
+                       get {
+                               return "parameters";
+                       }
+               }
+
+               public override string Name {
+                       get {
+                               return "parameter";
+                       }
+               }
+
+               public override string GetNodeKey (string name, XmlNode node)
+               {
+                       return node.Attributes["position"].Value;
+               }
+
+               public override void CompareTo (XmlDocument doc, XmlNode parent, object other)
+               {
+                       this.document = doc;
+                       if (group == null)
+                               group = doc.CreateElement (GroupName, null);
+
+                       Hashtable okeys = null;
+                       if (other != null && ((XMLParameters) other).keys != null) {
+                               okeys = ((XMLParameters) other).keys;
+                       }
+
+                       XmlNode node = null;
+                       bool onull = (okeys == null);
+                       if (keys != null) {
+                               foreach (DictionaryEntry entry in keys) {
+                                       node = doc.CreateElement (Name, null);
+                                       group.AppendChild (node);
+                                       string key = (string) entry.Key;
+                                       XMLParameter parm = (XMLParameter) entry.Value;
+                                       AddAttribute (node, "name", parm.Name);
+
+                                       if (!onull && HasKey (key, okeys)) {
+                                               parm.CompareTo (document, node, okeys[key]);
+                                               counters.AddPartialToPartial (parm.Counters);
+                                               okeys.Remove (key);
+                                               counters.Present++;
+                                       } else {
+                                               AddAttribute (node, "presence", "missing");
+                                               counters.Missing++;
+                                       }
+                               }
+                       }
+
+                       if (!onull && okeys.Count != 0) {
+                               foreach (XMLParameter value in okeys.Values) {
+                                       node = doc.CreateElement (Name, null);
+                                       AddAttribute (node, "name", value.Name);
+                                       AddAttribute (node, "presence", "extra");
+                                       group.AppendChild (node);
+                                       counters.Extra++;
+                               }
+                       }
+
+                       if (group.HasChildNodes)
+                               parent.AppendChild (group);
+               }
+       }
+
+       class XMLProperties : XMLMember
+       {
+               Hashtable nameToMethod = new Hashtable ();
+
+               protected override void CompareToInner (string name, XmlNode parent, XMLNameGroup other)
+               {
+                       Counters copy = counters;
+                       counters = new Counters();
+
+                       XMLProperties oprop = other as XMLProperties;
+                       if (oprop != null) {
+                               XMLMethods m = nameToMethod [name] as XMLMethods;
+                               XMLMethods om = oprop.nameToMethod [name] as XMLMethods;
+                               if (m != null || om != null) {
+                                       if (m == null)
+                                               m = new XMLMethods ();
+
+                                       m.CompareTo(document, parent, om);
+                                       counters.AddPartialToPartial(m.Counters);
+                               }
+                       }
+
+                       base.CompareToInner (name, parent, other);
+                       AddCountersAttributes(parent);
+
+                       copy.AddPartialToPartial(counters);
+                       counters = copy;
+               }
+
+               protected override void LoadExtraData (string name, XmlNode node)
+               {
+                       XmlNode orig = node;
+                       node = node.FirstChild;
+                       while (node != null) {
+                               if (node != null && node.Name == "methods") {
+                                       XMLMethods m = new XMLMethods ();
+                                       XmlNode parent = node.ParentNode;
+                                       string key = GetNodeKey (name, parent);
+                                       m.LoadData (node);
+                                       nameToMethod [key] = m;
+                                       break;
+                               }
+                               node = node.NextSibling;
+                       }
+
+                       base.LoadExtraData (name, orig);
+               }
+
+               public override string GetNodeKey (string name, XmlNode node)
+               {
+                       XmlAttributeCollection atts = node.Attributes;
+                       return String.Format ("{0}:{1}:{2}",
+                                             (atts["name"]   != null ? atts["name"].Value   : ""),
+                                             (atts["ptype"]  != null ? atts["ptype"].Value  : ""),
+                                             (atts["params"] != null ? atts["params"].Value : "")
+                                             );
+               }
+
+               public override string GroupName {
+                       get { return "properties"; }
+               }
+
+               public override string Name {
+                       get { return "property"; }
+               }
+       }
+
+       class XMLEvents : XMLMember
+       {
+               Hashtable eventTypes;
+               Hashtable nameToMethod = new Hashtable ();
+
+               protected override void LoadExtraData (string name, XmlNode node)
+               {
+                       XmlAttribute xatt = node.Attributes ["eventtype"];
+                       if (xatt != null) {
+                               if (eventTypes == null)
+                                       eventTypes = new Hashtable ();
+
+                               eventTypes [name] = xatt.Value;
+                       }
+
+                       XmlNode child = node.FirstChild;
+                       while (child != null) {
+                               if (child != null && child.Name == "methods") {
+                                       XMLMethods m = new XMLMethods ();
+                                       XmlNode parent = child.ParentNode;
+                                       string key = GetNodeKey (name, parent);
+                                       m.LoadData (child);
+                                       nameToMethod [key] = m;
+                                       break;
+                               }
+                               child = child.NextSibling;
+                       }
+
+                       base.LoadExtraData (name, node);
+               }
+
+               protected override void CompareToInner (string name, XmlNode parent, XMLNameGroup other)
+               {
+                       Counters copy = counters;
+                       counters = new Counters ();
+
+                       try {
+                               base.CompareToInner (name, parent, other);
+                               AddCountersAttributes (parent);
+                               if (eventTypes == null)
+                                       return;
+
+                               XMLEvents evt = (XMLEvents) other;
+                               string etype = eventTypes [name] as string;
+                               string oetype = null;
+                               if (evt.eventTypes != null)
+                                       oetype = evt.eventTypes [name] as string;
+
+                               if (etype != oetype)
+                                       AddWarning (parent, "Event type is {0} and should be {1}", oetype, etype);
+
+                               XMLMethods m = nameToMethod [name] as XMLMethods;
+                               XMLMethods om = evt.nameToMethod [name] as XMLMethods;
+                               if (m != null || om != null) {
+                                       if (m == null)
+                                               m = new XMLMethods ();
+
+                                       m.CompareTo (document, parent, om);
+                                       counters.AddPartialToPartial (m.Counters);
+                               }
+                       } finally {
+                               AddCountersAttributes (parent);
+                               copy.AddPartialToPartial (counters);
+                               counters = copy;
+                       }
+               }
+
+               protected override string ConvertToString (int att)
+               {
+                       EventAttributes ea = (EventAttributes) att;
+                       return ea.ToString ();
+               }
+
+               public override string GroupName {
+                       get { return "events"; }
+               }
+
+               public override string Name {
+                       get { return "event"; }
+               }
+       }
+
+       class XMLMethods : XMLMember
+       {
+               Hashtable returnTypes;
+               Hashtable parameters;
+               Hashtable genericConstraints;
+               Hashtable signatureFlags;
+
+               [Flags]
+               enum SignatureFlags
+               {
+                       None = 0,
+                       Abstract = 1,
+                       Virtual = 2,
+                       Static = 4,
+                       Final = 8,
+               }
+
+               protected override void LoadExtraData (string name, XmlNode node)
+               {
+                       XmlAttribute xatt = node.Attributes ["returntype"];
+                       if (xatt != null) {
+                               if (returnTypes == null)
+                                       returnTypes = new Hashtable ();
+
+                               returnTypes [name] = xatt.Value;
+                       }
+
+                       SignatureFlags flags = SignatureFlags.None;
+                       if (((XmlElement) node).GetAttribute ("abstract") == "true")
+                               flags |= SignatureFlags.Abstract;
+                       if (((XmlElement) node).GetAttribute ("static") == "true")
+                               flags |= SignatureFlags.Static;
+                       if (((XmlElement) node).GetAttribute ("virtual") == "true")
+                               flags |= SignatureFlags.Virtual;
+                       if (((XmlElement) node).GetAttribute ("final") == "true")
+                               flags |= SignatureFlags.Final;
+                       if (flags != SignatureFlags.None) {
+                               if (signatureFlags == null)
+                                       signatureFlags = new Hashtable ();
+                               signatureFlags [name] = flags;
+                       }
+
+                       XmlNode parametersNode = node.SelectSingleNode ("parameters");
+                       if (parametersNode != null) {
+                               if (parameters == null)
+                                       parameters = new Hashtable ();
+
+                               XMLParameters parms = new XMLParameters ();
+                               parms.LoadData (parametersNode);
+
+                               parameters[name] = parms;
+                       }
+
+                       XmlNode genericNode = node.SelectSingleNode ("generic-method-constraints");
+                       if (genericNode != null) {
+                               if (genericConstraints == null)
+                                       genericConstraints = new Hashtable ();
+                               XMLGenericMethodConstraints csts = new XMLGenericMethodConstraints ();
+                               csts.LoadData (genericNode);
+                               genericConstraints [name] = csts;
+                       }
+
+                       base.LoadExtraData (name, node);
+               }
+
+               public override string GetNodeKey (string name, XmlNode node)
+               {
+                       // for explicit/implicit operators we need to include the return
+                       // type in the key to allow matching; as a side-effect, differences
+                       // in return types will be reported as extra/missing methods
+                       //
+                       // for regular methods we do not need to take into account the
+                       // return type for matching methods; differences in return types
+                       // will be reported as a warning on the method
+                       if (name.StartsWith ("op_")) {
+                               XmlAttribute xatt = node.Attributes ["returntype"];
+                               string returnType = xatt != null ? xatt.Value + " " : string.Empty;
+                               return returnType + name;
+                       }
+                       return name;
+               }
+
+               protected override void CompareToInner (string name, XmlNode parent, XMLNameGroup other)
+               {
+                       // create backup of actual counters
+                       Counters copy = counters;
+                       // initialize counters for current method
+                       counters = new Counters();
+
+                       try {
+                               base.CompareToInner(name, parent, other);
+                               XMLMethods methods = (XMLMethods) other;
+
+                               SignatureFlags flags = signatureFlags != null &&
+                                       signatureFlags.ContainsKey (name) ?
+                                       (SignatureFlags) signatureFlags [name] :
+                                       SignatureFlags.None;
+                               SignatureFlags oflags = methods.signatureFlags != null &&
+                                       methods.signatureFlags.ContainsKey (name) ?
+                                       (SignatureFlags) methods.signatureFlags [name] :
+                                       SignatureFlags.None;
+
+                               if (flags!= oflags) {
+                                       if (flags == SignatureFlags.None)
+                                               AddWarning (parent, String.Format ("should not be {0}", oflags));
+                                       else if (oflags == SignatureFlags.None)
+                                               AddWarning (parent, String.Format ("should be {0}", flags));
+                                       else
+                                               AddWarning (parent, String.Format ("{0} and should be {1}", oflags, flags));
+                               }
+
+                               if (returnTypes != null) {
+                                       string rtype = returnTypes[name] as string;
+                                       string ortype = null;
+                                       if (methods.returnTypes != null)
+                                               ortype = methods.returnTypes[name] as string;
+
+                                       if (rtype != ortype)
+                                               AddWarning (parent, "Return type is {0} and should be {1}", ortype, rtype);
+                               }
+
+                               if (parameters != null) {
+                                       XMLParameters parms = parameters[name] as XMLParameters;
+                                       parms.CompareTo (document, parent, methods.parameters[name]);
+                                       counters.AddPartialToPartial (parms.Counters);
+                               }
+                       } finally {
+                               // output counter attributes in result document
+                               AddCountersAttributes(parent);
+
+                               // add temporary counters to actual counters
+                               copy.AddPartialToPartial(counters);
+                               // restore backup of actual counters
+                               counters = copy;
+                       }
+               }
+
+               protected override string ConvertToString (int att)
+               {
+                       MethodAttributes ma = (MethodAttributes) att;
+                       // ignore ReservedMasks
+                       ma &= ~ MethodAttributes.ReservedMask;
+                       ma &= ~ MethodAttributes.VtableLayoutMask;
+                       if ((ma & MethodAttributes.FamORAssem) != 0)
+                               ma = (ma & ~ MethodAttributes.FamORAssem) | MethodAttributes.Family;
+
+                       // ignore the HasSecurity attribute for now
+                       if ((ma & MethodAttributes.HasSecurity) != 0)
+                               ma = (MethodAttributes) (att - (int) MethodAttributes.HasSecurity);
+
+                       // ignore the RequireSecObject attribute for now
+                       if ((ma & MethodAttributes.RequireSecObject) != 0)
+                               ma = (MethodAttributes) (att - (int) MethodAttributes.RequireSecObject);
+
+                       // we don't care if the implementation is forwarded through PInvoke 
+                       if ((ma & MethodAttributes.PinvokeImpl) != 0)
+                               ma = (MethodAttributes) (att - (int) MethodAttributes.PinvokeImpl);
+
+                       return ma.ToString ();
+               }
+
+               public override string GroupName {
+                       get { return "methods"; }
+               }
+
+               public override string Name {
+                       get { return "method"; }
+               }
+       }
+
+       class XMLConstructors : XMLMethods
+       {
+               public override string GroupName {
+                       get { return "constructors"; }
+               }
+
+               public override string Name {
+                       get { return "constructor"; }
+               }
+       }
+
+       class XmlNodeComparer : IComparer
+       {
+               public static XmlNodeComparer Default = new XmlNodeComparer ();
+
+               public int Compare (object a, object b)
+               {
+                       XmlNode na = (XmlNode) a;
+                       XmlNode nb = (XmlNode) b;
+                       return String.Compare (na.Attributes ["name"].Value, nb.Attributes ["name"].Value);
+               }
+       }
+}
+
diff --git a/mcs/tools/gensources.sh b/mcs/tools/gensources.sh
deleted file mode 100755 (executable)
index 7e71029..0000000
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/env bash
-
-includefile=$1
-excludefile=$2
-
-## input variables:
-##     $filelist:
-##             A colon (':') separated list of files already read.
-##             Must be initialized to ":".
-##     $excludelist:
-##             A newline separated of element (support Shell Patterns) to exclude.
-##     $separator:
-##             The separator used in list for the output
-##     
-## output variables:
-##     $list:
-##             A list of elements separated by the separator given in $separator.
-##             The new elements will be appended to the list.
-readlist () {
-       local onelist
-       local onelistcontent
-       onelist=$1
-
-       if [ ":$onelist:" = "::" ] ; then return ; fi
-       if [ ! -f $onelist ] ; then return ; fi
-       if [ ":${filelist##*:$onelist:*}:" = "::" ]  ; then return ; fi
-       filelist=":$onelist$filelist"
-
-       onelistcontent=`cat $onelist | sed "s=[ \t]*$==g" | while read line ; do echo -n $line ; echo -n ":" ; done`
-
-       OFS="$IFS"
-       IFS=":"
-       for line in $onelistcontent ; do
-               line2=${line##\#}
-               if [ ":$line:" = ":$line2:" ] ; then
-                       for linex in $excludelist ; do
-                               if [ ":${line##$linex}:" = "::" ] ; then line="" ; fi
-                       done
-                       if [ ":$line:" != "::" ] ; then
-                               if [ ":$list:" = "::" ] ; then
-                                       list="$line"
-                               else
-                                       list="$list$separator$line"
-                               fi
-                       fi
-               else
-                       line3=${line2##include }
-                       if [ ":$line3:" != ":$line2:" -a ":$line3:" != "::" ] ; then
-                               readlist "$line3"
-                       fi
-               fi
-       done
-       IFS="$OFS"
-}
-
-list=""
-filelist=":"
-excludelist=""
-separator=":"
-readlist "$excludefile"
-
-excludelist="$list"
-list=""
-filelist=":"
-separator="
-"
-readlist "$includefile"
-echo "$list" | sort | uniq
index a16a673283891290fcd91fe59455469ef3ac090e..6b4f6d0120dceff812eef90c6105a4df1bd1f393 100644 (file)
@@ -1,3 +1,15 @@
+2010-04-16  Jonathan Pryor <jpryor@novell.com>
+
+       * Makefile: Add System.Xml.Linq.dll to the referenced assemblies.
+       * Mono.Documentation/webdoc.cs: Allow .source files to be provided to
+         'mdoc export-html-webdoc', which will cause the .source files to be
+         read and all referenced .tree/.zip files to be processed.
+
+2010-04-16  Jonathan Pryor <jpryor@novell.com>
+
+       * Mono.Documentation/monodocer.cs: Use Int64 instead of UInt64 for
+         enum values, so that we can properly capture negative values.
+
 2010-02-28  Jonathan Pryor <jpryor@novell.com>
 
        * Mono.Documentation/webdoc.cs: Add --use-system-sources option so
index c0746b17dd2c12d9ced5ebd85f5c156e239e423b..7e77baae75ffebc3250b3f02c691d879fa94ac3b 100644 (file)
@@ -12,6 +12,7 @@ MDOC_COMMON_FLAGS = \
        /resource:Resources/overview.xsl,overview.xsl                               \
        /resource:Resources/stylesheet.xsl,stylesheet.xsl                           \
        /r:System.Web.dll                                                           \
+       /r:System.Xml.Linq.dll                                                      \
        /r:ICSharpCode.SharpZipLib.dll                                              \
        /r:$(topdir)/class/lib/net_4_0/Mono.Cecil.dll
 
index 86afe17265549b31c28d9acb3352722f29d747e1..19500268532166244763555575588841db023830 100644 (file)
@@ -2287,7 +2287,7 @@ class MDocUpdater : MDocCommand
                        return v.ToString ();
                string typename = GetDocTypeFullName (valueType);
                var values = GetEnumerationValues (valueDef);
-               ulong c = Convert.ToUInt64 (v);
+               long c = ToInt64 (v);
                if (values.ContainsKey (c))
                        return typename + "." + values [c];
                if (valueDef.CustomAttributes.Cast<CustomAttribute> ()
@@ -2301,17 +2301,24 @@ class MDocUpdater : MDocCommand
                return "(" + GetDocTypeFullName (valueType) + ") " + v.ToString ();
        }
 
-       private static Dictionary<ulong, string> GetEnumerationValues (TypeDefinition type)
+       private static Dictionary<long, string> GetEnumerationValues (TypeDefinition type)
        {
-               var values = new Dictionary<ulong, string> ();
+               var values = new Dictionary<long, string> ();
                foreach (var f in 
                                (from f in type.Fields.Cast<FieldDefinition> ()
                                 where !(f.IsRuntimeSpecialName || f.IsSpecialName)
                                 select f)) {
-                       values [Convert.ToUInt64 (f.Constant)] = f.Name;
+                       values [ToInt64 (f.Constant)] = f.Name;
                }
                return values;
        }
+
+       static long ToInt64 (object value)
+       {
+               if (value is ulong)
+                       return (long) (ulong) value;
+               return Convert.ToInt64 (value);
+       }
        
        private void MakeParameters (XmlElement root, ParameterDefinitionCollection parameters)
        {
index 264fb42b798a29468838afcfa8cf3463f45859f5..045ab81341e3294b9276c48738caea3e8ae9089c 100644 (file)
@@ -33,6 +33,7 @@ using System.IO;
 using System.Linq;
 using System.Text;
 using System.Web;
+using System.Xml.Linq;
 
 using Monodoc;
 using Mono.Documentation;
@@ -85,9 +86,12 @@ namespace Mono.Documentation
                        Parse (options, args, "export-html-webdoc", 
                                        "[OPTIONS]+ FILES",
                                        "Export mdoc documentation within FILES to HTML for use by ASP.NET webdoc.\n\n" +
-                                       "FILES are .tree or .zip files as produced by 'mdoc assemble'.");
+                                       "FILES are .tree or .zip files as produced by 'mdoc assemble', or .source files\n" +
+                                       "which reference .tree and .zip files produced by 'mdoc assemble'.\n\n" + 
+                                       "See mdoc(5) or mdoc-assemble(1) for information about the .source file format.");
                        if (opts.Formats.Values.All (files => files.Count == 0))
                                Error ("No files specified.");
+                       ProcessSources (opts);
                        HelpSource.use_css = true;
                        HelpSource.FullHtml = false;
                        SettingsHandler.Settings.EnableEditing = false;
@@ -95,6 +99,36 @@ namespace Mono.Documentation
                                ProcessFiles (opts, p.Key, p.Value);
                }
 
+               void ProcessSources (Options opts)
+               {
+                       foreach (var p in opts.Formats) {
+                               var files = p.Value;
+                               foreach (var f in files.Where (f => f.EndsWith (".source")).ToList ()) {
+                                       files.Remove (f);
+                                       foreach (var tfi in GetTreeFilesFromSource (f)) {
+                                               List<string> treeFiles;
+                                               if (!opts.Formats.TryGetValue (tfi.Key, out treeFiles))
+                                                       opts.Formats.Add (tfi.Key, treeFiles = new List<string> ());
+                                               treeFiles.Add (tfi.Value);
+                                       }
+                               }
+                       }
+               }
+
+               IEnumerable<KeyValuePair<string, string>> GetTreeFilesFromSource (string sourceFile)
+               {
+                       try {
+                               var source = XElement.Load (sourceFile);
+                               return source.Descendants ("source")
+                                       .Select (e => new KeyValuePair<string, string>(e.Attribute ("provider").Value, 
+                                                               Path.Combine (Path.GetDirectoryName (sourceFile), e.Attribute ("basefile").Value + ".tree")));
+                       }
+                       catch (Exception e) {
+                               Message (TraceLevel.Error, "mdoc: error parsing file {0}: {1}", sourceFile, e.Message);
+                               return new KeyValuePair<string, string>[0];
+                       }
+               }
+
                void ProcessFiles (Options opts, string format, List<string> files)
                {
                        foreach (var basePath in 
index 5b45d75a6eb96a10c26c97209a4ca44947050974..1681e91c53dc70bdf8879b6aaeda5943eb42c7d9 100644 (file)
@@ -1,3 +1,7 @@
+2010-03-18  Zoltan Varga  <vargaz@gmail.com>
+
+       * mkbundle.cs: Update after the mono.pc and libmono version bump.
+
 2009-05-29  Steven Munroe  <munroesj@us.ibm.com>
 
        This patch is contributed under the terms of the MIT/X11 license
index 16b17d30d3a11959cabfba53c0c575720ffddb02..36a05394c537241404ee8bb84441fc3341e22105 100644 (file)
@@ -396,16 +396,16 @@ class MakeBundle {
                        if (static_link) {
                                string smonolib;
                                if (style == "osx")
-                                       smonolib = "`pkg-config --variable=libdir mono`/libmono.a ";
+                                       smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
                                else
-                                       smonolib = "-Wl,-Bstatic -lmono -Wl,-Bdynamic ";
-                               cmd = String.Format ("{4} -o {2} -Wall `pkg-config --cflags mono` {0} {3} " +
-                                                    "`pkg-config --libs-only-L mono` " + smonolib +
-                                                    "`pkg-config --libs-only-l mono | sed -e \"s/\\-lmono //\"` {1}",
+                                       smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
+                               cmd = String.Format ("{4} -o {2} -Wall `pkg-config --cflags mono-2` {0} {3} " +
+                                                    "`pkg-config --libs-only-L mono-2` " + smonolib +
+                                                    "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
                                                     temp_c, temp_o, output, zlib, cc);
                        } else {
                                
-                               cmd = String.Format ("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono` {3} {1}",
+                               cmd = String.Format ("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
                                                     temp_c, temp_o, output, zlib, cc);
                        }
                             
@@ -523,18 +523,19 @@ class MakeBundle {
        {
                Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
                                   "Options:\n" +
-                                  "    -c              Produce stub only, do not compile\n" +
-                                  "    -o out          Specifies output filename\n" +
-                                  "    -oo obj         Specifies output filename for helper object file\n" +
-                                  "    -L path         Adds `path' to the search path for assemblies\n" +
-                                  "    --nodeps        Turns off automatic dependency embedding (default)\n" +
-                                  "    --deps          Turns on automatic dependency embedding\n" +
-                                  "    --keeptemp      Keeps the temporary files\n" +
-                                  "    --config F      Bundle system config file `F'\n" +
-                                  "    --config-dir D  Set MONO_CFG_DIR to `D'\n" +
-                                  "    --static        Statically link to mono libs\n" +
-                                  "    --nomain        Don't include a main() function, for libraries\n" +
-                                  "    -z              Compress the assemblies before embedding.\n");
+                                  "    -c                  Produce stub only, do not compile\n" +
+                                  "    -o out              Specifies output filename\n" +
+                                  "    -oo obj             Specifies output filename for helper object file\n" +
+                                  "    -L path             Adds `path' to the search path for assemblies\n" +
+                                  "    --nodeps            Turns off automatic dependency embedding (default)\n" +
+                                  "    --deps              Turns on automatic dependency embedding\n" +
+                                  "    --keeptemp          Keeps the temporary files\n" +
+                                  "    --config F          Bundle system config file `F'\n" +
+                                  "    --config-dir D      Set MONO_CFG_DIR to `D'\n" +
+                                  "    --machine-config F  Use the given file as the machine.config for the application.\n" +
+                                  "    --static            Statically link to mono libs\n" +
+                                  "    --nomain            Don't include a main() function, for libraries\n" +
+                                  "    -z                  Compress the assemblies before embedding.\n");
        }
 
        [DllImport ("libc")]
index 6ac600b166121e96ef655a4e6c3afb719d0d9b17..2ea79257c13db28843124b03565002f00ee8a9b2 100644 (file)
@@ -1,3 +1,10 @@
+2010-04-25  Jonathan Pryor  <jpryor@novell.com>
+
+       * Monodoc/ecma-provider.cs: Support the full set of possible operator
+         names within EcmaHelpSource.MakeOperatorSignature() (where "full" is
+         "whatever is included in ECMA-335 Â§10.3.1 through Â§10.3.3").
+         Fixes InvalidOperationException reported to mono-docs-list.
+
 2010-02-28  Jonathan Pryor  <jpryor@novell.com>
 
        * Monodoc/provider.cs: Add
index 4c79062229eb022f6e3ee9b1a4c4b51d89c589ae..247553c421c359cb0e1540d200f49575340d9f45 100644 (file)
@@ -829,19 +829,57 @@ public class EcmaHelpSource : HelpSource {
                nicename = name.Substring(3);
                
                switch (name) {
-                       // unary operators: no overloading possible
-                       case "op_UnaryPlus": case "op_UnaryNegation": case "op_LogicalNot": case "op_OnesComplement":
-                       case "op_Increment": case "op_Decrement": 
-                       case "op_True": case "op_False":
+                       // unary operators: no overloading possible     [ECMA-335 Â§10.3.1]
+                       case "op_UnaryPlus":                    // static     R operator+       (T)
+                       case "op_UnaryNegation":                // static     R operator-       (T)
+                       case "op_LogicalNot":                   // static     R operator!       (T)
+                       case "op_OnesComplement":               // static     R operator~       (T)
+                       case "op_Increment":                    // static     R operator++      (T)
+                       case "op_Decrement":                    // static     R operator--      (T)
+                       case "op_True":                         // static  bool operator true   (T)
+                       case "op_False":                        // static  bool operator false  (T)
+                       case "op_AddressOf":                    // static     R operator&       (T)
+                       case "op_PointerDereference":           // static     R operator*       (T)
                                sig = nicename;
                                break;
                        
-                       // binary operators: overloading is possible based on parameter types
-                       case "op_Addition": case "op_Subtraction": case "op_Multiply": case "op_Division": case "op_Modulus":
-                       case "op_BitwiseAnd": case "op_BitwiseOr": case "op_ExclusiveOr":
-                       case "op_LeftShift": case "op_RightShift":
-                       case "op_Equality": case "op_Inequality":
-                       case "op_GreaterThan": case "op_LessThan": case "op_GreaterThanOrEqual": case "op_LessThanOrEqual":
+                       // binary operators: overloading is possible [ECMA-335 Â§10.3.2]
+                       case "op_Addition":                     // static    R operator+    (T1, T2)
+                       case "op_Subtraction":                  // static    R operator-    (T1, T2)
+                       case "op_Multiply":                     // static    R operator*    (T1, T2)
+                       case "op_Division":                     // static    R operator/    (T1, T2)
+                       case "op_Modulus":                      // static    R operator%    (T1, T2)
+                       case "op_ExclusiveOr":                  // static    R operator^    (T1, T2)
+                       case "op_BitwiseAnd":                   // static    R operator&    (T1, T2)
+                       case "op_BitwiseOr":                    // static    R operator|    (T1, T2)
+                       case "op_LogicalAnd":                   // static    R operator&&   (T1, T2)
+                       case "op_LogicalOr":                    // static    R operator||   (T1, T2)
+                       case "op_Assign":                       // static    R operator=    (T1, T2)
+                       case "op_LeftShift":                    // static    R operator<<   (T1, T2)
+                       case "op_RightShift":                   // static    R operator>>   (T1, T2)
+                       case "op_SignedRightShift":             // static    R operator>>   (T1, T2)
+                       case "op_UnsignedRightShift":           // static    R operator>>>  (T1, T2)
+                       case "op_Equality":                     // static bool operator==   (T1, T2)
+                       case "op_GreaterThan":                  // static bool operator>    (T1, T2)
+                       case "op_LessThan":                     // static bool operator<    (T1, T2)
+                       case "op_Inequality":                   // static bool operator!=   (T1, T2)
+                       case "op_GreaterThanOrEqual":           // static bool operator>=   (T1, T2)
+                       case "op_LessThanOrEqual":              // static bool operator<=   (T1, T2)
+                       case "op_UnsignedRightShiftAssignment": // static    R operator>>>= (T1, T2)
+                       case "op_MemberSelection":              // static    R operator->   (T1, T2)
+                       case "op_RightShiftAssignment":         // static    R operator>>=  (T1, T2)
+                       case "op_MultiplicationAssignment":     // static    R operator*=   (T1, T2)
+                       case "op_PointerToMemberSelection":     // static    R operator->*  (T1, T2)
+                       case "op_SubtractionAssignment":        // static    R operator-=   (T1, T2)
+                       case "op_ExclusiveOrAssignment":        // static    R operator^=   (T1, T2)
+                       case "op_LeftShiftAssignment":          // static    R operator<<=  (T1, T2)
+                       case "op_ModulusAssignment":            // static    R operator%=   (T1, T2)
+                       case "op_AdditionAssignment":           // static    R operator+=   (T1, T2)
+                       case "op_BitwiseAndAssignment":         // static    R operator&=   (T1, T2)
+                       case "op_BitwiseOrAssignment":          // static    R operator|=   (T1, T2)
+                       case "op_Comma":                        // static    R operator,    (T1, T2)
+                       case "op_DivisionAssignment":           // static    R operator/=   (T1, T2)
+                       default:                                // If all else fails, assume it can be overridden...whatever it is.
                                XmlNodeList paramnodes = n.SelectNodes("Parameters/Parameter");
                                sig = nicename + "(";
                                bool first = true;
@@ -855,16 +893,14 @@ public class EcmaHelpSource : HelpSource {
                                sig += ")";
                                break;
                        
-                       // overloading based on parameter and return type
-                       case "op_Implicit": case "op_Explicit":
+                       // conversion operators: overloading based on parameter and return type [ECMA-335 Â§10.3.3]
+                       case "op_Implicit":                    // static implicit operator R (T)
+                       case "op_Explicit":                    // static explicit operator R (T)
                                nicename = "Conversion";
                                string arg = n.SelectSingleNode("Parameters/Parameter/@Type").InnerText;
                                string ret = n.SelectSingleNode("ReturnValue/ReturnType").InnerText;
                                sig = EcmaDoc.ConvertCTSName(arg) + " to " + EcmaDoc.ConvertCTSName(ret);
                                break;
-                               
-                       default:
-                               throw new InvalidOperationException();
                }       
        }
 
index 8cc87a111dba4a80cfe85edcca069e8b8717a915..504d899f831e6a22c2b059c6a02317ed1f6a5db9 100644 (file)
@@ -231,7 +231,7 @@ class MonoP {
                foreach (Type t in types) {
                        if (filter_obsolete && t.IsDefined (typeof (ObsoleteAttribute), false))
                                obsolete_count ++;
-                       else
+                       else 
                                Console.WriteLine (t.FullName);
                }
 
@@ -277,6 +277,34 @@ class MonoP {
                
        }
 
+       static void ShowAll (string assembly, bool show_private, bool filter_obsolete)
+       {
+               Assembly a = GetAssembly (assembly, true);
+
+               object[] cls = a.GetCustomAttributes (typeof (CLSCompliantAttribute), false);
+               if (cls.Length > 0) {
+                       CLSCompliantAttribute cca = cls[0] as CLSCompliantAttribute;
+                       if (cca.IsCompliant)
+                               Console.WriteLine ("[CLSCompliant]");
+               }
+
+               foreach (string ai in a.ToString ().Split (','))
+                       Console.WriteLine (ai.Trim ());
+                       
+               Console.WriteLine ();
+               Type [] types = show_private ? a.GetTypes () : a.GetExportedTypes ();
+               Array.Sort (types, new TypeSorter ());
+               
+               var sw = new StreamWriter (Console.OpenStandardOutput (), Console.Out.Encoding);                                
+               foreach (Type t in types) {
+                       if (filter_obsolete && t.IsDefined (typeof (ObsoleteAttribute), false))
+                               continue;
+
+                       new Outline (t, sw, true, show_private, filter_obsolete).OutlineType ();
+               }
+               sw.Flush ();
+       }
+       
        static void Main (string [] args)
        {
                Options options = new Options ();
@@ -285,13 +313,18 @@ class MonoP {
                
                if (options.AssemblyReference != null) {
                        assembly = options.AssemblyReference;
-                       
-                       if (options.Type == null) {
-                               if (options.PrintRefs)
-                                       PrintRefs (assembly);
-                               else
-                                       PrintTypes (assembly, options.ShowPrivate, options.FilterObsolete);
+
+                       if (options.ShowAll){
+                               ShowAll (assembly, options.FilterObsolete, options.ShowPrivate);
                                return;
+                       } else {
+                               if (options.Type == null) {
+                                       if (options.PrintRefs)
+                                               PrintRefs (assembly);
+                                       else
+                                               PrintTypes (assembly, options.ShowPrivate, options.FilterObsolete);
+                                       return;
+                               }
                        }
                }
 
index f4558c12e2ed85c7d12cc916c6674376ed651f6c..fa1a10dda3460f0322c9ec13357830d3071f2076 100644 (file)
@@ -32,6 +32,7 @@ public class Options
        public bool FilterObsolete = false;
        public bool PrintRefs = false;
        public bool Search = false;
+       public bool ShowAll = false;
        public bool ShowPrivate = false;
        public string AssemblyReference = null;
        public string Type = null;
@@ -88,6 +89,9 @@ public class Options
                                        if (i < args.Length)
                                                AssemblyReference = args[i];
                                        break;
+                               case "-a":
+                                       ShowAll = true;
+                                       break;
                                default:
                                        if (args[i].StartsWith ("-r:") || args[i].StartsWith ("/r:")) {
                                                AssemblyReference = args [i].Substring (3);
@@ -131,6 +135,7 @@ public class Options
                Console.WriteLine ("\t--refs\t\t\tPrint a list of the referenced assemblies for an assembly");
                Console.WriteLine ("\t--runtime-version\tPrint runtime version");
                Console.WriteLine ("\t--search,-s,-k\t\tSearch through all known namespaces");
+               Console.WriteLine ("\t--a\t\tShows all the types declare in the specified assembly");
        }
 }
 
index 4682bd2b6dfd8ead5b330676d4a2ebee681b3aca..784cece95b2cbd41f030192bbaecacd71d740879 100644 (file)
@@ -866,6 +866,9 @@ public class Outline {
 
        static Type [] TypeGetInterfaces (Type t, bool declonly)
        {
+               if (t.IsGenericParameter)
+                       return new Type [0];
+
                Type [] ifaces = t.GetInterfaces ();
                if (! declonly)
                        return ifaces;
index f0771bf7d7f3006b8d61c13a5a856f7be16c072a..3f25fca6a2d74d5476ae0132dcd2b062b497290e 100644 (file)
@@ -47,6 +47,12 @@ using DbLinq.Factory;
 "fe4a9cbb059374c0cc047aa28839fed7176761813caf6a2ffa0bff9afb50ead56dd3f56186a663" +\r
 "962a12b830c2a70eb70ec77823eb5750e5bdef9e01d097c30b5c5463c3d07d3472b58e4c02f279" +\r
 "2309259f")]\r
+[assembly: InternalsVisibleTo("sqlmetal_test_net_4_0, PublicKey=" +\r
+"0024000004800000940000000602000000240000525341310004000001000100c5753d8c47f400" +\r
+"83f549016a5711238ac8ec297605abccd3dc4b6d0f280b4764eb2cc58ec4e37831edad7e7a07b8" +\r
+"fe4a9cbb059374c0cc047aa28839fed7176761813caf6a2ffa0bff9afb50ead56dd3f56186a663" +\r
+"962a12b830c2a70eb70ec77823eb5750e5bdef9e01d097c30b5c5463c3d07d3472b58e4c02f279" +\r
+"2309259f")]\r
 \r
 [assembly: DbLinq]\r
 \r
index bbda385744c7e862d6376d8f632113dcc780317a..b7abd09265aa4669c241fbfd05412737ac7e4d9d 100644 (file)
@@ -1,3 +1,11 @@
+2010-04-13  Jonathan Pryor <jonpryor@vt.edu>
+
+       * sqlmetal.exe.source: Add additional files.
+
+2010-03-29  Raja R Harinath  <harinath@hurrynot.org>
+
+       * AssemblyInfo.cs: Make internals visible to the test suite.
+
 2010-01-04  Jonathan Pryor <jonpryor@vt.edu>
 
        * Makefile: Ensure that Test/* files are distributed (so that 
index 8604037792d93ac0be5f030a00c9959ffdb7d932..350fc4fe92d37448eea31a892b4c0251c561f624 100644 (file)
@@ -3,6 +3,7 @@ AssemblyInfo.cs
 ../../class/System.Data.Linq/src/DbMetal/AbstractParameters.cs
 ../../class/System.Data.Linq/src/DbMetal/Configuration/ProvidersSection.cs
 ../../class/System.Data.Linq/src/DbMetal/Generator/AttributeDefinition.cs
+../../class/System.Data.Linq/src/DbMetal/Generator/CodeDomGenerator.cs
 ../../class/System.Data.Linq/src/DbMetal/Generator/CodeWriter.cs
 ../../class/System.Data.Linq/src/DbMetal/Generator/EntityInterface/IImplementation.cs
 ../../class/System.Data.Linq/src/DbMetal/Generator/EntityInterface/Implementation/IModifiedImplementation.cs
@@ -11,9 +12,6 @@ AssemblyInfo.cs
 ../../class/System.Data.Linq/src/DbMetal/Generator/EntityInterface/Implementation/InterfaceImplementation.cs
 ../../class/System.Data.Linq/src/DbMetal/Generator/GenerationContext.cs
 ../../class/System.Data.Linq/src/DbMetal/Generator/ICodeGenerator.cs
-../../class/System.Data.Linq/src/DbMetal/Generator/Implementation/CodeDomGenerator/AbstractCodeDomGenerator.cs
-../../class/System.Data.Linq/src/DbMetal/Generator/Implementation/CodeDomGenerator/CSharpCodeDomGenerator.cs
-../../class/System.Data.Linq/src/DbMetal/Generator/Implementation/CodeDomGenerator/VisualBasicCodeDomGenerator.cs
 ../../class/System.Data.Linq/src/DbMetal/Generator/Implementation/CodeTextGenerator/CodeGenerator.Class.cs
 ../../class/System.Data.Linq/src/DbMetal/Generator/Implementation/CodeTextGenerator/CodeGenerator.Context.Ctor.cs
 ../../class/System.Data.Linq/src/DbMetal/Generator/Implementation/CodeTextGenerator/CodeGenerator.cs
index 43b9742558090e1bcd1d5fb150ed309bc529417f..122704c215c3a8eebdc1310ec278831623c0089c 100644 (file)
@@ -1,3 +1,109 @@
+2010-04-25  Ankit Jain  <jankit@novell.com>
+
+       Fix bug #599486.
+       * xbuild/Microsoft.CSharp.targets:
+       * xbuild/Microsoft.VisualBasic.targets: Add $(CoreCompileDependsOn)
+       for the CoreCompile target.
+
+2010-04-21  Ankit Jain  <jankit@novell.com>
+
+       * Makefile: Remove unnecessary "/" in the paths.
+       Fixes windows build (thanks to Atsushi Eno).
+
+2010-04-14  Ankit Jain  <jankit@novell.com>
+
+       * xbuild/Microsoft.Silverlight*.targets: New.
+       * Makefile: Update to install silverlight target files.
+       * xbuild_targets.make: Update to handle silverlight
+       target files.
+
+2010-04-12  Ankit Jain  <jankit@novell.com>
+
+       * Makefile: Update EXTRA_DIST with the new targets files.
+
+2010-04-10  Ankit Jain  <jankit@novell.com>
+
+       * xbuild/*/Microsoft.Common.targets: Emit warning if
+       $(TargetFrameworkVersion) is not supported by the current
+       tool set.
+
+2010-04-10  Ankit Jain  <jankit@novell.com>
+
+       * xbuild/Microsoft.Common.targets: Move to 2.0, 3.5 and 4.0 .
+       The 4.0 copy gets the framework path for 4.0 .
+       * Makefile: Update for the above change.
+       * xbuild_targets.make: Likewise.
+
+
+2010-04-10  Ankit Jain  <jankit@novell.com>
+
+       * xbuild/Microsoft.Common.targets (DeployOutputFiles): Copy only
+       if the source file exists.
+
+2010-04-10  Ankit Jain  <jankit@novell.com>
+
+       * xbuild/3.5/Microsoft.Common.tasks:
+       * xbuild/4.0/Microsoft.Common.tasks: Remove spurious
+       Moonlight task declarations.
+
+2010-04-10  Ankit Jain  <jankit@novell.com>
+
+       * xbuild/Microsoft.Common.targets (BuildingResources): Refactor to
+       (PrepareResources): .. this.
+       (PrepareResourcesDependsOn): New.
+       (GetFrameworkPaths): Extract from PrepareForBuild target.
+
+2010-04-08  Ankit Jain  <jankit@novell.com>
+
+       * xbuild/Microsoft.VisualBasic.targets: Fix OutputAssembly
+       property for the Vbc task.
+
+2010-04-08  Ankit Jain  <jankit@novell.com>
+
+       Fix bug #594531.
+       * xbuild/Microsoft.VisualBasic.targets: Set RootNamespace
+       property of Vbc task.
+
+2010-04-08  Ankit Jain  <jankit@novell.com>
+
+       Fix bug #594526.
+       * xbuild/Microsoft.VisualBasic.targets(CoreCompile): Fix Outputs
+       to use @(IntermediateAssembly) instead of $(IntermediateAssembly).
+       Patch suggested by Eli Bishop (eli@wavemarket.com).
+
+2010-04-06  Ankit Jain  <jankit@novell.com>
+
+       * SolutionParser.cs: Identify and emit warning for a
+       common problem on some installations of windows.
+
+2010-04-06  Ankit Jain  <jankit@novell.com>
+
+       * Makefile: Add xbuild_targets.make .
+
+2010-04-03  Ankit Jain  <jankit@novell.com>
+
+       * Main.cs (Execute): If toolsversion is specified on the command line,
+       then use that.
+       * Parameters.cs: Read toolsversion from the command line ('/tv:..') .
+       * SolutionParser.cs: Infer ToolsVersion from the sln version.
+       Set ToolsVersion property of the MSBuild tasks, in the generated
+       .sln.proj file, for building the projects.
+
+       * xbuild/Microsoft.Common.tasks: Move to ..
+       * xbuild/2.0/Microsoft.Common.tasks: .. here.
+       * xbuild/3.5/Microsoft.Common.tasks: New.
+       * xbuild/4.0/Microsoft.Common.tasks: New.
+       Use the corresponding 3.5/4.0 tasks assembly.
+
+       * xbuild_targets.make: Copies the target and tasks file in the correct
+       place, to allow running tests with different toolsversion.
+       * Makefile: Import xbuild_targets.make . Use correct assembly names for
+       Utilities assembly, for 3.5/4.0 profiles.
+       Install the correct Microsoft.Common.tasks file for the profile.
+       Copy xbuild.exe to class/lib/$(PROFILE), so that it can find other
+       profile dirs as relative path.
+       (EXTRA_DISTFILES): Add the new Microsoft.Common.tasks files.
+
 2010-03-04  Ankit Jain  <jankit@novell.com>
 
        * CommandLineException.cs (Message): Include the inner exception message
index 8c8cd6c30951f3654121930067e1566db4fa4f20..89c84632a8d3737dc9e6513211a52fdc6bef7125 100644 (file)
@@ -44,7 +44,6 @@ namespace Mono.XBuild.CommandLine {
                
                Parameters      parameters;
                string[]        args;
-               string          binPath;
                string          defaultSchema;
                
                Engine          engine;
@@ -61,11 +60,11 @@ namespace Mono.XBuild.CommandLine {
                
                public MainClass ()
                {
-                       binPath = ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20);
+                       string binPath = ToolLocationHelper.GetPathToDotNetFramework (TargetDotNetFrameworkVersion.Version20);
                        defaultSchema = Path.Combine (binPath, "Microsoft.Build.xsd");
-                       parameters = new Parameters (binPath);
+                       parameters = new Parameters ();
                }
-               
+
                public void Execute ()
                {
                        bool result = false;
@@ -79,7 +78,14 @@ namespace Mono.XBuild.CommandLine {
                                if (parameters.DisplayVersion)
                                        ErrorUtilities.ShowVersion (false);
                                
-                               engine  = new Engine (binPath);
+                               //FIXME: cmd line arg to set toolsversion
+                               engine  = Engine.GlobalEngine;
+                               if (!String.IsNullOrEmpty (parameters.ToolsVersion)) {
+                                       if (engine.Toolsets [parameters.ToolsVersion] == null)
+                                               ErrorUtilities.ReportError (0, String.Format ("Unknown tools version : {0}", parameters.ToolsVersion));
+
+                                       engine.DefaultToolsVersion = parameters.ToolsVersion;
+                               }
                                
                                engine.GlobalProperties = this.parameters.Properties;
                                
index b1122842be6f90cd9c7885ed8e0893941e652d03..8643e4b1ef12a44f5e6ff938f7438b5408335af1 100644 (file)
@@ -3,21 +3,37 @@ SUBDIRS =
 include ../../build/rules.make
 HAS_NUNIT_TEST = yes
 
-LOCAL_MCS_FLAGS = -r:Microsoft.Build.Framework.dll -r:Microsoft.Build.Utilities.dll -r:Microsoft.Build.Engine.dll
-PROGRAM = xbuild.exe
+ifeq (3.5, $(FRAMEWORK_VERSION))
+NAME_SUFFIX = .v3.5
+ASSEMBLY_VERSION = 3.5.0.0
+else
+ifeq (4.0, $(FRAMEWORK_VERSION))
+NAME_SUFFIX = .v4.0
+ASSEMBLY_VERSION = 4.0.0.0
+endif
+endif
+
+LOCAL_MCS_FLAGS = -r:Microsoft.Build.Framework.dll -r:Microsoft.Build.Utilities$(NAME_SUFFIX).dll -r:Microsoft.Build.Engine.dll
+PROGRAM = $(topdir)/class/lib/$(PROFILE)/xbuild.exe
 
 include ../../build/executable.make
 
+CLEAN_FILES= xbuild.exe xbuild.exe.mdb
+
+XBUILD_DIR=.
+include $(XBUILD_DIR)/xbuild_targets.make
+
 install-local: install-extras
 
 WEBAPP_DIR = Microsoft/VisualStudio/v9.0/WebApplications
+SILVERLIGHT_DIR = $(mono_libdir)/mono/xbuild/Microsoft/Silverlight
 EXTRAS_DIR = $(mono_libdir)/mono/$(FRAMEWORK_VERSION)
 install-extras: 
        $(MKINSTALLDIRS) $(DESTDIR)$(EXTRAS_DIR)
        $(INSTALL_DATA) xbuild/xbuild.rsp $(DESTDIR)$(EXTRAS_DIR)
-       $(INSTALL_DATA) xbuild/Microsoft.Common.tasks $(DESTDIR)$(EXTRAS_DIR)
+       $(INSTALL_DATA) xbuild/$(FRAMEWORK_VERSION)/Microsoft.Common.tasks $(DESTDIR)$(EXTRAS_DIR)
        $(INSTALL_DATA) xbuild/Microsoft.Build.xsd $(DESTDIR)$(EXTRAS_DIR)
-       $(INSTALL_DATA) xbuild/Microsoft.Common.targets $(DESTDIR)$(EXTRAS_DIR)
+       $(INSTALL_DATA) xbuild/$(FRAMEWORK_VERSION)/Microsoft.Common.targets $(DESTDIR)$(EXTRAS_DIR)
        $(INSTALL_DATA) xbuild/Microsoft.CSharp.targets $(DESTDIR)$(EXTRAS_DIR)
        $(INSTALL_DATA) xbuild/Microsoft.VisualBasic.targets $(DESTDIR)$(EXTRAS_DIR)
        $(MKINSTALLDIRS) $(DESTDIR)$(EXTRAS_DIR)/MSBuild
@@ -26,14 +42,30 @@ install-extras:
        $(MKINSTALLDIRS) $(DESTDIR)$(mono_libdir)/mono/xbuild
        $(MKINSTALLDIRS) $(DESTDIR)$(mono_libdir)/mono/xbuild/$(WEBAPP_DIR)
        $(INSTALL_DATA) xbuild/Microsoft.WebApplication.targets $(DESTDIR)$(mono_libdir)/mono/xbuild/$(WEBAPP_DIR)
+       $(MKINSTALLDIRS) $(DESTDIR)$(SILVERLIGHT_DIR)/v2.0
+       $(MKINSTALLDIRS) $(DESTDIR)$(SILVERLIGHT_DIR)/v3.0
+       $(INSTALL_DATA) xbuild/Microsoft.Silverlight.CSharp.targets $(DESTDIR)$(SILVERLIGHT_DIR)/v2.0
+       $(INSTALL_DATA) xbuild/Microsoft.Silverlight.CSharp.targets $(DESTDIR)$(SILVERLIGHT_DIR)/v3.0
+       $(INSTALL_DATA) xbuild/Microsoft.Silverlight.VisualBasic.targets $(DESTDIR)$(SILVERLIGHT_DIR)/v2.0
+       $(INSTALL_DATA) xbuild/Microsoft.Silverlight.VisualBasic.targets $(DESTDIR)$(SILVERLIGHT_DIR)/v3.0
+       sed -e 's/@SILVERLIGHT_VERSION@/2.0/g' xbuild/Microsoft.Silverlight.Common.targets > $(DESTDIR)$(SILVERLIGHT_DIR)/v2.0/Microsoft.Silverlight.Common.targets
+       sed -e 's/@SILVERLIGHT_VERSION@/3.0/g' xbuild/Microsoft.Silverlight.Common.targets > $(DESTDIR)$(SILVERLIGHT_DIR)/v3.0/Microsoft.Silverlight.Common.targets
 
 EXTRA_DISTFILES = \
        xbuild/xbuild.rsp \
-       xbuild/Microsoft.Common.tasks \
+       xbuild/2.0/Microsoft.Common.tasks \
+       xbuild/3.5/Microsoft.Common.tasks \
+       xbuild/4.0/Microsoft.Common.tasks \
+       xbuild/2.0/Microsoft.Common.targets \
+       xbuild/3.5/Microsoft.Common.targets \
+       xbuild/4.0/Microsoft.Common.targets \
        xbuild/Microsoft.Build.xsd \
        xbuild/Microsoft.CSharp.targets \
-       xbuild/Microsoft.Common.targets \
        xbuild/MSBuild/Microsoft.Build.CommonTypes.xsd \
        xbuild/MSBuild/Microsoft.Build.Core.xsd         \
        xbuild/Microsoft.VisualBasic.targets \
-       xbuild/Microsoft.WebApplication.targets
+       xbuild/Microsoft.WebApplication.targets \
+       xbuild/Microsoft.Silverlight.Common.targets \
+       xbuild/Microsoft.Silverlight.CSharp.targets \
+       xbuild/Microsoft.Silverlight.VisualBasic.targets \
+       xbuild_targets.make
index 0dab523418c62c2fab0e00b8373bb19d98088be4..8cb4f5d7498fe1cb55f9bec295f18f9dbfc32a26 100644 (file)
@@ -56,10 +56,11 @@ namespace Mono.XBuild.CommandLine {
                string[]                targets;
                bool                    validate;
                string                  validationSchema;
+               string                  toolsVersion;
                
                string                  responseFile;
        
-               public Parameters (string binPath)
+               public Parameters ()
                {
                        consoleLoggerParameters = "";
                        displayHelp = false;
@@ -237,6 +238,8 @@ namespace Mono.XBuild.CommandLine {
                                        ProcessConsoleLoggerParameters (s);
                                } else if (s.StartsWith ("/validate:") || s.StartsWith ("/val:")) {
                                        ProcessValidate (s);
+                               } else if (s.StartsWith ("/toolsversion:") || s.StartsWith ("/tv:")) {
+                                       ToolsVersion = s.Split (':') [1];
                                } else
                                        return false;
                                break;
@@ -386,6 +389,11 @@ namespace Mono.XBuild.CommandLine {
                public string ValidationSchema {
                        get { return validationSchema; }
                }
+
+               public string ToolsVersion {
+                       get { return toolsVersion; }
+                       private set { toolsVersion = value; }
+               }
                
        }
 }
index 9ebff1e0a726f6c28014ff2ad587fa2a3345ea82..c2cece8e9afc9c2e1c48f80df261e53b9bfc5f72 100644 (file)
@@ -91,6 +91,7 @@ namespace Mono.XBuild.CommandLine {
 
                static string guidExpression = "{[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}}";
 
+               static Regex slnVersionRegex = new Regex (@"Microsoft Visual Studio Solution File, Format Version (\d?\d.\d\d)");
                static Regex projectRegex = new Regex ("Project\\(\"(" + guidExpression + ")\"\\) = \"(.*?)\", \"(.*?)\", \"(" + guidExpression + ")\"(\\s*?)((\\s*?)ProjectSection\\((.*?)\\) = (.*?)EndProjectSection(\\s*?))*(\\s*?)EndProject?", RegexOptions.Singleline);
                static Regex projectDependenciesRegex = new Regex ("ProjectSection\\((.*?)\\) = \\w*(.*?)EndProjectSection", RegexOptions.Singleline);
                static Regex projectDependencyRegex = new Regex ("\\s*(" + guidExpression + ") = (" + guidExpression + ")");
@@ -115,6 +116,14 @@ namespace Mono.XBuild.CommandLine {
                        AddGeneralSettings (file, p);
 
                        StreamReader reader = new StreamReader (file);
+                       string slnVersion = GetSlnFileVersion (reader);
+                       if (slnVersion == "11.00")
+                               p.DefaultToolsVersion = "4.0";
+                       else if (slnVersion == "10.00")
+                               p.DefaultToolsVersion = "3.5";
+                       else
+                               p.DefaultToolsVersion = "2.0";
+
                        string line = reader.ReadToEnd ();
                        line = line.Replace ("\r\n", "\n");
                        string solutionDir = Path.GetDirectoryName (file);
@@ -260,6 +269,30 @@ namespace Mono.XBuild.CommandLine {
                        AddSolutionTargets (p, num_levels, websiteProjectInfos.Values);
                }
 
+                string GetSlnFileVersion (StreamReader reader)
+                {
+                        string strVersion = null;
+                        string strInput = null;
+                        Match match;
+
+                        strInput = reader.ReadLine();
+                        if (strInput == null)
+                                return null;
+
+                        match = slnVersionRegex.Match(strInput);
+                        if (!match.Success) {
+                                strInput = reader.ReadLine();
+                                if (strInput == null)
+                                        return null;
+                                match = slnVersionRegex.Match (strInput);
+                        }
+
+                        if (match.Success)
+                                return match.Groups[1].Value;
+
+                        return null;
+                }
+
                void AddGeneralSettings (string solutionFile, Project p)
                {
                        p.DefaultTargets = "Build";
@@ -647,7 +680,17 @@ namespace Mono.XBuild.CommandLine {
                void AddValidateSolutionConfiguration (Project p)
                {
                        Target t = p.Targets.AddNewTarget ("ValidateSolutionConfiguration");
-                       BuildTask task = t.AddNewTask ("Error");
+                       BuildTask task = t.AddNewTask ("Warning");
+                       task.SetParameterValue ("Text", "On windows, an environment variable 'Platform' is set to MCD sometimes, and this overrides the Platform property" +
+                                               " for xbuild, which could be an invalid Platform for this solution file. And so you are getting the following error." +
+                                               " You could override it by either setting the environment variable to nothing, as\n" +
+                                               "   set Platform=\n" +
+                                               "Or explicity specify its value on the command line, as\n" +
+                                               "   xbuild Foo.sln /p:Platform=Release");
+                       task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' != 'true')" +
+                                       " and '$(Platform)' == 'MCD' and '$(OS)' == 'Windows_NT'";
+
+                       task = t.AddNewTask ("Error");
                        task.SetParameterValue ("Text", "Invalid solution configuration and platform: \"$(Configuration)|$(Platform)\".");
                        task.Condition = "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' != 'true')";
                        task = t.AddNewTask ("Warning");
@@ -692,6 +735,7 @@ namespace Mono.XBuild.CommandLine {
                                                if (projectTargetInfo.Build) {
                                                        task = target.AddNewTask ("MSBuild");
                                                        task.SetParameterValue ("Projects", project.FileName);
+                                                       task.SetParameterValue ("ToolsVersion", "$(ProjectToolsVersion)");
 
                                                        if (buildTarget != "Build")
                                                                task.SetParameterValue ("Targets", buildTarget);
@@ -782,6 +826,7 @@ namespace Mono.XBuild.CommandLine {
                                        task = t.AddNewTask ("MSBuild");
                                        task.SetParameterValue ("Condition", String.Format ("'@({0})' != ''", level_str));
                                        task.SetParameterValue ("Projects", String.Format ("@({0})", level_str));
+                                       task.SetParameterValue ("ToolsVersion", "$(ProjectToolsVersion)");
                                        task.SetParameterValue ("Properties",
                                                string.Format ("Configuration=%(Configuration); Platform=%(Platform); BuildingSolutionFile=true; CurrentSolutionConfigurationContents=$(CurrentSolutionConfigurationContents); SolutionDir=$(SolutionDir); SolutionExt=$(SolutionExt); SolutionFileName=$(SolutionFileName); SolutionName=$(SolutionName); SolutionPath=$(SolutionPath)"));
                                        if (buildTarget != "Build")
diff --git a/mcs/tools/xbuild/xbuild/2.0/Microsoft.Common.targets b/mcs/tools/xbuild/xbuild/2.0/Microsoft.Common.targets
new file mode 100644 (file)
index 0000000..4714854
--- /dev/null
@@ -0,0 +1,732 @@
+<Project DefaultTargets="Build" InitialTargets="_ValidateEssentialProperties" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+
+       <PropertyGroup>
+               <TargetExt Condition="'$(OutputType)' == 'Winexe'">.exe</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Exe'">.exe</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Library'">.dll</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Netmodule'">.netmodule</TargetExt>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <ProjectDir Condition="'$(ProjectDir)' == ''">$(MSBuildProjectDirectory)\</ProjectDir>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <AssemblyName Condition="'$(AssemblyName)' == ''">$(RootNamespace)</AssemblyName>
+               <OutputPath Condition="'$(OutputPath)' != '' and !HasTrailingSlash('$(OutputPath)')">$(OutputPath)\</OutputPath> 
+               <OutputPath Condition=" '$(Platform)'=='' and '$(Configuration)'=='' and '$(OutputPath)'=='' ">bin\Debug\</OutputPath>
+               <WarningLevel Condition="'$(WarningLevel)' == ''" >2</WarningLevel>
+               <TargetFrameworkVersion Condition="'$(TargetFrameworkVersion)' == ''">v2.0</TargetFrameworkVersion>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <OutDir Condition="'$(OutDir)' == ''">$(OutputPath)</OutDir>
+               <OutDir Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')">$(OutDir)\</OutDir>
+
+               <_OriginalConfiguration>$(Configuration)</_OriginalConfiguration>
+               <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+               <ConfigurationName Condition="'$(ConfigurationName)' == ''">$(Configuration)</ConfigurationName>
+
+               <_OriginalPlatform>$(Platform)</_OriginalPlatform>
+               <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+               <PlatformName Condition="'$(PlatformName)' == ''">$(Platform)</PlatformName>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)' == ''">obj\</BaseIntermediateOutputPath>
+               <CleanFile Condition="'$(CleanFile)'==''">$(MSBuildProjectFile).FilesWrittenAbsolute.txt</CleanFile>
+       </PropertyGroup>
+
+       <PropertyGroup Condition="'$(IntermediateOutputPath)' == ''">
+               <IntermediateOutputPath Condition=" '$(PlatformName)' == 'AnyCPU'">$(BaseIntermediateOutputPath)$(Configuration)\</IntermediateOutputPath>
+               <IntermediateOutputPath Condition=" '$(PlatformName)' != 'AnyCPU'">$(BaseIntermediateOutputPath)$(PlatformName)\$(Configuration)\</IntermediateOutputPath>
+       </PropertyGroup>
+
+       <ItemGroup>
+               <IntermediateAssembly Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt)" />
+
+               <!-- creating this as a item to use FullPath on it, to build TargetPath -->
+               <_OutDirItem Include="$(OutDir)"/>
+       </ItemGroup>
+
+       <PropertyGroup>
+               <TargetName Condition="'$(TargetName)' == '' ">$(AssemblyName)</TargetName>
+               <TargetFileName Condition="'$(TargetFileName)' == '' ">$(TargetName)$(TargetExt)</TargetFileName>
+               <TargetPath>@(_OutDirItem->'%(FullPath)\$(TargetFileName)')</TargetPath>
+
+               <KeyOriginatorFile Condition=" '$(SignAssembly)' == 'true' ">$(AssemblyOriginatorKeyFile)</KeyOriginatorFile>
+       </PropertyGroup>
+
+       <Target Name="_ValidateEssentialProperties">
+               <Error Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' != 'true'"
+                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
+
+               <Warning Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' == 'true'"
+                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
+
+               <!-- If OutDir is specified via the command line, then the earlier check
+                    to add a trailing slash won't have any affect, so error here. -->
+               <Error
+                       Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')"
+                       Text="OutDir property must end with a slash."/>
+       </Target>
+
+       <Target Name="PrepareForBuild">
+               <Message Importance="High" Text="Configuration: $(Configuration) Platform: $(Platform)"/>
+
+               <!-- Look for app.config, if $(AppConfig) is specified, then use that. Else look in
+                    @(None) and @(Content) -->
+               <CreateItem Include="$(AppConfig)" Condition="'$(AppConfig)' != ''"
+                       AdditionalMetadata="TargetPath=$(TargetFileName).config">
+                       <Output TaskParameter="Include" ItemName="AppConfigWithTargetPath" />
+               </CreateItem>
+
+               <FindAppConfigFile PrimaryList="@(None)" SecondaryList="@(Content)" TargetPath="$(TargetFileName).config"
+                       Condition="'$(AppConfig)' == ''">
+                       <Output TaskParameter="AppConfigFile" ItemName="AppConfigWithTargetPath"/>
+               </FindAppConfigFile>
+
+               <MakeDir 
+                       Directories="$(OutDir);$(IntermediateOutputPath)"
+               />
+       </Target>
+
+       <Target Name="GetFrameworkPaths">
+               <GetFrameworkPath>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.5'"
+                               TaskParameter="FrameworkVersion35Path"
+                               ItemName="TargetFrameworkDirectories"/>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'" 
+                               TaskParameter="FrameworkVersion30Path"
+                               ItemName="TargetFrameworkDirectories"/>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v2.0' or '$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'" 
+                               TaskParameter="FrameworkVersion20Path"
+                               ItemName="TargetFrameworkDirectories"/>
+               </GetFrameworkPath>
+               <Warning Text="TargetFrameworkVersion '$(TargetFrameworkVersion)' not supported by this toolset (ToolsVersion: $(MSBuildToolsVersion))."
+                       Condition="'$(TargetFrameworkVersion)' != 'v3.5' and '$(TargetFrameworkVersion)' != 'v3.0' and '$(TargetFrameworkVersion)' != 'v2.0'"/>
+       </Target>
+
+       <PropertyGroup>
+               <AllowedReferenceAssemblyFileExtensions Condition=" '$(AllowedReferenceAssemblyFileExtensions)' == '' ">
+                       .exe;
+                       .dll
+               </AllowedReferenceAssemblyFileExtensions>
+
+               <AllowedReferenceRelatedFileExtensions Condition=" '$(AllowedReferenceRelatedFileExtensions)' == '' ">
+                       .mdb
+               </AllowedReferenceRelatedFileExtensions>
+
+               <AssemblySearchPaths Condition="'$(AssemblySearchPaths)' == ''">
+                       {CandidateAssemblyFiles};
+                       {HintPathFromItem};
+                       {TargetFrameworkDirectory};
+                       {PkgConfig};
+                       {GAC};
+                       {RawFileName};
+                       $(OutDir)
+               </AssemblySearchPaths>
+
+               <ResolveReferencesDependsOn>
+                       BeforeResolveReferences;
+                       ResolveProjectReferences;
+                       ResolveAssemblyReferences;
+                       AfterResolveReferences
+               </ResolveReferencesDependsOn>
+       </PropertyGroup>
+
+       <Target Name="ResolveReferences" DependsOnTargets="$(ResolveReferencesDependsOn)"/>
+
+       <Target Name="BeforeResolveReferences" />
+       <Target Name="AfterResolveReferences" />
+
+       <Target Name="ResolveAssemblyReferences">
+               <ResolveAssemblyReference
+                       Assemblies="@(Reference)"
+                       AssemblyFiles="@(ChildProjectReferences)"
+                       SearchPaths="$(AssemblySearchPaths)"
+                       CandidateAssemblyFiles="@(Content);@(None)"
+                       TargetFrameworkDirectories="@(TargetFrameworkDirectories)"
+                       AllowedAssemblyExtensions="$(AllowedReferenceAssemblyFileExtensions)"
+                       AllowedRelatedFileExtensions="$(AllowedReferenceRelatedFileExtensions)"
+                       FindDependencies="true"
+                       FindSatellites="true"
+                       FindRelatedFiles="true"
+               >
+                       <Output TaskParameter="ResolvedFiles" ItemName="ResolvedFiles"/>
+                       <Output TaskParameter="ResolvedFiles" ItemName="ReferencePath"/>
+                       <Output TaskParameter="ResolvedDependencyFiles" ItemName="_ResolvedDependencyFiles"/>
+                       <Output TaskParameter="RelatedFiles" ItemName="_ReferenceRelatedPaths"/>
+                       <Output TaskParameter="SatelliteFiles" ItemName="ReferenceSatellitePaths"/>
+                       <Output TaskParameter="CopyLocalFiles" ItemName="ReferenceCopyLocalPaths"/>
+               </ResolveAssemblyReference>
+       </Target>
+
+       <Target
+               Name="AssignProjectConfigurations"
+               Condition="'@(ProjectReference)' != ''">
+
+               <!-- assign configs if building a solution file -->
+               <AssignProjectConfiguration
+                       ProjectReferences = "@(ProjectReference)"
+                       SolutionConfigurationContents = "$(CurrentSolutionConfigurationContents)"
+                       Condition="'$(BuildingSolutionFile)' == 'true'">
+
+                       <Output TaskParameter = "AssignedProjects" ItemName = "ProjectReferenceWithConfiguration"/>
+               </AssignProjectConfiguration>
+
+               <!-- Else, just -->
+               <CreateItem Include="@(ProjectReference)" Condition="'$(BuildingSolutionFile)' != 'true'">
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfiguration"/>
+               </CreateItem>
+
+       </Target>
+
+       <!-- Split projects into 2 lists
+               ProjectReferenceWithConfigurationExistent: Projects existent on disk
+               ProjectReferenceWithConfigurationNonExistent: Projects non-existent on disk -->
+
+       <Target Name="SplitProjectReferencesByExistent"
+               DependsOnTargets="AssignProjectConfigurations">
+
+               <CreateItem Include="@(ProjectReferenceWithConfiguration)" Condition="'@(ProjectReferenceWithConfiguration)' != ''">
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationExistent"
+                               Condition="Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
+
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationNonExistent"
+                               Condition="!Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
+               </CreateItem>
+       </Target>
+
+       <Target
+               Name="ResolveProjectReferences"
+               DependsOnTargets="SplitProjectReferencesByExistent"
+       >
+               <!-- If building from a .sln.proj or from IDE, then referenced projects have already
+                    been built, so just get the target paths -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="GetTargetPath"
+                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and ('$(BuildingSolutionFile)' == 'true' or '$(BuildingInsideVisualStudio)' == 'true')">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
+               </MSBuild>
+
+               <!-- Building a project directly, build the referenced the projects also -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' ">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
+               </MSBuild>
+
+               <Warning Text="Referenced Project %(ProjectReferenceWithConfigurationNonExistent.Identity) not found, ignoring."
+                        Condition="'@(ProjectReferenceWithConfigurationNonExistent)' != ''"/>
+       </Target>
+
+       <Target Name = "CopyFilesMarkedCopyLocal">
+               <Copy
+                       SourceFiles="@(ReferenceCopyLocalPaths)"
+                       DestinationFiles="@(ReferenceCopyLocalPaths->'$(OutDir)%(DestinationSubDirectory)%(Filename)%(Extension)')"
+                       SkipUnchangedFiles="true">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
+               </Copy>
+       </Target>
+
+<!--
+       Not needed at the moment
+       <Target Name="_ComputeNonExistentFileProperty" Condition='false'>
+               <CreateProperty Value="__NonExistentSubDir__\__NonExistentFile__">
+                       <Output TaskParameter="Value" PropertyName="NonExistentFile"/>
+               </CreateProperty>
+       </Target>
+-->
+
+       <PropertyGroup>
+               <BuildDependsOn>
+                       BeforeBuild;
+                       CoreBuild;
+                       AfterBuild
+               </BuildDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BeforeBuild"/>
+       <Target Name="AfterBuild"/>
+
+       <Target Name="Build" DependsOnTargets="$(BuildDependsOn)" Outputs="$(TargetPath)"/>
+
+       <PropertyGroup>
+               <CoreBuildDependsOn>
+                       PrepareForBuild;
+                       GetFrameworkPaths;
+                       PreBuildEvent;
+                       ResolveReferences;
+                       CopyFilesMarkedCopyLocal;
+                       PrepareResources;
+                       Compile;
+                       PrepareForRun;
+                       DeployOutputFiles;
+                       _RecordCleanFile;
+                       PostBuildEvent
+               </CoreBuildDependsOn>
+       </PropertyGroup>
+
+       <Target
+               Name="CoreBuild"
+               DependsOnTargets="$(CoreBuildDependsOn)"
+               Outputs="$(OutDir)$(AssemblyName)$(TargetExt)">
+
+               <OnError ExecuteTargets="_TimestampAfterCompile;PostBuildEvent"
+                       Condition=" '$(RunPostBuildEvent)' == 'Always' or '$(RunPostBuildEvent)' == 'OnOutputUpdated'"/>
+
+               <OnError ExecuteTargets="_RecordCleanFile" />
+       </Target>
+
+       <PropertyGroup>
+               <CompileDependsOn>
+                       ResolveReferences;
+                       BeforeCompile;
+                       _TimestampBeforeCompile;
+                       CoreCompile;
+                       _TimestampAfterCompile;
+                       AfterCompile
+               </CompileDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BeforeCompile" />
+       <Target Name="AfterCompile" />
+
+       <Target Name="Compile" DependsOnTargets="$(CompileDependsOn)"/>
+
+       <PropertyGroup>
+               <PrepareForRunDependsOn>
+                       DeployOutputFiles
+               </PrepareForRunDependsOn>
+       </PropertyGroup>
+       <Target Name="PrepareForRun" DependsOnTargets="$(PrepareForRunDependsOn)"/>
+
+       <PropertyGroup>
+               <PrepareResourcesDependsOn>
+                       AssignTargetPaths;
+                       SplitResourcesByCulture;
+                       CreateManifestResourceNames;
+                       CopyNonResxEmbeddedResources;
+                       GenerateResources;
+                       GenerateSatelliteAssemblies;
+                       CompileLicxFiles
+               </PrepareResourcesDependsOn>
+       </PropertyGroup>
+       <Target Name="PrepareResources" DependsOnTargets="$(PrepareResourcesDependsOn)" />
+
+       <Target Name="SplitResourcesByCulture" DependsOnTargets="AssignTargetPaths">
+               <!-- Extract .licx files into @(LicxFiles) -->
+               <CreateItem Include="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' == '.licx'">
+                       <Output TaskParameter="Include" ItemName="LicxFiles"/>
+               </CreateItem>
+
+               <!-- Split *remaining* resource files into various groups.. -->
+               <AssignCulture Files="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' != '.licx'">
+                       <Output TaskParameter="AssignedFilesWithNoCulture" ItemName="ResourcesWithNoCulture"/>
+                       <Output TaskParameter="AssignedFilesWithCulture" ItemName="ResourcesWithCulture"/>
+               </AssignCulture>
+
+               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' == '.resx'">
+                       <Output TaskParameter="Include" ItemName="ResxWithNoCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' != '.resx'">
+                       <Output TaskParameter="Include" ItemName="NonResxWithNoCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' == '.resx'">
+                       <Output TaskParameter="Include" ItemName="ResxWithCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' != '.resx'">
+                       <Output TaskParameter="Include" ItemName="NonResxWithCulture"/>
+               </CreateItem>
+       </Target>
+
+       <!-- Copy non-resx resources to their manifest resource names, this is what the compiler expects -->
+       <Target Name = "CopyNonResxEmbeddedResources"
+               Condition = "'@(NonResxWithCulture)' != '' or '@(NonResxWithNoCulture)' != '' or '@(ManifestNonResxWithCulture)' != '' or '@(ManifestNonResxWithNoCulture)' != ''">
+
+               <MakeDir Directories="$(IntermediateOutputPath)%(ManifestNonResxWithCulture.Culture)"/>
+               <Copy SourceFiles = "@(NonResxWithCulture)"
+                       DestinationFiles = "@(ManifestNonResxWithCulture->'$(IntermediateOutputPath)%(Identity)')"
+                       SkipUnchangedFiles="true">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithCultureOnDisk"/>
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
+               </Copy>
+
+               <Copy SourceFiles = "@(NonResxWithNoCulture)"
+                       DestinationFiles = "@(ManifestNonResxWithNoCulture->'$(IntermediateOutputPath)%(Identity)')"
+                       SkipUnchangedFiles="true">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithNoCultureOnDisk"/>
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name = "GenerateResources">
+               <GenerateResource
+                       Sources = "@(ResxWithNoCulture)"
+                       UseSourcePath = "true"
+                       OutputResources = "@(ManifestResourceWithNoCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
+                       Condition = "'@(ResxWithNoCulture)' != '' ">
+
+                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithNoCulture"/>
+                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
+               </GenerateResource>
+
+               <GenerateResource
+                       Sources = "@(ResxWithCulture)"
+                       UseSourcePath = "true"
+                       OutputResources = "@(ManifestResourceWithCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
+                       Condition = "'@(ResxWithCulture)' != '' ">
+
+                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithCulture"/>
+                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
+               </GenerateResource>
+       </Target>
+
+       <Target Name="GenerateSatelliteAssemblies"
+               Inputs="@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
+               Outputs="$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
+               <!-- @(NonResxWithCulture) - rename files to ManifestNon.. and then use for AL -->
+               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestResourceWithCulture.Culture)" Condition = "'@(ManifestResourceWithCulture)' != ''" />
+               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestNonResxWithCultureOnDisk.Culture)" Condition = "'@(ManifestNonResxWithCultureOnDisk)' != ''" />
+
+               <AL
+                       Culture = "%(Culture)"
+                       DelaySign="$(DelaySign)"
+                       EmbedResources = "@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
+                       KeyFile="$(KeyOriginatorFile)"
+                       ToolExe="$(AlToolExe)"
+                       ToolPath="$(AlToolPath)"
+                       OutputAssembly = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
+                       <Output TaskParameter="OutputAssembly" ItemName="FileWrites"/>
+               </AL>
+
+
+               <CreateItem
+                       Include = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll"
+                       AdditionalMetadata = "Culture=%(Culture)"
+                       Condition = "'@(ManifestResourceWithCulture)' != '' or '@(ManifestNonResxWithCultureOnDisk)' != ''">
+                       <Output TaskParameter = "Include" ItemName = "IntermediateSatelliteAssemblies" />
+               </CreateItem>
+       </Target>
+
+       <PropertyGroup>
+               <CompileLicxFilesDependsOn></CompileLicxFilesDependsOn>
+       </PropertyGroup>
+
+       <Target Name = "CompileLicxFiles"
+               Condition = "'@(LicxFiles)' != ''"
+               DependsOnTargets = "$(CompileLicxFilesDependsOn)"
+               Outputs = "$(IntermediateOutputPath)$(TargetFileName).licenses">
+               <LC
+                       Sources = "@(LicxFiles)"
+                       LicenseTarget = "$(TargetFileName)"
+                       OutputDirectory = "$(IntermediateOutputPath)"
+                       OutputLicense = "$(IntermediateOutputPath)$(TargetFileName).licenses"
+                       ReferencedAssemblies = "@(ReferencePath);@(_ResolvedDependencyFiles)"
+                       ToolPath = "$(LCToolPath)"
+                       ToolExe = "$(LCToolExe)">
+
+                       <Output TaskParameter="OutputLicense" ItemName="CompiledLicenseFile"/>
+                       <Output TaskParameter="OutputLicense" ItemName="FileWrites"/>
+               </LC>
+       </Target>
+
+       <!-- Assign target paths to files that will need to be copied along with the project -->
+       <Target Name = "AssignTargetPaths">
+               <AssignTargetPath Files="@(None)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="NoneWithTargetPath"/>
+               </AssignTargetPath>
+
+               <AssignTargetPath Files="@(Content)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="ContentWithTargetPath"/>
+               </AssignTargetPath>
+
+               <AssignTargetPath Files="@(EmbeddedResource)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="EmbeddedResourceWithTargetPath"/>
+               </AssignTargetPath>
+       </Target>
+
+       <Target Name="DeployOutputFiles"
+               DependsOnTargets="PrepareResources;CoreCompile;_CopyDeployFilesToOutputDirectory;_CopyAppConfigFile">
+
+               <Copy 
+                       SourceFiles="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
+                       Condition="'$(OutDir)' != '' and Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')"
+                       DestinationFolder="$(OutDir)"
+                       SkipUnchangedFiles="true" >
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+
+               <Copy SourceFiles="@(IntermediateAssembly)" Condition="'$(OutDir)' != '' and Exists ('@(IntermediateAssembly)')" DestinationFolder="$(OutDir)" SkipUnchangedFiles="true">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+
+               <Copy
+                       SourceFiles = "@(IntermediateSatelliteAssemblies)"
+                       DestinationFiles = "@(IntermediateSatelliteAssemblies->'$(OutDir)\%(Culture)\$(AssemblyName).resources.dll')"
+                       Condition = "'@(IntermediateSatelliteAssemblies)' != ''"
+                       SkipUnchangedFiles="true">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name="_CopyDeployFilesToOutputDirectory"
+               DependsOnTargets="GetCopyToOutputDirectoryItems;
+                       _CopyDeployFilesToOutputDirectoryAlways;
+                       _CopyDeployFilesToOutputDirectoryPreserveNewest"/>
+
+       <Target Name="_CopyDeployFilesToOutputDirectoryPreserveNewest"
+               Condition="'@(ItemsToCopyToOutputDirectoryPreserveNewest)' != ''"
+               Inputs="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
+               Outputs="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')">
+
+               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
+                       DestinationFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <!-- Copy if newer -->
+       <Target Name="_CopyDeployFilesToOutputDirectoryAlways"
+               Condition="'@(ItemsToCopyToOutputDirectoryAlways)' != ''">
+
+               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryAlways)"
+                       DestinationFiles="@(ItemsToCopyToOutputDirectoryAlways->'$(OutDir)%(TargetPath)')">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+
+       <Target Name="_CopyAppConfigFile" Condition="'@(AppConfigWithTargetPath)' != ''"
+               Inputs="@(AppConfigWithTargetPath)"
+               Outputs="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
+
+               <Copy SourceFiles="@(AppConfigWithTargetPath)"
+                       DestinationFiles="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name="GetTargetPath" Outputs="$(TargetPath)"/>
+
+       <Target Name="GetCopyToOutputDirectoryItems"
+               Outputs="@(AllItemsFullPathWithTargetPath)"
+               DependsOnTargets="AssignTargetPaths;SplitProjectReferencesByExistent">
+
+               <!-- FIXME: handle .vcproj
+                    FIXME: Private ProjectReferences are honored only in 3.5
+               -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="GetCopyToOutputDirectoryItems"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '%(ProjectReferenceWithConfigurationExistent.Private)' != 'false'">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="AllChildProjectItemsWithTargetPath"/>
+               </MSBuild>
+
+               <!-- Process items from child project. The outputs need to have full path
+                    as they'll be used from other projects -->
+
+               <CreateItem
+                       Include="@(AllChildProjectItemsWithTargetPath->'%(FullPath)')"
+                       Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+
+               </CreateItem>
+
+               <!-- Process _this_ project's items -->
+
+               <CreateItem
+                       Include="@(NoneWithTargetPath->'%(FullPath)')"
+                       Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(NoneWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+               <CreateItem
+                       Include="@(ContentWithTargetPath->'%(FullPath)')"
+                       Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(ContentWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+               <CreateItem
+                       Include="@(EmbeddedResourceWithTargetPath->'%(FullPath)')"
+                       Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+       </Target>
+
+       <!-- Pre/Post BuildEvents -->
+       <PropertyGroup>
+               <PreBuildEventDependsOn />
+       </PropertyGroup>
+
+       <Target Name="PreBuildEvent"
+               Condition="'$(PreBuildEvent)' != ''"
+               DependsOnTargets="$(PreBuildEventDependsOn)">
+
+               <Exec WorkingDirectory="$(OutDir)" Command="$(PreBuildEvent)" />
+       </Target>
+
+       <!-- PostBuildEvent depends on $(RunPostBuildEvent)
+
+               Default: OnBuildSuccess
+               OnBuildSuccess: Run after a successful build
+               OnOutputUpdated: Run only if the output assembly got updates
+               Always: Run always
+       -->
+       <PropertyGroup>
+               <PostBuildEventDependsOn />
+       </PropertyGroup>
+
+       <!-- this gets invoked in two cases, from CoreBuildDependsOn, if the build completes
+            successfully, OR from OnError in CoreBuild, if the build failed and $(RunPostBuildEvent)
+            is 'Always' or 'OnOutputUpdated'. Invoke $(PostBuildEvent) if its either Empty (== OnBuildSuccess)
+            or OnBuildSuccess or Always OR (OnOutputUpdated and output assembly got updated) -->
+       <Target Name="PostBuildEvent"
+               Condition="'$(PostBuildEvent)' != '' and
+                       ('$(RunPostBuildEvent)' != 'OnOutputUpdated' or
+                         '$(_AssemblyModifiedTimeBeforeCompile)' != '$(_AssemblyModifiedTimeAfterCompile)')"
+               DependsOnTargets="$(PostBuildEventDependsOn)">
+
+               <Exec WorkingDirectory="$(OutDir)" Command="$(PostBuildEvent)" />
+       </Target>
+
+       <!-- Timestamp the output assemblies, required for PostBuildEvent -->
+       <Target Name="_TimestampBeforeCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
+               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
+                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeBeforeCompile" />
+               </CreateItem>
+       </Target>
+       <Target Name="_TimestampAfterCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
+               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
+                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeAfterCompile" />
+               </CreateItem>
+       </Target>
+
+       <!-- Rebuild -->
+       <PropertyGroup>
+               <RebuildDependsOn>
+                       BeforeRebuild;
+                       Clean;
+                       $(MSBuildProjectDefaultTargets);
+                       AfterRebuild;
+               </RebuildDependsOn>
+
+               <RebuildDependsOn Condition="'$(MSBuildProjectDefaultTargets)' == 'Rebuild'">
+                       BeforeRebuild;
+                       Clean;
+                       Build;
+                       AfterRebuild;
+               </RebuildDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BeforeRebuild" />
+       <Target Name="AfterRebuild" />
+
+       <Target Name="Rebuild"
+               DependsOnTargets="$(RebuildDependsOn)"
+               Outputs="$(TargetPath)"/>
+
+       <!-- Clean -->
+       <Target Name="_RecordCleanFile"
+               DependsOnTargets="_GetCompileOutputsForClean">
+
+               <!-- add to list of previous writes for this platform/config -->
+
+               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
+                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
+               </ReadLinesFromFile>
+
+               <RemoveDuplicates Inputs="@(PreviousFileWrites);@(FileWrites->'%(FullPath)')">
+                       <Output TaskParameter="Filtered" ItemName="CombinedFileWrites"/>
+               </RemoveDuplicates>
+
+               <WriteLinesToFile
+                       File="$(IntermediateOutputPath)$(CleanFile)"
+                       Lines="@(CombinedFileWrites)"
+                       Overwrite="true"/>
+       </Target>
+
+       <PropertyGroup>
+               <CleanDependsOn>
+                       BeforeClean;
+                       CleanReferencedProjects;
+                       CoreClean;
+                       AfterClean
+               </CleanDependsOn>
+       </PropertyGroup>
+
+       <Target Name="_GetCompileOutputsForClean">
+               <!-- assembly and debug file in the *intermediate output path* -->
+               <CreateItem Include="@(IntermediateAssembly)" Condition="Exists('@(IntermediateAssembly)')">
+                       <Output TaskParameter="Include" ItemName="FileWrites"/>
+               </CreateItem>
+
+               <CreateItem Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
+                       Condition="Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')">
+                       <Output TaskParameter="Include" ItemName="FileWrites"/>
+               </CreateItem>
+       </Target>
+
+       <!-- Get the list of files written, for clean -->
+       <Target Name="_GetCleanFileWrites"
+               DependsOnTargets="_GetCompileOutputsForClean">
+               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
+                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
+               </ReadLinesFromFile>
+       </Target>
+
+       <Target Name="CleanReferencedProjects"
+               DependsOnTargets="AssignProjectConfigurations">
+
+               <!-- If building from .sln.proj or from IDE, clean will get handled by them,
+                    else we are building a project directly, from the command line, so
+                    clean the referenced projects -->
+               <MSBuild Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="Clean"
+                       Condition=" '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' and '@(ProjectReferenceWithConfigurationExistent)' != ''" />
+
+       </Target>
+
+       <Target Name="Clean" DependsOnTargets="$(CleanDependsOn)"/>
+
+       <!-- Override in project to run before/after clean tasks -->
+       <Target Name="BeforeClean" />
+       <Target Name="AfterClean" />
+
+       <Target Name="CoreClean" DependsOnTargets="_GetCleanFileWrites">
+               <Delete Files="@(PreviousFileWrites);@(FileWrites)" TreatErrorsAsWarnings="true"/>
+
+               <!-- all previous files written for this platform/config have been deleted,
+                    we can safely remove the file list now -->
+               <Delete Files="$(IntermediateOutputPath)$(CleanFile)" TreatErrorsAsWarnings="true" />
+       </Target>
+
+</Project>
diff --git a/mcs/tools/xbuild/xbuild/2.0/Microsoft.Common.tasks b/mcs/tools/xbuild/xbuild/2.0/Microsoft.Common.tasks
new file mode 100644 (file)
index 0000000..9b1c1ad
--- /dev/null
@@ -0,0 +1,33 @@
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" >
+       <UsingTask TaskName="Microsoft.Build.Tasks.AL"                  AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignTargetPath"    AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignCulture"       AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignProjectConfiguration"  AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CallTarget"          AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CombinePath"         AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Copy"                AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CreateItem"          AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CreateProperty"      AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Csc"                 AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Delete"              AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Error"               AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Exec"                AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.FindAppConfigFile"   AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.FindUnderPath"       AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GenerateResource"    AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkPath"    AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkSdkPath" AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.LC"                  AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.MakeDir"             AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Message"             AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.MSBuild"             AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.ReadLinesFromFile"   AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDir"           AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDuplicates"            AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.ResolveAssemblyReference"            AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.SignFile"            AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Touch"               AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Vbc"                 AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Warning"             AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.WriteLinesToFile"    AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+</Project>
diff --git a/mcs/tools/xbuild/xbuild/3.5/Microsoft.Common.targets b/mcs/tools/xbuild/xbuild/3.5/Microsoft.Common.targets
new file mode 100644 (file)
index 0000000..4714854
--- /dev/null
@@ -0,0 +1,732 @@
+<Project DefaultTargets="Build" InitialTargets="_ValidateEssentialProperties" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+
+       <PropertyGroup>
+               <TargetExt Condition="'$(OutputType)' == 'Winexe'">.exe</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Exe'">.exe</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Library'">.dll</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Netmodule'">.netmodule</TargetExt>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <ProjectDir Condition="'$(ProjectDir)' == ''">$(MSBuildProjectDirectory)\</ProjectDir>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <AssemblyName Condition="'$(AssemblyName)' == ''">$(RootNamespace)</AssemblyName>
+               <OutputPath Condition="'$(OutputPath)' != '' and !HasTrailingSlash('$(OutputPath)')">$(OutputPath)\</OutputPath> 
+               <OutputPath Condition=" '$(Platform)'=='' and '$(Configuration)'=='' and '$(OutputPath)'=='' ">bin\Debug\</OutputPath>
+               <WarningLevel Condition="'$(WarningLevel)' == ''" >2</WarningLevel>
+               <TargetFrameworkVersion Condition="'$(TargetFrameworkVersion)' == ''">v2.0</TargetFrameworkVersion>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <OutDir Condition="'$(OutDir)' == ''">$(OutputPath)</OutDir>
+               <OutDir Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')">$(OutDir)\</OutDir>
+
+               <_OriginalConfiguration>$(Configuration)</_OriginalConfiguration>
+               <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+               <ConfigurationName Condition="'$(ConfigurationName)' == ''">$(Configuration)</ConfigurationName>
+
+               <_OriginalPlatform>$(Platform)</_OriginalPlatform>
+               <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+               <PlatformName Condition="'$(PlatformName)' == ''">$(Platform)</PlatformName>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)' == ''">obj\</BaseIntermediateOutputPath>
+               <CleanFile Condition="'$(CleanFile)'==''">$(MSBuildProjectFile).FilesWrittenAbsolute.txt</CleanFile>
+       </PropertyGroup>
+
+       <PropertyGroup Condition="'$(IntermediateOutputPath)' == ''">
+               <IntermediateOutputPath Condition=" '$(PlatformName)' == 'AnyCPU'">$(BaseIntermediateOutputPath)$(Configuration)\</IntermediateOutputPath>
+               <IntermediateOutputPath Condition=" '$(PlatformName)' != 'AnyCPU'">$(BaseIntermediateOutputPath)$(PlatformName)\$(Configuration)\</IntermediateOutputPath>
+       </PropertyGroup>
+
+       <ItemGroup>
+               <IntermediateAssembly Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt)" />
+
+               <!-- creating this as a item to use FullPath on it, to build TargetPath -->
+               <_OutDirItem Include="$(OutDir)"/>
+       </ItemGroup>
+
+       <PropertyGroup>
+               <TargetName Condition="'$(TargetName)' == '' ">$(AssemblyName)</TargetName>
+               <TargetFileName Condition="'$(TargetFileName)' == '' ">$(TargetName)$(TargetExt)</TargetFileName>
+               <TargetPath>@(_OutDirItem->'%(FullPath)\$(TargetFileName)')</TargetPath>
+
+               <KeyOriginatorFile Condition=" '$(SignAssembly)' == 'true' ">$(AssemblyOriginatorKeyFile)</KeyOriginatorFile>
+       </PropertyGroup>
+
+       <Target Name="_ValidateEssentialProperties">
+               <Error Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' != 'true'"
+                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
+
+               <Warning Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' == 'true'"
+                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
+
+               <!-- If OutDir is specified via the command line, then the earlier check
+                    to add a trailing slash won't have any affect, so error here. -->
+               <Error
+                       Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')"
+                       Text="OutDir property must end with a slash."/>
+       </Target>
+
+       <Target Name="PrepareForBuild">
+               <Message Importance="High" Text="Configuration: $(Configuration) Platform: $(Platform)"/>
+
+               <!-- Look for app.config, if $(AppConfig) is specified, then use that. Else look in
+                    @(None) and @(Content) -->
+               <CreateItem Include="$(AppConfig)" Condition="'$(AppConfig)' != ''"
+                       AdditionalMetadata="TargetPath=$(TargetFileName).config">
+                       <Output TaskParameter="Include" ItemName="AppConfigWithTargetPath" />
+               </CreateItem>
+
+               <FindAppConfigFile PrimaryList="@(None)" SecondaryList="@(Content)" TargetPath="$(TargetFileName).config"
+                       Condition="'$(AppConfig)' == ''">
+                       <Output TaskParameter="AppConfigFile" ItemName="AppConfigWithTargetPath"/>
+               </FindAppConfigFile>
+
+               <MakeDir 
+                       Directories="$(OutDir);$(IntermediateOutputPath)"
+               />
+       </Target>
+
+       <Target Name="GetFrameworkPaths">
+               <GetFrameworkPath>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.5'"
+                               TaskParameter="FrameworkVersion35Path"
+                               ItemName="TargetFrameworkDirectories"/>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'" 
+                               TaskParameter="FrameworkVersion30Path"
+                               ItemName="TargetFrameworkDirectories"/>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v2.0' or '$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'" 
+                               TaskParameter="FrameworkVersion20Path"
+                               ItemName="TargetFrameworkDirectories"/>
+               </GetFrameworkPath>
+               <Warning Text="TargetFrameworkVersion '$(TargetFrameworkVersion)' not supported by this toolset (ToolsVersion: $(MSBuildToolsVersion))."
+                       Condition="'$(TargetFrameworkVersion)' != 'v3.5' and '$(TargetFrameworkVersion)' != 'v3.0' and '$(TargetFrameworkVersion)' != 'v2.0'"/>
+       </Target>
+
+       <PropertyGroup>
+               <AllowedReferenceAssemblyFileExtensions Condition=" '$(AllowedReferenceAssemblyFileExtensions)' == '' ">
+                       .exe;
+                       .dll
+               </AllowedReferenceAssemblyFileExtensions>
+
+               <AllowedReferenceRelatedFileExtensions Condition=" '$(AllowedReferenceRelatedFileExtensions)' == '' ">
+                       .mdb
+               </AllowedReferenceRelatedFileExtensions>
+
+               <AssemblySearchPaths Condition="'$(AssemblySearchPaths)' == ''">
+                       {CandidateAssemblyFiles};
+                       {HintPathFromItem};
+                       {TargetFrameworkDirectory};
+                       {PkgConfig};
+                       {GAC};
+                       {RawFileName};
+                       $(OutDir)
+               </AssemblySearchPaths>
+
+               <ResolveReferencesDependsOn>
+                       BeforeResolveReferences;
+                       ResolveProjectReferences;
+                       ResolveAssemblyReferences;
+                       AfterResolveReferences
+               </ResolveReferencesDependsOn>
+       </PropertyGroup>
+
+       <Target Name="ResolveReferences" DependsOnTargets="$(ResolveReferencesDependsOn)"/>
+
+       <Target Name="BeforeResolveReferences" />
+       <Target Name="AfterResolveReferences" />
+
+       <Target Name="ResolveAssemblyReferences">
+               <ResolveAssemblyReference
+                       Assemblies="@(Reference)"
+                       AssemblyFiles="@(ChildProjectReferences)"
+                       SearchPaths="$(AssemblySearchPaths)"
+                       CandidateAssemblyFiles="@(Content);@(None)"
+                       TargetFrameworkDirectories="@(TargetFrameworkDirectories)"
+                       AllowedAssemblyExtensions="$(AllowedReferenceAssemblyFileExtensions)"
+                       AllowedRelatedFileExtensions="$(AllowedReferenceRelatedFileExtensions)"
+                       FindDependencies="true"
+                       FindSatellites="true"
+                       FindRelatedFiles="true"
+               >
+                       <Output TaskParameter="ResolvedFiles" ItemName="ResolvedFiles"/>
+                       <Output TaskParameter="ResolvedFiles" ItemName="ReferencePath"/>
+                       <Output TaskParameter="ResolvedDependencyFiles" ItemName="_ResolvedDependencyFiles"/>
+                       <Output TaskParameter="RelatedFiles" ItemName="_ReferenceRelatedPaths"/>
+                       <Output TaskParameter="SatelliteFiles" ItemName="ReferenceSatellitePaths"/>
+                       <Output TaskParameter="CopyLocalFiles" ItemName="ReferenceCopyLocalPaths"/>
+               </ResolveAssemblyReference>
+       </Target>
+
+       <Target
+               Name="AssignProjectConfigurations"
+               Condition="'@(ProjectReference)' != ''">
+
+               <!-- assign configs if building a solution file -->
+               <AssignProjectConfiguration
+                       ProjectReferences = "@(ProjectReference)"
+                       SolutionConfigurationContents = "$(CurrentSolutionConfigurationContents)"
+                       Condition="'$(BuildingSolutionFile)' == 'true'">
+
+                       <Output TaskParameter = "AssignedProjects" ItemName = "ProjectReferenceWithConfiguration"/>
+               </AssignProjectConfiguration>
+
+               <!-- Else, just -->
+               <CreateItem Include="@(ProjectReference)" Condition="'$(BuildingSolutionFile)' != 'true'">
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfiguration"/>
+               </CreateItem>
+
+       </Target>
+
+       <!-- Split projects into 2 lists
+               ProjectReferenceWithConfigurationExistent: Projects existent on disk
+               ProjectReferenceWithConfigurationNonExistent: Projects non-existent on disk -->
+
+       <Target Name="SplitProjectReferencesByExistent"
+               DependsOnTargets="AssignProjectConfigurations">
+
+               <CreateItem Include="@(ProjectReferenceWithConfiguration)" Condition="'@(ProjectReferenceWithConfiguration)' != ''">
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationExistent"
+                               Condition="Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
+
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationNonExistent"
+                               Condition="!Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
+               </CreateItem>
+       </Target>
+
+       <Target
+               Name="ResolveProjectReferences"
+               DependsOnTargets="SplitProjectReferencesByExistent"
+       >
+               <!-- If building from a .sln.proj or from IDE, then referenced projects have already
+                    been built, so just get the target paths -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="GetTargetPath"
+                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and ('$(BuildingSolutionFile)' == 'true' or '$(BuildingInsideVisualStudio)' == 'true')">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
+               </MSBuild>
+
+               <!-- Building a project directly, build the referenced the projects also -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' ">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
+               </MSBuild>
+
+               <Warning Text="Referenced Project %(ProjectReferenceWithConfigurationNonExistent.Identity) not found, ignoring."
+                        Condition="'@(ProjectReferenceWithConfigurationNonExistent)' != ''"/>
+       </Target>
+
+       <Target Name = "CopyFilesMarkedCopyLocal">
+               <Copy
+                       SourceFiles="@(ReferenceCopyLocalPaths)"
+                       DestinationFiles="@(ReferenceCopyLocalPaths->'$(OutDir)%(DestinationSubDirectory)%(Filename)%(Extension)')"
+                       SkipUnchangedFiles="true">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
+               </Copy>
+       </Target>
+
+<!--
+       Not needed at the moment
+       <Target Name="_ComputeNonExistentFileProperty" Condition='false'>
+               <CreateProperty Value="__NonExistentSubDir__\__NonExistentFile__">
+                       <Output TaskParameter="Value" PropertyName="NonExistentFile"/>
+               </CreateProperty>
+       </Target>
+-->
+
+       <PropertyGroup>
+               <BuildDependsOn>
+                       BeforeBuild;
+                       CoreBuild;
+                       AfterBuild
+               </BuildDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BeforeBuild"/>
+       <Target Name="AfterBuild"/>
+
+       <Target Name="Build" DependsOnTargets="$(BuildDependsOn)" Outputs="$(TargetPath)"/>
+
+       <PropertyGroup>
+               <CoreBuildDependsOn>
+                       PrepareForBuild;
+                       GetFrameworkPaths;
+                       PreBuildEvent;
+                       ResolveReferences;
+                       CopyFilesMarkedCopyLocal;
+                       PrepareResources;
+                       Compile;
+                       PrepareForRun;
+                       DeployOutputFiles;
+                       _RecordCleanFile;
+                       PostBuildEvent
+               </CoreBuildDependsOn>
+       </PropertyGroup>
+
+       <Target
+               Name="CoreBuild"
+               DependsOnTargets="$(CoreBuildDependsOn)"
+               Outputs="$(OutDir)$(AssemblyName)$(TargetExt)">
+
+               <OnError ExecuteTargets="_TimestampAfterCompile;PostBuildEvent"
+                       Condition=" '$(RunPostBuildEvent)' == 'Always' or '$(RunPostBuildEvent)' == 'OnOutputUpdated'"/>
+
+               <OnError ExecuteTargets="_RecordCleanFile" />
+       </Target>
+
+       <PropertyGroup>
+               <CompileDependsOn>
+                       ResolveReferences;
+                       BeforeCompile;
+                       _TimestampBeforeCompile;
+                       CoreCompile;
+                       _TimestampAfterCompile;
+                       AfterCompile
+               </CompileDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BeforeCompile" />
+       <Target Name="AfterCompile" />
+
+       <Target Name="Compile" DependsOnTargets="$(CompileDependsOn)"/>
+
+       <PropertyGroup>
+               <PrepareForRunDependsOn>
+                       DeployOutputFiles
+               </PrepareForRunDependsOn>
+       </PropertyGroup>
+       <Target Name="PrepareForRun" DependsOnTargets="$(PrepareForRunDependsOn)"/>
+
+       <PropertyGroup>
+               <PrepareResourcesDependsOn>
+                       AssignTargetPaths;
+                       SplitResourcesByCulture;
+                       CreateManifestResourceNames;
+                       CopyNonResxEmbeddedResources;
+                       GenerateResources;
+                       GenerateSatelliteAssemblies;
+                       CompileLicxFiles
+               </PrepareResourcesDependsOn>
+       </PropertyGroup>
+       <Target Name="PrepareResources" DependsOnTargets="$(PrepareResourcesDependsOn)" />
+
+       <Target Name="SplitResourcesByCulture" DependsOnTargets="AssignTargetPaths">
+               <!-- Extract .licx files into @(LicxFiles) -->
+               <CreateItem Include="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' == '.licx'">
+                       <Output TaskParameter="Include" ItemName="LicxFiles"/>
+               </CreateItem>
+
+               <!-- Split *remaining* resource files into various groups.. -->
+               <AssignCulture Files="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' != '.licx'">
+                       <Output TaskParameter="AssignedFilesWithNoCulture" ItemName="ResourcesWithNoCulture"/>
+                       <Output TaskParameter="AssignedFilesWithCulture" ItemName="ResourcesWithCulture"/>
+               </AssignCulture>
+
+               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' == '.resx'">
+                       <Output TaskParameter="Include" ItemName="ResxWithNoCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' != '.resx'">
+                       <Output TaskParameter="Include" ItemName="NonResxWithNoCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' == '.resx'">
+                       <Output TaskParameter="Include" ItemName="ResxWithCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' != '.resx'">
+                       <Output TaskParameter="Include" ItemName="NonResxWithCulture"/>
+               </CreateItem>
+       </Target>
+
+       <!-- Copy non-resx resources to their manifest resource names, this is what the compiler expects -->
+       <Target Name = "CopyNonResxEmbeddedResources"
+               Condition = "'@(NonResxWithCulture)' != '' or '@(NonResxWithNoCulture)' != '' or '@(ManifestNonResxWithCulture)' != '' or '@(ManifestNonResxWithNoCulture)' != ''">
+
+               <MakeDir Directories="$(IntermediateOutputPath)%(ManifestNonResxWithCulture.Culture)"/>
+               <Copy SourceFiles = "@(NonResxWithCulture)"
+                       DestinationFiles = "@(ManifestNonResxWithCulture->'$(IntermediateOutputPath)%(Identity)')"
+                       SkipUnchangedFiles="true">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithCultureOnDisk"/>
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
+               </Copy>
+
+               <Copy SourceFiles = "@(NonResxWithNoCulture)"
+                       DestinationFiles = "@(ManifestNonResxWithNoCulture->'$(IntermediateOutputPath)%(Identity)')"
+                       SkipUnchangedFiles="true">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithNoCultureOnDisk"/>
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name = "GenerateResources">
+               <GenerateResource
+                       Sources = "@(ResxWithNoCulture)"
+                       UseSourcePath = "true"
+                       OutputResources = "@(ManifestResourceWithNoCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
+                       Condition = "'@(ResxWithNoCulture)' != '' ">
+
+                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithNoCulture"/>
+                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
+               </GenerateResource>
+
+               <GenerateResource
+                       Sources = "@(ResxWithCulture)"
+                       UseSourcePath = "true"
+                       OutputResources = "@(ManifestResourceWithCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
+                       Condition = "'@(ResxWithCulture)' != '' ">
+
+                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithCulture"/>
+                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
+               </GenerateResource>
+       </Target>
+
+       <Target Name="GenerateSatelliteAssemblies"
+               Inputs="@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
+               Outputs="$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
+               <!-- @(NonResxWithCulture) - rename files to ManifestNon.. and then use for AL -->
+               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestResourceWithCulture.Culture)" Condition = "'@(ManifestResourceWithCulture)' != ''" />
+               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestNonResxWithCultureOnDisk.Culture)" Condition = "'@(ManifestNonResxWithCultureOnDisk)' != ''" />
+
+               <AL
+                       Culture = "%(Culture)"
+                       DelaySign="$(DelaySign)"
+                       EmbedResources = "@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
+                       KeyFile="$(KeyOriginatorFile)"
+                       ToolExe="$(AlToolExe)"
+                       ToolPath="$(AlToolPath)"
+                       OutputAssembly = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
+                       <Output TaskParameter="OutputAssembly" ItemName="FileWrites"/>
+               </AL>
+
+
+               <CreateItem
+                       Include = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll"
+                       AdditionalMetadata = "Culture=%(Culture)"
+                       Condition = "'@(ManifestResourceWithCulture)' != '' or '@(ManifestNonResxWithCultureOnDisk)' != ''">
+                       <Output TaskParameter = "Include" ItemName = "IntermediateSatelliteAssemblies" />
+               </CreateItem>
+       </Target>
+
+       <PropertyGroup>
+               <CompileLicxFilesDependsOn></CompileLicxFilesDependsOn>
+       </PropertyGroup>
+
+       <Target Name = "CompileLicxFiles"
+               Condition = "'@(LicxFiles)' != ''"
+               DependsOnTargets = "$(CompileLicxFilesDependsOn)"
+               Outputs = "$(IntermediateOutputPath)$(TargetFileName).licenses">
+               <LC
+                       Sources = "@(LicxFiles)"
+                       LicenseTarget = "$(TargetFileName)"
+                       OutputDirectory = "$(IntermediateOutputPath)"
+                       OutputLicense = "$(IntermediateOutputPath)$(TargetFileName).licenses"
+                       ReferencedAssemblies = "@(ReferencePath);@(_ResolvedDependencyFiles)"
+                       ToolPath = "$(LCToolPath)"
+                       ToolExe = "$(LCToolExe)">
+
+                       <Output TaskParameter="OutputLicense" ItemName="CompiledLicenseFile"/>
+                       <Output TaskParameter="OutputLicense" ItemName="FileWrites"/>
+               </LC>
+       </Target>
+
+       <!-- Assign target paths to files that will need to be copied along with the project -->
+       <Target Name = "AssignTargetPaths">
+               <AssignTargetPath Files="@(None)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="NoneWithTargetPath"/>
+               </AssignTargetPath>
+
+               <AssignTargetPath Files="@(Content)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="ContentWithTargetPath"/>
+               </AssignTargetPath>
+
+               <AssignTargetPath Files="@(EmbeddedResource)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="EmbeddedResourceWithTargetPath"/>
+               </AssignTargetPath>
+       </Target>
+
+       <Target Name="DeployOutputFiles"
+               DependsOnTargets="PrepareResources;CoreCompile;_CopyDeployFilesToOutputDirectory;_CopyAppConfigFile">
+
+               <Copy 
+                       SourceFiles="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
+                       Condition="'$(OutDir)' != '' and Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')"
+                       DestinationFolder="$(OutDir)"
+                       SkipUnchangedFiles="true" >
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+
+               <Copy SourceFiles="@(IntermediateAssembly)" Condition="'$(OutDir)' != '' and Exists ('@(IntermediateAssembly)')" DestinationFolder="$(OutDir)" SkipUnchangedFiles="true">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+
+               <Copy
+                       SourceFiles = "@(IntermediateSatelliteAssemblies)"
+                       DestinationFiles = "@(IntermediateSatelliteAssemblies->'$(OutDir)\%(Culture)\$(AssemblyName).resources.dll')"
+                       Condition = "'@(IntermediateSatelliteAssemblies)' != ''"
+                       SkipUnchangedFiles="true">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name="_CopyDeployFilesToOutputDirectory"
+               DependsOnTargets="GetCopyToOutputDirectoryItems;
+                       _CopyDeployFilesToOutputDirectoryAlways;
+                       _CopyDeployFilesToOutputDirectoryPreserveNewest"/>
+
+       <Target Name="_CopyDeployFilesToOutputDirectoryPreserveNewest"
+               Condition="'@(ItemsToCopyToOutputDirectoryPreserveNewest)' != ''"
+               Inputs="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
+               Outputs="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')">
+
+               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
+                       DestinationFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <!-- Copy if newer -->
+       <Target Name="_CopyDeployFilesToOutputDirectoryAlways"
+               Condition="'@(ItemsToCopyToOutputDirectoryAlways)' != ''">
+
+               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryAlways)"
+                       DestinationFiles="@(ItemsToCopyToOutputDirectoryAlways->'$(OutDir)%(TargetPath)')">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+
+       <Target Name="_CopyAppConfigFile" Condition="'@(AppConfigWithTargetPath)' != ''"
+               Inputs="@(AppConfigWithTargetPath)"
+               Outputs="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
+
+               <Copy SourceFiles="@(AppConfigWithTargetPath)"
+                       DestinationFiles="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name="GetTargetPath" Outputs="$(TargetPath)"/>
+
+       <Target Name="GetCopyToOutputDirectoryItems"
+               Outputs="@(AllItemsFullPathWithTargetPath)"
+               DependsOnTargets="AssignTargetPaths;SplitProjectReferencesByExistent">
+
+               <!-- FIXME: handle .vcproj
+                    FIXME: Private ProjectReferences are honored only in 3.5
+               -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="GetCopyToOutputDirectoryItems"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '%(ProjectReferenceWithConfigurationExistent.Private)' != 'false'">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="AllChildProjectItemsWithTargetPath"/>
+               </MSBuild>
+
+               <!-- Process items from child project. The outputs need to have full path
+                    as they'll be used from other projects -->
+
+               <CreateItem
+                       Include="@(AllChildProjectItemsWithTargetPath->'%(FullPath)')"
+                       Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+
+               </CreateItem>
+
+               <!-- Process _this_ project's items -->
+
+               <CreateItem
+                       Include="@(NoneWithTargetPath->'%(FullPath)')"
+                       Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(NoneWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+               <CreateItem
+                       Include="@(ContentWithTargetPath->'%(FullPath)')"
+                       Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(ContentWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+               <CreateItem
+                       Include="@(EmbeddedResourceWithTargetPath->'%(FullPath)')"
+                       Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+       </Target>
+
+       <!-- Pre/Post BuildEvents -->
+       <PropertyGroup>
+               <PreBuildEventDependsOn />
+       </PropertyGroup>
+
+       <Target Name="PreBuildEvent"
+               Condition="'$(PreBuildEvent)' != ''"
+               DependsOnTargets="$(PreBuildEventDependsOn)">
+
+               <Exec WorkingDirectory="$(OutDir)" Command="$(PreBuildEvent)" />
+       </Target>
+
+       <!-- PostBuildEvent depends on $(RunPostBuildEvent)
+
+               Default: OnBuildSuccess
+               OnBuildSuccess: Run after a successful build
+               OnOutputUpdated: Run only if the output assembly got updates
+               Always: Run always
+       -->
+       <PropertyGroup>
+               <PostBuildEventDependsOn />
+       </PropertyGroup>
+
+       <!-- this gets invoked in two cases, from CoreBuildDependsOn, if the build completes
+            successfully, OR from OnError in CoreBuild, if the build failed and $(RunPostBuildEvent)
+            is 'Always' or 'OnOutputUpdated'. Invoke $(PostBuildEvent) if its either Empty (== OnBuildSuccess)
+            or OnBuildSuccess or Always OR (OnOutputUpdated and output assembly got updated) -->
+       <Target Name="PostBuildEvent"
+               Condition="'$(PostBuildEvent)' != '' and
+                       ('$(RunPostBuildEvent)' != 'OnOutputUpdated' or
+                         '$(_AssemblyModifiedTimeBeforeCompile)' != '$(_AssemblyModifiedTimeAfterCompile)')"
+               DependsOnTargets="$(PostBuildEventDependsOn)">
+
+               <Exec WorkingDirectory="$(OutDir)" Command="$(PostBuildEvent)" />
+       </Target>
+
+       <!-- Timestamp the output assemblies, required for PostBuildEvent -->
+       <Target Name="_TimestampBeforeCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
+               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
+                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeBeforeCompile" />
+               </CreateItem>
+       </Target>
+       <Target Name="_TimestampAfterCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
+               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
+                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeAfterCompile" />
+               </CreateItem>
+       </Target>
+
+       <!-- Rebuild -->
+       <PropertyGroup>
+               <RebuildDependsOn>
+                       BeforeRebuild;
+                       Clean;
+                       $(MSBuildProjectDefaultTargets);
+                       AfterRebuild;
+               </RebuildDependsOn>
+
+               <RebuildDependsOn Condition="'$(MSBuildProjectDefaultTargets)' == 'Rebuild'">
+                       BeforeRebuild;
+                       Clean;
+                       Build;
+                       AfterRebuild;
+               </RebuildDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BeforeRebuild" />
+       <Target Name="AfterRebuild" />
+
+       <Target Name="Rebuild"
+               DependsOnTargets="$(RebuildDependsOn)"
+               Outputs="$(TargetPath)"/>
+
+       <!-- Clean -->
+       <Target Name="_RecordCleanFile"
+               DependsOnTargets="_GetCompileOutputsForClean">
+
+               <!-- add to list of previous writes for this platform/config -->
+
+               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
+                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
+               </ReadLinesFromFile>
+
+               <RemoveDuplicates Inputs="@(PreviousFileWrites);@(FileWrites->'%(FullPath)')">
+                       <Output TaskParameter="Filtered" ItemName="CombinedFileWrites"/>
+               </RemoveDuplicates>
+
+               <WriteLinesToFile
+                       File="$(IntermediateOutputPath)$(CleanFile)"
+                       Lines="@(CombinedFileWrites)"
+                       Overwrite="true"/>
+       </Target>
+
+       <PropertyGroup>
+               <CleanDependsOn>
+                       BeforeClean;
+                       CleanReferencedProjects;
+                       CoreClean;
+                       AfterClean
+               </CleanDependsOn>
+       </PropertyGroup>
+
+       <Target Name="_GetCompileOutputsForClean">
+               <!-- assembly and debug file in the *intermediate output path* -->
+               <CreateItem Include="@(IntermediateAssembly)" Condition="Exists('@(IntermediateAssembly)')">
+                       <Output TaskParameter="Include" ItemName="FileWrites"/>
+               </CreateItem>
+
+               <CreateItem Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
+                       Condition="Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')">
+                       <Output TaskParameter="Include" ItemName="FileWrites"/>
+               </CreateItem>
+       </Target>
+
+       <!-- Get the list of files written, for clean -->
+       <Target Name="_GetCleanFileWrites"
+               DependsOnTargets="_GetCompileOutputsForClean">
+               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
+                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
+               </ReadLinesFromFile>
+       </Target>
+
+       <Target Name="CleanReferencedProjects"
+               DependsOnTargets="AssignProjectConfigurations">
+
+               <!-- If building from .sln.proj or from IDE, clean will get handled by them,
+                    else we are building a project directly, from the command line, so
+                    clean the referenced projects -->
+               <MSBuild Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="Clean"
+                       Condition=" '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' and '@(ProjectReferenceWithConfigurationExistent)' != ''" />
+
+       </Target>
+
+       <Target Name="Clean" DependsOnTargets="$(CleanDependsOn)"/>
+
+       <!-- Override in project to run before/after clean tasks -->
+       <Target Name="BeforeClean" />
+       <Target Name="AfterClean" />
+
+       <Target Name="CoreClean" DependsOnTargets="_GetCleanFileWrites">
+               <Delete Files="@(PreviousFileWrites);@(FileWrites)" TreatErrorsAsWarnings="true"/>
+
+               <!-- all previous files written for this platform/config have been deleted,
+                    we can safely remove the file list now -->
+               <Delete Files="$(IntermediateOutputPath)$(CleanFile)" TreatErrorsAsWarnings="true" />
+       </Target>
+
+</Project>
diff --git a/mcs/tools/xbuild/xbuild/3.5/Microsoft.Common.tasks b/mcs/tools/xbuild/xbuild/3.5/Microsoft.Common.tasks
new file mode 100644 (file)
index 0000000..ed726aa
--- /dev/null
@@ -0,0 +1,33 @@
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" >
+       <UsingTask TaskName="Microsoft.Build.Tasks.AL"                  AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignTargetPath"    AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignCulture"       AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignProjectConfiguration"  AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CallTarget"          AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CombinePath"         AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Copy"                AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CreateItem"          AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CreateProperty"      AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Csc"                 AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Delete"              AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Error"               AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Exec"                AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.FindAppConfigFile"   AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.FindUnderPath"       AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GenerateResource"    AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkPath"    AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkSdkPath" AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.LC"                  AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.MakeDir"             AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Message"             AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.MSBuild"             AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.ReadLinesFromFile"   AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDir"           AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDuplicates"            AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.ResolveAssemblyReference"            AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.SignFile"            AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Touch"               AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Vbc"                 AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Warning"             AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.WriteLinesToFile"    AssemblyName="Microsoft.Build.Tasks.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+</Project>
diff --git a/mcs/tools/xbuild/xbuild/4.0/Microsoft.Common.targets b/mcs/tools/xbuild/xbuild/4.0/Microsoft.Common.targets
new file mode 100644 (file)
index 0000000..46448f2
--- /dev/null
@@ -0,0 +1,735 @@
+<Project DefaultTargets="Build" InitialTargets="_ValidateEssentialProperties" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+
+       <PropertyGroup>
+               <TargetExt Condition="'$(OutputType)' == 'Winexe'">.exe</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Exe'">.exe</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Library'">.dll</TargetExt>
+               <TargetExt Condition="'$(OutputType)' == 'Netmodule'">.netmodule</TargetExt>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <ProjectDir Condition="'$(ProjectDir)' == ''">$(MSBuildProjectDirectory)\</ProjectDir>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <AssemblyName Condition="'$(AssemblyName)' == ''">$(RootNamespace)</AssemblyName>
+               <OutputPath Condition="'$(OutputPath)' != '' and !HasTrailingSlash('$(OutputPath)')">$(OutputPath)\</OutputPath> 
+               <OutputPath Condition=" '$(Platform)'=='' and '$(Configuration)'=='' and '$(OutputPath)'=='' ">bin\Debug\</OutputPath>
+               <WarningLevel Condition="'$(WarningLevel)' == ''" >2</WarningLevel>
+               <TargetFrameworkVersion Condition="'$(TargetFrameworkVersion)' == ''">v2.0</TargetFrameworkVersion>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <OutDir Condition="'$(OutDir)' == ''">$(OutputPath)</OutDir>
+               <OutDir Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')">$(OutDir)\</OutDir>
+
+               <_OriginalConfiguration>$(Configuration)</_OriginalConfiguration>
+               <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+               <ConfigurationName Condition="'$(ConfigurationName)' == ''">$(Configuration)</ConfigurationName>
+
+               <_OriginalPlatform>$(Platform)</_OriginalPlatform>
+               <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+               <PlatformName Condition="'$(PlatformName)' == ''">$(Platform)</PlatformName>
+       </PropertyGroup>
+
+       <PropertyGroup>
+               <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)' == ''">obj\</BaseIntermediateOutputPath>
+               <CleanFile Condition="'$(CleanFile)'==''">$(MSBuildProjectFile).FilesWrittenAbsolute.txt</CleanFile>
+       </PropertyGroup>
+
+       <PropertyGroup Condition="'$(IntermediateOutputPath)' == ''">
+               <IntermediateOutputPath Condition=" '$(PlatformName)' == 'AnyCPU'">$(BaseIntermediateOutputPath)$(Configuration)\</IntermediateOutputPath>
+               <IntermediateOutputPath Condition=" '$(PlatformName)' != 'AnyCPU'">$(BaseIntermediateOutputPath)$(PlatformName)\$(Configuration)\</IntermediateOutputPath>
+       </PropertyGroup>
+
+       <ItemGroup>
+               <IntermediateAssembly Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt)" />
+
+               <!-- creating this as a item to use FullPath on it, to build TargetPath -->
+               <_OutDirItem Include="$(OutDir)"/>
+       </ItemGroup>
+
+       <PropertyGroup>
+               <TargetName Condition="'$(TargetName)' == '' ">$(AssemblyName)</TargetName>
+               <TargetFileName Condition="'$(TargetFileName)' == '' ">$(TargetName)$(TargetExt)</TargetFileName>
+               <TargetPath>@(_OutDirItem->'%(FullPath)\$(TargetFileName)')</TargetPath>
+
+               <KeyOriginatorFile Condition=" '$(SignAssembly)' == 'true' ">$(AssemblyOriginatorKeyFile)</KeyOriginatorFile>
+       </PropertyGroup>
+
+       <Target Name="_ValidateEssentialProperties">
+               <Error Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' != 'true'"
+                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
+
+               <Warning Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' == 'true'"
+                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
+
+               <!-- If OutDir is specified via the command line, then the earlier check
+                    to add a trailing slash won't have any affect, so error here. -->
+               <Error
+                       Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')"
+                       Text="OutDir property must end with a slash."/>
+       </Target>
+
+       <Target Name="PrepareForBuild">
+               <Message Importance="High" Text="Configuration: $(Configuration) Platform: $(Platform)"/>
+
+               <!-- Look for app.config, if $(AppConfig) is specified, then use that. Else look in
+                    @(None) and @(Content) -->
+               <CreateItem Include="$(AppConfig)" Condition="'$(AppConfig)' != ''"
+                       AdditionalMetadata="TargetPath=$(TargetFileName).config">
+                       <Output TaskParameter="Include" ItemName="AppConfigWithTargetPath" />
+               </CreateItem>
+
+               <FindAppConfigFile PrimaryList="@(None)" SecondaryList="@(Content)" TargetPath="$(TargetFileName).config"
+                       Condition="'$(AppConfig)' == ''">
+                       <Output TaskParameter="AppConfigFile" ItemName="AppConfigWithTargetPath"/>
+               </FindAppConfigFile>
+
+               <MakeDir 
+                       Directories="$(OutDir);$(IntermediateOutputPath)"
+               />
+       </Target>
+
+       <Target Name="GetFrameworkPaths">
+               <GetFrameworkPath>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v4.0'"
+                               TaskParameter="FrameworkVersion40Path"
+                               ItemName="TargetFrameworkDirectories"/>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.5'"
+                               TaskParameter="FrameworkVersion35Path"
+                               ItemName="TargetFrameworkDirectories"/>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'" 
+                               TaskParameter="FrameworkVersion30Path"
+                               ItemName="TargetFrameworkDirectories"/>
+                       <Output Condition="'$(TargetFrameworkVersion)' == 'v2.0' or '$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'" 
+                               TaskParameter="FrameworkVersion20Path"
+                               ItemName="TargetFrameworkDirectories"/>
+               </GetFrameworkPath>
+               <Warning Text="TargetFrameworkVersion '$(TargetFrameworkVersion)' not supported by this toolset (ToolsVersion: $(MSBuildToolsVersion))."
+                       Condition="'$(TargetFrameworkVersion)' != 'v4.0' and '$(TargetFrameworkVersion)' != 'v3.5' and '$(TargetFrameworkVersion)' != 'v3.0' and '$(TargetFrameworkVersion)' != 'v2.0'"/>
+       </Target>
+
+       <PropertyGroup>
+               <AllowedReferenceAssemblyFileExtensions Condition=" '$(AllowedReferenceAssemblyFileExtensions)' == '' ">
+                       .exe;
+                       .dll
+               </AllowedReferenceAssemblyFileExtensions>
+
+               <AllowedReferenceRelatedFileExtensions Condition=" '$(AllowedReferenceRelatedFileExtensions)' == '' ">
+                       .mdb
+               </AllowedReferenceRelatedFileExtensions>
+
+               <AssemblySearchPaths Condition="'$(AssemblySearchPaths)' == ''">
+                       {CandidateAssemblyFiles};
+                       {HintPathFromItem};
+                       {TargetFrameworkDirectory};
+                       {PkgConfig};
+                       {GAC};
+                       {RawFileName};
+                       $(OutDir)
+               </AssemblySearchPaths>
+
+               <ResolveReferencesDependsOn>
+                       BeforeResolveReferences;
+                       ResolveProjectReferences;
+                       ResolveAssemblyReferences;
+                       AfterResolveReferences
+               </ResolveReferencesDependsOn>
+       </PropertyGroup>
+
+       <Target Name="ResolveReferences" DependsOnTargets="$(ResolveReferencesDependsOn)"/>
+
+       <Target Name="BeforeResolveReferences" />
+       <Target Name="AfterResolveReferences" />
+
+       <Target Name="ResolveAssemblyReferences">
+               <ResolveAssemblyReference
+                       Assemblies="@(Reference)"
+                       AssemblyFiles="@(ChildProjectReferences)"
+                       SearchPaths="$(AssemblySearchPaths)"
+                       CandidateAssemblyFiles="@(Content);@(None)"
+                       TargetFrameworkDirectories="@(TargetFrameworkDirectories)"
+                       AllowedAssemblyExtensions="$(AllowedReferenceAssemblyFileExtensions)"
+                       AllowedRelatedFileExtensions="$(AllowedReferenceRelatedFileExtensions)"
+                       FindDependencies="true"
+                       FindSatellites="true"
+                       FindRelatedFiles="true"
+               >
+                       <Output TaskParameter="ResolvedFiles" ItemName="ResolvedFiles"/>
+                       <Output TaskParameter="ResolvedFiles" ItemName="ReferencePath"/>
+                       <Output TaskParameter="ResolvedDependencyFiles" ItemName="_ResolvedDependencyFiles"/>
+                       <Output TaskParameter="RelatedFiles" ItemName="_ReferenceRelatedPaths"/>
+                       <Output TaskParameter="SatelliteFiles" ItemName="ReferenceSatellitePaths"/>
+                       <Output TaskParameter="CopyLocalFiles" ItemName="ReferenceCopyLocalPaths"/>
+               </ResolveAssemblyReference>
+       </Target>
+
+       <Target
+               Name="AssignProjectConfigurations"
+               Condition="'@(ProjectReference)' != ''">
+
+               <!-- assign configs if building a solution file -->
+               <AssignProjectConfiguration
+                       ProjectReferences = "@(ProjectReference)"
+                       SolutionConfigurationContents = "$(CurrentSolutionConfigurationContents)"
+                       Condition="'$(BuildingSolutionFile)' == 'true'">
+
+                       <Output TaskParameter = "AssignedProjects" ItemName = "ProjectReferenceWithConfiguration"/>
+               </AssignProjectConfiguration>
+
+               <!-- Else, just -->
+               <CreateItem Include="@(ProjectReference)" Condition="'$(BuildingSolutionFile)' != 'true'">
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfiguration"/>
+               </CreateItem>
+
+       </Target>
+
+       <!-- Split projects into 2 lists
+               ProjectReferenceWithConfigurationExistent: Projects existent on disk
+               ProjectReferenceWithConfigurationNonExistent: Projects non-existent on disk -->
+
+       <Target Name="SplitProjectReferencesByExistent"
+               DependsOnTargets="AssignProjectConfigurations">
+
+               <CreateItem Include="@(ProjectReferenceWithConfiguration)" Condition="'@(ProjectReferenceWithConfiguration)' != ''">
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationExistent"
+                               Condition="Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
+
+                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationNonExistent"
+                               Condition="!Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
+               </CreateItem>
+       </Target>
+
+       <Target
+               Name="ResolveProjectReferences"
+               DependsOnTargets="SplitProjectReferencesByExistent"
+       >
+               <!-- If building from a .sln.proj or from IDE, then referenced projects have already
+                    been built, so just get the target paths -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="GetTargetPath"
+                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and ('$(BuildingSolutionFile)' == 'true' or '$(BuildingInsideVisualStudio)' == 'true')">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
+               </MSBuild>
+
+               <!-- Building a project directly, build the referenced the projects also -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' ">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
+               </MSBuild>
+
+               <Warning Text="Referenced Project %(ProjectReferenceWithConfigurationNonExistent.Identity) not found, ignoring."
+                        Condition="'@(ProjectReferenceWithConfigurationNonExistent)' != ''"/>
+       </Target>
+
+       <Target Name = "CopyFilesMarkedCopyLocal">
+               <Copy
+                       SourceFiles="@(ReferenceCopyLocalPaths)"
+                       DestinationFiles="@(ReferenceCopyLocalPaths->'$(OutDir)%(DestinationSubDirectory)%(Filename)%(Extension)')"
+                       SkipUnchangedFiles="true">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
+               </Copy>
+       </Target>
+
+<!--
+       Not needed at the moment
+       <Target Name="_ComputeNonExistentFileProperty" Condition='false'>
+               <CreateProperty Value="__NonExistentSubDir__\__NonExistentFile__">
+                       <Output TaskParameter="Value" PropertyName="NonExistentFile"/>
+               </CreateProperty>
+       </Target>
+-->
+
+       <PropertyGroup>
+               <BuildDependsOn>
+                       BeforeBuild;
+                       CoreBuild;
+                       AfterBuild
+               </BuildDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BeforeBuild"/>
+       <Target Name="AfterBuild"/>
+
+       <Target Name="Build" DependsOnTargets="$(BuildDependsOn)" Outputs="$(TargetPath)"/>
+
+       <PropertyGroup>
+               <CoreBuildDependsOn>
+                       PrepareForBuild;
+                       GetFrameworkPaths;
+                       PreBuildEvent;
+                       ResolveReferences;
+                       CopyFilesMarkedCopyLocal;
+                       PrepareResources;
+                       Compile;
+                       PrepareForRun;
+                       DeployOutputFiles;
+                       _RecordCleanFile;
+                       PostBuildEvent
+               </CoreBuildDependsOn>
+       </PropertyGroup>
+
+       <Target
+               Name="CoreBuild"
+               DependsOnTargets="$(CoreBuildDependsOn)"
+               Outputs="$(OutDir)$(AssemblyName)$(TargetExt)">
+
+               <OnError ExecuteTargets="_TimestampAfterCompile;PostBuildEvent"
+                       Condition=" '$(RunPostBuildEvent)' == 'Always' or '$(RunPostBuildEvent)' == 'OnOutputUpdated'"/>
+
+               <OnError ExecuteTargets="_RecordCleanFile" />
+       </Target>
+
+       <PropertyGroup>
+               <CompileDependsOn>
+                       ResolveReferences;
+                       BeforeCompile;
+                       _TimestampBeforeCompile;
+                       CoreCompile;
+                       _TimestampAfterCompile;
+                       AfterCompile
+               </CompileDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BeforeCompile" />
+       <Target Name="AfterCompile" />
+
+       <Target Name="Compile" DependsOnTargets="$(CompileDependsOn)"/>
+
+       <PropertyGroup>
+               <PrepareForRunDependsOn>
+                       DeployOutputFiles
+               </PrepareForRunDependsOn>
+       </PropertyGroup>
+       <Target Name="PrepareForRun" DependsOnTargets="$(PrepareForRunDependsOn)"/>
+
+       <PropertyGroup>
+               <PrepareResourcesDependsOn>
+                       AssignTargetPaths;
+                       SplitResourcesByCulture;
+                       CreateManifestResourceNames;
+                       CopyNonResxEmbeddedResources;
+                       GenerateResources;
+                       GenerateSatelliteAssemblies;
+                       CompileLicxFiles
+               </PrepareResourcesDependsOn>
+       </PropertyGroup>
+       <Target Name="PrepareResources" DependsOnTargets="$(PrepareResourcesDependsOn)" />
+
+       <Target Name="SplitResourcesByCulture" DependsOnTargets="AssignTargetPaths">
+               <!-- Extract .licx files into @(LicxFiles) -->
+               <CreateItem Include="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' == '.licx'">
+                       <Output TaskParameter="Include" ItemName="LicxFiles"/>
+               </CreateItem>
+
+               <!-- Split *remaining* resource files into various groups.. -->
+               <AssignCulture Files="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' != '.licx'">
+                       <Output TaskParameter="AssignedFilesWithNoCulture" ItemName="ResourcesWithNoCulture"/>
+                       <Output TaskParameter="AssignedFilesWithCulture" ItemName="ResourcesWithCulture"/>
+               </AssignCulture>
+
+               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' == '.resx'">
+                       <Output TaskParameter="Include" ItemName="ResxWithNoCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' != '.resx'">
+                       <Output TaskParameter="Include" ItemName="NonResxWithNoCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' == '.resx'">
+                       <Output TaskParameter="Include" ItemName="ResxWithCulture"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' != '.resx'">
+                       <Output TaskParameter="Include" ItemName="NonResxWithCulture"/>
+               </CreateItem>
+       </Target>
+
+       <!-- Copy non-resx resources to their manifest resource names, this is what the compiler expects -->
+       <Target Name = "CopyNonResxEmbeddedResources"
+               Condition = "'@(NonResxWithCulture)' != '' or '@(NonResxWithNoCulture)' != '' or '@(ManifestNonResxWithCulture)' != '' or '@(ManifestNonResxWithNoCulture)' != ''">
+
+               <MakeDir Directories="$(IntermediateOutputPath)%(ManifestNonResxWithCulture.Culture)"/>
+               <Copy SourceFiles = "@(NonResxWithCulture)"
+                       DestinationFiles = "@(ManifestNonResxWithCulture->'$(IntermediateOutputPath)%(Identity)')"
+                       SkipUnchangedFiles="true">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithCultureOnDisk"/>
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
+               </Copy>
+
+               <Copy SourceFiles = "@(NonResxWithNoCulture)"
+                       DestinationFiles = "@(ManifestNonResxWithNoCulture->'$(IntermediateOutputPath)%(Identity)')"
+                       SkipUnchangedFiles="true">
+                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithNoCultureOnDisk"/>
+                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name = "GenerateResources">
+               <GenerateResource
+                       Sources = "@(ResxWithNoCulture)"
+                       UseSourcePath = "true"
+                       OutputResources = "@(ManifestResourceWithNoCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
+                       Condition = "'@(ResxWithNoCulture)' != '' ">
+
+                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithNoCulture"/>
+                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
+               </GenerateResource>
+
+               <GenerateResource
+                       Sources = "@(ResxWithCulture)"
+                       UseSourcePath = "true"
+                       OutputResources = "@(ManifestResourceWithCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
+                       Condition = "'@(ResxWithCulture)' != '' ">
+
+                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithCulture"/>
+                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
+               </GenerateResource>
+       </Target>
+
+       <Target Name="GenerateSatelliteAssemblies"
+               Inputs="@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
+               Outputs="$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
+               <!-- @(NonResxWithCulture) - rename files to ManifestNon.. and then use for AL -->
+               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestResourceWithCulture.Culture)" Condition = "'@(ManifestResourceWithCulture)' != ''" />
+               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestNonResxWithCultureOnDisk.Culture)" Condition = "'@(ManifestNonResxWithCultureOnDisk)' != ''" />
+
+               <AL
+                       Culture = "%(Culture)"
+                       DelaySign="$(DelaySign)"
+                       EmbedResources = "@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
+                       KeyFile="$(KeyOriginatorFile)"
+                       ToolExe="$(AlToolExe)"
+                       ToolPath="$(AlToolPath)"
+                       OutputAssembly = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
+                       <Output TaskParameter="OutputAssembly" ItemName="FileWrites"/>
+               </AL>
+
+
+               <CreateItem
+                       Include = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll"
+                       AdditionalMetadata = "Culture=%(Culture)"
+                       Condition = "'@(ManifestResourceWithCulture)' != '' or '@(ManifestNonResxWithCultureOnDisk)' != ''">
+                       <Output TaskParameter = "Include" ItemName = "IntermediateSatelliteAssemblies" />
+               </CreateItem>
+       </Target>
+
+       <PropertyGroup>
+               <CompileLicxFilesDependsOn></CompileLicxFilesDependsOn>
+       </PropertyGroup>
+
+       <Target Name = "CompileLicxFiles"
+               Condition = "'@(LicxFiles)' != ''"
+               DependsOnTargets = "$(CompileLicxFilesDependsOn)"
+               Outputs = "$(IntermediateOutputPath)$(TargetFileName).licenses">
+               <LC
+                       Sources = "@(LicxFiles)"
+                       LicenseTarget = "$(TargetFileName)"
+                       OutputDirectory = "$(IntermediateOutputPath)"
+                       OutputLicense = "$(IntermediateOutputPath)$(TargetFileName).licenses"
+                       ReferencedAssemblies = "@(ReferencePath);@(_ResolvedDependencyFiles)"
+                       ToolPath = "$(LCToolPath)"
+                       ToolExe = "$(LCToolExe)">
+
+                       <Output TaskParameter="OutputLicense" ItemName="CompiledLicenseFile"/>
+                       <Output TaskParameter="OutputLicense" ItemName="FileWrites"/>
+               </LC>
+       </Target>
+
+       <!-- Assign target paths to files that will need to be copied along with the project -->
+       <Target Name = "AssignTargetPaths">
+               <AssignTargetPath Files="@(None)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="NoneWithTargetPath"/>
+               </AssignTargetPath>
+
+               <AssignTargetPath Files="@(Content)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="ContentWithTargetPath"/>
+               </AssignTargetPath>
+
+               <AssignTargetPath Files="@(EmbeddedResource)" RootFolder="$(MSBuildProjectDirectory)">
+                       <Output TaskParameter="AssignedFiles" ItemName="EmbeddedResourceWithTargetPath"/>
+               </AssignTargetPath>
+       </Target>
+
+       <Target Name="DeployOutputFiles"
+               DependsOnTargets="PrepareResources;CoreCompile;_CopyDeployFilesToOutputDirectory;_CopyAppConfigFile">
+
+               <Copy 
+                       SourceFiles="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
+                       Condition="'$(OutDir)' != '' and Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')"
+                       DestinationFolder="$(OutDir)"
+                       SkipUnchangedFiles="true" >
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+
+               <Copy SourceFiles="@(IntermediateAssembly)" Condition="'$(OutDir)' != '' and Exists ('@(IntermediateAssembly)')" DestinationFolder="$(OutDir)" SkipUnchangedFiles="true">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+
+               <Copy
+                       SourceFiles = "@(IntermediateSatelliteAssemblies)"
+                       DestinationFiles = "@(IntermediateSatelliteAssemblies->'$(OutDir)\%(Culture)\$(AssemblyName).resources.dll')"
+                       Condition = "'@(IntermediateSatelliteAssemblies)' != ''"
+                       SkipUnchangedFiles="true">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name="_CopyDeployFilesToOutputDirectory"
+               DependsOnTargets="GetCopyToOutputDirectoryItems;
+                       _CopyDeployFilesToOutputDirectoryAlways;
+                       _CopyDeployFilesToOutputDirectoryPreserveNewest"/>
+
+       <Target Name="_CopyDeployFilesToOutputDirectoryPreserveNewest"
+               Condition="'@(ItemsToCopyToOutputDirectoryPreserveNewest)' != ''"
+               Inputs="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
+               Outputs="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')">
+
+               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
+                       DestinationFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <!-- Copy if newer -->
+       <Target Name="_CopyDeployFilesToOutputDirectoryAlways"
+               Condition="'@(ItemsToCopyToOutputDirectoryAlways)' != ''">
+
+               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryAlways)"
+                       DestinationFiles="@(ItemsToCopyToOutputDirectoryAlways->'$(OutDir)%(TargetPath)')">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+
+       <Target Name="_CopyAppConfigFile" Condition="'@(AppConfigWithTargetPath)' != ''"
+               Inputs="@(AppConfigWithTargetPath)"
+               Outputs="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
+
+               <Copy SourceFiles="@(AppConfigWithTargetPath)"
+                       DestinationFiles="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
+                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
+               </Copy>
+       </Target>
+
+       <Target Name="GetTargetPath" Outputs="$(TargetPath)"/>
+
+       <Target Name="GetCopyToOutputDirectoryItems"
+               Outputs="@(AllItemsFullPathWithTargetPath)"
+               DependsOnTargets="AssignTargetPaths;SplitProjectReferencesByExistent">
+
+               <!-- FIXME: handle .vcproj
+                    FIXME: Private ProjectReferences are honored only in 3.5
+               -->
+               <MSBuild
+                       Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="GetCopyToOutputDirectoryItems"
+                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '%(ProjectReferenceWithConfigurationExistent.Private)' != 'false'">
+
+                       <Output TaskParameter="TargetOutputs" ItemName="AllChildProjectItemsWithTargetPath"/>
+               </MSBuild>
+
+               <!-- Process items from child project. The outputs need to have full path
+                    as they'll be used from other projects -->
+
+               <CreateItem
+                       Include="@(AllChildProjectItemsWithTargetPath->'%(FullPath)')"
+                       Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+
+               </CreateItem>
+
+               <!-- Process _this_ project's items -->
+
+               <CreateItem
+                       Include="@(NoneWithTargetPath->'%(FullPath)')"
+                       Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(NoneWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+               <CreateItem
+                       Include="@(ContentWithTargetPath->'%(FullPath)')"
+                       Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(ContentWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+               <CreateItem
+                       Include="@(EmbeddedResourceWithTargetPath->'%(FullPath)')"
+                       Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
+                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
+                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
+                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
+                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
+               </CreateItem>
+
+       </Target>
+
+       <!-- Pre/Post BuildEvents -->
+       <PropertyGroup>
+               <PreBuildEventDependsOn />
+       </PropertyGroup>
+
+       <Target Name="PreBuildEvent"
+               Condition="'$(PreBuildEvent)' != ''"
+               DependsOnTargets="$(PreBuildEventDependsOn)">
+
+               <Exec WorkingDirectory="$(OutDir)" Command="$(PreBuildEvent)" />
+       </Target>
+
+       <!-- PostBuildEvent depends on $(RunPostBuildEvent)
+
+               Default: OnBuildSuccess
+               OnBuildSuccess: Run after a successful build
+               OnOutputUpdated: Run only if the output assembly got updates
+               Always: Run always
+       -->
+       <PropertyGroup>
+               <PostBuildEventDependsOn />
+       </PropertyGroup>
+
+       <!-- this gets invoked in two cases, from CoreBuildDependsOn, if the build completes
+            successfully, OR from OnError in CoreBuild, if the build failed and $(RunPostBuildEvent)
+            is 'Always' or 'OnOutputUpdated'. Invoke $(PostBuildEvent) if its either Empty (== OnBuildSuccess)
+            or OnBuildSuccess or Always OR (OnOutputUpdated and output assembly got updated) -->
+       <Target Name="PostBuildEvent"
+               Condition="'$(PostBuildEvent)' != '' and
+                       ('$(RunPostBuildEvent)' != 'OnOutputUpdated' or
+                         '$(_AssemblyModifiedTimeBeforeCompile)' != '$(_AssemblyModifiedTimeAfterCompile)')"
+               DependsOnTargets="$(PostBuildEventDependsOn)">
+
+               <Exec WorkingDirectory="$(OutDir)" Command="$(PostBuildEvent)" />
+       </Target>
+
+       <!-- Timestamp the output assemblies, required for PostBuildEvent -->
+       <Target Name="_TimestampBeforeCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
+               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
+                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeBeforeCompile" />
+               </CreateItem>
+       </Target>
+       <Target Name="_TimestampAfterCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
+               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
+                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeAfterCompile" />
+               </CreateItem>
+       </Target>
+
+       <!-- Rebuild -->
+       <PropertyGroup>
+               <RebuildDependsOn>
+                       BeforeRebuild;
+                       Clean;
+                       $(MSBuildProjectDefaultTargets);
+                       AfterRebuild;
+               </RebuildDependsOn>
+
+               <RebuildDependsOn Condition="'$(MSBuildProjectDefaultTargets)' == 'Rebuild'">
+                       BeforeRebuild;
+                       Clean;
+                       Build;
+                       AfterRebuild;
+               </RebuildDependsOn>
+       </PropertyGroup>
+
+       <Target Name="BeforeRebuild" />
+       <Target Name="AfterRebuild" />
+
+       <Target Name="Rebuild"
+               DependsOnTargets="$(RebuildDependsOn)"
+               Outputs="$(TargetPath)"/>
+
+       <!-- Clean -->
+       <Target Name="_RecordCleanFile"
+               DependsOnTargets="_GetCompileOutputsForClean">
+
+               <!-- add to list of previous writes for this platform/config -->
+
+               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
+                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
+               </ReadLinesFromFile>
+
+               <RemoveDuplicates Inputs="@(PreviousFileWrites);@(FileWrites->'%(FullPath)')">
+                       <Output TaskParameter="Filtered" ItemName="CombinedFileWrites"/>
+               </RemoveDuplicates>
+
+               <WriteLinesToFile
+                       File="$(IntermediateOutputPath)$(CleanFile)"
+                       Lines="@(CombinedFileWrites)"
+                       Overwrite="true"/>
+       </Target>
+
+       <PropertyGroup>
+               <CleanDependsOn>
+                       BeforeClean;
+                       CleanReferencedProjects;
+                       CoreClean;
+                       AfterClean
+               </CleanDependsOn>
+       </PropertyGroup>
+
+       <Target Name="_GetCompileOutputsForClean">
+               <!-- assembly and debug file in the *intermediate output path* -->
+               <CreateItem Include="@(IntermediateAssembly)" Condition="Exists('@(IntermediateAssembly)')">
+                       <Output TaskParameter="Include" ItemName="FileWrites"/>
+               </CreateItem>
+
+               <CreateItem Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
+                       Condition="Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')">
+                       <Output TaskParameter="Include" ItemName="FileWrites"/>
+               </CreateItem>
+       </Target>
+
+       <!-- Get the list of files written, for clean -->
+       <Target Name="_GetCleanFileWrites"
+               DependsOnTargets="_GetCompileOutputsForClean">
+               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
+                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
+               </ReadLinesFromFile>
+       </Target>
+
+       <Target Name="CleanReferencedProjects"
+               DependsOnTargets="AssignProjectConfigurations">
+
+               <!-- If building from .sln.proj or from IDE, clean will get handled by them,
+                    else we are building a project directly, from the command line, so
+                    clean the referenced projects -->
+               <MSBuild Projects="@(ProjectReferenceWithConfigurationExistent)"
+                       Targets="Clean"
+                       Condition=" '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' and '@(ProjectReferenceWithConfigurationExistent)' != ''" />
+
+       </Target>
+
+       <Target Name="Clean" DependsOnTargets="$(CleanDependsOn)"/>
+
+       <!-- Override in project to run before/after clean tasks -->
+       <Target Name="BeforeClean" />
+       <Target Name="AfterClean" />
+
+       <Target Name="CoreClean" DependsOnTargets="_GetCleanFileWrites">
+               <Delete Files="@(PreviousFileWrites);@(FileWrites)" TreatErrorsAsWarnings="true"/>
+
+               <!-- all previous files written for this platform/config have been deleted,
+                    we can safely remove the file list now -->
+               <Delete Files="$(IntermediateOutputPath)$(CleanFile)" TreatErrorsAsWarnings="true" />
+       </Target>
+
+</Project>
diff --git a/mcs/tools/xbuild/xbuild/4.0/Microsoft.Common.tasks b/mcs/tools/xbuild/xbuild/4.0/Microsoft.Common.tasks
new file mode 100644 (file)
index 0000000..4ace4fe
--- /dev/null
@@ -0,0 +1,33 @@
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" >
+       <UsingTask TaskName="Microsoft.Build.Tasks.AL"                  AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignTargetPath"    AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignCulture"       AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.AssignProjectConfiguration"  AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CallTarget"          AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CombinePath"         AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Copy"                AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CreateItem"          AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.CreateProperty"      AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Csc"                 AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Delete"              AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Error"               AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Exec"                AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.FindAppConfigFile"   AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.FindUnderPath"       AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GenerateResource"    AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkPath"    AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkSdkPath" AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.LC"                  AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.MakeDir"             AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Message"             AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.MSBuild"             AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.ReadLinesFromFile"   AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDir"           AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDuplicates"            AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.ResolveAssemblyReference"            AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.SignFile"            AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Touch"               AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Vbc"                 AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.Warning"             AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+       <UsingTask TaskName="Microsoft.Build.Tasks.WriteLinesToFile"    AssemblyName="Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
+</Project>
index 783cc74b2cb0da9fcdf46e545f3fe5a6bdc92d7b..96bd128f2292428df65588a50a3c545fc7ae3277 100644 (file)
@@ -12,6 +12,7 @@
 
        <PropertyGroup>
                <CreateManifestResourceNamesDependsOn></CreateManifestResourceNamesDependsOn>
+               <CoreCompileDependsOn></CoreCompileDependsOn>
        </PropertyGroup>
 
        <ItemGroup>
@@ -22,6 +23,7 @@
                Name="CoreCompile"
                Inputs="@(Compile)"
                Outputs="@(IntermediateAssembly)"
+               DependsOnTargets="$(CoreCompileDependsOn)"
        >
                <Csc
                        AdditionalLibPaths="$(AdditionalLibPaths)"
diff --git a/mcs/tools/xbuild/xbuild/Microsoft.Common.targets b/mcs/tools/xbuild/xbuild/Microsoft.Common.targets
deleted file mode 100644 (file)
index 9d0c322..0000000
+++ /dev/null
@@ -1,719 +0,0 @@
-<Project DefaultTargets="Build" InitialTargets="_ValidateEssentialProperties" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-
-       <PropertyGroup>
-               <TargetExt Condition="'$(OutputType)' == 'Winexe'">.exe</TargetExt>
-               <TargetExt Condition="'$(OutputType)' == 'Exe'">.exe</TargetExt>
-               <TargetExt Condition="'$(OutputType)' == 'Library'">.dll</TargetExt>
-               <TargetExt Condition="'$(OutputType)' == 'Netmodule'">.netmodule</TargetExt>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <ProjectDir Condition="'$(ProjectDir)' == ''">$(MSBuildProjectDirectory)\</ProjectDir>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <AssemblyName Condition="'$(AssemblyName)' == ''">$(RootNamespace)</AssemblyName>
-               <OutputPath Condition="'$(OutputPath)' != '' and !HasTrailingSlash('$(OutputPath)')">$(OutputPath)\</OutputPath> 
-               <OutputPath Condition=" '$(Platform)'=='' and '$(Configuration)'=='' and '$(OutputPath)'=='' ">bin\Debug\</OutputPath>
-               <WarningLevel Condition="'$(WarningLevel)' == ''" >2</WarningLevel>
-               <TargetFrameworkVersion Condition="'$(TargetFrameworkVersion)' == ''">v2.0</TargetFrameworkVersion>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <OutDir Condition="'$(OutDir)' == ''">$(OutputPath)</OutDir>
-               <OutDir Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')">$(OutDir)\</OutDir>
-
-               <_OriginalConfiguration>$(Configuration)</_OriginalConfiguration>
-               <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
-               <ConfigurationName Condition="'$(ConfigurationName)' == ''">$(Configuration)</ConfigurationName>
-
-               <_OriginalPlatform>$(Platform)</_OriginalPlatform>
-               <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
-               <PlatformName Condition="'$(PlatformName)' == ''">$(Platform)</PlatformName>
-       </PropertyGroup>
-
-       <PropertyGroup>
-               <BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)' == ''">obj\</BaseIntermediateOutputPath>
-               <CleanFile Condition="'$(CleanFile)'==''">$(MSBuildProjectFile).FilesWrittenAbsolute.txt</CleanFile>
-       </PropertyGroup>
-
-       <PropertyGroup Condition="'$(IntermediateOutputPath)' == ''">
-               <IntermediateOutputPath Condition=" '$(PlatformName)' == 'AnyCPU'">$(BaseIntermediateOutputPath)$(Configuration)\</IntermediateOutputPath>
-               <IntermediateOutputPath Condition=" '$(PlatformName)' != 'AnyCPU'">$(BaseIntermediateOutputPath)$(PlatformName)\$(Configuration)\</IntermediateOutputPath>
-       </PropertyGroup>
-
-       <ItemGroup>
-               <IntermediateAssembly Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt)" />
-
-               <!-- creating this as a item to use FullPath on it, to build TargetPath -->
-               <_OutDirItem Include="$(OutDir)"/>
-       </ItemGroup>
-
-       <PropertyGroup>
-               <TargetName Condition="'$(TargetName)' == '' ">$(AssemblyName)</TargetName>
-               <TargetFileName Condition="'$(TargetFileName)' == '' ">$(TargetName)$(TargetExt)</TargetFileName>
-               <TargetPath>@(_OutDirItem->'%(FullPath)\$(TargetFileName)')</TargetPath>
-
-               <KeyOriginatorFile Condition=" '$(SignAssembly)' == 'true' ">$(AssemblyOriginatorKeyFile)</KeyOriginatorFile>
-       </PropertyGroup>
-
-       <Target Name="_ValidateEssentialProperties">
-               <Error Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' != 'true'"
-                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
-
-               <Warning Condition=" '$(OutputPath)' == '' and '$(SkipInvalidConfigurations)' == 'true'"
-                       Text="'OutputPath' property is not set for this project. Usually this is caused by invalid Configuration/Platform combination. Original values: Configuration: $(_OriginalConfiguration) Platform: $(_OriginalPlatform)."/>
-
-               <!-- If OutDir is specified via the command line, then the earlier check
-                    to add a trailing slash won't have any affect, so error here. -->
-               <Error
-                       Condition="'$(OutDir)' != '' and !HasTrailingSlash('$(OutDir)')"
-                       Text="OutDir property must end with a slash."/>
-       </Target>
-
-       <Target Name="PrepareForBuild">
-               <Message Importance="High" Text="Configuration: $(Configuration) Platform: $(Platform)"/>
-
-               <!-- Look for app.config, if $(AppConfig) is specified, then use that. Else look in
-                    @(None) and @(Content) -->
-               <CreateItem Include="$(AppConfig)" Condition="'$(AppConfig)' != ''"
-                       AdditionalMetadata="TargetPath=$(TargetFileName).config">
-                       <Output TaskParameter="Include" ItemName="AppConfigWithTargetPath" />
-               </CreateItem>
-
-               <FindAppConfigFile PrimaryList="@(None)" SecondaryList="@(Content)" TargetPath="$(TargetFileName).config"
-                       Condition="'$(AppConfig)' == ''">
-                       <Output TaskParameter="AppConfigFile" ItemName="AppConfigWithTargetPath"/>
-               </FindAppConfigFile>
-
-               <MakeDir 
-                       Directories="$(OutDir);$(IntermediateOutputPath)"
-               />
-
-               <GetFrameworkPath>
-                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.5'"
-                               TaskParameter="FrameworkVersion35Path"
-                               ItemName="TargetFrameworkDirectories"/>
-                       <Output Condition="'$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'" 
-                               TaskParameter="FrameworkVersion30Path"
-                               ItemName="TargetFrameworkDirectories"/>
-                       <Output Condition="'$(TargetFrameworkVersion)' == 'v2.0' or '$(TargetFrameworkVersion)' == 'v3.0' or '$(TargetFrameworkVersion)' == 'v3.5'" 
-                               TaskParameter="FrameworkVersion20Path"
-                               ItemName="TargetFrameworkDirectories"/>
-               </GetFrameworkPath>
-       </Target>
-
-       <PropertyGroup>
-               <AllowedReferenceAssemblyFileExtensions Condition=" '$(AllowedReferenceAssemblyFileExtensions)' == '' ">
-                       .exe;
-                       .dll
-               </AllowedReferenceAssemblyFileExtensions>
-
-               <AllowedReferenceRelatedFileExtensions Condition=" '$(AllowedReferenceRelatedFileExtensions)' == '' ">
-                       .mdb
-               </AllowedReferenceRelatedFileExtensions>
-
-               <AssemblySearchPaths Condition="'$(AssemblySearchPaths)' == ''">
-                       {CandidateAssemblyFiles};
-                       {HintPathFromItem};
-                       {TargetFrameworkDirectory};
-                       {PkgConfig};
-                       {GAC};
-                       {RawFileName};
-                       $(OutDir)
-               </AssemblySearchPaths>
-
-               <ResolveReferencesDependsOn>
-                       BeforeResolveReferences;
-                       ResolveProjectReferences;
-                       ResolveAssemblyReferences;
-                       AfterResolveReferences
-               </ResolveReferencesDependsOn>
-       </PropertyGroup>
-
-       <Target Name="ResolveReferences" DependsOnTargets="$(ResolveReferencesDependsOn)"/>
-
-       <Target Name="BeforeResolveReferences" />
-       <Target Name="AfterResolveReferences" />
-
-       <Target Name="ResolveAssemblyReferences">
-               <ResolveAssemblyReference
-                       Assemblies="@(Reference)"
-                       AssemblyFiles="@(ChildProjectReferences)"
-                       SearchPaths="$(AssemblySearchPaths)"
-                       CandidateAssemblyFiles="@(Content);@(None)"
-                       TargetFrameworkDirectories="@(TargetFrameworkDirectories)"
-                       AllowedAssemblyExtensions="$(AllowedReferenceAssemblyFileExtensions)"
-                       AllowedRelatedFileExtensions="$(AllowedReferenceRelatedFileExtensions)"
-                       FindDependencies="true"
-                       FindSatellites="true"
-                       FindRelatedFiles="true"
-               >
-                       <Output TaskParameter="ResolvedFiles" ItemName="ResolvedFiles"/>
-                       <Output TaskParameter="ResolvedFiles" ItemName="ReferencePath"/>
-                       <Output TaskParameter="ResolvedDependencyFiles" ItemName="_ResolvedDependencyFiles"/>
-                       <Output TaskParameter="RelatedFiles" ItemName="_ReferenceRelatedPaths"/>
-                       <Output TaskParameter="SatelliteFiles" ItemName="ReferenceSatellitePaths"/>
-                       <Output TaskParameter="CopyLocalFiles" ItemName="ReferenceCopyLocalPaths"/>
-               </ResolveAssemblyReference>
-       </Target>
-
-       <Target
-               Name="AssignProjectConfigurations"
-               Condition="'@(ProjectReference)' != ''">
-
-               <!-- assign configs if building a solution file -->
-               <AssignProjectConfiguration
-                       ProjectReferences = "@(ProjectReference)"
-                       SolutionConfigurationContents = "$(CurrentSolutionConfigurationContents)"
-                       Condition="'$(BuildingSolutionFile)' == 'true'">
-
-                       <Output TaskParameter = "AssignedProjects" ItemName = "ProjectReferenceWithConfiguration"/>
-               </AssignProjectConfiguration>
-
-               <!-- Else, just -->
-               <CreateItem Include="@(ProjectReference)" Condition="'$(BuildingSolutionFile)' != 'true'">
-                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfiguration"/>
-               </CreateItem>
-
-       </Target>
-
-       <!-- Split projects into 2 lists
-               ProjectReferenceWithConfigurationExistent: Projects existent on disk
-               ProjectReferenceWithConfigurationNonExistent: Projects non-existent on disk -->
-
-       <Target Name="SplitProjectReferencesByExistent"
-               DependsOnTargets="AssignProjectConfigurations">
-
-               <CreateItem Include="@(ProjectReferenceWithConfiguration)" Condition="'@(ProjectReferenceWithConfiguration)' != ''">
-                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationExistent"
-                               Condition="Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
-
-                       <Output TaskParameter="Include" ItemName="ProjectReferenceWithConfigurationNonExistent"
-                               Condition="!Exists ('%(ProjectReferenceWithConfiguration.Identity)')"/>
-               </CreateItem>
-       </Target>
-
-       <Target
-               Name="ResolveProjectReferences"
-               DependsOnTargets="SplitProjectReferencesByExistent"
-       >
-               <!-- If building from a .sln.proj or from IDE, then referenced projects have already
-                    been built, so just get the target paths -->
-               <MSBuild
-                       Projects="@(ProjectReferenceWithConfigurationExistent)"
-                       Targets="GetTargetPath"
-                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
-                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and ('$(BuildingSolutionFile)' == 'true' or '$(BuildingInsideVisualStudio)' == 'true')">
-
-                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
-               </MSBuild>
-
-               <!-- Building a project directly, build the referenced the projects also -->
-               <MSBuild
-                       Projects="@(ProjectReferenceWithConfigurationExistent)"
-                       Properties="%(ProjectReferenceWithConfigurationExistent.SetConfiguration); %(ProjectReferenceWithConfigurationExistent.SetPlatform)"
-                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' ">
-
-                       <Output TaskParameter="TargetOutputs" ItemName="ChildProjectReferences" />
-               </MSBuild>
-
-               <Warning Text="Referenced Project %(ProjectReferenceWithConfigurationNonExistent.Identity) not found, ignoring."
-                        Condition="'@(ProjectReferenceWithConfigurationNonExistent)' != ''"/>
-       </Target>
-
-       <Target Name = "CopyFilesMarkedCopyLocal">
-               <Copy
-                       SourceFiles="@(ReferenceCopyLocalPaths)"
-                       DestinationFiles="@(ReferenceCopyLocalPaths->'$(OutDir)%(DestinationSubDirectory)%(Filename)%(Extension)')"
-                       SkipUnchangedFiles="true">
-                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
-               </Copy>
-       </Target>
-
-<!--
-       Not needed at the moment
-       <Target Name="_ComputeNonExistentFileProperty" Condition='false'>
-               <CreateProperty Value="__NonExistentSubDir__\__NonExistentFile__">
-                       <Output TaskParameter="Value" PropertyName="NonExistentFile"/>
-               </CreateProperty>
-       </Target>
--->
-
-       <PropertyGroup>
-               <BuildDependsOn>
-                       BeforeBuild;
-                       CoreBuild;
-                       AfterBuild
-               </BuildDependsOn>
-       </PropertyGroup>
-
-       <Target Name="BeforeBuild"/>
-       <Target Name="AfterBuild"/>
-
-       <Target Name="Build" DependsOnTargets="$(BuildDependsOn)" Outputs="$(TargetPath)"/>
-
-       <PropertyGroup>
-               <CoreBuildDependsOn>
-                       PrepareForBuild;
-                       PreBuildEvent;
-                       ResolveReferences;
-                       CopyFilesMarkedCopyLocal;
-                       BuildResources;
-                       CompileLicxFiles;
-                       Compile;
-                       PrepareForRun;
-                       DeployOutputFiles;
-                       _RecordCleanFile;
-                       PostBuildEvent
-               </CoreBuildDependsOn>
-       </PropertyGroup>
-
-       <Target
-               Name="CoreBuild"
-               DependsOnTargets="$(CoreBuildDependsOn)"
-               Outputs="$(OutDir)$(AssemblyName)$(TargetExt)">
-
-               <OnError ExecuteTargets="_TimestampAfterCompile;PostBuildEvent"
-                       Condition=" '$(RunPostBuildEvent)' == 'Always' or '$(RunPostBuildEvent)' == 'OnOutputUpdated'"/>
-
-               <OnError ExecuteTargets="_RecordCleanFile" />
-       </Target>
-
-       <PropertyGroup>
-               <CompileDependsOn>
-                       ResolveReferences;
-                       BeforeCompile;
-                       _TimestampBeforeCompile;
-                       CoreCompile;
-                       _TimestampAfterCompile;
-                       AfterCompile
-               </CompileDependsOn>
-       </PropertyGroup>
-
-       <Target Name="BeforeCompile" />
-       <Target Name="AfterCompile" />
-
-       <Target Name="Compile" DependsOnTargets="$(CompileDependsOn)"/>
-
-       <PropertyGroup>
-               <PrepareForRunDependsOn>
-                       DeployOutputFiles
-               </PrepareForRunDependsOn>
-       </PropertyGroup>
-       <Target Name="PrepareForRun" DependsOnTargets="$(PrepareForRunDependsOn)"/>
-
-       <Target Name="BuildResources"
-               DependsOnTargets="AssignTargetPaths;SplitResourcesByCulture;CreateManifestResourceNames;CopyNonResxEmbeddedResources;GenerateResources;GenerateSatelliteAssemblies">
-       </Target>
-
-       <Target Name="SplitResourcesByCulture" DependsOnTargets="AssignTargetPaths">
-               <!-- Extract .licx files into @(LicxFiles) -->
-               <CreateItem Include="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' == '.licx'">
-                       <Output TaskParameter="Include" ItemName="LicxFiles"/>
-               </CreateItem>
-
-               <!-- Split *remaining* resource files into various groups.. -->
-               <AssignCulture Files="@(EmbeddedResourceWithTargetPath)" Condition="'%(Extension)' != '.licx'">
-                       <Output TaskParameter="AssignedFilesWithNoCulture" ItemName="ResourcesWithNoCulture"/>
-                       <Output TaskParameter="AssignedFilesWithCulture" ItemName="ResourcesWithCulture"/>
-               </AssignCulture>
-
-               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' == '.resx'">
-                       <Output TaskParameter="Include" ItemName="ResxWithNoCulture"/>
-               </CreateItem>
-
-               <CreateItem Include="@(ResourcesWithNoCulture)" Condition="'%(Extension)' != '.resx'">
-                       <Output TaskParameter="Include" ItemName="NonResxWithNoCulture"/>
-               </CreateItem>
-
-               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' == '.resx'">
-                       <Output TaskParameter="Include" ItemName="ResxWithCulture"/>
-               </CreateItem>
-
-               <CreateItem Include="@(ResourcesWithCulture)" Condition="'%(Extension)' != '.resx'">
-                       <Output TaskParameter="Include" ItemName="NonResxWithCulture"/>
-               </CreateItem>
-       </Target>
-
-       <!-- Copy non-resx resources to their manifest resource names, this is what the compiler expects -->
-       <Target Name = "CopyNonResxEmbeddedResources"
-               Condition = "'@(NonResxWithCulture)' != '' or '@(NonResxWithNoCulture)' != '' or '@(ManifestNonResxWithCulture)' != '' or '@(ManifestNonResxWithNoCulture)' != ''">
-
-               <MakeDir Directories="$(IntermediateOutputPath)%(ManifestNonResxWithCulture.Culture)"/>
-               <Copy SourceFiles = "@(NonResxWithCulture)"
-                       DestinationFiles = "@(ManifestNonResxWithCulture->'$(IntermediateOutputPath)%(Identity)')"
-                       SkipUnchangedFiles="true">
-                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithCultureOnDisk"/>
-                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
-               </Copy>
-
-               <Copy SourceFiles = "@(NonResxWithNoCulture)"
-                       DestinationFiles = "@(ManifestNonResxWithNoCulture->'$(IntermediateOutputPath)%(Identity)')"
-                       SkipUnchangedFiles="true">
-                       <Output TaskParameter = "DestinationFiles" ItemName = "ManifestNonResxWithNoCultureOnDisk"/>
-                       <Output TaskParameter = "DestinationFiles" ItemName = "FileWrites"/>
-               </Copy>
-       </Target>
-
-       <Target Name = "GenerateResources">
-               <GenerateResource
-                       Sources = "@(ResxWithNoCulture)"
-                       UseSourcePath = "true"
-                       OutputResources = "@(ManifestResourceWithNoCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
-                       Condition = "'@(ResxWithNoCulture)' != '' ">
-
-                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithNoCulture"/>
-                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
-               </GenerateResource>
-
-               <GenerateResource
-                       Sources = "@(ResxWithCulture)"
-                       UseSourcePath = "true"
-                       OutputResources = "@(ManifestResourceWithCultureName->'$(IntermediateOutputPath)%(Identity).resources')"
-                       Condition = "'@(ResxWithCulture)' != '' ">
-
-                       <Output TaskParameter = "OutputResources" ItemName = "ManifestResourceWithCulture"/>
-                       <Output TaskParameter = "FilesWritten" ItemName = "FileWrites"/>
-               </GenerateResource>
-       </Target>
-
-       <Target Name="GenerateSatelliteAssemblies"
-               Inputs="@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
-               Outputs="$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
-               <!-- @(NonResxWithCulture) - rename files to ManifestNon.. and then use for AL -->
-               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestResourceWithCulture.Culture)" Condition = "'@(ManifestResourceWithCulture)' != ''" />
-               <MakeDir Directories = "$(IntermediateOutputPath)%(ManifestNonResxWithCultureOnDisk.Culture)" Condition = "'@(ManifestNonResxWithCultureOnDisk)' != ''" />
-
-               <AL
-                       Culture = "%(Culture)"
-                       DelaySign="$(DelaySign)"
-                       EmbedResources = "@(ManifestResourceWithCulture);@(ManifestNonResxWithCultureOnDisk)"
-                       KeyFile="$(KeyOriginatorFile)"
-                       ToolExe="$(AlToolExe)"
-                       ToolPath="$(AlToolPath)"
-                       OutputAssembly = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll" >
-                       <Output TaskParameter="OutputAssembly" ItemName="FileWrites"/>
-               </AL>
-
-
-               <CreateItem
-                       Include = "$(IntermediateOutputPath)%(Culture)\$(AssemblyName).resources.dll"
-                       AdditionalMetadata = "Culture=%(Culture)"
-                       Condition = "'@(ManifestResourceWithCulture)' != '' or '@(ManifestNonResxWithCultureOnDisk)' != ''">
-                       <Output TaskParameter = "Include" ItemName = "IntermediateSatelliteAssemblies" />
-               </CreateItem>
-       </Target>
-
-       <PropertyGroup>
-               <CompileLicxFilesDependsOn></CompileLicxFilesDependsOn>
-       </PropertyGroup>
-
-       <Target Name = "CompileLicxFiles"
-               Condition = "'@(LicxFiles)' != ''"
-               DependsOnTargets = "$(CompileLicxFilesDependsOn)"
-               Outputs = "$(IntermediateOutputPath)$(TargetFileName).licenses">
-               <LC
-                       Sources = "@(LicxFiles)"
-                       LicenseTarget = "$(TargetFileName)"
-                       OutputDirectory = "$(IntermediateOutputPath)"
-                       OutputLicense = "$(IntermediateOutputPath)$(TargetFileName).licenses"
-                       ReferencedAssemblies = "@(ReferencePath);@(_ResolvedDependencyFiles)"
-                       ToolPath = "$(LCToolPath)"
-                       ToolExe = "$(LCToolExe)">
-
-                       <Output TaskParameter="OutputLicense" ItemName="CompiledLicenseFile"/>
-                       <Output TaskParameter="OutputLicense" ItemName="FileWrites"/>
-               </LC>
-       </Target>
-
-       <!-- Assign target paths to files that will need to be copied along with the project -->
-       <Target Name = "AssignTargetPaths">
-               <AssignTargetPath Files="@(None)" RootFolder="$(MSBuildProjectDirectory)">
-                       <Output TaskParameter="AssignedFiles" ItemName="NoneWithTargetPath"/>
-               </AssignTargetPath>
-
-               <AssignTargetPath Files="@(Content)" RootFolder="$(MSBuildProjectDirectory)">
-                       <Output TaskParameter="AssignedFiles" ItemName="ContentWithTargetPath"/>
-               </AssignTargetPath>
-
-               <AssignTargetPath Files="@(EmbeddedResource)" RootFolder="$(MSBuildProjectDirectory)">
-                       <Output TaskParameter="AssignedFiles" ItemName="EmbeddedResourceWithTargetPath"/>
-               </AssignTargetPath>
-       </Target>
-
-       <Target Name="DeployOutputFiles"
-               DependsOnTargets="BuildResources;CoreCompile;_CopyDeployFilesToOutputDirectory;_CopyAppConfigFile">
-
-               <Copy 
-                       SourceFiles="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
-                       Condition="'$(OutDir)' != '' and Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')"
-                       DestinationFolder="$(OutDir)"
-                       SkipUnchangedFiles="true" >
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-
-               <Copy SourceFiles="@(IntermediateAssembly)" Condition="'$(OutDir)' != ''" DestinationFolder="$(OutDir)" SkipUnchangedFiles="true">
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-
-               <Copy
-                       SourceFiles = "@(IntermediateSatelliteAssemblies)"
-                       DestinationFiles = "@(IntermediateSatelliteAssemblies->'$(OutDir)\%(Culture)\$(AssemblyName).resources.dll')"
-                       Condition = "'@(IntermediateSatelliteAssemblies)' != ''"
-                       SkipUnchangedFiles="true">
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-       </Target>
-
-       <Target Name="_CopyDeployFilesToOutputDirectory"
-               DependsOnTargets="GetCopyToOutputDirectoryItems;
-                       _CopyDeployFilesToOutputDirectoryAlways;
-                       _CopyDeployFilesToOutputDirectoryPreserveNewest"/>
-
-       <Target Name="_CopyDeployFilesToOutputDirectoryPreserveNewest"
-               Condition="'@(ItemsToCopyToOutputDirectoryPreserveNewest)' != ''"
-               Inputs="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
-               Outputs="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')">
-
-               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest)"
-                       DestinationFiles="@(ItemsToCopyToOutputDirectoryPreserveNewest->'$(OutDir)%(TargetPath)')">
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-       </Target>
-
-       <!-- Copy if newer -->
-       <Target Name="_CopyDeployFilesToOutputDirectoryAlways"
-               Condition="'@(ItemsToCopyToOutputDirectoryAlways)' != ''">
-
-               <Copy SourceFiles="@(ItemsToCopyToOutputDirectoryAlways)"
-                       DestinationFiles="@(ItemsToCopyToOutputDirectoryAlways->'$(OutDir)%(TargetPath)')">
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-       </Target>
-
-
-       <Target Name="_CopyAppConfigFile" Condition="'@(AppConfigWithTargetPath)' != ''"
-               Inputs="@(AppConfigWithTargetPath)"
-               Outputs="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
-
-               <Copy SourceFiles="@(AppConfigWithTargetPath)"
-                       DestinationFiles="@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')">
-                       <Output TaskParameter="DestinationFiles" ItemName="FileWrites"/>
-               </Copy>
-       </Target>
-
-       <Target Name="GetTargetPath" Outputs="$(TargetPath)"/>
-
-       <Target Name="GetCopyToOutputDirectoryItems"
-               Outputs="@(AllItemsFullPathWithTargetPath)"
-               DependsOnTargets="AssignTargetPaths;SplitProjectReferencesByExistent">
-
-               <!-- FIXME: handle .vcproj
-                    FIXME: Private ProjectReferences are honored only in 3.5
-               -->
-               <MSBuild
-                       Projects="@(ProjectReferenceWithConfigurationExistent)"
-                       Targets="GetCopyToOutputDirectoryItems"
-                       Condition="'@(ProjectReferenceWithConfigurationExistent)' != '' and '%(ProjectReferenceWithConfigurationExistent.Private)' != 'false'">
-
-                       <Output TaskParameter="TargetOutputs" ItemName="AllChildProjectItemsWithTargetPath"/>
-               </MSBuild>
-
-               <!-- Process items from child project. The outputs need to have full path
-                    as they'll be used from other projects -->
-
-               <CreateItem
-                       Include="@(AllChildProjectItemsWithTargetPath->'%(FullPath)')"
-                       Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
-
-                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
-                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
-                               Condition="'%(AllChildProjectItemsWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
-
-               </CreateItem>
-
-               <!-- Process _this_ project's items -->
-
-               <CreateItem
-                       Include="@(NoneWithTargetPath->'%(FullPath)')"
-                       Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(NoneWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
-                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
-                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
-                               Condition="'%(NoneWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
-               </CreateItem>
-
-               <CreateItem
-                       Include="@(ContentWithTargetPath->'%(FullPath)')"
-                       Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(ContentWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
-                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
-                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
-                               Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
-               </CreateItem>
-
-               <CreateItem
-                       Include="@(EmbeddedResourceWithTargetPath->'%(FullPath)')"
-                       Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'Always' or '%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)' == 'PreserveNewest'">
-                       <Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryAlways"
-                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
-                       <Output TaskParameter="Include" ItemName="ItemsToCopyToOutputDirectoryPreserveNewest"
-                               Condition="'%(EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
-               </CreateItem>
-
-       </Target>
-
-       <!-- Pre/Post BuildEvents -->
-       <PropertyGroup>
-               <PreBuildEventDependsOn />
-       </PropertyGroup>
-
-       <Target Name="PreBuildEvent"
-               Condition="'$(PreBuildEvent)' != ''"
-               DependsOnTargets="$(PreBuildEventDependsOn)">
-
-               <Exec WorkingDirectory="$(OutDir)" Command="$(PreBuildEvent)" />
-       </Target>
-
-       <!-- PostBuildEvent depends on $(RunPostBuildEvent)
-
-               Default: OnBuildSuccess
-               OnBuildSuccess: Run after a successful build
-               OnOutputUpdated: Run only if the output assembly got updates
-               Always: Run always
-       -->
-       <PropertyGroup>
-               <PostBuildEventDependsOn />
-       </PropertyGroup>
-
-       <!-- this gets invoked in two cases, from CoreBuildDependsOn, if the build completes
-            successfully, OR from OnError in CoreBuild, if the build failed and $(RunPostBuildEvent)
-            is 'Always' or 'OnOutputUpdated'. Invoke $(PostBuildEvent) if its either Empty (== OnBuildSuccess)
-            or OnBuildSuccess or Always OR (OnOutputUpdated and output assembly got updated) -->
-       <Target Name="PostBuildEvent"
-               Condition="'$(PostBuildEvent)' != '' and
-                       ('$(RunPostBuildEvent)' != 'OnOutputUpdated' or
-                         '$(_AssemblyModifiedTimeBeforeCompile)' != '$(_AssemblyModifiedTimeAfterCompile)')"
-               DependsOnTargets="$(PostBuildEventDependsOn)">
-
-               <Exec WorkingDirectory="$(OutDir)" Command="$(PostBuildEvent)" />
-       </Target>
-
-       <!-- Timestamp the output assemblies, required for PostBuildEvent -->
-       <Target Name="_TimestampBeforeCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
-               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
-                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeBeforeCompile" />
-               </CreateItem>
-       </Target>
-       <Target Name="_TimestampAfterCompile" Condition="'$(RunPostBuildEvent)' == 'OnOutputUpdated'">
-               <CreateItem Include="%(IntermediateAssembly.ModifiedTime)">
-                       <Output TaskParameter="Include" PropertyName="_AssemblyModifiedTimeAfterCompile" />
-               </CreateItem>
-       </Target>
-
-       <!-- Rebuild -->
-       <PropertyGroup>
-               <RebuildDependsOn>
-                       BeforeRebuild;
-                       Clean;
-                       $(MSBuildProjectDefaultTargets);
-                       AfterRebuild;
-               </RebuildDependsOn>
-
-               <RebuildDependsOn Condition="'$(MSBuildProjectDefaultTargets)' == 'Rebuild'">
-                       BeforeRebuild;
-                       Clean;
-                       Build;
-                       AfterRebuild;
-               </RebuildDependsOn>
-       </PropertyGroup>
-
-       <Target Name="BeforeRebuild" />
-       <Target Name="AfterRebuild" />
-
-       <Target Name="Rebuild"
-               DependsOnTargets="$(RebuildDependsOn)"
-               Outputs="$(TargetPath)"/>
-
-       <!-- Clean -->
-       <Target Name="_RecordCleanFile"
-               DependsOnTargets="_GetCompileOutputsForClean">
-
-               <!-- add to list of previous writes for this platform/config -->
-
-               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
-                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
-               </ReadLinesFromFile>
-
-               <RemoveDuplicates Inputs="@(PreviousFileWrites);@(FileWrites->'%(FullPath)')">
-                       <Output TaskParameter="Filtered" ItemName="CombinedFileWrites"/>
-               </RemoveDuplicates>
-
-               <WriteLinesToFile
-                       File="$(IntermediateOutputPath)$(CleanFile)"
-                       Lines="@(CombinedFileWrites)"
-                       Overwrite="true"/>
-       </Target>
-
-       <PropertyGroup>
-               <CleanDependsOn>
-                       BeforeClean;
-                       CleanReferencedProjects;
-                       CoreClean;
-                       AfterClean
-               </CleanDependsOn>
-       </PropertyGroup>
-
-       <Target Name="_GetCompileOutputsForClean">
-               <!-- assembly and debug file in the *intermediate output path* -->
-               <CreateItem Include="@(IntermediateAssembly)" Condition="Exists('@(IntermediateAssembly)')">
-                       <Output TaskParameter="Include" ItemName="FileWrites"/>
-               </CreateItem>
-
-               <CreateItem Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb"
-                       Condition="Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')">
-                       <Output TaskParameter="Include" ItemName="FileWrites"/>
-               </CreateItem>
-       </Target>
-
-       <!-- Get the list of files written, for clean -->
-       <Target Name="_GetCleanFileWrites"
-               DependsOnTargets="_GetCompileOutputsForClean">
-               <ReadLinesFromFile File="$(IntermediateOutputPath)$(CleanFile)">
-                       <Output TaskParameter="Lines" ItemName="PreviousFileWrites"/>
-               </ReadLinesFromFile>
-       </Target>
-
-       <Target Name="CleanReferencedProjects"
-               DependsOnTargets="AssignProjectConfigurations">
-
-               <!-- If building from .sln.proj or from IDE, clean will get handled by them,
-                    else we are building a project directly, from the command line, so
-                    clean the referenced projects -->
-               <MSBuild Projects="@(ProjectReferenceWithConfigurationExistent)"
-                       Targets="Clean"
-                       Condition=" '$(BuildingSolutionFile)' != 'true' and '$(BuildingInsideVisualStudio)' != 'true' and '@(ProjectReferenceWithConfigurationExistent)' != ''" />
-
-       </Target>
-
-       <Target Name="Clean" DependsOnTargets="$(CleanDependsOn)"/>
-
-       <!-- Override in project to run before/after clean tasks -->
-       <Target Name="BeforeClean" />
-       <Target Name="AfterClean" />
-
-       <Target Name="CoreClean" DependsOnTargets="_GetCleanFileWrites">
-               <Delete Files="@(PreviousFileWrites);@(FileWrites)" TreatErrorsAsWarnings="true"/>
-
-               <!-- all previous files written for this platform/config have been deleted,
-                    we can safely remove the file list now -->
-               <Delete Files="$(IntermediateOutputPath)$(CleanFile)" TreatErrorsAsWarnings="true" />
-       </Target>
-
-</Project>
diff --git a/mcs/tools/xbuild/xbuild/Microsoft.Common.tasks b/mcs/tools/xbuild/xbuild/Microsoft.Common.tasks
deleted file mode 100644 (file)
index 9b1c1ad..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" >
-       <UsingTask TaskName="Microsoft.Build.Tasks.AL"                  AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.AssignTargetPath"    AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.AssignCulture"       AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.AssignProjectConfiguration"  AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.CallTarget"          AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.CombinePath"         AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Copy"                AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.CreateItem"          AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.CreateProperty"      AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Csc"                 AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Delete"              AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Error"               AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Exec"                AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.FindAppConfigFile"   AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.FindUnderPath"       AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.GenerateResource"    AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkPath"    AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.GetFrameworkSdkPath" AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.LC"                  AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.MakeDir"             AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Message"             AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.MSBuild"             AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.ReadLinesFromFile"   AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDir"           AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.RemoveDuplicates"            AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.ResolveAssemblyReference"            AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.SignFile"            AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Touch"               AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Vbc"                 AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.Warning"             AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-       <UsingTask TaskName="Microsoft.Build.Tasks.WriteLinesToFile"    AssemblyName="Microsoft.Build.Tasks, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
-</Project>
diff --git a/mcs/tools/xbuild/xbuild/Microsoft.Silverlight.CSharp.targets b/mcs/tools/xbuild/xbuild/Microsoft.Silverlight.CSharp.targets
new file mode 100644 (file)
index 0000000..7aff37d
--- /dev/null
@@ -0,0 +1,4 @@
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+       <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+       <Import Project="Microsoft.Silverlight.Common.targets"/>
+</Project>
diff --git a/mcs/tools/xbuild/xbuild/Microsoft.Silverlight.Common.targets b/mcs/tools/xbuild/xbuild/Microsoft.Silverlight.Common.targets
new file mode 100644 (file)
index 0000000..5de5a88
--- /dev/null
@@ -0,0 +1,147 @@
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+       <UsingTask TaskName="Moonlight.Build.Tasks.CreateTestPage" AssemblyFile="Moonlight.Build.Tasks.dll" />
+       <UsingTask TaskName="Moonlight.Build.Tasks.GenerateMoonlightManifest" AssemblyFile="Moonlight.Build.Tasks.dll"/>
+       <UsingTask TaskName="Moonlight.Build.Tasks.GenerateXap" AssemblyFile="Moonlight.Build.Tasks.dll" />
+       <UsingTask TaskName="Moonlight.Build.Tasks.GetMoonlightFrameworkPath" AssemblyFile="Moonlight.Build.Tasks.dll"/>
+       <UsingTask TaskName="Moonlight.Build.Tasks.Respack" AssemblyFile="Moonlight.Build.Tasks.dll" />
+       <UsingTask TaskName="Moonlight.Build.Tasks.XamlG" AssemblyFile="Moonlight.Build.Tasks.dll"/>
+
+       <PropertyGroup>
+               <PrepareResourcesDependsOn>
+                       GenerateXamlG;
+                       Respack;
+                       $(PrepareResourcesDependsOn)
+               </PrepareResourcesDependsOn>
+
+               <PrepareForRunDependsOn>
+                       GenerateMoonlightManifest;
+                       GenerateXap;
+                       CreateTestPage;
+                       $(PrepareForRunDependsOn)
+               </PrepareForRunDependsOn>
+
+               <CscToolExe Condition="'$(CscToolExe)' == '' and '$(OS)' == 'Windows_NT'">smcs.bat</CscToolExe>
+               <CscToolExe Condition="'$(CscToolExe)' == '' and '$(OS)' != 'Windows_NT'">smcs</CscToolExe>
+
+               <XapFileName Condition="'$(XapFileName)' == ''">$(AssemblyName).xap</XapFileName>
+               <TestPageFileName Condition="'$(TestPageFileName)' == ''">TestPage.html</TestPageFileName>
+               <SilverlightVersion Condition="'$(SilverlightVersion)' == ''">@SILVERLIGHT_VERSION@</SilverlightVersion>
+               <RuntimeVersion Condition="'$(RuntimeVersion)' == '' and '$(SilverlightVersion)' == '2.0'">2.0.31005.0</RuntimeVersion>
+               <RuntimeVersion Condition="'$(RuntimeVersion)' == '' and '$(SilverlightVersion)' == '3.0'">3.0.40624.0</RuntimeVersion>
+       </PropertyGroup>
+
+       <ItemGroup>
+               <MoonlightManifestFile Include="$(OutDir)AppManifest.xaml">
+                       <TargetPath>AppManifest.xaml</TargetPath>
+               </MoonlightManifestFile>
+       </ItemGroup>
+
+       <!-- Override 'GetFrameworkPaths' -->
+       <Target Name="GetFrameworkPaths">
+               <GetMoonlightFrameworkPath
+                       SilverlightVersion="$(SilverlightVersion)">
+                       <Output TaskParameter="FrameworkPath" ItemName="TargetFrameworkDirectories"/>
+                       <Output TaskParameter="FrameworkPath" ItemName="_FrameworkPath"/>
+               </GetMoonlightFrameworkPath>
+
+               <Error Text="Moonlight framework v$(SilverlightVersion) doesn't seem to be installed. Expected framework directory could not be found (@(_FrameworkPath)). To force a particular silverlight version, try: xbuild $(MSBuildProjectFile) /p:SilverlightVersion=2.0"
+                       Condition="!Exists('@(_FrameworkPath)')" />
+
+               <CreateProperty Value="$(AssemblySearchPaths);@(_FrameworkPath->'%(Identity)-redist')"
+                               Condition="Exists('@(_FrameworkPath->'%(Identity)-redist')')">
+                       <Output TaskParameter="Value" PropertyName="AssemblySearchPaths"/>
+               </CreateProperty>
+       </Target>
+
+       <Target Name="Respack">
+               <Respack
+                       Resources="@(Resource);@(Page);@(ApplicationDefinition)"
+                       OutputFile="$(IntermediateOutputPath)$(AssemblyName).g.resources">
+                       <Output TaskParameter="OutputFile" ItemName="FileWrites"/>
+                       <Output TaskParameter="OutputFile" ItemName="ManifestResourceWithNoCulture"/>
+               </Respack>
+       </Target>
+
+       <Target Name="GenerateXamlG">
+               <CreateItem Include="@(Compile)" Condition="'%(Compile.Extension)' == '.xaml' and '%(Compile.Generator)' == 'MSBuild:MarkupCompilePass1'">
+                       <Output TaskParameter="Include" ItemName="XamlFiles"/>
+               </CreateItem>
+               <CreateItem Include="@(ApplicationDefinition)" Condition="'%(Extension)' == '.xaml' and '%(Generator)' == 'MSBuild:MarkupCompilePass1'">
+                       <Output TaskParameter="Include" ItemName="XamlFiles"/>
+               </CreateItem>
+               <CreateItem Include="@(Page)" Condition="'%(Extension)' == '.xaml' and '%(Generator)' == 'MSBuild:MarkupCompilePass1'">
+                       <Output TaskParameter="Include" ItemName="XamlFiles"/>
+               </CreateItem>
+
+               <XamlG
+                       Sources="@(XamlFiles)"
+                       Language = "$(Language)"
+                       AssemblyName = "$(AssemblyName)"
+                       OutputFiles = "@(XamlFiles->'$(IntermediateOutputPath)%(Filename).g$(DefaultLanguageSourceExtension)')"
+               >
+                       <Output TaskParameter="OutputFiles" ItemName="Compile"/>
+                       <Output TaskParameter="OutputFiles" ItemName="FileWrites"/>
+               </XamlG>
+       </Target>
+
+       <Target Name="GenerateMoonlightManifest">
+               <GenerateMoonlightManifest
+                       ManifestFile="@(MoonlightManifestFile->'%(Identity)')"
+                       EntryPointAssembly="$(AssemblyName)$(TargetExt)"
+                       References="@(ReferenceCopyLocalPaths)"
+                       SilverlightManifestTemplate="$(SilverlightManifestTemplate)"
+                       SilverlightAppEntry="$(SilverlightAppEntry)"
+                       RuntimeVersion="$(RuntimeVersion)"
+
+                       Condition = "'$(GenerateSilverlightManifest)' == 'true'"
+               >
+                       <Output TaskParameter="ManifestFile" ItemName="FileWrites"/>
+               </GenerateMoonlightManifest>
+       </Target>
+
+       <PropertyGroup>
+               <GenerateXapDependsOn>
+                       GenerateXamlG;
+                       GenerateMoonlightManifest;
+                       GetXapInputFiles
+               </GenerateXapDependsOn>
+       </PropertyGroup>
+       <Target Name="GenerateXap" DependsOnTargets="$(GenerateXapDependsOn)" Condition="'$(XapOutputs)' == 'true'">
+               <!-- Looks for %(DestinationSubdirectory) in LocalCopyReferences -->
+               <GenerateXap
+                       InputFiles="@(XapInputFiles)"
+                       LocalCopyReferences="@(ReferenceCopyLocalPaths)"
+                       XapFilename="$(OutDir)$(XapFilename)"
+               >
+                       <Output TaskParameter="XapFilename" ItemName="FileWrites"/>
+               </GenerateXap>
+       </Target>
+
+       <Target Name="CreateTestPage" Condition="'$(CreateTestPage)' == 'true' and '$(XapOutputs)' == 'true'">
+               <CreateTestPage
+                       XapFileName="$(XapFileName)"
+                       Title="$(AssemblyName)"
+                       TestPageFilename="$(OutDir)$(TestPageFilename)">
+                       <Output TaskParameter="TestPageFilename" ItemName="FileWrites"/>
+               </CreateTestPage>
+       </Target>
+
+       <Target Name="GetXapInputFiles">
+               <CreateItem Include="@(IntermediateAssembly)" AdditionalMetadata="TargetPath=$(AssemblyName)$(TargetExt)">
+                       <Output TaskParameter="Include" ItemName="XapInputFiles"/>
+               </CreateItem>
+
+               <CreateItem Include="@(ContentWithTargetPath)">
+                       <Output TaskParameter="Include" ItemName="XapInputFiles"/>
+               </CreateItem>
+
+               <CreateItem Include="@(MoonlightManifestFile)" Condition="'$(GenerateSilverlightManifest)' == 'true'">
+                       <Output TaskParameter="Include" ItemName="XapInputFiles"/>
+               </CreateItem>
+
+               <CreateItem Include="$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb" AdditionalMetadata="TargetPath=$(AssemblyName)$(TargetExt).mdb"
+                               Condition="Exists('$(IntermediateOutputPath)$(AssemblyName)$(TargetExt).mdb')">
+                       <Output TaskParameter="Include" ItemName="XapInputFiles"/>
+               </CreateItem>
+       </Target>
+</Project>
diff --git a/mcs/tools/xbuild/xbuild/Microsoft.Silverlight.VisualBasic.targets b/mcs/tools/xbuild/xbuild/Microsoft.Silverlight.VisualBasic.targets
new file mode 100644 (file)
index 0000000..262754f
--- /dev/null
@@ -0,0 +1,4 @@
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+       <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
+       <Import Project="Microsoft.Silverlight.Common.targets"/>
+</Project>
index eb3c3fd96ad5898e25ee7d0fa799740b3ca77085..d284b86a231f2d70ee05a3f57638c6eb983abdf9 100644 (file)
@@ -23,6 +23,8 @@
 
                <DebugSymbols Condition=" '$(DebugType)' == 'none' ">false</DebugSymbols>
                <DebugType    Condition=" '$(DebugType)' == 'none' "></DebugType>
+
+               <CoreCompileDependsOn></CoreCompileDependsOn>
        </PropertyGroup>
 
        <ItemGroup>
@@ -32,7 +34,8 @@
        <Target
                Name="CoreCompile"
                Inputs="@(Compile)"
-               Outputs="$(IntermediateAssembly)"
+               Outputs="@(IntermediateAssembly)"
+               DependsOnTargets="$(CoreCompileDependsOn)"
        >
                <Vbc
                        AdditionalLibPaths="$(AdditionalLibPaths)"
                        OptionExplicit="$(OptionExplicit)"
                        OptionStrict="$(OptionStrict)"
                        OptionStrictType="$(OptionStrictType)" 
-                       OutputAssembly="$(IntermediateAssembly)"
+                       OutputAssembly="@(IntermediateAssembly)"
                        Platform="$(PlatformTarget)"
                        References="@(ResolvedFiles)"
                        RemoveIntegerChecks="$(RemoveIntegerChecks)"
                        Resources="@(ManifestResourceWithNoCulture);@(ManifestNonResxWithNoCultureOnDisk);@(CompiledLicenseFile)"
                        ResponseFiles="$(CompilerResponseFile)"
+                       RootNamespace="$(RootNamespace)"
                        Sources="@(Compile)"
                        TargetType="$(OutputType)"
                        TreatWarningsAsErrors="$(TreatWarningsAsErrors)"
diff --git a/mcs/tools/xbuild/xbuild_targets.make b/mcs/tools/xbuild/xbuild_targets.make
new file mode 100644 (file)
index 0000000..8c3c998
--- /dev/null
@@ -0,0 +1,22 @@
+test-local: copy-targets
+
+copy-targets:
+       for p in net_2_0 net_3_5 net_4_0; do \
+               cp $(XBUILD_DIR)/xbuild/Microsoft.CSharp.targets $(topdir)/class/lib/$$p; \
+               cp $(XBUILD_DIR)/xbuild/Microsoft.VisualBasic.targets $(topdir)/class/lib/$$p; \
+               cp $(XBUILD_DIR)/xbuild/Microsoft.Silverlight*.targets $(topdir)/class/lib/$$p; \
+       done
+       cp $(XBUILD_DIR)/xbuild/2.0/Microsoft.Common.* $(topdir)/class/lib/net_2_0
+       cp $(XBUILD_DIR)/xbuild/3.5/Microsoft.Common.* $(topdir)/class/lib/net_3_5
+       cp $(XBUILD_DIR)/xbuild/4.0/Microsoft.Common.* $(topdir)/class/lib/net_4_0
+
+clean-local: clean-target-files
+
+clean-target-files:
+       for p in net_2_0 net_3_5 net_4_0; do \
+               rm -f $(topdir)/class/lib/$$p/Microsoft.Common.targets; \
+               rm -f $(topdir)/class/lib/$$p/Microsoft.CSharp.targets; \
+               rm -f $(topdir)/class/lib/$$p/Microsoft.VisualBasic.targets; \
+               rm -f $(topdir)/class/lib/$$p/Microsoft.Silverlight*.targets; \
+               rm -f $(topdir)/class/lib/$$p/Microsoft.Common.tasks; \
+       done
index cc9f0ecd74a35183be5feae0f094349724157b24..9116df831991fbd52e71858cae80b9038504ace2 100644 (file)
@@ -1,3 +1,7 @@
+2010-03-30  Zoltan Varga  <vargaz@gmail.com>
+
+       * arm/*.sh: Remove bash dependency.
+
 2009-08-14  Zoltan Varga  <vargaz@gmail.com>
 
        * arm/arm-codegen.h: Add armv6 MOVW/MOVT.
index 0b0e716d7251176478c5b627d727af3efa34b0b6..978145d1b6e8a3a9ccfa8da6f6d127790bc6cbfe 100644 (file)
@@ -10,4 +10,6 @@
 /*.exe
 /*.dll
 /arm_dpimacros.h
+/arm_fpamacros.h
+/arm_vfpmacros.h
 /fixeol.sh
index 1802eecc40bd6834b09473001f8551cb7c12b9c4..d3b93ff52ae84355b6c3d42e287de19e9ed4dcfe 100755 (executable)
@@ -1,4 +1,4 @@
-#!/bin/bash
+#!/bin/sh
 
 OPCODES="AND EOR SUB RSB ADD ADC SBC RSC ORR BIC"
 CMP_OPCODES="TST TEQ CMP CMN"
@@ -6,7 +6,7 @@ MOV_OPCODES="MOV MVN"
 
 # $1: opcode list
 # $2: template
-function gen() {
+gen() {
        for i in $1; do
                sed "s/<Op>/$i/g" $2.th
        done
index fa6a280b6f2a3eceb847a1358979897b843543e7..be1987683a2ff21394d859b9ef63a4969c40e50a 100755 (executable)
@@ -1,11 +1,11 @@
-#!/bin/bash
+#!/bin/sh
 
 DYADIC="ADF MUF SUF RSF DVF RDF POW RPW RMF FML FDV FRD POL"
 MONADIC="MVF MNF ABS RND SQT LOG EXP SIN COS TAN ASN ACS ATN URD NRM"
 
 # $1: opcode list
 # $2: template
-function gen() {
+gen() {
        for i in $1; do
                sed "s/<Op>/$i/g" $2.th
        done
index 4f850f086f657ad39679c37be3208b747163567d..bed4a9c80eb627bf071a181d08cc0e17e6939401 100755 (executable)
@@ -1,11 +1,11 @@
-#!/bin/bash
+#!/bin/sh
 
 DYADIC="ADD SUB MUL NMUL DIV"
 MONADIC="CPY ABS NEG SQRT CMP CMPE CMPZ CMPEZ CVT UITO SITO TOUI TOSI TOUIZ TOSIZ"
 
 # $1: opcode list
 # $2: template
-function gen() {
+gen() {
        for i in $1; do
                sed "s/<Op>/$i/g" $2.th
        done
index d35967b025d5b0c1ab86eb8dbd2e87e486b45b7e..e756d354f96582e1137559c73f50cc7542b1c212 100644 (file)
@@ -1,3 +1,7 @@
+2010-03-23     Neale Ferguson <neale@sinenomine.net>
+       
+       * s390x-codegen.h: Remove duplicate
+
 2009-06-24     Neale Ferguson <neale@sinenomine.net>
        
        * s390x-codegen.h: Add some new instructions.
index 6af46dbf2405c182b05972cd68cc0c580d9bebb5..7a2e069bfc26a6934609ac6977887cb42f8adfcd 100644 (file)
@@ -773,7 +773,6 @@ typedef struct {
 #define s390_stey(c, r, x, b, d)       S390_RXY(c, 0xed66, r, x, b, d)
 #define s390_stfpc(c, b, d)            S390_S(c, 0xb29c, b, d)
 #define s390_stg(c, r, x, b, d)                S390_RXY(c, 0xe324, r, x, b, d)
-#define s390_stg(c, r, x, b, d)                S390_RXY(c, 0xe324, r, x, b, d)
 #define s390_sth(c, r, x, b, d)                S390_RX(c, 0x40, r, x, b, d)
 #define s390_sthy(c, r, x, b, d)       S390_RXY(c, 0xe370, r, x, b, d)
 #define s390_stm(c, r1, r2, b, d)      S390_RS_1(c, 0x90, r1, r2, b, d)
index b34c220d144369b18093dae7e2368f17c4e02ea7..535493ded0ab30213428d0cae4cfa2cb550e5a17 100644 (file)
@@ -9,3 +9,4 @@
 /semantic.cache
 /.project
 /.cproject
+/TAGS
index b788cdef9cc9b02d1b54d635de60d865546d379d..30b6a3f720cf808d31bbbe004fb028ad8957665a 100644 (file)
@@ -1,3 +1,34 @@
+2010-04-07  Jb Evain  <jbevain@novell.com>
+
+       * main.c: don't overwrite method_name.
+
+2010-04-06  Miguel de Icaza  <miguel@novell.com>
+
+       * main.c: Prevent a crash with broken assemblies.
+
+2010-03-30  Raja R Harinath  <harinath@hurrynot.org>
+
+       Clean up some whitespace in the output
+       * main.c (pinvoke_flags_map): Add a few trailing spaces.
+       * util.c (flags): Simplify.
+
+       Make util.c:flags() stricter
+       * get.c (field_flags_map): Add empty entries for
+       HAS_FIELD_MARSHAL, HAS_DEFAULT and HAS_FIELD_RVA.
+       * main.c (method_flags_map): Add empty entry for HAS_SECURITY.
+       * util.c (flags): Remove known flags from 'code' in loop.  Any
+       leftover flags are printed as "unknown-flag-xx".
+
+       Prepare for util.c:flags() to be stricter
+       * main.c (pinvoke_flags): Remove cset and cconv flags before
+       passing onto flags().
+       (method_flags): Likewise with access flags.
+       * get.c (field_flags): Likewise.
+       (get_method_impl_flags): Likewise, with code_type and managed_type
+       flags.
+
+       * get.c (managed_impl_flags): Add 'nooptimization' flag.
+
 2010-03-12  Jb Evain  <jbevain@novell.com>
 
        * dump.c (dump_table_exported): dump the type flags as well.
index a1eca828ae40a1a074ec0776685ed2ad6a99ac1c..5522dfa05164ccf9db5f277356a3911d53ab21dc 100644 (file)
@@ -1622,7 +1622,15 @@ static dis_map_t field_flags_map [] = {
        { FIELD_ATTRIBUTE_SPECIAL_NAME,        "specialname " },
        { FIELD_ATTRIBUTE_PINVOKE_IMPL,        "FIXME:pinvokeimpl " },
        { FIELD_ATTRIBUTE_RT_SPECIAL_NAME,        "rtspecialname " },
-       /*{ FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL,        "hasfieldmarshal " },*/
+
+       /* This is set when a MarshalAs attribute is seen. FIXME: round-trip?  */
+       { FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL,        "" },
+
+       /* This seems to be set if LITERAL is set. FIXME: round-trip? */
+       { FIELD_ATTRIBUTE_HAS_DEFAULT,          "" },
+
+       /* This seems to be set on compiler-generated array initializer fields. FIXME: round-trip? */
+       { FIELD_ATTRIBUTE_HAS_FIELD_RVA,                "" },
        { 0, NULL }
 };
 
@@ -1636,11 +1644,12 @@ field_flags (guint32 f)
 {
        char buffer [1024];
        int access = f & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK;
+       int rest = f & ~access;
        
        buffer [0] = 0;
 
        strcat (buffer, map (access, field_access_map));
-       strcat (buffer, flags (f, field_flags_map));
+       strcat (buffer, flags (rest, field_flags_map));
        return g_strdup (buffer);
 }
 
@@ -3181,6 +3190,7 @@ static dis_map_t managed_impl_flags [] = {
        { METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL,   "internalcall " },
        { METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED,    "synchronized " },
        { METHOD_IMPL_ATTRIBUTE_NOINLINING,      "noinlining " },
+       { METHOD_IMPL_ATTRIBUTE_NOOPTIMIZATION,  "nooptimization " },
        { 0, NULL }
 };
 
@@ -3191,10 +3201,11 @@ get_method_impl_flags (guint32 f)
        char *s;
        int code_type = f & METHOD_IMPL_ATTRIBUTE_CODE_TYPE_MASK;
        int managed_type = f & METHOD_IMPL_ATTRIBUTE_MANAGED_MASK;
+       int rest = f & ~(code_type | managed_type);
 
        g_string_append (str, map (code_type, method_impl_map));
        g_string_append (str, map (managed_type, managed_type_map));
-       g_string_append (str, flags (f, managed_impl_flags));
+       g_string_append (str, flags (rest, managed_impl_flags));
        
        s = str->str;
        g_string_free (str, FALSE);
index 7fa06acd902da2a06cd87ff3c4c42614d9070cf7..37d389b1bdb08ae6f830c3a03e1af2c5bc8fb314 100644 (file)
@@ -535,8 +535,8 @@ static dis_map_t method_flags_map [] = {
        { METHOD_ATTRIBUTE_RT_SPECIAL_NAME,     "rtspecialname " },
        { METHOD_ATTRIBUTE_UNMANAGED_EXPORT,    "export " },
 /* MS ilasm doesn't compile this statement - is must be added automagically when permissionset are present */
-/*     { METHOD_ATTRIBUTE_HAS_SECURITY,        "hassecurity" }, */
-       { METHOD_ATTRIBUTE_REQUIRE_SEC_OBJECT,  "requiresecobj" },
+       { METHOD_ATTRIBUTE_HAS_SECURITY,        "" /*"hassecurity"*/ },
+       { METHOD_ATTRIBUTE_REQUIRE_SEC_OBJECT,  "requiresecobj " },
        { METHOD_ATTRIBUTE_PINVOKE_IMPL,        "pinvokeimpl " }, 
        { METHOD_ATTRIBUTE_STRICT,                  "strict " }, 
        { 0, NULL }
@@ -552,10 +552,11 @@ method_flags (guint32 f)
 {
        GString *str = g_string_new ("");
        int access = f & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK;
+       int rest = f & ~access;
        char *s;
        
        g_string_append (str, map (access, method_access_map));
-       g_string_append (str, flags (f, method_flags_map));
+       g_string_append (str, flags (rest, method_flags_map));
 
        s = str->str;
        g_string_free (str, FALSE);
@@ -566,10 +567,10 @@ method_flags (guint32 f)
 static dis_map_t pinvoke_flags_map [] = {
        { PINVOKE_ATTRIBUTE_NO_MANGLE ,            "nomangle " },
        { PINVOKE_ATTRIBUTE_SUPPORTS_LAST_ERROR,   "lasterr " },
-       { PINVOKE_ATTRIBUTE_BEST_FIT_ENABLED,      "bestfit:on" },
-       { PINVOKE_ATTRIBUTE_BEST_FIT_DISABLED,      "bestfit:off" },
-       { PINVOKE_ATTRIBUTE_THROW_ON_UNMAPPABLE_ENABLED, "charmaperror:on" },
-       { PINVOKE_ATTRIBUTE_THROW_ON_UNMAPPABLE_DISABLED, "charmaperror:off" },
+       { PINVOKE_ATTRIBUTE_BEST_FIT_ENABLED,      "bestfit:on " },
+       { PINVOKE_ATTRIBUTE_BEST_FIT_DISABLED,      "bestfit:off " },
+       { PINVOKE_ATTRIBUTE_THROW_ON_UNMAPPABLE_ENABLED, "charmaperror:on " },
+       { PINVOKE_ATTRIBUTE_THROW_ON_UNMAPPABLE_DISABLED, "charmaperror:off " },
        { 0, NULL }
 };
 
@@ -602,11 +603,12 @@ pinvoke_flags (guint32 f)
        GString *str = g_string_new ("");
        int cset = f & PINVOKE_ATTRIBUTE_CHAR_SET_MASK;
        int cconv = f & PINVOKE_ATTRIBUTE_CALL_CONV_MASK;
+       int rest = f & ~(cset | cconv);
        char *s;
 
        g_string_append (str, map (cset, pinvoke_char_set_map));
        g_string_append (str, map (cconv, pinvoke_call_conv_map));
-       g_string_append (str, flags (f, pinvoke_flags_map));
+       g_string_append (str, flags (rest, pinvoke_flags_map));
 
        s = g_strdup(str->str);
        g_string_free (str, FALSE);
@@ -857,8 +859,11 @@ dis_method_list (const char *klass_name, MonoImage *m, guint32 start, guint32 en
                        container = type_container;
 
                ms = mono_metadata_parse_method_signature_full (m, container, i + 1, sig, &sig);
-               sig_str = dis_stringify_method_signature (m, ms, i + 1, container, FALSE);
-               method_name = mono_metadata_string_heap (m, cols [MONO_METHOD_NAME]);
+               if (ms != NULL){
+                       sig_str = dis_stringify_method_signature (m, ms, i + 1, container, FALSE);
+                       method_name = mono_metadata_string_heap (m, cols [MONO_METHOD_NAME]);
+               } else
+                       method_name = g_strdup ("<NULL METHOD SIGNATURE>");
 
                fprintf (output, "    // method line %d\n", i + 1);
                fprintf (output, "    .method %s", flags);
index e5e467d09ffcb6914bd6f6814784dacfbfaa1e6d..737f6fda774fbd6b8d437fb8026f42691dca73a8 100644 (file)
@@ -45,13 +45,15 @@ flags (guint32 code, dis_map_t *table)
        
        buffer [0] = 0;
        
-       for (i = 0; table [i].str != NULL; i++)
+       for (i = 0; code && table [i].str != NULL; i++)
                if (table [i].code & code) {
-                       if (buffer [0])
-                               strcat (buffer, " ");
+                       code &= ~table [i].code;
                        strcat (buffer, table [i].str);
                }
 
+       if (code)
+               sprintf (buffer + strlen (buffer), "unknown-flag-%2x ", code);
+
        return buffer;
 }
 
index 873c3335de4ef268a9ad88629d402aa00957c465..58fbb5d6ab66d9a6df0d95f5934a478ec1fa43de 100644 (file)
@@ -8,3 +8,4 @@
 /libmint.la
 /*.lo
 /semantic.cache
+/TAGS
index 1e861cb59b3956f23f92b967263466815e042cbb..9fda7d340a699e16320650ef7d98c53c0f289502 100644 (file)
@@ -9,3 +9,4 @@
 /*.o
 /.project
 /.cproject
+/TAGS
index 67cd07cd67863c91f68bd4c44aff01ffa40eb620..6897a93044dc027bfd5e26d26353ec402b1a1711 100644 (file)
@@ -1,3 +1,79 @@
+2010-04-26  Geoff Norton  <gnorton@novell.com>
+
+       * processes.c: Fix this for 64-bit darwin.
+
+2010-04-20  Jonathan Pryor  <jpryor@novell.com>
+
+       * collection.c: Cleanup platform checks around
+         pthread_attr_setstacksize(), and instead always use
+         MAX(65536, PTHREAD_STACK_MIN) as the stack size.
+       * mono-mutex.c: Remove near duplicate pthread_mutex_timedlock()
+         declarations, and merge via a CONST_NEEDED intermediate #define.
+
+2010-04-19  Jonathan Pryor  <jpryor@novell.com>
+
+       * collection.c, mono-mutex.c: Add Android support.
+
+2010-04-14  Zoltan Varga  <vargaz@gmail.com>
+
+       * collection.c (_wapi_collection_init): Set stack size on openbsd similarly to
+       the other BSDs.
+
+2010-04-10  Andreas Färber  <andreas.faerber@web.de>
+
+       * processes.c (EnumProcesses, load_modules): Add implementations
+       for Haiku. Fixes build on Haiku.
+       (OpenProcess, EnumProcessModules, get_process_name_from_proc):
+       Tweak implementations for Haiku.
+       * process-private.h: Fix _WAPI_PROCESS_UNHANDLED_PID_MASK for
+       32-bit pids (Haiku).
+       * ChangeLog: Fix UTF-8 encoding
+
+       Code is contributed under MIT/X11 license.
+
+2010-04-09  Zoltan Varga  <vargaz@gmail.com>
+
+       * processes.c: Applied more openbsd changes from Robert Nagy <robert@openbsd.org>.
+
+2009-04-06 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * wthreads.c (TlsSetValue): Don't take locks here. We trust pthread_setspecific
+       return value to tell if we tried to store to an invalid slot.
+
+2010-04-04  Zoltan Varga  <vargaz@gmail.com>
+
+       * processes.c: Applied more openbsd changes from Robert Nagy <robert@openbsd.org>.
+
+2010-04-03  Zoltan Varga  <vargaz@gmail.com>
+
+       * processes.c: Applied more openbsd changes from Robert Nagy <robert@openbsd.org>.
+
+2010-04-03  Zoltan Varga  <vargaz@gmail.com>
+
+       * processes.c: Applied some openbsd changes from Robert Nagy <robert@openbsd.org>.
+
+2010-03-26  Zoltan Varga  <vargaz@gmail.com>
+
+       * sockets.c: Apply some openbsd changes from openbsd ports.
+
+2010-03-26  Zoltan Varga  <vargaz@gmail.com>
+
+       * shared.c: Disable shared supported by default, it can be enabled by setting
+       the MONO_ENABLE_SHM env variable.
+
+2009-03-22 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * threads.h: Add wapi_self_interrupt.
+
+       * wthreads.c: Add wapi_self_interrupt which puts the current
+       thread in interrupted state.
+
+       * wthreads.c (wapi_thread_clear_wait_handle): Previous handle
+       can possibly be NULL if an async interrupt cleared it.
+
+       This is safe because it is only async cleared if running inside a
+       handler block.
+
 2010-03-06 Gonzalo Paniagua Javier <gonzalo@novell.com>
 
        * processes.c: made ShellExecuteEx actually work when the file name to
@@ -94,7 +170,7 @@ Wed Feb 24 16:01:37 CET 2010 Paolo Molaro <lupus@ximian.com>
 
 2009-09-01  Zoltan Varga  <vargaz@gmail.com>
 
-       * processes.c (EnumProcessModules): Applied patch from Romain Tartière
+       * processes.c (EnumProcessModules): Applied patch from Romain Tartière
        (romain@blogreen.org). Fix this on freebsd/OSX. Fixes #533893.
 
 2009-08-18  Christian Hergert  <chris@dronelabs.com>
index c8ec28e4c8ebd0d10be40c5b47634dd0411567fe..9388819d7472160d311d94138c0a1c4ba152c6a4 100644 (file)
@@ -58,17 +58,13 @@ void _wapi_collection_init (void)
         ret = pthread_attr_init (&attr);
         g_assert (ret == 0);
 
-#ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
+#if defined(HAVE_PTHREAD_ATTR_SETSTACKSIZE)
         if (set_stacksize == 0) {
-#if defined(__FreeBSD__) || defined(__NetBSD__)
-                ret = pthread_attr_setstacksize (&attr, 65536);
-#else
-                ret = pthread_attr_setstacksize (&attr, PTHREAD_STACK_MIN);
-#endif
-                g_assert (ret == 0);
+                       ret = pthread_attr_setstacksize (&attr, MAX (65536, PTHREAD_STACK_MIN));
+                       g_assert (ret == 0);
         } else if (set_stacksize == 1) {
-                ret = pthread_attr_setstacksize (&attr, 131072);
-                g_assert (ret == 0);
+                       ret = pthread_attr_setstacksize (&attr, 131072);
+                       g_assert (ret == 0);
         }
 #endif
 
index 154035a6e5fa64c5f4e049cdb800606d3ae45b5b..f5152c2f29d5159cb294208ef16ed114f3da6608 100644 (file)
 
 
 #ifndef HAVE_PTHREAD_MUTEX_TIMEDLOCK
-int pthread_mutex_timedlock (pthread_mutex_t *mutex,
-                           const struct timespec *timeout);
+/* Android does not implement pthread_mutex_timedlock(), but does provide an
+ * unusual declaration: http://code.google.com/p/android/issues/detail?id=7807
+ */
+#ifdef PLATFORM_ANDROID
+#define CONST_NEEDED
+#else
+#define CONST_NEEDED const
+#endif
 
+int pthread_mutex_timedlock (pthread_mutex_t *mutex,
+                           CONST_NEEDED struct timespec *timeout);
 int
-pthread_mutex_timedlock (pthread_mutex_t *mutex, const struct timespec *timeout)
+pthread_mutex_timedlock (pthread_mutex_t *mutex, CONST_NEEDED struct timespec *timeout)
 {
        struct timeval timenow;
        struct timespec sleepytime;
index a8b9f5414c0e3d81c2191cce78b1a27ca5e9b09f..dc952832288cf64ec73263e5246e603e52065cfd 100644 (file)
 
 /* This marks a system process that we don't have a handle on */
 /* FIXME: cope with pids > 16bit */
+#if defined(__HAIKU__)
+#define _WAPI_PROCESS_UNHANDLED_PID_MASK 0x7FFFFFFF
+#else
 #define _WAPI_PROCESS_UNHANDLED_PID_MASK 0x7FFF
+#endif
 #define _WAPI_PROCESS_UNHANDLED (-1 & ~_WAPI_PROCESS_UNHANDLED_PID_MASK)
 
 extern gpointer _wapi_process_duplicate (void);
index b5917161551c6e7bbdf384b2ff0c62bf11c6141e..57f6bab425211888e849077b8dd7d62869ae54e7 100644 (file)
 #include <sys/resource.h>
 #endif
 
-#ifdef PLATFORM_MACOSX
+#if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
 #include <sys/proc.h>
 #include <sys/sysctl.h>
-#include <sys/utsname.h>
+#  if !defined(__OpenBSD__)
+#    include <sys/utsname.h>
+#  endif
 #endif
 
 #ifdef PLATFORM_SOLARIS
 #endif
 #endif
 
+#ifdef __HAIKU__
+#include <KernelKit.h>
+#endif
+
 #include <mono/io-layer/wapi.h>
 #include <mono/io-layer/wapi-private.h>
 #include <mono/io-layer/handles-private.h>
@@ -79,8 +85,10 @@ extern char **environ;
 
 static guint32 process_wait (gpointer handle, guint32 timeout);
 
+#if !defined(__OpenBSD__)
 static FILE *
 open_process_map (int pid, const char *mode);
+#endif
 
 struct _WapiHandleOps _wapi_process_ops = {
        NULL,                           /* close_shared */
@@ -1513,32 +1521,53 @@ static gboolean process_enum (gpointer handle, gpointer user_data)
 }
 #endif /* UNUSED_CODE */
 
-#ifdef PLATFORM_MACOSX
+#if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
 
 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
 {
        guint32 count, fit, i, j;
        gint32 err;
        gboolean done;
+       size_t proclength, size;
+#if defined(__OpenBSD__)
+       struct kinfo_proc2 *result;
+       int name[6];
+       name[0] = CTL_KERN;
+       name[1] = KERN_PROC2;
+       name[2] = KERN_PROC_ALL;
+       name[3] = 0;
+       name[4] = sizeof(struct kinfo_proc2);
+       name[5] = 0;
+#else
        struct kinfo_proc *result;
-       size_t proclength;
        static const int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
-       
+#endif
+
        mono_once (&process_current_once, process_set_current);
-       
+
        result = NULL;
        done = FALSE;
-       
+
        do {
                proclength = 0;
-               err = sysctl ((int *)name, (sizeof(name) / sizeof(*name)) - 1, NULL, &proclength, NULL, 0);
+#if defined(__OpenBSD__)
+               size = (sizeof(name) / sizeof(*name));
+#else
+               size = (sizeof(name) / sizeof(*name)) - 1;
+#endif
+               err = sysctl ((int *)name, size, NULL, &proclength, NULL, 0);
 
                if (err == 0) {
                        result = malloc (proclength);
+
                        if (result == NULL)
                                return FALSE;
-                       
-                       err = sysctl ((int *) name, (sizeof(name) / sizeof(*name)) - 1, result, &proclength, NULL, 0);
+
+#if defined(__OpenBSD__)
+                       name[5] = (int)(proclength / sizeof(struct kinfo_proc2));
+#endif
+
+                       err = sysctl ((int *) name, size, result, &proclength, NULL, 0);
 
                        if (err == 0) 
                                done = TRUE;
@@ -1554,11 +1583,19 @@ gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
                }
                return(FALSE);
        }       
-       
+
+#if defined(__OpenBSD__)
+       count = proclength / sizeof(struct kinfo_proc2);
+#else
        count = proclength / sizeof(struct kinfo_proc);
+#endif
        fit = len / sizeof(guint32);
        for (i = 0, j = 0; j< fit && i < count; i++) {
+#if defined(__OpenBSD__)
+               pids [j++] = result [i].p_pid;
+#else
                pids [j++] = result [i].kp_proc.p_pid;
+#endif
        }
        free (result);
        result = NULL;
@@ -1566,6 +1603,24 @@ gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
        
        return(TRUE);
 }
+#elif defined(__HAIKU__)
+
+gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
+{
+       guint32 fit, i = 0;
+       int32 cookie = 0;
+       team_info teamInfo;
+
+       mono_once (&process_current_once, process_set_current);
+
+       fit = len / sizeof (guint32);
+       while (get_next_team_info (&cookie, &teamInfo) == B_OK && i < fit) {
+               pids [i++] = teamInfo.team;
+       }
+       *needed = i * sizeof (guint32);
+
+       return TRUE;
+}
 #else
 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
 {
@@ -1650,8 +1705,15 @@ gpointer OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_
                                      process_open_compare,
                                      GUINT_TO_POINTER (pid), NULL, TRUE);
        if (handle == 0) {
+#if defined(__OpenBSD__)
+               if ((kill(pid, 0) == 0) || (errno == EPERM)) {
+#elif defined(__HAIKU__)
+               team_info teamInfo;
+               if (get_team_info ((team_id)pid, &teamInfo) == B_OK) {
+#else
                gchar *dir = g_strdup_printf ("/proc/%d", pid);
                if (!access (dir, F_OK)) {
+#endif
                        /* Return a pseudo handle for processes we
                         * don't have handles for
                         */
@@ -1829,15 +1891,24 @@ static GSList *load_modules (void)
        int i = 0;
 
        for (i = 0; i < count; i++) {
+#if SIZEOF_VOID_P == 8
+               const struct mach_header_64 *hdr;
+               const struct section_64 *sec;
+#else
                const struct mach_header *hdr;
                const struct section *sec;
+#endif
                const char *name;
                intptr_t slide;
 
                slide = _dyld_get_image_vmaddr_slide (i);
                name = _dyld_get_image_name (i);
                hdr = _dyld_get_image_header (i);
+#if SIZEOF_VOID_P == 8
+               sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
+#else
                sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
+#endif
 
                /* Some dynlibs do not have data sections on osx (#533893) */
                if (sec == 0) {
@@ -1864,6 +1935,98 @@ static GSList *load_modules (void)
        
        return(ret);
 }
+#elif defined(__OpenBSD__)
+#include <link.h>
+static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
+{
+       if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
+           + sizeof (info->dlpi_phnum))
+               return (-1);
+
+       struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
+       if (!cpy)
+               return (-1);
+
+       memcpy(cpy, info, sizeof(*info));
+
+       g_ptr_array_add ((GPtrArray *)ptr, cpy);
+
+       return (0);
+}
+
+static GSList *load_modules (void)
+{
+       GSList *ret = NULL;
+       WapiProcModule *mod;
+       GPtrArray *dlarray = g_ptr_array_new();
+       int i;
+
+       if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
+               return (ret);
+
+       for (i = 0; i < dlarray->len; i++) {
+               struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
+
+               mod = g_new0 (WapiProcModule, 1);
+               mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
+               mod->address_end = (gpointer)(info->dlpi_addr +
+                                       info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
+               mod->perms = g_strdup ("r--p");
+               mod->address_offset = 0;
+               mod->inode = (ino_t) i;
+               mod->filename = g_strdup (info->dlpi_name); 
+
+#ifdef DEBUG
+               g_message ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
+                                  mod->inode, mod->filename, mod->address_start, mod->address_end);
+#endif
+
+               free(info);
+
+               if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
+                       ret = g_slist_prepend (ret, mod);
+               } else {
+                       free_procmodule (mod);
+               }
+       }
+
+       g_ptr_array_free (dlarray, TRUE);
+
+       ret = g_slist_reverse (ret);
+
+       return(ret);
+}
+#elif defined(__HAIKU__)
+
+static GSList *load_modules (void)
+{
+       GSList *ret = NULL;
+       WapiProcModule *mod;
+       int32 cookie = 0;
+       image_info imageInfo;
+
+       while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
+               mod = g_new0 (WapiProcModule, 1);
+               mod->device = imageInfo.device;
+               mod->inode = imageInfo.node;
+               mod->filename = g_strdup (imageInfo.name);
+               mod->address_start = MIN (imageInfo.text, imageInfo.data);
+               mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
+                       (uint8_t*)imageInfo.data + imageInfo.data_size);
+               mod->perms = g_strdup ("r--p");
+               mod->address_offset = 0;
+
+               if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
+                       ret = g_slist_prepend (ret, mod);
+               } else {
+                       free_procmodule (mod);
+               }
+       }
+
+       ret = g_slist_reverse (ret);
+
+       return ret;
+}
 #else
 static GSList *load_modules (FILE *fp)
 {
@@ -2014,6 +2177,7 @@ static gboolean match_procname_to_modulename (gchar *procname, gchar *modulename
        return result;
 }
 
+#if !defined(__OpenBSD__)
 static FILE *
 open_process_map (int pid, const char *mode)
 {
@@ -2034,13 +2198,16 @@ open_process_map (int pid, const char *mode)
 
        return fp;
 }
+#endif
 
 gboolean EnumProcessModules (gpointer process, gpointer *modules,
                             guint32 size, guint32 *needed)
 {
        struct _WapiHandle_process *process_handle;
        gboolean ok;
+#if !defined(__OpenBSD__)
        FILE *fp;
+#endif
        GSList *mods = NULL;
        WapiProcModule *module;
        guint32 count, avail = size / sizeof(gpointer);
@@ -2078,7 +2245,7 @@ gboolean EnumProcessModules (gpointer process, gpointer *modules,
                proc_name = process_handle->proc_name;
        }
        
-#ifdef PLATFORM_MACOSX
+#if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
        {
                mods = load_modules ();
 #else
@@ -2126,10 +2293,12 @@ gboolean EnumProcessModules (gpointer process, gpointer *modules,
 
 static gchar *get_process_name_from_proc (pid_t pid)
 {
+#if !defined(__OpenBSD__)
+       FILE *fp;
        gchar *filename = NULL;
-       gchar *ret = NULL;
        gchar buf[256];
-       FILE *fp;
+#endif
+       gchar *ret = NULL;
 
 #if defined(PLATFORM_SOLARIS)
        filename = g_strdup_printf ("/proc/%d/psinfo", pid);
@@ -2150,6 +2319,47 @@ static gchar *get_process_name_from_proc (pid_t pid)
        proc_name (pid, buf, sizeof(buf));
        if (strlen (buf) > 0)
                ret = g_strdup (buf);
+#elif defined(__OpenBSD__)
+       int mib [6];
+       size_t size;
+       struct kinfo_proc2 *pi;
+
+       mib [0] = CTL_KERN;
+       mib [1] = KERN_PROC2;
+       mib [2] = KERN_PROC_PID;
+       mib [3] = pid;
+       mib [4] = sizeof(struct kinfo_proc2);
+       mib [5] = 0;
+
+retry:
+       if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0)
+               return(ret);
+
+       if ((pi = malloc(size)) == NULL)
+               return(ret);
+
+       mib[5] = (int)(size / sizeof(struct kinfo_proc2));
+
+       if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
+               (size != sizeof (struct kinfo_proc2))) {
+               if (errno == ENOMEM) {
+                       free(pi);
+                       goto retry;
+               }
+               return(ret);
+       }
+
+       if (strlen (pi->p_comm) > 0)
+               ret = g_strdup (pi->p_comm);
+
+       free(pi);
+#elif defined(__HAIKU__)
+       image_info imageInfo;
+       int32 cookie = 0;
+
+       if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
+               ret = g_strdup (imageInfo.name);
+       }
 #else
        memset (buf, '\0', sizeof(buf));
        filename = g_strdup_printf ("/proc/%d/exe", pid);
@@ -2215,7 +2425,9 @@ static guint32 get_module_name (gpointer process, gpointer module,
        gchar *procname_ext = NULL;
        glong len;
        gsize bytes;
+#if !defined(__OpenBSD__)
        FILE *fp;
+#endif
        GSList *mods = NULL;
        WapiProcModule *found_module;
        guint32 count;
@@ -2255,7 +2467,7 @@ static guint32 get_module_name (gpointer process, gpointer module,
        }
 
        /* Look up the address in /proc/<pid>/maps */
-#ifdef PLATFORM_MACOSX
+#if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
        {
                mods = load_modules ();
 #else
@@ -2367,7 +2579,9 @@ gboolean GetModuleInformation (gpointer process, gpointer module,
        struct _WapiHandle_process *process_handle;
        gboolean ok;
        pid_t pid;
+#if !defined(__OpenBSD__)
        FILE *fp;
+#endif
        GSList *mods = NULL;
        WapiProcModule *found_module;
        guint32 count;
@@ -2405,7 +2619,7 @@ gboolean GetModuleInformation (gpointer process, gpointer module,
                proc_name = g_strdup (process_handle->proc_name);
        }
 
-#ifdef PLATFORM_MACOSX
+#if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
        {
                mods = load_modules ();
 #else
index c36f360b14bae1dd96d3a7603db3e6e43612e69d..bf966d202c3c01f1a37590693c7e8bb104c465d0 100644 (file)
 
 static mono_mutex_t noshm_sems[_WAPI_SHARED_SEM_COUNT];
 
-#ifdef DISABLE_SHARED_HANDLES
 gboolean _wapi_shm_disabled = TRUE;
-#else
-gboolean _wapi_shm_disabled = FALSE;
-#endif
 
 static void
 noshm_semaphores_init (void)
@@ -391,11 +387,12 @@ try_again:
 static gboolean
 check_disabled (void)
 {
-       if (_wapi_shm_disabled || g_getenv ("MONO_DISABLE_SHM")) {
-               const char* val = g_getenv ("MONO_DISABLE_SHM");
-               if (val == NULL || *val == '1' || *val == 'y' || *val == 'Y') {
-                       _wapi_shm_disabled = TRUE;
-               }
+       static gboolean env_checked;
+
+       if (!env_checked) {
+               if (g_getenv ("MONO_ENABLE_SHM"))
+                       _wapi_shm_disabled = FALSE;
+               env_checked = TRUE;
        }
 
        return _wapi_shm_disabled;
index 16dcb16892f85e5b97427f34e3ca2abdbed4b01c..8e787209be10189c79fd70f444d22821c7a3a076 100644 (file)
@@ -14,6 +14,9 @@
 #include <string.h>
 #include <sys/types.h>
 #include <sys/socket.h>
+#ifdef HAVE_SYS_UIO_H
+#  include <sys/uio.h>
+#endif
 #ifdef HAVE_SYS_IOCTL_H
 #  include <sys/ioctl.h>
 #endif
index 700e77b55832c23a776250a8874a25183b262464..b61f26113517d6e76d9675d434545e44bafede6d 100644 (file)
@@ -74,6 +74,8 @@ void wapi_interrupt_thread (gpointer handle);
 void wapi_clear_interruption (void);
 gboolean wapi_thread_set_wait_handle (gpointer handle);
 void wapi_thread_clear_wait_handle (gpointer handle);
+void wapi_self_interrupt (void);
+
 char* wapi_current_thread_desc (void);
 
 G_END_DECLS
index 480db8cabf7004442377c07d2f4ede415eb35a12..684f84629e1067ee5b7a12f042fbce4c12138b7a 100644 (file)
@@ -949,33 +949,15 @@ gboolean TlsSetValue(guint32 idx, gpointer value)
        g_message ("%s: setting key %d to %p", __func__, idx, value);
 #endif
        
-       MONO_SPIN_LOCK (TLS_spinlock);
-       
-       if(TLS_used[idx]==FALSE) {
-#ifdef TLS_DEBUG
-               g_message ("%s: key %d unused", __func__, idx);
-#endif
-
-               MONO_SPIN_UNLOCK (TLS_spinlock);
-
-               return(FALSE);
-       }
        
        ret=pthread_setspecific(TLS_keys[idx], value);
-       if(ret!=0) {
 #ifdef TLS_DEBUG
+       if(ret!=0)
                g_message ("%s: pthread_setspecific error: %s", __func__,
                           strerror (ret));
 #endif
-
-               MONO_SPIN_UNLOCK (TLS_spinlock);
-
-               return(FALSE);
-       }
        
-       MONO_SPIN_UNLOCK (TLS_spinlock);
-       
-       return(TRUE);
+       return(ret == 0);
 }
 
 /**
@@ -1198,11 +1180,59 @@ void wapi_interrupt_thread (gpointer thread_handle)
        _wapi_handle_unref (wait_handle);
 }
 
+/*
+ * wapi_self_interrupt:
+ *
+ *   This is not part of the WIN32 API.
+ * Set the 'interrupted' state of the calling thread if it's NULL.
+ */
+void wapi_self_interrupt (void)
+{
+       struct _WapiHandle_thread *thread;
+       gboolean ok;
+       gpointer prev_handle, wait_handle;
+       gpointer thread_handle;
+
+
+       thread_handle = OpenThread (0, 0, GetCurrentThreadId ());
+       ok = _wapi_lookup_handle (thread_handle, WAPI_HANDLE_THREAD,
+                                                         (gpointer *)&thread);
+       g_assert (ok);
+
+       while (TRUE) {
+               wait_handle = thread->wait_handle;
+
+               /*
+                * Atomically obtain the handle the thread is waiting on, and
+                * change it to a flag value.
+                */
+               prev_handle = InterlockedCompareExchangePointer (&thread->wait_handle,
+                                                                                                                INTERRUPTION_REQUESTED_HANDLE, wait_handle);
+               if (prev_handle == INTERRUPTION_REQUESTED_HANDLE)
+                       /* Already interrupted */
+                       goto cleanup;
+               /*We did not get interrupted*/
+               if (prev_handle == wait_handle)
+                       break;
+
+               /* Try again */
+       }
+
+       if (wait_handle) {
+               /* ref added by set_wait_handle */
+               _wapi_handle_unref (wait_handle);
+       }
+
+cleanup:
+       _wapi_handle_unref (thread_handle);
+}
+
 /*
  * wapi_clear_interruption:
  *
  *   This is not part of the WIN32 API. 
  * Clear the 'interrupted' state of the calling thread.
+ * This function is signal safe
  */
 void wapi_clear_interruption (void)
 {
@@ -1324,7 +1354,8 @@ void wapi_thread_clear_wait_handle (gpointer handle)
                _wapi_handle_unref (handle);
                WAIT_DEBUG (printf ("%p: state -> NORMAL.\n", GetCurrentThreadId ()););
        } else {
-               g_assert (prev_handle == INTERRUPTION_REQUESTED_HANDLE);
+               /*It can be NULL if it was asynchronously cleared*/
+               g_assert (prev_handle == INTERRUPTION_REQUESTED_HANDLE || prev_handle == NULL);
                WAIT_DEBUG (printf ("%p: finished waiting.\n", GetCurrentThreadId ()););
        }
 
index bb234610d0871e85d3212a7a8bcc4f41912b53f4..9a5c6cdea1c728a1d13bedcd95515a4cacb5e11a 100644 (file)
@@ -11,3 +11,4 @@
 /semantic.cache
 /.project
 /.cproject
+/TAGS
index cba5effa4ee2afe9f02606fb6fe5476efbe0939c..2ce2441fd24915d3a946bec391ffaddef8916b6c 100644 (file)
@@ -1,3 +1,824 @@
+2010-04-27  Mark Probst  <mark.probst@gmail.com>
+
+       * sgen-gc.c, sgen-marksweep.c, sgen-major-copying.c: Don't do a
+       separate pass to scan pinned and large object but use the gray
+       queue like for regular objects.
+
+2010-04-26  Zoltan Varga  <vargaz@gmail.com>
+
+       * boehm-gc.c: Applied patch from Robert Nagy (robert@openbsd.org). Include
+       string.h for memmove.
+
+       socket-io.c: Applied patch from Robert Nagy (robert@openbsd.org).
+       ipaddress_to_struct_in6_addr() is only needed when
+       defined(HAVE_STRUCT_IP_MREQN) || defined(HAVE_STRUCT_IP_MREQ).
+
+2010-04-25  Mark Probst  <mark.probst@gmail.com>
+
+       * sgen-gc.c, sgen-marksweep.c, sgen-major-copying.c: Properly
+       separate copy_object functions for major vs nursery.  Allows us to
+       get rid of a few checks and the start and end parameters for many
+       functions.
+
+2010-04-25  Mark Probst  <mark.probst@gmail.com>
+
+       * sgen-marksweep.c, sgen-gc.c, sgen-major-copying.c,
+       sgen-protocol.c, sgen-protocol.h, Makefile.am: Major Mark&Sweep
+       collector.
+
+2010-04-25  Zoltan Varga  <vargaz@gmail.com>
+
+       * class.c (mono_class_create_from_typedef): Initialize class->nested_in after
+       calling setup_mono_type () since the nested parent could recursively reference
+       the nested class using generic constraints. Fixes #599469.
+
+2010-04-24  Mark Probst  <mark.probst@gmail.com>
+
+       * sgen-gc.c, sgen-pinning.c, sgen-major-copying.c: Major collector
+       abstraction.
+
+2010-04-24  Mark Probst  <mark.probst@gmail.com>
+
+       * sgen-gc.c: Remove more unneeded code.
+
+2010-04-24  Mark Probst  <mark.probst@gmail.com>
+
+       * sgen-gc.c: Disable managed allocator and wbarrier when the
+       binary protocol is enabled.
+
+2010-04-24  Mark Probst  <mark.probst@gmail.com>
+
+       * sgen-gc.c: Put nursery-fragment-cleaning into its own function.
+
+2010-04-24  Mark Probst  <mark.probst@gmail.com>
+
+       * sgen-gc.c: Remove a few commented out and unneeded bits.
+
+2010-04-23 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * threadpool.c: patch from Robert Nagy that fixes a nullref and
+       uses mono_sem_wait instead of mono_sem_timedwait for openbsd.
+
+2010-04-20 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * icall.c (ves_icall_type_is_assignable_from): Properly handle byref
+       types.
+
+       Fixes #331126
+
+2010-04-21  Mark Probst  <mark.probst@gmail.com>
+
+       * sgen-gc.c: Turn off semi-precise stack mark.
+
+2010-04-20  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * reflection.c (mono_custom_attrs_from_index): Use right function
+       to free 'list' (i.e. g_list_free) if the verifier fails.
+
+2010-04-19 Rodrigo Kumpera  <rkumpera@novell.com>
+
+               * verify.c: Handle the case where mono_type_get_underlying_type_any
+               returns NULL. Remove duplicated code between MONO_TYPE_GENERICINST
+               and MONO_TYPE_VALUETYPE in those case.
+
+               Based on a slightly modified patch by Sebastien Pouliot  <sebastien@ximian.com>
+
+               Hopefully Fixes #564253.
+
+2010-04-19 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * domain-internals.h: made threadpool_jobs volatile.
+       * mono-wsq.c: add an assert to verify that the threadpool cleaned up
+       all local jobs.
+       * threadpool.c:
+               -When two threads try to initialize the socket IO pool,
+               the second one waits until the intialization is finished
+               instead of continuing right away.
+               -Add checks for domain unload: no items added in this case.
+               -Only measure the time every 10 elements added to the queue.
+               This is an experiment since linux x86 gettimeofday() sucks.
+               -Create new thread if there are none waiting for work items.
+               -There was a missing decrement of the busy threads.
+               -Make sure the local queue is cleaned up before exiting the
+               thread when the program ends.
+
+2010-04-19 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * reflection.c (mono_type_get_object): Normalize generics types
+       as to how managed code expect them to be. A generic instance over
+       the GTD arguments must have the same mirror as the GTD itself.
+
+       Fixes #473289.
+
+2010-04-19  Zoltan Varga  <vargaz@gmail.com>
+
+       * locales.c: Implement support for DISABLE_NORMALIZATION.
+
+2010-04-16  Zoltan Varga  <vargaz@gmail.com>
+
+       * marshal.c (mono_marshal_get_native_func_wrapper): Set the marshal info to NULL,
+       since it is not a MonoMethod.
+
+2010-04-16  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * icall-def.h: Add get_RequiresElevatedPermissions icall to
+       System.Security.SecurityManager - used only by Moonlight
+       * security-core-clr.c|h: Add Elevated Trust/Permission support
+       for CoreCLR / Moonlight
+
+2010-04-16  Zoltan Varga  <vargaz@gmail.com>
+
+       * boehm-gc.c (mono_gc_base_init): Applied patch from Robert Nagy
+       (robert@openbsd.org). Fix GC_stackbottom calculation on OpenBSD.
+
+2010-04-16  Marek Habersack  <mhabersack@novell.com>
+
+       * mono-perfcounters.c: added code for the "Mono
+       Memory/Total Physical Memory" performance counter.
+
+       * mono-perfcounters-def.h: added definition of the "Mono
+       Memory/Total Physical Memory" performance counter.
+
+2010-04-15 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * class.c (mono_class_get_method_by_index): Return NULL
+       on type load failures.
+
+2010-04-15 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * class.c (mono_class_from_typeref): Check if the supplied
+       image has an assembly bound to it.
+
+       Fixes #567884.
+
+2010-04-15 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * loader.c (mono_method_get_signature_full): Use new function
+       inflate_generic_signature_checked to check for errors.
+
+       Fixes #560839.
+
+2010-04-15 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * loader.c (inflate_generic_signature): Add _checked variant
+       and move this function to use it.
+
+2010-04-15 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * class.c (mono_class_setup_vtable_general): Use error checking
+       version of mono_class_inflate_generic_method_full.
+
+       Fixes #596975.
+
+2010-04-15 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * class.c (mono_class_inflate_generic_type_no_copy): Do proper
+       error handling passing MonoError around.
+
+       Fixes #560336.
+
+2010-04-14 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * socket-io.c: make GetHostByName ("") work on windows.
+       Fixes bug #456723.
+
+2010-04-14 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * object-internals.h:
+       * threads.c: use a spin lock when accesing the per-thread appdomain
+       list.
+
+2010-04-14 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * threads.c: no need to take the threads lock in push/pop appdomain.
+
+2010-04-14 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * reflection.c (_mono_reflection_parse_type): MS supports
+       non-assembly-qualified types in a generic type parameter list
+       when enclosed in '[]' (which signals that they should be a fqn).
+
+       This breaks ECMA specs for how type names are encoded in cattr
+       blobs but F# does it.
+
+       Fixes #576342.
+
+2010-04-14 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * icall.c (ves_icall_InternalInvoke): Check if the vtable is sane
+       for instance methods/ctors.
+
+       Fixes #422113.
+
+2010-04-13 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * reflection.c: Use the new verifier support for checking
+       custom attributes.
+
+       Fixes #595306.
+
+2010-04-13 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * metadata-verify.c: Implement structural verification
+       of custom attributes. This check requires access to the
+       loader since to resolve the size of an enum we have to
+       look it up.
+       We don't check if named argumenments are encoded in a
+       compatible fashion to their underlying field/prop.
+       Maybe we should?
+
+       * verify-internals.h: Add two new cattr verification API.
+
+2010-04-13 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * metadata-verify.c (decode_signature_header): Fix signature.
+
+2010-04-13 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * verify.c (mono_verifier_is_enabled_for_method): Handle
+       assembly less images.
+
+       * verify.c (mono_verifier_is_class_full_trust): Ditto.
+
+2010-04-13 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * loader.c (mono_method_signature_checked): Properly
+       init MonoError.
+
+       * loader.c (mono_method_signature): It's the calee
+       resposibility to init the error object.
+
+2010-04-13 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * metadata-verify.c (decode_signature_header): Do proper
+       overflow checking.
+
+Tue Apr 13 12:36:29 CEST 2010 Paolo Molaro <lupus@ximian.com>
+
+       * reflection.c: maintain the invariants required by
+       mono_class_layout_fields() also in typebuilder_setup_fields ().
+
+2010-04-11  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * security-core-clr.c: Call mono_class_setup_methods in 
+       get_default_ctor before checking klass->methods. Fix typo in
+       comment
+
+2010-04-10  Jb Evain  <jbevain@novell.com>
+
+       * domain.c (supported_runtimes): remove .net 4.0 beta 2 and
+       add .net 4.0 RTM version.
+
+2010-04-09 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * reflection.c (resolve_object): Properly inflate generic
+       methods when a context is supplied.
+
+       Fixes #591226.
+
+2010-04-09 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * verify.c (mono_method_verify): A switch op don't empty
+       the stack for the next one. Fixes a bug when running fsi
+       under --verify-all.
+
+2010-04-09 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * metadata-verify.c (is_valid_standalonesig_blob): Accept
+       fields as valid standalone sig too. F# does generate them.
+
+       * metadata-verify.c (verify_typedef_table_full): Ignore
+       what <module> extends.
+
+2010-04-09 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * verify.c (do_invoke_method): It's ok to do use call with
+       virtual, non-final methods if their class is sealed.
+
+2010-04-08 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * icall.c (ves_icall_MonoField_GetValueInternal): This function
+       is a near identical copy of mono_field_get_value_object. So simply
+       call it.
+
+       * object.c (mono_field_get_value_object): Handle literal fields
+       on open generic classes.
+
+       Fixes #594942.
+
+2010-04-08 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * reflection.c (mono_reflection_create_runtime_class): Setup
+       parent/supertype information again since it can be changed
+       without notice.
+
+2010-04-07 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * verify.c (verify_type_compatibility_full): Properly handle
+       stores between arrays of primitives.
+
+       Fixes the verifier side of #555950.
+
+2010-04-07 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       class.c (mono_bounded_array_class_get): Properly init
+       cast_class to take the fact that uint[] and int[] can be
+       casted between each other.
+
+       Fixes #555950.
+
+2010-04-07  Geoff Norton  <gnorton@novell.com>
+
+       * domain.c: Avoid a deadlock on osx.  Fixes #565765
+
+2010-04-08  Zoltan Varga  <vargaz@gmail.com>
+
+       * icall.c (ves_icall_System_Enum_ToObject): Avoid a crash for unfinished type
+       builders. Fixes #594464.
+
+2010-04-08  Zoltan Varga  <vargaz@gmail.com>
+
+       * icall.c (ves_icall_System_Environment_Exit): Shutdown the threadpool before
+       waiting for all threads to suspend, as those threads can't be suspended.
+
+2010-04-08  Zoltan Varga  <vargaz@gmail.com>
+
+       * threads.c (mono_thread_suspend_all_other_threads): Call ensure_synch_cs_set ()
+       to avoid crashes on newly created threads.
+
+2010-04-07 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * file-io.c: reset the MonoIOStat structure in case of error.
+       Fixes bug #582667.
+
+2010-04-06 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * class.c (print_implemented_interfaces): Print proper type name.
+
+       * class.c (mono_class_setup_vtable): Don't try that hard to produce
+       the override map for generic instances since it later ignored.
+
+       * class.c (mono_class_implement_interface_slow): Don't break for
+       dynamic generic instances.
+
+       * object.c (mono_runtime_invoke_array): Add an assert for allocation.
+
+       * reflection.c (mono_reflection_method_get_handle): New method that
+       resolves a method handle.
+
+       * reflection.c (mono_reflection_get_dynamic_overrides): Handle the
+       case when we override methods from a dynamic generic instance interface.
+
+       Fixes #575941.
+
+2010-04-05 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * threadpool.c: don't attempt to close the pipe when it has not been
+       created.
+
+2010-04-05 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * threadpool.c: if there are no waiting threads, try to start a new
+       one. This fixes the not-so-random hangs in System.ServiceModel tests.
+       No need to use InterlockedCompareExchange to read volatile variables.
+
+2010-04-05 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * verify.c (verify_type_compatibility_full): Fail mixed valuetype
+       and reference types that point to the same class.
+
+       Fixes #565598.
+
+2010-04-05 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * verify.c (verify_stack_type_compatibility_full): Ignore constraints
+       when verifying compatibility between a generic instance and a generic
+       parameter.
+
+       * verify.c (check_is_valid_type_for_field_ops): Improve error message.
+
+       * verify.c (stack_slot_stack_type_full_name): Improve verification type
+       name.
+
+       Fixes #587849.
+
+2010-04-04  Mark Probst  <mark.probst@gmail.com>
+
+       * sgen-gc.c: Remove superfluous scanning of alloc-pinned objects.
+
+2010-04-04  Zoltan Varga  <vargaz@gmail.com>
+
+       * threads.c Applied some openbsd changes from Robert Nagy <robert@openbsd.org>.
+
+2010-04-03  Marek Habersack  <mhabersack@novell.com>
+
+       * process.c: when cross-compiling with MinGW, force GetProcessId
+       lookup using GetProcAddress.
+
+2010-04-02  Mark Probst  <mark.probst@gmail.com>
+
+       * sgen-gc.c: parse_environment_string_extract_number() must be
+       static.
+
+2010-04-02  Mark Probst  <mark.probst@gmail.com>
+
+       * sgen-gc.c, sgen-gray.c: Macros for gray_object_enqueue() and
+       gray_object_dequeue(), to make sure they're inlined.
+
+2010-04-02  Mark Probst  <mark.probst@gmail.com>
+
+       * sgen-gc.c, sgen-gray.c: Fix a few debug levels, put a few
+       asserts in inner loops into DEBUG and lower MAX_DEBUG_LEVEL.
+
+2010-04-02  Jb Evain  <jbevain@novell.com>
+
+       * exception.c: remove dead code.
+
+2010-04-02  Zoltan Varga  <vargaz@gmail.com>
+
+       * *-gc.c: Fix the signature of mono_gc_get_used/heap_size () to be consistent
+       with mono-gc.h.
+
+2010-04-01  Sanjoy Das <sanjoy@playingwithpointers.com>
+
+       * sgen-gc.c: Make the nursery size adjustable by the
+       MONO_GC_PARAMS environment variable.
+
+       Code is contributed under MIT/X11 license.
+
+2010-04-01 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * threadpool.c: threadpool threads wait is alertable.
+       Fixes bug #592964.
+       Reduced the stack size of the *poll_wait thread.
+
+2010-04-01  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * exception.c|metadata-internals.h: Add new mono_get_exception_
+       field_access_msg and mono_get_exception_method_access_msg 
+       functions that accept a const char* parameter to provide more 
+       details when the exception is thrown.
+       * security-core-clr.c|h: Rework code to allow logging exceptions
+       (export MONO_LOG_MASK="security") and to supply more details in
+       [TypeLoad|MethodAccess|FieldAccess]Exception thrown. Also added
+       mono_security_core_clr_is_field_access_allowed and 
+       mono_security_core_clr_is_call_allowed to return an exception,
+       with messages and logging, that can be emitted by method-to-ir.c
+
+2010-04-01  Mark Probst  <mark.probst@gmail.com>
+
+       * sgen-gc.c, sgen-pinning-stats.c: In the heap-dump, dump each
+       pinned object.
+
+2010-04-01  Zoltan Varga  <vargaz@gmail.com>
+
+       * appdomain.c (mono_domain_assembly_postload_search): Avoid a crash/assert if
+       the assembly name is not well formed utf8. Fixes #567882.
+
+2010-04-01  Zoltan Varga  <vargaz@gmail.com>
+
+       * reflection.c (mono_reflection_create_generic_class): Set the flags field of
+       the generic parameters from the builder. Fixes #473298.
+
+2010-03-31  Miguel de Icaza  <miguel@novell.com>
+
+       * object.c (mono_class_proxy_vtable): Eliminate warning. 
+
+       * marshal.c (emit_marshal_boolean): Eliminate possible
+       uninitialized local warning. 
+
+2010-03-30  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * class.c (mono_class_init): Postpone coreclr inheritance check
+       until the end of the initialization (so we can check up the 
+       default ctor manually for the core-clr inheritance rules).
+       * security-core-clr.c: Add the missing (undocumented) checks on
+       default constructors when verifying inheritance rules.
+
+2010-03-30 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * domain-internals.h (MonoJitExceptionInfo): Add new field
+       handler_end to the data union. To be used to point the end
+       of a finally block.
+
+2010-03-30 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * reflection.c: Add support for new v4 type
+       System.Reflection.MonoModule that is the concrete version
+       of Module which is abstract unver v4.
+
+2010-03-30 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * class.c (mono_class_init): Don't set class failure after
+       inited = 1 is set. It must be done before.
+
+2010-03-30  Andreas Färber  <andreas.faerber@web.de>
+
+       * mono-config.c: Add support for OS "haiku"
+       * ChangeLog: Fix UTF-8 encoding
+
+       Code is contributed under MIT/X11 license.
+
+Tue Mar 30 15:53:06 CEST 2010 Paolo Molaro <lupus@ximian.com>
+
+       * console-unix.c: fixed include logic for sys/ioctl.h.
+
+2010-03-30  Mark Probst  <mark.probst@gmail.com>
+
+       * threads.c: Fix bitmap generation for TLS marking on 64 bit
+       systems.
+
+2010-03-30  Zoltan Varga  <vargaz@gmail.com>
+
+       * icall.c (ves_icall_System_Enum_get_underlying_type): Don't crash on
+       unfinished/broken typebuilders.
+
+2010-03-29  Mark Probst  <mark.probst@gmail.com>
+
+       * sgen-gc.c: Use the same heuristic for the LOS target that we use
+       for the minor section allowance.
+
+2010-03-29  Raja R Harinath  <harinath@hurrynot.org>
+
+       * metadata-verify.c (INVALID_METHOD_IMPLFLAG_BITS): Allow bit 6
+       "NoOptimization".
+
+2010-03-29  Mark Probst  <mark.probst@gmail.com>
+
+       * sgen-gc.c: Count bytes allocated with heavy statistics.
+
+2010-03-29  Mark Probst  <mark.probst@gmail.com>
+
+       * sgen-gc.c: More detailed time statistics.
+
+Mon Mar 29 11:52:34 CEST 2010 Paolo Molaro <lupus@ximian.com>
+
+       * gc-internal.h, sgen-gc.c, threads.c, utils/mono-hash.c:
+       fix the user defined mark interface to pass a pointer
+       to the object location and not the object itself.
+
+2010-03-27 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * reflection.c (mono_method_body_get_object): Release
+       the method header before the call to CACHE_OBJECT since
+       this is a macro that returns.
+
+2010-03-26 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * class.c (inflate_generic_type): mono_metadata_type_dup
+       already dupes array information, the g_memdup was just
+       leaking memory.
+
+2010-03-26 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * verify.c: Add stack_peek function. Fix CEE_DUP
+       to not read from invalid memory if push did expand
+       the stack.
+
+2010-03-26 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * verify.c: Remove old table verification code that has
+       been superseeded by the new metadata verifier.
+
+       * verify.h: Remove mono_image_verify_tables from the public
+       API.
+
+       * pedump.c: Fix for removed bits.
+
+2010-03-26 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * verify.c: Allocate stack slows lazily to reduce stack usage
+       in case of methods with huge stacks. Reduces memory consumption
+       for mcs yyparse from 459Mb to 1.8Mb.
+
+2010-03-26 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * threadpool.c: don't try executing items from domains being
+       unloaded. Fixes appdomain-async-invoke test.
+
+2010-03-26 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * threadpool.c: spin while the threadpool initializes.
+       * mono-wsq.c: if the WSQ has not been initialized or has been shut
+       down, don't do anything.
+
+2010-03-26  Zoltan Varga  <vargaz@gmail.com>
+
+       * threads.c (mono_thread_create_internal): Set the GC type of the
+       threads_starting_up hash table.
+
+2010-03-26 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * threadpool.c: reset 'state' to avoid returning non-null when the
+       event type is not found.
+
+Fri Mar 26 19:03:09 CET 2010 Paolo Molaro <lupus@ximian.com>
+
+       * sgen-gc.c: make copy_object () take the address of the
+       slot holding the reference. This allows saving memory stores
+       when not needed and it allows keeping track of oldspace->nursery
+       references for the card table code.
+
+2010-03-26  Andreas Färber  <andreas.faerber@web.de>
+
+       * null-gc.c (mono_gc_invoke_with_gc_lock): Fix function name.
+
+       Code is contributed under MIT/X11 license.
+
+Fri Mar 26 11:33:17 CET 2010 Paolo Molaro <lupus@ximian.com>
+
+       * object.c, threads.c, threads-types.h, threads.h: make the
+       managed thread local storage references precisely tracked.
+
+2010-03-25 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * threadpool.[ch]: reworked the threadpool:
+               -Threadpool threads use a work-stealing queue. Adding a work
+               item from a threadpool thread will queue it in the thread
+               local queue without locking (in most cases).
+               -epoll events are coalesced before being added to the IO
+               queue.
+               -Dynamically change the number of active threads
+               -Changed the global queue to be more GC friendly
+
+       * class-internals.h: add 2 new performance counters for the number of
+       threads in the threadpool and the IO threadpool.
+
+       * object-internals.h: new field in MonoAsyncResult.
+       * icall-def.h: new internal call for queueing work items.
+
+       * Makefile.am: add 2 new files.
+
+       * appdomain.c: bump up corlib version.
+
+       * mono-wsq.[ch]: an implementation of a work-stealing queue.
+
+       * mono-perfcounters-def.h:
+       * mono-perfcounters.c: added 2 new performance counters.
+
+2010-03-26  Mark Probst  <mark.probst@gmail.com>
+
+       * sgen-gc.c: More FIXME/TODO updates.
+
+2010-03-25  Mark Probst  <mark.probst@gmail.com>
+
+       * gc-internal.h, sgen-gc.c, sgen-gc.h, boehm-gc.c, null-gc.c: New
+       function mono_gc_invoke_with_gc_lock() which invokes a function
+       with the guarantee that no collection will occur during its execution.
+
+2010-03-25  Mark Probst  <mark.probst@gmail.com>
+
+       * sgen-gc.c: Update a few comments.
+
+2010-03-24 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * reflection.c: Add support for new v4 type
+       System.Reflection.MonoAssembly that is the concrete version
+       of Assembly which is abstract unver v4.
+
+2010-03-24  U-anarquia\miguel  <miguel@anarquia>
+
+       * reflection.c (mono_reflection_get_custom_attrs_info): Protect
+       code that uses System.Reflection.Emit in DISABLE_REFLECTION_EMIT.
+
+       Expose a few macros that are needed for SR but not SRE to the
+       world (previous inside the SRE ifdef)
+
+2010-03-24  Mark Probst  <mark.probst@gmail.com>
+
+       * sgen-gc.c (gc_register_current_thread): We need
+       stack_start_limit as well in the non-attribute pthread case.
+
+2010-03-23 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * threads.c: Fix windows build.
+
+2010-03-22 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * thread-types.h: Add mono_thread_resume_interruption.
+
+       * threads.c: Add mono_thread_resume_interruption, this
+       function should be called after the last protected handler
+       found at interruption time has finished.
+
+2010-03-22 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * threads.c (ves_icall_System_Threading_Thread_ResetAbort):
+       Check MonoInternalThread's ::state instead of ::abort_exc
+       since the later can be lazily created.
+
+       This is specially problematic when running a finally block
+       under AbortRequested state. ResetAbort must work, but the
+       abort_exc object has not been created because interruption
+       has not began.
+
+2010-03-22  Geoff Norton  <gnorton@novell.com>
+
+       * locales.c: Its possible for CFStringGetCStringPtr
+       to return null and not convert encodings.  Use
+       CFStringGetCString instead.
+
+Mon Mar 22 18:06:38 CET 2010 Paolo Molaro <lupus@ximian.com>
+
+       * class-internals.h, class.c, object.c: introduce compressed
+       interface bitmaps (for now only under small config): this saves
+       about 600 KB of runtime memory on gmcs bootstraps or monodevelop
+       startups.
+
+Mon Mar 22 16:03:34 CET 2010 Paolo Molaro <lupus@ximian.com>
+
+       * mono-debug.c: don't try to get the method header, it causes a
+       deadlock and it is not used for anything anymore.
+
+2010-03-22  Zoltan Varga  <vargaz@gmail.com>
+
+       * loader.c (mono_method_get_marshal_info): Fix the handling of dynamic methods
+       broken by the last change.
+
+2010-03-21  Andreas Färber  <andreas.faerber@web.de>
+
+       * socket-io.c: Don't depend on AF_SNA, AF_DECnet,
+       SOCK_RDM.
+       
+       Code is contributed under MIT/X11 license.
+
+2010-03-20  Sanjoy Das <sanjoy@playingwithpointers.com>
+
+       * sgen-gc.c (mono_gc_get_write_barrier): Handle non-aligned
+       nursery.
+
+       Code is contributed under MIT/X11 license.
+
+2010-03-19  Martin Baulig  <martin@ximian.com>
+
+       * mono-debug.c (MonoDebugWrapperData): Replace `cil_code' with a
+       dummy field, containing an empty string.
+       (mono_debug_add_method): Don't call mono_disasm_code() for wrappers.
+
+
+Fri Mar 19 17:26:43 CET 2010 Paolo Molaro <lupus@ximian.com>
+
+       * class.c: setup_interface_offsets() refactor to not call
+       mono_class_get_implemented_interfaces () more times than needed and
+       to reduce the runtime memory requirements to be O(num_interfaces)
+       instead of O(max_interface_id).
+
+2010-03-18 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * mono-mlist.[ch]: add mono_mlist_set_next ().
+
+2010-03-16 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * domain-internals.h: Add MonoTryBlockHoleJitInfo struct and
+       associated changes to support holes in the protected range of a
+       try block.
+
+       * domain.c: Add mono_jit_info_get_try_block_hole_table_info, which
+       retrieves the holes table from a given MonoJitInfo.
+
+Tue Mar 16 13:11:15 CET 2010 Paolo Molaro <lupus@ximian.com>
+
+       * object.h, object-internals.h, object.c, icall.c, gc-internal.h,
+       debug-helpers.c, cominterop.c, process.c, sgen-gc.c, socket-io.c:
+       hide the contents of the MonoString and MonoArray structs from the
+       public API. Change the accessor macros to accessors functions where
+       needed. Adjusted the array API to allow for pointer-sized lengths and
+       starting positions, so 64 bit arrays can be optionally provided in an
+       API compatible way if needed on 64 bit systems.
+
+Tue Mar 16 10:18:07 CET 2010 Paolo Molaro <lupus@ximian.com>
+
+       * class-internals.h, class.c, loader.c, marshal.c, metadata.c,
+       reflection.c: the MonoMethodNormal struct is now unused, so remove it.
+
+Mon Mar 15 18:28:00 CET 2010 Paolo Molaro <lupus@ximian.com>
+
+       * class-internals.h: remove the method header from MonoMethod since
+       from now on it will be transient. We have a header pointer for method
+       wrappers, since in that case we need to keep track of it. For this
+       reason, all the Reflection.Emit generated methods use MonoMethodWrapper
+       structs now. The same happens with MonoMethodInflated.
+       * class.c: reset the sre_method flag for inflated method structures:
+       this makes the code that cares look at the header in the MonoMethodInflated
+       structure.
+       * loader.c: lookup the method header in the appropriate field now that
+       it is removed from MonoMethod.
+       * metadata-internals.h: add a flag to the method header to know if it
+       can be freed inside mono_metadata_free_mh ().
+       * method-builder.c: updates after moving the header field from
+       MonoMethod to MonoMethodWrapper.
+       * reflection.c: MonoMethods generated from Reflection.Emit use
+       MonoMethodWrapper structs if they need a method header now (later take
+       advantage of this and remove all the current unsafe uses of method_aux_hash).
+       * metadata.c: make method header parsing not leak when verification
+       fails. Alloc it with g_malloc() and free it in mono_metadata_free_mh().
+       These changes save a few hundred KB of runtime memory in a mcs
+       bootstrap or a monodevelop startup.
+
+2010-03-12 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * verify.c: Improve error message.
+
 2010-03-12  Jb Evain  <jbevain@novell.com>
 
        * reflection.c (add_exported_type): populate the exported
index 7a1e5cfed45637082c99bd28ade1999782630ace..4643d979c5a01e9ab3da34ff3cbe2c8db658fed0 100644 (file)
@@ -59,7 +59,8 @@ null_sources = \
 sgen_sources = \
        sgen-gray.c     \
        sgen-pinning.c  \
-       sgen-pinning-stats.c
+       sgen-pinning-stats.c    \
+       sgen-marksweep.c
 
 libmonoruntime_la_SOURCES = \
        $(platform_sources)     \
@@ -128,6 +129,8 @@ libmonoruntime_la_SOURCES = \
        mono-perfcounters.c     \
        mono-perfcounters.h     \
        mono-perfcounters-def.h \
+       mono-wsq.c              \
+       mono-wsq.h              \
        monitor.c               \
        monitor.h               \
        normalization-tables.h  \
index d922fb71b2e485b70264ed5690e3ebbc6bac3c7a..13a3d5f54d9560fd569e7ff2ca63b74224d73837 100644 (file)
@@ -73,7 +73,7 @@
  * Changes which are already detected at runtime, like the addition
  * of icalls, do not require an increment.
  */
-#define MONO_CORLIB_VERSION 89
+#define MONO_CORLIB_VERSION 90
 
 typedef struct
 {
@@ -950,12 +950,17 @@ mono_domain_assembly_postload_search (MonoAssemblyName *aname,
        MonoReflectionAssembly *assembly;
        MonoDomain *domain = mono_domain_get ();
        char *aname_str;
+       MonoString *str;
 
        aname_str = mono_stringify_assembly_name (aname);
 
        /* FIXME: We invoke managed code here, so there is a potential for deadlocks */
-       assembly = mono_try_assembly_resolve (domain, mono_string_new (domain, aname_str), refonly);
-
+       str = mono_string_new (domain, aname_str);
+       if (!str) {
+               g_free (aname_str);
+               return NULL;
+       }
+       assembly = mono_try_assembly_resolve (domain, str, refonly);
        g_free (aname_str);
 
        if (assembly)
@@ -2369,7 +2374,7 @@ mono_domain_try_unload (MonoDomain *domain, MonoObject **exc)
                        *exc = (MonoObject *) mono_get_exception_cannot_unload_appdomain ("Appdomain is already unloaded.");
                        return;
                default:
-                       g_warning ("Incalid appdomain state %d", prev_state);
+                       g_warning ("Invalid appdomain state %d", prev_state);
                        g_assert_not_reached ();
                }
        }
index 4f1fd91227fd05c8333e85fb643606d21811ba16..c1f38cdbc43dc0728768b4dbc73d3d53805f6592 100644 (file)
@@ -6,6 +6,9 @@
  */
 
 #include "config.h"
+
+#include <string.h>
+
 #define GC_I_HIDE_POINTERS
 #include <mono/metadata/gc-internal.h>
 #include <mono/metadata/mono-gc.h>
@@ -85,6 +88,17 @@ mono_gc_base_init (void)
        }
 #elif defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
                GC_stackbottom = (char*)pthread_get_stackaddr_np (pthread_self ());
+#elif defined(__OpenBSD__)
+#  include <pthread_np.h>
+       {
+               stack_t ss;
+               int rslt;
+
+               rslt = pthread_stackseg_np(pthread_self(), &ss);
+               g_assert (rslt == 0);
+
+               GC_stackbottom = (char*)ss.ss_sp;
+       }
 #else
        {
                int dummy;
@@ -153,13 +167,13 @@ mono_gc_add_memory_pressure (gint64 value)
 {
 }
 
-gint64
+int64_t
 mono_gc_get_used_size (void)
 {
        return GC_get_heap_size () - GC_get_free_bytes ();
 }
 
-gint64
+int64_t
 mono_gc_get_heap_size (void)
 {
        return GC_get_heap_size ();
@@ -932,5 +946,11 @@ mono_gc_get_write_barrier (void)
 
 #endif
 
+void*
+mono_gc_invoke_with_gc_lock (MonoGCLockedCallbackFunc func, void *data)
+{
+       return GC_call_with_alloc_lock (func, data);
+}
+
 #endif /* no Boehm GC */
 
index 114c8ccbc41966f9fc296db124ccebfe5f449e8f..b6e0197afdd6262635d95833356d779762c40b4a 100644 (file)
@@ -19,7 +19,6 @@ extern gboolean mono_print_vtable;
 
 typedef void     (*MonoStackWalkImpl) (MonoStackWalk func, gboolean do_il_offset, gpointer user_data);
 
-typedef struct _MonoMethodNormal MonoMethodNormal;
 typedef struct _MonoMethodWrapper MonoMethodWrapper;
 typedef struct _MonoMethodInflated MonoMethodInflated;
 typedef struct _MonoMethodPInvoke MonoMethodPInvoke;
@@ -68,13 +67,14 @@ struct _MonoMethod {
        unsigned int string_ctor:1;
        unsigned int save_lmf:1;
        unsigned int dynamic:1; /* created & destroyed during runtime */
+       unsigned int sre_method:1; /* created at runtime using Reflection.Emit */
        unsigned int is_generic:1; /* whenever this is a generic method definition */
        unsigned int is_inflated:1; /* whether we're a MonoMethodInflated */
        unsigned int skip_visibility:1; /* whenever to skip JIT visibility checks */
        unsigned int verification_success:1; /* whether this method has been verified successfully.*/
        /* TODO we MUST get rid of this field, it's an ugly hack nobody is proud of. */
        unsigned int is_mb_open : 1;            /* This is the fully open instantiation of a generic method_builder. Worse than is_tb_open, but it's temporary */
-       signed int slot : 17;
+       signed int slot : 16;
 
        /*
         * If is_generic is TRUE, the generic_container is stored in image->property_hash, 
@@ -82,13 +82,9 @@ struct _MonoMethod {
         */
 };
 
-struct _MonoMethodNormal {
+struct _MonoMethodWrapper {
        MonoMethod method;
        MonoMethodHeader *header;
-};
-
-struct _MonoMethodWrapper {
-       MonoMethodNormal method;
        void *method_data;
 };
 
@@ -370,8 +366,12 @@ struct _MonoClass {
        guint16     interface_offsets_count;
        MonoClass **interfaces_packed;
        guint16    *interface_offsets_packed;
+/* enabled only with small config for now: we might want to do it unconditionally */
+#ifdef MONO_SMALL_CONFIG
+#define COMPRESSED_INTERFACE_BITMAP 1
+#endif
        guint8     *interface_bitmap;
-       
+
        MonoClass **interfaces;
 
        union {
@@ -426,7 +426,16 @@ struct _MonoClass {
        MonoClassExt *ext;
 };
 
-#define MONO_CLASS_IMPLEMENTS_INTERFACE(k,uiid) (((uiid) <= (k)->max_interface_id) && ((k)->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7))))
+#ifdef COMPRESSED_INTERFACE_BITMAP
+int mono_compress_bitmap (uint8_t *dest, const uint8_t *bitmap, int size) MONO_INTERNAL;
+int mono_class_interface_match (const uint8_t *bitmap, int id) MONO_INTERNAL;
+#else
+#define mono_class_interface_match(bmap,uiid) ((bmap) [(uiid) >> 3] & (1 << ((uiid)&7)))
+#endif
+
+#define MONO_CLASS_IMPLEMENTS_INTERFACE(k,uiid) (((uiid) <= (k)->max_interface_id) && mono_class_interface_match ((k)->interface_bitmap, (uiid)))
+
+
 int mono_class_interface_offset (MonoClass *klass, MonoClass *itf);
 int mono_class_interface_offset_with_variance (MonoClass *klass, MonoClass *itf, gboolean *non_exact_match) MONO_INTERNAL;
 
@@ -457,7 +466,7 @@ struct MonoVTable {
 
 #define MONO_SIZEOF_VTABLE (sizeof (MonoVTable) - MONO_ZERO_LEN_ARRAY * SIZEOF_VOID_P)
 
-#define MONO_VTABLE_IMPLEMENTS_INTERFACE(vt,uiid) (((uiid) <= (vt)->max_interface_id) && ((vt)->interface_bitmap [(uiid) >> 3] & (1 << ((uiid)&7))))
+#define MONO_VTABLE_IMPLEMENTS_INTERFACE(vt,uiid) (((uiid) <= (vt)->max_interface_id) && mono_class_interface_match ((vt)->interface_bitmap, (uiid)))
 
 /*
  * Generic instantiation data type encoding.
@@ -499,9 +508,9 @@ struct _MonoGenericContext {
 struct _MonoMethodInflated {
        union {
                MonoMethod method;
-               MonoMethodNormal normal;
                MonoMethodPInvoke pinvoke;
        } method;
+       MonoMethodHeader *header;
        MonoMethod *declaring;          /* the generic method definition. */
        MonoGenericContext context;     /* The current instantiation */
 };
@@ -781,6 +790,8 @@ typedef struct {
        /* Threadpool */
        guint64 threadpool_workitems;
        guint64 threadpool_ioworkitems;
+       guint threadpool_threads;
+       guint threadpool_iothreads;
 } MonoPerfCounters;
 
 extern MonoPerfCounters *mono_perfcounters MONO_INTERNAL;
index ff39c9a6233f75fd0fa4aa6ae843f79c8cab6966..fa47ec83b1a558c1a3c313d1f41468fa272ad8d9 100644 (file)
@@ -172,7 +172,7 @@ mono_class_from_typeref (MonoImage *image, guint32 type_token)
                
                mono_assembly_get_assemblyref (image, idx - 1, &aname);
                human_name = mono_stringify_assembly_name (&aname);
-               mono_loader_set_error_assembly_load (human_name, image->assembly->ref_only);
+               mono_loader_set_error_assembly_load (human_name, image->assembly ? image->assembly->ref_only : FALSE);
                g_free (human_name);
                
                return NULL;
@@ -561,7 +561,6 @@ inflate_generic_type (MonoImage *image, MonoType *type, MonoGenericContext *cont
                if (!inflated || !mono_error_ok (error))
                        return NULL;
                nt = mono_metadata_type_dup (image, type);
-               nt->data.array = g_memdup (nt->data.array, sizeof (MonoArrayType));
                nt->data.array->eklass = mono_class_from_mono_type (inflated);
                mono_metadata_free_type (inflated);
                return nt;
@@ -745,14 +744,15 @@ mono_class_inflate_generic_type_checked (MonoType *type, MonoGenericContext *con
  * was done.
  */
 static MonoType*
-mono_class_inflate_generic_type_no_copy (MonoImage *image, MonoType *type, MonoGenericContext *context)
+mono_class_inflate_generic_type_no_copy (MonoImage *image, MonoType *type, MonoGenericContext *context, MonoError *error)
 {
-       MonoError error;
        MonoType *inflated = NULL; 
 
+       mono_error_init (error);
        if (context) {
-               inflated = inflate_generic_type (image, type, context, &error);
-               g_assert (mono_error_ok (&error)); /*FIXME proper error handling*/
+               inflated = inflate_generic_type (image, type, context, error);
+               if (!mono_error_ok (error))
+                       return NULL;
        }
 
        if (!inflated)
@@ -964,13 +964,13 @@ mono_class_inflate_generic_method_full_checked (MonoMethod *method, MonoClass *k
        if (sig->pinvoke) {
                memcpy (&iresult->method.pinvoke, method, sizeof (MonoMethodPInvoke));
        } else {
-               memcpy (&iresult->method.normal, method, sizeof (MonoMethodNormal));
-               iresult->method.normal.header = NULL;
+               memcpy (&iresult->method.method, method, sizeof (MonoMethod));
        }
 
        result = (MonoMethod *) iresult;
        result->is_inflated = TRUE;
        result->is_generic = FALSE;
+       result->sre_method = FALSE;
        result->signature = NULL;
        result->is_mb_open = is_mb_open;
 
@@ -1191,6 +1191,7 @@ mono_type_has_exceptions (MonoType *type)
 static void
 mono_class_setup_fields (MonoClass *class)
 {
+       MonoError error;
        MonoImage *m = class->image; 
        int top = class->field.count;
        guint32 layout = class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK;
@@ -1306,7 +1307,14 @@ mono_class_setup_fields (MonoClass *class)
 
                        field->name = mono_field_get_name (gfield);
                        /*This memory must come from the image mempool as we don't have a chance to free it.*/
-                       field->type = mono_class_inflate_generic_type_no_copy (class->image, gfield->type, mono_class_get_context (class));
+                       field->type = mono_class_inflate_generic_type_no_copy (class->image, gfield->type, mono_class_get_context (class), &error);
+                       if (!mono_error_ok (&error)) {
+                               char *err_msg = g_strdup_printf ("Could not load field %d type due to: %s", i, mono_error_get_message (&error));
+                               mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, err_msg);
+                               g_free (err_msg);
+                               mono_error_cleanup (&error);
+                               return;
+                       }
                        g_assert (field->type->attrs == gfield->type->attrs);
                        if (mono_field_is_deleted (field))
                                continue;
@@ -1931,7 +1939,8 @@ mono_class_get_method_by_index (MonoClass *class, int index)
                return m;
        } else {
                mono_class_setup_methods (class);
-               g_assert (!class->exception_type); /*FIXME do proper error handling*/
+               if (class->exception_type) /*FIXME do proper error handling*/
+                       return NULL;
                g_assert (index >= 0 && index < class->method.count);
                return class->methods [index];
        }
@@ -2447,12 +2456,16 @@ mono_class_interface_offset_with_variance (MonoClass *klass, MonoClass *itf, gbo
 
 static void
 print_implemented_interfaces (MonoClass *klass) {
+       char *name;
        MonoError error;
        GPtrArray *ifaces = NULL;
        int i;
        int ancestor_level = 0;
-       
-       printf ("Packed interface table for class %s has size %d\n", klass->name, klass->interface_offsets_count);
+
+       name = mono_type_get_full_name (klass);
+       printf ("Packed interface table for class %s has size %d\n", name, klass->interface_offsets_count);
+       g_free (name);
+
        for (i = 0; i < klass->interface_offsets_count; i++)
                printf ("  [%03d][UUID %03d][SLOT %03d][SIZE  %03d] interface %s.%s\n", i,
                                klass->interfaces_packed [i]->interface_id,
@@ -2468,8 +2481,20 @@ print_implemented_interfaces (MonoClass *klass) {
                        printf ("(%d,F)", i);
        printf ("\n");
        printf ("Dump interface flags:");
+#ifdef COMPRESSED_INTERFACE_BITMAP
+       {
+               const uint8_t* p = klass->interface_bitmap;
+               i = klass->max_interface_id;
+               while (i > 0) {
+                       printf (" %d x 00 %02X", p [0], p [1]);
+                       i -= p [0] * 8;
+                       i -= 8;
+               }
+       }
+#else
        for (i = 0; i < ((((klass->max_interface_id + 1) >> 3)) + (((klass->max_interface_id + 1) & 7)? 1 :0)); i++)
                printf (" %02X", klass->interface_bitmap [i]);
+#endif
        printf ("\n");
        while (klass != NULL) {
                printf ("[LEVEL %d] Implemented interfaces by class %s:\n", ancestor_level, klass->name);
@@ -2782,6 +2807,170 @@ count_virtual_methods (MonoClass *class)
        return count;
 }
 
+static int
+find_interface (int num_ifaces, MonoClass **interfaces_full, MonoClass *ic)
+{
+       int m, l = 0;
+       if (!num_ifaces)
+               return -1;
+       while (1) {
+               if (l > num_ifaces)
+                       return -1;
+               m = (l + num_ifaces) / 2;
+               if (interfaces_full [m] == ic)
+                       return m;
+               if (l == num_ifaces)
+                       return -1;
+               if (!interfaces_full [m] || interfaces_full [m]->interface_id > ic->interface_id) {
+                       num_ifaces = m - 1;
+               } else {
+                       l =  m + 1;
+               }
+       }
+}
+
+static int
+find_interface_offset (int num_ifaces, MonoClass **interfaces_full, int *interface_offsets_full, MonoClass *ic)
+{
+       int i = find_interface (num_ifaces, interfaces_full, ic);
+       if (ic >= 0)
+               return interface_offsets_full [i];
+       return -1;
+}
+
+static mono_bool
+set_interface_and_offset (int num_ifaces, MonoClass **interfaces_full, int *interface_offsets_full, MonoClass *ic, int offset, mono_bool force_set)
+{
+       int i = find_interface (num_ifaces, interfaces_full, ic);
+       if (i >= 0) {
+               if (!force_set)
+                       return TRUE;
+               interface_offsets_full [i] = offset;
+               return FALSE;
+       }
+       for (i = 0; i < num_ifaces; ++i) {
+               if (interfaces_full [i]) {
+                       int end;
+                       if (interfaces_full [i]->interface_id < ic->interface_id)
+                               continue;
+                       end = i + 1;
+                       while (end < num_ifaces && interfaces_full [end]) end++;
+                       memmove (interfaces_full + i + 1, interfaces_full + i, sizeof (MonoClass*) * (end - i));
+                       memmove (interface_offsets_full + i + 1, interface_offsets_full + i, sizeof (int) * (end - i));
+               }
+               interfaces_full [i] = ic;
+               interface_offsets_full [i] = offset;
+               break;
+       }
+       return FALSE;
+}
+
+#ifdef COMPRESSED_INTERFACE_BITMAP
+
+/*
+ * Compressed interface bitmap design.
+ *
+ * Interface bitmaps take a large amount of memory, because their size is
+ * linear with the maximum interface id assigned in the process (each interface
+ * is assigned a unique id as it is loaded). The number of interface classes
+ * is high because of the many implicit interfaces implemented by arrays (we'll
+ * need to lazy-load them in the future).
+ * Most classes implement a very small number of interfaces, so the bitmap is
+ * sparse. This bitmap needs to be checked by interface casts, so access to the
+ * needed bit must be fast and doable with few jit instructions.
+ *
+ * The current compression format is as follows:
+ * *) it is a sequence of one or more two-byte elements
+ * *) the first byte in the element is the count of empty bitmap bytes
+ * at the current bitmap position
+ * *) the second byte in the element is an actual bitmap byte at the current
+ * bitmap position
+ *
+ * As an example, the following compressed bitmap bytes:
+ *     0x07 0x01 0x00 0x7
+ * correspond to the following bitmap:
+ *     0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x01 0x07
+ *
+ * Each two-byte element can represent up to 2048 bitmap bits, but as few as a single
+ * bitmap byte for non-sparse sequences. In practice the interface bitmaps created
+ * during a gmcs bootstrap are reduced to less tha 5% of the original size.
+ */
+
+/**
+ * mono_compress_bitmap:
+ * @dest: destination buffer
+ * @bitmap: bitmap buffer
+ * @size: size of @bitmap in bytes
+ *
+ * This is a mono internal function.
+ * The @bitmap data is compressed into a format that is small but
+ * still searchable in few instructions by the JIT and runtime.
+ * The compressed data is stored in the buffer pointed to by the
+ * @dest array. Passing a #NULL value for @dest allows to just compute
+ * the size of the buffer.
+ * This compression algorithm assumes the bits set in the bitmap are
+ * few and far between, like in interface bitmaps.
+ * Returns: the size of the compressed bitmap in bytes.
+ */
+int
+mono_compress_bitmap (uint8_t *dest, const uint8_t *bitmap, int size)
+{
+       int numz = 0;
+       int res = 0;
+       const uint8_t *end = bitmap + size;
+       while (bitmap < end) {
+               if (*bitmap || numz == 255) {
+                       if (dest) {
+                               *dest++ = numz;
+                               *dest++ = *bitmap;
+                       }
+                       res += 2;
+                       numz = 0;
+                       bitmap++;
+                       continue;
+               }
+               bitmap++;
+               numz++;
+       }
+       if (numz) {
+               res += 2;
+               if (dest) {
+                       *dest++ = numz;
+                       *dest++ = 0;
+               }
+       }
+       return res;
+}
+
+/**
+ * mono_class_interface_match:
+ * @bitmap: a compressed bitmap buffer
+ * @id: the index to check in the bitmap
+ *
+ * This is a mono internal function.
+ * Checks if a bit is set in a compressed interface bitmap. @id must
+ * be already checked for being smaller than the maximum id encoded in the
+ * bitmap.
+ *
+ * Returns: a non-zero value if bit @id is set in the bitmap @bitmap,
+ * #FALSE otherwise.
+ */
+int
+mono_class_interface_match (const uint8_t *bitmap, int id)
+{
+       while (TRUE) {
+               id -= bitmap [0] * 8;
+               if (id < 8) {
+                       if (id < 0)
+                               return 0;
+                       return bitmap [1] & (1 << id);
+               }
+               bitmap += 2;
+               id -= 8;
+       }
+}
+#endif
+
 /*
  * LOCKING: this is supposed to be called with the loader lock held.
  * Return -1 on failure and set exception_type
@@ -2791,15 +2980,17 @@ setup_interface_offsets (MonoClass *class, int cur_slot)
 {
        MonoError error;
        MonoClass *k, *ic;
-       int i, max_iid;
+       int i, j, max_iid, num_ifaces;
        MonoClass **interfaces_full = NULL;
        int *interface_offsets_full = NULL;
        GPtrArray *ifaces;
+       GPtrArray **ifaces_array = NULL;
        int interface_offsets_count;
        MonoClass **array_interfaces = NULL;
        int num_array_interfaces;
        int is_enumerator = FALSE;
 
+       mono_class_setup_supertypes (class);
        /* 
         * get the implicit generic interfaces for either the arrays or for System.Array/InternalEnumerator<T>
         * implicit interfaces have the property that they are assigned the same slot in the
@@ -2809,7 +3000,11 @@ setup_interface_offsets (MonoClass *class, int cur_slot)
 
        /* compute maximum number of slots and maximum interface id */
        max_iid = 0;
-       for (k = class; k ; k = k->parent) {
+       num_ifaces = num_array_interfaces; /* this can include duplicated ones */
+       ifaces_array = g_new0 (GPtrArray *, class->idepth);
+       for (j = 0; j < class->idepth; j++) {
+               k = class->supertypes [j];
+               num_ifaces += k->interface_count;
                for (i = 0; i < k->interface_count; i++) {
                        ic = k->interfaces [i];
 
@@ -2825,17 +3020,20 @@ setup_interface_offsets (MonoClass *class, int cur_slot)
                        mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Error getting the interfaces of %s due to %s", name, mono_error_get_message (&error)));
                        g_free (name);
                        mono_error_cleanup (&error);
-                       goto fail;
+                       cur_slot = -1;
+                       goto end;
                }
                if (ifaces) {
+                       num_ifaces += ifaces->len;
                        for (i = 0; i < ifaces->len; ++i) {
                                ic = g_ptr_array_index (ifaces, i);
                                if (max_iid < ic->interface_id)
                                        max_iid = ic->interface_id;
                        }
-                       g_ptr_array_free (ifaces, TRUE);
+                       ifaces_array [j] = ifaces;
                }
        }
+
        for (i = 0; i < num_array_interfaces; ++i) {
                ic = array_interfaces [i];
                mono_class_init (ic);
@@ -2844,22 +3042,23 @@ setup_interface_offsets (MonoClass *class, int cur_slot)
        }
 
        if (MONO_CLASS_IS_INTERFACE (class)) {
+               num_ifaces++;
                if (max_iid < class->interface_id)
                        max_iid = class->interface_id;
        }
        class->max_interface_id = max_iid;
        /* compute vtable offset for interfaces */
-       interfaces_full = g_malloc (sizeof (MonoClass*) * (max_iid + 1));
-       interface_offsets_full = g_malloc (sizeof (int) * (max_iid + 1));
+       interfaces_full = g_malloc0 (sizeof (MonoClass*) * num_ifaces);
+       interface_offsets_full = g_malloc (sizeof (int) * num_ifaces);
 
-       for (i = 0; i <= max_iid; i++) {
-               interfaces_full [i] = NULL;
+       for (i = 0; i < num_ifaces; i++) {
                interface_offsets_full [i] = -1;
        }
 
-       for (k = class->parent; k ; k = k->parent) {
-               ifaces = mono_class_get_implemented_interfaces (k, &error);
-               g_assert (mono_error_ok (&error));/*FIXME we perform the same thing above, so not failing there but here is VERY wrong.*/
+       /* skip the current class */
+       for (j = 0; j < class->idepth - 1; j++) {
+               k = class->supertypes [j];
+               ifaces = ifaces_array [j];
 
                if (ifaces) {
                        for (i = 0; i < ifaces->len; ++i) {
@@ -2869,56 +3068,43 @@ setup_interface_offsets (MonoClass *class, int cur_slot)
                                /*Force the sharing of interface offsets between parent and subtypes.*/
                                io = mono_class_interface_offset (k, ic);
                                g_assert (io >= 0);
-                               interfaces_full [ic->interface_id] = ic;
-                               interface_offsets_full [ic->interface_id] = io;
+                               set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, ic, io, TRUE);
                        }
-                       g_ptr_array_free (ifaces, TRUE);
                }
        }
 
-
-       ifaces = mono_class_get_implemented_interfaces (class, &error);
-       if (!mono_error_ok (&error)) {
-               char *name = mono_type_get_full_name (class);
-               mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Error getting the interfaces of %s due to %s", name, mono_error_get_message (&error)));
-               g_free (name);
-               mono_error_cleanup (&error);
-               goto fail;
-       } else if (ifaces) {
+       g_assert (class == class->supertypes [class->idepth - 1]);
+       ifaces = ifaces_array [class->idepth - 1];
+       if (ifaces) {
                for (i = 0; i < ifaces->len; ++i) {
                        int count;
                        ic = g_ptr_array_index (ifaces, i);
-                       if (interfaces_full [ic->interface_id] != NULL)
+                       if (set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, ic, cur_slot, FALSE))
                                continue;
-                       interfaces_full [ic->interface_id] = ic;
-                       interface_offsets_full [ic->interface_id] = cur_slot;
                        count = count_virtual_methods (ic);
                        if (count == -1) {
                                char *name = mono_type_get_full_name (ic);
                                mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, g_strdup_printf ("Error calculating interface offset of %s", name));
                                g_free (name);
-                               goto fail;
+                               cur_slot = -1;
+                               goto end;
                        }
                        cur_slot += count;
                }
-               g_ptr_array_free (ifaces, TRUE);
        }
 
-       if (MONO_CLASS_IS_INTERFACE (class)) {
-               interfaces_full [class->interface_id] = class;
-               interface_offsets_full [class->interface_id] = cur_slot;
-       }
+       if (MONO_CLASS_IS_INTERFACE (class))
+               set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, class, cur_slot, TRUE);
 
        if (num_array_interfaces) {
                if (is_enumerator) {
-                       int ienumerator_offset;
                        int ienumerator_idx = find_array_interface (class, "IEnumerator`1");
-                       ienumerator_offset = interface_offsets_full [class->interfaces [ienumerator_idx]->interface_id];
+                       int ienumerator_offset = find_interface_offset (num_ifaces, interfaces_full, interface_offsets_full, class->interfaces [ienumerator_idx]);
+                       g_assert (ienumerator_offset >= 0);
                        for (i = 0; i < num_array_interfaces; ++i) {
                                ic = array_interfaces [i];
-                               interfaces_full [ic->interface_id] = ic;
                                if (strcmp (ic->name, "IEnumerator`1") == 0)
-                                       interface_offsets_full [ic->interface_id] = ienumerator_offset;
+                                       set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, ic, ienumerator_offset, TRUE);
                                else
                                        g_assert_not_reached ();
                                /*g_print ("type %s has %s offset at %d (%s)\n", class->name, ic->name, interface_offsets_full [ic->interface_id], class->interfaces [0]->name);*/
@@ -2926,29 +3112,31 @@ setup_interface_offsets (MonoClass *class, int cur_slot)
                } else {
                        int ilist_offset, icollection_offset, ienumerable_offset;
                        int ilist_iface_idx = find_array_interface (class, "IList`1");
-                       int icollection_iface_idx = find_array_interface (class->interfaces [ilist_iface_idx], "ICollection`1");
-                       int ienumerable_iface_idx = find_array_interface (class->interfaces [ilist_iface_idx], "IEnumerable`1");
-                       ilist_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interface_id];
-                       icollection_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interfaces [icollection_iface_idx]->interface_id];
-                       ienumerable_offset = interface_offsets_full [class->interfaces [ilist_iface_idx]->interfaces [ienumerable_iface_idx]->interface_id];
+                       MonoClass* ilist_class = class->interfaces [ilist_iface_idx];
+                       int icollection_iface_idx = find_array_interface (ilist_class, "ICollection`1");
+                       int ienumerable_iface_idx = find_array_interface (ilist_class, "IEnumerable`1");
+                       ilist_offset = find_interface_offset (num_ifaces, interfaces_full, interface_offsets_full, class->interfaces [ilist_iface_idx]);
+                       icollection_offset = find_interface_offset (num_ifaces, interfaces_full, interface_offsets_full, ilist_class->interfaces [icollection_iface_idx]);
+                       ienumerable_offset = find_interface_offset (num_ifaces, interfaces_full, interface_offsets_full, ilist_class->interfaces [ienumerable_iface_idx]);
                        g_assert (ilist_offset >= 0 && icollection_offset >= 0 && ienumerable_offset >= 0);
                        for (i = 0; i < num_array_interfaces; ++i) {
+                               int offset;
                                ic = array_interfaces [i];
-                               interfaces_full [ic->interface_id] = ic;
                                if (ic->generic_class->container_class == mono_defaults.generic_ilist_class)
-                                       interface_offsets_full [ic->interface_id] = ilist_offset;
+                                       offset = ilist_offset;
                                else if (strcmp (ic->name, "ICollection`1") == 0)
-                                       interface_offsets_full [ic->interface_id] = icollection_offset;
+                                       offset = icollection_offset;
                                else if (strcmp (ic->name, "IEnumerable`1") == 0)
-                                       interface_offsets_full [ic->interface_id] = ienumerable_offset;
+                                       offset = ienumerable_offset;
                                else
                                        g_assert_not_reached ();
-                               /*g_print ("type %s has %s offset at %d (%s)\n", class->name, ic->name, interface_offsets_full [ic->interface_id], class->interfaces [0]->name);*/
+                               set_interface_and_offset (num_ifaces, interfaces_full, interface_offsets_full, ic, offset, TRUE);
+                               /*g_print ("type %s has %s offset at %d (%s)\n", class->name, ic->name, offset, class->interfaces [0]->name);*/
                        }
                }
        }
 
-       for (interface_offsets_count = 0, i = 0; i <= max_iid; i++) {
+       for (interface_offsets_count = 0, i = 0; i < num_ifaces; i++) {
                if (interface_offsets_full [i] != -1) {
                        interface_offsets_count ++;
                }
@@ -2961,35 +3149,50 @@ setup_interface_offsets (MonoClass *class, int cur_slot)
        if (class->interfaces_packed) {
                g_assert (class->interface_offsets_count == interface_offsets_count);
        } else {
+               uint8_t *bitmap;
+               int bsize;
                class->interface_offsets_count = interface_offsets_count;
                class->interfaces_packed = mono_image_alloc (class->image, sizeof (MonoClass*) * interface_offsets_count);
                class->interface_offsets_packed = mono_image_alloc (class->image, sizeof (guint16) * interface_offsets_count);
-               class->interface_bitmap = mono_image_alloc0 (class->image, (sizeof (guint8) * ((max_iid + 1) >> 3)) + (((max_iid + 1) & 7)? 1 :0));
-               for (interface_offsets_count = 0, i = 0; i <= max_iid; i++) {
-                       if (interface_offsets_full [i] != -1) {
-                               class->interface_bitmap [i >> 3] |= (1 << (i & 7));
-                               class->interfaces_packed [interface_offsets_count] = interfaces_full [i];
-                               class->interface_offsets_packed [interface_offsets_count] = interface_offsets_full [i];
-                               /*if (num_array_interfaces)
-                                 g_print ("type %s has %s offset at %d\n", mono_type_get_name_full (&class->byval_arg, 0), mono_type_get_name_full (&interfaces_full [i]->byval_arg, 0), interface_offsets_full [i]);*/
-                               interface_offsets_count ++;
-                       }
-               }
+               bsize = (sizeof (guint8) * ((max_iid + 1) >> 3)) + (((max_iid + 1) & 7)? 1 :0);
+#ifdef COMPRESSED_INTERFACE_BITMAP
+               bitmap = g_malloc0 (bsize);
+#else
+               bitmap = mono_image_alloc0 (class->image, bsize);
+#endif
+               for (i = 0; i < interface_offsets_count; i++) {
+                       int id = interfaces_full [i]->interface_id;
+                       bitmap [id >> 3] |= (1 << (id & 7));
+                       class->interfaces_packed [i] = interfaces_full [i];
+                       class->interface_offsets_packed [i] = interface_offsets_full [i];
+                       /*if (num_array_interfaces)
+                         g_print ("type %s has %s offset at %d\n", mono_type_get_name_full (&class->byval_arg, 0), mono_type_get_name_full (&interfaces_full [i]->byval_arg, 0), interface_offsets_full [i]);*/
+               }
+#ifdef COMPRESSED_INTERFACE_BITMAP
+               i = mono_compress_bitmap (NULL, bitmap, bsize);
+               class->interface_bitmap = mono_image_alloc0 (class->image, i);
+               mono_compress_bitmap (class->interface_bitmap, bitmap, bsize);
+               g_free (bitmap);
+#else
+               class->interface_bitmap = bitmap;
+#endif
        }
-       
+
+end:
        g_free (interfaces_full);
        g_free (interface_offsets_full);
        g_free (array_interfaces);
+       for (i = 0; i < class->idepth; i++) {
+               ifaces = ifaces_array [i];
+               if (ifaces)
+                       g_ptr_array_free (ifaces, TRUE);
+       }
+       g_free (ifaces_array);
        
        //printf ("JUST DONE: ");
        //print_implemented_interfaces (class);
  
        return cur_slot;
-fail:
-       g_free (interfaces_full);
-       g_free (interface_offsets_full);
-       g_free (array_interfaces);
-       return -1;
 }
 
 /*
@@ -3032,7 +3235,6 @@ mono_class_setup_vtable (MonoClass *class)
        MonoGenericContext *context;
        guint32 type_token;
        int onum = 0;
-       int i;
        gboolean ok = TRUE;
 
        if (class->vtable)
@@ -3069,30 +3271,14 @@ mono_class_setup_vtable (MonoClass *class)
        }
 
        if (class->image->dynamic) {
-               if (class->generic_class) {
-                       MonoClass *gklass = class->generic_class->container_class;
-
-                       mono_reflection_get_dynamic_overrides (gklass, &overrides, &onum);
-                       for (i = 0; i < onum; ++i) {
-                               MonoMethod *override = overrides [(i * 2) + 1];
-                               MonoMethod *inflated = NULL;
-                               int j;
-
-                               for (j = 0; j < class->method.count; ++j) {
-                                       if (gklass->methods [j] == override) {
-                                               inflated = class->methods [j];
-                                               break;
-                                       }
-                               }
-                               g_assert (inflated);
-                                               
-                               overrides [(i * 2) + 1] = inflated;
-                       }
-               } else {
-                       mono_reflection_get_dynamic_overrides (class, &overrides, &onum);
-               }
+               /* Generic instances can have zero method overrides without causing any harm.
+                * This is true since we don't do layout all over again for them, we simply inflate
+                * the layout of the parent.
+                */
+               mono_reflection_get_dynamic_overrides (class, &overrides, &onum);
        } else {
                /* The following call fails if there are missing methods in the type */
+               /* FIXME it's probably a good idea to avoid this for generic instances. */
                ok = mono_class_get_overrides_full (class->image, type_token, &overrides, &onum, context);
        }
 
@@ -3542,6 +3728,7 @@ mono_class_setup_vtable_general (MonoClass *class, MonoMethod **overrides, int o
 
        /* Optimized version for generic instances */
        if (class->generic_class) {
+               MonoError error;
                MonoClass *gklass = class->generic_class->container_class;
                MonoMethod **tmp;
 
@@ -3555,7 +3742,15 @@ mono_class_setup_vtable_general (MonoClass *class, MonoMethod **overrides, int o
                class->vtable_size = gklass->vtable_size;
                for (i = 0; i < gklass->vtable_size; ++i)
                        if (gklass->vtable [i]) {
-                               tmp [i] = mono_class_inflate_generic_method_full (gklass->vtable [i], class, mono_class_get_context (class));
+                               MonoMethod *inflated = mono_class_inflate_generic_method_full_checked (gklass->vtable [i], class, mono_class_get_context (class), &error);
+                               if (!mono_error_ok (&error)) {
+                                       char *err_msg = g_strdup_printf ("Could not inflate method due to %s", mono_error_get_message (&error));
+                                       mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, err_msg);
+                                       g_free (err_msg);
+                                       mono_error_cleanup (&error);
+                                       return;
+                               }
+                               tmp [i] = inflated;
                                tmp [i]->slot = gklass->vtable [i]->slot;
                        }
                mono_memory_barrier ();
@@ -4250,9 +4445,6 @@ mono_class_init (MonoClass *class)
                mono_secman_inheritancedemand_class (class, class->parent);
        }
 
-       if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
-               mono_security_core_clr_check_inheritance (class);
-
        mono_stats.initialized_class_count++;
 
        if (class->generic_class && !class->generic_class->is_dynamic) {
@@ -4459,13 +4651,8 @@ mono_class_init (MonoClass *class)
                setup_interface_offsets (class, 0);
        }
 
-       goto leave;
-
- leave:
-       /* Because of the double-checking locking pattern */
-       mono_memory_barrier ();
-       class->inited = 1;
-       class->init_pending = 0;
+       if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
+               mono_security_core_clr_check_inheritance (class);
 
        if (mono_loader_get_last_error ()) {
                if (class->exception_type == MONO_EXCEPTION_NONE) {
@@ -4474,6 +4661,14 @@ mono_class_init (MonoClass *class)
                mono_loader_clear_error ();
        }
 
+       goto leave;
+
+ leave:
+       /* Because of the double-checking locking pattern */
+       mono_memory_barrier ();
+       class->inited = 1;
+       class->init_pending = 0;
+
        mono_loader_unlock ();
 
        if (mono_debugger_class_init_func)
@@ -4847,7 +5042,15 @@ mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
                }
        }
 
-       /* do this early so it's available for interfaces in setup_mono_type () */
+       mono_class_setup_parent (class, parent);
+
+       /* uses ->valuetype, which is initialized by mono_class_setup_parent above */
+       mono_class_setup_mono_type (class);
+
+       /* 
+        * This might access class->byval_arg for recursion generated by generic constraints,
+        * so it has to come after setup_mono_type ().
+        */
        if ((nesting_tokeen = mono_metadata_nested_in_typedef (image, type_token))) {
                class->nested_in = mono_class_create_from_typedef (image, nesting_tokeen);
                if (!class->nested_in) {
@@ -4858,11 +5061,6 @@ mono_class_create_from_typedef (MonoImage *image, guint32 type_token)
                }
        }
 
-       mono_class_setup_parent (class, parent);
-
-       /* uses ->valuetype, which is initialized by mono_class_setup_parent above */
-       mono_class_setup_mono_type (class);
-
        if ((class->flags & TYPE_ATTRIBUTE_STRING_FORMAT_MASK) == TYPE_ATTRIBUTE_UNICODE_CLASS)
                class->unicode = 1;
 
@@ -5603,6 +5801,29 @@ mono_bounded_array_class_get (MonoClass *eclass, guint32 rank, gboolean bounded)
        else
                class->cast_class = eclass;
 
+       switch (class->cast_class->byval_arg.type) {
+       case MONO_TYPE_I1:
+               class->cast_class = mono_defaults.byte_class;
+               break;
+       case MONO_TYPE_U2:
+               class->cast_class = mono_defaults.int16_class;
+               break;
+       case MONO_TYPE_U4:
+#if SIZEOF_VOID_P == 4
+       case MONO_TYPE_I:
+       case MONO_TYPE_U:
+#endif
+               class->cast_class = mono_defaults.int32_class;
+               break;
+       case MONO_TYPE_U8:
+#if SIZEOF_VOID_P == 8
+       case MONO_TYPE_I:
+       case MONO_TYPE_U:
+#endif
+               class->cast_class = mono_defaults.int64_class;
+               break;
+       }
+
        class->element_class = eclass;
 
        if ((rank > 1) || bounded) {
@@ -6854,7 +7075,7 @@ mono_class_implement_interface_slow (MonoClass *target, MonoClass *candidate)
                if (candidate->image->dynamic && !candidate->wastypebuilder) {
                        MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (candidate);
                        int j;
-                       if (tb->interfaces) {
+                       if (tb && tb->interfaces) {
                                for (j = mono_array_length (tb->interfaces) - 1; j >= 0; --j) {
                                        MonoReflectionType *iface = mono_array_get (tb->interfaces, MonoReflectionType*, j);
                                        MonoClass *iface_class = mono_class_from_mono_type (iface->type);
index e1a2fe3e2acb6155e12da48f60d72a15a88d6a4a..6d9fe24c3c1ddb829b7cc7dbf74e1329b46cfdab 100644 (file)
@@ -358,7 +358,7 @@ cominterop_get_com_slot_for_method (MonoMethod* method)
 
 
 static void
-cominterop_mono_string_to_guid (const MonoString* string, guint8 *guid);
+cominterop_mono_string_to_guid (MonoString* string, guint8 *guid);
 
 static gboolean
 cominterop_class_guid (MonoClass* klass, guint8* guid)
@@ -2241,7 +2241,7 @@ cominterop_get_managed_wrapper_adjusted (MonoMethod *method)
  * to a 16 byte Microsoft GUID.
  */
 static void
-cominterop_mono_string_to_guid (const MonoString* string, guint8 *guid) {
+cominterop_mono_string_to_guid (MonoString* string, guint8 *guid) {
        gunichar2 * chars = mono_string_chars (string);
        int i = 0;
        static guint8 indexes[16] = {7, 5, 3, 1, 12, 10, 17, 15, 20, 22, 25, 27, 29, 31, 33, 35};
@@ -2946,8 +2946,8 @@ static gboolean
 mono_marshal_safearray_begin (gpointer safearray, MonoArray **result, gpointer *indices, gpointer empty, gpointer parameter, gboolean allocateNewArray)
 {
        int dim;
-       mono_array_size_t *sizes;
-       mono_array_size_t *bounds;
+       uintptr_t *sizes;
+       intptr_t *bounds;
        MonoClass *aklass;
        int i;
        gboolean bounded = FALSE;
@@ -2973,8 +2973,8 @@ mono_marshal_safearray_begin (gpointer safearray, MonoArray **result, gpointer *
 
                        *indices = g_malloc (dim * sizeof(int));
 
-                       sizes = alloca (dim * sizeof(mono_array_size_t));
-                       bounds = alloca (dim * sizeof(mono_array_size_t));
+                       sizes = alloca (dim * sizeof(uintptr_t));
+                       bounds = alloca (dim * sizeof(intptr_t));
 
                        for (i=0; i<dim; ++i) {
                                glong lbound, ubound;
index 99e075431c5669a827a7037ca4ff3a9e3f9e9842..0845c64f466729cb8c9e58dc85793f413548d670 100644 (file)
 #ifdef HAVE_SYS_FILIO_H
 #    include <sys/filio.h>
 #endif
-#ifndef TIOCGWINSZ
-#    ifdef HAVE_SYS_IOCTL_H
-#        include <sys/ioctl.h>
-#    endif
+#ifdef HAVE_SYS_IOCTL_H
+#    include <sys/ioctl.h>
 #endif
 
 #include <mono/metadata/console-io.h>
index 961c80830d690f1bd7d63a837e218c4bce0cad52..ee61167991ac8214af79fef7bb66679068204adf 100644 (file)
@@ -14,166 +14,166 @@ static const DateTimeFormatEntry datetime_format_entries [] = {
        {853, 876, 888, 376, 370, 447, 457, 465, 468, {897, 906, 914, 922, 931, 938, 948}, {957, 961, 965, 969, 973, 977, 981}, {985, 991, 998, 1004, 1010, 1015, 1020, 1027, 1033, 1042, 1050, 1059, 343}, {1068, 1073, 998, 1078, 1010, 1015, 1083, 1088, 1092, 1097, 1102, 1107, 343}, 0, 0, 344, 346, {348,888},{357,876},{370},{376}},
        {1112, 357, 348, 376, 370, 1136, 1146, 1154, 1161, {1168, 1178, 1188, 1198, 1208, 1218, 1228}, {1238, 1242, 1246, 1250, 1254, 1258, 1262}, {1266, 1273, 1280, 1287, 1294, 1301, 1308, 1315, 1322, 1329, 1336, 1346, 343}, {1266, 1273, 1280, 1287, 1294, 1301, 1308, 1315, 1322, 1329, 1336, 1346, 343}, 0, 0, 344, 346, {348},{357},{370},{376}},
        {1356, 1379, 1392, 1399, 1409, 447, 1414, 1422, 1427, {1432, 1440, 1450, 1458, 1466, 1475, 1482}, {1489, 1492, 1495, 1499, 1502, 1506, 1510}, {1513, 1519, 1525, 1533, 1539, 1547, 1555, 1565, 1571, 1579, 1587, 1596, 343}, {1605, 1607, 1610, 1614, 1617, 1619, 1622, 1626, 1631, 1634, 1636, 1639, 343}, 0, 1, 344, 346, {348,1392},{357,1379},{370,1409},{376,1399}},
-       {1643, 1664, 1676, 438, 370, 447, 457, 465, 468, {1687, 1695, 1702, 1710, 1717, 1725, 1732}, {1740, 1745, 1749, 1753, 1757, 1761, 1765}, {1770, 1777, 1785, 1791, 1797, 1801, 1806, 1811, 1818, 1828, 1836, 1845, 343}, {1854, 1858, 1862, 1866, 1797, 1870, 1874, 1878, 1882, 1886, 1890, 1894, 343}, 0, 1, 344, 346, {348,1898,1676},{357,1664},{370},{376,438}},
-       {1907, 1379, 1929, 438, 370, 447, 1414, 1940, 1946, {1953, 1961, 1968, 1977, 1986, 1997, 2005}, {2013, 2016, 2019, 2022, 2025, 2028, 2031}, {2034, 2041, 2049, 2055, 2061, 2065, 2070, 2075, 2082, 2092, 2100, 2109, 343}, {2118, 2122, 2126, 2130, 2061, 2134, 2138, 2142, 2146, 2150, 2154, 2158, 343}, 0, 1, 344, 346, {348,844,1929},{357,1379},{370},{376,438}},
-       {2162, 409, 37, 2186, 56, 447, 457, 2197, 2202, {2207, 2222, 2237, 2248, 2263, 2276, 2295}, {2310, 2317, 2324, 2331, 2338, 2345, 2352}, {2359, 2380, 2403, 2418, 2435, 2446, 2461, 2476, 2495, 2518, 2537, 2556, 343}, {2577, 2584, 2591, 2598, 2605, 2612, 2621, 2630, 2637, 2644, 2651, 2658, 343}, 0, 1, 344, 346, {348,2665,37},{357,409},{370,56},{376,2676,2186}},
-       {2688, 2719, 2739, 2186, 2746, 447, 2754, 465, 468, {2761, 2768, 2775, 2783, 2793, 2802, 2809}, {2818, 2822, 2826, 2830, 2834, 2838, 2842}, {2846, 2854, 2863, 2055, 2869, 2873, 2878, 2075, 2082, 2883, 2100, 2891, 343}, {2118, 2122, 2900, 2130, 2869, 2134, 2138, 2142, 2146, 2904, 2154, 2908, 343}, 0, 0, 344, 346, {348,2739},{2719,2719,2912,2926,2946},{2746,2746,2961,1409,370},{2186,2186,2970,2982,438}},
-       {2990, 3024, 3046, 2970, 370, 3057, 3062, 3074, 3079, {3084, 3092, 3098, 3105, 3116, 3123, 3131}, {3139, 3143, 1862, 3147, 3152, 3156, 3160}, {3165, 3171, 3179, 1004, 3185, 3190, 3196, 3202, 3209, 1042, 3220, 3230, 343}, {3240, 1858, 1862, 3244, 3248, 1870, 1874, 3252, 1882, 3256, 1890, 3260, 343}, 0, 1, 344, 346, {348,3264,3046},{357,3024},{370},{376,2970}},
-       {3272, 3297, 3314, 2982, 370, 3323, 3336, 465, 468, {3348, 3358, 3368, 3376, 3388, 3396, 3406}, {3415, 3418, 3421, 3424, 3427, 3430, 3433}, {3436, 3445, 3454, 3464, 3473, 3482, 3491, 3501, 3508, 3516, 3524, 3534, 343}, {3543, 3549, 3555, 3562, 3568, 3574, 3580, 3587, 3591, 3596, 3601, 3608, 343}, 0, 1, 344, 346, {348,3314},{357,3297},{370},{376,2982}},
-       {3614, 3640, 888, 438, 370, 447, 74, 465, 468, {3657, 3666, 3672, 3678, 3687, 3693, 3702}, {3709, 3714, 3719, 3724, 3729, 3734, 3739}, {3744, 3752, 3761, 3766, 3772, 3776, 3781, 3789, 3795, 3805, 1050, 3813, 343}, {3823, 3829, 3761, 3836, 3772, 3776, 3841, 3789, 3847, 1097, 1102, 3853, 343}, 0, 0, 344, 346, {888,3859,3264},{357,876,3640},{370},{376,438}},
-       {3869, 876, 2665, 438, 370, 447, 74, 465, 468, {3890, 3908, 3922, 3940, 3958, 3976, 3992}, {3999, 4002, 4005, 4008, 4011, 4014, 4017}, {4020, 4031, 4044, 4051, 4062, 4069, 4078, 4087, 4100, 4113, 4128, 4141, 343}, {4152, 4159, 4044, 4166, 4062, 4173, 4180, 4187, 4194, 4201, 4208, 4215, 343}, 0, 0, 344, 346, {348,888,2665},{357,876},{370},{376,438}},
-       {4222, 4244, 4258, 2982, 1409, 4272, 4283, 4291, 4294, {4297, 4307, 4315, 4320, 4327, 4340, 4348}, {1617, 4356, 4358, 4360, 4364, 4367, 4369}, {4373, 4381, 4390, 4399, 4408, 4415, 4423, 4431, 4441, 4452, 1836, 1845, 343}, {4461, 4466, 4472, 4479, 4485, 4491, 4497, 4503, 4508, 4515, 1102, 4520, 343}, 0, 1, 344, 346, {348,4525,4258},{357,4244},{370,1409},{376,1399,2982}},
-       {1907, 1379, 3314, 438, 370, 447, 1414, 465, 468, {4537, 4548, 4559, 4573, 4587, 4599, 4611}, {4623, 4627, 4632, 4637, 4642, 4646, 4651}, {4655, 4663, 3761, 4672, 4679, 4684, 4691, 4698, 1818, 4452, 4706, 4716, 343}, {1854, 1858, 1862, 1866, 4679, 4725, 4730, 4735, 1882, 1886, 4741, 4746, 343}, 0, 0, 344, 346, {348,3314},{357,1379},{370},{376,438}},
-       {4750, 409, 888, 376, 370, 447, 74, 4774, 4777, {4780, 4789, 4797, 4806, 4817, 4826, 4835}, {3139, 3143, 1862, 4842, 4846, 4850, 4854}, {4858, 4866, 3179, 4875, 4882, 4889, 4896, 3202, 4903, 4913, 1050, 4921, 343}, {4930, 1858, 1862, 1866, 4934, 4938, 4942, 3252, 4946, 4950, 1890, 3260, 343}, 0, 1, 344, 346, {348,888},{357,409},{370},{376}},
-       {4954, 4984, 5006, 2982, 1409, 5017, 5033, 5046, 5053, {5060, 5070, 5080, 5090, 5100, 5110, 5120}, {1238, 5130, 5134, 5138, 5142, 5146, 5150}, {5154, 5159, 5164, 5169, 5174, 5179, 5184, 5189, 5194, 5199, 5205, 5211, 343}, {5217, 5219, 5221, 5223, 5225, 5227, 5229, 5231, 5233, 5235, 5238, 5241, 343}, 0, 0, 344, 346, {5006,5006,348,5244,5251,5260,5279,5296},{4984,4984,5315,5339,5366},{1409,1409,370,5395,5403},{2982,438,5412,5423}},
-       {5435, 5488, 5515, 5524, 5550, 5568, 5585, 5599, 5606, {5613, 5623, 5633, 5643, 5653, 5663, 5673}, {5683, 5687, 5691, 5695, 5699, 5703, 5707}, {5711, 5716, 5721, 5726, 5731, 5736, 5741, 5746, 5751, 5756, 5762, 5768, 343}, {5711, 5716, 5721, 5726, 5731, 5736, 5741, 5746, 5751, 5756, 5762, 5768, 343}, 0, 0, 344, 346, {348,5515},{357,5488},{370,5550},{376,5524}},
-       {5774, 876, 5796, 1399, 1409, 447, 74, 465, 468, {5803, 5810, 5818, 5826, 5835, 5845, 5853}, {5862, 3418, 5865, 5868, 5871, 5874, 5877}, {5880, 5888, 5897, 1791, 5903, 1801, 1806, 5907, 1818, 1828, 1836, 1845, 343}, {1854, 1858, 5916, 1866, 5903, 1870, 1874, 1878, 1882, 1886, 1890, 1894, 343}, 0, 1, 344, 346, {348,5796},{357,876},{370,1409},{376,1399}},
-       {5920, 1379, 844, 5944, 5955, 447, 1414, 465, 468, {1687, 1695, 1702, 1710, 1717, 1725, 1732}, {5961, 3418, 3421, 5965, 3427, 5968, 5971}, {1770, 1777, 3761, 1791, 3772, 1801, 1806, 1811, 1818, 1828, 1836, 4716, 343}, {1854, 1858, 1862, 1866, 3772, 1870, 1874, 1878, 1882, 1886, 1890, 4746, 343}, 0, 1, 344, 346, {348,844},{357,1379},{370,5955},{376,5944}},
-       {5975, 876, 5996, 438, 370, 447, 74, 465, 468, {6007, 6017, 6031, 6038, 6045, 6054, 1482}, {6062, 6064, 6067, 6070, 6074, 6077, 2013}, {6080, 6089, 6094, 6101, 1797, 6111, 6120, 6127, 6137, 6147, 1587, 6160, 343}, {6170, 6174, 1862, 6178, 1797, 6182, 6186, 6190, 6194, 6198, 6203, 6207, 343}, 0, 1, 344, 346, {348,5515,5996},{357,876},{370},{376,438}},
-       {6211, 3024, 1676, 376, 370, 3057, 3062, 465, 468, {3084, 6244, 6258, 6271, 6284, 6297, 3131}, {3139, 6309, 6313, 6317, 6321, 6325, 3160}, {6329, 6337, 6347, 1004, 6354, 6359, 6365, 3202, 6371, 6380, 6388, 6397, 343}, {1854, 6406, 1862, 3244, 3772, 1870, 1874, 3252, 4946, 6410, 1890, 6414, 343}, 0, 0, 344, 346, {348,1676},{357,3024},{370},{376}},
-       {5975, 876, 1929, 438, 370, 447, 74, 465, 468, {6418, 6428, 6433, 6440, 6449, 6453, 6460}, {6471, 6473, 6475, 2022, 6478, 1617, 6480}, {6482, 6491, 6501, 6508, 3772, 6516, 6522, 1811, 6528, 6539, 6549, 6559, 343}, {6569, 2122, 2900, 2130, 2061, 6573, 6577, 2142, 2146, 2904, 2154, 2908, 343}, 0, 1, 344, 346, {348,1929},{357,876},{370},{376,438}},
-       {6581, 6607, 1929, 2982, 1409, 6625, 74, 465, 468, {6641, 6664, 505, 6687, 6698, 6713, 6728}, {6743, 6748, 6753, 6758, 6763, 6768, 6773}, {6778, 6791, 6806, 6815, 6828, 6835, 6844, 6853, 6866, 6883, 6898, 6911, 343}, {6926, 6933, 6940, 6947, 678, 6954, 6961, 6968, 6975, 6982, 6989, 6996, 343}, 0, 1, 344, 346, {348,844,1929},{357,6607},{370,1409},{376,1399,2982}},
-       {7003, 7025, 3314, 2982, 370, 4272, 1146, 465, 468, {7039, 7048, 7060, 7067, 7075, 7085, 7091}, {7098, 7102, 7106, 7110, 7114, 7119, 7123}, {7127, 7137, 7146, 7154, 7162, 7170, 7177, 7184, 7192, 1587, 7198, 7206, 343}, {7215, 7219, 7223, 7228, 7232, 6186, 7236, 7240, 7244, 6203, 7248, 7252, 343}, 0, 1, 344, 346, {348,7256,3314},{357,7025},{370},{376,2982}},
-       {7267, 1379, 7288, 2982, 1409, 447, 1414, 465, 468, {7299, 7307, 7316, 7323, 7330, 7339, 7346}, {7353, 7356, 7359, 7362, 7365, 7369, 2013}, {4373, 4381, 7372, 4672, 7378, 4725, 4730, 1811, 1818, 4452, 1836, 1845, 343}, {1854, 1858, 1862, 1866, 7378, 4725, 4730, 1878, 1882, 1886, 1890, 1894, 343}, 0, 1, 344, 346, {348,3314,7288},{357,1379},{370,1409},{376,1399,2982}},
-       {7383, 409, 5996, 7407, 7418, 447, 457, 7425, 7428, {7431, 7438, 7447, 7456, 7468, 7476, 7485}, {7495, 7499, 2900, 7504, 7509, 7513, 7517}, {7521, 7527, 3761, 7534, 1797, 7540, 7548, 7555, 7561, 7569, 7575, 7583, 343}, {2118, 7591, 2900, 7595, 7599, 7603, 7607, 7611, 7517, 7615, 7619, 7624, 343}, 0, 1, 344, 346, {348,5515,5996},{357,409},{370,7418},{376,7628,7407}},
-       {7640, 7668, 5996, 5944, 5955, 447, 74, 7685, 7688, {7691, 7699, 7707, 1710, 1717, 1725, 7714}, {7722, 7726, 3421, 5965, 3427, 5968, 7730}, {5880, 5888, 3761, 1791, 1797, 1801, 1806, 7734, 1818, 1828, 1836, 1845, 343}, {1854, 1858, 1862, 1866, 1797, 1870, 1874, 1878, 1882, 1886, 1890, 1894, 343}, 0, 1, 344, 346, {348,5996},{357,7668},{370,5955},{376,5944}},
-       {7742, 876, 37, 2982, 1409, 447, 74, 7763, 7794, {7825, 7856, 7884, 7912, 7931, 7965, 7990}, {8015, 8023, 8028, 8033, 8038, 8046, 8051}, {8056, 8075, 8106, 8125, 8144, 8166, 8191, 8213, 8235, 8257, 8276, 8304, 343}, {8326, 8335, 8344, 8356, 8368, 8377, 8389, 8398, 8407, 8416, 8425, 8434, 343}, 0, 0, 344, 346, {348,37},{357,876},{370,1409},{376,8443,2982}},
-       {8483, 8510, 1929, 438, 370, 447, 457, 465, 468, {8528, 8534, 8544, 8550, 8561, 8571, 8576}, {8586, 8590, 8594, 8598, 8603, 8607, 8611}, {8615, 8620, 8627, 8632, 8638, 8645, 8653, 8660, 8669, 8676, 8681, 8688, 343}, {8696, 8700, 2900, 8705, 2869, 8709, 8713, 8717, 8722, 8726, 8730, 8734, 343}, 0, 1, 344, 346, {348,1929},{357,8510},{370},{376,438}},
-       {1112, 357, 348, 376, 370, 1136, 1146, 465, 468, {8738, 8745, 8751, 8758, 8763, 8769, 8775}, {8781, 8785, 8789, 8793, 8797, 8801, 8805}, {8809, 8817, 8826, 2055, 8832, 2065, 2070, 8836, 2082, 2092, 2100, 8844, 343}, {2118, 2122, 2900, 2130, 8832, 2134, 2138, 8853, 2146, 2150, 2154, 8857, 343}, 0, 0, 344, 346, {348},{357},{370},{376}},
-       {8861, 876, 1929, 2982, 370, 8881, 74, 465, 468, {8897, 8910, 8929, 8946, 8959, 8972, 8988}, {9001, 6748, 6753, 6758, 6763, 6768, 6773}, {9006, 9017, 9030, 9045, 9058, 9071, 9084, 9095, 9108, 9123, 9136, 9155, 343}, {9168, 9175, 9182, 9189, 9198, 9207, 9216, 9223, 9232, 9239, 9248, 9257, 343}, 0, 1, 344, 346, {348,844,1929},{357,876},{370},{376,2982}},
-       {9266, 876, 1392, 5944, 5955, 447, 74, 465, 468, {9289, 9304, 9325, 9340, 9353, 9366, 9381}, {9394, 9399, 9404, 9409, 9414, 9419, 9424}, {9429, 9446, 9455, 9470, 678, 9487, 9502, 9515, 9530, 9547, 9568, 9585, 343}, {9600, 9175, 9607, 9614, 678, 9621, 9628, 9635, 9232, 9642, 9649, 9656, 343}, 0, 1, 344, 346, {348,1392},{357,876},{370,5955},{376,5944}},
-       {9663, 9685, 3314, 2982, 1409, 447, 9699, 465, 468, {9708, 9716, 9727, 9733, 9739, 9748, 1482}, {7098, 7102, 1757, 9754, 7114, 7119, 9758}, {1770, 1777, 7372, 1791, 1797, 9762, 9768, 9774, 1818, 1828, 1836, 1845, 343}, {1854, 1858, 1862, 1866, 1797, 1870, 1874, 9781, 1882, 1886, 1890, 1894, 343}, 0, 1, 344, 346, {348,9785,3314},{357,9685},{370,1409},{376,1399,2982}},
-       {8861, 876, 9792, 2982, 1409, 447, 9802, 465, 468, {9810, 9821, 9832, 9843, 9854, 9865, 9871}, {4367, 9880, 9882, 4358, 6062, 9884, 6473}, {9886, 9894, 9903, 9910, 3772, 9917, 9923, 1811, 1818, 9929, 1836, 9938, 343}, {9948, 9953, 9903, 1866, 3772, 9917, 9923, 1878, 9959, 1886, 1890, 9964, 343}, 0, 1, 344, 346, {348,844,9792},{357,876},{370,1409},{376,1399,2982}},
-       {9969, 9998, 4525, 2982, 370, 10019, 1414, 465, 468, {10037, 10048, 10058, 10067, 10078, 10090, 10101}, {10111, 4367, 10114, 9882, 10116, 10118, 6480}, {10121, 10131, 1785, 10142, 10151, 10157, 10165, 10173, 10181, 10192, 10201, 10211, 343}, {2118, 2122, 2900, 2130, 2061, 10221, 10226, 2142, 2146, 2150, 2154, 2908, 343}, 0, 1, 344, 346, {348,10231,4525},{357,9998},{370},{376,2982}},
-       {10238, 10271, 7256, 376, 370, 10293, 10308, 465, 468, {10320, 10332, 10344, 10356, 10370, 10385, 10398}, {10412, 10415, 10418, 10421, 10424, 6064, 7365}, {10427, 10434, 10442, 10447, 10458, 10468, 10478, 10485, 10497, 10506, 10513, 10524, 343}, {10534, 10538, 10542, 10546, 10550, 10554, 10558, 10562, 10566, 10570, 10574, 10578, 343}, 0, 1, 344, 346, {348,7256},{357,10271},{370},{376}},
-       {10582, 876, 10606, 2970, 370, 447, 74, 10615, 10622, {10629, 10645, 10658, 10674, 10691, 10709, 10718}, {10727, 10731, 10735, 10739, 10743, 10747, 10751}, {10755, 10768, 229, 10779, 10790, 10795, 10804, 10815, 10822, 10837, 10848, 10861, 343}, {10874, 10881, 10888, 10895, 10902, 10909, 10916, 10815, 10923, 10930, 10937, 10944, 343}, 0, 0, 344, 346, {348,10951,10606},{357,876},{370},{376,10961,2970}},
-       {10974, 409, 2665, 2186, 370, 447, 457, 10998, 11001, {11004, 11017, 11027, 11036, 11046, 11057, 11068}, {11080, 11083, 11088, 11093, 11098, 11103, 11108}, {11113, 11126, 11137, 11147, 11158, 11170, 11182, 11195, 11207, 11220, 11235, 11256, 343}, {11275, 11281, 11287, 11293, 11299, 11305, 11311, 11317, 11323, 11329, 11336, 11343, 343}, 0, 1, 344, 346, {348,2665},{357,409},{370},{376,2186}},
-       {11350, 2912, 1929, 2982, 370, 447, 2754, 11372, 11380, {11388, 11401, 11422, 11441, 11462, 11481, 11494}, {11505, 11512, 11519, 11526, 11533, 11540, 11547}, {11554, 11571, 11588, 11597, 11608, 11619, 11632, 11645, 11660, 11679, 11698, 11715, 343}, {11734, 11741, 11748, 11755, 11762, 11769, 11776, 11783, 11790, 11797, 11804, 11811, 343}, 0, 1, 344, 346, {348,11818,1929},{357,2912},{370},{376,2982}},
-       {1112, 357, 348, 376, 370, 1136, 1146, 465, 468, {11827, 11835, 11846, 11856, 11867, 11876, 11885}, {11895, 11898, 11901, 11904, 11907, 11910, 11913}, {11916, 11926, 11934, 11942, 11950, 11958, 11965, 11973, 11981, 11988, 11994, 12001, 343}, {12009, 12013, 1862, 12017, 3772, 12021, 12025, 12029, 12033, 12037, 12041, 12045, 343}, 0, 0, 344, 346, {348},{357},{370},{376}},
-       {387, 409, 1929, 438, 370, 447, 457, 465, 468, {12049, 484, 505, 6687, 12062, 12079, 12090}, {574, 582, 590, 12103, 12111, 612, 12119}, {12127, 641, 658, 667, 12142, 12149, 12158, 699, 712, 731, 748, 763, 343}, {12167, 786, 12175, 794, 12183, 12191, 12199, 802, 12207, 818, 826, 12217, 343}, 0, 1, 344, 346, {348,12229,1929},{357,409},{370},{376,438}},
-       {1112, 357, 348, 376, 370, 1136, 1146, 12237, 12240, {12243, 12250, 12258, 12266, 12275, 12285, 12292}, {2013, 6475, 2019, 12301, 2025, 12304, 2031}, {12307, 12316, 12326, 2055, 8832, 12332, 12338, 12344, 2082, 2092, 2100, 8844, 343}, {2118, 2122, 2900, 2130, 8832, 2134, 2138, 2142, 2146, 2150, 2154, 8857, 343}, 0, 0, 344, 346, {348},{357},{370},{376}},
-       {12353, 12373, 348, 376, 370, 12382, 1146, 12389, 12405, {5217, 5219, 5221, 5223, 5225, 5227, 5229}, {5217, 5219, 5221, 5223, 5225, 5227, 5229}, {5217, 5219, 5221, 5223, 5225, 5227, 5229, 5231, 5233, 5235, 5238, 5241, 343}, {5217, 5219, 5221, 5223, 5225, 5227, 5229, 5231, 5233, 5235, 5238, 5241, 343}, 0, 0, 344, 346, {348},{357,12373},{370},{376}},
-       {12427, 1664, 1898, 376, 370, 447, 457, 465, 468, {4537, 12450, 12461, 12471, 12481, 12491, 12505}, {4623, 4627, 12517, 12522, 12526, 12531, 12536}, {1770, 1777, 3761, 4672, 3772, 1801, 1806, 1811, 1818, 1828, 1836, 4716, 343}, {1854, 1858, 1862, 1866, 3772, 1870, 1874, 1878, 1882, 1886, 1890, 4746, 343}, 0, 0, 344, 346, {348,1898},{357,1664},{370},{376}},
+       {1643, 1664, 1676, 438, 370, 447, 1687, 465, 468, {1696, 1704, 1711, 1719, 1726, 1734, 1741}, {1749, 1754, 1758, 1762, 1766, 1770, 1774}, {1779, 1786, 1794, 1800, 1806, 1810, 1815, 1820, 1827, 1837, 1845, 1854, 343}, {1863, 1867, 1871, 1875, 1806, 1879, 1883, 1887, 1891, 1895, 1899, 1903, 343}, 0, 1, 344, 346, {348,1907,1676},{357,1664},{370},{376,438}},
+       {1916, 1379, 1938, 438, 370, 447, 1414, 1949, 1955, {1962, 1970, 1977, 1986, 1995, 2006, 2014}, {2022, 2025, 2028, 2031, 2034, 2037, 2040}, {2043, 2050, 2058, 2064, 2070, 2074, 2079, 2084, 2091, 2101, 2109, 2118, 343}, {2127, 2131, 2135, 2139, 2070, 2143, 2147, 2151, 2155, 2159, 2163, 2167, 343}, 0, 1, 344, 346, {348,844,1938},{357,1379},{370},{376,438}},
+       {2171, 409, 37, 2195, 56, 447, 457, 2206, 2211, {2216, 2231, 2246, 2257, 2272, 2285, 2304}, {2319, 2326, 2333, 2340, 2347, 2354, 2361}, {2368, 2389, 2412, 2427, 2444, 2455, 2470, 2485, 2504, 2527, 2546, 2565, 343}, {2586, 2593, 2600, 2607, 2614, 2621, 2630, 2639, 2646, 2653, 2660, 2667, 343}, 0, 1, 344, 346, {348,2674,37},{357,409},{370,56},{376,2685,2195}},
+       {2697, 2728, 2748, 2195, 2755, 447, 2763, 465, 468, {2770, 2777, 2784, 2792, 2802, 2811, 2818}, {2827, 2831, 2835, 2839, 2843, 2847, 2851}, {2855, 2863, 2872, 2064, 2878, 2882, 2887, 2084, 2091, 2892, 2109, 2900, 343}, {2127, 2131, 2909, 2139, 2878, 2143, 2147, 2151, 2155, 2913, 2163, 2917, 343}, 0, 0, 344, 346, {348,2748},{2728,2728,2921,2935,2955},{2755,2755,2970,1409,370},{2195,2195,2979,2991,438}},
+       {2999, 3033, 3055, 2979, 370, 3066, 3071, 3083, 3088, {3093, 3101, 3107, 3114, 3125, 3132, 3140}, {3148, 3152, 1871, 3156, 3161, 3165, 3169}, {3174, 3180, 3188, 1004, 3194, 3199, 3205, 3211, 3218, 1042, 3229, 3239, 343}, {3249, 1867, 1871, 3253, 3257, 1879, 1883, 3261, 1891, 3265, 1899, 3269, 343}, 0, 1, 344, 346, {348,3273,3055},{357,3033},{370},{376,2979}},
+       {3281, 3306, 3323, 2991, 370, 3332, 3345, 465, 468, {3357, 3367, 3377, 3385, 3397, 3405, 3415}, {3424, 3427, 3430, 3433, 3436, 3439, 3442}, {3445, 3454, 3463, 3473, 3482, 3491, 3500, 3510, 3517, 3525, 3533, 3543, 343}, {3552, 3558, 3564, 3571, 3577, 3583, 3589, 3596, 3600, 3605, 3610, 3617, 343}, 0, 1, 344, 346, {348,3323},{357,3306},{370},{376,2991}},
+       {3623, 3649, 888, 438, 370, 447, 74, 465, 468, {3666, 3675, 3681, 3687, 3696, 3702, 3711}, {3718, 3723, 3728, 3733, 3738, 3743, 3748}, {3753, 3761, 3770, 3775, 3781, 3785, 3790, 3798, 3804, 3814, 1050, 3822, 343}, {3832, 3838, 3770, 3845, 3781, 3785, 3850, 3798, 3856, 1097, 1102, 3862, 343}, 0, 0, 344, 346, {888,3868,3273},{357,876,3649},{370},{376,438}},
+       {3878, 876, 2674, 438, 370, 447, 74, 465, 468, {3899, 3917, 3931, 3949, 3967, 3985, 4001}, {4008, 4011, 4014, 4017, 4020, 4023, 4026}, {4029, 4040, 4053, 4060, 4071, 4078, 4087, 4096, 4109, 4122, 4137, 4150, 343}, {4161, 4168, 4053, 4175, 4071, 4182, 4189, 4196, 4203, 4210, 4217, 4224, 343}, 0, 0, 344, 346, {348,888,2674},{357,876},{370},{376,438}},
+       {4231, 4253, 4267, 2991, 1409, 4281, 4292, 4300, 4303, {4306, 4316, 4324, 4329, 4336, 4349, 4357}, {1617, 4365, 4367, 4369, 4373, 4376, 4378}, {4382, 4390, 4399, 4408, 4417, 4424, 4432, 4440, 4450, 4461, 1845, 1854, 343}, {4470, 4475, 4481, 4488, 4494, 4500, 4506, 4512, 4517, 4524, 1102, 4529, 343}, 0, 1, 344, 346, {348,4534,4267},{357,4253},{370,1409},{376,1399,2991}},
+       {1916, 1379, 3323, 438, 370, 447, 1414, 465, 468, {4546, 4557, 4568, 4582, 4596, 4608, 4620}, {4632, 4636, 4641, 4646, 4651, 4655, 4660}, {4664, 4672, 3770, 4681, 4688, 4693, 4700, 4707, 1827, 4461, 4715, 4725, 343}, {1863, 1867, 1871, 1875, 4688, 4734, 4739, 4744, 1891, 1895, 4750, 4755, 343}, 0, 0, 344, 346, {348,3323},{357,1379},{370},{376,438}},
+       {4759, 409, 888, 376, 370, 447, 74, 4783, 4786, {4789, 4798, 4806, 4815, 4826, 4835, 4844}, {3148, 3152, 1871, 4851, 4855, 4859, 4863}, {4867, 4875, 3188, 4884, 4891, 4898, 4905, 3211, 4912, 4922, 1050, 4930, 343}, {4939, 1867, 1871, 1875, 4943, 4947, 4951, 3261, 4955, 4959, 1899, 3269, 343}, 0, 1, 344, 346, {348,888},{357,409},{370},{376}},
+       {4963, 4993, 5015, 2991, 1409, 5026, 5042, 5055, 5062, {5069, 5079, 5089, 5099, 5109, 5119, 5129}, {1238, 5139, 5143, 5147, 5151, 5155, 5159}, {5163, 5168, 5173, 5178, 5183, 5188, 5193, 5198, 5203, 5208, 5214, 5220, 343}, {5226, 5228, 5230, 5232, 5234, 5236, 5238, 5240, 5242, 5244, 5247, 5250, 343}, 0, 0, 344, 346, {5015,5015,348,5253,5260,5269,5288,5305},{4993,4993,5324,5348,5375},{1409,1409,370,5404,5412},{2991,438,5421,5432}},
+       {5444, 5497, 5524, 5533, 5559, 5577, 5594, 5608, 5615, {5622, 5632, 5642, 5652, 5662, 5672, 5682}, {5692, 5696, 5700, 5704, 5708, 5712, 5716}, {5720, 5725, 5730, 5735, 5740, 5745, 5750, 5755, 5760, 5765, 5771, 5777, 343}, {5720, 5725, 5730, 5735, 5740, 5745, 5750, 5755, 5760, 5765, 5771, 5777, 343}, 0, 0, 344, 346, {348,5524},{357,5497},{370,5559},{376,5533}},
+       {5783, 876, 5805, 1399, 1409, 447, 74, 465, 468, {5812, 5819, 5827, 5835, 5844, 5854, 5862}, {5871, 3427, 5874, 5877, 5880, 5883, 5886}, {5889, 5897, 5906, 1800, 5912, 1810, 1815, 5916, 1827, 1837, 1845, 1854, 343}, {1863, 1867, 5925, 1875, 5912, 1879, 1883, 1887, 1891, 1895, 1899, 1903, 343}, 0, 1, 344, 346, {348,5805},{357,876},{370,1409},{376,1399}},
+       {5929, 1379, 844, 5953, 5964, 447, 1414, 465, 468, {1696, 1704, 1711, 1719, 1726, 1734, 1741}, {5970, 3427, 3430, 5974, 3436, 5977, 5980}, {1779, 1786, 3770, 1800, 3781, 1810, 1815, 1820, 1827, 1837, 1845, 4725, 343}, {1863, 1867, 1871, 1875, 3781, 1879, 1883, 1887, 1891, 1895, 1899, 4755, 343}, 0, 1, 344, 346, {348,844},{357,1379},{370,5964},{376,5953}},
+       {5984, 876, 6005, 438, 370, 447, 74, 465, 468, {6016, 6026, 6040, 6047, 6054, 6063, 1482}, {6071, 6073, 6076, 6079, 6083, 6086, 2022}, {6089, 6098, 6103, 6110, 1806, 6120, 6129, 6136, 6146, 6156, 1587, 6169, 343}, {6179, 6183, 1871, 6187, 1806, 6191, 6195, 6199, 6203, 6207, 6212, 6216, 343}, 0, 1, 344, 346, {348,5524,6005},{357,876},{370},{376,438}},
+       {6220, 3033, 1676, 376, 370, 3066, 3071, 465, 468, {3093, 6253, 6267, 6280, 6293, 6306, 3140}, {3148, 6318, 6322, 6326, 6330, 6334, 3169}, {6338, 6346, 6356, 1004, 6363, 6368, 6374, 3211, 6380, 6389, 6397, 6406, 343}, {1863, 6415, 1871, 3253, 3781, 1879, 1883, 3261, 4955, 6419, 1899, 6423, 343}, 0, 0, 344, 346, {348,1676},{357,3033},{370},{376}},
+       {5984, 876, 1938, 438, 370, 447, 74, 465, 468, {6427, 6437, 6442, 6449, 6458, 6462, 6469}, {6480, 6482, 6484, 2031, 6487, 1617, 6489}, {6491, 6500, 6510, 6517, 3781, 6525, 6531, 1820, 6537, 6548, 6558, 6568, 343}, {6578, 2131, 2909, 2139, 2070, 6582, 6586, 2151, 2155, 2913, 2163, 2917, 343}, 0, 1, 344, 346, {348,1938},{357,876},{370},{376,438}},
+       {6590, 6616, 1938, 2991, 1409, 6634, 74, 465, 468, {6650, 6673, 505, 6696, 6707, 6722, 6737}, {6752, 6757, 6762, 6767, 6772, 6777, 6782}, {6787, 6800, 6815, 6824, 6837, 6844, 6853, 6862, 6875, 6892, 6907, 6920, 343}, {6935, 6942, 6949, 6956, 678, 6963, 6970, 6977, 6984, 6991, 6998, 7005, 343}, 0, 1, 344, 346, {348,844,1938},{357,6616},{370,1409},{376,1399,2991}},
+       {7012, 7034, 3323, 2991, 370, 4281, 1146, 465, 468, {7048, 7057, 7069, 7076, 7084, 7094, 7100}, {7107, 7111, 7115, 7119, 7123, 7128, 7132}, {7136, 7146, 7155, 7163, 7171, 7179, 7186, 7193, 7201, 1587, 7207, 7215, 343}, {7224, 7228, 7232, 7237, 7241, 6195, 7245, 7249, 7253, 6212, 7257, 7261, 343}, 0, 1, 344, 346, {348,7265,3323},{357,7034},{370},{376,2991}},
+       {7276, 1379, 7297, 2991, 1409, 447, 1414, 465, 468, {7308, 7316, 7325, 7332, 7339, 7348, 7355}, {7362, 7365, 7368, 7371, 7374, 7378, 2022}, {4382, 4390, 7381, 4681, 7387, 4734, 4739, 1820, 1827, 4461, 1845, 1854, 343}, {1863, 1867, 1871, 1875, 7387, 4734, 4739, 1887, 1891, 1895, 1899, 1903, 343}, 0, 1, 344, 346, {348,3323,7297},{357,1379},{370,1409},{376,1399,2991}},
+       {7392, 409, 6005, 7416, 7427, 447, 457, 7434, 7437, {7440, 7447, 7456, 7465, 7477, 7485, 7494}, {7504, 7508, 2909, 7513, 7518, 7522, 7526}, {7530, 7536, 3770, 7543, 1806, 7549, 7557, 7564, 7570, 7578, 7584, 7592, 343}, {2127, 7600, 2909, 7604, 7608, 7612, 7616, 7620, 7526, 7624, 7628, 7633, 343}, 0, 1, 344, 346, {348,5524,6005},{357,409},{370,7427},{376,7637,7416}},
+       {7649, 7677, 6005, 5953, 5964, 447, 74, 7694, 7697, {7700, 7708, 7716, 1719, 1726, 1734, 7723}, {7731, 7735, 3430, 5974, 3436, 5977, 7739}, {5889, 5897, 3770, 1800, 1806, 1810, 1815, 7743, 1827, 1837, 1845, 1854, 343}, {1863, 1867, 1871, 1875, 1806, 1879, 1883, 1887, 1891, 1895, 1899, 1903, 343}, 0, 1, 344, 346, {348,6005},{357,7677},{370,5964},{376,5953}},
+       {7751, 876, 37, 2991, 1409, 447, 74, 7772, 7803, {7834, 7865, 7893, 7921, 7940, 7974, 7999}, {8024, 8032, 8037, 8042, 8047, 8055, 8060}, {8065, 8084, 8115, 8134, 8153, 8175, 8200, 8222, 8244, 8266, 8285, 8313, 343}, {8335, 8344, 8353, 8365, 8377, 8386, 8398, 8407, 8416, 8425, 8434, 8443, 343}, 0, 0, 344, 346, {348,37},{357,876},{370,1409},{376,8452,2991}},
+       {8492, 8519, 1938, 438, 370, 447, 457, 465, 468, {8537, 8543, 8553, 8559, 8570, 8580, 8585}, {8595, 8599, 8603, 8607, 8612, 8616, 8620}, {8624, 8629, 8636, 8641, 8647, 8654, 8662, 8669, 8678, 8685, 8690, 8697, 343}, {8705, 8709, 2909, 8714, 2878, 8718, 8722, 8726, 8731, 8735, 8739, 8743, 343}, 0, 1, 344, 346, {348,1938},{357,8519},{370},{376,438}},
+       {1112, 357, 348, 376, 370, 1136, 1146, 465, 468, {8747, 8754, 8760, 8767, 8772, 8778, 8784}, {8790, 8794, 8798, 8802, 8806, 8810, 8814}, {8818, 8826, 8835, 2064, 8841, 2074, 2079, 8845, 2091, 2101, 2109, 8853, 343}, {2127, 2131, 2909, 2139, 8841, 2143, 2147, 8862, 2155, 2159, 2163, 8866, 343}, 0, 0, 344, 346, {348},{357},{370},{376}},
+       {8870, 876, 1938, 2991, 370, 8890, 74, 465, 468, {8906, 8919, 8938, 8955, 8968, 8981, 8997}, {9010, 6757, 6762, 6767, 6772, 6777, 6782}, {9015, 9026, 9039, 9054, 9067, 9080, 9093, 9104, 9117, 9132, 9145, 9164, 343}, {9177, 9184, 9191, 9198, 9207, 9216, 9225, 9232, 9241, 9248, 9257, 9266, 343}, 0, 1, 344, 346, {348,844,1938},{357,876},{370},{376,2991}},
+       {9275, 876, 1392, 5953, 5964, 447, 74, 465, 468, {9298, 9313, 9334, 9349, 9362, 9375, 9390}, {9403, 9408, 9413, 9418, 9423, 9428, 9433}, {9438, 9455, 9464, 9479, 678, 9496, 9511, 9524, 9539, 9556, 9577, 9594, 343}, {9609, 9184, 9616, 9623, 678, 9630, 9637, 9644, 9241, 9651, 9658, 9665, 343}, 0, 1, 344, 346, {348,1392},{357,876},{370,5964},{376,5953}},
+       {9672, 9694, 3323, 2991, 1409, 447, 1687, 465, 468, {9708, 9716, 9727, 9733, 9739, 9748, 1482}, {7107, 7111, 1766, 9754, 7123, 7128, 9758}, {1779, 1786, 7381, 1800, 1806, 9762, 9768, 9774, 1827, 1837, 1845, 1854, 343}, {1863, 1867, 1871, 1875, 1806, 1879, 1883, 9781, 1891, 1895, 1899, 1903, 343}, 0, 1, 344, 346, {348,9785,3323},{357,9694},{370,1409},{376,1399,2991}},
+       {8870, 876, 9792, 2991, 1409, 447, 9802, 465, 468, {9810, 9821, 9832, 9843, 9854, 9865, 9871}, {4376, 9880, 9882, 4367, 6071, 9884, 6482}, {9886, 9894, 9903, 9910, 3781, 9917, 9923, 1820, 1827, 9929, 1845, 9938, 343}, {9948, 9953, 9903, 1875, 3781, 9917, 9923, 1887, 9959, 1895, 1899, 9964, 343}, 0, 1, 344, 346, {348,844,9792},{357,876},{370,1409},{376,1399,2991}},
+       {9969, 9998, 4534, 2991, 370, 10019, 1414, 465, 468, {10037, 10048, 10058, 10067, 10078, 10090, 10101}, {10111, 4376, 10114, 9882, 10116, 10118, 6489}, {10121, 10131, 1794, 10142, 10151, 10157, 10165, 10173, 10181, 10192, 10201, 10211, 343}, {2127, 2131, 2909, 2139, 2070, 10221, 10226, 2151, 2155, 2159, 2163, 2917, 343}, 0, 1, 344, 346, {348,10231,4534},{357,9998},{370},{376,2991}},
+       {10238, 10271, 7265, 376, 370, 10293, 10308, 465, 468, {10320, 10332, 10344, 10356, 10370, 10385, 10398}, {10412, 10415, 10418, 10421, 10424, 6073, 7374}, {10427, 10434, 10442, 10447, 10458, 10468, 10478, 10485, 10497, 10506, 10513, 10524, 343}, {10534, 10538, 10542, 10546, 10550, 10554, 10558, 10562, 10566, 10570, 10574, 10578, 343}, 0, 1, 344, 346, {348,7265},{357,10271},{370},{376}},
+       {10582, 876, 10606, 2979, 370, 447, 74, 10615, 10622, {10629, 10645, 10658, 10674, 10691, 10709, 10718}, {10727, 10731, 10735, 10739, 10743, 10747, 10751}, {10755, 10768, 229, 10779, 10790, 10795, 10804, 10815, 10822, 10837, 10848, 10861, 343}, {10874, 10881, 10888, 10895, 10902, 10909, 10916, 10815, 10923, 10930, 10937, 10944, 343}, 0, 0, 344, 346, {348,10951,10606},{357,876},{370},{376,10961,2979}},
+       {10974, 409, 2674, 2195, 370, 447, 457, 10998, 11001, {11004, 11017, 11027, 11036, 11046, 11057, 11068}, {11080, 11083, 11088, 11093, 11098, 11103, 11108}, {11113, 11126, 11137, 11147, 11158, 11170, 11182, 11195, 11207, 11220, 11235, 11256, 343}, {11275, 11281, 11287, 11293, 11299, 11305, 11311, 11317, 11323, 11329, 11336, 11343, 343}, 0, 1, 344, 346, {348,2674},{357,409},{370},{376,2195}},
+       {11350, 2921, 1938, 2991, 370, 447, 2763, 11372, 11380, {11388, 11401, 11422, 11441, 11462, 11481, 11494}, {11505, 11512, 11519, 11526, 11533, 11540, 11547}, {11554, 11571, 11588, 11597, 11608, 11619, 11632, 11645, 11660, 11679, 11698, 11715, 343}, {11734, 11741, 11748, 11755, 11762, 11769, 11776, 11783, 11790, 11797, 11804, 11811, 343}, 0, 1, 344, 346, {348,11818,1938},{357,2921},{370},{376,2991}},
+       {1112, 357, 348, 376, 370, 1136, 1146, 465, 468, {11827, 11835, 11846, 11856, 11867, 11876, 11885}, {11895, 11898, 11901, 11904, 11907, 11910, 11913}, {11916, 11926, 11934, 11942, 11950, 11958, 11965, 11973, 11981, 11988, 11994, 12001, 343}, {12009, 12013, 1871, 12017, 3781, 12021, 12025, 12029, 12033, 12037, 12041, 12045, 343}, 0, 0, 344, 346, {348},{357},{370},{376}},
+       {387, 409, 1938, 438, 370, 447, 457, 465, 468, {12049, 484, 505, 6696, 12062, 12079, 12090}, {574, 582, 590, 12103, 12111, 612, 12119}, {12127, 641, 658, 667, 12142, 12149, 12158, 699, 712, 731, 748, 763, 343}, {12167, 786, 12175, 794, 12183, 12191, 12199, 802, 12207, 818, 826, 12217, 343}, 0, 1, 344, 346, {348,12229,1938},{357,409},{370},{376,438}},
+       {1112, 357, 348, 376, 370, 1136, 1146, 12237, 12240, {12243, 12250, 12258, 12266, 12275, 12285, 12292}, {2022, 6484, 2028, 12301, 2034, 12304, 2040}, {12307, 12316, 12326, 2064, 8841, 12332, 12338, 12344, 2091, 2101, 2109, 8853, 343}, {2127, 2131, 2909, 2139, 8841, 2143, 2147, 2151, 2155, 2159, 2163, 8866, 343}, 0, 0, 344, 346, {348},{357},{370},{376}},
+       {12353, 12373, 348, 376, 370, 12382, 1146, 12389, 12405, {5226, 5228, 5230, 5232, 5234, 5236, 5238}, {5226, 5228, 5230, 5232, 5234, 5236, 5238}, {5226, 5228, 5230, 5232, 5234, 5236, 5238, 5240, 5242, 5244, 5247, 5250, 343}, {5226, 5228, 5230, 5232, 5234, 5236, 5238, 5240, 5242, 5244, 5247, 5250, 343}, 0, 0, 344, 346, {348},{357,12373},{370},{376}},
+       {12427, 1664, 1907, 376, 370, 447, 457, 465, 468, {4546, 12450, 12461, 12471, 12481, 12491, 12505}, {4632, 4636, 12517, 12522, 12526, 12531, 12536}, {1779, 1786, 3770, 4681, 3781, 1810, 1815, 1820, 1827, 1837, 1845, 4725, 343}, {1863, 1867, 1871, 1875, 3781, 1879, 1883, 1887, 1891, 1895, 1899, 4755, 343}, 0, 0, 344, 346, {348,1907},{357,1664},{370},{376}},
        {1112, 357, 348, 376, 370, 1136, 1146, 12540, 12568, {12590, 12609, 12628, 12650, 12669, 12691, 12716}, {12735, 12745, 12755, 12768, 12778, 12791, 12807}, {12817, 12833, 12849, 12865, 12884, 12891, 12901, 12917, 12933, 12955, 12977, 12996, 343}, {12817, 12833, 12849, 12865, 12884, 12891, 12901, 12917, 12933, 12955, 12977, 12996, 343}, 0, 0, 344, 346, {348},{357},{370},{376}},
-       {1112, 357, 348, 376, 370, 1136, 1146, 465, 468, {13018, 13027, 13036, 13044, 13053, 13062, 13069}, {13078, 13082, 13086, 13090, 13094, 13098, 13102}, {8809, 8817, 13106, 13112, 8832, 2065, 13119, 13125, 13132, 13141, 13148, 13156, 343}, {2118, 2122, 2900, 2130, 8832, 2134, 2138, 13164, 2146, 2150, 2154, 8857, 343}, 0, 6, 344, 346, {348},{357},{370},{376}},
+       {1112, 357, 348, 376, 370, 1136, 1146, 465, 468, {13018, 13027, 13036, 13044, 13053, 13062, 13069}, {13078, 13082, 13086, 13090, 13094, 13098, 13102}, {8818, 8826, 13106, 13112, 8841, 2074, 13119, 13125, 13132, 13141, 13148, 13156, 343}, {2127, 2131, 2909, 2139, 8841, 2143, 2147, 13164, 2155, 2159, 2163, 8866, 343}, 0, 6, 344, 346, {348},{357},{370},{376}},
        {1112, 357, 348, 376, 370, 1136, 1146, 13168, 13210, {13252, 13271, 13290, 13312, 13331, 13353, 13378}, {13397, 13407, 13417, 13430, 13440, 13453, 13469}, {13479, 13507, 13535, 13551, 13570, 13577, 13587, 13603, 13619, 13647, 13669, 13691, 343}, {13716, 13735, 13535, 13551, 13570, 13577, 13587, 13603, 13754, 13770, 13786, 13796, 343}, 0, 0, 344, 346, {348},{357},{370},{376}},
        {1112, 357, 348, 376, 370, 1136, 1146, 13809, 13822, {13835, 13854, 13876, 13901, 13917, 13939, 13958}, {13968, 13975, 13982, 13989, 13996, 14003, 14010}, {14014, 14030, 14055, 14074, 14093, 14100, 14113, 14126, 14145, 14176, 14201, 14223, 343}, {14248, 14256, 14270, 14284, 14093, 14100, 14113, 14295, 14303, 14317, 14328, 14336, 343}, 0, 0, 344, 346, {348},{357},{370},{376}},
        {1112, 357, 348, 376, 370, 1136, 1146, 14347, 14375, {14397, 14419, 14441, 14466, 14488, 14513, 14541}, {14563, 14573, 14583, 14596, 14606, 14619, 14635}, {14645, 14661, 14686, 14705, 14727, 14734, 14747, 14760, 14779, 14810, 14835, 14854, 343}, {14645, 14661, 14686, 14705, 14727, 14734, 14747, 14760, 14779, 14810, 14835, 14854, 343}, 0, 0, 344, 346, {348},{357},{370},{376}},
        {1112, 357, 348, 376, 370, 1136, 1146, 14879, 14907, {14929, 14948, 14967, 14989, 15008, 15030, 15055}, {15074, 15079, 15087, 15095, 15103, 15111, 15119}, {15130, 15146, 15171, 15190, 15212, 15219, 15232, 15245, 15264, 15292, 15317, 15339, 343}, {15130, 15146, 15171, 15190, 15212, 15219, 15232, 15245, 15264, 15292, 15317, 15339, 343}, 0, 0, 344, 346, {348},{357},{370},{376}},
        {1112, 357, 348, 376, 370, 1136, 1146, 15364, 15376, {12590, 12609, 15388, 12650, 12669, 12691, 12716}, {12735, 12745, 15410, 12768, 12778, 12791, 12807}, {15423, 15448, 12849, 15473, 15492, 12891, 15499, 15512, 15528, 15556, 15578, 15606, 343}, {15423, 15448, 12849, 15473, 15492, 12891, 15499, 15512, 15528, 15556, 15578, 15606, 343}, 0, 0, 344, 346, {348},{357},{370},{376}},
-       {1112, 357, 348, 376, 370, 1136, 1146, 465, 468, {15628, 15636, 15641, 15648, 15658, 15664, 15671}, {15679, 15683, 2900, 15687, 15692, 15696, 15700}, {15705, 15713, 15722, 15728, 15734, 15739, 15745, 15751, 15758, 15767, 15775, 15784, 343}, {15793, 2122, 2900, 15797, 2061, 15801, 15806, 13164, 15810, 15814, 2154, 2908, 343}, 0, 0, 344, 346, {348},{357},{370},{376}},
+       {1112, 357, 348, 376, 370, 1136, 1146, 465, 468, {15628, 15636, 15641, 15648, 15658, 15664, 15671}, {15679, 15683, 2909, 15687, 15692, 15696, 15700}, {15705, 15713, 15722, 15728, 15734, 15739, 15745, 15751, 15758, 15767, 15775, 15784, 343}, {15793, 2131, 2909, 15797, 2070, 15801, 15806, 13164, 15810, 15814, 2163, 2917, 343}, 0, 0, 344, 346, {348},{357},{370},{376}},
        {1112, 357, 348, 376, 370, 1136, 1146, 15364, 15376, {15818, 12609, 15846, 12650, 12669, 12691, 12716}, {12735, 12745, 15410, 12768, 12778, 12791, 12807}, {15423, 15865, 12849, 15473, 15492, 12891, 15499, 15512, 15528, 15556, 15578, 15606, 343}, {15423, 15448, 12849, 15473, 15492, 12891, 15499, 15512, 15528, 15556, 15578, 15606, 343}, 0, 0, 344, 346, {348},{357},{370},{376}},
        {1, 24, 37, 46, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {87, 98, 113, 130, 147, 160, 173}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37},{357,24},{370,56},{376,46}},
        {387, 409, 422, 438, 370, 447, 457, 465, 468, {471, 484, 505, 520, 531, 550, 561}, {574, 582, 590, 596, 602, 612, 620}, {628, 641, 658, 667, 678, 685, 692, 699, 712, 731, 748, 763, 343}, {780, 786, 658, 794, 678, 685, 692, 802, 810, 818, 826, 836, 343}, 0, 1, 344, 346, {348,844,422},{357,409},{370},{376,438}},
-       {5975, 876, 2665, 438, 370, 447, 457, 465, 468, {897, 906, 914, 922, 931, 938, 948}, {957, 961, 965, 969, 973, 977, 981}, {985, 991, 998, 1004, 1010, 1015, 1020, 1027, 1033, 1042, 1050, 1059, 343}, {1068, 1073, 998, 1078, 1010, 1015, 1083, 1088, 1092, 1097, 1102, 1107, 343}, 0, 1, 344, 346, {348,888,2665},{357,876},{370},{376,438}},
-       {15896, 4984, 5251, 15941, 15964, 5017, 5033, 1154, 1161, {1168, 1178, 1188, 1198, 1208, 1218, 1228}, {1238, 1242, 1246, 1250, 1254, 1258, 1262}, {1266, 1273, 1280, 1287, 1294, 1301, 1308, 1315, 1322, 1329, 1336, 1346, 343}, {1266, 1273, 1280, 1287, 1294, 1301, 1308, 1315, 1322, 1329, 1336, 1346, 343}, 0, 0, 344, 346, {348,5251},{357,4984},{370,15964},{376,15941}},
-       {7267, 1379, 3314, 2982, 1409, 447, 1414, 1422, 1427, {1432, 1440, 1450, 1458, 1466, 1475, 1482}, {1489, 1492, 1495, 1499, 1502, 1506, 1510}, {1513, 1519, 1525, 1533, 1539, 1547, 1555, 1565, 1571, 1579, 1587, 1596, 343}, {1605, 1607, 1610, 1614, 1617, 1619, 1622, 1626, 1631, 1634, 1636, 1639, 343}, 0, 1, 344, 346, {348,1392,3314},{357,1379},{370,1409},{376,1399,2982}},
-       {1643, 1664, 1676, 438, 370, 447, 457, 465, 468, {1687, 1695, 1702, 1710, 1717, 1725, 1732}, {1740, 1745, 1749, 1753, 1757, 1761, 1765}, {1770, 1777, 1785, 1791, 1797, 1801, 1806, 1811, 1818, 1828, 1836, 1845, 343}, {1854, 1858, 1862, 1866, 1797, 1870, 1874, 1878, 1882, 1886, 1890, 1894, 343}, 0, 1, 344, 346, {348,1898,1676},{357,1664},{370},{376,438}},
-       {1907, 1379, 1929, 438, 370, 447, 1414, 1940, 1946, {1953, 1961, 1968, 1977, 1986, 1997, 2005}, {2013, 2016, 2019, 2022, 2025, 2028, 2031}, {2034, 2041, 2049, 2055, 2061, 2065, 2070, 2075, 2082, 2092, 2100, 2109, 343}, {2118, 2122, 2126, 2130, 2061, 2134, 2138, 2142, 2146, 2150, 2154, 2158, 343}, 0, 1, 344, 346, {348,844,1929},{357,1379},{370},{376,438}},
-       {2162, 409, 37, 2186, 56, 447, 457, 2197, 2202, {2207, 2222, 2237, 2248, 2263, 2276, 2295}, {2310, 2317, 2324, 2331, 2338, 2345, 2352}, {2359, 2380, 2403, 2418, 2435, 2446, 2461, 2476, 2495, 2518, 2537, 2556, 343}, {2577, 2584, 2591, 2598, 2605, 2612, 2621, 2630, 2637, 2644, 2651, 2658, 343}, 0, 1, 344, 346, {348,2665,37},{357,409},{370,56},{376,2676,2186}},
-       {2688, 2719, 10606, 2186, 2746, 63, 2754, 465, 468, {2761, 2768, 2775, 2783, 2793, 2802, 2809}, {2818, 2822, 2826, 2830, 2834, 2838, 2842}, {2846, 2854, 2863, 2055, 2869, 2873, 2878, 2075, 2082, 2883, 2100, 2891, 343}, {2118, 2122, 2900, 2130, 2869, 2134, 2138, 2142, 2146, 2904, 2154, 2908, 343}, 0, 0, 344, 346, {10606,10606,2739,2739,11818,3046,348,5996,15971},{2719,2719,2912,2926,2946},{2746,2746,2961,1409,370},{2186,2186,2970,2982,438}},
-       {3272, 3297, 3314, 2982, 370, 3323, 3336, 465, 468, {3348, 3358, 3368, 3376, 3388, 3396, 3406}, {3415, 3418, 3421, 3424, 3427, 3430, 3433}, {3436, 3445, 3454, 3464, 3473, 3482, 3491, 3501, 3508, 3516, 3524, 3534, 343}, {3543, 3549, 3555, 3562, 3568, 3574, 3580, 3587, 3591, 3596, 3601, 3608, 343}, 0, 1, 344, 346, {348,3314},{357,3297},{370},{376,2982}},
-       {3614, 3640, 2665, 438, 370, 447, 74, 465, 468, {3657, 3666, 3672, 3678, 3687, 3693, 3702}, {3709, 3714, 3719, 3724, 3729, 3734, 3739}, {3744, 3752, 3761, 3766, 3772, 3776, 3781, 3789, 3795, 3805, 1050, 3813, 343}, {3823, 3829, 3761, 3836, 3772, 3776, 3841, 3789, 3847, 1097, 1102, 3853, 343}, 0, 1, 344, 346, {888,3859,3264,2665},{357,876,3640},{370},{376,438}},
-       {3869, 876, 2665, 438, 370, 447, 74, 465, 468, {3890, 3908, 3922, 3940, 3958, 3976, 3992}, {3999, 4002, 4005, 4008, 4011, 4014, 4017}, {4020, 4031, 4044, 4051, 4062, 4069, 4078, 4087, 4100, 4113, 4128, 4141, 343}, {4152, 4159, 4044, 4166, 4062, 4173, 4180, 4187, 4194, 4201, 4208, 4215, 343}, 0, 0, 344, 346, {348,888,2665},{357,876},{370},{376,438}},
-       {4222, 4244, 4258, 2982, 1409, 4272, 4283, 4291, 4294, {4297, 4307, 4315, 4320, 4327, 4340, 4348}, {1617, 4356, 4358, 4360, 4364, 4367, 4369}, {4373, 4381, 4390, 4399, 4408, 4415, 4423, 4431, 4441, 4452, 1836, 1845, 343}, {4461, 4466, 4472, 4479, 4485, 4491, 4497, 4503, 4508, 4515, 1102, 4520, 343}, 0, 1, 344, 346, {348,4525,4258},{357,4244},{370,1409},{376,1399,2982}},
-       {1907, 1379, 3314, 438, 370, 447, 1414, 465, 468, {4537, 4548, 4559, 4573, 4587, 4599, 4611}, {4623, 4627, 4632, 4637, 4642, 4646, 4651}, {4655, 4663, 3761, 4672, 4679, 4684, 4691, 4698, 1818, 4452, 4706, 4716, 343}, {1854, 1858, 1862, 1866, 4679, 4725, 4730, 4735, 1882, 1886, 4741, 4746, 343}, 0, 0, 344, 346, {348,3314},{357,1379},{370},{376,438}},
-       {15981, 409, 2665, 16002, 370, 447, 74, 4774, 4777, {4780, 4789, 4797, 4806, 4817, 4826, 4835}, {3139, 3143, 1862, 4842, 4846, 4850, 4854}, {4858, 4866, 3179, 4875, 4882, 4889, 4896, 3202, 4903, 4913, 1050, 4921, 343}, {4930, 1858, 1862, 1866, 4934, 4938, 4942, 3252, 4946, 4950, 1890, 3260, 343}, 0, 1, 344, 346, {348,888,2665},{357,409},{370},{376,1399,16002}},
-       {4954, 4984, 5006, 2982, 1409, 5017, 5033, 5046, 5053, {5060, 5070, 5080, 5090, 5100, 5110, 5120}, {1238, 5130, 5134, 5138, 5142, 5146, 5150}, {5154, 5159, 5164, 5169, 5174, 5179, 5184, 5189, 5194, 5199, 5205, 5211, 343}, {5217, 5219, 5221, 5223, 5225, 5227, 5229, 5231, 5233, 5235, 5238, 5241, 343}, 0, 0, 344, 346, {5006,5006,348,5244,5251,5260,5279,5296},{4984,4984,5315,5339,5366},{1409,1409,370,5395,5403},{2982,438,5412,5423}},
-       {16010, 16060, 5006, 16084, 5395, 5568, 5585, 5599, 5606, {5613, 5623, 5633, 5643, 5653, 5663, 5673}, {5683, 5687, 5691, 5695, 5699, 5703, 5707}, {5711, 5716, 5721, 5726, 5731, 5736, 5741, 5746, 5751, 5756, 5762, 5768, 343}, {5711, 5716, 5721, 5726, 5731, 5736, 5741, 5746, 5751, 5756, 5762, 5768, 343}, 0, 0, 344, 346, {5006,5006,348,5244,5251,16110,16123},{16060,16060,16134,16160,16182},{5395,1409,370,16206,16220,16235,5395,5403,16251,16268,16286},{16084,16084,16305,16327,2982,438,16351,16376,5412,5423}},
-       {8861, 876, 16403, 2982, 1409, 447, 74, 465, 468, {5803, 5810, 5818, 5826, 5835, 5845, 5853}, {5862, 3418, 5865, 5868, 5871, 5874, 5877}, {5880, 5888, 5897, 1791, 5903, 1801, 1806, 5907, 1818, 1828, 1836, 1845, 343}, {1854, 1858, 5916, 1866, 5903, 1870, 1874, 1878, 1882, 1886, 1890, 1894, 343}, 0, 1, 344, 346, {348,5796,16403},{357,876},{370,1409},{376,1399,2982}},
-       {5920, 1379, 844, 5944, 5955, 447, 1414, 465, 468, {1687, 1695, 1702, 1710, 1717, 1725, 1732}, {5961, 3418, 3421, 5965, 3427, 5968, 5971}, {1770, 1777, 3761, 1791, 3772, 1801, 1806, 1811, 1818, 1828, 1836, 4716, 343}, {1854, 1858, 1862, 1866, 3772, 1870, 1874, 1878, 1882, 1886, 1890, 4746, 343}, 0, 1, 344, 346, {348,844},{357,1379},{370,5955},{376,5944}},
-       {5975, 876, 5996, 438, 370, 447, 74, 465, 468, {6007, 6017, 6031, 6038, 6045, 6054, 1482}, {6062, 6064, 6067, 6070, 6074, 6077, 2013}, {6080, 6089, 6094, 6101, 1797, 6111, 6120, 6127, 6137, 6147, 1587, 6160, 343}, {6170, 6174, 1862, 6178, 1797, 6182, 6186, 6190, 6194, 6198, 6203, 6207, 343}, 0, 1, 344, 346, {348,5515,5996},{357,876},{370},{376,438}},
-       {16412, 3024, 37, 438, 370, 3057, 3062, 465, 468, {3084, 6244, 6258, 6271, 6284, 6297, 3131}, {3139, 6309, 6313, 6317, 6321, 6325, 3160}, {6329, 6337, 6347, 1004, 6354, 6359, 6365, 3202, 6371, 6380, 6388, 6397, 343}, {1854, 6406, 1862, 3244, 3772, 1870, 1874, 3252, 4946, 6410, 1890, 6414, 343}, 0, 0, 344, 346, {348,1676,888,37},{357,3024},{370},{376,16443,438}},
-       {5975, 876, 1929, 438, 370, 447, 74, 465, 468, {6418, 6428, 6433, 6440, 6449, 6453, 6460}, {6471, 6473, 6475, 2022, 6478, 1617, 6480}, {6482, 6491, 6501, 6508, 3772, 6516, 6522, 1811, 6528, 6539, 6549, 6559, 343}, {6569, 2122, 2900, 2130, 2061, 6573, 6577, 2142, 2146, 2904, 2154, 2908, 343}, 0, 1, 344, 346, {348,1929},{357,876},{370},{376,438}},
-       {6581, 6607, 1929, 2982, 1409, 6625, 74, 465, 468, {6641, 6664, 505, 6687, 6698, 6713, 6728}, {6743, 6748, 6753, 6758, 6763, 6768, 6773}, {6778, 6791, 6806, 6815, 6828, 6835, 6844, 6853, 6866, 6883, 6898, 6911, 343}, {6926, 6933, 6940, 6947, 678, 6954, 6961, 6968, 6975, 6982, 6989, 6996, 343}, 0, 1, 344, 346, {348,844,1929},{357,6607},{370,1409},{376,1399,2982}},
-       {7003, 7025, 3314, 2982, 370, 4272, 1146, 465, 468, {7039, 7048, 7060, 7067, 7075, 7085, 7091}, {7098, 7102, 7106, 7110, 7114, 7119, 7123}, {7127, 7137, 7146, 7154, 7162, 7170, 7177, 7184, 7192, 1587, 7198, 7206, 343}, {7215, 7219, 7223, 7228, 7232, 6186, 7236, 7240, 7244, 6203, 7248, 7252, 343}, 0, 1, 344, 346, {348,7256,3314},{357,7025},{370},{376,2982}},
-       {7267, 1379, 7288, 2982, 1409, 447, 1414, 465, 468, {7299, 7307, 7316, 7323, 7330, 7339, 7346}, {7353, 7356, 7359, 7362, 7365, 7369, 2013}, {4373, 4381, 7372, 4672, 7378, 4725, 4730, 1811, 1818, 4452, 1836, 1845, 343}, {1854, 1858, 1862, 1866, 7378, 4725, 4730, 1878, 1882, 1886, 1890, 1894, 343}, 0, 1, 344, 346, {348,3314,7288},{357,1379},{370,1409},{376,1399,2982}},
-       {7383, 409, 5996, 7407, 7418, 447, 457, 7425, 7428, {7431, 7438, 7447, 7456, 7468, 7476, 7485}, {7495, 7499, 2900, 7504, 7509, 7513, 7517}, {7521, 7527, 3761, 7534, 1797, 7540, 7548, 7555, 7561, 7569, 7575, 7583, 343}, {2118, 7591, 2900, 7595, 7599, 7603, 7607, 7611, 7517, 7615, 7619, 7624, 343}, 0, 1, 344, 346, {348,5515,5996},{357,409},{370,7418},{376,7628,7407}},
-       {16460, 7668, 5996, 438, 370, 447, 74, 7685, 7688, {7691, 7699, 7707, 1710, 1717, 1725, 7714}, {7722, 7726, 3421, 5965, 3427, 5968, 7730}, {5880, 5888, 3761, 1791, 1797, 1801, 1806, 7734, 1818, 1828, 1836, 1845, 343}, {1854, 1858, 1862, 1866, 1797, 1870, 1874, 1878, 1882, 1886, 1890, 1894, 343}, 0, 1, 344, 346, {348,5996},{357,7668},{370,5955},{376,5944,438}},
-       {7742, 876, 37, 2982, 1409, 447, 74, 7763, 7794, {7825, 7856, 7884, 7912, 7931, 7965, 7990}, {8015, 8023, 8028, 8033, 8038, 8046, 8051}, {8056, 8075, 8106, 8125, 8144, 8166, 8191, 8213, 8235, 8257, 8276, 8304, 343}, {8326, 8335, 8344, 8356, 8368, 8377, 8389, 8398, 8407, 8416, 8425, 8434, 343}, 0, 0, 344, 346, {348,37},{357,876},{370,1409},{376,8443,2982}},
-       {8483, 8510, 1929, 438, 370, 447, 457, 465, 468, {8528, 8534, 8544, 8550, 8561, 8571, 8576}, {8586, 8590, 8594, 8598, 8603, 8607, 8611}, {8615, 8620, 8627, 8632, 8638, 8645, 8653, 8660, 8669, 8676, 8681, 8688, 343}, {8696, 8700, 2900, 8705, 2869, 8709, 8713, 8717, 8722, 8726, 8730, 8734, 343}, 0, 1, 344, 346, {348,1929},{357,8510},{370},{376,438}},
-       {16486, 409, 2665, 2982, 1409, 447, 457, 465, 468, {8738, 8745, 8751, 8758, 8763, 8769, 8775}, {8781, 8785, 8789, 8793, 8797, 8801, 8805}, {8809, 8817, 8826, 2055, 8832, 2065, 2070, 8836, 2082, 2092, 2100, 8844, 343}, {2118, 2122, 2900, 2130, 8832, 2134, 2138, 8853, 2146, 2150, 2154, 8857, 343}, 0, 0, 344, 346, {348,888,2665},{357,409},{370,1409},{376,2982}},
-       {8861, 876, 1929, 2982, 370, 8881, 74, 465, 468, {8897, 8910, 8929, 8946, 8959, 8972, 8988}, {9001, 6748, 6753, 6758, 6763, 6768, 6773}, {9006, 9017, 9030, 9045, 9058, 9071, 9084, 9095, 9108, 9123, 9136, 9155, 343}, {9168, 9175, 9182, 9189, 9198, 9207, 9216, 9223, 9232, 9239, 9248, 9257, 343}, 0, 1, 344, 346, {348,844,1929},{357,876},{370},{376,2982}},
-       {8861, 876, 1929, 2982, 5955, 447, 74, 465, 468, {9289, 9304, 9325, 9340, 9353, 9366, 9381}, {9394, 9399, 9404, 9409, 9414, 9419, 9424}, {9429, 9446, 9455, 9470, 678, 9487, 9502, 9515, 9530, 9547, 9568, 9585, 343}, {9600, 9175, 9607, 9614, 678, 9621, 9628, 9635, 9232, 9642, 9649, 9656, 343}, 0, 1, 344, 346, {348,1392,1929},{357,876},{370,5955},{376,5944,2982}},
-       {9663, 9685, 3314, 2982, 1409, 447, 9699, 465, 468, {9708, 9716, 9727, 9733, 9739, 9748, 1482}, {7098, 7102, 1757, 9754, 7114, 7119, 9758}, {1770, 1777, 7372, 1791, 1797, 9762, 9768, 9774, 1818, 1828, 1836, 1845, 343}, {1854, 1858, 1862, 1866, 1797, 1870, 1874, 9781, 1882, 1886, 1890, 1894, 343}, 0, 1, 344, 346, {348,9785,3314},{357,9685},{370,1409},{376,1399,2982}},
-       {8861, 876, 9792, 2982, 1409, 447, 9802, 465, 468, {9810, 9821, 9832, 9843, 9854, 9865, 9871}, {4367, 9880, 9882, 4358, 6062, 9884, 6473}, {9886, 9894, 9903, 9910, 3772, 9917, 9923, 1811, 1818, 9929, 1836, 9938, 343}, {9948, 9953, 9903, 1866, 3772, 9917, 9923, 1878, 9959, 1886, 1890, 9964, 343}, 0, 1, 344, 346, {348,844,9792},{357,876},{370,1409},{376,1399,2982}},
-       {9969, 9998, 4525, 2982, 370, 10019, 1414, 465, 468, {10037, 10048, 10058, 10067, 10078, 10090, 10101}, {10111, 4367, 10114, 9882, 10116, 10118, 6480}, {10121, 10131, 1785, 10142, 10151, 10157, 10165, 10173, 10181, 10192, 10201, 10211, 343}, {2118, 2122, 2900, 2130, 2061, 10221, 10226, 2142, 2146, 2150, 2154, 2908, 343}, 0, 1, 344, 346, {348,10231,4525},{357,9998},{370},{376,2982}},
-       {16507, 10271, 7256, 438, 370, 10293, 10308, 465, 468, {10320, 10332, 10344, 10356, 10370, 10385, 10398}, {10412, 10415, 10418, 10421, 10424, 6064, 7365}, {10427, 10434, 10442, 10447, 10458, 10468, 10478, 10485, 10497, 10506, 10513, 10524, 343}, {10534, 10538, 10542, 10546, 10550, 10554, 10558, 10562, 10566, 10570, 10574, 10578, 343}, 0, 1, 344, 346, {348,7256},{357,10271},{370},{376,438}},
-       {10582, 876, 10606, 2970, 370, 447, 74, 10615, 10622, {10629, 10645, 10658, 10674, 10691, 10709, 10718}, {10727, 10731, 10735, 10739, 10743, 10747, 10751}, {10755, 10768, 229, 10779, 10790, 10795, 10804, 10815, 10822, 10837, 10848, 10861, 343}, {10874, 10881, 10888, 10895, 10902, 10909, 10916, 10815, 10923, 10930, 10937, 10944, 343}, 0, 6, 344, 346, {348,10951,10606},{357,876},{370},{376,10961,2970}},
-       {10974, 409, 2665, 2186, 370, 447, 457, 10998, 11001, {11004, 11017, 11027, 11036, 11046, 11057, 11068}, {11080, 11083, 11088, 11093, 11098, 11103, 11108}, {11113, 11126, 11137, 11147, 11158, 11170, 11182, 11195, 11207, 11220, 11235, 11256, 343}, {11275, 11281, 11287, 11293, 11299, 11305, 11311, 11317, 11323, 11329, 11336, 11343, 343}, 0, 1, 344, 346, {348,2665},{357,409},{370},{376,2186}},
-       {11350, 2912, 1929, 2982, 370, 447, 2754, 11372, 16538, {11388, 11401, 11422, 11441, 11462, 11481, 11494}, {11505, 11512, 11519, 11526, 11533, 11540, 11547}, {16546, 16561, 11588, 11597, 11608, 16576, 16589, 11645, 11660, 11679, 11698, 11715, 343}, {16602, 16609, 11748, 11755, 11762, 16616, 16623, 11783, 11790, 11797, 11804, 11811, 343}, 0, 1, 344, 346, {348,11818,1929},{357,2912},{370},{376,2982}},
-       {16630, 16669, 5006, 438, 370, 16699, 1146, 465, 468, {11827, 11835, 11846, 11856, 11867, 11876, 11885}, {11895, 11898, 11901, 11904, 11907, 11910, 11913}, {11916, 11926, 11934, 11942, 11950, 11958, 11965, 11973, 11981, 11988, 11994, 12001, 343}, {12009, 12013, 1862, 12017, 3772, 12021, 12025, 12029, 12033, 12037, 12041, 12045, 343}, 0, 1, 344, 346, {348,16714,5006},{357,16669},{370},{376,438}},
-       {387, 409, 1929, 438, 370, 447, 457, 465, 468, {12049, 484, 505, 6687, 12062, 12079, 12090}, {574, 582, 590, 12103, 12111, 612, 12119}, {12127, 641, 658, 667, 12142, 12149, 12158, 699, 712, 731, 748, 763, 343}, {12167, 786, 12175, 794, 12183, 12191, 12199, 802, 12207, 818, 826, 12217, 343}, 0, 1, 344, 346, {348,12229,1929},{357,409},{370},{376,438}},
-       {16727, 409, 5006, 2970, 56, 447, 457, 343, 343, {12243, 12250, 12258, 12266, 12275, 12285, 12292}, {2013, 6475, 2019, 12301, 2025, 12304, 2031}, {12307, 12316, 12326, 2055, 8832, 12332, 12338, 12344, 2082, 2092, 2100, 8844, 343}, {2118, 2122, 2900, 2130, 8832, 2134, 2138, 2142, 2146, 2150, 2154, 8857, 343}, 0, 0, 344, 346, {348,5006},{357,409},{370,56},{376,46,2970}},
-       {16752, 16792, 1929, 2982, 1409, 12382, 1146, 12389, 12405, {5217, 5219, 5221, 5223, 5225, 5227, 5229}, {5217, 5219, 5221, 5223, 5225, 5227, 5229}, {5217, 5219, 5221, 5223, 5225, 5227, 5229, 5231, 5233, 5235, 5238, 5241, 343}, {5217, 5219, 5221, 5223, 5225, 5227, 5229, 5231, 5233, 5235, 5238, 5241, 343}, 0, 0, 344, 346, {348,1929},{357,12373,16792},{370,1409},{376,2982}},
-       {16824, 1664, 1676, 16845, 370, 447, 457, 465, 468, {4537, 12450, 12461, 12471, 12481, 12491, 12505}, {4623, 4627, 12517, 12522, 12526, 12531, 12536}, {1770, 1777, 3761, 4672, 3772, 1801, 1806, 1811, 1818, 1828, 1836, 4716, 343}, {1854, 1858, 1862, 1866, 3772, 1870, 1874, 1878, 1882, 1886, 1890, 4746, 343}, 0, 0, 344, 346, {348,1898,1676},{357,1664},{370},{376,16845}},
-       {5975, 876, 1676, 438, 56, 447, 74, 12540, 12568, {12590, 12609, 12628, 12650, 12669, 12691, 12716}, {12735, 12745, 12755, 12768, 12778, 12791, 12807}, {12817, 12833, 12849, 12865, 12884, 12891, 12901, 12917, 12933, 12955, 12977, 12996, 343}, {12817, 12833, 12849, 12865, 12884, 12891, 12901, 12917, 12933, 12955, 12977, 12996, 343}, 0, 0, 344, 346, {348,5796,1676},{357,876},{370,56},{376,2676,438}},
-       {16854, 357, 10606, 16878, 370, 1136, 1146, 465, 468, {13018, 13027, 13036, 13044, 13053, 13062, 13069}, {13078, 13082, 13086, 13090, 13094, 13098, 13102}, {8809, 8817, 13106, 13112, 8832, 2065, 13119, 13125, 13132, 13141, 13148, 13156, 343}, {2118, 2122, 2900, 2130, 8832, 2134, 2138, 13164, 2146, 2150, 2154, 8857, 343}, 0, 6, 344, 346, {348,10606},{357},{370},{376,16878}},
+       {5984, 876, 2674, 438, 370, 447, 457, 465, 468, {897, 906, 914, 922, 931, 938, 948}, {957, 961, 965, 969, 973, 977, 981}, {985, 991, 998, 1004, 1010, 1015, 1020, 1027, 1033, 1042, 1050, 1059, 343}, {1068, 1073, 998, 1078, 1010, 1015, 1083, 1088, 1092, 1097, 1102, 1107, 343}, 0, 1, 344, 346, {348,888,2674},{357,876},{370},{376,438}},
+       {15896, 4993, 5260, 15941, 15964, 5026, 5042, 1154, 1161, {1168, 1178, 1188, 1198, 1208, 1218, 1228}, {1238, 1242, 1246, 1250, 1254, 1258, 1262}, {1266, 1273, 1280, 1287, 1294, 1301, 1308, 1315, 1322, 1329, 1336, 1346, 343}, {1266, 1273, 1280, 1287, 1294, 1301, 1308, 1315, 1322, 1329, 1336, 1346, 343}, 0, 0, 344, 346, {348,5260},{357,4993},{370,15964},{376,15941}},
+       {7276, 1379, 3323, 2991, 1409, 447, 1414, 1422, 1427, {1432, 1440, 1450, 1458, 1466, 1475, 1482}, {1489, 1492, 1495, 1499, 1502, 1506, 1510}, {1513, 1519, 1525, 1533, 1539, 1547, 1555, 1565, 1571, 1579, 1587, 1596, 343}, {1605, 1607, 1610, 1614, 1617, 1619, 1622, 1626, 1631, 1634, 1636, 1639, 343}, 0, 1, 344, 346, {348,1392,3323},{357,1379},{370,1409},{376,1399,2991}},
+       {1643, 1664, 1676, 438, 370, 447, 1687, 465, 468, {1696, 1704, 1711, 1719, 1726, 1734, 1741}, {1749, 1754, 1758, 1762, 1766, 1770, 1774}, {1779, 1786, 1794, 1800, 1806, 1810, 1815, 1820, 1827, 1837, 1845, 1854, 343}, {1863, 1867, 1871, 1875, 1806, 1879, 1883, 1887, 1891, 1895, 1899, 1903, 343}, 0, 1, 344, 346, {348,1907,1676},{357,1664},{370},{376,438}},
+       {1916, 1379, 1938, 438, 370, 447, 1414, 1949, 1955, {1962, 1970, 1977, 1986, 1995, 2006, 2014}, {2022, 2025, 2028, 2031, 2034, 2037, 2040}, {2043, 2050, 2058, 2064, 2070, 2074, 2079, 2084, 2091, 2101, 2109, 2118, 343}, {2127, 2131, 2135, 2139, 2070, 2143, 2147, 2151, 2155, 2159, 2163, 2167, 343}, 0, 1, 344, 346, {348,844,1938},{357,1379},{370},{376,438}},
+       {2171, 409, 37, 2195, 56, 447, 457, 2206, 2211, {2216, 2231, 2246, 2257, 2272, 2285, 2304}, {2319, 2326, 2333, 2340, 2347, 2354, 2361}, {2368, 2389, 2412, 2427, 2444, 2455, 2470, 2485, 2504, 2527, 2546, 2565, 343}, {2586, 2593, 2600, 2607, 2614, 2621, 2630, 2639, 2646, 2653, 2660, 2667, 343}, 0, 1, 344, 346, {348,2674,37},{357,409},{370,56},{376,2685,2195}},
+       {2697, 2728, 10606, 2195, 2755, 63, 2763, 465, 468, {2770, 2777, 2784, 2792, 2802, 2811, 2818}, {2827, 2831, 2835, 2839, 2843, 2847, 2851}, {2855, 2863, 2872, 2064, 2878, 2882, 2887, 2084, 2091, 2892, 2109, 2900, 343}, {2127, 2131, 2909, 2139, 2878, 2143, 2147, 2151, 2155, 2913, 2163, 2917, 343}, 0, 0, 344, 346, {10606,10606,2748,2748,11818,3055,348,6005,15971},{2728,2728,2921,2935,2955},{2755,2755,2970,1409,370},{2195,2195,2979,2991,438}},
+       {3281, 3306, 3323, 2991, 370, 3332, 3345, 465, 468, {3357, 3367, 3377, 3385, 3397, 3405, 3415}, {3424, 3427, 3430, 3433, 3436, 3439, 3442}, {3445, 3454, 3463, 3473, 3482, 3491, 3500, 3510, 3517, 3525, 3533, 3543, 343}, {3552, 3558, 3564, 3571, 3577, 3583, 3589, 3596, 3600, 3605, 3610, 3617, 343}, 0, 1, 344, 346, {348,3323},{357,3306},{370},{376,2991}},
+       {3623, 3649, 2674, 438, 370, 447, 74, 465, 468, {3666, 3675, 3681, 3687, 3696, 3702, 3711}, {3718, 3723, 3728, 3733, 3738, 3743, 3748}, {3753, 3761, 3770, 3775, 3781, 3785, 3790, 3798, 3804, 3814, 1050, 3822, 343}, {3832, 3838, 3770, 3845, 3781, 3785, 3850, 3798, 3856, 1097, 1102, 3862, 343}, 0, 1, 344, 346, {888,3868,3273,2674},{357,876,3649},{370},{376,438}},
+       {3878, 876, 2674, 438, 370, 447, 74, 465, 468, {3899, 3917, 3931, 3949, 3967, 3985, 4001}, {4008, 4011, 4014, 4017, 4020, 4023, 4026}, {4029, 4040, 4053, 4060, 4071, 4078, 4087, 4096, 4109, 4122, 4137, 4150, 343}, {4161, 4168, 4053, 4175, 4071, 4182, 4189, 4196, 4203, 4210, 4217, 4224, 343}, 0, 0, 344, 346, {348,888,2674},{357,876},{370},{376,438}},
+       {4231, 4253, 4267, 2991, 1409, 4281, 4292, 4300, 4303, {4306, 4316, 4324, 4329, 4336, 4349, 4357}, {1617, 4365, 4367, 4369, 4373, 4376, 4378}, {4382, 4390, 4399, 4408, 4417, 4424, 4432, 4440, 4450, 4461, 1845, 1854, 343}, {4470, 4475, 4481, 4488, 4494, 4500, 4506, 4512, 4517, 4524, 1102, 4529, 343}, 0, 1, 344, 346, {348,4534,4267},{357,4253},{370,1409},{376,1399,2991}},
+       {1916, 1379, 3323, 438, 370, 447, 1414, 465, 468, {4546, 4557, 4568, 4582, 4596, 4608, 4620}, {4632, 4636, 4641, 4646, 4651, 4655, 4660}, {4664, 4672, 3770, 4681, 4688, 4693, 4700, 4707, 1827, 4461, 4715, 4725, 343}, {1863, 1867, 1871, 1875, 4688, 4734, 4739, 4744, 1891, 1895, 4750, 4755, 343}, 0, 0, 344, 346, {348,3323},{357,1379},{370},{376,438}},
+       {15981, 409, 2674, 16002, 370, 447, 74, 4783, 4786, {4789, 4798, 4806, 4815, 4826, 4835, 4844}, {3148, 3152, 1871, 4851, 4855, 4859, 4863}, {4867, 4875, 3188, 4884, 4891, 4898, 4905, 3211, 4912, 4922, 1050, 4930, 343}, {4939, 1867, 1871, 1875, 4943, 4947, 4951, 3261, 4955, 4959, 1899, 3269, 343}, 0, 1, 344, 346, {348,888,2674},{357,409},{370},{376,1399,16002}},
+       {4963, 4993, 5015, 2991, 1409, 5026, 5042, 5055, 5062, {5069, 5079, 5089, 5099, 5109, 5119, 5129}, {1238, 5139, 5143, 5147, 5151, 5155, 5159}, {5163, 5168, 5173, 5178, 5183, 5188, 5193, 5198, 5203, 5208, 5214, 5220, 343}, {5226, 5228, 5230, 5232, 5234, 5236, 5238, 5240, 5242, 5244, 5247, 5250, 343}, 0, 0, 344, 346, {5015,5015,348,5253,5260,5269,5288,5305},{4993,4993,5324,5348,5375},{1409,1409,370,5404,5412},{2991,438,5421,5432}},
+       {16010, 16060, 5015, 16084, 5404, 5577, 5594, 5608, 5615, {5622, 5632, 5642, 5652, 5662, 5672, 5682}, {5692, 5696, 5700, 5704, 5708, 5712, 5716}, {5720, 5725, 5730, 5735, 5740, 5745, 5750, 5755, 5760, 5765, 5771, 5777, 343}, {5720, 5725, 5730, 5735, 5740, 5745, 5750, 5755, 5760, 5765, 5771, 5777, 343}, 0, 0, 344, 346, {5015,5015,348,5253,5260,16110,16123},{16060,16060,16134,16160,16182},{5404,1409,370,16206,16220,16235,5404,5412,16251,16268,16286},{16084,16084,16305,16327,2991,438,16351,16376,5421,5432}},
+       {8870, 876, 16403, 2991, 1409, 447, 74, 465, 468, {5812, 5819, 5827, 5835, 5844, 5854, 5862}, {5871, 3427, 5874, 5877, 5880, 5883, 5886}, {5889, 5897, 5906, 1800, 5912, 1810, 1815, 5916, 1827, 1837, 1845, 1854, 343}, {1863, 1867, 5925, 1875, 5912, 1879, 1883, 1887, 1891, 1895, 1899, 1903, 343}, 0, 1, 344, 346, {348,5805,16403},{357,876},{370,1409},{376,1399,2991}},
+       {5929, 1379, 844, 5953, 5964, 447, 1414, 465, 468, {1696, 1704, 1711, 1719, 1726, 1734, 1741}, {5970, 3427, 3430, 5974, 3436, 5977, 5980}, {1779, 1786, 3770, 1800, 3781, 1810, 1815, 1820, 1827, 1837, 1845, 4725, 343}, {1863, 1867, 1871, 1875, 3781, 1879, 1883, 1887, 1891, 1895, 1899, 4755, 343}, 0, 1, 344, 346, {348,844},{357,1379},{370,5964},{376,5953}},
+       {5984, 876, 6005, 438, 370, 447, 74, 465, 468, {6016, 6026, 6040, 6047, 6054, 6063, 1482}, {6071, 6073, 6076, 6079, 6083, 6086, 2022}, {6089, 6098, 6103, 6110, 1806, 6120, 6129, 6136, 6146, 6156, 1587, 6169, 343}, {6179, 6183, 1871, 6187, 1806, 6191, 6195, 6199, 6203, 6207, 6212, 6216, 343}, 0, 1, 344, 346, {348,5524,6005},{357,876},{370},{376,438}},
+       {16412, 3033, 37, 438, 370, 3066, 3071, 465, 468, {3093, 6253, 6267, 6280, 6293, 6306, 3140}, {3148, 6318, 6322, 6326, 6330, 6334, 3169}, {6338, 6346, 6356, 1004, 6363, 6368, 6374, 3211, 6380, 6389, 6397, 6406, 343}, {1863, 6415, 1871, 3253, 3781, 1879, 1883, 3261, 4955, 6419, 1899, 6423, 343}, 0, 0, 344, 346, {348,1676,888,37},{357,3033},{370},{376,16443,438}},
+       {5984, 876, 1938, 438, 370, 447, 74, 465, 468, {6427, 6437, 6442, 6449, 6458, 6462, 6469}, {6480, 6482, 6484, 2031, 6487, 1617, 6489}, {6491, 6500, 6510, 6517, 3781, 6525, 6531, 1820, 6537, 6548, 6558, 6568, 343}, {6578, 2131, 2909, 2139, 2070, 6582, 6586, 2151, 2155, 2913, 2163, 2917, 343}, 0, 1, 344, 346, {348,1938},{357,876},{370},{376,438}},
+       {6590, 6616, 1938, 2991, 1409, 6634, 74, 465, 468, {6650, 6673, 505, 6696, 6707, 6722, 6737}, {6752, 6757, 6762, 6767, 6772, 6777, 6782}, {6787, 6800, 6815, 6824, 6837, 6844, 6853, 6862, 6875, 6892, 6907, 6920, 343}, {6935, 6942, 6949, 6956, 678, 6963, 6970, 6977, 6984, 6991, 6998, 7005, 343}, 0, 1, 344, 346, {348,844,1938},{357,6616},{370,1409},{376,1399,2991}},
+       {7012, 7034, 3323, 2991, 370, 4281, 1146, 465, 468, {7048, 7057, 7069, 7076, 7084, 7094, 7100}, {7107, 7111, 7115, 7119, 7123, 7128, 7132}, {7136, 7146, 7155, 7163, 7171, 7179, 7186, 7193, 7201, 1587, 7207, 7215, 343}, {7224, 7228, 7232, 7237, 7241, 6195, 7245, 7249, 7253, 6212, 7257, 7261, 343}, 0, 1, 344, 346, {348,7265,3323},{357,7034},{370},{376,2991}},
+       {7276, 1379, 7297, 2991, 1409, 447, 1414, 465, 468, {7308, 7316, 7325, 7332, 7339, 7348, 7355}, {7362, 7365, 7368, 7371, 7374, 7378, 2022}, {4382, 4390, 7381, 4681, 7387, 4734, 4739, 1820, 1827, 4461, 1845, 1854, 343}, {1863, 1867, 1871, 1875, 7387, 4734, 4739, 1887, 1891, 1895, 1899, 1903, 343}, 0, 1, 344, 346, {348,3323,7297},{357,1379},{370,1409},{376,1399,2991}},
+       {7392, 409, 6005, 7416, 7427, 447, 457, 7434, 7437, {7440, 7447, 7456, 7465, 7477, 7485, 7494}, {7504, 7508, 2909, 7513, 7518, 7522, 7526}, {7530, 7536, 3770, 7543, 1806, 7549, 7557, 7564, 7570, 7578, 7584, 7592, 343}, {2127, 7600, 2909, 7604, 7608, 7612, 7616, 7620, 7526, 7624, 7628, 7633, 343}, 0, 1, 344, 346, {348,5524,6005},{357,409},{370,7427},{376,7637,7416}},
+       {16460, 7677, 6005, 438, 370, 447, 74, 7694, 7697, {7700, 7708, 7716, 1719, 1726, 1734, 7723}, {7731, 7735, 3430, 5974, 3436, 5977, 7739}, {5889, 5897, 3770, 1800, 1806, 1810, 1815, 7743, 1827, 1837, 1845, 1854, 343}, {1863, 1867, 1871, 1875, 1806, 1879, 1883, 1887, 1891, 1895, 1899, 1903, 343}, 0, 1, 344, 346, {348,6005},{357,7677},{370,5964},{376,5953,438}},
+       {7751, 876, 37, 2991, 1409, 447, 74, 7772, 7803, {7834, 7865, 7893, 7921, 7940, 7974, 7999}, {8024, 8032, 8037, 8042, 8047, 8055, 8060}, {8065, 8084, 8115, 8134, 8153, 8175, 8200, 8222, 8244, 8266, 8285, 8313, 343}, {8335, 8344, 8353, 8365, 8377, 8386, 8398, 8407, 8416, 8425, 8434, 8443, 343}, 0, 0, 344, 346, {348,37},{357,876},{370,1409},{376,8452,2991}},
+       {8492, 8519, 1938, 438, 370, 447, 457, 465, 468, {8537, 8543, 8553, 8559, 8570, 8580, 8585}, {8595, 8599, 8603, 8607, 8612, 8616, 8620}, {8624, 8629, 8636, 8641, 8647, 8654, 8662, 8669, 8678, 8685, 8690, 8697, 343}, {8705, 8709, 2909, 8714, 2878, 8718, 8722, 8726, 8731, 8735, 8739, 8743, 343}, 0, 1, 344, 346, {348,1938},{357,8519},{370},{376,438}},
+       {16486, 409, 2674, 2991, 1409, 447, 457, 465, 468, {8747, 8754, 8760, 8767, 8772, 8778, 8784}, {8790, 8794, 8798, 8802, 8806, 8810, 8814}, {8818, 8826, 8835, 2064, 8841, 2074, 2079, 8845, 2091, 2101, 2109, 8853, 343}, {2127, 2131, 2909, 2139, 8841, 2143, 2147, 8862, 2155, 2159, 2163, 8866, 343}, 0, 0, 344, 346, {348,888,2674},{357,409},{370,1409},{376,2991}},
+       {8870, 876, 1938, 2991, 370, 8890, 74, 465, 468, {8906, 8919, 8938, 8955, 8968, 8981, 8997}, {9010, 6757, 6762, 6767, 6772, 6777, 6782}, {9015, 9026, 9039, 9054, 9067, 9080, 9093, 9104, 9117, 9132, 9145, 9164, 343}, {9177, 9184, 9191, 9198, 9207, 9216, 9225, 9232, 9241, 9248, 9257, 9266, 343}, 0, 1, 344, 346, {348,844,1938},{357,876},{370},{376,2991}},
+       {8870, 876, 1938, 2991, 5964, 447, 74, 465, 468, {9298, 9313, 9334, 9349, 9362, 9375, 9390}, {9403, 9408, 9413, 9418, 9423, 9428, 9433}, {9438, 9455, 9464, 9479, 678, 9496, 9511, 9524, 9539, 9556, 9577, 9594, 343}, {9609, 9184, 9616, 9623, 678, 9630, 9637, 9644, 9241, 9651, 9658, 9665, 343}, 0, 1, 344, 346, {348,1392,1938},{357,876},{370,5964},{376,5953,2991}},
+       {9672, 9694, 3323, 2991, 1409, 447, 1687, 465, 468, {9708, 9716, 9727, 9733, 9739, 9748, 1482}, {7107, 7111, 1766, 9754, 7123, 7128, 9758}, {1779, 1786, 7381, 1800, 1806, 9762, 9768, 9774, 1827, 1837, 1845, 1854, 343}, {1863, 1867, 1871, 1875, 1806, 1879, 1883, 9781, 1891, 1895, 1899, 1903, 343}, 0, 1, 344, 346, {348,9785,3323},{357,9694},{370,1409},{376,1399,2991}},
+       {8870, 876, 9792, 2991, 1409, 447, 9802, 465, 468, {9810, 9821, 9832, 9843, 9854, 9865, 9871}, {4376, 9880, 9882, 4367, 6071, 9884, 6482}, {9886, 9894, 9903, 9910, 3781, 9917, 9923, 1820, 1827, 9929, 1845, 9938, 343}, {9948, 9953, 9903, 1875, 3781, 9917, 9923, 1887, 9959, 1895, 1899, 9964, 343}, 0, 1, 344, 346, {348,844,9792},{357,876},{370,1409},{376,1399,2991}},
+       {9969, 9998, 4534, 2991, 370, 10019, 1414, 465, 468, {10037, 10048, 10058, 10067, 10078, 10090, 10101}, {10111, 4376, 10114, 9882, 10116, 10118, 6489}, {10121, 10131, 1794, 10142, 10151, 10157, 10165, 10173, 10181, 10192, 10201, 10211, 343}, {2127, 2131, 2909, 2139, 2070, 10221, 10226, 2151, 2155, 2159, 2163, 2917, 343}, 0, 1, 344, 346, {348,10231,4534},{357,9998},{370},{376,2991}},
+       {16507, 10271, 7265, 438, 370, 10293, 10308, 465, 468, {10320, 10332, 10344, 10356, 10370, 10385, 10398}, {10412, 10415, 10418, 10421, 10424, 6073, 7374}, {10427, 10434, 10442, 10447, 10458, 10468, 10478, 10485, 10497, 10506, 10513, 10524, 343}, {10534, 10538, 10542, 10546, 10550, 10554, 10558, 10562, 10566, 10570, 10574, 10578, 343}, 0, 1, 344, 346, {348,7265},{357,10271},{370},{376,438}},
+       {10582, 876, 10606, 2979, 370, 447, 74, 10615, 10622, {10629, 10645, 10658, 10674, 10691, 10709, 10718}, {10727, 10731, 10735, 10739, 10743, 10747, 10751}, {10755, 10768, 229, 10779, 10790, 10795, 10804, 10815, 10822, 10837, 10848, 10861, 343}, {10874, 10881, 10888, 10895, 10902, 10909, 10916, 10815, 10923, 10930, 10937, 10944, 343}, 0, 6, 344, 346, {348,10951,10606},{357,876},{370},{376,10961,2979}},
+       {10974, 409, 2674, 2195, 370, 447, 457, 10998, 11001, {11004, 11017, 11027, 11036, 11046, 11057, 11068}, {11080, 11083, 11088, 11093, 11098, 11103, 11108}, {11113, 11126, 11137, 11147, 11158, 11170, 11182, 11195, 11207, 11220, 11235, 11256, 343}, {11275, 11281, 11287, 11293, 11299, 11305, 11311, 11317, 11323, 11329, 11336, 11343, 343}, 0, 1, 344, 346, {348,2674},{357,409},{370},{376,2195}},
+       {11350, 2921, 1938, 2991, 370, 447, 2763, 11372, 16538, {11388, 11401, 11422, 11441, 11462, 11481, 11494}, {11505, 11512, 11519, 11526, 11533, 11540, 11547}, {16546, 16561, 11588, 11597, 11608, 16576, 16589, 11645, 11660, 11679, 11698, 11715, 343}, {16602, 16609, 11748, 11755, 11762, 16616, 16623, 11783, 11790, 11797, 11804, 11811, 343}, 0, 1, 344, 346, {348,11818,1938},{357,2921},{370},{376,2991}},
+       {16630, 16669, 5015, 438, 370, 16699, 1146, 465, 468, {11827, 11835, 11846, 11856, 11867, 11876, 11885}, {11895, 11898, 11901, 11904, 11907, 11910, 11913}, {11916, 11926, 11934, 11942, 11950, 11958, 11965, 11973, 11981, 11988, 11994, 12001, 343}, {12009, 12013, 1871, 12017, 3781, 12021, 12025, 12029, 12033, 12037, 12041, 12045, 343}, 0, 1, 344, 346, {348,16714,5015},{357,16669},{370},{376,438}},
+       {387, 409, 1938, 438, 370, 447, 457, 465, 468, {12049, 484, 505, 6696, 12062, 12079, 12090}, {574, 582, 590, 12103, 12111, 612, 12119}, {12127, 641, 658, 667, 12142, 12149, 12158, 699, 712, 731, 748, 763, 343}, {12167, 786, 12175, 794, 12183, 12191, 12199, 802, 12207, 818, 826, 12217, 343}, 0, 1, 344, 346, {348,12229,1938},{357,409},{370},{376,438}},
+       {16727, 409, 5015, 2979, 56, 447, 457, 343, 343, {12243, 12250, 12258, 12266, 12275, 12285, 12292}, {2022, 6484, 2028, 12301, 2034, 12304, 2040}, {12307, 12316, 12326, 2064, 8841, 12332, 12338, 12344, 2091, 2101, 2109, 8853, 343}, {2127, 2131, 2909, 2139, 8841, 2143, 2147, 2151, 2155, 2159, 2163, 8866, 343}, 0, 0, 344, 346, {348,5015},{357,409},{370,56},{376,46,2979}},
+       {16752, 16792, 1938, 2991, 1409, 12382, 1146, 12389, 12405, {5226, 5228, 5230, 5232, 5234, 5236, 5238}, {5226, 5228, 5230, 5232, 5234, 5236, 5238}, {5226, 5228, 5230, 5232, 5234, 5236, 5238, 5240, 5242, 5244, 5247, 5250, 343}, {5226, 5228, 5230, 5232, 5234, 5236, 5238, 5240, 5242, 5244, 5247, 5250, 343}, 0, 0, 344, 346, {348,1938},{357,12373,16792},{370,1409},{376,2991}},
+       {16824, 1664, 1676, 16845, 370, 447, 457, 465, 468, {4546, 12450, 12461, 12471, 12481, 12491, 12505}, {4632, 4636, 12517, 12522, 12526, 12531, 12536}, {1779, 1786, 3770, 4681, 3781, 1810, 1815, 1820, 1827, 1837, 1845, 4725, 343}, {1863, 1867, 1871, 1875, 3781, 1879, 1883, 1887, 1891, 1895, 1899, 4755, 343}, 0, 0, 344, 346, {348,1907,1676},{357,1664},{370},{376,16845}},
+       {5984, 876, 1676, 438, 56, 447, 74, 12540, 12568, {12590, 12609, 12628, 12650, 12669, 12691, 12716}, {12735, 12745, 12755, 12768, 12778, 12791, 12807}, {12817, 12833, 12849, 12865, 12884, 12891, 12901, 12917, 12933, 12955, 12977, 12996, 343}, {12817, 12833, 12849, 12865, 12884, 12891, 12901, 12917, 12933, 12955, 12977, 12996, 343}, 0, 0, 344, 346, {348,5805,1676},{357,876},{370,56},{376,2685,438}},
+       {16854, 357, 10606, 16878, 370, 1136, 1146, 465, 468, {13018, 13027, 13036, 13044, 13053, 13062, 13069}, {13078, 13082, 13086, 13090, 13094, 13098, 13102}, {8818, 8826, 13106, 13112, 8841, 2074, 13119, 13125, 13132, 13141, 13148, 13156, 343}, {2127, 2131, 2909, 2139, 8841, 2143, 2147, 13164, 2155, 2159, 2163, 8866, 343}, 0, 6, 344, 346, {348,10606},{357},{370},{376,16878}},
        {16889, 876, 16914, 16922, 16935, 447, 74, 13168, 13210, {13252, 13271, 13290, 13312, 13331, 13353, 13378}, {13397, 13407, 13417, 13430, 13440, 13453, 13469}, {13479, 13507, 13535, 13551, 13570, 13577, 13587, 13603, 13619, 13647, 13669, 13691, 343}, {13716, 13735, 13535, 13551, 13570, 13577, 13587, 13603, 13754, 13770, 13786, 13796, 343}, 0, 0, 344, 346, {348,16914},{357,876},{370,16935},{376,16922}},
-       {16943, 876, 5796, 2676, 56, 447, 74, 13809, 13822, {13835, 13854, 13876, 13901, 13917, 13939, 13958}, {13968, 13975, 13982, 13989, 13996, 14003, 14010}, {14014, 14030, 14055, 14074, 14093, 14100, 14113, 14126, 14145, 14176, 14201, 14223, 343}, {14248, 14256, 14270, 14284, 14093, 14100, 14113, 14295, 14303, 14317, 14328, 14336, 343}, 0, 0, 344, 346, {348,5796},{357,876},{370,56},{376,2676}},
-       {16943, 876, 1898, 2676, 56, 447, 74, 14347, 14375, {14397, 14419, 14441, 14466, 14488, 14513, 14541}, {14563, 14573, 14583, 14596, 14606, 14619, 14635}, {14645, 14661, 14686, 14705, 14727, 14734, 14747, 14760, 14779, 14810, 14835, 14854, 343}, {14645, 14661, 14686, 14705, 14727, 14734, 14747, 14760, 14779, 14810, 14835, 14854, 343}, 0, 0, 344, 346, {348,1898},{357,876},{370,56},{376,2676}},
-       {16889, 876, 5796, 16922, 16935, 447, 74, 14879, 14907, {14929, 14948, 14967, 14989, 15008, 15030, 15055}, {15074, 15079, 15087, 15095, 15103, 15111, 15119}, {15130, 15146, 15171, 15190, 15212, 15219, 15232, 15245, 15264, 15292, 15317, 15339, 343}, {15130, 15146, 15171, 15190, 15212, 15219, 15232, 15245, 15264, 15292, 15317, 15339, 343}, 0, 0, 344, 346, {348,5796},{357,876},{370,16935},{376,16922}},
-       {16943, 876, 5796, 2676, 56, 447, 74, 15364, 15376, {12590, 12609, 15388, 12650, 12669, 12691, 12716}, {12735, 12745, 15410, 12768, 12778, 12791, 12807}, {15423, 15448, 12849, 15473, 15492, 12891, 15499, 15512, 15528, 15556, 15578, 15606, 343}, {15423, 15448, 12849, 15473, 15492, 12891, 15499, 15512, 15528, 15556, 15578, 15606, 343}, 0, 0, 344, 346, {348,5796},{357,876},{370,56},{376,2676}},
-       {4750, 409, 888, 376, 370, 447, 457, 465, 468, {15628, 15636, 15641, 15648, 15658, 15664, 15671}, {15679, 15683, 2900, 15687, 15692, 15696, 15700}, {15705, 15713, 15722, 15728, 15734, 15739, 15745, 15751, 15758, 15767, 15775, 15784, 343}, {15793, 2122, 2900, 15797, 2061, 15801, 15806, 13164, 15810, 15814, 2154, 2908, 343}, 0, 1, 344, 346, {348,888},{357,409},{370},{376}},
-       {16943, 876, 5796, 2676, 56, 447, 74, 15364, 15376, {15818, 12609, 15846, 12650, 12669, 12691, 12716}, {12735, 12745, 15410, 12768, 12778, 12791, 12807}, {15423, 15865, 12849, 15473, 15492, 12891, 15499, 15512, 15528, 15556, 15578, 15606, 343}, {15423, 15448, 12849, 15473, 15492, 12891, 15499, 15512, 15528, 15556, 15578, 15606, 343}, 0, 0, 344, 346, {348,5796},{357,876},{370,56},{376,2676}},
+       {16943, 876, 5805, 2685, 56, 447, 74, 13809, 13822, {13835, 13854, 13876, 13901, 13917, 13939, 13958}, {13968, 13975, 13982, 13989, 13996, 14003, 14010}, {14014, 14030, 14055, 14074, 14093, 14100, 14113, 14126, 14145, 14176, 14201, 14223, 343}, {14248, 14256, 14270, 14284, 14093, 14100, 14113, 14295, 14303, 14317, 14328, 14336, 343}, 0, 0, 344, 346, {348,5805},{357,876},{370,56},{376,2685}},
+       {16943, 876, 1907, 2685, 56, 447, 74, 14347, 14375, {14397, 14419, 14441, 14466, 14488, 14513, 14541}, {14563, 14573, 14583, 14596, 14606, 14619, 14635}, {14645, 14661, 14686, 14705, 14727, 14734, 14747, 14760, 14779, 14810, 14835, 14854, 343}, {14645, 14661, 14686, 14705, 14727, 14734, 14747, 14760, 14779, 14810, 14835, 14854, 343}, 0, 0, 344, 346, {348,1907},{357,876},{370,56},{376,2685}},
+       {16889, 876, 5805, 16922, 16935, 447, 74, 14879, 14907, {14929, 14948, 14967, 14989, 15008, 15030, 15055}, {15074, 15079, 15087, 15095, 15103, 15111, 15119}, {15130, 15146, 15171, 15190, 15212, 15219, 15232, 15245, 15264, 15292, 15317, 15339, 343}, {15130, 15146, 15171, 15190, 15212, 15219, 15232, 15245, 15264, 15292, 15317, 15339, 343}, 0, 0, 344, 346, {348,5805},{357,876},{370,16935},{376,16922}},
+       {16943, 876, 5805, 2685, 56, 447, 74, 15364, 15376, {12590, 12609, 15388, 12650, 12669, 12691, 12716}, {12735, 12745, 15410, 12768, 12778, 12791, 12807}, {15423, 15448, 12849, 15473, 15492, 12891, 15499, 15512, 15528, 15556, 15578, 15606, 343}, {15423, 15448, 12849, 15473, 15492, 12891, 15499, 15512, 15528, 15556, 15578, 15606, 343}, 0, 0, 344, 346, {348,5805},{357,876},{370,56},{376,2685}},
+       {4759, 409, 888, 376, 370, 447, 457, 465, 468, {15628, 15636, 15641, 15648, 15658, 15664, 15671}, {15679, 15683, 2909, 15687, 15692, 15696, 15700}, {15705, 15713, 15722, 15728, 15734, 15739, 15745, 15751, 15758, 15767, 15775, 15784, 343}, {15793, 2131, 2909, 15797, 2070, 15801, 15806, 13164, 15810, 15814, 2163, 2917, 343}, 0, 1, 344, 346, {348,888},{357,409},{370},{376}},
+       {16943, 876, 5805, 2685, 56, 447, 74, 15364, 15376, {15818, 12609, 15846, 12650, 12669, 12691, 12716}, {12735, 12745, 15410, 12768, 12778, 12791, 12807}, {15423, 15865, 12849, 15473, 15492, 12891, 15499, 15512, 15528, 15556, 15578, 15606, 343}, {15423, 15448, 12849, 15473, 15492, 12891, 15499, 15512, 15528, 15556, 15578, 15606, 343}, 0, 0, 344, 346, {348,5805},{357,876},{370,56},{376,2685}},
        {1, 24, 37, 46, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {184, 187, 190, 193, 196, 199, 202}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37},{357,24},{370,56},{376,46}},
-       {16967, 4984, 17012, 17019, 17042, 5017, 5033, 1154, 1161, {1168, 1178, 1188, 1198, 1208, 1218, 1228}, {1238, 1242, 1246, 1250, 1254, 1258, 1262}, {1266, 1273, 1280, 1287, 1294, 1301, 1308, 1315, 1322, 1329, 1336, 1346, 343}, {1266, 1273, 1280, 1287, 1294, 1301, 1308, 1315, 1322, 1329, 1336, 1346, 343}, 0, 0, 344, 346, {348,17012},{357,4984},{370,17042},{376,17019}},
-       {1907, 1379, 1929, 438, 370, 447, 1414, 1940, 1946, {1953, 1961, 1968, 1977, 1986, 1997, 2005}, {2013, 2016, 2019, 2022, 2025, 2028, 2031}, {2034, 2041, 2049, 2055, 2061, 2065, 2070, 2075, 2082, 2092, 2100, 2109, 343}, {2118, 2122, 2126, 2130, 2061, 2134, 2138, 2142, 2146, 2150, 2154, 2158, 343}, 0, 1, 344, 346, {348,844,1929},{357,1379},{370},{376,438}},
-       {5975, 876, 2665, 438, 370, 447, 74, 465, 468, {2761, 2768, 2775, 2783, 2793, 2802, 2809}, {2818, 2822, 2826, 2830, 2834, 2838, 2842}, {2846, 2854, 2863, 2055, 2869, 2873, 2878, 2075, 2082, 2883, 2100, 2891, 343}, {2118, 2122, 2900, 2130, 2869, 2134, 2138, 2142, 2146, 2904, 2154, 2908, 343}, 0, 1, 344, 346, {348,2739,2665},{2719,2719,2912,2926,2946,876},{2746,2746,2961,1409,370},{2186,2186,2970,2982,438,376}},
-       {2990, 3024, 2665, 2970, 16935, 3057, 3062, 3074, 3079, {3084, 3092, 3098, 3105, 3116, 3123, 3131}, {3139, 3143, 1862, 3147, 3152, 3156, 3160}, {3165, 3171, 3179, 1004, 3185, 3190, 3196, 3202, 3209, 1042, 3220, 3230, 343}, {3240, 1858, 1862, 3244, 3248, 1870, 1874, 3252, 1882, 3256, 1890, 3260, 343}, 0, 1, 344, 346, {348,3264,3046,888,2665},{357,3024},{370,16935},{376,2970,16922}},
-       {8861, 876, 3859, 2982, 370, 447, 74, 465, 468, {3657, 3666, 3672, 3678, 3687, 3693, 3702}, {3709, 3714, 3719, 3724, 3729, 3734, 3739}, {3744, 3752, 3761, 3766, 3772, 3776, 3781, 3789, 3795, 3805, 1050, 3813, 343}, {3823, 3829, 3761, 3836, 3772, 3776, 3841, 3789, 3847, 1097, 1102, 3853, 343}, 0, 1, 344, 346, {888,3859,3264},{357,876,3640},{370},{376,438,2982}},
-       {5975, 876, 1929, 438, 370, 447, 74, 4774, 4777, {4780, 4789, 4797, 4806, 4817, 4826, 4835}, {3139, 3143, 1862, 4842, 4846, 4850, 4854}, {4858, 4866, 3179, 4875, 4882, 4889, 4896, 3202, 4903, 4913, 1050, 4921, 343}, {4930, 1858, 1862, 1866, 4934, 4938, 4942, 3252, 4946, 4950, 1890, 3260, 343}, 0, 1, 344, 346, {348,888,844,1929},{357,409,876},{370},{376,438}},
-       {8861, 876, 3859, 2982, 370, 447, 74, 465, 468, {5803, 5810, 5818, 5826, 5835, 5845, 5853}, {5862, 3418, 5865, 5868, 5871, 5874, 5877}, {5880, 5888, 5897, 1791, 5903, 1801, 1806, 5907, 1818, 1828, 1836, 1845, 343}, {1854, 1858, 5916, 1866, 5903, 1870, 1874, 1878, 1882, 1886, 1890, 1894, 343}, 0, 1, 344, 346, {348,5796,3264,3859},{357,876},{370,1409},{376,1399,2982}},
-       {5920, 1379, 844, 5944, 5955, 447, 1414, 465, 468, {1687, 1695, 1702, 1710, 1717, 1725, 1732}, {5961, 3418, 3421, 5965, 3427, 5968, 5971}, {1770, 1777, 3761, 1791, 3772, 1801, 1806, 1811, 1818, 1828, 1836, 4716, 343}, {1854, 1858, 1862, 1866, 3772, 1870, 1874, 1878, 1882, 1886, 1890, 4746, 343}, 0, 1, 344, 346, {348,844},{357,1379},{370,5955},{376,5944}},
-       {17048, 3024, 1676, 2982, 370, 3057, 3062, 465, 468, {3084, 6244, 6258, 6271, 6284, 6297, 3131}, {3139, 6309, 6313, 6317, 6321, 6325, 3160}, {6329, 6337, 6347, 1004, 6354, 6359, 6365, 3202, 6371, 6380, 6388, 6397, 343}, {1854, 6406, 1862, 3244, 3772, 1870, 1874, 3252, 4946, 6410, 1890, 6414, 343}, 0, 1, 344, 346, {348,1676},{357,3024},{370},{376,2982}},
-       {16460, 7668, 3314, 438, 5955, 447, 74, 7685, 7688, {7691, 7699, 7707, 1710, 1717, 1725, 7714}, {7722, 7726, 3421, 5965, 3427, 5968, 7730}, {5880, 5888, 3761, 1791, 1797, 1801, 1806, 7734, 1818, 1828, 1836, 1845, 343}, {1854, 1858, 1862, 1866, 1797, 1870, 1874, 1878, 1882, 1886, 1890, 1894, 343}, 0, 1, 344, 346, {348,5996,3314},{357,7668},{370,5955},{376,5944,438}},
-       {17078, 24, 2665, 2970, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {184, 187, 190, 193, 196, 199, 202}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,2665},{357,24},{370,56},{376,46,2970}},
-       {17103, 5315, 17150, 15941, 17042, 17170, 17187, 1154, 1161, {1168, 1178, 1188, 1198, 1208, 1218, 1228}, {1238, 1242, 1246, 1250, 1254, 1258, 1262}, {1266, 1273, 1280, 1287, 1294, 1301, 1308, 1315, 1322, 1329, 1336, 1346, 343}, {5154, 5159, 5164, 5169, 5174, 5179, 5184, 5189, 5194, 5199, 5205, 5211, 343}, 0, 0, 344, 346, {348,17150},{357,5315},{370,17042},{376,15941}},
-       {17202, 9685, 1929, 438, 370, 447, 9699, 1940, 1946, {1953, 1961, 1968, 1977, 1986, 1997, 2005}, {2013, 2016, 2019, 2022, 2025, 2028, 2031}, {17225, 2041, 2049, 2055, 2061, 2065, 2070, 2075, 2082, 2092, 2100, 2109, 343}, {17233, 2122, 17238, 2130, 2061, 2134, 2138, 2142, 2146, 2150, 2154, 2158, 343}, 0, 1, 344, 346, {348,844,1929},{357,1379,9685},{370},{376,438}},
-       {17243, 876, 3859, 2186, 56, 447, 74, 465, 468, {2761, 2768, 2775, 2783, 2793, 2802, 2809}, {2818, 2822, 2826, 2830, 2834, 2838, 2842}, {2846, 2854, 2863, 2055, 2869, 2873, 2878, 2075, 2082, 2883, 2100, 2891, 343}, {2118, 2122, 2900, 2130, 2869, 2134, 2138, 2142, 2146, 2904, 2154, 2908, 343}, 0, 0, 344, 346, {348,2739,3264,3859},{2719,2719,2912,2926,2946,876},{2746,2746,2961,1409,370,56},{2186,2186,2970,2982,438,46}},
-       {17266, 17303, 2665, 2982, 1409, 17332, 457, 3074, 3079, {3084, 3092, 3098, 3105, 3116, 3123, 3131}, {3139, 3143, 1862, 3147, 3152, 3156, 3160}, {3165, 3171, 3179, 1004, 3185, 3190, 3196, 3202, 3209, 1042, 3220, 3230, 343}, {3240, 1858, 1862, 3244, 3248, 1870, 1874, 3252, 1882, 3256, 1890, 3260, 343}, 0, 1, 344, 346, {348,3264,3046,888,2665},{357,3024,17303},{370,1409},{376,2970,2982}},
-       {5975, 876, 5996, 438, 370, 447, 74, 465, 468, {3657, 3666, 3672, 3678, 3687, 3693, 3702}, {3709, 3714, 3719, 3724, 3729, 3734, 3739}, {3744, 3752, 3761, 3766, 3772, 3776, 3781, 3789, 3795, 3805, 1050, 3813, 343}, {3823, 3829, 3761, 3836, 3772, 3776, 3841, 3789, 3847, 1097, 1102, 3853, 343}, 0, 0, 344, 346, {888,3859,3264,5515,5996},{357,876,3640},{370},{376,438}},
-       {17078, 24, 2665, 2970, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {184, 187, 190, 193, 196, 199, 202}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,2665},{357,24},{370,56},{376,46,2970}},
+       {16967, 4993, 17012, 17019, 17042, 5026, 5042, 1154, 1161, {1168, 1178, 1188, 1198, 1208, 1218, 1228}, {1238, 1242, 1246, 1250, 1254, 1258, 1262}, {1266, 1273, 1280, 1287, 1294, 1301, 1308, 1315, 1322, 1329, 1336, 1346, 343}, {1266, 1273, 1280, 1287, 1294, 1301, 1308, 1315, 1322, 1329, 1336, 1346, 343}, 0, 0, 344, 346, {348,17012},{357,4993},{370,17042},{376,17019}},
+       {1916, 1379, 1938, 438, 370, 447, 1414, 1949, 1955, {1962, 1970, 1977, 1986, 1995, 2006, 2014}, {2022, 2025, 2028, 2031, 2034, 2037, 2040}, {2043, 2050, 2058, 2064, 2070, 2074, 2079, 2084, 2091, 2101, 2109, 2118, 343}, {2127, 2131, 2135, 2139, 2070, 2143, 2147, 2151, 2155, 2159, 2163, 2167, 343}, 0, 1, 344, 346, {348,844,1938},{357,1379},{370},{376,438}},
+       {5984, 876, 2674, 438, 370, 447, 74, 465, 468, {2770, 2777, 2784, 2792, 2802, 2811, 2818}, {2827, 2831, 2835, 2839, 2843, 2847, 2851}, {2855, 2863, 2872, 2064, 2878, 2882, 2887, 2084, 2091, 2892, 2109, 2900, 343}, {2127, 2131, 2909, 2139, 2878, 2143, 2147, 2151, 2155, 2913, 2163, 2917, 343}, 0, 1, 344, 346, {348,2748,2674},{2728,2728,2921,2935,2955,876},{2755,2755,2970,1409,370},{2195,2195,2979,2991,438,376}},
+       {2999, 3033, 2674, 2979, 16935, 3066, 3071, 3083, 3088, {3093, 3101, 3107, 3114, 3125, 3132, 3140}, {3148, 3152, 1871, 3156, 3161, 3165, 3169}, {3174, 3180, 3188, 1004, 3194, 3199, 3205, 3211, 3218, 1042, 3229, 3239, 343}, {3249, 1867, 1871, 3253, 3257, 1879, 1883, 3261, 1891, 3265, 1899, 3269, 343}, 0, 1, 344, 346, {348,3273,3055,888,2674},{357,3033},{370,16935},{376,2979,16922}},
+       {8870, 876, 3868, 2991, 370, 447, 74, 465, 468, {3666, 3675, 3681, 3687, 3696, 3702, 3711}, {3718, 3723, 3728, 3733, 3738, 3743, 3748}, {3753, 3761, 3770, 3775, 3781, 3785, 3790, 3798, 3804, 3814, 1050, 3822, 343}, {3832, 3838, 3770, 3845, 3781, 3785, 3850, 3798, 3856, 1097, 1102, 3862, 343}, 0, 1, 344, 346, {888,3868,3273},{357,876,3649},{370},{376,438,2991}},
+       {5984, 876, 1938, 438, 370, 447, 74, 4783, 4786, {4789, 4798, 4806, 4815, 4826, 4835, 4844}, {3148, 3152, 1871, 4851, 4855, 4859, 4863}, {4867, 4875, 3188, 4884, 4891, 4898, 4905, 3211, 4912, 4922, 1050, 4930, 343}, {4939, 1867, 1871, 1875, 4943, 4947, 4951, 3261, 4955, 4959, 1899, 3269, 343}, 0, 1, 344, 346, {348,888,844,1938},{357,409,876},{370},{376,438}},
+       {8870, 876, 3868, 2991, 370, 447, 74, 465, 468, {5812, 5819, 5827, 5835, 5844, 5854, 5862}, {5871, 3427, 5874, 5877, 5880, 5883, 5886}, {5889, 5897, 5906, 1800, 5912, 1810, 1815, 5916, 1827, 1837, 1845, 1854, 343}, {1863, 1867, 5925, 1875, 5912, 1879, 1883, 1887, 1891, 1895, 1899, 1903, 343}, 0, 1, 344, 346, {348,5805,3273,3868},{357,876},{370,1409},{376,1399,2991}},
+       {5929, 1379, 844, 5953, 5964, 447, 1414, 465, 468, {1696, 1704, 1711, 1719, 1726, 1734, 1741}, {5970, 3427, 3430, 5974, 3436, 5977, 5980}, {1779, 1786, 3770, 1800, 3781, 1810, 1815, 1820, 1827, 1837, 1845, 4725, 343}, {1863, 1867, 1871, 1875, 3781, 1879, 1883, 1887, 1891, 1895, 1899, 4755, 343}, 0, 1, 344, 346, {348,844},{357,1379},{370,5964},{376,5953}},
+       {17048, 3033, 1676, 2991, 370, 3066, 3071, 465, 468, {3093, 6253, 6267, 6280, 6293, 6306, 3140}, {3148, 6318, 6322, 6326, 6330, 6334, 3169}, {6338, 6346, 6356, 1004, 6363, 6368, 6374, 3211, 6380, 6389, 6397, 6406, 343}, {1863, 6415, 1871, 3253, 3781, 1879, 1883, 3261, 4955, 6419, 1899, 6423, 343}, 0, 1, 344, 346, {348,1676},{357,3033},{370},{376,2991}},
+       {16460, 7677, 3323, 438, 5964, 447, 74, 7694, 7697, {7700, 7708, 7716, 1719, 1726, 1734, 7723}, {7731, 7735, 3430, 5974, 3436, 5977, 7739}, {5889, 5897, 3770, 1800, 1806, 1810, 1815, 7743, 1827, 1837, 1845, 1854, 343}, {1863, 1867, 1871, 1875, 1806, 1879, 1883, 1887, 1891, 1895, 1899, 1903, 343}, 0, 1, 344, 346, {348,6005,3323},{357,7677},{370,5964},{376,5953,438}},
+       {17078, 24, 2674, 2979, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {184, 187, 190, 193, 196, 199, 202}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,2674},{357,24},{370,56},{376,46,2979}},
+       {17103, 5324, 17150, 15941, 17042, 17170, 17187, 1154, 1161, {1168, 1178, 1188, 1198, 1208, 1218, 1228}, {1238, 1242, 1246, 1250, 1254, 1258, 1262}, {1266, 1273, 1280, 1287, 1294, 1301, 1308, 1315, 1322, 1329, 1336, 1346, 343}, {5163, 5168, 5173, 5178, 5183, 5188, 5193, 5198, 5203, 5208, 5214, 5220, 343}, 0, 0, 344, 346, {348,17150},{357,5324},{370,17042},{376,15941}},
+       {17202, 9694, 1938, 438, 370, 447, 1687, 1949, 1955, {1962, 1970, 1977, 1986, 1995, 2006, 2014}, {2022, 2025, 2028, 2031, 2034, 2037, 2040}, {17225, 2050, 2058, 2064, 2070, 2074, 2079, 2084, 2091, 2101, 2109, 2118, 343}, {17233, 2131, 17238, 2139, 2070, 2143, 2147, 2151, 2155, 2159, 2163, 2167, 343}, 0, 1, 344, 346, {348,844,1938},{357,1379,9694},{370},{376,438}},
+       {17243, 876, 3868, 2195, 56, 447, 74, 465, 468, {2770, 2777, 2784, 2792, 2802, 2811, 2818}, {2827, 2831, 2835, 2839, 2843, 2847, 2851}, {2855, 2863, 2872, 2064, 2878, 2882, 2887, 2084, 2091, 2892, 2109, 2900, 343}, {2127, 2131, 2909, 2139, 2878, 2143, 2147, 2151, 2155, 2913, 2163, 2917, 343}, 0, 0, 344, 346, {348,2748,3273,3868},{2728,2728,2921,2935,2955,876},{2755,2755,2970,1409,370,56},{2195,2195,2979,2991,438,46}},
+       {17266, 17303, 2674, 2991, 1409, 17332, 457, 3083, 3088, {3093, 3101, 3107, 3114, 3125, 3132, 3140}, {3148, 3152, 1871, 3156, 3161, 3165, 3169}, {3174, 3180, 3188, 1004, 3194, 3199, 3205, 3211, 3218, 1042, 3229, 3239, 343}, {3249, 1867, 1871, 3253, 3257, 1879, 1883, 3261, 1891, 3265, 1899, 3269, 343}, 0, 1, 344, 346, {348,3273,3055,888,2674},{357,3033,17303},{370,1409},{376,2979,2991}},
+       {5984, 876, 6005, 438, 370, 447, 74, 465, 468, {3666, 3675, 3681, 3687, 3696, 3702, 3711}, {3718, 3723, 3728, 3733, 3738, 3743, 3748}, {3753, 3761, 3770, 3775, 3781, 3785, 3790, 3798, 3804, 3814, 1050, 3822, 343}, {3832, 3838, 3770, 3845, 3781, 3785, 3850, 3798, 3856, 1097, 1102, 3862, 343}, 0, 0, 344, 346, {888,3868,3273,5524,6005},{357,876,3649},{370},{376,438}},
+       {17078, 24, 2674, 2979, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {184, 187, 190, 193, 196, 199, 202}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,2674},{357,24},{370,56},{376,46,2979}},
        {17347, 17370, 888, 17382, 17393, 447, 457, 1154, 1161, {1168, 1178, 1188, 1198, 1208, 1218, 1228}, {1238, 1242, 1246, 1250, 1254, 1258, 1262}, {1266, 1273, 1280, 1287, 1294, 1301, 1308, 1315, 1322, 1329, 1336, 1346, 343}, {1266, 1273, 1280, 1287, 1294, 1301, 1308, 1315, 1322, 1329, 1336, 1346, 343}, 0, 0, 344, 346, {348,888},{357,17370},{370,17393},{376,17382}},
-       {1907, 1379, 1929, 438, 370, 447, 1414, 1940, 1946, {1953, 1961, 1968, 1977, 1986, 1997, 2005}, {2013, 2016, 2019, 2022, 2025, 2028, 2031}, {2034, 2041, 2049, 2055, 2061, 2065, 2070, 2075, 2082, 2092, 2100, 2109, 343}, {2118, 2122, 2126, 2130, 2061, 2134, 2138, 2142, 2146, 2150, 2154, 2158, 343}, 0, 1, 344, 346, {348,844,1929},{357,1379},{370},{376,438}},
-       {17401, 17425, 2665, 2186, 56, 447, 2754, 465, 468, {2761, 2768, 2775, 2783, 2793, 2802, 2809}, {2818, 2822, 2826, 2830, 2834, 2838, 2842}, {2846, 2854, 2863, 2055, 2869, 2873, 2878, 2075, 2082, 2883, 2100, 2891, 343}, {2118, 2122, 2900, 2130, 2869, 2134, 2138, 2142, 2146, 2904, 2154, 2908, 343}, 0, 0, 344, 346, {348,2739,888,2665},{2719,2719,2912,2926,2946,17425},{2746,2746,2961,1409,370,56},{2186,2186,2970,2982,438,2676}},
-       {2990, 3024, 2665, 2970, 16935, 3057, 3062, 3074, 3079, {3084, 3092, 3098, 3105, 3116, 3123, 3131}, {3139, 3143, 1862, 3147, 3152, 3156, 3160}, {3165, 3171, 3179, 1004, 3185, 3190, 3196, 3202, 3209, 1042, 3220, 3230, 343}, {3240, 1858, 1862, 3244, 3248, 1870, 1874, 3252, 1882, 3256, 1890, 3260, 343}, 0, 1, 344, 346, {348,3264,3046,2665},{357,3024},{370,16935},{376,2970,16922}},
-       {5975, 876, 1929, 438, 370, 447, 74, 465, 468, {3657, 3666, 3672, 3678, 3687, 3693, 3702}, {3709, 3714, 3719, 3724, 3729, 3734, 3739}, {3744, 3752, 3761, 3766, 3772, 3776, 3781, 3789, 3795, 3805, 1050, 3813, 343}, {3823, 3829, 3761, 3836, 3772, 3776, 3841, 3789, 3847, 1097, 1102, 3853, 343}, 0, 1, 344, 346, {888,3859,3264,844,1929},{357,876,3640},{370},{376,438}},
-       {17438, 24, 1676, 2982, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {184, 187, 190, 193, 196, 199, 202}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,1676},{357,24},{370,56},{376,46,2982}},
-       {17103, 5315, 17150, 15941, 17042, 17170, 17187, 1154, 1161, {1168, 1178, 1188, 1198, 1208, 1218, 1228}, {1238, 1242, 1246, 1250, 1254, 1258, 1262}, {1266, 1273, 1280, 1287, 1294, 1301, 1308, 1315, 1322, 1329, 1336, 1346, 343}, {5154, 5159, 5164, 5169, 5174, 5179, 5184, 5189, 5194, 5199, 5205, 5211, 343}, 0, 0, 344, 346, {348,17150},{357,5315},{370,17042},{376,15941}},
-       {17243, 876, 3859, 2186, 56, 447, 74, 3074, 3079, {2761, 2768, 2775, 2783, 2793, 2802, 2809}, {2818, 2822, 2826, 2830, 2834, 2838, 2842}, {2846, 2854, 2863, 2055, 2869, 2873, 2878, 2075, 2082, 2883, 2100, 2891, 343}, {2118, 2122, 2900, 2130, 2869, 2134, 2138, 2142, 2146, 2904, 2154, 2908, 343}, 0, 0, 344, 346, {348,2739,3264,3859},{2719,2719,2912,2926,2946,876},{2746,2746,2961,1409,370,56},{2186,2186,2970,2982,438,46}},
-       {2990, 3024, 2665, 2970, 16935, 3057, 3062, 3074, 3079, {3084, 3092, 3098, 3105, 3116, 3123, 3131}, {3139, 3143, 1862, 3147, 3152, 3156, 3160}, {3165, 3171, 3179, 1004, 3185, 3190, 3196, 3202, 3209, 1042, 3220, 3230, 343}, {3240, 1858, 1862, 3244, 3248, 1870, 1874, 3252, 1882, 3256, 1890, 3260, 343}, 0, 1, 344, 346, {348,3264,3046,888,2665},{357,3024},{370,16935},{376,2970,16922}},
-       {3614, 3640, 2665, 438, 370, 447, 74, 465, 468, {3657, 3666, 3672, 3678, 3687, 3693, 3702}, {3709, 3714, 3719, 3724, 3729, 3734, 3739}, {3744, 3752, 3761, 3766, 3772, 3776, 3781, 3789, 3795, 3805, 1050, 3813, 343}, {3823, 3829, 3761, 3836, 3772, 3776, 3841, 3789, 3847, 1097, 1102, 3853, 343}, 0, 1, 344, 346, {888,3859,3264,2665},{357,876,3640},{370},{376,438}},
-       {17438, 24, 1676, 2982, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {184, 187, 190, 193, 196, 199, 202}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,1676},{357,24},{370,56},{376,46,2982}},
-       {5975, 876, 2665, 438, 370, 447, 74, 3074, 3079, {2761, 2768, 2775, 2783, 2793, 2802, 2809}, {2818, 2822, 2826, 2830, 2834, 2838, 2842}, {2846, 2854, 2863, 2055, 2869, 2873, 2878, 2075, 2082, 2883, 2100, 2891, 343}, {2118, 2122, 2900, 2130, 2869, 2134, 2138, 2142, 2146, 2904, 2154, 2908, 343}, 0, 0, 344, 346, {348,2739,2665},{2719,2719,2912,2926,2946,876},{2746,2746,2961,1409,370},{2186,2186,2970,2982,438,376}},
-       {2990, 3024, 3046, 2970, 16935, 3057, 3062, 3074, 3079, {3084, 3092, 3098, 3105, 3116, 3123, 3131}, {3139, 3143, 1862, 3147, 3152, 3156, 3160}, {3165, 3171, 3179, 1004, 3185, 3190, 3196, 3202, 3209, 1042, 3220, 3230, 343}, {3240, 1858, 1862, 3244, 3248, 1870, 1874, 3252, 1882, 3256, 1890, 3260, 343}, 0, 1, 344, 346, {348,3264,3046,11818},{357,3024},{370,16935},{376,2970,16922}},
-       {17438, 24, 1676, 2982, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {87, 98, 113, 130, 147, 160, 173}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,1676},{357,24},{370,56},{376,46,2982}},
-       {16727, 409, 5006, 2970, 56, 447, 457, 465, 468, {2761, 2768, 2775, 2783, 2793, 2802, 2809}, {2818, 2822, 2826, 2830, 2834, 2838, 2842}, {2846, 2854, 2863, 2055, 2869, 2873, 2878, 2075, 2082, 2883, 2100, 2891, 343}, {2118, 2122, 2900, 2130, 2869, 2134, 2138, 2142, 2146, 2904, 2154, 2908, 343}, 0, 0, 344, 346, {348,2739,5006},{2719,2719,2912,2926,2946,409},{2746,2746,2961,1409,370,56},{2186,2186,2970,2982,438,46}},
-       {2990, 3024, 2665, 2970, 16935, 3057, 3062, 3074, 3079, {3084, 3092, 3098, 3105, 3116, 3123, 3131}, {3139, 3143, 1862, 3147, 3152, 3156, 3160}, {3165, 3171, 3179, 1004, 3185, 3190, 3196, 3202, 3209, 1042, 3220, 3230, 343}, {3240, 1858, 1862, 3244, 3248, 1870, 1874, 3252, 1882, 3256, 1890, 3260, 343}, 0, 1, 344, 346, {348,3264,3046,888,2665},{357,3024},{370,16935},{376,2970,16922}},
-       {17078, 24, 2665, 2970, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {184, 187, 190, 193, 196, 199, 202}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,2665},{357,24},{370,56},{376,46,2970}},
-       {2990, 3024, 2665, 2970, 16935, 3057, 3062, 3074, 3079, {3084, 3092, 3098, 3105, 3116, 3123, 3131}, {3139, 3143, 1862, 3147, 3152, 3156, 3160}, {3165, 3171, 3179, 1004, 3185, 3190, 3196, 3202, 3209, 1042, 3220, 3230, 343}, {3240, 1858, 1862, 3244, 3248, 1870, 1874, 3252, 1882, 3256, 1890, 3260, 343}, 0, 1, 344, 346, {348,3264,3046,888,2665},{357,3024},{370,16935},{376,2970,16922}},
-       {17078, 24, 2665, 2970, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {87, 98, 113, 130, 147, 160, 173}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,2665},{357,24},{370,56},{376,46,2970}},
-       {2990, 3024, 2665, 2970, 1409, 3057, 3062, 3074, 3079, {3084, 3092, 3098, 3105, 3116, 3123, 3131}, {3139, 3143, 1862, 3147, 3152, 3156, 3160}, {3165, 3171, 3179, 1004, 3185, 3190, 3196, 3202, 3209, 1042, 3220, 3230, 343}, {3240, 1858, 1862, 3244, 3248, 1870, 1874, 3252, 1882, 3256, 1890, 3260, 343}, 0, 1, 344, 346, {348,3264,3046,2665},{357,3024},{370,1409},{376,2970,1399}},
-       {17078, 24, 2665, 2970, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {87, 98, 113, 130, 147, 160, 173}, {17459, 17483, 17492, 17501, 17512, 17521, 17534, 17543, 17548, 17559, 17581, 17605, 343}, {17459, 17483, 17492, 17501, 17512, 17521, 17534, 17543, 17548, 17559, 17581, 17605, 343}, 0, 4, 344, 346, {348,37,2665},{357,24},{370,56},{376,46,2970}},
-       {2990, 3024, 2665, 2970, 16935, 3057, 3062, 3074, 3079, {3084, 3092, 3098, 3105, 3116, 3123, 3131}, {3139, 3143, 1862, 3147, 3152, 3156, 3160}, {3165, 3171, 3179, 1004, 3185, 3190, 3196, 3202, 3209, 1042, 3220, 3230, 343}, {3240, 1858, 1862, 3244, 3248, 1870, 1874, 3252, 1882, 3256, 1890, 3260, 343}, 0, 1, 344, 346, {348,3264,3046,888,2665},{357,3024},{370,16935},{376,2970,16922}},
-       {17078, 24, 2665, 2970, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {87, 98, 113, 130, 147, 160, 173}, {17459, 17483, 17492, 17501, 17627, 17521, 17534, 17543, 17548, 17559, 17581, 17605, 343}, {17459, 17483, 17492, 17501, 17627, 17521, 17534, 17543, 17548, 17559, 17581, 17605, 343}, 0, 6, 344, 346, {348,37,2665},{357,24},{370,56},{376,46,2970}},
-       {2990, 3024, 2665, 2970, 370, 3057, 3062, 3074, 3079, {3084, 3092, 3098, 3105, 3116, 3123, 3131}, {3139, 3143, 1862, 3147, 3152, 3156, 3160}, {3165, 3171, 3179, 1004, 3185, 3190, 3196, 3202, 3209, 1042, 3220, 3230, 343}, {3240, 1858, 1862, 3244, 3248, 1870, 1874, 3252, 1882, 3256, 1890, 3260, 343}, 0, 1, 344, 346, {348,3264,3046,888,2665},{357,3024},{370},{376,2970,1399}},
-       {17078, 24, 2665, 2970, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {87, 98, 113, 130, 147, 160, 173}, {17459, 17483, 17492, 17501, 17512, 17521, 17534, 17543, 17548, 17559, 17581, 17605, 343}, {17459, 17483, 17492, 17501, 17512, 17521, 17534, 17543, 17548, 17559, 17581, 17605, 343}, 0, 6, 344, 346, {348,37,2665},{357,24},{370,56},{376,46,2970}},
-       {2162, 409, 10606, 2186, 56, 447, 457, 465, 468, {2761, 2768, 2775, 2783, 2793, 2802, 2809}, {2818, 2822, 2826, 2830, 2834, 2838, 2842}, {2846, 2854, 2863, 2055, 2869, 2873, 2878, 2075, 2082, 2883, 2100, 2891, 343}, {2118, 2122, 2900, 2130, 2869, 2134, 2138, 2142, 2146, 2904, 2154, 2908, 343}, 0, 0, 344, 346, {348,2739,37,10606},{2719,2719,2912,2926,2946,409},{2746,2746,2961,1409,370,56},{2186,2186,2970,2982,438,46}},
-       {17048, 3024, 2665, 2982, 1409, 3057, 3062, 3074, 3079, {3084, 3092, 3098, 3105, 3116, 3123, 3131}, {3139, 3143, 1862, 3147, 3152, 3156, 3160}, {3165, 3171, 3179, 1004, 3185, 3190, 3196, 3202, 3209, 1042, 3220, 3230, 343}, {3240, 1858, 1862, 3244, 3248, 1870, 1874, 3252, 1882, 3256, 1890, 3260, 343}, 0, 1, 344, 346, {348,3264,3046,888,2665},{357,3024},{370,1409},{376,2970,1399,2982}},
-       {17078, 24, 2665, 2970, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {184, 187, 190, 193, 196, 199, 202}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,2665},{357,24},{370,56},{376,46,2970}},
-       {17401, 17425, 10606, 2186, 56, 447, 2754, 465, 468, {2761, 2768, 2775, 2783, 2793, 2802, 2809}, {2818, 2822, 2826, 2830, 2834, 2838, 2842}, {2846, 2854, 2863, 2055, 2869, 2873, 2878, 2075, 2082, 2883, 2100, 2891, 343}, {2118, 2122, 2900, 2130, 2869, 2134, 2138, 2142, 2146, 2904, 2154, 2908, 343}, 0, 0, 344, 346, {348,2739,10606},{2719,2719,2912,2926,2946,17425},{2746,2746,2961,1409,370,56},{2186,2186,2970,2982,438,2676}},
-       {17048, 3024, 1676, 2982, 1409, 3057, 3062, 3074, 3079, {3084, 3092, 3098, 3105, 3116, 3123, 3131}, {3139, 3143, 1862, 3147, 3152, 3156, 3160}, {3165, 3171, 3179, 1004, 3185, 3190, 3196, 3202, 3209, 1042, 3220, 3230, 343}, {3240, 1858, 1862, 3244, 3248, 1870, 1874, 3252, 1882, 3256, 1890, 3260, 343}, 0, 1, 344, 346, {348,3264,3046,1898,1676},{357,3024},{370,1409},{376,2970,1399,2982}},
-       {17078, 24, 2665, 2970, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {184, 187, 190, 193, 196, 199, 202}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,2665},{357,24},{370,56},{376,46,2970}},
-       {2990, 3024, 2665, 2970, 16935, 3057, 3062, 3074, 3079, {3084, 3092, 3098, 3105, 3116, 3123, 3131}, {3139, 3143, 1862, 3147, 3152, 3156, 3160}, {3165, 3171, 3179, 1004, 3185, 3190, 3196, 3202, 3209, 1042, 3220, 3230, 343}, {3240, 1858, 1862, 3244, 3248, 1870, 1874, 3252, 1882, 3256, 1890, 3260, 343}, 0, 1, 344, 346, {348,3264,3046,888,2665},{357,3024},{370,16935},{376,2970,16922}},
-       {17078, 24, 2665, 2970, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {184, 187, 190, 193, 196, 199, 202}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,2665},{357,24},{370,56},{376,46,2970}},
-       {2990, 3024, 2665, 2970, 16935, 3057, 3062, 3074, 3079, {3084, 3092, 3098, 3105, 3116, 3123, 3131}, {3139, 3143, 1862, 3147, 3152, 3156, 3160}, {3165, 3171, 3179, 1004, 3185, 3190, 3196, 3202, 3209, 1042, 3220, 3230, 343}, {3240, 1858, 1862, 3244, 3248, 1870, 1874, 3252, 1882, 3256, 1890, 3260, 343}, 0, 1, 344, 346, {348,3264,3046,888,2665},{357,3024},{370,16935},{376,2970,16922}},
-       {17078, 24, 2665, 2970, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {87, 98, 113, 130, 147, 160, 173}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,2665},{357,24},{370,56},{376,46,2970}},
-       {2990, 3024, 2665, 2970, 16935, 3057, 3062, 3074, 3079, {3084, 3092, 3098, 3105, 3116, 3123, 3131}, {3139, 3143, 1862, 3147, 3152, 3156, 3160}, {3165, 3171, 3179, 1004, 3185, 3190, 3196, 3202, 3209, 1042, 3220, 3230, 343}, {3240, 1858, 1862, 3244, 3248, 1870, 1874, 3252, 1882, 3256, 1890, 3260, 343}, 0, 1, 344, 346, {348,3264,3046,888,2665},{357,3024},{370,16935},{376,2970,16922}},
-       {2990, 3024, 2665, 2970, 16935, 3057, 3062, 3074, 3079, {3084, 3092, 3098, 3105, 3116, 3123, 3131}, {3139, 3143, 1862, 3147, 3152, 3156, 3160}, {3165, 3171, 3179, 1004, 3185, 3190, 3196, 3202, 3209, 1042, 3220, 3230, 343}, {3240, 1858, 1862, 3244, 3248, 1870, 1874, 3252, 1882, 3256, 1890, 3260, 343}, 0, 1, 344, 346, {348,3264,3046,888,2665},{357,3024},{370,16935},{376,2970,16922}},
-       {17636, 17671, 2665, 2970, 16935, 3057, 17694, 3074, 3079, {3084, 3092, 3098, 3105, 3116, 3123, 3131}, {3139, 3143, 1862, 3147, 3152, 3156, 3160}, {3165, 3171, 3179, 1004, 3185, 3190, 3196, 3202, 3209, 1042, 3220, 3230, 343}, {3240, 1858, 1862, 3244, 3248, 1870, 1874, 3252, 1882, 3256, 1890, 3260, 343}, 0, 1, 344, 346, {348,3264,3046,888,2665},{357,3024,17671},{370,16935},{376,2970,16922}},
-       {2990, 3024, 2665, 2970, 16935, 3057, 3062, 3074, 3079, {3084, 3092, 3098, 3105, 3116, 3123, 3131}, {3139, 3143, 1862, 3147, 3152, 3156, 3160}, {3165, 3171, 3179, 1004, 3185, 3190, 3196, 3202, 3209, 1042, 3220, 3230, 343}, {3240, 1858, 1862, 3244, 3248, 1870, 1874, 3252, 1882, 3256, 1890, 3260, 343}, 0, 1, 344, 346, {348,3264,3046,888,2665},{357,3024},{370,16935},{376,2970,16922}},
-       {2990, 3024, 2665, 2970, 16935, 3057, 3062, 3074, 3079, {3084, 3092, 3098, 3105, 3116, 3123, 3131}, {3139, 3143, 1862, 3147, 3152, 3156, 3160}, {3165, 3171, 3179, 1004, 3185, 3190, 3196, 3202, 3209, 1042, 3220, 3230, 343}, {3240, 1858, 1862, 3244, 3248, 1870, 1874, 3252, 1882, 3256, 1890, 3260, 343}, 0, 1, 344, 346, {348,3264,3046,11818,2665},{357,3024},{370,16935},{376,2970,16922}},
+       {1916, 1379, 1938, 438, 370, 447, 1414, 1949, 1955, {1962, 1970, 1977, 1986, 1995, 2006, 2014}, {2022, 2025, 2028, 2031, 2034, 2037, 2040}, {2043, 2050, 2058, 2064, 2070, 2074, 2079, 2084, 2091, 2101, 2109, 2118, 343}, {2127, 2131, 2135, 2139, 2070, 2143, 2147, 2151, 2155, 2159, 2163, 2167, 343}, 0, 1, 344, 346, {348,844,1938},{357,1379},{370},{376,438}},
+       {17401, 17425, 2674, 2195, 56, 447, 2763, 465, 468, {2770, 2777, 2784, 2792, 2802, 2811, 2818}, {2827, 2831, 2835, 2839, 2843, 2847, 2851}, {2855, 2863, 2872, 2064, 2878, 2882, 2887, 2084, 2091, 2892, 2109, 2900, 343}, {2127, 2131, 2909, 2139, 2878, 2143, 2147, 2151, 2155, 2913, 2163, 2917, 343}, 0, 0, 344, 346, {348,2748,888,2674},{2728,2728,2921,2935,2955,17425},{2755,2755,2970,1409,370,56},{2195,2195,2979,2991,438,2685}},
+       {2999, 3033, 2674, 2979, 16935, 3066, 3071, 3083, 3088, {3093, 3101, 3107, 3114, 3125, 3132, 3140}, {3148, 3152, 1871, 3156, 3161, 3165, 3169}, {3174, 3180, 3188, 1004, 3194, 3199, 3205, 3211, 3218, 1042, 3229, 3239, 343}, {3249, 1867, 1871, 3253, 3257, 1879, 1883, 3261, 1891, 3265, 1899, 3269, 343}, 0, 1, 344, 346, {348,3273,3055,2674},{357,3033},{370,16935},{376,2979,16922}},
+       {5984, 876, 1938, 438, 370, 447, 74, 465, 468, {3666, 3675, 3681, 3687, 3696, 3702, 3711}, {3718, 3723, 3728, 3733, 3738, 3743, 3748}, {3753, 3761, 3770, 3775, 3781, 3785, 3790, 3798, 3804, 3814, 1050, 3822, 343}, {3832, 3838, 3770, 3845, 3781, 3785, 3850, 3798, 3856, 1097, 1102, 3862, 343}, 0, 1, 344, 346, {888,3868,3273,844,1938},{357,876,3649},{370},{376,438}},
+       {17438, 24, 1676, 2991, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {184, 187, 190, 193, 196, 199, 202}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,1676},{357,24},{370,56},{376,46,2991}},
+       {17103, 5324, 17150, 15941, 17042, 17170, 17187, 1154, 1161, {1168, 1178, 1188, 1198, 1208, 1218, 1228}, {1238, 1242, 1246, 1250, 1254, 1258, 1262}, {1266, 1273, 1280, 1287, 1294, 1301, 1308, 1315, 1322, 1329, 1336, 1346, 343}, {5163, 5168, 5173, 5178, 5183, 5188, 5193, 5198, 5203, 5208, 5214, 5220, 343}, 0, 0, 344, 346, {348,17150},{357,5324},{370,17042},{376,15941}},
+       {17243, 876, 3868, 2195, 56, 447, 74, 3083, 3088, {2770, 2777, 2784, 2792, 2802, 2811, 2818}, {2827, 2831, 2835, 2839, 2843, 2847, 2851}, {2855, 2863, 2872, 2064, 2878, 2882, 2887, 2084, 2091, 2892, 2109, 2900, 343}, {2127, 2131, 2909, 2139, 2878, 2143, 2147, 2151, 2155, 2913, 2163, 2917, 343}, 0, 0, 344, 346, {348,2748,3273,3868},{2728,2728,2921,2935,2955,876},{2755,2755,2970,1409,370,56},{2195,2195,2979,2991,438,46}},
+       {2999, 3033, 2674, 2979, 16935, 3066, 3071, 3083, 3088, {3093, 3101, 3107, 3114, 3125, 3132, 3140}, {3148, 3152, 1871, 3156, 3161, 3165, 3169}, {3174, 3180, 3188, 1004, 3194, 3199, 3205, 3211, 3218, 1042, 3229, 3239, 343}, {3249, 1867, 1871, 3253, 3257, 1879, 1883, 3261, 1891, 3265, 1899, 3269, 343}, 0, 1, 344, 346, {348,3273,3055,888,2674},{357,3033},{370,16935},{376,2979,16922}},
+       {3623, 3649, 2674, 438, 370, 447, 74, 465, 468, {3666, 3675, 3681, 3687, 3696, 3702, 3711}, {3718, 3723, 3728, 3733, 3738, 3743, 3748}, {3753, 3761, 3770, 3775, 3781, 3785, 3790, 3798, 3804, 3814, 1050, 3822, 343}, {3832, 3838, 3770, 3845, 3781, 3785, 3850, 3798, 3856, 1097, 1102, 3862, 343}, 0, 1, 344, 346, {888,3868,3273,2674},{357,876,3649},{370},{376,438}},
+       {17438, 24, 1676, 2991, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {184, 187, 190, 193, 196, 199, 202}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,1676},{357,24},{370,56},{376,46,2991}},
+       {5984, 876, 2674, 438, 370, 447, 74, 3083, 3088, {2770, 2777, 2784, 2792, 2802, 2811, 2818}, {2827, 2831, 2835, 2839, 2843, 2847, 2851}, {2855, 2863, 2872, 2064, 2878, 2882, 2887, 2084, 2091, 2892, 2109, 2900, 343}, {2127, 2131, 2909, 2139, 2878, 2143, 2147, 2151, 2155, 2913, 2163, 2917, 343}, 0, 0, 344, 346, {348,2748,2674},{2728,2728,2921,2935,2955,876},{2755,2755,2970,1409,370},{2195,2195,2979,2991,438,376}},
+       {2999, 3033, 3055, 2979, 16935, 3066, 3071, 3083, 3088, {3093, 3101, 3107, 3114, 3125, 3132, 3140}, {3148, 3152, 1871, 3156, 3161, 3165, 3169}, {3174, 3180, 3188, 1004, 3194, 3199, 3205, 3211, 3218, 1042, 3229, 3239, 343}, {3249, 1867, 1871, 3253, 3257, 1879, 1883, 3261, 1891, 3265, 1899, 3269, 343}, 0, 1, 344, 346, {348,3273,3055,11818},{357,3033},{370,16935},{376,2979,16922}},
+       {17438, 24, 1676, 2991, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {87, 98, 113, 130, 147, 160, 173}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,1676},{357,24},{370,56},{376,46,2991}},
+       {16727, 409, 5015, 2979, 56, 447, 457, 465, 468, {2770, 2777, 2784, 2792, 2802, 2811, 2818}, {2827, 2831, 2835, 2839, 2843, 2847, 2851}, {2855, 2863, 2872, 2064, 2878, 2882, 2887, 2084, 2091, 2892, 2109, 2900, 343}, {2127, 2131, 2909, 2139, 2878, 2143, 2147, 2151, 2155, 2913, 2163, 2917, 343}, 0, 0, 344, 346, {348,2748,5015},{2728,2728,2921,2935,2955,409},{2755,2755,2970,1409,370,56},{2195,2195,2979,2991,438,46}},
+       {2999, 3033, 2674, 2979, 16935, 3066, 3071, 3083, 3088, {3093, 3101, 3107, 3114, 3125, 3132, 3140}, {3148, 3152, 1871, 3156, 3161, 3165, 3169}, {3174, 3180, 3188, 1004, 3194, 3199, 3205, 3211, 3218, 1042, 3229, 3239, 343}, {3249, 1867, 1871, 3253, 3257, 1879, 1883, 3261, 1891, 3265, 1899, 3269, 343}, 0, 1, 344, 346, {348,3273,3055,888,2674},{357,3033},{370,16935},{376,2979,16922}},
+       {17078, 24, 2674, 2979, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {184, 187, 190, 193, 196, 199, 202}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,2674},{357,24},{370,56},{376,46,2979}},
+       {2999, 3033, 2674, 2979, 16935, 3066, 3071, 3083, 3088, {3093, 3101, 3107, 3114, 3125, 3132, 3140}, {3148, 3152, 1871, 3156, 3161, 3165, 3169}, {3174, 3180, 3188, 1004, 3194, 3199, 3205, 3211, 3218, 1042, 3229, 3239, 343}, {3249, 1867, 1871, 3253, 3257, 1879, 1883, 3261, 1891, 3265, 1899, 3269, 343}, 0, 1, 344, 346, {348,3273,3055,888,2674},{357,3033},{370,16935},{376,2979,16922}},
+       {17078, 24, 2674, 2979, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {87, 98, 113, 130, 147, 160, 173}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,2674},{357,24},{370,56},{376,46,2979}},
+       {2999, 3033, 2674, 2979, 1409, 3066, 3071, 3083, 3088, {3093, 3101, 3107, 3114, 3125, 3132, 3140}, {3148, 3152, 1871, 3156, 3161, 3165, 3169}, {3174, 3180, 3188, 1004, 3194, 3199, 3205, 3211, 3218, 1042, 3229, 3239, 343}, {3249, 1867, 1871, 3253, 3257, 1879, 1883, 3261, 1891, 3265, 1899, 3269, 343}, 0, 1, 344, 346, {348,3273,3055,2674},{357,3033},{370,1409},{376,2979,1399}},
+       {17078, 24, 2674, 2979, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {87, 98, 113, 130, 147, 160, 173}, {17459, 17483, 17492, 17501, 17512, 17521, 17534, 17543, 17548, 17559, 17581, 17605, 343}, {17459, 17483, 17492, 17501, 17512, 17521, 17534, 17543, 17548, 17559, 17581, 17605, 343}, 0, 4, 344, 346, {348,37,2674},{357,24},{370,56},{376,46,2979}},
+       {2999, 3033, 2674, 2979, 16935, 3066, 3071, 3083, 3088, {3093, 3101, 3107, 3114, 3125, 3132, 3140}, {3148, 3152, 1871, 3156, 3161, 3165, 3169}, {3174, 3180, 3188, 1004, 3194, 3199, 3205, 3211, 3218, 1042, 3229, 3239, 343}, {3249, 1867, 1871, 3253, 3257, 1879, 1883, 3261, 1891, 3265, 1899, 3269, 343}, 0, 1, 344, 346, {348,3273,3055,888,2674},{357,3033},{370,16935},{376,2979,16922}},
+       {17078, 24, 2674, 2979, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {87, 98, 113, 130, 147, 160, 173}, {17459, 17483, 17492, 17501, 17627, 17521, 17534, 17543, 17548, 17559, 17581, 17605, 343}, {17459, 17483, 17492, 17501, 17627, 17521, 17534, 17543, 17548, 17559, 17581, 17605, 343}, 0, 6, 344, 346, {348,37,2674},{357,24},{370,56},{376,46,2979}},
+       {2999, 3033, 2674, 2979, 370, 3066, 3071, 3083, 3088, {3093, 3101, 3107, 3114, 3125, 3132, 3140}, {3148, 3152, 1871, 3156, 3161, 3165, 3169}, {3174, 3180, 3188, 1004, 3194, 3199, 3205, 3211, 3218, 1042, 3229, 3239, 343}, {3249, 1867, 1871, 3253, 3257, 1879, 1883, 3261, 1891, 3265, 1899, 3269, 343}, 0, 1, 344, 346, {348,3273,3055,888,2674},{357,3033},{370},{376,2979,1399}},
+       {17078, 24, 2674, 2979, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {87, 98, 113, 130, 147, 160, 173}, {17459, 17483, 17492, 17501, 17512, 17521, 17534, 17543, 17548, 17559, 17581, 17605, 343}, {17459, 17483, 17492, 17501, 17512, 17521, 17534, 17543, 17548, 17559, 17581, 17605, 343}, 0, 6, 344, 346, {348,37,2674},{357,24},{370,56},{376,46,2979}},
+       {2171, 409, 10606, 2195, 56, 447, 457, 465, 468, {2770, 2777, 2784, 2792, 2802, 2811, 2818}, {2827, 2831, 2835, 2839, 2843, 2847, 2851}, {2855, 2863, 2872, 2064, 2878, 2882, 2887, 2084, 2091, 2892, 2109, 2900, 343}, {2127, 2131, 2909, 2139, 2878, 2143, 2147, 2151, 2155, 2913, 2163, 2917, 343}, 0, 0, 344, 346, {348,2748,37,10606},{2728,2728,2921,2935,2955,409},{2755,2755,2970,1409,370,56},{2195,2195,2979,2991,438,46}},
+       {17048, 3033, 2674, 2991, 1409, 3066, 3071, 3083, 3088, {3093, 3101, 3107, 3114, 3125, 3132, 3140}, {3148, 3152, 1871, 3156, 3161, 3165, 3169}, {3174, 3180, 3188, 1004, 3194, 3199, 3205, 3211, 3218, 1042, 3229, 3239, 343}, {3249, 1867, 1871, 3253, 3257, 1879, 1883, 3261, 1891, 3265, 1899, 3269, 343}, 0, 1, 344, 346, {348,3273,3055,888,2674},{357,3033},{370,1409},{376,2979,1399,2991}},
+       {17078, 24, 2674, 2979, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {184, 187, 190, 193, 196, 199, 202}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,2674},{357,24},{370,56},{376,46,2979}},
+       {17401, 17425, 10606, 2195, 56, 447, 2763, 465, 468, {2770, 2777, 2784, 2792, 2802, 2811, 2818}, {2827, 2831, 2835, 2839, 2843, 2847, 2851}, {2855, 2863, 2872, 2064, 2878, 2882, 2887, 2084, 2091, 2892, 2109, 2900, 343}, {2127, 2131, 2909, 2139, 2878, 2143, 2147, 2151, 2155, 2913, 2163, 2917, 343}, 0, 0, 344, 346, {348,2748,10606},{2728,2728,2921,2935,2955,17425},{2755,2755,2970,1409,370,56},{2195,2195,2979,2991,438,2685}},
+       {17048, 3033, 1676, 2991, 1409, 3066, 3071, 3083, 3088, {3093, 3101, 3107, 3114, 3125, 3132, 3140}, {3148, 3152, 1871, 3156, 3161, 3165, 3169}, {3174, 3180, 3188, 1004, 3194, 3199, 3205, 3211, 3218, 1042, 3229, 3239, 343}, {3249, 1867, 1871, 3253, 3257, 1879, 1883, 3261, 1891, 3265, 1899, 3269, 343}, 0, 1, 344, 346, {348,3273,3055,1907,1676},{357,3033},{370,1409},{376,2979,1399,2991}},
+       {17078, 24, 2674, 2979, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {184, 187, 190, 193, 196, 199, 202}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,2674},{357,24},{370,56},{376,46,2979}},
+       {2999, 3033, 2674, 2979, 16935, 3066, 3071, 3083, 3088, {3093, 3101, 3107, 3114, 3125, 3132, 3140}, {3148, 3152, 1871, 3156, 3161, 3165, 3169}, {3174, 3180, 3188, 1004, 3194, 3199, 3205, 3211, 3218, 1042, 3229, 3239, 343}, {3249, 1867, 1871, 3253, 3257, 1879, 1883, 3261, 1891, 3265, 1899, 3269, 343}, 0, 1, 344, 346, {348,3273,3055,888,2674},{357,3033},{370,16935},{376,2979,16922}},
+       {17078, 24, 2674, 2979, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {184, 187, 190, 193, 196, 199, 202}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,2674},{357,24},{370,56},{376,46,2979}},
+       {2999, 3033, 2674, 2979, 16935, 3066, 3071, 3083, 3088, {3093, 3101, 3107, 3114, 3125, 3132, 3140}, {3148, 3152, 1871, 3156, 3161, 3165, 3169}, {3174, 3180, 3188, 1004, 3194, 3199, 3205, 3211, 3218, 1042, 3229, 3239, 343}, {3249, 1867, 1871, 3253, 3257, 1879, 1883, 3261, 1891, 3265, 1899, 3269, 343}, 0, 1, 344, 346, {348,3273,3055,888,2674},{357,3033},{370,16935},{376,2979,16922}},
+       {17078, 24, 2674, 2979, 56, 63, 74, 81, 84, {87, 98, 113, 130, 147, 160, 173}, {87, 98, 113, 130, 147, 160, 173}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, {205, 216, 229, 238, 249, 258, 269, 280, 291, 304, 317, 330, 343}, 0, 6, 344, 346, {348,37,2674},{357,24},{370,56},{376,46,2979}},
+       {2999, 3033, 2674, 2979, 16935, 3066, 3071, 3083, 3088, {3093, 3101, 3107, 3114, 3125, 3132, 3140}, {3148, 3152, 1871, 3156, 3161, 3165, 3169}, {3174, 3180, 3188, 1004, 3194, 3199, 3205, 3211, 3218, 1042, 3229, 3239, 343}, {3249, 1867, 1871, 3253, 3257, 1879, 1883, 3261, 1891, 3265, 1899, 3269, 343}, 0, 1, 344, 346, {348,3273,3055,888,2674},{357,3033},{370,16935},{376,2979,16922}},
+       {2999, 3033, 2674, 2979, 16935, 3066, 3071, 3083, 3088, {3093, 3101, 3107, 3114, 3125, 3132, 3140}, {3148, 3152, 1871, 3156, 3161, 3165, 3169}, {3174, 3180, 3188, 1004, 3194, 3199, 3205, 3211, 3218, 1042, 3229, 3239, 343}, {3249, 1867, 1871, 3253, 3257, 1879, 1883, 3261, 1891, 3265, 1899, 3269, 343}, 0, 1, 344, 346, {348,3273,3055,888,2674},{357,3033},{370,16935},{376,2979,16922}},
+       {17636, 17671, 2674, 2979, 16935, 3066, 17694, 3083, 3088, {3093, 3101, 3107, 3114, 3125, 3132, 3140}, {3148, 3152, 1871, 3156, 3161, 3165, 3169}, {3174, 3180, 3188, 1004, 3194, 3199, 3205, 3211, 3218, 1042, 3229, 3239, 343}, {3249, 1867, 1871, 3253, 3257, 1879, 1883, 3261, 1891, 3265, 1899, 3269, 343}, 0, 1, 344, 346, {348,3273,3055,888,2674},{357,3033,17671},{370,16935},{376,2979,16922}},
+       {2999, 3033, 2674, 2979, 16935, 3066, 3071, 3083, 3088, {3093, 3101, 3107, 3114, 3125, 3132, 3140}, {3148, 3152, 1871, 3156, 3161, 3165, 3169}, {3174, 3180, 3188, 1004, 3194, 3199, 3205, 3211, 3218, 1042, 3229, 3239, 343}, {3249, 1867, 1871, 3253, 3257, 1879, 1883, 3261, 1891, 3265, 1899, 3269, 343}, 0, 1, 344, 346, {348,3273,3055,888,2674},{357,3033},{370,16935},{376,2979,16922}},
+       {2999, 3033, 2674, 2979, 16935, 3066, 3071, 3083, 3088, {3093, 3101, 3107, 3114, 3125, 3132, 3140}, {3148, 3152, 1871, 3156, 3161, 3165, 3169}, {3174, 3180, 3188, 1004, 3194, 3199, 3205, 3211, 3218, 1042, 3229, 3239, 343}, {3249, 1867, 1871, 3253, 3257, 1879, 1883, 3261, 1891, 3265, 1899, 3269, 343}, 0, 1, 344, 346, {348,3273,3055,11818,2674},{357,3033},{370,16935},{376,2979,16922}},
        {1112, 357, 348, 376, 370, 1136, 1146, 1154, 1161, {1168, 1178, 1188, 1198, 1208, 1218, 1228}, {1238, 1242, 1246, 1250, 1254, 1258, 1262}, {1266, 1273, 1280, 1287, 1294, 1301, 1308, 1315, 1322, 1329, 1336, 1346, 343}, {1266, 1273, 1280, 1287, 1294, 1301, 1308, 1315, 1322, 1329, 1336, 1346, 343}, 0, 0, 344, 346, {348},{357},{370},{376}}
 };
 
@@ -310,7 +310,7 @@ static const NumberFormatEntry number_format_entries [] = {
        {17744, 17737, 17744, 17737, 17744, 17737, 17965, 17742, 17746, 17720, 17750, 17760, 17733, 17735, 0, 0, 1, 1, 1, 2, 2, 2, {3, -1, -1, -1, -1}, {3, -1, -1, -1, -1}, {3, -1, -1, -1, -1}},
        {17744, 17928, 17744, 17928, 17744, 17928, 17967, 17742, 17716, 17720, 17724, 17729, 17733, 17735, 2, 2, 1, 1, 1, 2, 2, 2, {3, -1, -1, -1, -1}, {3, -1, -1, -1, -1}, {3, -1, -1, -1, -1}},
        {17707, 17710, 17707, 17710, 17707, 17710, 17972, 17713, 17716, 17720, 17724, 17729, 17733, 17735, 11, 2, 1, 1, 3, 2, 2, 2, {3, -1, -1, -1, -1}, {3, -1, -1, -1, -1}, {3, -1, -1, -1, -1}},
-       {17744, 17737, 17744, 17737, 17744, 17737, 4367, 17742, 17746, 17720, 17750, 17760, 17733, 17735, 0, 0, 1, 1, 1, 2, 2, 2, {3, -1, -1, -1, -1}, {3, -1, -1, -1, -1}, {3, -1, -1, -1, -1}},
+       {17744, 17737, 17744, 17737, 17744, 17737, 4376, 17742, 17746, 17720, 17750, 17760, 17733, 17735, 0, 0, 1, 1, 1, 2, 2, 2, {3, -1, -1, -1, -1}, {3, -1, -1, -1, -1}, {3, -1, -1, -1, -1}},
        {17744, 17737, 17744, 17737, 17744, 17737, 17800, 17742, 17746, 17720, 17750, 17760, 17733, 17735, 1, 0, 1, 1, 1, 2, 2, 2, {3, -1, -1, -1, -1}, {3, -1, -1, -1, -1}, {3, -1, -1, -1, -1}},
        {17737, 17744, 17737, 17744, 17737, 17744, 17982, 17742, 17716, 17720, 17724, 17729, 17733, 17735, 0, 0, 1, 1, 1, 2, 2, 2, {3, -1, -1, -1, -1}, {3, -1, -1, -1, -1}, {3, -1, -1, -1, -1}},
        {17737, 17744, 17737, 17744, 17737, 17744, 17785, 17742, 17716, 17720, 17724, 17729, 17733, 17735, 8, 3, 1, 1, 1, 2, 2, 2, {3, -1, -1, -1, -1}, {3, -1, -1, -1, -1}, {3, -1, -1, -1, -1}},
@@ -360,7 +360,7 @@ static const CultureInfoEntry culture_entries [] = {
        {0x0009, 0x007F, 0x0409, -1,18384, 18387, 18387, 18387, 18387, 18395, 18399, 18384, 0, {0, 0, 0, 0, 0}, 8, 8, { 1252, 37, 10000, 437, ',' }},
        {0x000A, 0x007F, 0x0C0A, -1,18403, 18406, 18406, 18406, 18414, 18423, 18427, 18403, 0, {0, 0, 0, 0, 0}, 9, 9, { 1252, 20284, 10000, 850, ';' }},
        {0x000B, 0x007F, 0x040B, -1,18431, 18434, 18434, 18434, 18442, 18448, 18452, 18431, 0, {0, 0, 0, 0, 0}, 10, 10, { 1252, 20278, 10000, 850, ';' }},
-       {0x000C, 0x007F, 0x040C, -1,5968, 18456, 18456, 18456, 18463, 18473, 18477, 5968, 0, {0, 0, 0, 0, 0}, 11, 11, { 1252, 20297, 10000, 850, ';' }},
+       {0x000C, 0x007F, 0x040C, -1,5977, 18456, 18456, 18456, 18463, 18473, 18477, 5977, 0, {0, 0, 0, 0, 0}, 11, 11, { 1252, 20297, 10000, 850, ';' }},
        {0x000D, 0x007F, 0x040D, -1,18481, 18484, 18484, 18484, 18491, 18502, 18506, 18481, 0, {0, 0, 0, 0, 0}, 12, 12, { 1255, 500, 10005, 862, ',' }},
        {0x000E, 0x007F, 0x040E, -1,18510, 18513, 18513, 18513, 18523, 18530, 18534, 18510, 0, {0, 0, 0, 0, 0}, 13, 13, { 1250, 500, 10029, 852, ';' }},
        {0x000F, 0x007F, 0x040F, -1,18538, 18541, 18541, 18541, 18551, 18561, 18565, 18538, 0, {0, 0, 0, 0, 0}, 14, 14, { 1252, 20871, 10079, 850, ';' }},
@@ -387,7 +387,7 @@ static const CultureInfoEntry culture_entries [] = {
        {0x0026, 0x007F, 0x0426, -1,19180, 19183, 19183, 19183, 19191, 19201, 19205, 19180, 0, {0, 0, 0, 0, 0}, 35, 35, { 1257, 500, 10029, 775, ';' }},
        {0x0027, 0x007F, 0x0427, -1,19209, 19212, 19212, 19212, 19223, 19233, 19237, 19209, 0, {0, 0, 0, 0, 0}, 36, 36, { 1257, 500, 10029, 775, ';' }},
        {0x0029, 0x007F, 0x0429, -1,19241, 19244, 19244, 19244, 19252, 19263, 19267, 19241, 0, {0, 0, 0, 0, 0}, 37, 37, { 1256, 20420, 10004, 720, ';' }},
-       {0x002A, 0x007F, 0x042A, -1,19271, 19274, 19274, 19274, 19285, 19300, 3156, 19271, 0, {0, 0, 0, 0, 0}, 38, 38, { 1258, 500, 10000, 1258, ',' }},
+       {0x002A, 0x007F, 0x042A, -1,19271, 19274, 19274, 19274, 19285, 19300, 3165, 19271, 0, {0, 0, 0, 0, 0}, 38, 38, { 1258, 500, 10000, 1258, ',' }},
        {0x002B, 0x007F, 0x042B, -1,19304, 19307, 19307, 19307, 19316, 19331, 19335, 19304, 0, {0, 0, 0, 0, 0}, 39, 39, { 0, 500, 2, 1, ',' }},
        {0x002D, 0x007F, 0x042D, -1,19339, 19342, 19342, 19342, 19349, 19357, 19361, 19339, 0, {0, 0, 0, 0, 0}, 40, 40, { 1252, 500, 10000, 850, ';' }},
        {0x002F, 0x007F, 0x042F, -1,19365, 19368, 19368, 19368, 19379, 19400, 19404, 19365, 0, {0, 0, 0, 0, 0}, 41, 41, { 1251, 500, 10007, 866, ';' }},
@@ -400,7 +400,7 @@ static const CultureInfoEntry culture_entries [] = {
        {0x0049, 0x007F, 0x0449, -1,19615, 19618, 19618, 19618, 19624, 19640, 19644, 19615, 0, {0, 0, 0, 0, 0}, 48, 48, { 0, 500, 2, 1, ',' }},
        {0x004A, 0x007F, 0x044A, -1,19648, 19651, 19651, 19651, 19658, 19677, 19681, 19648, 0, {0, 0, 0, 0, 0}, 49, 49, { 0, 500, 2, 1, ',' }},
        {0x004B, 0x007F, 0x044B, -1,19685, 19688, 19688, 19688, 19696, 19712, 19716, 19685, 0, {0, 0, 0, 0, 0}, 50, 50, { 0, 500, 2, 1, ',' }},
-       {0x004E, 0x007F, 0x044E, -1,19720, 19723, 19723, 19723, 19731, 19747, 1862, 19720, 0, {0, 0, 0, 0, 0}, 51, 51, { 0, 500, 2, 1, ',' }},
+       {0x004E, 0x007F, 0x044E, -1,19720, 19723, 19723, 19723, 19731, 19747, 1871, 19720, 0, {0, 0, 0, 0, 0}, 51, 51, { 0, 500, 2, 1, ',' }},
        {0x0056, 0x007F, 0x0456, -1,19751, 19754, 19754, 19754, 19763, 19770, 19774, 19751, 0, {0, 0, 0, 0, 0}, 52, 52, { 1252, 500, 10000, 850, ',' }},
        {0x0057, 0x007F, 0x0457, -1,19778, 19782, 19782, 19782, 19790, 19809, 19778, 19511, 0, {0, 0, 0, 0, 0}, 53, 53, { 0, 500, 2, 1, ',' }},
        {0x0401, 0x0001, 0x0401, 174,19813, 19819, 19819, 19819, 19841, 18165, 18169, 18140, 10998, {16777216, 0, 0, 0, 0}, 54, 54, { 1256, 20420, 10004, 720, ';' }},
@@ -409,11 +409,11 @@ static const CultureInfoEntry culture_entries [] = {
        {0x0404, 0x7C04, 0x0404, 207,20001, 20007, 20007, 20007, 20024, 20040, 18266, 18270, 20044, {0, 0, 0, 0, 0}, 57, 57, { 950, 500, 10002, 950, ',' }},
        {0x0405, 0x0005, 0x0405, 49,20047, 20053, 20053, 20053, 20076, 18292, 18296, 18273, 20106, {0, 0, 0, 0, 0}, 58, 58, { 1250, 500, 10029, 852, ';' }},
        {0x0406, 0x0006, 0x0406, 52,20109, 20115, 20115, 20115, 20132, 18316, 18320, 18300, 20148, {0, 0, 0, 0, 0}, 59, 59, { 1252, 20277, 10000, 850, ';' }},
-       {0x0407, 0x0007, 0x0407, 50,20151, 20157, 20157, 20157, 20174, 18342, 18346, 18324, 4291, {0, 0, 0, 0, 0}, 60, 60, { 1252, 20273, 10000, 850, ';' }},
+       {0x0407, 0x0007, 0x0407, 50,20151, 20157, 20157, 20157, 20174, 18342, 18346, 18324, 4300, {0, 0, 0, 0, 0}, 60, 60, { 1252, 20273, 10000, 850, ';' }},
        {0x0408, 0x0008, 0x0408, 81,20196, 20202, 20202, 20202, 20217, 18376, 18380, 18350, 20249, {0, 0, 0, 0, 0}, 61, 61, { 1253, 20273, 10006, 737, ';' }},
        {0x0409, 0x0009, 0x0409, 212,20252, 20258, 20258, 20258, 20258, 18395, 18399, 18384, 20282, {0, 0, 0, 0, 0}, 62, 62, { 1252, 37, 10000, 437, ',' }},
        {0x040B, 0x000B, 0x040B, 63,20285, 20291, 20291, 20291, 20309, 18448, 18452, 18431, 20323, {0, 0, 0, 0, 0}, 63, 63, { 1252, 20278, 10000, 850, ';' }},
-       {0x040C, 0x000C, 0x040C, 68,20326, 20332, 20332, 20332, 20348, 18473, 18477, 5968, 20367, {0, 0, 0, 0, 0}, 64, 64, { 1252, 20297, 10000, 850, ';' }},
+       {0x040C, 0x000C, 0x040C, 68,20326, 20332, 20332, 20332, 20348, 18473, 18477, 5977, 20367, {0, 0, 0, 0, 0}, 64, 64, { 1252, 20297, 10000, 850, ';' }},
        {0x040D, 0x000D, 0x040D, 92,20370, 20376, 20376, 20376, 20392, 18502, 18506, 18481, 20416, {0, 0, 0, 0, 0}, 65, 65, { 1255, 500, 10005, 862, ',' }},
        {0x040E, 0x000E, 0x040E, 89,20419, 20425, 20425, 20425, 20445, 18530, 18534, 18510, 20468, {0, 0, 0, 0, 0}, 66, 66, { 1250, 500, 10029, 852, ';' }},
        {0x040F, 0x000F, 0x040F, 97,20471, 20477, 20477, 20477, 20497, 18561, 18565, 18538, 20517, {0, 0, 0, 0, 0}, 67, 67, { 1252, 20871, 10079, 850, ';' }},
@@ -440,7 +440,7 @@ static const CultureInfoEntry culture_entries [] = {
        {0x0426, 0x0026, 0x0426, 121,21606, 21612, 21612, 21612, 21629, 19201, 19205, 19180, 21649, {0, 0, 0, 0, 0}, 88, 88, { 1257, 500, 10029, 775, ';' }},
        {0x0427, 0x0027, 0x0427, 119,21652, 21658, 21658, 21658, 21681, 19233, 19237, 19209, 21701, {0, 0, 0, 0, 0}, 89, 89, { 1257, 500, 10029, 775, ';' }},
        {0x0429, 0x0029, 0x0429, 96,21704, 21710, 21710, 21710, 21725, 19263, 19267, 19241, 21749, {0, 0, 0, 0, 0}, 90, 90, { 1256, 20420, 10004, 720, ';' }},
-       {0x042A, 0x002A, 0x042A, 220,21752, 21758, 21758, 21758, 21779, 19300, 3156, 19271, 21807, {0, 0, 0, 0, 0}, 91, 91, { 1258, 500, 10000, 1258, ',' }},
+       {0x042A, 0x002A, 0x042A, 220,21752, 21758, 21758, 21758, 21779, 19300, 3165, 19271, 21807, {0, 0, 0, 0, 0}, 91, 91, { 1258, 500, 10000, 1258, ',' }},
        {0x042B, 0x002B, 0x042B, 5,21810, 21816, 21816, 21816, 21835, 19331, 19335, 19304, 465, {0, 0, 0, 0, 0}, 92, 92, { 0, 500, 2, 1, ',' }},
        {0x042D, 0x002D, 0x042D, 61,21900, 21906, 21906, 21906, 21921, 19357, 19361, 19339, 19998, {0, 0, 0, 0, 0}, 93, 93, { 1252, 500, 10000, 850, ';' }},
        {0x042F, 0x002F, 0x042F, 128,21940, 21946, 21946, 21946, 21969, 19400, 19404, 19365, 22013, {0, 0, 0, 0, 0}, 94, 94, { 1251, 500, 10007, 866, ';' }},
@@ -453,7 +453,7 @@ static const CultureInfoEntry culture_entries [] = {
        {0x0449, 0x0049, 0x0449, 93,22369, 22375, 22375, 22375, 22389, 19640, 19644, 19615, 22263, {0, 0, 0, 0, 0}, 101, 101, { 0, 500, 2, 1, ',' }},
        {0x044A, 0x004A, 0x044A, 93,22429, 22435, 22435, 22435, 22450, 19677, 19681, 19648, 22263, {0, 0, 0, 0, 0}, 102, 102, { 0, 500, 2, 1, ',' }},
        {0x044B, 0x004B, 0x044B, 93,22497, 22503, 22503, 22503, 22519, 19712, 19716, 19685, 22263, {0, 0, 0, 0, 0}, 103, 103, { 0, 500, 2, 1, ',' }},
-       {0x044E, 0x004E, 0x044E, 93,22550, 22556, 22556, 22556, 22572, 19747, 1862, 19720, 22263, {0, 0, 0, 0, 0}, 104, 104, { 0, 500, 2, 1, ',' }},
+       {0x044E, 0x004E, 0x044E, 93,22550, 22556, 22556, 22556, 22572, 19747, 1871, 19720, 22263, {0, 0, 0, 0, 0}, 104, 104, { 0, 500, 2, 1, ',' }},
        {0x0456, 0x0056, 0x0456, 61,22603, 22609, 22609, 22609, 22626, 19770, 19774, 19751, 19998, {0, 0, 0, 0, 0}, 105, 105, { 1252, 500, 10000, 850, ',' }},
        {0x0457, 0x0057, 0x0457, 93,22643, 22650, 22650, 22650, 22666, 19809, 19778, 19778, 22263, {0, 0, 0, 0, 0}, 106, 106, { 0, 500, 2, 1, ',' }},
        {0x0801, 0x0001, 0x0801, 95,22700, 22706, 22706, 22706, 22720, 22750, 18169, 18140, 22754, {2, 1, 0, 0, 0}, 107, 107, { 1256, 20420, 10004, 720, ';' }},
@@ -461,7 +461,7 @@ static const CultureInfoEntry culture_entries [] = {
        {0x0807, 0x0007, 0x0807, 37,22795, 22801, 22801, 22801, 22822, 22840, 18346, 18324, 11001, {0, 0, 0, 0, 0}, 109, 109, { 1252, 20273, 10000, 850, ';' }},
        {0x0809, 0x0009, 0x0809, 70,22844, 22850, 22850, 22850, 22850, 22875, 18399, 18384, 22879, {0, 0, 0, 0, 0}, 110, 110, { 1252, 20285, 10000, 850, ',' }},
        {0x080A, 0x000A, 0x080A, 141,22882, 22888, 22888, 22888, 22905, 22924, 18427, 18403, 22928, {0, 0, 0, 0, 0}, 111, 111, { 1252, 20284, 10000, 850, ',' }},
-       {0x080C, 0x000C, 0x080C, 17,22931, 22937, 22937, 22937, 22954, 22975, 18477, 5968, 22979, {0, 0, 0, 0, 0}, 112, 112, { 1252, 20297, 10000, 850, ';' }},
+       {0x080C, 0x000C, 0x080C, 17,22931, 22937, 22937, 22937, 22954, 22975, 18477, 5977, 22979, {0, 0, 0, 0, 0}, 112, 112, { 1252, 20297, 10000, 850, ';' }},
        {0x0810, 0x0010, 0x0810, 37,22982, 22988, 22988, 22988, 23010, 23030, 18593, 18569, 11001, {0, 0, 0, 0, 0}, 113, 113, { 1252, 500, 10000, 850, ';' }},
        {0x0813, 0x0013, 0x0813, 17,23034, 23040, 23040, 23040, 23056, 23077, 18679, 18655, 22979, {0, 0, 0, 0, 0}, 114, 114, { 1252, 500, 10000, 850, ';' }},
        {0x0814, 0x0014, 0x0814, 150,23081, 23087, 23087, 23087, 23114, 23136, 23140, 23144, 20803, {0, 0, 0, 0, 0}, 115, 115, { 1252, 20277, 10000, 850, ';' }},
@@ -472,18 +472,18 @@ static const CultureInfoEntry culture_entries [] = {
        {0x0C07, 0x0007, 0x0C07, 10,23386, 23392, 23392, 23392, 23409, 23431, 18346, 18324, 23435, {0, 0, 0, 0, 0}, 120, 120, { 1252, 20273, 10000, 850, ';' }},
        {0x0C09, 0x0009, 0x0C09, 11,23438, 23444, 23444, 23444, 23444, 23464, 18399, 18384, 23468, {0, 0, 0, 0, 0}, 121, 121, { 1252, 500, 10000, 850, ',' }},
        {0x0C0A, 0x000A, 0x0C0A, 61,23471, 23477, 23477, 23477, 23493, 23512, 18427, 18403, 19998, {0, 0, 0, 0, 0}, 122, 122, { 1252, 20284, 10000, 850, ';' }},
-       {0x0C0C, 0x000C, 0x0C0C, 32,23516, 23522, 23522, 23522, 23538, 23557, 18477, 5968, 23561, {0, 0, 0, 0, 0}, 123, 123, { 1252, 20297, 10000, 850, ';' }},
+       {0x0C0C, 0x000C, 0x0C0C, 32,23516, 23522, 23522, 23522, 23538, 23557, 18477, 5977, 23561, {0, 0, 0, 0, 0}, 123, 123, { 1252, 20297, 10000, 850, ';' }},
        {0x1001, 0x0001, 0x1001, 122,23564, 23570, 23570, 23570, 23585, 23613, 18169, 18140, 23617, {16777216, 0, 0, 0, 0}, 124, 124, { 1256, 20420, 10004, 720, ';' }},
        {0x1004, 0x0004, 0x1004, 179,23620, 23626, 23626, 23626, 23646, 23665, 18266, 18270, 23669, {0, 0, 0, 0, 0}, 125, 125, { 936, 500, 10008, 936, ',' }},
        {0x1007, 0x0007, 0x1007, 120,23672, 23678, 23678, 23678, 23698, 23718, 18346, 18324, 23722, {0, 0, 0, 0, 0}, 126, 126, { 1252, 20273, 10000, 850, ';' }},
        {0x1009, 0x0009, 0x1009, 32,23725, 23731, 23731, 23731, 23731, 23748, 18399, 18384, 23561, {0, 0, 0, 0, 0}, 127, 127, { 1252, 37, 10000, 850, ',' }},
        {0x100A, 0x000A, 0x100A, 82,23752, 23758, 23758, 23758, 23778, 23799, 18427, 18403, 23803, {0, 0, 0, 0, 0}, 128, 128, { 1252, 20284, 10000, 850, ',' }},
-       {0x100C, 0x000C, 0x100C, 37,23806, 23812, 23812, 23812, 23833, 23852, 18477, 5968, 11001, {0, 0, 0, 0, 0}, 129, 129, { 1252, 20297, 10000, 850, ';' }},
+       {0x100C, 0x000C, 0x100C, 37,23806, 23812, 23812, 23812, 23833, 23852, 18477, 5977, 11001, {0, 0, 0, 0, 0}, 129, 129, { 1252, 20297, 10000, 850, ';' }},
        {0x1401, 0x0001, 0x1401, 55,23856, 23862, 23862, 23862, 23879, 23911, 18169, 18140, 23915, {16777216, 0, 0, 0, 0}, 130, 130, { 1256, 20420, 10004, 720, ';' }},
        {0x1404, 0x0004, 0x1404, 132,23918, 23924, 23924, 23924, 23953, 23990, 18266, 18270, 23994, {0, 0, 0, 0, 0}, 131, 131, { 950, 500, 10002, 950, ',' }},
        {0x1409, 0x0009, 0x1409, 154,23997, 24003, 24003, 24003, 24003, 24025, 18399, 18384, 24029, {0, 0, 0, 0, 0}, 132, 132, { 1252, 500, 10000, 850, ',' }},
        {0x140A, 0x000A, 0x140A, 44,24032, 24038, 24038, 24038, 24059, 24081, 18427, 18403, 24085, {0, 0, 0, 0, 0}, 133, 133, { 1252, 20284, 10000, 850, ',' }},
-       {0x140C, 0x000C, 0x140C, 120,24088, 24094, 24094, 24094, 24114, 24137, 18477, 5968, 23722, {0, 0, 0, 0, 0}, 134, 134, { 1252, 20297, 10000, 850, ';' }},
+       {0x140C, 0x000C, 0x140C, 120,24088, 24094, 24094, 24094, 24114, 24137, 18477, 5977, 23722, {0, 0, 0, 0, 0}, 134, 134, { 1252, 20297, 10000, 850, ';' }},
        {0x1801, 0x0001, 0x1801, 123,24141, 24147, 24147, 24147, 24164, 24194, 18169, 18140, 24198, {16777216, 0, 0, 0, 0}, 135, 135, { 1256, 20420, 10004, 720, ';' }},
        {0x1809, 0x0009, 0x1809, 91,24201, 24207, 24207, 24207, 24207, 24225, 18399, 18384, 24229, {0, 0, 0, 0, 0}, 136, 136, { 1252, 500, 10000, 850, ',' }},
        {0x180A, 0x000A, 0x180A, 156,24232, 24238, 24238, 24238, 24255, 24274, 18427, 18403, 24278, {0, 0, 0, 0, 0}, 137, 137, { 1252, 20284, 10000, 850, ',' }},
@@ -595,7 +595,7 @@ static const CultureInfoNameEntry culture_name_entries [] = {
        {26104, 63},
        {19482, 44},
        {26110, 97},
-       {5968, 11},
+       {5977, 11},
        {26116, 112},
        {26122, 123},
        {26128, 129},
@@ -739,7 +739,7 @@ static const RegionInfoEntry region_entries [] = {
        { 0, 47,27857,343,343,27860,343,26799,26803},
        { 0, 48,27877,343,343,27880,343,27887,27891},
        { 0, 49,20106,343,343,27904,343,27919,27923},
-       { 0, 50,4291,343,343,27945,343,26780,26784},
+       { 0, 50,4300,343,343,27945,343,26780,26784},
        { 0, 51,27953,343,343,27956,343,27965,27969},
        { 0, 52,20148,343,343,27984,343,27992,27996},
        { 0, 53,28009,343,343,28012,343,26540,26544},
@@ -814,7 +814,7 @@ static const RegionInfoEntry region_entries [] = {
        { 0, 122,23617,343,343,29713,343,29719,29723},
        { 0, 123,24198,343,343,29736,343,28182,28186},
        { 0, 124,29744,343,343,29747,343,26780,26784},
-       { 0, 125,7428,343,343,29754,343,29762,29766},
+       { 0, 125,7437,343,343,29754,343,29762,29766},
        { 0, 126,29779,343,343,29782,343,29793,29797},
        { 0, 127,29814,343,343,29817,343,26758,26762},
        { 0, 128,22013,343,343,29834,343,29844,29848},
@@ -973,7 +973,7 @@ static const RegionInfoNameEntry region_name_entries [] = {
        {27857, 47},
        {27877, 48},
        {20106, 49},
-       {4291, 50},
+       {4300, 50},
        {27953, 51},
        {20148, 52},
        {28009, 53},
@@ -1048,7 +1048,7 @@ static const RegionInfoNameEntry region_name_entries [] = {
        {23617, 122},
        {24198, 123},
        {29744, 124},
-       {7428, 125},
+       {7437, 125},
        {29779, 126},
        {29814, 127},
        {22013, 128},
@@ -1361,6 +1361,7 @@ static const char locale_strings [] = {
        "d. MMM yyyy HH:mm:ss\0"
        "d. MMM yyyy\0"
        "dd-MM-yyyy\0"
+       "dd. MMMM\0"
        "s\xc3\xb8ndag\0"
        "mandag\0"
        "tirsdag\0"
@@ -2289,7 +2290,6 @@ static const char locale_strings [] = {
        "\xd1\x81\xd0\xbd\xd0\xb5\0"
        "dd. MMMM yyyy H:mm:ss\0"
        "dd. MMMM yyyy\0"
-       "dd. MMMM\0"
        "nedelja\0"
        "ponedeljek\0"
        "torek\0"
index e3cfd09b61ed439605aadb0db8bd7383c2d1d2f9..1cf21e31b702c20ca165a913ad217e7c8ce2a745 100644 (file)
@@ -12,6 +12,7 @@
 #include "mono/metadata/opcodes.h"
 #include "mono/metadata/metadata-internals.h"
 #include "mono/metadata/class-internals.h"
+#include "mono/metadata/object-internals.h"
 #include "mono/metadata/mono-endian.h"
 #include "mono/metadata/debug-helpers.h"
 #include "mono/metadata/tabledefs.h"
@@ -843,7 +844,7 @@ mono_object_describe (MonoObject *obj)
                MonoArray *array = (MonoArray*)obj;
                sep = print_name_space (klass);
                g_print ("%s%s", sep, klass->name);
-               g_print (" at %p, rank: %d, length: %d\n", obj, klass->rank, mono_array_length (array));
+               g_print (" at %p, rank: %d, length: %d\n", obj, klass->rank, (int)mono_array_length (array));
        } else {
                sep = print_name_space (klass);
                g_print ("%s%s", sep, klass->name);
index 600873fa7fb608fd921234f4254f310b3f2198ab..c4579ebe128009ee231c34a394d75a9452228af3 100644 (file)
@@ -85,6 +85,7 @@ typedef struct {
        union {
                MonoClass *catch_class;
                gpointer filter;
+               gpointer handler_end;
        } data;
 } MonoJitExceptionInfo;
 
@@ -105,6 +106,42 @@ typedef struct
        gboolean this_in_reg:1;
 } MonoGenericJitInfo;
 
+/*
+A try block hole is used to represent a non-contiguous part of
+of a segment of native code protected by a given .try block.
+Usually, a try block is defined as a contiguous segment of code.
+But in some cases it's needed to have some parts of it to not be protected.
+For example, given "try {} finally {}", the code in the .try block to call
+the finally part looks like:
+
+try {
+    ...
+       call finally_block
+       adjust stack
+       jump outside try block
+       ...
+} finally {
+       ...
+}
+
+The instructions between the call and the jump should not be under the try block since they happen
+after the finally block executes, which means if an async exceptions happens at that point we would
+execute the finally clause twice. So, to avoid this, we introduce a hole in the try block to signal
+that those instructions are not protected.
+*/
+typedef struct
+{
+       guint32 offset;
+       guint16 clause;
+       guint16 length;
+} MonoTryBlockHoleJitInfo;
+
+typedef struct
+{
+       guint16 num_holes;
+       MonoTryBlockHoleJitInfo holes [MONO_ZERO_LEN_ARRAY];
+} MonoTryBlockHoleTableJitInfo;
+
 struct _MonoJitInfo {
        /* NOTE: These first two elements (method and
           next_jit_code_hash) must be in the same order and at the
@@ -127,6 +164,7 @@ struct _MonoJitInfo {
        gboolean    cas_method_deny:1;
        gboolean    cas_method_permitonly:1;
        gboolean    has_generic_jit_info:1;
+       gboolean    has_try_block_holes:1;
        gboolean    from_aot:1;
        gboolean    from_llvm:1;
 #ifdef HAVE_SGEN_GC
@@ -135,6 +173,7 @@ struct _MonoJitInfo {
 #endif
        MonoJitExceptionInfo clauses [MONO_ZERO_LEN_ARRAY];
        /* There is an optional MonoGenericJitInfo after the clauses */
+       /* There is an optional MonoTryBlockHoleTableJitInfo after MonoGenericJitInfo clauses*/
 };
 
 #define MONO_SIZEOF_JIT_INFO (offsetof (struct _MonoJitInfo, clauses))
@@ -259,7 +298,7 @@ struct _MonoDomain {
        gpointer runtime_info;
 
        /*thread pool jobs, used to coordinate shutdown.*/
-       int                                     threadpool_jobs;
+       volatile int                    threadpool_jobs;
        HANDLE                          cleanup_semaphore;
        
        /* Contains the compiled runtime invoke wrapper used by finalizers */
@@ -372,6 +411,9 @@ mono_domain_unset (void) MONO_INTERNAL;
 void
 mono_domain_set_internal_with_options (MonoDomain *domain, gboolean migrate_exception) MONO_INTERNAL;
 
+MonoTryBlockHoleTableJitInfo*
+mono_jit_info_get_try_block_hole_table_info (MonoJitInfo *ji) MONO_INTERNAL;
+
 /* 
  * Installs a new function which is used to return a MonoJitInfo for a method inside
  * an AOT module.
index 12a21fa61aab330f9a0a2ad61bb92076823cbc4a..7349c6cb28c0b63896be7ee00fcef61ffc553387 100644 (file)
@@ -130,8 +130,8 @@ static MonoAotModuleInfoTable *aot_modules = NULL;
 static const MonoRuntimeInfo supported_runtimes[] = {
        {"v2.0.50215","2.0", { {2,0,0,0},    {8,0,0,0} }        },
        {"v2.0.50727","2.0", { {2,0,0,0},    {8,0,0,0} }        },
-       {"v4.0.21006","4.0", { {4,0,0,0},    {10,0,0,0} }   },
        {"v4.0.30128","4.0", { {4,0,0,0},    {10,0,0,0} }   },
+       {"v4.0.30319","4.0", { {4,0,0,0},    {10,0,0,0} }   },
        {"moonlight", "2.1", { {2,0,5,0},    {9,0,0,0} }    },
 };
 
@@ -433,6 +433,9 @@ mono_jit_info_table_find (MonoDomain *domain, char *addr)
        } while (chunk_pos < table->num_chunks);
 
  not_found:
+       if (!hp)
+               return NULL;
+
        mono_hazard_pointer_clear (hp, JIT_INFO_TABLE_HAZARD_INDEX);
        mono_hazard_pointer_clear (hp, JIT_INFO_HAZARD_INDEX);
 
@@ -1020,7 +1023,19 @@ mono_jit_info_set_generic_sharing_context (MonoJitInfo *ji, MonoGenericSharingCo
 
        gi->generic_sharing_context = gsctx;
 }
+
+MonoTryBlockHoleTableJitInfo*
+mono_jit_info_get_try_block_hole_table_info (MonoJitInfo *ji)
+{
+       if (ji->has_try_block_holes) {
+               char *ptr = (char*)&ji->clauses [ji->num_clauses];
+               if (ji->has_generic_jit_info)
+                       ptr += sizeof (MonoGenericJitInfo);
+               return (MonoTryBlockHoleTableJitInfo*)ptr;
+       } else {
+               return NULL;
+       }
+}
 void
 mono_install_create_domain_hook (MonoCreateDomainFunc func)
 {
index d723b806de7b24286e303f79eacb5ac02a6961aa..7e12b63b824e1abdf55b4558943e3584e8468336 100644 (file)
@@ -684,6 +684,18 @@ mono_get_exception_field_access (void)
        return mono_exception_from_name (mono_get_corlib (), "System", "FieldAccessException");
 }
 
+/**
+ * mono_get_exception_field_access2:
+ * @msg: an informative message for the user.
+ *
+ * Returns: a new instance of the System.FieldAccessException
+ */
+MonoException *
+mono_get_exception_field_access_msg (const char *msg)
+{
+       return mono_exception_from_name_msg (mono_get_corlib (), "System", "FieldAccessException", msg);
+}
+
 /**
  * mono_get_exception_method_access:
  *
@@ -695,6 +707,18 @@ mono_get_exception_method_access (void)
        return mono_exception_from_name (mono_get_corlib (), "System", "MethodAccessException");
 }
 
+/**
+ * mono_get_exception_method_access2:
+ * @msg: an informative message for the user.
+ *
+ * Returns: a new instance of the System.MethodAccessException
+ */
+MonoException *
+mono_get_exception_method_access_msg (const char *msg)
+{
+       return mono_exception_from_name_msg (mono_get_corlib (), "System", "MethodAccessException", msg);
+}
+
 /**
  * mono_get_exception_reflection_type_load:
  * @types: an array of types that were defined in the moduled loaded.
index ff67e997f05b4b633775601e9450477a4091854f..1ee2d20efc1f58808db5f1acbd6b5df3cd81357b 100644 (file)
@@ -715,6 +715,7 @@ ves_icall_System_IO_MonoIO_GetFileStat (MonoString *path, MonoIOStat *stat,
                                                   stat);
        } else {
                *error=GetLastError ();
+               memset (stat, 0, sizeof (MonoIOStat));
        }
 
        return result;
index 10b94338ffabf3ad7c6473fb54fcf763072ee20a..f97576280111f29d80bd26c9ed1e71eeda882556 100644 (file)
@@ -83,13 +83,13 @@ void* mono_gc_make_descr_from_bitmap (gsize *bitmap, int numbits) MONO_INTERNAL;
 /* User defined marking function */
 /* It should work like this:
  * foreach (ref in GC references in the are structure pointed to by ADDR)
- *    *ref = mark_func (*ref)
+ *    mark_func (ref)
  */
-typedef void *(*MonoGCCopyFunc) (void *addr);
-typedef void (*MonoGCMarkFunc) (void *addr, MonoGCCopyFunc mark_func);
+typedef void (*MonoGCMarkFunc)     (void **addr);
+typedef void (*MonoGCRootMarkFunc) (void *addr, MonoGCMarkFunc mark_func);
 
 /* Create a descriptor with a user defined marking function */
-void *mono_gc_make_root_descr_user (MonoGCMarkFunc marker);
+void *mono_gc_make_root_descr_user (MonoGCRootMarkFunc marker);
 
 /* desc is the result from mono_gc_make_descr*. A NULL value means
  * all the words might contain GC pointers.
@@ -112,8 +112,8 @@ void     mono_gc_finalize_notify    (void) MONO_INTERNAL;
 
 void* mono_gc_alloc_pinned_obj (MonoVTable *vtable, size_t size) MONO_INTERNAL;
 void* mono_gc_alloc_obj (MonoVTable *vtable, size_t size) MONO_INTERNAL;
-void* mono_gc_alloc_vector (MonoVTable *vtable, size_t size, mono_array_size_t max_length) MONO_INTERNAL;
-void* mono_gc_alloc_array (MonoVTable *vtable, size_t size, mono_array_size_t max_length, mono_array_size_t bounds_size) MONO_INTERNAL;
+void* mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length) MONO_INTERNAL;
+void* mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uintptr_t bounds_size) MONO_INTERNAL;
 void* mono_gc_alloc_string (MonoVTable *vtable, size_t size, gint32 len) MONO_INTERNAL;
 void* mono_gc_make_descr_for_string (gsize *bitmap, int numbits) MONO_INTERNAL;
 void* mono_gc_make_descr_for_object (gsize *bitmap, int numbits, size_t obj_size) MONO_INTERNAL;
@@ -214,6 +214,10 @@ gsize* mono_gc_get_bitmap_for_descr (void *descr, int *numbits) MONO_INTERNAL;
    or -1 if not applicable. */
 int mono_gc_get_suspend_signal (void) MONO_INTERNAL;
 
+typedef void* (*MonoGCLockedCallbackFunc) (void *data);
+
+void* mono_gc_invoke_with_gc_lock (MonoGCLockedCallbackFunc func, void *data) MONO_INTERNAL;
+
 #ifdef HAVE_SGEN_GC
 int mono_gc_get_los_limit (void) MONO_INTERNAL;
 #endif
index 55d304a1fddd921e1587abcb01467ee6d661707a..16c43472e513ed8dd88ccb7b993b843030d48497 100644 (file)
@@ -47,7 +47,6 @@ ICALL(COMPROX_2, "FindProxy", ves_icall_Mono_Interop_ComInteropProxy_FindProxy)
 
 ICALL_TYPE(RUNTIME, "Mono.Runtime", RUNTIME_1)
 ICALL(RUNTIME_1, "GetDisplayName", ves_icall_Mono_Runtime_GetDisplayName)
-ICALL(RUNTIME_2, "NewObject", ves_icall_Mono_Runtime_NewObject)
 
 #ifndef PLATFORM_RO_FS
 ICALL_TYPE(KPAIR, "Mono.Security.Cryptography.KeyPairPersistence", KPAIR_1)
@@ -779,9 +778,10 @@ ICALL(SECSTRING_2, "EncryptInternal", ves_icall_System_Security_SecureString_Enc
 ICALL_TYPE(SECMAN, "System.Security.SecurityManager", SECMAN_1)
 ICALL(SECMAN_1, "GetLinkDemandSecurity", ves_icall_System_Security_SecurityManager_GetLinkDemandSecurity)
 ICALL(SECMAN_2, "get_CheckExecutionRights", ves_icall_System_Security_SecurityManager_get_CheckExecutionRights)
-ICALL(SECMAN_3, "get_SecurityEnabled", ves_icall_System_Security_SecurityManager_get_SecurityEnabled)
-ICALL(SECMAN_4, "set_CheckExecutionRights", ves_icall_System_Security_SecurityManager_set_CheckExecutionRights)
-ICALL(SECMAN_5, "set_SecurityEnabled", ves_icall_System_Security_SecurityManager_set_SecurityEnabled)
+ICALL(SECMAN_3, "get_RequiresElevatedPermissions", mono_security_core_clr_require_elevated_permissions)
+ICALL(SECMAN_4, "get_SecurityEnabled", ves_icall_System_Security_SecurityManager_get_SecurityEnabled)
+ICALL(SECMAN_5, "set_CheckExecutionRights", ves_icall_System_Security_SecurityManager_set_CheckExecutionRights)
+ICALL(SECMAN_6, "set_SecurityEnabled", ves_icall_System_Security_SecurityManager_set_SecurityEnabled)
 
 ICALL_TYPE(STRING, "System.String", STRING_1)
 ICALL(STRING_1, ".ctor(char*)", ves_icall_System_String_ctor_RedirectToCreateString)
@@ -915,6 +915,7 @@ ICALL(THREADP_2, "GetMaxThreads", ves_icall_System_Threading_ThreadPool_GetMaxTh
 ICALL(THREADP_3, "GetMinThreads", ves_icall_System_Threading_ThreadPool_GetMinThreads)
 ICALL(THREADP_35, "SetMaxThreads", ves_icall_System_Threading_ThreadPool_SetMaxThreads)
 ICALL(THREADP_4, "SetMinThreads", ves_icall_System_Threading_ThreadPool_SetMinThreads)
+ICALL(THREADP_5, "pool_queue", icall_append_job)
 
 ICALL_TYPE(WAITH, "System.Threading.WaitHandle", WAITH_1)
 ICALL(WAITH_1, "SignalAndWait_Internal", ves_icall_System_Threading_WaitHandle_SignalAndWait_Internal)
index d1f2bb0806f481647c130c7795941c23bc48031d..37dcfa503161b6c73a4b790ae911fd9c1f47643b 100644 (file)
@@ -559,7 +559,7 @@ ves_icall_System_Array_CreateInstanceImpl (MonoReflectionType *type, MonoArray *
 {
        MonoClass *aklass;
        MonoArray *array;
-       mono_array_size_t *sizes, i;
+       uintptr_t *sizes, i;
        gboolean bounded = FALSE;
 
        MONO_ARCH_SAVE_REGS;
@@ -583,7 +583,7 @@ ves_icall_System_Array_CreateInstanceImpl (MonoReflectionType *type, MonoArray *
 
        aklass = mono_bounded_array_class_get (mono_class_from_mono_type (type->type), mono_array_length (lengths), bounded);
 
-       sizes = alloca (aklass->rank * sizeof(mono_array_size_t) * 2);
+       sizes = alloca (aklass->rank * sizeof(intptr_t) * 2);
        for (i = 0; i < aklass->rank; ++i) {
                sizes [i] = mono_array_get (lengths, guint32, i);
                if (bounds)
@@ -592,7 +592,7 @@ ves_icall_System_Array_CreateInstanceImpl (MonoReflectionType *type, MonoArray *
                        sizes [i + aklass->rank] = 0;
        }
 
-       array = mono_array_new_full (mono_object_domain (type), aklass, sizes, sizes + aklass->rank);
+       array = mono_array_new_full (mono_object_domain (type), aklass, sizes, (intptr_t*)sizes + aklass->rank);
 
        return array;
 }
@@ -602,7 +602,7 @@ ves_icall_System_Array_CreateInstanceImpl64 (MonoReflectionType *type, MonoArray
 {
        MonoClass *aklass;
        MonoArray *array;
-       mono_array_size_t *sizes, i;
+       uintptr_t *sizes, i;
        gboolean bounded = FALSE;
 
        MONO_ARCH_SAVE_REGS;
@@ -627,7 +627,7 @@ ves_icall_System_Array_CreateInstanceImpl64 (MonoReflectionType *type, MonoArray
 
        aklass = mono_bounded_array_class_get (mono_class_from_mono_type (type->type), mono_array_length (lengths), bounded);
 
-       sizes = alloca (aklass->rank * sizeof(mono_array_size_t) * 2);
+       sizes = alloca (aklass->rank * sizeof(intptr_t) * 2);
        for (i = 0; i < aklass->rank; ++i) {
                sizes [i] = mono_array_get (lengths, guint64, i);
                if (bounds)
@@ -636,7 +636,7 @@ ves_icall_System_Array_CreateInstanceImpl64 (MonoReflectionType *type, MonoArray
                        sizes [i + aklass->rank] = 0;
        }
 
-       array = mono_array_new_full (mono_object_domain (type), aklass, sizes, sizes + aklass->rank);
+       array = mono_array_new_full (mono_object_domain (type), aklass, sizes, (intptr_t*)sizes + aklass->rank);
 
        return array;
 }
@@ -653,7 +653,7 @@ static gint32
 ves_icall_System_Array_GetLength (MonoArray *this, gint32 dimension)
 {
        gint32 rank = ((MonoObject *)this)->vtable->klass->rank;
-       mono_array_size_t length;
+       uintptr_t length;
 
        MONO_ARCH_SAVE_REGS;
 
@@ -1569,6 +1569,23 @@ ves_icall_type_is_subtype_of (MonoReflectionType *type, MonoReflectionType *c, M
        return mono_class_is_subclass_of (klass, klassc, check_interfaces);
 }
 
+static gboolean
+mono_type_is_primitive (MonoType *type)
+{
+       return (type->type >= MONO_TYPE_BOOLEAN && type->type <= MONO_TYPE_R8) ||
+                       type-> type == MONO_TYPE_I || type->type == MONO_TYPE_U;
+}
+
+static MonoType*
+mono_type_get_underlying_type_ignore_byref (MonoType *type)
+{
+       if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
+               return mono_class_enum_basetype (type->data.klass);
+       if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
+               return mono_class_enum_basetype (type->data.generic_class->container_class);
+       return type;
+}
+
 static guint32
 ves_icall_type_is_assignable_from (MonoReflectionType *type, MonoReflectionType *c)
 {
@@ -1585,9 +1602,31 @@ ves_icall_type_is_assignable_from (MonoReflectionType *type, MonoReflectionType
        klass = mono_class_from_mono_type (type->type);
        klassc = mono_class_from_mono_type (c->type);
 
-       if (type->type->byref && !c->type->byref)
+       if (type->type->byref c->type->byref)
                return FALSE;
 
+       if (type->type->byref) {
+               MonoType *t = mono_type_get_underlying_type_ignore_byref (type->type);
+               MonoType *ot = mono_type_get_underlying_type_ignore_byref (c->type);
+
+               klass = mono_class_from_mono_type (t);
+               klassc = mono_class_from_mono_type (ot);
+
+               if (mono_type_is_primitive (t)) {
+                       return mono_type_is_primitive (ot) && klass->instance_size == klassc->instance_size;
+               } else if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR) {
+                       return t->type == ot->type && t->data.generic_param->num == ot->data.generic_param->num;
+               } else if (t->type == MONO_TYPE_PTR || t->type == MONO_TYPE_FNPTR) {
+                       return t->type == ot->type;
+               } else {
+                        if (ot->type == MONO_TYPE_VAR || ot->type == MONO_TYPE_MVAR)
+                                return FALSE;
+
+                        if (klass->valuetype)
+                               return klass == klassc;
+                       return klass->valuetype == klassc->valuetype;
+               }
+       }
        return mono_class_is_assignable_from (klass, klassc);
 }
 
@@ -1749,129 +1788,18 @@ ves_icall_MonoField_GetParentType (MonoReflectionField *field, MonoBoolean decla
 static MonoObject *
 ves_icall_MonoField_GetValueInternal (MonoReflectionField *field, MonoObject *obj)
 {      
-       MonoObject *o;
+       MonoClass *fklass = field->klass;
        MonoClassField *cf = field->field;
-       MonoClass *klass;
-       MonoVTable *vtable;
-       MonoType *t;
-       MonoDomain *domain = mono_object_domain (field); 
-       gchar *v;
-       gboolean is_static = FALSE;
-       gboolean is_ref = FALSE;
-
-       MONO_ARCH_SAVE_REGS;
+       MonoDomain *domain = mono_object_domain (field);
 
-       if (field->klass->image->assembly->ref_only)
+       if (fklass->image->assembly->ref_only)
                mono_raise_exception (mono_get_exception_invalid_operation (
                                        "It is illegal to get the value on a field on a type loaded using the ReflectionOnly methods."));
-       
+
        if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
                mono_security_core_clr_ensure_reflection_access_field (cf);
 
-       mono_class_init (field->klass);
-
-       if (cf->type->attrs & FIELD_ATTRIBUTE_STATIC)
-               is_static = TRUE;
-
-       if (obj && !is_static) {
-               /* Check that the field belongs to the object */
-               gboolean found = FALSE;
-               MonoClass *k;
-
-               for (k = obj->vtable->klass; k; k = k->parent) {
-                       if (k == cf->parent) {
-                               found = TRUE;
-                               break;
-                       }
-               }
-
-               if (!found) {
-                       char *msg = g_strdup_printf ("Field '%s' defined on type '%s' is not a field on the target object which is of type '%s'.", mono_field_get_name (cf), cf->parent->name, obj->vtable->klass->name);
-                       MonoException *ex = mono_get_exception_argument (NULL, msg);
-                       g_free (msg);
-                       mono_raise_exception (ex);
-               }
-       }
-
-       t = mono_type_get_underlying_type (cf->type);
-       switch (t->type) {
-       case MONO_TYPE_STRING:
-       case MONO_TYPE_OBJECT:
-       case MONO_TYPE_CLASS:
-       case MONO_TYPE_ARRAY:
-       case MONO_TYPE_SZARRAY:
-               is_ref = TRUE;
-               break;
-       case MONO_TYPE_U1:
-       case MONO_TYPE_I1:
-       case MONO_TYPE_BOOLEAN:
-       case MONO_TYPE_U2:
-       case MONO_TYPE_I2:
-       case MONO_TYPE_CHAR:
-       case MONO_TYPE_U:
-       case MONO_TYPE_I:
-       case MONO_TYPE_U4:
-       case MONO_TYPE_I4:
-       case MONO_TYPE_R4:
-       case MONO_TYPE_U8:
-       case MONO_TYPE_I8:
-       case MONO_TYPE_R8:
-       case MONO_TYPE_VALUETYPE:
-               is_ref = t->byref;
-               break;
-       case MONO_TYPE_GENERICINST:
-               if (mono_type_generic_inst_is_valuetype (t)) {
-                       is_ref = t->byref;
-               } else {
-                       is_ref = TRUE;
-               }
-               break;
-       default:
-               g_error ("type 0x%x not handled in "
-                        "ves_icall_Monofield_GetValue", t->type);
-               return NULL;
-       }
-
-       vtable = NULL;
-       if (is_static) {
-               vtable = mono_class_vtable_full (domain, cf->parent, TRUE);
-               if (!vtable->initialized && !(cf->type->attrs & FIELD_ATTRIBUTE_LITERAL))
-                       mono_runtime_class_init (vtable);
-       }
-       
-       if (is_ref) {
-               if (is_static) {
-                       mono_field_static_get_value (vtable, cf, &o);
-               } else {
-                       mono_field_get_value (obj, cf, &o);
-               }
-               return o;
-       }
-
-       if (mono_class_is_nullable (mono_class_from_mono_type (cf->type))) {
-               MonoClass *nklass = mono_class_from_mono_type (cf->type);
-               guint8 *buf;
-
-               /* Convert the Nullable structure into a boxed vtype */
-               if (is_static)
-                       buf = (guint8*)vtable->data + cf->offset;
-               else
-                       buf = (guint8*)obj + cf->offset;
-
-               return mono_nullable_box (buf, nklass);
-       }
-
-       /* boxed value type */
-       klass = mono_class_from_mono_type (cf->type);
-       o = mono_object_new (domain, klass);
-       v = ((gchar *) o) + sizeof (MonoObject);
-       if (is_static) {
-               mono_field_static_get_value (vtable, cf, v);
-       } else {
-               mono_field_get_value (obj, cf, v);
-       }
-
-       return o;
+       return mono_field_get_value_object (domain, cf, obj);
 }
 
 static void
@@ -2821,6 +2749,11 @@ ves_icall_InternalInvoke (MonoReflectionMethod *method, MonoObject *this, MonoAr
                mono_security_core_clr_ensure_reflection_access_method (m);
 
        if (!(m->flags & METHOD_ATTRIBUTE_STATIC)) {
+               if (!mono_class_vtable_full (mono_object_domain (method), m->klass, FALSE)) {
+                       mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_class_get_exception_for_failure (m->klass));
+                       return NULL;
+               }
+
                if (this) {
                        if (!mono_object_isinst (this, m->klass)) {
                                mono_gc_wbarrier_generic_store (exc, (MonoObject*) mono_exception_from_name_msg (mono_defaults.corlib, "System.Reflection", "TargetException", "Object does not match target type."));
@@ -2854,12 +2787,13 @@ ves_icall_InternalInvoke (MonoReflectionMethod *method, MonoObject *this, MonoAr
        
        if (m->klass->rank && !strcmp (m->name, ".ctor")) {
                int i;
-               mono_array_size_t *lengths;
-               mono_array_size_t *lower_bounds;
+               uintptr_t *lengths;
+               intptr_t *lower_bounds;
                pcount = mono_array_length (params);
-               lengths = alloca (sizeof (mono_array_size_t) * pcount);
+               lengths = alloca (sizeof (uintptr_t) * pcount);
+               /* Note: the synthetized array .ctors have int32 as argument type */
                for (i = 0; i < pcount; ++i)
-                       lengths [i] = *(mono_array_size_t*) ((char*)mono_array_get (params, gpointer, i) + sizeof (MonoObject));
+                       lengths [i] = *(int32_t*) ((char*)mono_array_get (params, gpointer, i) + sizeof (MonoObject));
 
                if (m->klass->rank == pcount) {
                        /* Only lengths provided. */
@@ -2867,7 +2801,7 @@ ves_icall_InternalInvoke (MonoReflectionMethod *method, MonoObject *this, MonoAr
                } else {
                        g_assert (pcount == (m->klass->rank * 2));
                        /* lower bounds are first. */
-                       lower_bounds = lengths;
+                       lower_bounds = (intptr_t*)lengths;
                        lengths += m->klass->rank;
                }
 
@@ -3070,6 +3004,7 @@ ves_icall_System_Enum_ToObject (MonoReflectionType *enumType, MonoObject *value)
        MonoDomain *domain; 
        MonoClass *enumc, *objc;
        MonoObject *res;
+       MonoType *etype;
        guint64 val;
        
        MONO_ARCH_SAVE_REGS;
@@ -3086,9 +3021,14 @@ ves_icall_System_Enum_ToObject (MonoReflectionType *enumType, MonoObject *value)
        if (!((objc->enumtype) || (objc->byval_arg.type >= MONO_TYPE_I1 && objc->byval_arg.type <= MONO_TYPE_U8)))
                mono_raise_exception (mono_get_exception_argument ("value", "The value passed in must be an enum base or an underlying type for an enum, such as an Int32."));
 
+       etype = mono_class_enum_basetype (enumc);
+       if (!etype)
+               /* MS throws this for typebuilders */
+               mono_raise_exception (mono_get_exception_argument ("Type must be a type provided by the runtime.", "enumType"));
+
        res = mono_object_new (domain, enumc);
        val = read_enum_value ((char *)value + sizeof (MonoObject), objc->enumtype? mono_class_enum_basetype (objc)->type: objc->byval_arg.type);
-       write_enum_value ((char *)res + sizeof (MonoObject), mono_class_enum_basetype (enumc)->type, val);
+       write_enum_value ((char *)res + sizeof (MonoObject), etype->type, val);
 
        return res;
 }
@@ -3123,9 +3063,16 @@ ves_icall_System_Enum_get_value (MonoObject *this)
 static MonoReflectionType *
 ves_icall_System_Enum_get_underlying_type (MonoReflectionType *type)
 {
+       MonoType *etype;
+
        MONO_ARCH_SAVE_REGS;
 
-       return mono_type_get_object (mono_object_domain (type), mono_class_enum_basetype (mono_class_from_mono_type (type->type)));
+       etype = mono_class_enum_basetype (mono_class_from_mono_type (type->type));
+       if (!etype)
+               /* MS throws this for typebuilders */
+               mono_raise_exception (mono_get_exception_argument ("Type must be a type provided by the runtime.", "enumType"));
+
+       return mono_type_get_object (mono_object_domain (type), etype);
 }
 
 static int
@@ -6455,6 +6402,9 @@ ves_icall_System_Environment_Exit (int result)
 
        mono_runtime_set_shutting_down ();
 
+       /* This will kill the tp threads which cannot be suspended */
+       mono_thread_pool_cleanup ();
+
        /* Suspend all managed threads since the runtime is going away */
        mono_thread_suspend_all_other_threads ();
 
@@ -7387,12 +7337,6 @@ ves_icall_Mono_Runtime_GetDisplayName (void)
        return display_name;
 }
 
-static MonoObject *
-ves_icall_Mono_Runtime_NewObject (MonoType *t)
-{
-       return mono_object_new (mono_domain_get (), mono_class_from_mono_type (t));
-}
-
 static MonoString*
 ves_icall_System_ComponentModel_Win32Exception_W32ErrorMessage (guint32 code)
 {
index e08e19c81e2e2560fb33b73a11bcfd72a24d3525..8279931397fc3d7c5a0862e27d4abd5ce054cb97 100644 (file)
@@ -705,22 +705,28 @@ find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSig
 }
 
 static MonoMethodSignature*
-inflate_generic_signature (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context)
+inflate_generic_signature_checked (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
 {
        MonoMethodSignature *res;
        gboolean is_open;
        int i;
 
+       mono_error_init (error);
        if (!context)
                return sig;
 
        res = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)sig->param_count) * sizeof (MonoType*));
        res->param_count = sig->param_count;
        res->sentinelpos = -1;
-       res->ret = mono_class_inflate_generic_type (sig->ret, context);
+       res->ret = mono_class_inflate_generic_type_checked (sig->ret, context, error);
+       if (!mono_error_ok (error))
+               goto fail;
        is_open = mono_class_is_open_constructed_type (res->ret);
        for (i = 0; i < sig->param_count; ++i) {
-               res->params [i] = mono_class_inflate_generic_type (sig->params [i], context);
+               res->params [i] = mono_class_inflate_generic_type_checked (sig->params [i], context, error);
+               if (!mono_error_ok (error))
+                       goto fail;
+
                if (!is_open)
                        is_open = mono_class_is_open_constructed_type (res->params [i]);
        }
@@ -733,6 +739,25 @@ inflate_generic_signature (MonoImage *image, MonoMethodSignature *sig, MonoGener
        res->has_type_parameters = is_open;
        res->is_inflated = 1;
        return res;
+
+fail:
+       if (res->ret)
+               mono_metadata_free_type (res->ret);
+       for (i = 0; i < sig->param_count; ++i) {
+               if (res->params [i])
+                       mono_metadata_free_type (res->params [i]);
+       }
+       g_free (res);
+       return NULL;
+}
+
+static MonoMethodSignature*
+inflate_generic_signature (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context)
+{
+       MonoError error;
+       MonoMethodSignature *res = inflate_generic_signature_checked (image, sig, context, &error);
+       g_assert (mono_error_ok (&error)); /*FIXME move callers to use _checked version*/
+       return res;
 }
 
 static MonoMethodHeader*
@@ -824,10 +849,17 @@ mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 to
        }
 
        if (context) {
+               MonoError error;
                MonoMethodSignature *cached;
 
                /* This signature is not owned by a MonoMethod, so need to cache */
-               sig = inflate_generic_signature (image, sig, context);
+               sig = inflate_generic_signature_checked (image, sig, context, &error);
+               if (!mono_error_ok (&error)) {/*XXX bubble up this and kill one use of loader errors */
+                       mono_loader_set_error_bad_image (g_strdup_printf ("Could not inflate signature %s", mono_error_get_message (&error)));
+                       mono_error_cleanup (&error);
+                       return NULL;
+               }
+
                cached = mono_metadata_get_inflated_signature (sig, context);
                if (cached != sig)
                        mono_metadata_free_inflated_signature (sig);
@@ -1508,7 +1540,7 @@ mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
            (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
                result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
        else
-               result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodNormal));
+               result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethod));
 
        mono_stats.method_count ++;
 
@@ -1737,12 +1769,12 @@ mono_free_method  (MonoMethod *method)
                mono_image_property_remove (method->klass->image, method);
 
                g_free ((char*)method->name);
-               if (mw->method.header) {
-                       g_free ((char*)mw->method.header->code);
-                       for (i = 0; i < mw->method.header->num_locals; ++i)
-                               g_free (mw->method.header->locals [i]);
-                       g_free (mw->method.header->clauses);
-                       g_free (mw->method.header);
+               if (mw->header) {
+                       g_free ((char*)mw->header->code);
+                       for (i = 0; i < mw->header->num_locals; ++i)
+                               g_free (mw->header->locals [i]);
+                       g_free (mw->header->clauses);
+                       g_free (mw->header);
                }
                g_free (mw->method_data);
                g_free (method->signature);
@@ -1867,6 +1899,7 @@ mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
                        for (i = 0; i < signature->param_count + 1; ++i)
                                if (dyn_specs [i]) {
                                        mspecs [i] = g_new0 (MonoMarshalSpec, 1);
+                                       memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
                                        mspecs [i]->data.custom_data.custom_name = g_strdup (dyn_specs [i]->data.custom_data.custom_name);
                                        mspecs [i]->data.custom_data.cookie = g_strdup (dyn_specs [i]->data.custom_data.cookie);
                                }
@@ -2066,7 +2099,7 @@ mono_loader_lock_is_owned_by_self (void)
  * Return the signature of the method M. On failure, returns NULL, and ERR is set.
  */
 MonoMethodSignature*
-mono_method_signature_checked (MonoMethod *m, MonoError *err)
+mono_method_signature_checked (MonoMethod *m, MonoError *error)
 {
        int idx;
        int size;
@@ -2079,6 +2112,8 @@ mono_method_signature_checked (MonoMethod *m, MonoError *err)
 
        /* We need memory barriers below because of the double-checked locking pattern */ 
 
+       mono_error_init (error);
+
        if (m->signature)
                return m->signature;
 
@@ -2130,7 +2165,7 @@ mono_method_signature_checked (MonoMethod *m, MonoError *err)
                /*TODO we should cache the failure result somewhere*/
                if (!mono_verifier_verify_method_signature (img, sig_offset, NULL)) {
                        mono_loader_unlock ();
-                       mono_error_set_method_load (err, m->klass, m->name, "");
+                       mono_error_set_method_load (error, m->klass, m->name, "");
                        return NULL;
                }
 
@@ -2139,7 +2174,7 @@ mono_method_signature_checked (MonoMethod *m, MonoError *err)
                signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL);
                if (!signature) {
                        mono_loader_unlock ();
-                       mono_error_set_method_load (err, m->klass, m->name, "");
+                       mono_error_set_method_load (error, m->klass, m->name, "");
                        return NULL;
                }
 
@@ -2151,17 +2186,17 @@ mono_method_signature_checked (MonoMethod *m, MonoError *err)
        if (signature->generic_param_count) {
                if (!container || !container->is_method) {
                        mono_loader_unlock ();
-                       mono_error_set_method_load (err, m->klass, m->name, "Signature claims method has generic parameters, but generic_params table says it doesn't for method 0x%08x from image %s", idx, img->name);
+                       mono_error_set_method_load (error, m->klass, m->name, "Signature claims method has generic parameters, but generic_params table says it doesn't for method 0x%08x from image %s", idx, img->name);
                        return NULL;
                }
                if (container->type_argc != signature->generic_param_count) {
                        mono_loader_unlock ();
-                       mono_error_set_method_load (err, m->klass, m->name, "Inconsistent generic parameter count.  Signature says %d, generic_params table says %d for method 0x%08x from image %s", signature->generic_param_count, container->type_argc, idx, img->name);
+                       mono_error_set_method_load (error, m->klass, m->name, "Inconsistent generic parameter count.  Signature says %d, generic_params table says %d for method 0x%08x from image %s", signature->generic_param_count, container->type_argc, idx, img->name);
                        return NULL;
                }
        } else if (container && container->is_method && container->type_argc) {
                mono_loader_unlock ();
-               mono_error_set_method_load (err, m->klass, m->name, "generic_params table claims method has generic parameters, but signature says it doesn't for method 0x%08x from image %s", idx, img->name);
+               mono_error_set_method_load (error, m->klass, m->name, "generic_params table claims method has generic parameters, but signature says it doesn't for method 0x%08x from image %s", idx, img->name);
                return NULL;
        }
        if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
@@ -2192,7 +2227,7 @@ mono_method_signature_checked (MonoMethod *m, MonoError *err)
                case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
                default:
                        mono_loader_unlock ();
-                       mono_error_set_method_load (err, m->klass, m->name, "unsupported calling convention : 0x%04x for method 0x%08x from image %s", piinfo->piflags, idx, img->name);
+                       mono_error_set_method_load (error, m->klass, m->name, "unsupported calling convention : 0x%04x for method 0x%08x from image %s", piinfo->piflags, idx, img->name);
                        return NULL;
                }
                signature->call_convention = conv;
@@ -2213,15 +2248,13 @@ mono_method_signature_checked (MonoMethod *m, MonoError *err)
 MonoMethodSignature*
 mono_method_signature (MonoMethod *m)
 {
-       MonoError err;
+       MonoError error;
        MonoMethodSignature *sig;
 
-       mono_error_init (&err);
-
-       sig = mono_method_signature_checked (m, &err);
+       sig = mono_method_signature_checked (m, &error);
        if (!sig) {
-               g_warning ("Could not load signature due to: %s", mono_error_get_message (&err));
-               mono_error_cleanup (&err);
+               g_warning ("Could not load signature due to: %s", mono_error_get_message (&error));
+               mono_error_cleanup (&error);
        }
 
        return sig;
@@ -2252,40 +2285,39 @@ mono_method_get_header (MonoMethod *method)
        guint32 rva;
        MonoImage* img;
        gpointer loc;
-       MonoMethodNormal* mn = (MonoMethodNormal*) method;
        MonoMethodHeader *header;
 
        if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) || (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) || (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
                return NULL;
 
-#ifdef G_LIKELY
-       if (G_LIKELY (mn->header))
-#else
-       if (mn->header)
-#endif
-               return mn->header;
+       if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) {
+               MonoMethodWrapper *mw = (MonoMethodWrapper *)method;
+               g_assert (mw->header);
+               return mw->header;
+       }
 
        if (method->is_inflated) {
                MonoMethodInflated *imethod = (MonoMethodInflated *) method;
                MonoMethodHeader *header;
 
-               header = mono_method_get_header (imethod->declaring);
-
                mono_loader_lock ();
 
-               if (mn->header) {
+               if (imethod->header) {
                        mono_loader_unlock ();
-                       return mn->header;
+                       return imethod->header;
                }
 
-               mn->header = inflate_generic_header (header, mono_method_get_context (method));
+               header = mono_method_get_header (imethod->declaring);
+
+               imethod->header = inflate_generic_header (header, mono_method_get_context (method));
                mono_loader_unlock ();
-               return mn->header;
+               mono_metadata_free_mh (header);
+               return imethod->header;
        }
 
        /* 
-        * Do most of the work outside the loader lock, to avoid assembly loader hook
-        * deadlocks.
+        * We don't need locks here: the new header is allocated from malloc memory
+        * and is not stored anywhere in the runtime, the user needs to free it.
         */
        g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
        idx = mono_metadata_token_index (method->token);
@@ -2301,20 +2333,7 @@ mono_method_get_header (MonoMethod *method)
 
        header = mono_metadata_parse_mh_full (img, mono_method_get_generic_container (method), loc);
 
-       mono_loader_lock ();
-
-       if (mn->header) {
-               /* header is allocated from the image mempool, no need to free it */
-               mono_loader_unlock ();
-               return mn->header;
-       }
-
-       mono_memory_barrier ();
-
-       mn->header = header;
-
-       mono_loader_unlock ();
-       return mn->header;
+       return header;
 }
 
 guint32
index 928ce29026652761704311239dfa7c84fa1b7d43..e188ee4ae49a480b08034d7652af0868f61e2c5f 100644 (file)
 #include <mono/metadata/locales.h>
 #include <mono/metadata/culture-info.h>
 #include <mono/metadata/culture-info-tables.h>
-#include <mono/metadata/normalization-tables.h>
 
+#ifndef DISABLE_NORMALIZATION
+#include <mono/metadata/normalization-tables.h>
+#endif
 
 #include <locale.h>
 #if defined(__APPLE__)
@@ -381,11 +383,14 @@ get_posix_locale (void)
 static gchar*
 get_darwin_locale (void)
 {
-       const gchar *darwin_locale = NULL;
-       gchar *cur_locale = NULL;
-       int i;
+       static gchar *darwin_locale = NULL;
        CFLocaleRef locale = NULL;
        CFStringRef locale_cfstr = NULL;
+       CFIndex len;
+       int i;
+
+       if (darwin_locale != NULL)
+               return g_strdup (darwin_locale);
 
        locale = CFLocaleCopyCurrent ();
 
@@ -393,20 +398,24 @@ get_darwin_locale (void)
                locale_cfstr = CFLocaleGetIdentifier (locale);
 
                if (locale_cfstr) {
-                       darwin_locale = CFStringGetCStringPtr (locale_cfstr, kCFStringEncodingMacRoman);
-
-                       cur_locale = g_strdup (darwin_locale);
+                       len = CFStringGetMaximumSizeForEncoding (CFStringGetLength (locale_cfstr), kCFStringEncodingMacRoman) + 1;
+                       darwin_locale = (char *) malloc (len);
+                       if (!CFStringGetCString (locale_cfstr, darwin_locale, len, kCFStringEncodingMacRoman)) {
+                               free (darwin_locale);
+                               CFRelease (locale);
+                               darwin_locale = NULL;
+                               return NULL;
+                       }
 
-                       for (i = 0; i < strlen (cur_locale); i++)
-                               if (cur_locale [i] == '_')
-                                       cur_locale [i] = '-';
+                       for (i = 0; i < strlen (darwin_locale); i++)
+                               if (darwin_locale [i] == '_')
+                                       darwin_locale [i] = '-';
                }
 
-
                CFRelease (locale);
        }
 
-       return cur_locale;
+       return g_strdup (darwin_locale);
 }
 #endif
 
@@ -416,7 +425,7 @@ get_current_locale_name (void)
        gchar *locale;
        gchar *corrected = NULL;
        const gchar *p;
-        gchar *c;
+       gchar *c;
 
 #ifdef HOST_WIN32
        locale = g_win32_getlocale ();
@@ -972,12 +981,16 @@ void load_normalization_resource (guint8 **argProps,
                                  guint8 **argMapIdxToComposite,
                                  guint8 **argCombiningClass)
 {
+#ifdef DISABLE_NORMALIZATION
+       mono_raise_exception (mono_get_exception_not_supported ("This runtime has been compiled without string normalization support."));
+#else
        *argProps = (guint8*)props;
        *argMappedChars = (guint8*) mappedChars;
        *argCharMapIndex = (guint8*) charMapIndex;
        *argHelperIndex = (guint8*) helperIndex;
        *argMapIdxToComposite = (guint8*) mapIdxToComposite;
        *argCombiningClass = (guint8*)combiningClass;
+#endif
 }
 
 
index ff3c8bf4c34550f782bb79a16c9aa687e1b859cd..ab56fa8f937f129b2847a27d75247c55d23bcc01 100644 (file)
@@ -7631,11 +7631,11 @@ emit_marshal_boolean (EmitMarshalContext *m, int argnum, MonoType *t,
                
                /* Check null */
                if (t->byref) {
-                       
                        label_null = mono_mb_emit_branch (mb, CEE_BRFALSE);
                        mono_mb_emit_ldarg (mb, argnum);
                        mono_mb_emit_byte (mb, ldop);
-               }
+               } else
+                       label_null = 0;
 
                label_false = mono_mb_emit_branch (mb, CEE_BRFALSE);
                mono_mb_emit_byte (mb, CEE_LDC_I4_1);
@@ -8060,6 +8060,12 @@ mono_marshal_emit_native_wrapper (MonoImage *image, MonoMethodBuilder *mb, MonoM
        mono_mb_emit_byte (mb, CEE_RET);
 }
 
+G_GNUC_UNUSED static void
+code_for (MonoMethod *method) {
+       MonoMethodHeader *header = mono_method_get_header (method);
+       printf ("CODE FOR %s: \n%s.\n", mono_method_full_name (method, TRUE), mono_disasm_code (0, method, header->code, header->code + header->code_size));
+}
+
 /**
  * mono_marshal_get_native_wrapper:
  * @method: The MonoMethod to wrap.
@@ -8247,7 +8253,7 @@ mono_marshal_get_native_wrapper (MonoMethod *method, gboolean check_exceptions,
                        mono_metadata_free_marshal_spec (mspecs [i]);
        g_free (mspecs);
 
-       /* printf ("CODE FOR %s: \n%s.\n", mono_method_full_name (res, TRUE), mono_disasm_code (0, res, ((MonoMethodNormal*)res)->header->code, ((MonoMethodNormal*)res)->header->code + ((MonoMethodNormal*)res)->header->code_size)); */ 
+       /* code_for (res); */
 
        return res;
 }
@@ -8288,7 +8294,9 @@ mono_marshal_get_native_func_wrapper (MonoImage *image, MonoMethodSignature *sig
                                                                        mb, csig, csig->param_count + 16);
        mono_mb_free (mb);
 
-       /* printf ("CODE FOR %s: \n%s.\n", mono_method_full_name (res, TRUE), mono_disasm_code (0, res, ((MonoMethodNormal*)res)->header->code, ((MonoMethodNormal*)res)->header->code + ((MonoMethodNormal*)res)->header->code_size)); */ 
+       mono_marshal_set_wrapper_info (res, NULL);
+
+       /* code_for (res); */
 
        return res;
 }
@@ -8661,7 +8669,7 @@ mono_marshal_get_managed_wrapper (MonoMethod *method, MonoClass *delegate_klass,
                        mono_metadata_free_marshal_spec (mspecs [i]);
        g_free (mspecs);
 
-       /* printf ("CODE FOR %s: \n%s.\n", mono_method_full_name (res, TRUE), mono_disasm_code (0, res, ((MonoMethodNormal*)res)->header->code, ((MonoMethodNormal*)res)->header->code + ((MonoMethodNormal*)res)->header->code_size)); */
+       /* code_for (res); */
 
        return res;
 }
@@ -9296,7 +9304,7 @@ mono_marshal_get_unbox_wrapper (MonoMethod *method)
                                                                                 mb, sig, sig->param_count + 16);
        mono_mb_free (mb);
 
-       /* printf ("CODE FOR %s: \n%s.\n", mono_method_full_name (res, TRUE), mono_disasm_code (0, res, ((MonoMethodNormal*)res)->header->code, ((MonoMethodNormal*)res)->header->code + ((MonoMethodNormal*)res)->header->code_size)); */
+       /* code_for (res); */
 
        return res;     
 }
index e9a3df0dbf0521af37d1f6855184cdd07e7ca6f4..9fa06f0446ca323c5198aec79510381af9866f3d 100644 (file)
@@ -438,7 +438,8 @@ struct _MonoMethodHeader {
 #else
        guint32      code_size;
 #endif
-       guint16      max_stack;
+       guint16      max_stack   : 15;
+       unsigned int is_transient: 1; /* mono_metadata_free_mh () will actually free this header */
        unsigned int num_clauses : 15;
        /* if num_locals != 0, then the following apply: */
        unsigned int init_locals : 1;
@@ -686,5 +687,9 @@ void mono_image_load_names (MonoImage *image) MONO_INTERNAL;
 
 MonoImage *mono_image_open_raw (const char *fname, MonoImageOpenStatus *status) MONO_INTERNAL;
 
+MonoException *mono_get_exception_field_access_msg (const char *msg) MONO_INTERNAL;
+
+MonoException *mono_get_exception_method_access_msg (const char *msg) MONO_INTERNAL;
+
 #endif /* __MONO_METADATA_INTERNALS_H__ */
 
index e4ff0b7d53604d871e437e91ab25b44a539e7c79..78a7a533d6489a8ad12a27d8c91addc7e521e069 100644 (file)
@@ -858,11 +858,9 @@ verify_tables_schema (VerifyContext *ctx)
        guint32 count;
        int i;
 
-       //printf ("tables_area size %d offset %x %s\n", tables_area.size, tables_area.offset, ctx->image->name);
        if (tables_area.size < 24)
                ADD_ERROR (ctx, g_strdup_printf ("Table schemata size (%d) too small to for initial decoding (requires 24 bytes)", tables_area.size));
 
-       //printf ("ptr %x %x\n", ptr[4], ptr[5]);
        if (ptr [4] != 2 && ptr [4] != 1)
                ADD_ERROR (ctx, g_strdup_printf ("Invalid table schemata major version %d, expected 2", ptr [4]));
        if (ptr [5] != 0)
@@ -1121,7 +1119,7 @@ decode_value (const char *_ptr, unsigned available, unsigned *value, unsigned *s
 }
 
 static gboolean
-decode_signature_header (VerifyContext *ctx, guint32 offset, int *size, const char **first_byte)
+decode_signature_header (VerifyContext *ctx, guint32 offset, guint32 *size, const char **first_byte)
 {
        MonoStreamHeader blob = ctx->image->heap_blob;
        guint32 value, enc_size;
@@ -1132,14 +1130,16 @@ decode_signature_header (VerifyContext *ctx, guint32 offset, int *size, const ch
        if (!decode_value (blob.data + offset, blob.size - offset, &value, &enc_size))
                return FALSE;
 
-       if (offset + enc_size + value < offset)
+       if (CHECK_ADD4_OVERFLOW_UN (offset, enc_size))
                return FALSE;
 
-       if (offset + enc_size + value > blob.size)
+       offset += enc_size;
+
+       if (ADD_IS_GREATER_OR_OVF (offset, value, blob.size))
                return FALSE;
 
        *size = value;
-       *first_byte = blob.data + offset + enc_size;
+       *first_byte = blob.data + offset;
        return TRUE;
 }
 
@@ -1587,7 +1587,7 @@ parse_locals_signature (VerifyContext *ctx, const char **_ptr, const char *end)
 static gboolean
 is_valid_field_signature (VerifyContext *ctx, guint32 offset)
 {
-       int size = 0;
+       guint32 size = 0;
        unsigned signature = 0;
        const char *ptr = NULL, *end;
 
@@ -1608,7 +1608,7 @@ is_valid_field_signature (VerifyContext *ctx, guint32 offset)
 static gboolean
 is_valid_method_signature (VerifyContext *ctx, guint32 offset)
 {
-       int size = 0;
+       guint32 size = 0;
        const char *ptr = NULL, *end;
 
        if (!decode_signature_header (ctx, offset, &size, &ptr))
@@ -1621,7 +1621,7 @@ is_valid_method_signature (VerifyContext *ctx, guint32 offset)
 static gboolean
 is_valid_method_or_field_signature (VerifyContext *ctx, guint32 offset)
 {
-       int size = 0;
+       guint32 size = 0;
        unsigned signature = 0;
        const char *ptr = NULL, *end;
 
@@ -1640,9 +1640,9 @@ is_valid_method_or_field_signature (VerifyContext *ctx, guint32 offset)
 }
 
 static gboolean
-is_vald_cattr_blob (VerifyContext *ctx, guint32 offset)
+is_valid_cattr_blob (VerifyContext *ctx, guint32 offset)
 {
-       int size = 0;
+       guint32 size = 0;
        unsigned prolog = 0;
        const char *ptr = NULL, *end;
 
@@ -1658,7 +1658,324 @@ is_vald_cattr_blob (VerifyContext *ctx, guint32 offset)
 
        if (prolog != 1)
                FAIL (ctx, g_strdup_printf ("CustomAttribute: Prolog is 0x%x, expected 0x1", prolog));
-               
+
+       return TRUE;
+}
+
+static gboolean
+is_valid_cattr_type (MonoType *type)
+{
+       MonoClass *klass;
+
+       if (type->type == MONO_TYPE_OBJECT || (type->type >= MONO_TYPE_BOOLEAN && type->type <= MONO_TYPE_STRING))
+               return TRUE;
+
+       if (type->type == MONO_TYPE_VALUETYPE) {
+               klass = mono_class_from_mono_type (type);
+               return klass && klass->enumtype;
+       }
+
+       if (type->type == MONO_TYPE_CLASS)
+               return mono_class_from_mono_type (type) == mono_defaults.systemtype_class;
+
+       return FALSE;
+}
+
+static gboolean
+is_valid_ser_string_full (VerifyContext *ctx, const char **str_start, guint32 *str_len, const char **_ptr, const char *end)
+{
+       guint32 size = 0;
+       const char *ptr = *_ptr;
+
+       *str_start = NULL;
+       *str_len = 0;
+
+       if (ptr >= end)
+               FAIL (ctx, g_strdup ("CustomAttribute: Not enough room for string size"));
+
+       /*NULL string*/
+       if (*ptr == (char)0xFF) {
+               *_ptr = ptr + 1;
+               return TRUE;
+       }
+
+       if (!safe_read_cint (size, ptr, end))
+               FAIL (ctx, g_strdup ("CustomAttribute: Not enough room for string size"));
+
+       if (ADDP_IS_GREATER_OR_OVF (ptr, size, end))
+               FAIL (ctx, g_strdup ("CustomAttribute: Not enough room for string"));
+
+       *str_start = ptr;
+       *str_len = size;
+
+       *_ptr = ptr + size;
+       return TRUE;
+}
+
+static gboolean
+is_valid_ser_string (VerifyContext *ctx, const char **_ptr, const char *end)
+{
+       const char *dummy_str;
+       guint32 dummy_int;
+       return is_valid_ser_string_full (ctx, &dummy_str, &dummy_int, _ptr, end);
+}
+
+static MonoClass*
+get_enum_by_encoded_name (VerifyContext *ctx, const char **_ptr, const char *end)
+{
+       MonoType *type;
+       MonoClass *klass;
+       const char *str_start = NULL;
+       const char *ptr = *_ptr;
+       char *enum_name;
+       guint32 str_len = 0;
+
+       if (!is_valid_ser_string_full (ctx, &str_start, &str_len, &ptr, end))
+               return NULL;
+
+       /*NULL or empty string*/
+       if (str_start == NULL || str_len == 0) {
+               ADD_ERROR_NO_RETURN (ctx, g_strdup ("CustomAttribute: Null or empty enum name"));
+               return NULL;
+       }
+
+       enum_name = g_memdup (str_start, str_len + 1);
+       enum_name [str_len] = 0;
+       type = mono_reflection_type_from_name (enum_name, ctx->image);
+       if (!type) {
+               ADD_ERROR_NO_RETURN (ctx, g_strdup_printf ("CustomAttribute: Invalid enum class %s", enum_name));
+               g_free (enum_name);
+               return NULL;
+       }
+       g_free (enum_name);
+
+       klass = mono_class_from_mono_type (type);
+       if (!klass || !klass->enumtype) {
+               ADD_ERROR_NO_RETURN (ctx, g_strdup_printf ("CustomAttribute:Class %s::%s is not an enum", klass->name_space, klass->name));
+               return NULL;
+       }
+
+       *_ptr = ptr;
+       return klass;
+}
+
+static gboolean
+is_valid_fixed_param (VerifyContext *ctx, MonoType *mono_type, const char **_ptr, const char *end)
+{
+       MonoClass *klass;
+       const char *ptr = *_ptr;
+       int elem_size = 0;
+       guint32 element_count, i;
+       int type;
+
+       klass = mono_type->data.klass;
+       type = mono_type->type;
+
+handle_enum:
+       switch (type) {
+       case MONO_TYPE_BOOLEAN:
+       case MONO_TYPE_I1:
+       case MONO_TYPE_U1:
+               elem_size = 1;
+               break;
+       case MONO_TYPE_I2:
+       case MONO_TYPE_U2:
+       case MONO_TYPE_CHAR:
+               elem_size = 2;
+               break;
+       case MONO_TYPE_I4:
+       case MONO_TYPE_U4:
+       case MONO_TYPE_R4:
+               elem_size = 4;
+               break;
+       case MONO_TYPE_I8:
+       case MONO_TYPE_U8:
+       case MONO_TYPE_R8:
+               elem_size = 8;
+               break;
+
+       case MONO_TYPE_STRING:
+               *_ptr = ptr;
+               return is_valid_ser_string (ctx, _ptr, end);
+
+       case MONO_TYPE_OBJECT: {
+               unsigned sub_type = 0;
+               if (!safe_read8 (sub_type, ptr, end))
+                       FAIL (ctx, g_strdup ("CustomAttribute: Not enough room for array type"));
+
+               if (sub_type >= MONO_TYPE_BOOLEAN && sub_type <= MONO_TYPE_STRING) {
+                       type = sub_type;
+                       goto handle_enum;
+               }
+               if (sub_type == MONO_TYPE_ENUM) {
+                       klass = get_enum_by_encoded_name (ctx, &ptr, end);
+                       if (!klass)
+                               return FALSE;
+
+                       klass = klass->element_class;
+                       type = klass->byval_arg.type;
+                       goto handle_enum;
+               }
+               if (sub_type == 0x50) { /*Type*/
+                       *_ptr = ptr;
+                       return is_valid_ser_string (ctx, _ptr, end);
+               }
+               if (sub_type == MONO_TYPE_SZARRAY) {
+                       MonoType simple_type = {{0}};
+                       unsigned etype = 0;
+                       if (!safe_read8 (etype, ptr, end))
+                               FAIL (ctx, g_strdup ("CustomAttribute: Not enough room for array element type"));
+
+                       if (etype == MONO_TYPE_ENUM) {
+                               klass = get_enum_by_encoded_name (ctx, &ptr, end);
+                               if (!klass)
+                                       return FALSE;
+                       } else if ((etype >= MONO_TYPE_BOOLEAN && etype <= MONO_TYPE_STRING) || etype == 0x51) {
+                               simple_type.type = etype == 0x51 ? MONO_TYPE_OBJECT : etype;
+                               klass = mono_class_from_mono_type (&simple_type);
+                       } else
+                               FAIL (ctx, g_strdup_printf ("CustomAttribute: Invalid array element type %x", etype));
+
+                       type = MONO_TYPE_SZARRAY;
+                       goto handle_enum;
+               }
+               FAIL (ctx, g_strdup_printf ("CustomAttribute: Invalid boxed object type %x", sub_type));
+       }
+
+
+       case MONO_TYPE_CLASS:
+               if (klass != mono_defaults.systemtype_class)
+                       FAIL (ctx, g_strdup_printf ("CustomAttribute: Invalid class parameter type %s:%s ",klass->name_space, klass->name));
+               *_ptr = ptr;
+               return is_valid_ser_string (ctx, _ptr, end);
+
+       case MONO_TYPE_VALUETYPE:
+               if (!klass || !klass->enumtype)
+                       FAIL (ctx, g_strdup_printf ("CustomAttribute: Invalid valuetype parameter expected enum %s:%s ",klass->name_space, klass->name));
+
+               klass = klass->element_class;
+               type = klass->byval_arg.type;
+               goto handle_enum;
+
+       case MONO_TYPE_SZARRAY:
+               mono_type = &klass->byval_arg;
+               if (!is_valid_cattr_type (mono_type))
+                       FAIL (ctx, g_strdup_printf ("CustomAttribute: Invalid array element type %s:%s ",klass->name_space, klass->name));
+               if (!safe_read32 (element_count, ptr, end))
+                       FAIL (ctx, g_strdup_printf ("CustomAttribute: Invalid class parameter type %s:%s ",klass->name_space, klass->name));
+               if (element_count == 0xFFFFFFFFu) {
+                       *_ptr = ptr;
+                       return TRUE;
+               }
+               for (i = 0; i < element_count; ++i) {
+                       if (!is_valid_fixed_param (ctx, mono_type, &ptr, end))
+                               return FALSE;
+               }
+               *_ptr = ptr;
+               return TRUE;
+       default:
+               FAIL (ctx, g_strdup_printf ("CustomAttribute: Invalid parameter type %x ", type));
+       }
+
+       if (ADDP_IS_GREATER_OR_OVF (ptr, elem_size, end))
+               FAIL (ctx, g_strdup ("CustomAttribute: Not enough space for element"));
+       *_ptr = ptr + elem_size;
+       return TRUE;
+}
+
+static gboolean
+is_valid_cattr_content (VerifyContext *ctx, MonoMethod *ctor, const char *ptr, guint32 size)
+{
+       MonoError error;
+       unsigned prolog = 0;
+       const char *end;
+       MonoMethodSignature *sig;
+       int args, i;
+       unsigned num_named;
+
+       if (!ctor)
+               FAIL (ctx, g_strdup ("CustomAttribute: Invalid constructor"));
+
+       sig = mono_method_signature_checked (ctor, &error);
+       if (!mono_error_ok (&error)) {
+               ADD_ERROR_NO_RETURN (ctx, g_strdup_printf ("CustomAttribute: Invalid constructor signature %s", mono_error_get_message (&error)));
+               mono_error_cleanup (&error);
+               return FALSE;
+       }
+
+       if (sig->sentinelpos != -1 || sig->call_convention == MONO_CALL_VARARG)
+               FAIL (ctx, g_strdup ("CustomAttribute: Constructor cannot have VARAG signature"));
+
+       end = ptr + size;
+
+       if (!safe_read16 (prolog, ptr, end))
+               FAIL (ctx, g_strdup ("CustomAttribute: Not enough room for prolog"));
+
+       if (prolog != 1)
+               FAIL (ctx, g_strdup_printf ("CustomAttribute: Prolog is 0x%x, expected 0x1", prolog));
+
+       args = sig->param_count;
+       for (i = 0; i < args; ++i) {
+               MonoType *arg_type = sig->params [i];
+               if (!is_valid_fixed_param (ctx, arg_type, &ptr, end))
+                       return FALSE;
+       }
+
+       if (!safe_read16 (num_named, ptr, end))
+               FAIL (ctx, g_strdup ("CustomAttribute: Not enough space for num_named field"));
+
+       for (i = 0; i < num_named; ++i) {
+               MonoType *type, simple_type = {{0}};
+               unsigned kind;
+
+               if (!safe_read8 (kind, ptr, end))
+                       FAIL (ctx, g_strdup_printf ("CustomAttribute: Not enough space for named parameter %d kind", i));
+               if (kind != 0x53 && kind != 0x54)
+                       FAIL (ctx, g_strdup_printf ("CustomAttribute: Invalid named parameter %d kind %x", i, kind));
+               if (!safe_read8 (kind, ptr, end))
+                       FAIL (ctx, g_strdup_printf ("CustomAttribute: Not enough space for named parameter %d type", i));
+
+               if (kind >= MONO_TYPE_BOOLEAN && kind <= MONO_TYPE_STRING) {
+                       simple_type.type = kind;
+                       type = &simple_type;
+               } else if (kind == MONO_TYPE_ENUM) {
+                       MonoClass *klass = get_enum_by_encoded_name (ctx, &ptr, end);
+                       if (!klass)
+                               return FALSE;
+                       type = &klass->byval_arg;
+               } else if (kind == 0x50) {
+                       type = &mono_defaults.systemtype_class->byval_arg;
+               } else if (kind == 0x51) {
+                       type = &mono_defaults.object_class->byval_arg;
+               } else if (kind == MONO_TYPE_SZARRAY) {
+                       MonoClass *klass;
+                       unsigned etype = 0;
+                       if (!safe_read8 (etype, ptr, end))
+                               FAIL (ctx, g_strdup ("CustomAttribute: Not enough room for array element type"));
+
+                       if (etype == MONO_TYPE_ENUM) {
+                               klass = get_enum_by_encoded_name (ctx, &ptr, end);
+                               if (!klass)
+                                       return FALSE;
+                       } else if ((etype >= MONO_TYPE_BOOLEAN && etype <= MONO_TYPE_STRING) || etype == 0x51) {
+                               simple_type.type = etype == 0x51 ? MONO_TYPE_OBJECT : etype;
+                               klass = mono_class_from_mono_type (&simple_type);
+                       } else
+                               FAIL (ctx, g_strdup_printf ("CustomAttribute: Invalid array element type %x", etype));
+
+                       type = &mono_array_class_get (klass, 1)->byval_arg;
+               } else {
+                       FAIL (ctx, g_strdup_printf ("CustomAttribute: Invalid named parameter type %x", kind));
+               }
+
+               if (!is_valid_ser_string (ctx, &ptr, end))
+                       return FALSE;
+
+               if (!is_valid_fixed_param (ctx, type, &ptr, end))
+                       return FALSE;
+
+       }
+
        return TRUE;
 }
 
@@ -1681,7 +1998,7 @@ is_valid_permission_set (VerifyContext *ctx, guint32 offset)
 static gboolean
 is_valid_standalonesig_blob (VerifyContext *ctx, guint32 offset)
 {
-       int size = 0;
+       guint32 size = 0;
        unsigned signature = 0;
        const char *ptr = NULL, *end;
 
@@ -1695,13 +2012,18 @@ is_valid_standalonesig_blob (VerifyContext *ctx, guint32 offset)
        --ptr;
        if (signature == 0x07)
                return parse_locals_signature (ctx, &ptr, end);
+
+       /*F# and managed C++ produce standalonesig for fields even thou the spec doesn't mention it.*/
+       if (signature == 0x06)
+               return parse_field (ctx, &ptr, end);
+
        return parse_method_signature (ctx, &ptr, end, TRUE, TRUE);
 }
 
 static gboolean
 is_valid_property_sig_blob (VerifyContext *ctx, guint32 offset)
 {
-       int size = 0;
+       guint32 size = 0;
        const char *ptr = NULL, *end;
 
        if (!decode_signature_header (ctx, offset, &size, &ptr))
@@ -1714,11 +2036,10 @@ is_valid_property_sig_blob (VerifyContext *ctx, guint32 offset)
 static gboolean
 is_valid_typespec_blob (VerifyContext *ctx, guint32 offset)
 {
-       int size = 0;
+       guint32 size = 0;
        const char *ptr = NULL, *end;
        unsigned type = 0;
        
-
        if (!decode_signature_header (ctx, offset, &size, &ptr))
                FAIL (ctx, g_strdup ("TypeSpec: Could not decode signature header"));
        end = ptr + size;
@@ -1746,7 +2067,7 @@ is_valid_typespec_blob (VerifyContext *ctx, guint32 offset)
 static gboolean
 is_valid_methodspec_blob (VerifyContext *ctx, guint32 offset)
 {
-       int size = 0;
+       guint32 size = 0;
        const char *ptr = NULL, *end;
        unsigned type = 0;
        unsigned count = 0, i;
@@ -2106,8 +2427,10 @@ verify_typedef_table_full (VerifyContext *ctx)
                mono_metadata_decode_row (table, i, data, MONO_TYPEDEF_SIZE);
 
                if (i == 0) {
-                       if (data [MONO_TYPEDEF_EXTENDS] != 0)
+                       /*XXX it's ok if <module> extends object, or anything at all, actually. */
+                       /*if (data [MONO_TYPEDEF_EXTENDS] != 0)
                                ADD_ERROR (ctx, g_strdup_printf ("Invalid typedef row 0 for the special <module> type must have a null extend field"));
+                       */
                        continue;
                }
 
@@ -2213,8 +2536,8 @@ verify_field_table_full (VerifyContext *ctx)
        }
 }
 
-/*bits 6,8,9,10,11,13,14,15*/
-#define INVALID_METHOD_IMPLFLAG_BITS ((1 << 6) | (1 << 8) | (1 << 9) | (1 << 10) | (1 << 11) | (1 << 13) | (1 << 14) | (1 << 15))
+/*bits 8,9,10,11,13,14,15*/
+#define INVALID_METHOD_IMPLFLAG_BITS ((1 << 8) | (1 << 9) | (1 << 10) | (1 << 11) | (1 << 13) | (1 << 14) | (1 << 15))
 static void
 verify_method_table (VerifyContext *ctx)
 {
@@ -2551,14 +2874,36 @@ static void
 verify_cattr_table_full (VerifyContext *ctx)
 {
        MonoTableInfo *table = &ctx->image->tables [MONO_TABLE_CUSTOMATTRIBUTE];
-       guint32 data [MONO_CUSTOM_ATTR_SIZE];
+       MonoMethod *ctor;
+       const char *ptr;
+       guint32 data [MONO_CUSTOM_ATTR_SIZE], mtoken, size;
        int i;
 
        for (i = 0; i < table->rows; ++i) {
                mono_metadata_decode_row (table, i, data, MONO_CUSTOM_ATTR_SIZE);
 
-               if (!is_vald_cattr_blob (ctx, data [MONO_CUSTOM_ATTR_VALUE]))
+               if (!is_valid_cattr_blob (ctx, data [MONO_CUSTOM_ATTR_VALUE]))
                        ADD_ERROR (ctx, g_strdup_printf ("Invalid CustomAttribute row %d Value field 0x%08x", i, data [MONO_CUSTOM_ATTR_VALUE]));
+
+               mtoken = data [MONO_CUSTOM_ATTR_TYPE] >> MONO_CUSTOM_ATTR_TYPE_BITS;
+               switch (data [MONO_CUSTOM_ATTR_TYPE] & MONO_CUSTOM_ATTR_TYPE_MASK) {
+               case MONO_CUSTOM_ATTR_TYPE_METHODDEF:
+                       mtoken |= MONO_TOKEN_METHOD_DEF;
+                       break;
+               case MONO_CUSTOM_ATTR_TYPE_MEMBERREF:
+                       mtoken |= MONO_TOKEN_MEMBER_REF;
+                       break;
+               default:
+                       ADD_ERROR (ctx, g_strdup_printf ("Invalid CustomAttribute constructor row %d Token 0x%08x", i, data [MONO_CUSTOM_ATTR_TYPE]));
+               }
+
+               ctor = mono_get_method (ctx->image, mtoken, NULL);
+
+               /*This can't fail since this is checked in is_valid_cattr_blob*/
+               g_assert (decode_signature_header (ctx, data [MONO_CUSTOM_ATTR_VALUE], &size, &ptr));
+
+               if (!is_valid_cattr_content (ctx, ctor, ptr, size))
+                       ADD_ERROR (ctx, g_strdup_printf ("Invalid CustomAttribute content row %d Value field 0x%08x", i, data [MONO_CUSTOM_ATTR_VALUE]));
        }
 }
 
@@ -3721,6 +4066,38 @@ mono_verifier_verify_string_signature (MonoImage *image, guint32 offset, GSList
        return cleanup_context (&ctx, error_list);
 }
 
+gboolean
+mono_verifier_verify_cattr_blob (MonoImage *image, guint32 offset, GSList **error_list)
+{
+       VerifyContext ctx;
+
+       if (!mono_verifier_is_enabled_for_image (image))
+               return TRUE;
+
+       init_verify_context (&ctx, image, error_list);
+       ctx.stage = STAGE_TABLES;
+
+       is_valid_cattr_blob (&ctx, offset);
+
+       return cleanup_context (&ctx, error_list);
+}
+
+gboolean
+mono_verifier_verify_cattr_content (MonoImage *image, MonoMethod *ctor, const guchar *data, guint32 size, GSList **error_list)
+{
+       VerifyContext ctx;
+
+       if (!mono_verifier_is_enabled_for_image (image))
+               return TRUE;
+
+       init_verify_context (&ctx, image, error_list);
+       ctx.stage = STAGE_TABLES;
+
+       is_valid_cattr_content (&ctx, ctor, (const char*)data, size);
+
+       return cleanup_context (&ctx, error_list);
+}
+
 gboolean
 mono_verifier_is_sig_compatible (MonoImage *image, MonoMethod *method, MonoMethodSignature *signature)
 {
@@ -3822,6 +4199,18 @@ mono_verifier_verify_string_signature (MonoImage *image, guint32 offset, GSList
        return TRUE;
 }
 
+gboolean
+mono_verifier_verify_cattr_blob (MonoImage *image, guint32 offset, GSList **error_list)
+{
+       return TRUE;
+}
+
+gboolean
+mono_verifier_verify_cattr_content (MonoImage *image, MonoMethod *ctor, const guchar *data, guint32 size, GSList **error_list)
+{
+       return TRUE;
+}
+
 gboolean
 mono_verifier_is_sig_compatible (MonoImage *image, MonoMethod *method, MonoMethodSignature *signature)
 {
index bdeda849b494732926e1a2fa9fabc06037ee1ff6..4f1cfaf04154bc596df2b0c9703b7516a08239ec 100644 (file)
@@ -1504,7 +1504,7 @@ mono_metadata_cleanup (void)
  *
  * To parse a generic type, `generic_container' points to the current class'es
  * (the `generic_container' field in the MonoClass) or the current generic method's
- * (the `generic_container' field in the MonoMethodNormal) generic container.
+ * (stored in image->property_hash) generic container.
  * When we encounter any MONO_TYPE_VAR or MONO_TYPE_MVAR's, they're looked up in
  * this MonoGenericContainer.
  * This is a Mono runtime internal function.
@@ -2589,8 +2589,7 @@ free_inflated_method (MonoMethodInflated *imethod)
                mono_metadata_free_inflated_signature (method->signature);
 
        if (!((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) || (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) || (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))) {
-               MonoMethodNormal* mn = (MonoMethodNormal*) method;
-               MonoMethodHeader *header = mn->header;
+               MonoMethodHeader *header = imethod->header;
 
                if (header) {
                        /* Allocated in inflate_generic_header () */
@@ -3008,7 +3007,7 @@ select_container (MonoGenericContainer *gc, MonoTypeEnum type)
 
 /* 
  * mono_metadata_parse_generic_param:
- * @generic_container: Our MonoClass's or MonoMethodNormal's MonoGenericContainer;
+ * @generic_container: Our MonoClass's or MonoMethod's MonoGenericContainer;
  *                     see mono_metadata_parse_type_full() for details.
  * Internal routine to parse a generic type parameter.
  * LOCKING: Acquires the loader lock
@@ -3233,16 +3232,16 @@ hex_dump (const char *buffer, int base, int count)
 #endif
 
 /** 
- * @mh: The Method header
  * @ptr: Points to the beginning of the Section Data (25.3)
  */
-static void
-parse_section_data (MonoImage *m, MonoMethodHeader *mh, const unsigned char *ptr)
+static MonoExceptionClause*
+parse_section_data (MonoImage *m, int *num_clauses, const unsigned char *ptr)
 {
        unsigned char sect_data_flags;
        const unsigned char *sptr;
        int is_fat;
        guint32 sect_data_len;
+       MonoExceptionClause* clauses = NULL;
        
        while (1) {
                /* align on 32-bit boundary */
@@ -3269,11 +3268,11 @@ parse_section_data (MonoImage *m, MonoMethodHeader *mh, const unsigned char *ptr
                if (sect_data_flags & METHOD_HEADER_SECTION_EHTABLE) {
                        const unsigned char *p = dword_align (ptr);
                        int i;
-                       mh->num_clauses = is_fat ? sect_data_len / 24: sect_data_len / 12;
+                       *num_clauses = is_fat ? sect_data_len / 24: sect_data_len / 12;
                        /* we could just store a pointer if we don't need to byteswap */
-                       mh->clauses = mono_image_alloc0 (m, sizeof (MonoExceptionClause) * mh->num_clauses);
-                       for (i = 0; i < mh->num_clauses; ++i) {
-                               MonoExceptionClause *ec = &mh->clauses [i];
+                       clauses = g_malloc0 (sizeof (MonoExceptionClause) * (*num_clauses));
+                       for (i = 0; i < *num_clauses; ++i) {
+                               MonoExceptionClause *ec = &clauses [i];
                                guint32 tof_value;
                                if (is_fat) {
                                        ec->flags = read32 (p);
@@ -3306,7 +3305,7 @@ parse_section_data (MonoImage *m, MonoMethodHeader *mh, const unsigned char *ptr
                if (sect_data_flags & METHOD_HEADER_SECTION_MORE_SECTS)
                        ptr += sect_data_len - 4; /* LAMESPEC: it seems the size includes the header */
                else
-                       return;
+                       return clauses;
        }
 }
 
@@ -3339,8 +3338,8 @@ mono_method_get_header_summary (MonoMethod *method, MonoMethodHeaderSummary *sum
        if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) || (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) || (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
                return FALSE;
 
-       if (method->klass->image->dynamic || ((MonoMethodNormal*) method)->header) {
-               MonoMethodHeader *header = mono_method_get_header (method);
+       if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) {
+               MonoMethodHeader *header =  ((MonoMethodWrapper *)method)->header;
                if (!header)
                        return FALSE;
                summary->code_size = header->code_size;
@@ -3404,15 +3403,19 @@ mono_metadata_parse_mh_full (MonoImage *m, MonoGenericContainer *container, cons
        guint16 fat_flags;
        guint32 local_var_sig_tok, max_stack, code_size, init_locals;
        const unsigned char *code;
-       int hsize;
-       
+       MonoExceptionClause* clauses = NULL;
+       int hsize, num_clauses = 0;
+       MonoTableInfo *t = &m->tables [MONO_TABLE_STANDALONESIG];
+       guint32 cols [MONO_STAND_ALONE_SIGNATURE_SIZE];
+
        g_return_val_if_fail (ptr != NULL, NULL);
 
        switch (format) {
        case METHOD_HEADER_TINY_FORMAT:
-               mh = mono_image_alloc0 (m, MONO_SIZEOF_METHOD_HEADER);
+               mh = g_malloc0 (MONO_SIZEOF_METHOD_HEADER);
                ptr++;
                mh->max_stack = 8;
+               mh->is_transient = TRUE;
                local_var_sig_tok = 0;
                mh->code_size = flags >> 2;
                mh->code = (unsigned char*)ptr;
@@ -3446,17 +3449,21 @@ mono_metadata_parse_mh_full (MonoImage *m, MonoGenericContainer *container, cons
        default:
                return NULL;
        }
-                      
-       if (local_var_sig_tok) {
-               MonoTableInfo *t = &m->tables [MONO_TABLE_STANDALONESIG];
-               const char *locals_ptr;
-               guint32 cols [MONO_STAND_ALONE_SIGNATURE_SIZE];
-               int len=0, i, bsize;
 
-               mono_metadata_decode_row (t, (local_var_sig_tok & 0xffffff)-1, cols, 1);
+       if (local_var_sig_tok) {
+               int idx = (local_var_sig_tok & 0xffffff)-1;
+               if (idx >= t->rows)
+                       return NULL;
+               mono_metadata_decode_row (t, idx, cols, 1);
 
                if (!mono_verifier_verify_standalone_signature (m, cols [MONO_STAND_ALONE_SIGNATURE], NULL))
                        return NULL;
+       }
+       if (fat_flags & METHOD_HEADER_MORE_SECTS)
+               clauses = parse_section_data (m, &num_clauses, (const unsigned char*)ptr);
+       if (local_var_sig_tok) {
+               const char *locals_ptr;
+               int len=0, i, bsize;
 
                locals_ptr = mono_metadata_blob_heap (m, cols [MONO_STAND_ALONE_SIGNATURE]);
                bsize = mono_metadata_decode_blob_size (locals_ptr, &locals_ptr);
@@ -3464,24 +3471,31 @@ mono_metadata_parse_mh_full (MonoImage *m, MonoGenericContainer *container, cons
                        g_warning ("wrong signature for locals blob");
                locals_ptr++;
                len = mono_metadata_decode_value (locals_ptr, &locals_ptr);
-               mh = mono_image_alloc0 (m, MONO_SIZEOF_METHOD_HEADER + len * sizeof (MonoType*));
+               mh = g_malloc0 (MONO_SIZEOF_METHOD_HEADER + len * sizeof (MonoType*) + num_clauses * sizeof (MonoExceptionClause));
                mh->num_locals = len;
                for (i = 0; i < len; ++i) {
                        mh->locals [i] = mono_metadata_parse_type_full (
                                m, container, MONO_PARSE_LOCAL, 0, locals_ptr, &locals_ptr);
                        if (!mh->locals [i]) {
+                               g_free (clauses);
                                return NULL;
                        }
                }
        } else {
-               mh = mono_image_alloc0 (m, MONO_SIZEOF_METHOD_HEADER);
+               mh = g_malloc0 (MONO_SIZEOF_METHOD_HEADER + num_clauses * sizeof (MonoExceptionClause));
        }
        mh->code = code;
        mh->code_size = code_size;
        mh->max_stack = max_stack;
+       mh->is_transient = TRUE;
        mh->init_locals = init_locals;
-       if (fat_flags & METHOD_HEADER_MORE_SECTS)
-               parse_section_data (m, mh, (const unsigned char*)ptr);
+       if (clauses) {
+               MonoExceptionClause* clausesp = (MonoExceptionClause*)&mh->locals [mh->num_locals];
+               memcpy (clausesp, clauses, num_clauses * sizeof (MonoExceptionClause));
+               g_free (clauses);
+               mh->clauses = clausesp;
+               mh->num_clauses = num_clauses;
+       }
        return mh;
 }
 
@@ -3515,12 +3529,16 @@ mono_metadata_parse_mh (MonoImage *m, const char *ptr)
  * @mh: a method header
  *
  * Free the memory allocated for the method header.
- * This is a Mono runtime internal function.
  */
 void
 mono_metadata_free_mh (MonoMethodHeader *mh)
 {
-       /* Allocated from the mempool */
+       /* If it is not transient it means it's part of a wrapper method,
+        * or a SRE-generated method, so the lifetime in that case is
+        * dictated by the method's own lifetime
+        */
+       if (mh->is_transient)
+               g_free (mh);
 }
 
 /*
index 74b42a204e0695da6718cc55b505a8e26c8e676d..247c749bdedad87bad1932fc978dea8bb7f81eb9 100644 (file)
@@ -142,11 +142,12 @@ mono_mb_create_method (MonoMethodBuilder *mb, MonoMethodSignature *signature, in
        mono_loader_lock (); /*FIXME I think this lock can go.*/
        if (mb->dynamic) {
                method = mb->method;
+               mw = (MonoMethodWrapper*)method;
 
                method->name = mb->name;
                method->dynamic = TRUE;
 
-               ((MonoMethodNormal *)method)->header = header = (MonoMethodHeader *) 
+               mw->header = header = (MonoMethodHeader *) 
                        g_malloc0 (MONO_SIZEOF_METHOD_HEADER + mb->locals * sizeof (MonoType *));
 
                header->code = mb->code;
@@ -159,13 +160,14 @@ mono_mb_create_method (MonoMethodBuilder *mb, MonoMethodSignature *signature, in
 
                method = mono_image_alloc0 (image, sizeof (MonoMethodWrapper));
                memcpy (method, mb->method, sizeof (MonoMethodWrapper));
+               mw = (MonoMethodWrapper*) method;
 
                if (mb->no_dup_name)
                        method->name = mb->name;
                else
                        method->name = mono_image_strdup (image, mb->name);
 
-               ((MonoMethodNormal *)method)->header = header = (MonoMethodHeader *) 
+               mw->header = header = (MonoMethodHeader *) 
                        mono_image_alloc0 (image, MONO_SIZEOF_METHOD_HEADER + mb->locals * sizeof (MonoType *));
 
                header->code = mono_image_alloc (image, mb->pos);
@@ -192,7 +194,6 @@ mono_mb_create_method (MonoMethodBuilder *mb, MonoMethodSignature *signature, in
 
        method->skip_visibility = mb->skip_visibility;
 
-       mw = (MonoMethodWrapper*) mb->method;
        i = g_list_length (mw->method_data);
        if (i) {
                GList *tmp;
@@ -210,7 +211,7 @@ mono_mb_create_method (MonoMethodBuilder *mb, MonoMethodSignature *signature, in
                }
                g_list_free (l);
 
-               ((MonoMethodWrapper*)method)->method_data = data;
+               mw->method_data = data;
        }
        /*{
                static int total_code = 0;
index 9145603be81e70d177f5ef6def4c2fdc2b5dc67a..8f3b63303858e5d4d658540638c7731f3e63289b 100644 (file)
@@ -39,6 +39,8 @@
 #define CONFIG_OS "aix"
 #elif defined(__hpux)
 #define CONFIG_OS "hpux"
+#elif defined(__HAIKU__)
+#define CONFIG_OS "haiku"
 #else
 #warning Unknown operating system
 #define CONFIG_OS "unknownOS"
index 0b8f8063358dea16c0fa4361f6919b9204019deb..a1767f01076066a3011837438d5b5032d185ff2a 100644 (file)
@@ -72,7 +72,7 @@ struct _MonoDebugDataTable {
 
 typedef struct {
        const gchar *method_name;
-       const gchar *cil_code;
+       const gchar *obsolete_cil_code;
        guint32 wrapper_type;
 } MonoDebugWrapperData;
 
@@ -159,7 +159,6 @@ free_header_data (gpointer key, gpointer value, gpointer user_data)
 
        if (header->wrapper_data) {
                g_free ((gpointer)header->wrapper_data->method_name);
-               g_free ((gpointer)header->wrapper_data->cil_code);
                g_slist_free (header->address_list);
                g_free (header->wrapper_data);
        }
@@ -654,21 +653,13 @@ mono_debug_add_method (MonoMethod *method, MonoDebugMethodJitInfo *jit, MonoDoma
                g_hash_table_insert (table->method_hash, declaring, header);
 
                if (is_wrapper) {
-                       const unsigned char* il_code;
-                       MonoMethodHeader *mheader;
                        MonoDebugWrapperData *wrapper;
-                       guint32 il_codesize;
-
-                       mheader = mono_method_get_header (declaring);
-                       il_code = mono_method_header_get_code (mheader, &il_codesize, NULL);
 
                        header->wrapper_data = wrapper = g_new0 (MonoDebugWrapperData, 1);
 
                        wrapper->wrapper_type = method->wrapper_type;
                        wrapper->method_name = mono_method_full_name (declaring, TRUE);
-                       wrapper->cil_code = mono_disasm_code (
-                               NULL, declaring, il_code, il_code + il_codesize);
-                       mono_metadata_free_mh (mheader);
+                       wrapper->obsolete_cil_code = "";
                }
        } else {
                address->header.wrapper_data = header->wrapper_data;
index e0fda55dd9066797abaffa3644ce69ef4a2a45fd..a7543b50f851ec194734d38cd5c576bf9ad65d40 100644 (file)
@@ -11,7 +11,7 @@
 #include "mono/metadata/appdomain.h"
 #include "mono/metadata/class-internals.h"
 
-/* matches the System.MonoListItem objcet*/
+/* matches the System.MonoListItem object*/
 struct _MonoMList {
        MonoObject object;
        MonoMList *next;
@@ -72,6 +72,23 @@ mono_mlist_set_data (MonoMList* list, MonoObject *data)
        MONO_OBJECT_SETREF (list, data, data);
 }
 
+/**
+ * mono_mlist_set_next:
+ * @list: a managed list node
+ * @next: list node that will be next for the @list node.
+ *
+ * Set next node for @list to @next.
+ */
+MonoMList *
+mono_mlist_set_next (MonoMList* list, MonoMList *next)
+{
+       if (!list)
+               return next;
+
+       MONO_OBJECT_SETREF (list, next, next);
+       return list;
+}
+
 /**
  * mono_mlist_length:
  * @list: the managed list
@@ -175,7 +192,7 @@ find_prev (MonoMList* list, MonoMList *item)
 /**
  * mono_mlist_remove_item:
  * @list: the managed list
- * @data: the object to add to the list
+ * @data: the object to remove from the list
  *
  * Remove the list node @item from the managed list @list.
  * Since managed lists are singly-linked, this operation can take O(n) time.
index 61724e9ceb9d323e7cc4edfac7f1fb87c503bc6c..0dc0b4b5d58f8918fd597deb3dc9cb413ed9aed6 100644 (file)
@@ -8,10 +8,10 @@
 #include <mono/metadata/object.h>
 
 typedef struct _MonoMList MonoMList;
-
 MonoMList*  mono_mlist_alloc       (MonoObject *data);
 MonoObject* mono_mlist_get_data    (MonoMList* list);
 void        mono_mlist_set_data    (MonoMList* list, MonoObject *data);
+MonoMList*  mono_mlist_set_next    (MonoMList* list, MonoMList *next);
 int         mono_mlist_length      (MonoMList* list);
 MonoMList*  mono_mlist_next        (MonoMList* list);
 MonoMList*  mono_mlist_last        (MonoMList* list);
index b73ae60fea70822d44e603a8f206ef41f96a3e1a..e9510d53011e047402cf5385d973b01e2e9ef314 100644 (file)
@@ -27,6 +27,7 @@ PERFCTR_COUNTER(PROC_PBYTES,    "Private Bytes", "", NumberOfItems64, unused)
 /* sample runtime counter */
 PERFCTR_CAT(MONO_MEM, "Mono Memory", "", SingleInstance, Mono, MEM_NUM_OBJECTS)
 PERFCTR_COUNTER(MEM_NUM_OBJECTS, "Allocated Objects", "", NumberOfItems64, unused)
+PERFCTR_COUNTER(MEM_PHYS_TOTAL, "Total Physical Memory", "Physical memory installed in the machine, in bytes", NumberOfItems64, unused)
 
 PERFCTR_CAT(ASPNET, "ASP.NET", "", MultiInstance, Mono, ASPNET_REQ_Q)
 PERFCTR_COUNTER(ASPNET_REQ_Q, "Requests Queued", "", NumberOfItems64, aspnet_requests_queued)
@@ -124,6 +125,8 @@ PERFCTR_COUNTER(THREADPOOL_WORKITEMS, "Work Items Added", "", NumberOfItems64, t
 PERFCTR_COUNTER(THREADPOOL_WORKITEMS_PSEC, "Work Items Added/Sec", "", RateOfCountsPerSecond32, threadpool_workitems)
 PERFCTR_COUNTER(THREADPOOL_IOWORKITEMS, "IO Work Items Added", "", NumberOfItems64, threadpool_ioworkitems)
 PERFCTR_COUNTER(THREADPOOL_IOWORKITEMS_PSEC, "IO Work Items Added/Sec", "", RateOfCountsPerSecond32, threadpool_ioworkitems)
+PERFCTR_COUNTER(THREADPOOL_THREADS, "# of Threads", "", NumberOfItems32, threadpool_threads)
+PERFCTR_COUNTER(THREADPOOL_IOTHREADS, "# of IO Threads", "", NumberOfItems32, threadpool_iothreads)
 
 PERFCTR_CAT(NETWORK, "Network Interface", "", MultiInstance, NetworkInterface, NETWORK_BYTESRECSEC)
 PERFCTR_COUNTER(NETWORK_BYTESRECSEC, "Bytes Received/sec", "", RateOfCountsPerSecond64, unused)
index 48b666df947c598a56bf65728a684c2c9178e57a..35e271b65f1637f54f1cf158e20fdc716cd4c9db 100644 (file)
 #include <time.h>
 #include <string.h>
 #include <stdlib.h>
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#if defined (__OpenBSD__)
+#include <sys/param.h>
+#endif
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
 #ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
+#if defined (__NetBSD__) || defined (__APPLE__)
+#include <sys/sysctl.h>
+#endif
 #include "metadata/mono-perfcounters.h"
 #include "metadata/appdomain.h"
 #include "metadata/object-internals.h"
@@ -380,6 +392,60 @@ predef_cleanup (ImplVtable *vtable)
        perfctr_unlock ();
 }
 
+static guint64
+mono_determine_physical_ram_size (void)
+{
+#if defined (TARGET_WIN32)
+       MEMORYSTATUSEX memstat;
+
+       memstat.dwLength = sizeof (memstat);
+       GlobalMemoryStatusEx (&memstat);
+       return (guint64)memstat.ullTotalPhys;
+#elif defined (__NetBSD__) || defined (__APPLE__)
+#ifdef __NetBSD__
+       unsigned long value;
+#else
+       guint64 value;
+#endif
+       int mib[2] = {
+               CTL_HW,
+#ifdef __NetBSD__
+               HW_PHYSMEM
+#else
+               HW_MEMSIZE
+#endif
+       };
+       size_t size_sys = sizeof (value);
+
+       sysctl (mib, 2, &value, &size_sys, NULL, 0);
+       if (value == 0)
+               return 134217728;
+
+       return (guint64)value;
+#elif defined (HAVE_SYSCONF)
+       guint64 page_size = 0, num_pages = 0;
+
+       /* sysconf works on most *NIX operating systems, if your system doesn't have it or if it
+        * reports invalid values, please add your OS specific code below. */
+#ifdef _SC_PAGESIZE
+       page_size = (guint64)sysconf (_SC_PAGESIZE);
+#endif
+
+#ifdef _SC_PHYS_PAGES
+       num_pages = (guint64)sysconf (_SC_PHYS_PAGES);
+#endif
+
+       if (!page_size || !num_pages) {
+               g_warning ("Your operating system's sysconf (3) function doesn't correctly report physical memory size!");
+               return 134217728;
+       }
+
+       return page_size * num_pages;
+#else
+       return 134217728;
+#endif
+}
+
 void
 mono_perfcounters_init (void)
 {
@@ -829,6 +895,9 @@ mono_mem_counter (ImplVtable *vtable, MonoBoolean only_value, MonoCounterSample
        case COUNTER_MEM_NUM_OBJECTS:
                sample->rawValue = mono_stats.new_object_count;
                return TRUE;
+       case COUNTER_MEM_PHYS_TOTAL:
+               sample->rawValue = mono_determine_physical_ram_size ();;
+               return TRUE;
        }
        return FALSE;
 }
@@ -929,6 +998,12 @@ predef_writable_counter (ImplVtable *vtable, MonoBoolean only_value, MonoCounter
                case COUNTER_THREADPOOL_IOWORKITEMS:
                        sample->rawValue = mono_perfcounters->threadpool_ioworkitems;
                        return TRUE;
+               case COUNTER_THREADPOOL_THREADS:
+                       sample->rawValue = mono_perfcounters->threadpool_threads;
+                       return TRUE;
+               case COUNTER_THREADPOOL_IOTHREADS:
+                       sample->rawValue = mono_perfcounters->threadpool_iothreads;
+                       return TRUE;
                }
                break;
        }
@@ -954,6 +1029,8 @@ predef_writable_update (ImplVtable *vtable, MonoBoolean do_incr, gint64 value)
                switch (id) {
                case COUNTER_THREADPOOL_WORKITEMS: ptr64 = (gint64 *) &mono_perfcounters->threadpool_workitems; break;
                case COUNTER_THREADPOOL_IOWORKITEMS: ptr64 = (gint64 *) &mono_perfcounters->threadpool_ioworkitems; break;
+               case COUNTER_THREADPOOL_THREADS: ptr = &mono_perfcounters->threadpool_threads; break;
+               case COUNTER_THREADPOOL_IOTHREADS: ptr = &mono_perfcounters->threadpool_iothreads; break;
                }
                break;
        }
diff --git a/mono/metadata/mono-wsq.c b/mono/metadata/mono-wsq.c
new file mode 100644 (file)
index 0000000..14c7fd1
--- /dev/null
@@ -0,0 +1,205 @@
+/*
+ * mono-wsq.c: work-stealing queue
+ *
+ * Authors:
+ *   Gonzalo Paniagua Javier (gonzalo@novell.com)
+ *
+ * Copyright (c) 2010 Novell, Inc (http://www.novell.com)
+ */
+
+#include <string.h>
+#include <mono/metadata/object.h>
+#include <mono/metadata/mono-wsq.h>
+#include <mono/utils/mono-semaphore.h>
+
+#define INITIAL_LENGTH 32
+#define WSQ_DEBUG(...)
+//#define WSQ_DEBUG(...) g_message(__VA_ARGS__)
+
+struct _MonoWSQ {
+       volatile gint head;
+       volatile gint tail;
+       MonoArray *queue;
+       gint32 mask;
+       MonoSemType lock;
+};
+
+static guint32 wsq_tlskey = -1;
+
+void
+mono_wsq_init ()
+{
+       wsq_tlskey = TlsAlloc ();
+}
+
+void
+mono_wsq_cleanup ()
+{
+       if (wsq_tlskey == -1)
+               return;
+       TlsFree (wsq_tlskey);
+       wsq_tlskey = -1;
+}
+
+MonoWSQ *
+mono_wsq_create ()
+{
+       MonoWSQ *wsq;
+       MonoDomain *root;
+
+       if (wsq_tlskey == -1)
+               return NULL;
+
+       wsq = g_new0 (MonoWSQ, 1);
+       wsq->mask = INITIAL_LENGTH - 1;
+       MONO_GC_REGISTER_ROOT (wsq->queue);
+       root = mono_get_root_domain ();
+       wsq->queue = mono_array_new_cached (root, mono_defaults.object_class, INITIAL_LENGTH);
+       MONO_SEM_INIT (&wsq->lock, 1);
+       TlsSetValue (wsq_tlskey, wsq);
+       return wsq;
+}
+
+void
+mono_wsq_destroy (MonoWSQ *wsq)
+{
+       if (wsq == NULL || wsq->queue == NULL)
+               return;
+
+       g_assert (mono_wsq_count (wsq) == 0);
+       MONO_GC_UNREGISTER_ROOT (wsq->queue);
+       MONO_SEM_DESTROY (&wsq->lock);
+       if (wsq_tlskey != -1 && TlsGetValue (wsq_tlskey) == wsq)
+               TlsSetValue (wsq_tlskey, NULL);
+       memset (wsq, 0, sizeof (MonoWSQ));
+       g_free (wsq);
+}
+
+gint
+mono_wsq_count (MonoWSQ *wsq)
+{
+       if (!wsq)
+               return 0;
+       return ((wsq->tail - wsq->head) & wsq->mask);
+}
+
+gboolean
+mono_wsq_local_push (void *obj)
+{
+       int tail;
+       int head;
+       int count;
+       MonoWSQ *wsq;
+
+       if (obj == NULL || wsq_tlskey == -1)
+               return FALSE;
+
+       wsq = (MonoWSQ *) TlsGetValue (wsq_tlskey);
+       if (wsq == NULL) {
+               WSQ_DEBUG ("local_push: no wsq\n");
+               return FALSE;
+       }
+
+       tail = wsq->tail;
+       if (tail < wsq->head + wsq->mask) {
+               mono_array_setref (wsq->queue, tail & wsq->mask, (MonoObject *) obj);
+               wsq->tail = tail + 1;
+               WSQ_DEBUG ("local_push: OK %p %p\n", wsq, obj);
+               return TRUE;
+       }
+
+       MONO_SEM_WAIT (&wsq->lock);
+       head = wsq->head;
+       count = wsq->tail - wsq->head;
+       if (count >= wsq->mask) {
+               MonoArray *new_array;
+               int length;
+               int i;
+
+               length = mono_array_length (wsq->queue);
+               new_array = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, length * 2);
+               for (i = 0; i < length; i++)
+                       mono_array_setref (new_array, i, mono_array_get (wsq->queue, MonoObject*, (i + head) & wsq->mask));
+
+               memset (mono_array_addr (wsq->queue, MonoObject *, 0), 0, sizeof (MonoObject*) * length);
+               wsq->queue = new_array;
+               wsq->head = 0;
+               wsq->tail = tail = count;
+               wsq->mask = (wsq->mask << 1) | 1;
+       }
+       mono_array_setref (wsq->queue, tail & wsq->mask, obj);
+       wsq->tail = tail + 1;
+       MONO_SEM_POST (&wsq->lock);
+       WSQ_DEBUG ("local_push: LOCK %p  %p\n", wsq, obj);
+       return TRUE;
+}
+
+gboolean
+mono_wsq_local_pop (void **ptr)
+{
+       int tail;
+       gboolean res;
+       MonoWSQ *wsq;
+
+       if (ptr == NULL || wsq_tlskey == -1)
+               return FALSE;
+
+       wsq = (MonoWSQ *) TlsGetValue (wsq_tlskey);
+       if (wsq == NULL) {
+               WSQ_DEBUG ("local_pop: no wsq\n");
+               return FALSE;
+       }
+
+       tail = wsq->tail;
+       if (wsq->head >= tail) {
+               WSQ_DEBUG ("local_pop: empty\n");
+               return FALSE;
+       }
+       tail--;
+       InterlockedExchange (&wsq->tail, tail);
+       if (wsq->head <= tail) {
+               *ptr = mono_array_get (wsq->queue, void *, tail & wsq->mask);
+               mono_array_set (wsq->queue, void *, tail & wsq->mask, NULL);
+               WSQ_DEBUG ("local_pop: GOT ONE %p %p\n", wsq, *ptr);
+               return TRUE;
+       }
+
+       MONO_SEM_WAIT (&wsq->lock);
+       if (wsq->head <= tail) {
+               *ptr = mono_array_get (wsq->queue, void *, tail & wsq->mask);
+               mono_array_set (wsq->queue, void *, tail & wsq->mask, NULL);
+               res = TRUE;
+       } else {
+               wsq->tail = tail + 1;
+               res = FALSE;
+       }
+       MONO_SEM_POST (&wsq->lock);
+       WSQ_DEBUG ("local_pop: LOCK %d %p %p\n", res, wsq, *ptr);
+       return res;
+}
+
+void
+mono_wsq_try_steal (MonoWSQ *wsq, void **ptr, guint32 ms_timeout)
+{
+       if (wsq == NULL || ptr == NULL || *ptr != NULL || wsq_tlskey == -1)
+               return;
+
+       if (TlsGetValue (wsq_tlskey) == wsq)
+               return;
+
+       if (MONO_SEM_TIMEDWAIT (&wsq->lock, ms_timeout)) {
+               int head;
+
+               head = wsq->head;
+               InterlockedExchange (&wsq->head, head + 1);
+               if (head < wsq->tail) {
+                       *ptr = mono_array_get (wsq->queue, void *, head & wsq->mask);
+                       mono_array_set (wsq->queue, void *, head & wsq->mask, NULL);
+                       WSQ_DEBUG ("STEAL %p %p\n", wsq, *ptr);
+               } else {
+                       wsq->head = head;
+               }
+               MONO_SEM_POST (&wsq->lock);
+       }
+}
+
diff --git a/mono/metadata/mono-wsq.h b/mono/metadata/mono-wsq.h
new file mode 100644 (file)
index 0000000..7208dad
--- /dev/null
@@ -0,0 +1,26 @@
+#ifndef _MONO_WSQ_H
+#define _MONO_WSQ_H
+
+#include <config.h>
+#include <glib.h>
+#include <mono/metadata/object.h>
+#include <mono/metadata/gc-internal.h>
+#include <mono/io-layer/io-layer.h>
+
+G_BEGIN_DECLS
+
+typedef struct _MonoWSQ MonoWSQ;
+
+void mono_wsq_init (void) MONO_INTERNAL;
+void mono_wsq_cleanup (void) MONO_INTERNAL;
+
+MonoWSQ *mono_wsq_create (void) MONO_INTERNAL;
+void mono_wsq_destroy (MonoWSQ *wsq) MONO_INTERNAL;
+gboolean mono_wsq_local_push (void *obj) MONO_INTERNAL;
+gboolean mono_wsq_local_pop (void **ptr) MONO_INTERNAL;
+void mono_wsq_try_steal (MonoWSQ *wsq, void **ptr, guint32 ms_timeout) MONO_INTERNAL;
+gint mono_wsq_count (MonoWSQ *wsq) MONO_INTERNAL;
+
+G_END_DECLS
+
+#endif
index 90b0a131a1ad716d79ac0dfca6dc58ebd64d58df..d98df2bd17473a3e97d10aafe600d9fc57004fe2 100644 (file)
@@ -46,13 +46,13 @@ mono_gc_add_memory_pressure (gint64 value)
 }
 
 /* maybe track the size, not important, though */
-gint64
+int64_t
 mono_gc_get_used_size (void)
 {
        return 1024*1024;
 }
 
-gint64
+int64_t
 mono_gc_get_heap_size (void)
 {
        return 2*1024*1024;
@@ -262,5 +262,11 @@ mono_gc_get_write_barrier (void)
        return NULL;
 }
 
+void*
+mono_gc_invoke_with_gc_lock (MonoGCLockedCallbackFunc func, void *data)
+{
+       return func (data);
+}
+
 #endif
 
index 37be81878e4227ea141a208e9a48782bfba7611e..49c4ea53c576bdf6ee0ce0f4c716a35fad8fe495 100644 (file)
 
 #endif
 
+#ifdef MONO_BIG_ARRAYS
+typedef uint64_t mono_array_size_t;
+typedef int64_t mono_array_lower_bound_t;
+#define MONO_ARRAY_MAX_INDEX G_MAXINT64
+#define MONO_ARRAY_MAX_SIZE  G_MAXUINT64
+#else
+typedef uint32_t mono_array_size_t;
+typedef int32_t mono_array_lower_bound_t;
+#define MONO_ARRAY_MAX_INDEX ((int32_t) 0x7fffffff)
+#define MONO_ARRAY_MAX_SIZE  ((uint32_t) 0xffffffff)
+#endif
+
+typedef struct {
+       mono_array_size_t length;
+       mono_array_lower_bound_t lower_bound;
+} MonoArrayBounds;
+
+struct _MonoArray {
+       MonoObject obj;
+       /* bounds is NULL for szarrays */
+       MonoArrayBounds *bounds;
+       /* total number of elements of the array */
+       mono_array_size_t max_length; 
+       /* we use double to ensure proper alignment on platforms that need it */
+       double vector [MONO_ZERO_LEN_ARRAY];
+};
+
+struct _MonoString {
+       MonoObject object;
+       int32_t length;
+       mono_unichar2 chars [MONO_ZERO_LEN_ARRAY];
+};
+
+#define mono_object_class(obj) (((MonoObject*)(obj))->vtable->klass)
+#define mono_object_domain(obj) (((MonoObject*)(obj))->vtable->domain)
+
+#define mono_string_chars_fast(s) ((mono_unichar2*)(s)->chars)
+#define mono_string_length_fast(s) ((s)->length)
+
+#define mono_array_length_fast(array) ((array)->max_length)
+#define mono_array_addr_with_size_fast(array,size,index) ( ((char*)(array)->vector) + (size) * (index) )
+
 typedef struct {
        MonoObject obj;
        MonoObject *identity;
@@ -229,6 +271,7 @@ typedef struct {
        MonoObject  *async_callback;
        MonoObject  *execution_context;
        MonoObject  *original_context;
+       gint64       add_time;
 } MonoAsyncResult;
 
 typedef struct {
@@ -317,7 +360,7 @@ typedef enum {
 
 struct _MonoInternalThread {
        MonoObject  obj;
-       int         lock_thread_id; /* to be used as the pre-shifted thread id in thin locks */
+       volatile int lock_thread_id; /* to be used as the pre-shifted thread id in thin locks. Used for appdomain_ref push/pop */
        HANDLE      handle;
        MonoArray  *cached_culture_info;
        gpointer    unused1;
@@ -1351,7 +1394,7 @@ void
 mono_array_full_copy (MonoArray *src, MonoArray *dest) MONO_INTERNAL;
 
 gboolean
-mono_array_calc_byte_len (MonoClass *class, mono_array_size_t len, mono_array_size_t *res) MONO_INTERNAL;
+mono_array_calc_byte_len (MonoClass *class, uintptr_t len, uintptr_t *res) MONO_INTERNAL;
 
 gpointer
 mono_remote_class_vtable (MonoDomain *domain, MonoRemoteClass *remote_class, MonoRealProxy *real_proxy) MONO_INTERNAL;
index dfb2a3016631f7a62ba57fc7d8084be3449f3b66..59a62636ea42320fa5cb12f253e96f2986e3d52f 100644 (file)
@@ -1910,11 +1910,29 @@ mono_class_create_runtime_vtable (MonoDomain *domain, MonoClass *class, gboolean
                        if (special_static != SPECIAL_STATIC_NONE) {
                                guint32 size, offset;
                                gint32 align;
+                               gsize default_bitmap [4] = {0};
+                               gsize *bitmap;
+                               int max_set = 0;
+                               MonoClass *fclass;
+                               if (mono_type_is_reference (field->type)) {
+                                       default_bitmap [0] = 1;
+                                       max_set = 1;
+                                       bitmap = default_bitmap;
+                               } else if (mono_type_is_struct (field->type)) {
+                                       fclass = mono_class_from_mono_type (field->type);
+                                       bitmap = compute_class_bitmap (fclass, default_bitmap, sizeof (default_bitmap) * 8, 0, &max_set, FALSE);
+                               } else {
+                                       default_bitmap [0] = 0;
+                                       max_set = 0;
+                                       bitmap = default_bitmap;
+                               }
                                size = mono_type_size (field->type, &align);
-                               offset = mono_alloc_special_static_data (special_static, size, align);
+                               offset = mono_alloc_special_static_data (special_static, size, align, bitmap, max_set);
                                if (!domain->special_static_fields)
                                        domain->special_static_fields = g_hash_table_new (NULL, NULL);
                                g_hash_table_insert (domain->special_static_fields, field, GUINT_TO_POINTER (offset));
+                               if (bitmap != default_bitmap)
+                                       g_free (bitmap);
                                /* 
                                 * This marks the field as special static to speed up the
                                 * checks in mono_field_static_get/set_value ().
@@ -2080,6 +2098,12 @@ mono_class_proxy_vtable (MonoDomain *domain, MonoRemoteClass *remote_class, Mono
        GSList *extra_interfaces = NULL;
        MonoClass *class = remote_class->proxy_class;
        gpointer *interface_offsets;
+       uint8_t *bitmap;
+       int bsize;
+       
+#ifdef COMPRESSED_INTERFACE_BITMAP
+       int bcsize;
+#endif
 
        vt = mono_class_vtable (domain, class);
        g_assert (vt); /*FIXME property handle failure*/
@@ -2167,7 +2191,12 @@ mono_class_proxy_vtable (MonoDomain *domain, MonoRemoteClass *remote_class, Mono
        }
 
        pvt->max_interface_id = max_interface_id;
-       pvt->interface_bitmap = mono_domain_alloc0 (domain, sizeof (guint8) * (max_interface_id/8 + 1 ));
+       bsize = sizeof (guint8) * (max_interface_id/8 + 1 );
+#ifdef COMPRESSED_INTERFACE_BITMAP
+       bitmap = g_malloc0 (bsize);
+#else
+       bitmap = mono_domain_alloc0 (domain, bsize);
+#endif
 
        if (! ARCH_USE_IMT) {
                /* initialize interface offsets */
@@ -2179,7 +2208,7 @@ mono_class_proxy_vtable (MonoDomain *domain, MonoRemoteClass *remote_class, Mono
        }
        for (i = 0; i < class->interface_offsets_count; ++i) {
                int interface_id = class->interfaces_packed [i]->interface_id;
-               pvt->interface_bitmap [interface_id >> 3] |= (1 << (interface_id & 7));
+               bitmap [interface_id >> 3] |= (1 << (interface_id & 7));
        }
 
        if (extra_interfaces) {
@@ -2196,7 +2225,7 @@ mono_class_proxy_vtable (MonoDomain *domain, MonoRemoteClass *remote_class, Mono
                        if (! ARCH_USE_IMT) {
                                interface_offsets [max_interface_id - interf->interface_id] = &pvt->vtable [slot];
                        }
-                       pvt->interface_bitmap [interf->interface_id >> 3] |= (1 << (interf->interface_id & 7));
+                       bitmap [interf->interface_id >> 3] |= (1 << (interf->interface_id & 7));
 
                        iter = NULL;
                        j = 0;
@@ -2218,6 +2247,14 @@ mono_class_proxy_vtable (MonoDomain *domain, MonoRemoteClass *remote_class, Mono
                }
        }
 
+#ifdef COMPRESSED_INTERFACE_BITMAP
+       bcsize = mono_compress_bitmap (NULL, bitmap, bsize);
+       pvt->interface_bitmap = mono_domain_alloc0 (domain, bcsize);
+       mono_compress_bitmap (pvt->interface_bitmap, bitmap, bsize);
+       g_free (bitmap);
+#else
+       pvt->interface_bitmap = bitmap;
+#endif
        return pvt;
 }
 
@@ -2937,6 +2974,7 @@ mono_field_get_value_object (MonoDomain *domain, MonoClassField *field, MonoObje
        gchar *v;
        gboolean is_static = FALSE;
        gboolean is_ref = FALSE;
+       gboolean is_literal = FALSE;
 
        switch (field->type->type) {
        case MONO_TYPE_STRING:
@@ -2964,7 +3002,7 @@ mono_field_get_value_object (MonoDomain *domain, MonoClassField *field, MonoObje
                is_ref = field->type->byref;
                break;
        case MONO_TYPE_GENERICINST:
-               is_ref = !field->type->data.generic_class->container_class->valuetype;
+               is_ref = !mono_type_generic_inst_is_valuetype (field->type);
                break;
        default:
                g_error ("type 0x%x not handled in "
@@ -2972,21 +3010,30 @@ mono_field_get_value_object (MonoDomain *domain, MonoClassField *field, MonoObje
                return NULL;
        }
 
+       if (field->type->attrs & FIELD_ATTRIBUTE_LITERAL)
+               is_literal = TRUE;
+
        if (field->type->attrs & FIELD_ATTRIBUTE_STATIC) {
                is_static = TRUE;
-               vtable = mono_class_vtable (domain, field->parent);
-               if (!vtable) {
-                       char *name = mono_type_get_full_name (field->parent);
-                       g_warning ("Could not retrieve the vtable for type %s in mono_field_get_value_object", name);
-                       g_free (name);
-                       return NULL;
+
+               if (!is_literal) {
+                       vtable = mono_class_vtable (domain, field->parent);
+                       if (!vtable) {
+                               char *name = mono_type_get_full_name (field->parent);
+                               /*FIXME extend this to use the MonoError api*/
+                               g_warning ("Could not retrieve the vtable for type %s in mono_field_get_value_object", name);
+                               g_free (name);
+                               return NULL;
+                       }
+                       if (!vtable->initialized)
+                               mono_runtime_class_init (vtable);
                }
-               if (!vtable->initialized)
-                       mono_runtime_class_init (vtable);
        }
        
        if (is_ref) {
-               if (is_static) {
+               if (is_literal) {
+                       get_default_field_value (domain, field, &o);
+               } else if (is_static) {
                        mono_field_static_get_value (vtable, field, &o);
                } else {
                        mono_field_get_value (obj, field, &o);
@@ -3002,7 +3049,10 @@ mono_field_get_value_object (MonoDomain *domain, MonoClassField *field, MonoObje
 
        o = mono_object_new (domain, klass);
        v = ((gchar *) o) + sizeof (MonoObject);
-       if (is_static) {
+
+       if (is_literal) {
+               get_default_field_value (domain, field, v);
+       } else if (is_static) {
                mono_field_static_get_value (vtable, field, v);
        } else {
                mono_field_get_value (obj, field, v);
@@ -3950,6 +4000,7 @@ mono_runtime_invoke_array (MonoMethod *method, void *obj, MonoArray *params,
 
                if (!obj) {
                        obj = mono_object_new (mono_domain_get (), method->klass);
+                       g_assert (obj); /*maybe we should raise a TLE instead?*/
                        if (mono_object_class(obj) == mono_defaults.transparent_proxy_class) {
                                method = mono_marshal_get_remoting_invoke (method->slot == -1 ? method : method->klass->vtable [method->slot]);
                        }
@@ -4298,7 +4349,7 @@ mono_object_clone (MonoObject *obj)
 void
 mono_array_full_copy (MonoArray *src, MonoArray *dest)
 {
-       mono_array_size_t size;
+       uintptr_t size;
        MonoClass *klass = src->obj.vtable->klass;
 
        MONO_ARCH_SAVE_REGS;
@@ -4334,8 +4385,8 @@ MonoArray*
 mono_array_clone_in_domain (MonoDomain *domain, MonoArray *array)
 {
        MonoArray *o;
-       mono_array_size_t size, i;
-       mono_array_size_t *sizes;
+       uintptr_t size, i;
+       uintptr_t *sizes;
        MonoClass *klass = array->obj.vtable->klass;
 
        MONO_ARCH_SAVE_REGS;
@@ -4360,14 +4411,14 @@ mono_array_clone_in_domain (MonoDomain *domain, MonoArray *array)
                return o;
        }
        
-       sizes = alloca (klass->rank * sizeof(mono_array_size_t) * 2);
+       sizes = alloca (klass->rank * sizeof(intptr_t) * 2);
        size = mono_array_element_size (klass);
        for (i = 0; i < klass->rank; ++i) {
                sizes [i] = array->bounds [i].length;
                size *= array->bounds [i].length;
                sizes [i + klass->rank] = array->bounds [i].lower_bound;
        }
-       o = mono_array_new_full (domain, klass, sizes, sizes + klass->rank);
+       o = mono_array_new_full (domain, klass, sizes, (intptr_t*)sizes + klass->rank);
 #ifdef HAVE_SGEN_GC
        if (klass->element_class->valuetype) {
                if (klass->element_class->has_references)
@@ -4416,9 +4467,9 @@ mono_array_clone (MonoArray *array)
 #endif
 
 gboolean
-mono_array_calc_byte_len (MonoClass *class, mono_array_size_t len, mono_array_size_t *res)
+mono_array_calc_byte_len (MonoClass *class, uintptr_t len, uintptr_t *res)
 {
-       mono_array_size_t byte_len;
+       uintptr_t byte_len;
 
        byte_len = mono_array_element_size (class);
        if (CHECK_MUL_OVERFLOW_UN (byte_len, len))
@@ -4444,9 +4495,9 @@ mono_array_calc_byte_len (MonoClass *class, mono_array_size_t len, mono_array_si
  * lower bounds and type.
  */
 MonoArray*
-mono_array_new_full (MonoDomain *domain, MonoClass *array_class, mono_array_size_t *lengths, mono_array_size_t *lower_bounds)
+mono_array_new_full (MonoDomain *domain, MonoClass *array_class, uintptr_t *lengths, intptr_t *lower_bounds)
 {
-       mono_array_size_t byte_len, len, bounds_size;
+       uintptr_t byte_len, len, bounds_size;
        MonoObject *o;
        MonoArray *array;
        MonoArrayBounds *bounds;
@@ -4546,7 +4597,7 @@ mono_array_new_full (MonoDomain *domain, MonoClass *array_class, mono_array_size
  * This routine creates a new szarray with @n elements of type @eclass.
  */
 MonoArray *
-mono_array_new (MonoDomain *domain, MonoClass *eclass, mono_array_size_t n)
+mono_array_new (MonoDomain *domain, MonoClass *eclass, uintptr_t n)
 {
        MonoClass *ac;
 
@@ -4567,11 +4618,11 @@ mono_array_new (MonoDomain *domain, MonoClass *eclass, mono_array_size_t n)
  * can be sure about the domain it operates in.
  */
 MonoArray *
-mono_array_new_specific (MonoVTable *vtable, mono_array_size_t n)
+mono_array_new_specific (MonoVTable *vtable, uintptr_t n)
 {
        MonoObject *o;
        MonoArray *ao;
-       guint32 byte_len;
+       uintptr_t byte_len;
 
        MONO_ARCH_SAVE_REGS;
 
@@ -5243,7 +5294,7 @@ mono_string_to_utf8_checked (MonoString *s, MonoError *error)
  * This is a temporary helper until our string implementation
  * is reworked to always include the null terminating char.
  */
-gunichar2 *
+mono_unichar2*
 mono_string_to_utf16 (MonoString *s)
 {
        char *as;
@@ -6144,7 +6195,6 @@ mono_get_addr_from_ftnptr (gpointer descr)
        return callbacks.get_addr_from_ftnptr (descr);
 }      
 
-#if 0
 /**
  * mono_string_chars:
  * @s: a MonoString
@@ -6152,9 +6202,9 @@ mono_get_addr_from_ftnptr (gpointer descr)
  * Returns a pointer to the UCS16 characters stored in the MonoString
  */
 gunichar2 *
-mono_string_chars(MonoString *s)
+mono_string_chars (MonoString *s)
 {
-       /* This method is here only for documentation extraction, this is a macro */
+       return s->chars;
 }
 
 /**
@@ -6166,7 +6216,33 @@ mono_string_chars(MonoString *s)
 int
 mono_string_length (MonoString *s)
 {
-       /* This method is here only for documentation extraction, this is a macro */
+       return s->length;
+}
+
+/**
+ * mono_array_length:
+ * @array: a MonoArray*
+ *
+ * Returns the total number of elements in the array. This works for
+ * both vectors and multidimensional arrays.
+ */
+uintptr_t
+mono_array_length (MonoArray *array)
+{
+       return array->max_length;
+}
+
+/**
+ * mono_array_addr_with_size:
+ * @array: a MonoArray*
+ * @size: size of the array elements
+ * @idx: index into the array
+ *
+ * Returns the address of the @idx element in the array.
+ */
+char*
+mono_array_addr_with_size (MonoArray *array, int size, uintptr_t idx)
+{
+       return ((char*)(array)->vector) + size * idx;
 }
 
-#endif
index ee21889f3659ed45555b7c2281a428387334b56e..88692693bb0e97109c521e91e69a9599c7d80ea4 100644 (file)
@@ -7,6 +7,8 @@ MONO_BEGIN_DECLS
 
 typedef mono_byte MonoBoolean;
 
+typedef struct _MonoString MonoString;
+typedef struct _MonoArray MonoArray;
 typedef struct _MonoReflectionMethod MonoReflectionMethod;
 typedef struct _MonoReflectionAssembly MonoReflectionAssembly;
 typedef struct _MonoReflectionModule MonoReflectionModule;
@@ -28,46 +30,10 @@ typedef struct {
        MonoThreadsSync *synchronisation;
 } MonoObject;
 
-#ifdef MONO_BIG_ARRAYS
-typedef uint64_t mono_array_size_t;
-typedef int64_t mono_array_lower_bound_t;
-#define MONO_ARRAY_MAX_INDEX G_MAXINT64
-#define MONO_ARRAY_MAX_SIZE  G_MAXUINT64
-#else
-typedef uint32_t mono_array_size_t;
-typedef int32_t mono_array_lower_bound_t;
-#define MONO_ARRAY_MAX_INDEX ((int32_t) 0x7fffffff)
-#define MONO_ARRAY_MAX_SIZE  ((uint32_t) 0xffffffff)
-#endif
-
-typedef struct {
-       mono_array_size_t length;
-       mono_array_lower_bound_t lower_bound;
-} MonoArrayBounds;
-
-typedef struct {
-       MonoObject obj;
-       /* bounds is NULL for szarrays */
-       MonoArrayBounds *bounds;
-       /* total number of elements of the array */
-       mono_array_size_t max_length; 
-       /* we use double to ensure proper alignment on platforms that need it */
-       double vector [MONO_ZERO_LEN_ARRAY];
-} MonoArray;
-
-typedef struct {
-       MonoObject object;
-       int32_t length;
-       mono_unichar2 chars [MONO_ZERO_LEN_ARRAY];
-} MonoString;
-
 typedef MonoObject* (*MonoInvokeFunc)       (MonoMethod *method, void *obj, void **params, MonoObject **exc);
 typedef void*    (*MonoCompileFunc)         (MonoMethod *method);
 typedef void       (*MonoMainThreadFunc)    (void* user_data);
 
-#define mono_object_class(obj) (((MonoObject*)(obj))->vtable->klass)
-#define mono_object_domain(obj) (((MonoObject*)(obj))->vtable->domain)
-
 #define MONO_OBJECT_SETREF(obj,fieldname,value) do {   \
                mono_gc_wbarrier_set_field ((MonoObject*)(obj), &((obj)->fieldname), (MonoObject*)value);       \
                /*(obj)->fieldname = (value);*/ \
@@ -78,9 +44,7 @@ typedef void      (*MonoMainThreadFunc)    (void* user_data);
         mono_gc_wbarrier_generic_store (&((s)->field), (MonoObject*)(value)); \
     } while (0)
 
-#define mono_array_length(array) ((array)->max_length)
 #define mono_array_addr(array,type,index) ((type*)(void*) mono_array_addr_with_size (array, sizeof (type), index))
-#define mono_array_addr_with_size(array,size,index) ( ((char*)(array)->vector) + (size) * (index) )
 #define mono_array_get(array,type,index) ( *(type*)mono_array_addr ((array), type, (index)) ) 
 #define mono_array_set(array,type,index,value) \
        do {    \
@@ -100,8 +64,8 @@ typedef void     (*MonoMainThreadFunc)    (void* user_data);
                mono_gc_wbarrier_arrayref_copy (__p, __s, (count));     \
        } while (0)
 
-#define mono_string_chars(s) ((mono_unichar2*)(s)->chars)
-#define mono_string_length(s) ((s)->length)
+mono_unichar2 *mono_string_chars  (MonoString *s);
+int            mono_string_length (MonoString *s);
 
 MonoObject *
 mono_object_new                    (MonoDomain *domain, MonoClass *klass);
@@ -120,18 +84,24 @@ MonoObject *
 mono_object_new_from_token  (MonoDomain *domain, MonoImage *image, uint32_t token);
 
 MonoArray*
-mono_array_new             (MonoDomain *domain, MonoClass *eclass, mono_array_size_t n);
+mono_array_new             (MonoDomain *domain, MonoClass *eclass, uintptr_t n);
 
 MonoArray*
 mono_array_new_full        (MonoDomain *domain, MonoClass *array_class,
-                            mono_array_size_t *lengths, mono_array_size_t *lower_bounds);
+                            uintptr_t *lengths, intptr_t *lower_bounds);
 
 MonoArray *
-mono_array_new_specific            (MonoVTable *vtable, mono_array_size_t n);
+mono_array_new_specific            (MonoVTable *vtable, uintptr_t n);
 
 MonoArray*
 mono_array_clone           (MonoArray *array);
 
+char*
+mono_array_addr_with_size   (MonoArray *array, int size, uintptr_t idx);
+
+uintptr_t
+mono_array_length           (MonoArray *array);
+
 MonoString*
 mono_string_new_utf16      (MonoDomain *domain, const mono_unichar2 *text, int32_t len);
 
index 317ffc0966b63c78460cde5c7f4789d8e37adb02..a0f8432755fd140980ea8a7a69a7f4db13abbd56 100644 (file)
@@ -349,18 +349,6 @@ dump_verify_info (MonoImage *image, int flags)
                "Ok", "Error", "Warning", NULL, "CLS", NULL, NULL, NULL, "Not Verifiable"
        };
 
-       if (verify_metadata) {
-               errors = mono_image_verify_tables (image, flags);
-       
-               for (tmp = errors; tmp; tmp = tmp->next) {
-                       MonoVerifyInfo *info = tmp->data;
-                       g_print ("%s: %s\n", desc [info->status], info->message);
-                       if (info->status == MONO_VERIFY_ERROR)
-                               count++;
-               }
-               mono_free_verify_list (errors);
-       }
-
        if (verify_code) { /* verify code */
                int i;
                MonoTableInfo *m = &image->tables [MONO_TABLE_METHOD];
index 330572c6481e0edc7eec9dc340c5ceacafdae6bb..48f9db9872af77e60d9ce5447cbd865bc5bf77b1 100644 (file)
@@ -13,7 +13,7 @@
 #include <glib.h>
 #include <string.h>
 
-#include <mono/metadata/object.h>
+#include <mono/metadata/object-internals.h>
 #include <mono/metadata/process.h>
 #include <mono/metadata/assembly.h>
 #include <mono/metadata/appdomain.h>
@@ -510,6 +510,10 @@ complete_path (const gunichar2 *appname, gchar **completed)
        return TRUE;
 }
 
+#if defined (MINGW_CROSS_COMPILE) && defined (HAVE_GETPROCESSID)
+#undef HAVE_GETPROCESSID
+#endif
+
 #ifndef HAVE_GETPROCESSID
 /* Run-time GetProcessId detection for Windows */
 #ifdef TARGET_WIN32
index 31dbd8e55ad8e2089473917a82d60aa9655ff38a..03ca68981a6efa5ab24abaa75e549ec0d7c8518e 100644 (file)
@@ -38,6 +38,7 @@
 #include <mono/metadata/mempool-internals.h>
 #include <mono/metadata/security-core-clr.h>
 #include <mono/metadata/debug-helpers.h>
+#include <mono/metadata/verify-internals.h>
 #include <mono/utils/mono-string.h>
 #include <mono/utils/mono-error-internals.h>
 
@@ -2768,7 +2769,7 @@ mono_image_get_field_on_inst_token (MonoDynamicImage *assembly, MonoReflectionFi
                token = mono_image_get_memberref_token (assembly, &klass->byval_arg, field->name, sig);
        } else {
                char *name = mono_type_get_full_name (mono_object_class (f->fb));
-               g_error ("mono_image_get_method_on_inst_token: don't know how to handle %s", name);
+               g_error ("mono_image_get_field_on_inst_token: don't know how to handle %s", name);
        }
 
        mono_g_hash_table_insert (assembly->handleref_managed, f, GUINT_TO_POINTER (token));
@@ -6119,14 +6120,18 @@ mono_image_set_wrappers_type (MonoReflectionModuleBuilder *moduleb, MonoReflecti
 MonoReflectionAssembly*
 mono_assembly_get_object (MonoDomain *domain, MonoAssembly *assembly)
 {
-       static MonoClass *System_Reflection_Assembly;
+       static MonoClass *assembly_type;
        MonoReflectionAssembly *res;
        
        CHECK_OBJECT (MonoReflectionAssembly *, assembly, NULL);
-       if (!System_Reflection_Assembly)
-               System_Reflection_Assembly = mono_class_from_name (
-                       mono_defaults.corlib, "System.Reflection", "Assembly");
-       res = (MonoReflectionAssembly *)mono_object_new (domain, System_Reflection_Assembly);
+       if (!assembly_type) {
+               MonoClass *class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoAssembly");
+               if (class == NULL)
+                       class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "Assembly");
+               g_assert (class);
+               assembly_type = class;
+       }
+       res = (MonoReflectionAssembly *)mono_object_new (domain, assembly_type);
        res->assembly = assembly;
 
        CACHE_OBJECT (MonoReflectionAssembly *, assembly, res, NULL);
@@ -6137,15 +6142,19 @@ mono_assembly_get_object (MonoDomain *domain, MonoAssembly *assembly)
 MonoReflectionModule*   
 mono_module_get_object   (MonoDomain *domain, MonoImage *image)
 {
-       static MonoClass *System_Reflection_Module;
+       static MonoClass *module_type;
        MonoReflectionModule *res;
        char* basename;
        
        CHECK_OBJECT (MonoReflectionModule *, image, NULL);
-       if (!System_Reflection_Module)
-               System_Reflection_Module = mono_class_from_name (
-                       mono_defaults.corlib, "System.Reflection", "Module");
-       res = (MonoReflectionModule *)mono_object_new (domain, System_Reflection_Module);
+       if (!module_type) {
+               MonoClass *class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoModule");
+               if (class == NULL)
+                       class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "Module");
+               g_assert (class);
+               module_type = class;
+       }
+       res = (MonoReflectionModule *)mono_object_new (domain, module_type);
 
        res->image = image;
        MONO_OBJECT_SETREF (res, assembly, (MonoReflectionAssembly *) mono_assembly_get_object(domain, image->assembly));
@@ -6177,7 +6186,7 @@ mono_module_get_object   (MonoDomain *domain, MonoImage *image)
 MonoReflectionModule*   
 mono_module_file_get_object (MonoDomain *domain, MonoImage *image, int table_index)
 {
-       static MonoClass *System_Reflection_Module;
+       static MonoClass *module_type;
        MonoReflectionModule *res;
        MonoTableInfo *table;
        guint32 cols [MONO_FILE_SIZE];
@@ -6185,10 +6194,14 @@ mono_module_file_get_object (MonoDomain *domain, MonoImage *image, int table_ind
        guint32 i, name_idx;
        const char *val;
        
-       if (!System_Reflection_Module)
-               System_Reflection_Module = mono_class_from_name (
-                       mono_defaults.corlib, "System.Reflection", "Module");
-       res = (MonoReflectionModule *)mono_object_new (domain, System_Reflection_Module);
+       if (!module_type) {
+               MonoClass *class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoModule");
+               if (class == NULL)
+                       class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "Module");
+               g_assert (class);
+               module_type = class;
+       }
+       res = (MonoReflectionModule *)mono_object_new (domain, module_type);
 
        table = &image->tables [MONO_TABLE_FILE];
        g_assert (table_index < table->rows);
@@ -6385,6 +6398,49 @@ verify_safe_for_managed_space (MonoType *type)
        return TRUE;
 }
 
+static MonoType*
+mono_type_normalize (MonoType *type)
+{
+       int i;
+       MonoGenericClass *gclass;
+       MonoGenericInst *ginst;
+       MonoClass *gtd;
+       MonoGenericContainer *gcontainer;
+       MonoType **argv = NULL;
+       gboolean is_denorm_gtd = TRUE, requires_rebind = FALSE;
+
+       if (type->type != MONO_TYPE_GENERICINST)
+               return type;
+
+       gclass = type->data.generic_class;
+       ginst = gclass->context.class_inst;
+       if (!ginst->is_open)
+               return type;
+
+       gtd = gclass->container_class;
+       gcontainer = gtd->generic_container;
+       argv = g_newa (MonoType*, ginst->type_argc);
+
+       for (i = 0; i < ginst->type_argc; ++i) {
+               MonoType *t = ginst->type_argv [i], *norm;
+               if (t->type != MONO_TYPE_VAR || t->data.generic_param->num != i || t->data.generic_param->owner != gcontainer)
+                       is_denorm_gtd = FALSE;
+               norm = mono_type_normalize (t);
+               argv [i] = norm;
+               if (norm != t)
+                       requires_rebind = TRUE;
+       }
+
+       if (is_denorm_gtd)
+               return type->byref == gtd->byval_arg.byref ? &gtd->byval_arg : &gtd->this_arg;
+
+       if (requires_rebind) {
+               MonoClass *klass = mono_class_bind_generic_parameters (gtd, ginst->type_argc, argv, gclass->is_dynamic);
+               return type->byref == klass->byval_arg.byref ? &klass->byval_arg : &klass->this_arg;
+       }
+
+       return type;
+}
 /*
  * mono_type_get_object:
  * @domain: an app domain
@@ -6395,6 +6451,7 @@ verify_safe_for_managed_space (MonoType *type)
 MonoReflectionType*
 mono_type_get_object (MonoDomain *domain, MonoType *type)
 {
+       MonoType *norm_type;
        MonoReflectionType *res;
        MonoClass *klass = mono_class_from_mono_type (type);
 
@@ -6432,6 +6489,23 @@ mono_type_get_object (MonoDomain *domain, MonoType *type)
                mono_loader_unlock ();
                return res;
        }
+
+       /*Types must be normalized so a generic instance of the GTD get's the same inner type.
+        * For example in: Foo<A,B>; Bar<A> : Foo<A, Bar<A>>
+        * The second Bar will be encoded a generic instance of Bar with <A> as parameter.
+        * On all other places, Bar<A> will be encoded as the GTD itself. This is an implementation
+        * artifact of how generics are encoded and should be transparent to managed code so we
+        * need to weed out this diference when retrieving managed System.Type objects.
+        */
+       norm_type = mono_type_normalize (type);
+       if (norm_type != type) {
+               res = mono_type_get_object (domain, norm_type);
+               mono_g_hash_table_insert (domain->type_hash, type, res);
+               mono_domain_unlock (domain);
+               mono_loader_unlock ();
+               return res;
+       }
+
        /* Create a MonoGenericClass object for instantiations of not finished TypeBuilders */
        if ((type->type == MONO_TYPE_GENERICINST) && type->data.generic_class->is_dynamic && !type->data.generic_class->container_class->wastypebuilder) {
                res = (MonoReflectionType *)mono_generic_class_get_object (domain, type);
@@ -6847,7 +6921,6 @@ mono_method_body_get_object (MonoDomain *domain, MonoMethod *method)
        static MonoClass *System_Reflection_LocalVariableInfo = NULL;
        static MonoClass *System_Reflection_ExceptionHandlingClause = NULL;
        MonoReflectionMethodBody *ret;
-       MonoMethodNormal *mn;
        MonoMethodHeader *header;
        guint32 method_rva, local_var_sig_token;
     char *ptr;
@@ -6868,7 +6941,6 @@ mono_method_body_get_object (MonoDomain *domain, MonoMethod *method)
            (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
            (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME))
                return NULL;
-       mn = (MonoMethodNormal *)method;
        header = mono_method_get_header (method);
        
        /* Obtain local vars signature token */
@@ -6927,8 +6999,8 @@ mono_method_body_get_object (MonoDomain *domain, MonoMethod *method)
                mono_array_setref (ret->clauses, i, info);
        }
 
-       CACHE_OBJECT (MonoReflectionMethodBody *, method, ret, NULL);
        mono_metadata_free_mh (header);
+       CACHE_OBJECT (MonoReflectionMethodBody *, method, ret, NULL);
        return ret;
 }
 
@@ -7260,7 +7332,8 @@ _mono_reflection_parse_type (char *name, char **endptr, gboolean is_recursed,
                                        if (!_mono_reflection_parse_type (p, &p, TRUE, subinfo))
                                                return 0;
 
-                                       if (fqname) {
+                                       /*MS is lenient on [] delimited parameters that aren't fqn - and F# uses them.*/
+                                       if (fqname && (*p != ']')) {
                                                char *aname;
 
                                                if (*p != ',')
@@ -7285,6 +7358,8 @@ _mono_reflection_parse_type (char *name, char **endptr, gboolean is_recursed,
                                                if (!*aname ||
                                                    !assembly_name_to_aname (&subinfo->assembly, aname))
                                                        return 0;
+                                       } else if (fqname && (*p == ']')) {
+                                               *p++ = 0;
                                        }
 
                                        if (i + 1 < arity) {
@@ -7696,11 +7771,11 @@ mono_reflection_get_token (MonoObject *obj)
                g_assert (mono_class_is_reflection_method_or_constructor (member_class));
 
                token = mono_method_get_param_token (((MonoReflectionMethod*)p->MemberImpl)->method, p->PositionImpl);
-       } else if (strcmp (klass->name, "Module") == 0) {
+       } else if (strcmp (klass->name, "Module") == 0 || strcmp (klass->name, "MonoModule") == 0) {
                MonoReflectionModule *m = (MonoReflectionModule*)obj;
 
                token = m->token;
-       } else if (strcmp (klass->name, "Assembly") == 0) {
+       } else if (strcmp (klass->name, "Assembly") == 0 || strcmp (klass->name, "MonoAssembly") == 0) {
                token = mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1);
        } else {
                gchar *msg = g_strdup_printf ("MetadataToken is not supported for type '%s.%s'", klass->name_space, klass->name);
@@ -8061,6 +8136,9 @@ create_custom_attr (MonoImage *image, MonoMethod *method, const guchar *data, gu
 
        mono_class_init (method->klass);
 
+       if (!mono_verifier_verify_cattr_content (image, method, data, len, NULL))
+               return NULL;
+
        if (len == 0) {
                attr = mono_object_new (mono_domain_get (), method->klass);
                mono_runtime_invoke (method, attr, NULL, NULL);
@@ -8161,6 +8239,9 @@ mono_reflection_create_custom_attr_data_args (MonoImage *image, MonoMethod *meth
        guint32 i, j, num_named;
        CattrNamedArg *arginfo = NULL;
 
+       if (!mono_verifier_verify_cattr_content (image, method, data, len, NULL))
+               return;
+
        mono_class_init (method->klass);
 
        *typed_args = NULL;
@@ -8433,6 +8514,14 @@ mono_custom_attrs_from_index (MonoImage *image, guint32 idx)
                        g_free (ainfo);
                        return NULL;
                }
+
+               if (!mono_verifier_verify_cattr_blob (image, cols [MONO_CUSTOM_ATTR_VALUE], NULL)) {
+                       /*FIXME raising an exception here doesn't make any sense*/
+                       g_warning ("Invalid custom attribute blob on image %s for index %x", image->name, idx);
+                       g_list_free (list);
+                       g_free (ainfo);
+                       return NULL;
+               }
                data = mono_metadata_blob_heap (image, cols [MONO_CUSTOM_ATTR_VALUE]);
                ainfo->attrs [i].data_size = mono_metadata_decode_value (data, &data);
                ainfo->attrs [i].data = (guchar*)data;
@@ -8684,10 +8773,10 @@ mono_reflection_get_custom_attrs_info (MonoObject *obj)
                MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
                klass = mono_class_from_mono_type (type);
                cinfo = mono_custom_attrs_from_class (klass);
-       } else if (strcmp ("Assembly", klass->name) == 0) {
+       } else if (strcmp ("Assembly", klass->name) == 0 || strcmp ("MonoAssembly", klass->name) == 0) {
                MonoReflectionAssembly *rassembly = (MonoReflectionAssembly*)obj;
                cinfo = mono_custom_attrs_from_assembly (rassembly->assembly);
-       } else if (strcmp ("Module", klass->name) == 0) {
+       } else if (strcmp ("Module", klass->name) == 0 || strcmp ("MonoModule", klass->name) == 0) {
                MonoReflectionModule *module = (MonoReflectionModule*)obj;
                cinfo = mono_custom_attrs_from_module (module->image);
        } else if (strcmp ("MonoProperty", klass->name) == 0) {
@@ -8719,11 +8808,13 @@ mono_reflection_get_custom_attrs_info (MonoObject *obj)
                        g_assert (method);
 
                        cinfo = mono_custom_attrs_from_param (method, param->PositionImpl + 1);
-               } else if (is_sre_method_on_tb_inst (member_class)) {/*XXX This is a workaround for Compiler Context*/
+               } 
+#ifndef DISABLE_REFLECTION_EMIT
+               else if (is_sre_method_on_tb_inst (member_class)) {/*XXX This is a workaround for Compiler Context*/
                        MonoMethod *method = mono_reflection_method_on_tb_inst_get_handle ((MonoReflectionMethodOnTypeBuilderInst*)param->MemberImpl);
                        cinfo = mono_custom_attrs_from_param (method, param->PositionImpl + 1);
                } else if (is_sre_ctor_on_tb_inst (member_class)) { /*XX This is a workaround for Compiler Context*/
-               MonoReflectionCtorOnTypeBuilderInst *c = (MonoReflectionCtorOnTypeBuilderInst*)param->MemberImpl;
+                       MonoReflectionCtorOnTypeBuilderInst *c = (MonoReflectionCtorOnTypeBuilderInst*)param->MemberImpl;
                        MonoMethod *method = NULL;
                        if (is_sre_ctor_builder (mono_object_class (c->cb)))
                                method = ((MonoReflectionCtorBuilder *)c->cb)->mhandle;
@@ -8733,7 +8824,9 @@ mono_reflection_get_custom_attrs_info (MonoObject *obj)
                                g_error ("mono_reflection_get_custom_attrs_info:: can't handle a CTBI with base_method of type %s", mono_type_get_full_name (member_class));
 
                        cinfo = mono_custom_attrs_from_param (method, param->PositionImpl + 1);
-               } else {
+               } 
+#endif
+               else {
                        char *type_name = mono_type_get_full_name (member_class);
                        char *msg = g_strdup_printf ("Custom attributes on a ParamInfo with member %s are not supported", type_name);
                        MonoException *ex = mono_get_exception_not_supported  (msg);
@@ -8852,7 +8945,6 @@ mono_reflection_type_get_underlying_system_type (MonoReflectionType* t)
         return (MonoReflectionType *) mono_runtime_invoke (usertype_method, t, NULL, NULL);
 }
 
-#ifndef DISABLE_REFLECTION_EMIT
 
 static gboolean
 is_corlib_type (MonoClass *class)
@@ -8871,6 +8963,8 @@ is_corlib_type (MonoClass *class)
        return FALSE; \
 } while (0) \
 
+
+#ifndef DISABLE_REFLECTION_EMIT
 static gboolean
 is_sre_array (MonoClass *class)
 {
@@ -8919,42 +9013,6 @@ is_sre_field_builder (MonoClass *class)
        check_corlib_type_cached (class, "System.Reflection.Emit", "FieldBuilder");
 }
 
-static gboolean
-is_sr_mono_method (MonoClass *class)
-{
-       check_corlib_type_cached (class, "System.Reflection", "MonoMethod");
-}
-
-static gboolean
-is_sr_mono_cmethod (MonoClass *class)
-{
-       check_corlib_type_cached (class, "System.Reflection", "MonoCMethod");
-}
-
-static gboolean
-is_sr_mono_generic_method (MonoClass *class)
-{
-       check_corlib_type_cached (class, "System.Reflection", "MonoGenericMethod");
-}
-
-static gboolean
-is_sr_mono_generic_cmethod (MonoClass *class)
-{
-       check_corlib_type_cached (class, "System.Reflection", "MonoGenericCMethod");
-}
-
-static gboolean
-is_sr_mono_field (MonoClass *class)
-{
-       check_corlib_type_cached (class, "System.Reflection", "MonoField");
-}
-
-static gboolean
-is_sr_mono_property (MonoClass *class)
-{
-       check_corlib_type_cached (class, "System.Reflection", "MonoProperty");
-}
-
 static gboolean
 is_sre_method_on_tb_inst (MonoClass *class)
 {
@@ -8967,12 +9025,6 @@ is_sre_ctor_on_tb_inst (MonoClass *class)
        check_corlib_type_cached (class, "System.Reflection.Emit", "ConstructorOnTypeBuilderInst");
 }
 
-gboolean
-mono_class_is_reflection_method_or_constructor (MonoClass *class)
-{
-       return is_sr_mono_method (class) || is_sr_mono_cmethod (class) || is_sr_mono_generic_method (class) || is_sr_mono_generic_cmethod (class);
-}
-
 MonoType*
 mono_reflection_type_get_handle (MonoReflectionType* ref)
 {
@@ -9192,6 +9244,49 @@ is_sre_generic_instance (MonoClass *class)
 
 #endif /* !DISABLE_REFLECTION_EMIT */
 
+
+static gboolean
+is_sr_mono_field (MonoClass *class)
+{
+       check_corlib_type_cached (class, "System.Reflection", "MonoField");
+}
+
+static gboolean
+is_sr_mono_property (MonoClass *class)
+{
+       check_corlib_type_cached (class, "System.Reflection", "MonoProperty");
+}
+
+static gboolean
+is_sr_mono_method (MonoClass *class)
+{
+       check_corlib_type_cached (class, "System.Reflection", "MonoMethod");
+}
+
+static gboolean
+is_sr_mono_cmethod (MonoClass *class)
+{
+       check_corlib_type_cached (class, "System.Reflection", "MonoCMethod");
+}
+
+static gboolean
+is_sr_mono_generic_method (MonoClass *class)
+{
+       check_corlib_type_cached (class, "System.Reflection", "MonoGenericMethod");
+}
+
+static gboolean
+is_sr_mono_generic_cmethod (MonoClass *class)
+{
+       check_corlib_type_cached (class, "System.Reflection", "MonoGenericCMethod");
+}
+
+gboolean
+mono_class_is_reflection_method_or_constructor (MonoClass *class)
+{
+       return is_sr_mono_method (class) || is_sr_mono_cmethod (class) || is_sr_mono_generic_method (class) || is_sr_mono_generic_cmethod (class);
+}
+
 static gboolean
 is_usertype (MonoReflectionType *ref)
 {
@@ -9776,6 +9871,7 @@ mono_reflection_create_generic_class (MonoReflectionTypeBuilder *tb)
                /*Make sure we are a diferent type instance */
                klass->generic_container->type_params [i].param.owner = klass->generic_container;
                klass->generic_container->type_params [i].info.pklass = NULL;
+               klass->generic_container->type_params [i].info.flags = gparam->attrs;
 
                g_assert (klass->generic_container->type_params [i].param.owner);
        }
@@ -9936,7 +10032,7 @@ reflection_methodbuilder_to_mono_method (MonoClass *klass,
 {
        MonoError error;
        MonoMethod *m;
-       MonoMethodNormal *pm;
+       MonoMethodWrapper *wrapperm;
        MonoMarshalSpec **specs;
        MonoReflectionMethodAux *method_aux;
        MonoImage *image;
@@ -9960,12 +10056,10 @@ reflection_methodbuilder_to_mono_method (MonoClass *klass,
        if ((rmb->attrs & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
                        (rmb->iattrs & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
                m = (MonoMethod *)image_g_new0 (image, MonoMethodPInvoke, 1);
-       else if (rmb->refs)
-               m = (MonoMethod *)image_g_new0 (image, MonoMethodWrapper, 1);
        else
-               m = (MonoMethod *)image_g_new0 (image, MonoMethodNormal, 1);
+               m = (MonoMethod *)image_g_new0 (image, MonoMethodWrapper, 1);
 
-       pm = (MonoMethodNormal*)m;
+       wrapperm = (MonoMethodWrapper*)m;
 
        m->dynamic = dynamic;
        m->slot = -1;
@@ -9975,6 +10069,7 @@ reflection_methodbuilder_to_mono_method (MonoClass *klass,
        g_assert (mono_error_ok (&error));
        m->klass = klass;
        m->signature = sig;
+       m->sre_method = TRUE;
        m->skip_visibility = rmb->skip_visibility;
        if (rmb->table_idx)
                m->token = MONO_TOKEN_METHOD_DEF | (*rmb->table_idx);
@@ -10054,7 +10149,7 @@ reflection_methodbuilder_to_mono_method (MonoClass *klass,
                                 rmb->ilgen, num_clauses);
                }
 
-               pm->header = header;
+               wrapperm->header = header;
        }
 
        if (rmb->generic_params) {
@@ -10676,6 +10771,45 @@ ensure_runtime_vtable (MonoClass *klass)
         */
 }
 
+static MonoMethod*
+mono_reflection_method_get_handle (MonoObject *method)
+{
+       MonoClass *class = mono_object_class (method);
+       if (is_sr_mono_method (class)) {
+               MonoReflectionMethod *sr_method = (MonoReflectionMethod*)method;
+               return sr_method->method;
+       }
+       if (is_sre_method_builder (class)) {
+               MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder*)method;
+               return mb->mhandle;
+       }
+       if (is_sre_method_on_tb_inst (class)) {
+               MonoReflectionMethodOnTypeBuilderInst *m = (MonoReflectionMethodOnTypeBuilderInst*)method;
+               MonoMethod *result;
+               /*FIXME move this to a proper method and unify with resolve_object*/
+               if (m->method_args) {
+                       result = mono_reflection_method_on_tb_inst_get_handle (m);
+               } else {
+                       MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)m->inst);
+                       MonoClass *inflated_klass = mono_class_from_mono_type (type);
+                       MonoMethod *mono_method;
+
+                       if (is_sre_method_builder (mono_object_class (m->mb)))
+                               mono_method = ((MonoReflectionMethodBuilder *)m->mb)->mhandle;
+                       else if (is_sr_mono_method (mono_object_class (m->mb)))
+                               mono_method = ((MonoReflectionMethod *)m->mb)->method;
+                       else
+                               g_error ("resolve_object:: can't handle a MTBI with base_method of type %s", mono_type_get_full_name (mono_object_class (m->mb)));
+
+                       result = inflate_mono_method (inflated_klass, mono_method, (MonoObject*)m->mb);
+               }
+               return result;
+       }
+
+       g_error ("Can't handle methods of type %s:%s", class->name_space, class->name);
+       return NULL;
+}
+
 void
 mono_reflection_get_dynamic_overrides (MonoClass *klass, MonoMethod ***overrides, int *num_overrides)
 {
@@ -10712,13 +10846,9 @@ mono_reflection_get_dynamic_overrides (MonoClass *klass, MonoMethod ***overrides
                        MonoReflectionMethodBuilder *mb = 
                                mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i);
                        if (mb->override_method) {
-                               (*overrides) [onum * 2] = 
-                                       mb->override_method->method;
-                               (*overrides) [onum * 2 + 1] =
-                                       mb->mhandle;
+                               (*overrides) [onum * 2] = mono_reflection_method_get_handle ((MonoObject *)mb->override_method);
+                               (*overrides) [onum * 2 + 1] = mb->mhandle;
 
-                               /* FIXME: What if 'override_method' is a MethodBuilder ? */
-                               g_assert (mb->override_method->method);
                                g_assert (mb->mhandle);
 
                                onum ++;
@@ -10788,6 +10918,9 @@ typebuilder_setup_fields (MonoClass *klass, MonoError *error)
                fb->handle = field;
                mono_save_custom_attrs (klass->image, field, fb->cattrs);
 
+               if (klass->enumtype && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
+                       klass->cast_class = klass->element_class = mono_class_from_mono_type (field->type);
+               }
                if (fb->def_value) {
                        MonoDynamicImage *assembly = (MonoDynamicImage*)klass->image;
                        field->type->attrs |= FIELD_ATTRIBUTE_HAS_DEFAULT;
@@ -11034,6 +11167,11 @@ mono_reflection_create_runtime_class (MonoReflectionTypeBuilder *tb)
        klass->has_cctor = 1;
        klass->has_finalize = 1;
 
+       /* fool mono_class_setup_parent */
+       klass->supertypes = NULL;
+       mono_class_setup_parent (klass, klass->parent);
+       mono_class_setup_mono_type (klass);
+
 #if 0
        if (!((MonoDynamicImage*)klass->image)->run) {
                if (klass->generic_container) {
@@ -11618,6 +11756,8 @@ resolve_object (MonoImage *image, MonoObject *obj, MonoClass **handle_class, Mon
                MonoReflectionMethodOnTypeBuilderInst *m = (MonoReflectionMethodOnTypeBuilderInst*)obj;
                if (m->method_args) {
                        result = mono_reflection_method_on_tb_inst_get_handle (m);
+                       if (context)
+                               result = mono_class_inflate_generic_method (result, context);
                } else {
                        MonoType *type = mono_class_inflate_generic_type (mono_reflection_type_get_handle ((MonoReflectionType*)m->inst), context);
                        MonoClass *inflated_klass = mono_class_from_mono_type (type);
index 50e0d84eafa1d029ce67705ff9556aa074c72788..4c0307d8c1dab1db387752e06d66a34a886a04c4 100644 (file)
@@ -5,7 +5,7 @@
  *     Mark Probst <mark.probst@gmail.com>
  *     Sebastien Pouliot  <sebastien@ximian.com>
  *
- * Copyright 2007-2009 Novell, Inc (http://www.novell.com)
+ * Copyright 2007-2010 Novell, Inc (http://www.novell.com)
  */
 
 #include <mono/metadata/class-internals.h>
@@ -15,6 +15,8 @@
 #include <mono/metadata/verify-internals.h>
 #include <mono/metadata/object.h>
 #include <mono/metadata/exception.h>
+#include <mono/metadata/debug-helpers.h>
+#include <mono/utils/mono-logger-internal.h>
 
 #include "security-core-clr.h"
 
@@ -46,6 +48,81 @@ security_safe_critical_attribute (void)
        return class;
 }
 
+/*
+ * set_type_load_exception_type
+ *
+ *     Set MONO_EXCEPTION_TYPE_LOAD on the specified 'class' and provide
+ *     a descriptive message for the exception. This message is also, 
+ *     optionally, being logged (export MONO_LOG_MASK="security") for
+ *     debugging purposes.
+ */
+static void
+set_type_load_exception_type (const char *format, MonoClass *class)
+{
+       char *type_name = mono_type_get_full_name (class);
+       char *parent_name = mono_type_get_full_name (class->parent);
+       char *message = g_strdup_printf (format, type_name, parent_name);
+
+       g_free (parent_name);
+       g_free (type_name);
+       
+       mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, message);
+       mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, message);
+       // note: do not free string given to mono_class_set_failure
+}
+
+/*
+ * set_type_load_exception_methods
+ *
+ *     Set MONO_EXCEPTION_TYPE_LOAD on the 'override' class and provide
+ *     a descriptive message for the exception. This message is also, 
+ *     optionally, being logged (export MONO_LOG_MASK="security") for
+ *     debugging purposes.
+ */
+static void
+set_type_load_exception_methods (const char *format, MonoMethod *override, MonoMethod *base)
+{
+       char *method_name = mono_method_full_name (override, TRUE);
+       char *base_name = mono_method_full_name (base, TRUE);
+       char *message = g_strdup_printf (format, method_name, base_name);
+
+       g_free (base_name);
+       g_free (method_name);
+
+       mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, message);
+       mono_class_set_failure (override->klass, MONO_EXCEPTION_TYPE_LOAD, message);
+       // note: do not free string given to mono_class_set_failure
+}
+
+/* MonoClass is not fully initialized (inited is not yet == 1) when we 
+ * check the inheritance rules so we need to look for the default ctor
+ * ourselve to avoid recursion (and aborting)
+ */
+static MonoMethod*
+get_default_ctor (MonoClass *klass)
+{
+       int i;
+
+       mono_class_setup_methods (klass);
+       if (!klass->methods)
+               return NULL;
+
+       for (i = 0; i < klass->method.count; ++i) {
+               MonoMethodSignature *sig;
+               MonoMethod *method = klass->methods [i];
+
+               if ((method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) == 0)
+                       continue;
+               if ((method->name[0] != '.') || strcmp (".ctor", method->name))
+                       continue;
+               sig = mono_method_signature (method);
+               if (sig && (sig->param_count == 0))
+                       return method;
+       }
+
+       return NULL;
+}
+
 /*
  * mono_security_core_clr_check_inheritance:
  *
@@ -59,6 +136,12 @@ security_safe_critical_attribute (void)
  *     Critical        Critical
  *
  *     Reference: http://msdn.microsoft.com/en-us/magazine/cc765416.aspx#id0190030
+ *
+ *     Furthermore a class MUST have a default constructor if its base 
+ *     class has a non-transparent default constructor. The same 
+ *     inheritance rule applies to both default constructors.
+ *
+ *     Reference: message from a SecurityException in SL4RC
  */
 void
 mono_security_core_clr_check_inheritance (MonoClass *class)
@@ -72,8 +155,19 @@ mono_security_core_clr_check_inheritance (MonoClass *class)
        class_level = mono_security_core_clr_class_level (class);
        parent_level = mono_security_core_clr_class_level (parent);
 
-       if (class_level < parent_level)
-               mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
+       if (class_level < parent_level) {
+               set_type_load_exception_type (
+                       "Inheritance failure for type %s. Parent class %s is more restricted.",
+                       class);
+       } else {
+               class_level = mono_security_core_clr_method_level (get_default_ctor (class), FALSE);
+               parent_level = mono_security_core_clr_method_level (get_default_ctor (parent), FALSE);
+               if (class_level < parent_level) {
+                       set_type_load_exception_type (
+                               "Inheritance failure for type %s. Default constructor security mismatch with %s.",
+                               class);
+               }
+       }
 }
 
 /*
@@ -97,12 +191,18 @@ mono_security_core_clr_check_override (MonoClass *class, MonoMethod *override, M
        MonoSecurityCoreCLRLevel override_level = mono_security_core_clr_method_level (override, FALSE);
        /* if the base method is decorated with [SecurityCritical] then the overrided method MUST be too */
        if (base_level == MONO_SECURITY_CORE_CLR_CRITICAL) {
-               if (override_level != MONO_SECURITY_CORE_CLR_CRITICAL)
-                       mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               if (override_level != MONO_SECURITY_CORE_CLR_CRITICAL) {
+                       set_type_load_exception_methods (
+                               "Override failure for %s over %s. Override MUST be [SecurityCritical].",
+                               override, base);
+               }
        } else {
                /* base is [SecuritySafeCritical] or [SecurityTransparent], override MUST NOT be [SecurityCritical] */
-               if (override_level == MONO_SECURITY_CORE_CLR_CRITICAL)
-                       mono_class_set_failure (class, MONO_EXCEPTION_TYPE_LOAD, NULL);
+               if (override_level == MONO_SECURITY_CORE_CLR_CRITICAL) {
+                       set_type_load_exception_methods (
+                               "Override failure for %s over %s. Override must NOT be [SecurityCritical].", 
+                               override, base);
+               }
        }
 }
 
@@ -188,7 +288,7 @@ get_caller_no_reflection_related (MonoMethod *m, gint32 no, gint32 ilo, gboolean
  * 
  *     Walk to the first managed method outside:
  *     - System.Reflection* namespaces
- *     - System.[MulticastDelegate]Delegate or Activator type
+ *     - System.[Multicast]Delegate or Activator type
  *     - platform code
  *     and return a pointer to its MonoMethod.
  *
@@ -199,11 +299,101 @@ get_reflection_caller (void)
 {
        MonoMethod *m = NULL;
        mono_stack_walk_no_il (get_caller_no_reflection_related, &m);
-       if (!m)
-               g_warning ("could not find a caller outside reflection");
+       if (G_UNLIKELY (!m)) {
+               mono_trace (G_LOG_LEVEL_ERROR, MONO_TRACE_SECURITY, "No caller outside reflection was found");
+       }
        return m;
 }
 
+typedef struct {
+       int depth;
+       MonoMethod *caller;
+} ElevatedTrustCookie;
+
+/*
+ * get_caller_of_elevated_trust_code
+ *
+ *     Stack walk to find who is calling code requiring Elevated Trust.
+ *     If a critical method is found then the caller is platform code
+ *     and has elevated trust, otherwise (transparent) a check needs to
+ *     be done (on the managed side) to determine if the application is
+ *     running with elevated permissions.
+ */
+static gboolean
+get_caller_of_elevated_trust_code (MonoMethod *m, gint32 no, gint32 ilo, gboolean managed, gpointer data)
+{
+       ElevatedTrustCookie *cookie = data;
+
+       /* skip unmanaged frames and wrappers */
+       if (!managed || (m->wrapper_type != MONO_WRAPPER_NONE))
+               return FALSE;
+
+       /* end stack walk if we find ourselves outside platform code (we won't find critical code anymore) */
+       if (!mono_security_core_clr_is_platform_image (m->klass->image)) {
+               cookie->caller = m;
+               return TRUE;
+       }
+
+       switch (cookie->depth) {
+       /* while depth == 0 look for SecurityManager::[Check|Ensure]ElevatedPermissions */
+       case 0:
+               if (strcmp (m->klass->name_space, "System.Security"))
+                       return FALSE;
+               if (strcmp (m->klass->name, "SecurityManager"))
+                       return FALSE;
+               if ((strcmp (m->name, "EnsureElevatedPermissions")) && strcmp (m->name, "CheckElevatedPermissions"))
+                       return FALSE;
+               cookie->depth = 1;
+               break;
+       /* while depth == 1 look for the caller to SecurityManager::[Check|Ensure]ElevatedPermissions */
+       case 1:
+               /* this frame is [SecuritySafeCritical] because it calls [SecurityCritical] [Check|Ensure]ElevatedPermissions */
+               /* the next frame will contain the caller(s) we want to check */
+               cookie->depth = 2;
+               break;
+       /* while depth >= 2 look for [safe]critical caller, end stack walk if we find it  */
+       default:
+               cookie->depth++;
+               /* if the caller is transparent then we continue the stack walk */
+               if (mono_security_core_clr_method_level (m, TRUE) == MONO_SECURITY_CORE_CLR_TRANSPARENT)
+                       break;
+
+               /* Security[Safe]Critical code is always allowed to call elevated-trust code */
+               cookie->caller = m;
+               return TRUE;
+       }
+
+       return FALSE;
+}
+
+/*
+ * mono_security_core_clr_require_elevated_permissions:
+ *
+ *     Return TRUE if the caller of the current method (the code who 
+ *     called SecurityManager.get_RequiresElevatedPermissions) needs
+ *     elevated trust to perform an action.
+ *
+ *     A stack walk is done to find the callers. If one of the callers
+ *     is either [SecurityCritical] or [SecuritySafeCritical] then the
+ *     action is needed for platform code (i.e. no restriction). 
+ *     Otherwise (transparent) the requested action needs elevated trust
+ */
+gboolean
+mono_security_core_clr_require_elevated_permissions (void)
+{
+       ElevatedTrustCookie cookie;
+       cookie.depth = 0;
+       cookie.caller = NULL;
+       mono_stack_walk_no_il (get_caller_of_elevated_trust_code, &cookie);
+
+       /* return TRUE if the stack walk did not reach far enough or did not find callers */
+       if (!cookie.caller || cookie.depth < 3)
+               return TRUE;
+
+       /* return TRUE if the caller is transparent, i.e. if elevated trust is required to continue executing the method */
+       return (mono_security_core_clr_method_level (cookie.caller, TRUE) == MONO_SECURITY_CORE_CLR_TRANSPARENT);
+}
+
 /*
  * check_field_access:
  *
@@ -236,6 +426,81 @@ check_method_access (MonoMethod *caller, MonoMethod *callee)
        return FALSE;
 }
 
+/*
+ * get_argument_exception
+ *
+ *     Helper function to create an MonoException (ArgumentException in
+ *     managed-land) and provide a descriptive message for it. This 
+ *     message is also, optionally, being logged (export 
+ *     MONO_LOG_MASK="security") for debugging purposes.
+ */
+static MonoException*
+get_argument_exception (const char *format, MonoMethod *caller, MonoMethod *callee)
+{
+       MonoException *ex;
+       char *caller_name = mono_method_full_name (caller, TRUE);
+       char *callee_name = mono_method_full_name (callee, TRUE);
+       char *message = g_strdup_printf (format, caller_name, callee_name);
+       g_free (callee_name);
+       g_free (caller_name);
+
+       mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, message);
+       ex = mono_get_exception_argument ("method", message);
+       g_free (message);
+
+       return ex;
+}
+
+/*
+ * get_field_access_exception
+ *
+ *     Helper function to create an MonoException (FieldAccessException
+ *     in managed-land) and provide a descriptive message for it. This
+ *     message is also, optionally, being logged (export 
+ *     MONO_LOG_MASK="security") for debugging purposes.
+ */
+static MonoException*
+get_field_access_exception (const char *format, MonoMethod *caller, MonoClassField *field)
+{
+       MonoException *ex;
+       char *caller_name = mono_method_full_name (caller, TRUE);
+       char *field_name = mono_field_full_name (field);
+       char *message = g_strdup_printf (format, caller_name, field_name);
+       g_free (field_name);
+       g_free (caller_name);
+
+       mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, message);
+       ex = mono_get_exception_field_access_msg (message);
+       g_free (message);
+
+       return ex;
+}
+
+/*
+ * get_method_access_exception
+ *
+ *     Helper function to create an MonoException (MethodAccessException
+ *     in managed-land) and provide a descriptive message for it. This
+ *     message is also, optionally, being logged (export 
+ *     MONO_LOG_MASK="security") for debugging purposes.
+ */
+static MonoException*
+get_method_access_exception (const char *format, MonoMethod *caller, MonoMethod *callee)
+{
+       MonoException *ex;
+       char *caller_name = mono_method_full_name (caller, TRUE);
+       char *callee_name = mono_method_full_name (callee, TRUE);
+       char *message = g_strdup_printf (format, caller_name, callee_name);
+       g_free (callee_name);
+       g_free (caller_name);
+
+       mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_SECURITY, message);
+       ex = mono_get_exception_method_access_msg (message);
+       g_free (message);
+
+       return ex;
+}
+
 /*
  * mono_security_core_clr_ensure_reflection_access_field:
  *
@@ -254,12 +519,18 @@ mono_security_core_clr_ensure_reflection_access_field (MonoClassField *field)
                return;
 
        /* Transparent code cannot [get|set]value on Critical fields */
-       if (mono_security_core_clr_class_level (mono_field_get_parent (field)) == MONO_SECURITY_CORE_CLR_CRITICAL)
-               mono_raise_exception (mono_get_exception_field_access ());
+       if (mono_security_core_clr_class_level (mono_field_get_parent (field)) == MONO_SECURITY_CORE_CLR_CRITICAL) {
+               mono_raise_exception (get_field_access_exception (
+                       "Transparent method %s cannot get or set Critical field %s.", 
+                       caller, field));
+       }
 
        /* also it cannot access a fields that is not visible from it's (caller) point of view */
-       if (!check_field_access (caller, field))
-               mono_raise_exception (mono_get_exception_field_access ());
+       if (!check_field_access (caller, field)) {
+               mono_raise_exception (get_field_access_exception (
+                       "Transparent method %s cannot get or set private/internal field %s.", 
+                       caller, field));
+       }
 }
 
 /*
@@ -280,12 +551,18 @@ mono_security_core_clr_ensure_reflection_access_method (MonoMethod *method)
                return;
 
        /* Transparent code cannot invoke, even using reflection, Critical code */
-       if (mono_security_core_clr_method_level (method, TRUE) == MONO_SECURITY_CORE_CLR_CRITICAL)
-               mono_raise_exception (mono_get_exception_method_access ());
+       if (mono_security_core_clr_method_level (method, TRUE) == MONO_SECURITY_CORE_CLR_CRITICAL) {
+               mono_raise_exception (get_method_access_exception (
+                       "Transparent method %s cannot invoke Critical method %s.", 
+                       caller, method));
+       }
 
        /* also it cannot invoke a method that is not visible from it's (caller) point of view */
-       if (!check_method_access (caller, method))
-               mono_raise_exception (mono_get_exception_method_access ());
+       if (!check_method_access (caller, method)) {
+               mono_raise_exception (get_method_access_exception (
+                       "Transparent method %s cannot invoke private/internal method %s.", 
+                       caller, method));
+       }
 }
 
 /*
@@ -351,12 +628,17 @@ mono_security_core_clr_ensure_delegate_creation (MonoMethod *method, gboolean th
                if (!throwOnBindFailure)
                        return FALSE;
 
-               mono_raise_exception (mono_get_exception_argument ("method", "Transparent code cannot call Critical code"));
+               mono_raise_exception (get_argument_exception (
+                       "Transparent method %s cannot create a delegate on Critical method %s.", 
+                       caller, method));
        }
        
        /* also it cannot create the delegate on a method that is not visible from it's (caller) point of view */
-       if (!check_method_access (caller, method))
-               mono_raise_exception (mono_get_exception_method_access ());
+       if (!check_method_access (caller, method)) {
+               mono_raise_exception (get_method_access_exception (
+                       "Transparent method %s cannot create a delegate on private/internal method %s.", 
+                       caller, method));
+       }
 
        return TRUE;
 }
@@ -380,8 +662,11 @@ mono_security_core_clr_ensure_dynamic_method_resolved_object (gpointer ref, Mono
                if (mono_security_core_clr_is_platform_image (klass->image)) {
                        MonoMethod *caller = get_reflection_caller ();
                        /* XXX Critical code probably can do this / need some test cases (safer off otherwise) XXX */
-                       if (!check_field_access (caller, field))
-                               return mono_get_exception_field_access ();
+                       if (!check_field_access (caller, field)) {
+                               return get_field_access_exception (
+                                       "Dynamic method %s cannot create access private/internal field %s.", 
+                                       caller, field);
+                       }
                }
        } else if (handle_class == mono_defaults.methodhandle_class) {
                MonoMethod *method = (MonoMethod*) ref;
@@ -389,8 +674,11 @@ mono_security_core_clr_ensure_dynamic_method_resolved_object (gpointer ref, Mono
                if (mono_security_core_clr_is_platform_image (method->klass->image)) {
                        MonoMethod *caller = get_reflection_caller ();
                        /* XXX Critical code probably can do this / need some test cases (safer off otherwise) XXX */
-                       if (!check_method_access (caller, method))
-                               return mono_get_exception_method_access ();
+                       if (!check_method_access (caller, method)) {
+                               return get_method_access_exception (
+                                       "Dynamic method %s cannot create access private/internal method %s.", 
+                                       caller, method);
+                       }
                }
        }
        return NULL;
@@ -423,6 +711,54 @@ mono_security_core_clr_can_access_internals (MonoImage *accessing, MonoImage* ac
        return (strcmp (accessed->assembly->basedir, accessing->assembly->basedir) == 0);
 }
 
+/*
+ * mono_security_core_clr_is_field_access_allowed
+ *
+ *     Return a MonoException (FieldccessException in managed-land) if
+ *     the access from "caller" to "field" is not valid under CoreCLR -
+ *     i.e. a [SecurityTransparent] method calling a [SecurityCritical]
+ *     field.
+ */
+MonoException*
+mono_security_core_clr_is_field_access_allowed (MonoMethod *caller, MonoClassField *field)
+{
+       /* there's no restriction to access Transparent or SafeCritical fields, so we only check calls to Critical methods */
+       if (mono_security_core_clr_class_level (mono_field_get_parent (field)) != MONO_SECURITY_CORE_CLR_CRITICAL)
+               return NULL;
+
+       /* caller is Critical! only SafeCritical and Critical callers can access the field, so we throw if caller is Transparent */
+       if (!caller || (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT))
+               return NULL;
+
+       return get_field_access_exception (
+               "Transparent method %s cannot call use Critical field %s.", 
+               caller, field);
+}
+
+/*
+ * mono_security_core_clr_is_call_allowed
+ *
+ *     Return a MonoException (MethodAccessException in managed-land) if
+ *     the call from "caller" to "callee" is not valid under CoreCLR -
+ *     i.e. a [SecurityTransparent] method calling a [SecurityCritical]
+ *     method.
+ */
+MonoException*
+mono_security_core_clr_is_call_allowed (MonoMethod *caller, MonoMethod *callee)
+{
+       /* there's no restriction to call Transparent or SafeCritical code, so we only check calls to Critical methods */
+       if (mono_security_core_clr_method_level (callee, TRUE) != MONO_SECURITY_CORE_CLR_CRITICAL)
+               return NULL;
+
+       /* callee is Critical! only SafeCritical and Critical callers can call it, so we throw if the caller is Transparent */
+       if (!caller || (mono_security_core_clr_method_level (caller, TRUE) != MONO_SECURITY_CORE_CLR_TRANSPARENT))
+               return NULL;
+
+       return get_method_access_exception (
+               "Transparent method %s cannot call Critical method %s.", 
+               caller, callee);
+}
+
 /*
  * mono_security_core_clr_level_from_cinfo:
  *
index 6f49e380c2d5338123b153c3b332c3c15ff3cbe0..323aeb28c0d397bd8063b79f2b1d8f30417ceb40 100644 (file)
@@ -4,7 +4,7 @@
  * Author:
  *     Mark Probst <mark.probst@gmail.com>
  *
- * (C) 2007 Novell, Inc
+ * (C) 2007, 2010 Novell, Inc
  */
 
 #ifndef _MONO_METADATA_SECURITY_CORE_CLR_H_
@@ -32,10 +32,15 @@ extern MonoException* mono_security_core_clr_ensure_dynamic_method_resolved_obje
 
 extern gboolean mono_security_core_clr_can_access_internals (MonoImage *accessing, MonoImage* accessed) MONO_INTERNAL;
 
+extern MonoException* mono_security_core_clr_is_field_access_allowed (MonoMethod *caller, MonoClassField *field) MONO_INTERNAL;
+extern MonoException* mono_security_core_clr_is_call_allowed (MonoMethod *caller, MonoMethod *callee) MONO_INTERNAL;
+
 extern MonoSecurityCoreCLRLevel mono_security_core_clr_class_level (MonoClass *class) MONO_INTERNAL;
 extern MonoSecurityCoreCLRLevel mono_security_core_clr_method_level (MonoMethod *method, gboolean with_class_level) MONO_INTERNAL;
 
 extern gboolean mono_security_core_clr_is_platform_image (MonoImage *image) MONO_INTERNAL;
 extern gboolean mono_security_core_clr_determine_platform_image (MonoImage *image) MONO_INTERNAL;
 
+extern gboolean mono_security_core_clr_require_elevated_permissions (void);
+
 #endif /* _MONO_METADATA_SECURITY_CORE_CLR_H_ */
index 1a0b07a82ec4e41ebd703858f541e294435c970a..fcf93fd19ae1e7132944b42eefab13be5df3e0c4 100644 (file)
@@ -1,3 +1,28 @@
+/*
+ * SGen is licensed under the terms of the MIT X11 license
+ *
+ * Copyright 2001-2003 Ximian, Inc
+ * Copyright 2003-2010 Novell, Inc.
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
 #ifndef __MONO_SGENARCHDEP_H__
 #define __MONO_SGENARCHDEP_H__
 
index 89a1803443f5fa51fab514a9c3c42c87b3002bac..3477cfbf77ccc1a78ded63886d4411b952555cab 100644 (file)
@@ -4,7 +4,7 @@
  * Author:
  *     Paolo Molaro (lupus@ximian.com)
  *
- * Copyright 2005-2009 Novell, Inc (http://www.novell.com)
+ * Copyright 2005-2010 Novell, Inc (http://www.novell.com)
  *
  * Thread start/stop adapted from Boehm's GC:
  * Copyright (c) 1994 by Xerox Corporation.  All rights reserved.
  * provided the above notices are retained, and a notice that the code was
  * modified is included with the above copyright notice.
  *
- * All the rest of the code is LGPL.
+ *
+ * Copyright 2001-2003 Ximian, Inc
+ * Copyright 2003-2010 Novell, Inc.
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
  *
  * Important: allocation provides always zeroed memory, having to do
  * a memset after allocation is deadly for performance.
  * 1) 2-word header with no GC pointers in it (first vtable, second to store the
  *    forwarding ptr)
  * 2) gc descriptor is the second word in the vtable (first word in the class)
- * 3) 8 byte alignment is the minimum and enough (not true for special structures, FIXME)
+ * 3) 8 byte alignment is the minimum and enough (not true for special structures (SIMD), FIXME)
  * 4) there is a function to get an object's size and the number of
  *    elements in an array.
  * 5) we know the special way bounds are allocated for complex arrays
+ * 6) we know about proxies and how to treat them when domains are unloaded
  *
  * Always try to keep stack usage to a minimum: no recursive behaviour
  * and no large stack allocs.
@@ -48,7 +71,9 @@
  * When the nursery is full we start a nursery collection: this is performed with a
  * copying GC.
  * When the old generation is full we start a copying GC of the old generation as well:
- * this will be changed to mark/compact in the future.
+ * this will be changed to mark&sweep with copying when fragmentation becomes to severe
+ * in the future.  Maybe we'll even do both during the same collection like IMMIX.
+ *
  * The things that complicate this description are:
  * *) pinned objects: we can't move them so we need to keep track of them
  * *) no precise info of the thread stacks and registers: we need to be able to
 
 /*
  * TODO:
- *) change the jit to emit write barrier calls when needed (we
-  can have specialized write barriers): done with icalls, still need to
-  use some specialized barriers
+
  *) we could have a function pointer in MonoClass to implement
   customized write barriers for value types
- *) the write barrier code could be isolated in a couple of functions: when a
-  thread is stopped if it's inside the barrier it is let go again
-  until we stop outside of them (not really needed, see below GC-safe points)
+
  *) investigate the stuff needed to advance a thread to a GC-safe
-  point (single-stepping, read from unmapped memory etc) and implement it
-  Not needed yet: since we treat the objects reachable from the stack/regs as
-  roots, we store the ptr and exec the write barrier so there is no race.
-  We may need this to solve the issue with setting the length of arrays and strings.
+  point (single-stepping, read from unmapped memory etc) and implement it.
+  This would enable us to inline allocations and write barriers, for example,
+  or at least parts of them, like the write barrier checks.
   We may need this also for handling precise info on stacks, even simple things
   as having uninitialized data on the stack and having to wait for the prolog
   to zero it. Not an issue for the last frame that we scan conservatively.
   We could always not trust the value in the slots anyway.
- *) make the jit info table lock free
+
  *) modify the jit to save info about references in stack locations:
   this can be done just for locals as a start, so that at least
   part of the stack is handled precisely.
- *) Make the debug printf stuff thread and signal safe.
- *) test/fix 64 bit issues
+
  *) test/fix endianess issues
- *) port to non-Linux
- *) add batch moving profile info
- *) add more timing info
- *) there is a possible race when an array or string is created: the vtable is set,
-    but the length is set only later so if the GC needs to scan the object in that window,
-    it won't get the correct size for the object. The object can't have references and it will
-    be pinned, but a free memory fragment may be created that overlaps with it.
-    We should change the array max_length field to be at the same offset as the string length:
-    this way we can have a single special alloc function for them that sets the length.
-    Multi-dim arrays have the same issue for rank == 1 for the bounds data.
- *) implement a card table as the write barrier instead of remembered sets?
- *) some sort of blacklist support?
- *) fin_ready_list and critical_fin_list are part of the root set, too
- *) consider lowering the large object min size to 16/32KB or so and benchmark
- *) once mark-compact is implemented we could still keep the
-    copying collector for the old generation and use it if we think
-    it is better (small heaps and no pinning object in the old
-    generation)
-  *) avoid the memory store from copy_object when not needed.
-  *) optimize the write barriers fastpath to happen in managed code
+
+ *) Implement a card table as the write barrier instead of remembered
+    sets?  Card tables are not easy to implement with our current
+    memory layout.  We have several different kinds of major heap
+    objects: Small objects in regular blocks, small objects in pinned
+    chunks and LOS objects.  If we just have a pointer we have no way
+    to tell which kind of object it points into, therefore we cannot
+    know where its card table is.  The least we have to do to make
+    this happen is to get rid of write barriers for indirect stores.
+    (See next item)
+
+ *) Get rid of write barriers for indirect stores.  We can do this by
+    telling the GC to wbarrier-register an object once we do an ldloca
+    or ldelema on it, and to unregister it once it's not used anymore
+    (it can only travel downwards on the stack).  The problem with
+    unregistering is that it needs to happen eventually no matter
+    what, even if exceptions are thrown, the thread aborts, etc.
+    Rodrigo suggested that we could do only the registering part and
+    let the collector find out (pessimistically) when it's safe to
+    unregister, namely when the stack pointer of the thread that
+    registered the object is higher than it was when the registering
+    happened.  This might make for a good first implementation to get
+    some data on performance.
+
+ *) Some sort of blacklist support?  Blacklists is a concept from the
+    Boehm GC: if during a conservative scan we find pointers to an
+    area which we might use as heap, we mark that area as unusable, so
+    pointer retention by random pinning pointers is reduced.
+
+ *) experiment with max small object size (very small right now - 2kb,
+    because it's tied to the max freelist size)
+
   *) add an option to mmap the whole heap in one chunk: it makes for many
      simplifications in the checks (put the nursery at the top and just use a single
      check for inclusion/exclusion): the issue this has is that on 32 bit systems it's
      back to the system (mprotect(PROT_NONE) will still keep the memory allocated if it
      was written to, munmap is needed, but the following mmap may not find the same segment
      free...)
-   *) memzero the fragments after restarting the world and optionally a smaller chunk at a time
-   *) an additional strategy to realloc/expand the nursery when fully pinned is to start
-      allocating objects in the old generation. This means that we can't optimize away write
-      barrier calls in ctors (but that is not valid for other reasons, too).
-   *) add write barriers to the Clone methods
+
+ *) memzero the major fragments after restarting the world and optionally a smaller
+    chunk at a time
+
+ *) investigate having fragment zeroing threads
+
+ *) separate locks for finalization and other minor stuff to reduce
+    lock contention
+
+ *) try a different copying order to improve memory locality
+
+ *) a thread abort after a store but before the write barrier will
+    prevent the write barrier from executing
+
+ *) specialized dynamically generated markers/copiers
+
+ *) Dynamically adjust TLAB size to the number of threads.  If we have
+    too many threads that do allocation, we might need smaller TLABs,
+    and we might get better performance with larger TLABs if we only
+    have a handful of threads.  We could sum up the space left in all
+    assigned TLABs and if that's more than some percentage of the
+    nursery size, reduce the TLAB size.
+
  */
 #include "config.h"
 #ifdef HAVE_SGEN_GC
 #include <signal.h>
 #include <errno.h>
 #include <assert.h>
+#include <pthread.h>
 #include "metadata/metadata-internals.h"
 #include "metadata/class-internals.h"
 #include "metadata/gc-internal.h"
@@ -185,7 +235,7 @@ static gboolean xdomain_checks = FALSE;
 /* If not null, dump the heap after each collection into this file */
 static FILE *heap_dump_file = NULL;
 /* If set, mark stacks conservatively, even if precise marking is possible */
-static gboolean conservative_stack_mark = FALSE;
+static gboolean conservative_stack_mark = TRUE;
 /* If set, do a plausibility check on the scan_starts before and after
    each collection */
 static gboolean do_scan_starts_check = FALSE;
@@ -204,7 +254,10 @@ static gboolean do_scan_starts_check = FALSE;
 
 #ifdef HEAVY_STATISTICS
 static long stat_objects_alloced = 0;
+static long stat_bytes_alloced = 0;
 static long stat_objects_alloced_degraded = 0;
+static long stat_bytes_alloced_degraded = 0;
+static long stat_bytes_alloced_los = 0;
 static long stat_copy_object_called_nursery = 0;
 static long stat_objects_copied_nursery = 0;
 static long stat_copy_object_called_major = 0;
@@ -236,6 +289,27 @@ static int stat_wbarrier_value_copy = 0;
 static int stat_wbarrier_object_copy = 0;
 #endif
 
+static long time_minor_pre_collection_fragment_clear = 0;
+static long time_minor_pinning = 0;
+static long time_minor_scan_remsets = 0;
+static long time_minor_scan_pinned = 0;
+static long time_minor_scan_registered_roots = 0;
+static long time_minor_scan_thread_data = 0;
+static long time_minor_finish_gray_stack = 0;
+static long time_minor_fragment_creation = 0;
+
+static long time_major_pre_collection_fragment_clear = 0;
+static long time_major_pinning = 0;
+static long time_major_scan_pinned = 0;
+static long time_major_scan_registered_roots = 0;
+static long time_major_scan_thread_data = 0;
+static long time_major_scan_alloc_pinned = 0;
+static long time_major_scan_finalized = 0;
+static long time_major_scan_big_objects = 0;
+static long time_major_finish_gray_stack = 0;
+static long time_major_sweep = 0;
+static long time_major_fragment_creation = 0;
+
 static long pinned_chunk_bytes_alloced = 0;
 static long large_internal_bytes_alloced = 0;
 
@@ -254,6 +328,8 @@ enum {
        INTERNAL_MEM_REMSET,
        INTERNAL_MEM_GRAY_QUEUE,
        INTERNAL_MEM_STORE_REMSET,
+       INTERNAL_MEM_MS_TABLES,
+       INTERNAL_MEM_MS_BLOCK_INFO,
        INTERNAL_MEM_MAX
 };
 
@@ -267,12 +343,18 @@ mono_gc_flush_info (void)
 }
 */
 
-#define MAX_DEBUG_LEVEL 8
+#define MAX_DEBUG_LEVEL 2
 #define DEBUG(level,a) do {if (G_UNLIKELY ((level) <= MAX_DEBUG_LEVEL && (level) <= gc_debug_level)) a;} while (0)
 
+/* Define this to allow the user to change some of the constants by specifying
+ * their values in the MONO_GC_PARAMS environmental variable. See
+ * mono_gc_base_init for details. */
+#define USER_CONFIG 1
+
 #define TV_DECLARE(name) gint64 name
 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
 #define TV_ELAPSED(start,end) (int)((end-start) / 10)
+#define TV_ELAPSED_MS(start,end) ((TV_ELAPSED((start),(end)) + 500) / 1000)
 
 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
 
@@ -330,9 +412,8 @@ typedef struct _LOSObject LOSObject;
 struct _LOSObject {
        LOSObject *next;
        mword size; /* this is the object size */
-       int dummy; /* to have a sizeof (LOSObject) a multiple of ALLOC_ALIGN  and data starting at same alignment */
        guint16 role;
-       guint16 scanned;
+       int dummy; /* to have a sizeof (LOSObject) a multiple of ALLOC_ALIGN  and data starting at same alignment */
        char data [MONO_ZERO_LEN_ARRAY];
 };
 
@@ -482,7 +563,6 @@ static __thread RememberedSet *remembered_set MONO_TLS_FAST;
 static pthread_key_t remembered_set_key;
 static RememberedSet *global_remset;
 static RememberedSet *freed_thread_remsets;
-//static int store_to_global_remset = 0;
 static GenericStoreRememberedSet *generic_store_remsets = NULL;
 
 /* FIXME: later choose a size that takes into account the RememberedSet struct
@@ -578,16 +658,27 @@ static int gc_disabled = 0;
 static int num_minor_gcs = 0;
 static int num_major_gcs = 0;
 
+#ifdef USER_CONFIG
+
 /* good sizes are 512KB-1MB: larger ones increase a lot memzeroing time */
-//#define DEFAULT_NURSERY_SIZE (1024*512*125+4096*118)
-#define DEFAULT_NURSERY_SIZE (1024*512*2)
+#define DEFAULT_NURSERY_SIZE (default_nursery_size)
+static int default_nursery_size = (1 << 20);
+#ifdef ALIGN_NURSERY
 /* The number of trailing 0 bits in DEFAULT_NURSERY_SIZE */
+#define DEFAULT_NURSERY_BITS (default_nursery_bits)
+static int default_nursery_bits = 20;
+#endif
+
+#else
+
+#define DEFAULT_NURSERY_SIZE (1024*512*2)
+#ifdef ALIGN_NURSERY
 #define DEFAULT_NURSERY_BITS 20
-#define MAJOR_SECTION_SIZE     (128*1024)
-#define BLOCK_FOR_OBJECT(o)            ((Block*)(((mword)(o)) & ~(MAJOR_SECTION_SIZE - 1)))
-#define MAJOR_SECTION_FOR_OBJECT(o)    ((GCMemSection*)BLOCK_FOR_OBJECT ((o)))
-#define MIN_MINOR_COLLECTION_SECTION_ALLOWANCE (DEFAULT_NURSERY_SIZE * 3 / MAJOR_SECTION_SIZE)
-#define DEFAULT_LOS_COLLECTION_TARGET (DEFAULT_NURSERY_SIZE * 2)
+#endif
+
+#endif
+
+#define MIN_LOS_ALLOWANCE              (DEFAULT_NURSERY_SIZE * 2)
 /* to quickly find the head of an object pinned by a conservative address
  * we keep track of the objects allocated for each SCAN_START_SIZE memory
  * chunk in the nursery or other memory sections. Larger values have less
@@ -600,13 +691,9 @@ static int num_major_gcs = 0;
 #define FREELIST_PAGESIZE 4096
 
 static mword pagesize = 4096;
-static mword nursery_size = DEFAULT_NURSERY_SIZE;
+static mword nursery_size;
 static int degraded_mode = 0;
 
-static int minor_collection_section_allowance = MIN_MINOR_COLLECTION_SECTION_ALLOWANCE;
-static int minor_collection_sections_alloced = 0;
-static int num_major_sections = 0;
-
 static LOSObject *los_object_list = NULL;
 static mword los_memory_usage = 0;
 static mword los_num_objects = 0;
@@ -615,11 +702,12 @@ static mword total_alloc = 0;
 /* use this to tune when to do a major/minor collection */
 static mword memory_pressure = 0;
 
-static GCMemSection *section_list = NULL;
 static GCMemSection *nursery_section = NULL;
 static mword lowest_heap_address = ~(mword)0;
 static mword highest_heap_address = 0;
 
+static LOCK_DECLARE (interruption_mutex);
+
 typedef struct _FinalizeEntry FinalizeEntry;
 struct _FinalizeEntry {
        FinalizeEntry *next;
@@ -661,6 +749,8 @@ enum {
        GENERATION_MAX
 };
 
+int current_collection_generation = -1;
+
 /*
  * The link pointer is hidden by negating each bit.  We use the lowest
  * bit of the link (before negation) to store whether it needs
@@ -696,32 +786,15 @@ static const int freelist_sizes [] = {
        448, 512, 584, 680, 816, 1024, 1360, 2048};
 #define FREELIST_NUM_SLOTS (sizeof (freelist_sizes) / sizeof (freelist_sizes [0]))
 
-static char* max_pinned_chunk_addr = NULL;
-static char* min_pinned_chunk_addr = (char*)-1;
-/* pinned_chunk_list is used for allocations of objects that are never moved */
-static PinnedChunk *pinned_chunk_list = NULL;
+/* This is also the MAJOR_SECTION_SIZE for the copying major
+   collector */
+#define PINNED_CHUNK_SIZE      (128 * 1024)
+
 /* internal_chunk_list is used for allocating structures needed by the GC */
 static PinnedChunk *internal_chunk_list = NULL;
 
-static gboolean
-obj_is_from_pinned_alloc (char *p)
-{
-       return BLOCK_FOR_OBJECT (p)->role == MEMORY_ROLE_PINNED;
-}
-
 static int slot_for_size (size_t size);
 
-static void
-free_pinned_object (PinnedChunk *chunk, char *obj, size_t size)
-{
-       void **p = (void**)obj;
-       int slot = slot_for_size (size);
-
-       g_assert (obj >= (char*)chunk->start_data && obj < ((char*)chunk + chunk->num_pages * FREELIST_PAGESIZE));
-       *p = chunk->free_list [slot];
-       chunk->free_list [slot] = p;
-}
-
 enum {
        ROOT_TYPE_NORMAL = 0, /* "normal" roots */
        ROOT_TYPE_PINNED = 1, /* roots without a GC descriptor */
@@ -839,7 +912,6 @@ static __thread long *store_remset_buffer_index_addr;
 static char *nursery_next = NULL;
 static char *nursery_frag_real_end = NULL;
 static char *nursery_real_end = NULL;
-//static char *nursery_first_pinned_start = NULL;
 static char *nursery_last_pinned_end = NULL;
 
 /* The size of a TLAB */
@@ -855,19 +927,18 @@ static Fragment *nursery_fragments = NULL;
 /* freeelist of fragment structures */
 static Fragment *fragment_freelist = NULL;
 
-/* 
- * used when moving the objects
- */
-static char *to_space_bumper = NULL;
-static char *to_space_top = NULL;
-static GCMemSection *to_space_section = NULL;
-
 /* objects bigger then this go into the large object space */
-#define MAX_SMALL_OBJ_SIZE MAX_FREELIST_SIZE
+#define MAX_SMALL_OBJ_SIZE 2040
 
 /* Functions supplied by the runtime to be called by the GC */
 static MonoGCCallbacks gc_callbacks;
 
+#define ALLOC_ALIGN 8
+
+#define MOVED_OBJECTS_NUM 64
+static void *moved_objects [MOVED_OBJECTS_NUM];
+static int moved_objects_idx = 0;
+
 /*
  * ######################################################################
  * ########  Macros and function declarations.
@@ -891,44 +962,74 @@ align_pointer (void *ptr)
        return (void*)p;
 }
 
+typedef void (*CopyOrMarkObjectFunc) (void**);
+typedef char* (*ScanObjectFunc) (char*);
+
 /* forward declarations */
 static void* get_internal_mem          (size_t size, int type);
 static void  free_internal_mem         (void *addr, int type);
 static void* get_os_memory             (size_t size, int activate);
+static void* get_os_memory_aligned     (mword size, mword alignment, gboolean activate);
 static void  free_os_memory            (void *addr, size_t size);
 static G_GNUC_UNUSED void  report_internal_mem_usage (void);
 
 static int stop_world (void);
 static int restart_world (void);
+static void add_to_global_remset (gpointer ptr, gboolean root);
 static void scan_thread_data (void *start_nursery, void *end_nursery, gboolean precise);
 static void scan_from_remsets (void *start_nursery, void *end_nursery);
+static void scan_from_registered_roots (CopyOrMarkObjectFunc copy_func, char *addr_start, char *addr_end, int root_type);
+static void scan_finalizer_entries (CopyOrMarkObjectFunc copy_func, FinalizeEntry *list);
 static void find_pinning_ref_from_thread (char *obj, size_t size);
 static void update_current_thread_stack (void *start);
-static GCMemSection* alloc_major_section (void);
-static void finalize_in_range (char *start, char *end, int generation);
+static void finalize_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int generation);
 static void add_or_remove_disappearing_link (MonoObject *obj, void **link, gboolean track, int generation);
-static void null_link_in_range (char *start, char *end, int generation);
+static void null_link_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int generation);
 static void null_links_for_domain (MonoDomain *domain, int generation);
 static gboolean search_fragment_for_size (size_t size);
-static void mark_pinned_from_addresses (PinnedChunk *chunk, void **start, void **end);
+static void build_nursery_fragments (int start_pin, int end_pin);
+static void clear_nursery_fragments (char *next);
+static void pin_from_roots (void *start_nursery, void *end_nursery);
+static int pin_objects_from_addresses (GCMemSection *section, void **start, void **end, void *start_nursery, void *end_nursery);
+static void pin_objects_in_section (GCMemSection *section);
+static void optimize_pin_queue (int start_slot);
 static void clear_remsets (void);
 static void clear_tlabs (void);
-typedef void (*ScanPinnedObjectCallbackFunc) (PinnedChunk*, char*, size_t, void*);
-static void scan_pinned_objects (ScanPinnedObjectCallbackFunc callback, void *callback_data);
-static void sweep_pinned_objects (void);
-static void scan_from_pinned_objects (char *addr_start, char *addr_end);
+typedef void (*IterateObjectCallbackFunc) (char*, size_t, void*);
+static void scan_area_with_callback (char *start, char *end, IterateObjectCallbackFunc callback, void *data);
+static char* scan_object (char *start);
+static char* major_scan_object (char *start);
+static void* copy_object_no_checks (void *obj);
+static void copy_object (void **obj_slot);
+static void* get_chunk_freelist (PinnedChunk *chunk, int slot);
+static PinnedChunk* alloc_pinned_chunk (void);
 static void free_large_object (LOSObject *obj);
-static void free_major_section (GCMemSection *section);
-static void to_space_expand (void);
+static void sort_addresses (void **array, int size);
+static void drain_gray_stack (void);
+static void finish_gray_stack (char *start_addr, char *end_addr, int generation);
 
 static void mono_gc_register_disappearing_link (MonoObject *obj, void **link, gboolean track);
 
 void describe_ptr (char *ptr);
-void check_consistency (void);
-char* check_object (char *start);
+static void check_consistency (void);
+static void check_section_scan_starts (GCMemSection *section);
+static void check_scan_starts (void);
+static void check_for_xdomain_refs (void);
+static void dump_section (GCMemSection *section, const char *type);
+static void dump_heap (const char *type, int num, const char *reason);
+static void commit_stats (int generation);
+static void report_pinned_chunk (PinnedChunk *chunk, int seq);
 
 void mono_gc_scan_for_specific_ref (MonoObject *key);
 
+static void init_stats (void);
+
+//#define BINARY_PROTOCOL
+#include "sgen-protocol.c"
+#include "sgen-pinning.c"
+#include "sgen-pinning-stats.c"
+#include "sgen-gray.c"
+
 /*
  * ######################################################################
  * ########  GC descriptors
@@ -977,17 +1078,12 @@ enum {
 #define VECTOR_INFO_SHIFT 14
 #define VECTOR_ELSIZE_SHIFT 3
 #define LARGE_BITMAP_SIZE (GC_BITS_PER_WORD - LOW_TYPE_BITS)
-#define MAX_SMALL_SIZE ((1 << SMALL_BITMAP_SHIFT) - 1)
-#define SMALL_SIZE_MASK 0xfff8
 #define MAX_ELEMENT_SIZE 0x3ff
-#define ELEMENT_SIZE_MASK (0x3ff << LOW_TYPE_BITS)
 #define VECTOR_SUBTYPE_PTRFREE (DESC_TYPE_V_PTRFREE << VECTOR_INFO_SHIFT)
 #define VECTOR_SUBTYPE_REFS    (DESC_TYPE_V_REFS << VECTOR_INFO_SHIFT)
 #define VECTOR_SUBTYPE_RUN_LEN (DESC_TYPE_V_RUN_LEN << VECTOR_INFO_SHIFT)
 #define VECTOR_SUBTYPE_BITMAP  (DESC_TYPE_V_BITMAP << VECTOR_INFO_SHIFT)
 
-#define ALLOC_ALIGN 8
-
 
 /* Root bitmap descriptors are simpler: the lower three bits describe the type
  * and we either have 30/62 bitmap bits or nibble-based run-length,
@@ -1010,7 +1106,7 @@ enum {
 static gsize* complex_descriptors = NULL;
 static int complex_descriptors_size = 0;
 static int complex_descriptors_next = 0;
-static MonoGCMarkFunc user_descriptors [MAX_USER_DESCRIPTORS];
+static MonoGCRootMarkFunc user_descriptors [MAX_USER_DESCRIPTORS];
 static int user_descriptors_next = 0;
 
 static int
@@ -1357,69 +1453,8 @@ mono_gc_get_bitmap_for_descr (void *descr, int *numbits)
                }       \
        } while (0)
 
-#define COUNT_OBJECT_TYPES do {                                                \
-       switch (desc & 0x7) {                                           \
-       case DESC_TYPE_STRING: type_str++; break;                       \
-       case DESC_TYPE_RUN_LENGTH: type_rlen++; break;                  \
-       case DESC_TYPE_ARRAY: case DESC_TYPE_VECTOR: type_vector++; break; \
-       case DESC_TYPE_SMALL_BITMAP: type_bitmap++; break;              \
-       case DESC_TYPE_LARGE_BITMAP: type_lbit++; break;                \
-       case DESC_TYPE_COMPLEX: type_complex++; break;                  \
-       case DESC_TYPE_COMPLEX_ARR: type_complex++; break;              \
-       default: g_assert_not_reached ();                               \
-       }                                                               \
-       } while (0)
-
-
-/*
- * ######################################################################
- * ########  Detecting and removing garbage.
- * ######################################################################
- * This section of code deals with detecting the objects no longer in use
- * and reclaiming the memory.
- */
-
-#if 0
-static mword new_obj_references = 0;
-static mword obj_references_checked = 0;
-
-#undef HANDLE_PTR
-#define HANDLE_PTR(ptr,obj)    do {    \
-               if (*(ptr) && (char*)*(ptr) >= nursery_start && (char*)*(ptr) < nursery_next) { \
-                       new_obj_references++;   \
-                       /*printf ("bogus ptr %p found at %p in object %p (%s.%s)\n", *(ptr), (ptr), o, o->vtable->klass->name_space, o->vtable->klass->name);*/ \
-               } else {        \
-                       obj_references_checked++;       \
-               }       \
-       } while (0)
-
-static void __attribute__((noinline))
-scan_area (char *start, char *end)
-{
-       GCVTable *vt;
-       int type_str = 0, type_rlen = 0, type_bitmap = 0, type_vector = 0, type_lbit = 0, type_complex = 0;
-       new_obj_references = 0;
-       obj_references_checked = 0;
-       while (start < end) {
-               if (!*(void**)start) {
-                       start += sizeof (void*); /* should be ALLOC_ALIGN, really */
-                       continue;
-               }
-               vt = (GCVTable*)LOAD_VTABLE (start);
-               DEBUG (8, fprintf (gc_debug_file, "Scanning object %p, vtable: %p (%s)\n", start, vt, vt->klass->name));
-               if (0) {
-                       MonoObject *obj = (MonoObject*)start;
-                       g_print ("found at %p (0x%zx): %s.%s\n", start, vt->desc, obj->vtable->klass->name_space, obj->vtable->klass->name);
-               }
-
-#define SCAN_OBJECT_ACTION COUNT_OBJECT_TYPES
-#include "sgen-scan-object.h"
-       }
-       /*printf ("references to new nursery %p-%p (size: %dk): %d, checked: %d\n", old_start, end, (end-old_start)/1024, new_obj_references, obj_references_checked);
-       printf ("\tstrings: %d, runl: %d, vector: %d, bitmaps: %d, lbitmaps: %d, complex: %d\n",
-               type_str, type_rlen, type_vector, type_bitmap, type_lbit, type_complex);*/
-}
-#endif
+//#include "sgen-major-copying.c"
+#include "sgen-marksweep.c"
 
 static gboolean
 is_xdomain_ref_allowed (gpointer *ptr, char *obj, MonoDomain *domain)
@@ -1552,20 +1587,27 @@ scan_object_for_specific_ref (char *start, MonoObject *key)
 }
 
 static void
-scan_area_for_specific_ref (char *start, char *end, MonoObject *key)
+scan_area_with_callback (char *start, char *end, IterateObjectCallbackFunc callback, void *data)
 {
        while (start < end) {
+               size_t size;
                if (!*(void**)start) {
                        start += sizeof (void*); /* should be ALLOC_ALIGN, really */
                        continue;
                }
 
-               start = scan_object_for_specific_ref (start, key);
+               size = safe_object_get_size ((MonoObject*) start);
+               size += ALLOC_ALIGN - 1;
+               size &= ~(ALLOC_ALIGN - 1);
+
+               callback (start, size, data);
+
+               start += size;
        }
 }
 
 static void
-scan_pinned_object_for_specific_ref_callback (PinnedChunk *chunk, char *obj, size_t size, MonoObject *key)
+scan_object_for_specific_ref_callback (char *obj, size_t size, MonoObject *key)
 {
        scan_object_for_specific_ref (obj, key);
 }
@@ -1581,11 +1623,10 @@ check_root_obj_specific_ref (RootRecord *root, MonoObject *key, MonoObject *obj)
 static MonoObject *check_key = NULL;
 static RootRecord *check_root = NULL;
 
-static void*
-check_root_obj_specific_ref_from_marker (void *obj)
+static void
+check_root_obj_specific_ref_from_marker (void **obj)
 {
-       check_root_obj_specific_ref (check_root, check_key, obj);
-       return obj;
+       check_root_obj_specific_ref (check_root, check_key, *obj);
 }
 
 static void
@@ -1630,7 +1671,7 @@ scan_roots_for_specific_ref (MonoObject *key, int root_type)
                                break;
                        }
                        case ROOT_DESC_USER: {
-                               MonoGCMarkFunc marker = user_descriptors [desc >> ROOT_DESC_TYPE_SHIFT];
+                               MonoGCRootMarkFunc marker = user_descriptors [desc >> ROOT_DESC_TYPE_SHIFT];
                                marker (start_root, check_root_obj_specific_ref_from_marker);
                                break;
                        }
@@ -1648,19 +1689,18 @@ scan_roots_for_specific_ref (MonoObject *key, int root_type)
 void
 mono_gc_scan_for_specific_ref (MonoObject *key)
 {
-       GCMemSection *section;
        LOSObject *bigobj;
        RootRecord *root;
        int i;
 
-       for (section = section_list; section; section = section->block.next)
-               scan_area_for_specific_ref (section->data, section->end_data, key);
+       scan_area_with_callback (nursery_section->data, nursery_section->end_data,
+                       (IterateObjectCallbackFunc)scan_object_for_specific_ref_callback, key);
+
+       major_iterate_objects (TRUE, TRUE, (IterateObjectCallbackFunc)scan_object_for_specific_ref_callback, key);
 
        for (bigobj = los_object_list; bigobj; bigobj = bigobj->next)
                scan_object_for_specific_ref (bigobj->data, key);
 
-       scan_pinned_objects ((ScanPinnedObjectCallbackFunc)scan_pinned_object_for_specific_ref_callback, key);
-
        scan_roots_for_specific_ref (key, ROOT_TYPE_NORMAL);
        scan_roots_for_specific_ref (key, ROOT_TYPE_WBARRIER);
 
@@ -1676,14 +1716,25 @@ mono_gc_scan_for_specific_ref (MonoObject *key)
        }
 }
 
-//#define BINARY_PROTOCOL
-#include "sgen-protocol.c"
+/* Clear all remaining nursery fragments */
+static void
+clear_nursery_fragments (char *next)
+{
+       Fragment *frag;
+       if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION) {
+               g_assert (next <= nursery_frag_real_end);
+               memset (next, 0, nursery_frag_real_end - next);
+               for (frag = nursery_fragments; frag; frag = frag->next) {
+                       memset (frag->fragment_start, 0, frag->fragment_end - frag->fragment_start);
+               }
+       }
+}
 
 static gboolean
 need_remove_object_for_domain (char *start, MonoDomain *domain)
 {
        if (mono_object_domain (start) == domain) {
-               DEBUG (1, fprintf (gc_debug_file, "Need to cleanup object %p\n", start));
+               DEBUG (4, fprintf (gc_debug_file, "Need to cleanup object %p\n", start));
                binary_protocol_cleanup (start, (gpointer)LOAD_VTABLE (start), safe_object_get_size ((MonoObject*)start));
                return TRUE;
        }
@@ -1704,48 +1755,19 @@ process_object_for_domain_clearing (char *start, MonoDomain *domain)
                /* The server could already have been zeroed out, so
                   we need to check for that, too. */
                if (server && (!LOAD_VTABLE (server) || mono_object_domain (server) == domain)) {
-                       DEBUG (1, fprintf (gc_debug_file, "Cleaning up remote pointer in %p to object %p\n",
+                       DEBUG (4, fprintf (gc_debug_file, "Cleaning up remote pointer in %p to object %p\n",
                                        start, server));
                        ((MonoRealProxy*)start)->unwrapped_server = NULL;
                }
        }
 }
 
-static void __attribute__((noinline))
-scan_area_for_domain (MonoDomain *domain, char *start, char *end)
-{
-       GCVTable *vt;
-       gboolean remove;
-
-       while (start < end) {
-               if (!*(void**)start) {
-                       start += sizeof (void*); /* should be ALLOC_ALIGN, really */
-                       continue;
-               }
-               vt = (GCVTable*)LOAD_VTABLE (start);
-               process_object_for_domain_clearing (start, domain);
-               remove = need_remove_object_for_domain (start, domain);
-               if (remove && ((MonoObject*)start)->synchronisation) {
-                       void **dislink = mono_monitor_get_object_monitor_weak_link ((MonoObject*)start);
-                       if (dislink)
-                               mono_gc_register_disappearing_link (NULL, dislink, FALSE);
-               }
-
-#define SCAN_OBJECT_NOSCAN
-#define SCAN_OBJECT_ACTION do {                                                \
-                       if (remove) memset (start, 0, skip_size);       \
-               } while (0)
-#include "sgen-scan-object.h"
-       }
-}
-
 static MonoDomain *check_domain = NULL;
 
-static void*
-check_obj_not_in_domain (void *o)
+static void
+check_obj_not_in_domain (void **o)
 {
-       g_assert (((MonoObject*)o)->vtable->domain != check_domain);
-       return o;
+       g_assert (((MonoObject*)(*o))->vtable->domain != check_domain);
 }
 
 static void
@@ -1793,7 +1815,7 @@ scan_for_registered_roots_in_domain (MonoDomain *domain, int root_type)
                                break;
                        }
                        case ROOT_DESC_USER: {
-                               MonoGCMarkFunc marker = user_descriptors [desc >> ROOT_DESC_TYPE_SHIFT];
+                               MonoGCRootMarkFunc marker = user_descriptors [desc >> ROOT_DESC_TYPE_SHIFT];
                                marker (start_root, check_obj_not_in_domain);
                                break;
                        }
@@ -1808,37 +1830,66 @@ scan_for_registered_roots_in_domain (MonoDomain *domain, int root_type)
 }
 
 static void
-clear_domain_process_pinned_object_callback (PinnedChunk *chunk, char *obj, size_t size, MonoDomain *domain)
+scan_pinned_object_for_xdomain_refs_callback (char *obj, size_t size, gpointer dummy)
 {
-       process_object_for_domain_clearing (obj, domain);
+       scan_object_for_xdomain_refs (obj);
 }
 
 static void
-clear_domain_free_pinned_object_callback (PinnedChunk *chunk, char *obj, size_t size, MonoDomain *domain)
+check_for_xdomain_refs (void)
 {
-       if (need_remove_object_for_domain (obj, domain))
-               free_pinned_object (chunk, obj, size);
+       LOSObject *bigobj;
+
+       scan_area_for_xdomain_refs (nursery_section->data, nursery_section->end_data);
+
+       major_iterate_objects (TRUE, TRUE, scan_pinned_object_for_xdomain_refs_callback, NULL);
+
+       for (bigobj = los_object_list; bigobj; bigobj = bigobj->next)
+               scan_object_for_xdomain_refs (bigobj->data);
 }
 
-static void
-scan_pinned_object_for_xdomain_refs_callback (PinnedChunk *chunk, char *obj, size_t size, gpointer dummy)
+static gboolean
+clear_domain_process_object (char *obj, MonoDomain *domain)
 {
-       scan_object_for_xdomain_refs (obj);
+       gboolean remove;
+
+       process_object_for_domain_clearing (obj, domain);
+       remove = need_remove_object_for_domain (obj, domain);
+
+       if (remove && ((MonoObject*)obj)->synchronisation) {
+               void **dislink = mono_monitor_get_object_monitor_weak_link ((MonoObject*)obj);
+               if (dislink)
+                       mono_gc_register_disappearing_link (NULL, dislink, FALSE);
+       }
+
+       return remove;
 }
 
 static void
-check_for_xdomain_refs (void)
+clear_domain_process_minor_object_callback (char *obj, size_t size, MonoDomain *domain)
 {
-       GCMemSection *section;
-       LOSObject *bigobj;
+       if (clear_domain_process_object (obj, domain))
+               memset (obj, 0, size);
+}
 
-       for (section = section_list; section; section = section->block.next)
-               scan_area_for_xdomain_refs (section->data, section->end_data);
+static void
+clear_domain_process_major_object_callback (char *obj, size_t size, MonoDomain *domain)
+{
+       clear_domain_process_object (obj, domain);
+}
 
-       for (bigobj = los_object_list; bigobj; bigobj = bigobj->next)
-               scan_object_for_xdomain_refs (bigobj->data);
+static void
+clear_domain_free_major_non_pinned_object_callback (char *obj, size_t size, MonoDomain *domain)
+{
+       if (need_remove_object_for_domain (obj, domain))
+               major_free_non_pinned_object (obj, size);
+}
 
-       scan_pinned_objects (scan_pinned_object_for_xdomain_refs_callback, NULL);
+static void
+clear_domain_free_major_pinned_object_callback (char *obj, size_t size, MonoDomain *domain)
+{
+       if (need_remove_object_for_domain (obj, domain))
+               free_pinned_object (obj, size);
 }
 
 /*
@@ -1853,20 +1904,12 @@ check_for_xdomain_refs (void)
 void
 mono_gc_clear_domain (MonoDomain * domain)
 {
-       GCMemSection *section;
        LOSObject *bigobj, *prev;
-       Fragment *frag;
        int i;
 
        LOCK_GC;
-       /* Clear all remaining nursery fragments */
-       if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION) {
-               g_assert (nursery_next <= nursery_frag_real_end);
-               memset (nursery_next, 0, nursery_frag_real_end - nursery_next);
-               for (frag = nursery_fragments; frag; frag = frag->next) {
-                       memset (frag->fragment_start, 0, frag->fragment_end - frag->fragment_start);
-               }
-       }
+
+       clear_nursery_fragments (nursery_next);
 
        if (xdomain_checks && domain != mono_get_root_domain ()) {
                scan_for_registered_roots_in_domain (domain, ROOT_TYPE_NORMAL);
@@ -1874,19 +1917,19 @@ mono_gc_clear_domain (MonoDomain * domain)
                check_for_xdomain_refs ();
        }
 
-       for (section = section_list; section; section = section->block.next) {
-               scan_area_for_domain (domain, section->data, section->end_data);
-       }
+       scan_area_with_callback (nursery_section->data, nursery_section->end_data,
+                       (IterateObjectCallbackFunc)clear_domain_process_minor_object_callback, domain);
 
-       /* We need two passes over pinned and large objects because
-          freeing such an object gives its memory back to the OS (in
-          the case of large objects) or obliterates its vtable
-          (pinned objects), but we might need to dereference a
-          pointer from an object to another object if the first
-          object is a proxy. */
-       scan_pinned_objects ((ScanPinnedObjectCallbackFunc)clear_domain_process_pinned_object_callback, domain);
+       /* We need two passes over major and large objects because
+          freeing such objects might give their memory back to the OS
+          (in the case of large objects) or obliterate its vtable
+          (pinned objects with major-copying or pinned and non-pinned
+          objects with major-mark&sweep), but we might need to
+          dereference a pointer from an object to another object if
+          the first object is a proxy. */
+       major_iterate_objects (TRUE, TRUE, (IterateObjectCallbackFunc)clear_domain_process_major_object_callback, domain);
        for (bigobj = los_object_list; bigobj; bigobj = bigobj->next)
-               process_object_for_domain_clearing (bigobj->data, domain);
+               clear_domain_process_object (bigobj->data, domain);
 
        prev = NULL;
        for (bigobj = los_object_list; bigobj;) {
@@ -1897,7 +1940,7 @@ mono_gc_clear_domain (MonoDomain * domain)
                        else
                                los_object_list = bigobj->next;
                        bigobj = bigobj->next;
-                       DEBUG (1, fprintf (gc_debug_file, "Freeing large object %p\n",
+                       DEBUG (4, fprintf (gc_debug_file, "Freeing large object %p\n",
                                        bigobj->data));
                        free_large_object (to_free);
                        continue;
@@ -1905,7 +1948,8 @@ mono_gc_clear_domain (MonoDomain * domain)
                prev = bigobj;
                bigobj = bigobj->next;
        }
-       scan_pinned_objects ((ScanPinnedObjectCallbackFunc)clear_domain_free_pinned_object_callback, domain);
+       major_iterate_objects (TRUE, FALSE, (IterateObjectCallbackFunc)clear_domain_free_major_non_pinned_object_callback, domain);
+       major_iterate_objects (FALSE, TRUE, (IterateObjectCallbackFunc)clear_domain_free_major_pinned_object_callback, domain);
 
        for (i = GENERATION_NURSERY; i < GENERATION_MAX; ++i)
                null_links_for_domain (domain, i);
@@ -1965,146 +2009,32 @@ add_to_global_remset (gpointer ptr, gboolean root)
        }
 }
 
-#define MOVED_OBJECTS_NUM 64
-static void *moved_objects [MOVED_OBJECTS_NUM];
-static int moved_objects_idx = 0;
-
-#include "sgen-gray.c"
-
 /*
- * This is how the copying happens from the nursery to the old generation.
- * We assume that at this time all the pinned objects have been identified and
- * marked as such.
- * We run scan_object() for each pinned object so that each referenced
- * objects if possible are copied. The new gray objects created can have
- * scan_object() run on them right away, too.
- * Then we run copy_object() for the precisely tracked roots. At this point
- * all the roots are either gray or black. We run scan_object() on the gray
- * objects until no more gray objects are created.
- * At the end of the process we walk again the pinned list and we unmark
- * the pinned flag. As we go we also create the list of free space for use
- * in the next allocation runs.
- *
- * We need to remember objects from the old generation that point to the new one
- * (or just addresses?).
- *
- * copy_object could be made into a macro once debugged (use inline for now).
+ * FIXME: allocate before calling this function and pass the
+ * destination address.
  */
-
-static char* __attribute__((noinline))
-copy_object (char *obj, char *from_space_start, char *from_space_end)
+static void*
+copy_object_no_checks (void *obj)
 {
-       static void *copy_labels [] = { &&LAB_0, &&LAB_1, &&LAB_2, &&LAB_3, &&LAB_4, &&LAB_5, &&LAB_6, &&LAB_7, &&LAB_8 };
+       static const void *copy_labels [] = { &&LAB_0, &&LAB_1, &&LAB_2, &&LAB_3, &&LAB_4, &&LAB_5, &&LAB_6, &&LAB_7, &&LAB_8 };
 
-       char *forwarded;
        mword objsize;
+       char *destination;
        MonoVTable *vt;
 
-       HEAVY_STAT (++num_copy_object_called);
-
-       if (!(obj >= from_space_start && obj < from_space_end)) {
-               DEBUG (9, fprintf (gc_debug_file, "Not copying %p because it's not in from space (%p-%p)\n",
-                                               obj, from_space_start, from_space_end));
-               HEAVY_STAT (++stat_copy_object_failed_from_space);
-               return obj;
-       }
-
-       DEBUG (9, fprintf (gc_debug_file, "Precise copy of %p", obj));
-
-       /*
-        * obj must belong to one of:
-        *
-        * 1. the nursery
-        * 2. the LOS
-        * 3. a pinned chunk
-        * 4. a non-to-space section of the major heap
-        * 5. a to-space section of the major heap
-        *
-        * In addition, objects in 1, 2 and 4 might also be pinned.
-        * Objects in 1 and 4 might be forwarded.
-        *
-        * Before we can copy the object we must make sure that we are
-        * allowed to, i.e. that the object not pinned, not already
-        * forwarded and doesn't belong to the LOS, a pinned chunk, or
-        * a to-space section.
-        *
-        * We are usually called for to-space objects (5) when we have
-        * two remset entries for the same reference.  The first entry
-        * copies the object and updates the reference and the second
-        * calls us with the updated reference that points into
-        * to-space.  There might also be other circumstances where we
-        * get to-space objects.
-        */
-
-       if ((forwarded = object_is_forwarded (obj))) {
-               g_assert (((MonoVTable*)LOAD_VTABLE(obj))->gc_descr);
-               DEBUG (9, fprintf (gc_debug_file, " (already forwarded to %p)\n", forwarded));
-               HEAVY_STAT (++stat_copy_object_failed_forwarded);
-               return forwarded;
-       }
-       if (object_is_pinned (obj)) {
-               g_assert (((MonoVTable*)LOAD_VTABLE(obj))->gc_descr);
-               DEBUG (9, fprintf (gc_debug_file, " (pinned, no change)\n"));
-               HEAVY_STAT (++stat_copy_object_failed_pinned);
-               return obj;
-       }
-
        objsize = safe_object_get_size ((MonoObject*)obj);
        objsize += ALLOC_ALIGN - 1;
        objsize &= ~(ALLOC_ALIGN - 1);
 
-       if (ptr_in_nursery (obj))
-               goto copy;
-
-       /*
-        * At this point we know obj is not pinned, not forwarded and
-        * belongs to 2, 3, 4, or 5.
-        *
-        * LOS object (2) are simple, at least until we always follow
-        * the rule: if objsize > MAX_SMALL_OBJ_SIZE, pin the object
-        * and return it.  At the end of major collections, we walk
-        * the los list and if the object is pinned, it is marked,
-        * otherwise it can be freed.
-        *
-        * Pinned chunks (3) and major heap sections (4, 5) both
-        * reside in blocks, which are always aligned, so once we've
-        * eliminated LOS objects, we can just access the block and
-        * see whether it's a pinned chunk or a major heap section.
-        */
-       if (G_UNLIKELY (objsize > MAX_SMALL_OBJ_SIZE || obj_is_from_pinned_alloc (obj))) {
-               DEBUG (9, fprintf (gc_debug_file, " (marked LOS/Pinned %p (%s), size: %zd)\n", obj, safe_name (obj), objsize));
-               binary_protocol_pin (obj, (gpointer)LOAD_VTABLE (obj), safe_object_get_size ((MonoObject*)obj));
-               pin_object (obj);
-               HEAVY_STAT (++stat_copy_object_failed_large_pinned);
-               return obj;
-       }
-
-       /*
-        * Now we know the object is in a major heap section.  All we
-        * need to do is check whether it's already in to-space (5) or
-        * not (4).
-        */
-       if (MAJOR_SECTION_FOR_OBJECT (obj)->is_to_space) {
-               g_assert (objsize <= MAX_SMALL_OBJ_SIZE);
-               DEBUG (9, fprintf (gc_debug_file, " (already copied)\n"));
-               HEAVY_STAT (++stat_copy_object_failed_to_space);
-               return obj;
-       }
+       MAJOR_GET_COPY_OBJECT_SPACE (destination, objsize);
 
- copy:
-       DEBUG (9, fprintf (gc_debug_file, " (to %p, %s size: %zd)\n", to_space_bumper, ((MonoObject*)obj)->vtable->klass->name, objsize));
-       binary_protocol_copy (obj, to_space_bumper, ((MonoObject*)obj)->vtable, objsize);
+       DEBUG (9, fprintf (gc_debug_file, " (to %p, %s size: %zd)\n", destination, ((MonoObject*)obj)->vtable->klass->name, objsize));
+       binary_protocol_copy (obj, destination, ((MonoObject*)obj)->vtable, objsize);
 
        HEAVY_STAT (++num_objects_copied);
 
-       /* Make sure we have enough space available */
-       if (to_space_bumper + objsize > to_space_top) {
-               to_space_expand ();
-               g_assert (to_space_bumper + objsize <= to_space_top);
-       }
-
        if (objsize <= sizeof (gpointer) * 8) {
-               mword *dest = (mword*)to_space_bumper;
+               mword *dest = (mword*)destination;
                goto *copy_labels [objsize / sizeof (gpointer)];
        LAB_8:
                (dest) [7] = ((mword*)obj) [7];
@@ -2129,7 +2059,7 @@ copy_object (char *obj, char *from_space_start, char *from_space_end)
                {
                        int ecx;
                        char* esi = obj;
-                       char* edi = to_space_bumper;
+                       char* edi = destination;
                        __asm__ __volatile__(
                                "rep; movsl"
                                : "=&c" (ecx), "=&D" (edi), "=&S" (esi)
@@ -2138,43 +2068,101 @@ copy_object (char *obj, char *from_space_start, char *from_space_end)
                                             );
                }
 #else
-               memcpy (to_space_bumper, obj, objsize);
+               memcpy (destination, obj, objsize);
 #endif
        }
        /* adjust array->bounds */
        vt = ((MonoObject*)obj)->vtable;
-       g_assert (vt->gc_descr);
+       DEBUG (9, g_assert (vt->gc_descr));
        if (G_UNLIKELY (vt->rank && ((MonoArray*)obj)->bounds)) {
-               MonoArray *array = (MonoArray*)to_space_bumper;
-               array->bounds = (MonoArrayBounds*)((char*)to_space_bumper + ((char*)((MonoArray*)obj)->bounds - (char*)obj));
+               MonoArray *array = (MonoArray*)destination;
+               array->bounds = (MonoArrayBounds*)((char*)destination + ((char*)((MonoArray*)obj)->bounds - (char*)obj));
                DEBUG (9, fprintf (gc_debug_file, "Array instance %p: size: %zd, rank: %d, length: %d\n", array, objsize, vt->rank, mono_array_length (array)));
        }
        /* set the forwarding pointer */
-       forward_object (obj, to_space_bumper);
+       forward_object (obj, destination);
        if (G_UNLIKELY (mono_profiler_events & MONO_PROFILE_GC_MOVES)) {
                if (moved_objects_idx == MOVED_OBJECTS_NUM) {
                        mono_profiler_gc_moves (moved_objects, moved_objects_idx);
                        moved_objects_idx = 0;
                }
                moved_objects [moved_objects_idx++] = obj;
-               moved_objects [moved_objects_idx++] = to_space_bumper;
+               moved_objects [moved_objects_idx++] = destination;
        }
-       obj = to_space_bumper;
-       to_space_section->scan_starts [((char*)obj - (char*)to_space_section->data)/SCAN_START_SIZE] = obj;
-       to_space_bumper += objsize;
+       obj = destination;
        DEBUG (9, fprintf (gc_debug_file, "Enqueuing gray object %p (%s)\n", obj, safe_name (obj)));
-       gray_object_enqueue (obj);
-       DEBUG (8, g_assert (to_space_bumper <= to_space_top));
+       GRAY_OBJECT_ENQUEUE (obj);
        return obj;
 }
 
-#undef HANDLE_PTR
-#define HANDLE_PTR(ptr,obj)    do {    \
-               void *__old = *(ptr);   \
-               void *__copy;           \
-               if (__old) {    \
-                       *(ptr) = __copy = copy_object (__old, from_start, from_end);    \
-                       DEBUG (9, if (__old != __copy) fprintf (gc_debug_file, "Overwrote field at %p with %p (was: %p)\n", (ptr), *(ptr), __old));     \
+/*
+ * This is how the copying happens from the nursery to the old generation.
+ * We assume that at this time all the pinned objects have been identified and
+ * marked as such.
+ * We run scan_object() for each pinned object so that each referenced
+ * objects if possible are copied. The new gray objects created can have
+ * scan_object() run on them right away, too.
+ * Then we run copy_object() for the precisely tracked roots. At this point
+ * all the roots are either gray or black. We run scan_object() on the gray
+ * objects until no more gray objects are created.
+ * At the end of the process we walk again the pinned list and we unmark
+ * the pinned flag. As we go we also create the list of free space for use
+ * in the next allocation runs.
+ *
+ * We need to remember objects from the old generation that point to the new one
+ * (or just addresses?).
+ *
+ * copy_object could be made into a macro once debugged (use inline for now).
+ */
+
+static void __attribute__((noinline))
+copy_object (void **obj_slot)
+{
+       char *forwarded;
+       char *obj = *obj_slot;
+
+       DEBUG (9, g_assert (current_collection_generation == GENERATION_NURSERY));
+
+       HEAVY_STAT (++num_copy_object_called);
+
+       if (!ptr_in_nursery (obj)) {
+               HEAVY_STAT (++stat_copy_object_failed_from_space);
+               return;
+       }
+
+       DEBUG (9, fprintf (gc_debug_file, "Precise copy of %p from %p", obj, obj_slot));
+
+       /*
+        * Before we can copy the object we must make sure that we are
+        * allowed to, i.e. that the object not pinned or not already
+        * forwarded.
+        */
+
+       if ((forwarded = object_is_forwarded (obj))) {
+               DEBUG (9, g_assert (((MonoVTable*)LOAD_VTABLE(obj))->gc_descr));
+               DEBUG (9, fprintf (gc_debug_file, " (already forwarded to %p)\n", forwarded));
+               HEAVY_STAT (++stat_copy_object_failed_forwarded);
+               *obj_slot = forwarded;
+               return;
+       }
+       if (object_is_pinned (obj)) {
+               DEBUG (9, g_assert (((MonoVTable*)LOAD_VTABLE(obj))->gc_descr));
+               DEBUG (9, fprintf (gc_debug_file, " (pinned, no change)\n"));
+               HEAVY_STAT (++stat_copy_object_failed_pinned);
+               return;
+       }
+
+       *obj_slot = copy_object_no_checks (obj);
+}
+
+#undef HANDLE_PTR
+#define HANDLE_PTR(ptr,obj)    do {    \
+               void *__old = *(ptr);   \
+               void *__copy;           \
+               if (__old) {    \
+                       copy_object ((ptr));    \
+                       __copy = *(ptr);        \
+                       DEBUG (9, if (__old != __copy) fprintf (gc_debug_file, "Overwrote field at %p with %p (was: %p)\n", (ptr), *(ptr), __old));     \
                        if (G_UNLIKELY (ptr_in_nursery (__copy) && !ptr_in_nursery ((ptr)))) \
                                add_to_global_remset ((ptr), FALSE);                                                    \
                }       \
@@ -2187,31 +2175,13 @@ copy_object (char *obj, char *from_space_start, char *from_space_end)
  * Returns a pointer to the end of the object.
  */
 static char*
-scan_object (char *start, char* from_start, char* from_end)
+scan_object (char *start)
 {
 #include "sgen-scan-object.h"
 
        return start;
 }
 
-/*
- * drain_gray_stack:
- *
- *   Scan objects in the gray stack until the stack is empty. This should be called
- * frequently after each object is copied, to achieve better locality and cache
- * usage.
- */
-static void inline
-drain_gray_stack (char *start_addr, char *end_addr)
-{
-       char *obj;
-
-       while ((obj = gray_object_dequeue ())) {
-               DEBUG (9, fprintf (gc_debug_file, "Precise gray object scan %p (%s)\n", obj, safe_name (obj)));
-               scan_object (obj, start_addr, end_addr);
-       }
-}
-
 /*
  * scan_vtype:
  *
@@ -2250,7 +2220,57 @@ scan_vtype (char *start, mword desc, char* from_start, char* from_end)
        return NULL;
 }
 
-#include "sgen-pinning-stats.c"
+#undef HANDLE_PTR
+#define HANDLE_PTR(ptr,obj)    do {    \
+               void *__old = *(ptr);   \
+               void *__copy;           \
+               if (__old) {    \
+                       major_copy_or_mark_object ((ptr));      \
+                       __copy = *(ptr);        \
+                       DEBUG (9, if (__old != __copy) fprintf (gc_debug_file, "Overwrote field at %p with %p (was: %p)\n", (ptr), *(ptr), __old));     \
+                       if (G_UNLIKELY (ptr_in_nursery (__copy) && !ptr_in_nursery ((ptr)))) \
+                               add_to_global_remset ((ptr), FALSE);                                                    \
+               }       \
+       } while (0)
+
+static char*
+major_scan_object (char *start)
+{
+#include "sgen-scan-object.h"
+
+       return start;
+}
+
+/*
+ * drain_gray_stack:
+ *
+ *   Scan objects in the gray stack until the stack is empty. This should be called
+ * frequently after each object is copied, to achieve better locality and cache
+ * usage.
+ */
+static void inline
+drain_gray_stack (void)
+{
+       char *obj;
+
+       if (current_collection_generation == GENERATION_NURSERY) {
+               for (;;) {
+                       GRAY_OBJECT_DEQUEUE (obj);
+                       if (!obj)
+                               break;
+                       DEBUG (9, fprintf (gc_debug_file, "Precise gray object scan %p (%s)\n", obj, safe_name (obj)));
+                       scan_object (obj);
+               }
+       } else {
+               for (;;) {
+                       GRAY_OBJECT_DEQUEUE (obj);
+                       if (!obj)
+                               break;
+                       DEBUG (9, fprintf (gc_debug_file, "Precise gray object scan %p (%s)\n", obj, safe_name (obj)));
+                       major_scan_object (obj);
+               }
+       }
+}
 
 /*
  * Addresses from start to end are already sorted. This function finds
@@ -2316,6 +2336,7 @@ pin_objects_from_addresses (GCMemSection *section, void **start, void **end, voi
                                        DEBUG (4, fprintf (gc_debug_file, "Pinned object %p, vtable %p (%s), count %d\n", search_start, *(void**)search_start, safe_name (search_start), count));
                                        binary_protocol_pin (search_start, (gpointer)LOAD_VTABLE (search_start), safe_object_get_size (search_start));
                                        pin_object (search_start);
+                                       GRAY_OBJECT_ENQUEUE (search_start);
                                        if (heap_dump_file)
                                                pin_stats_register_object (search_start, last_obj_size);
                                        definitely_pinned [count] = search_start;
@@ -2336,9 +2357,19 @@ pin_objects_from_addresses (GCMemSection *section, void **start, void **end, voi
        return count;
 }
 
-static void** pin_queue;
-static int pin_queue_size = 0;
-static int next_pin_slot = 0;
+static void
+pin_objects_in_section (GCMemSection *section)
+{
+       int start = section->pin_queue_start;
+       int end = section->pin_queue_end;
+       if (start != end) {
+               int reduced_to;
+               reduced_to = pin_objects_from_addresses (section, pin_queue + start, pin_queue + end,
+                               section->data, section->next_data);
+               section->pin_queue_start = start;
+               section->pin_queue_end = start + reduced_to;
+       }
+}
 
 static int
 new_gap (int gap)
@@ -2428,42 +2459,6 @@ optimize_pin_queue (int start_slot)
        
 }
 
-static int
-optimized_pin_queue_search (void *addr)
-{
-       int first = 0, last = next_pin_slot;
-       while (first < last) {
-               int middle = first + ((last - first) >> 1);
-               if (addr <= pin_queue [middle])
-                       last = middle;
-               else
-                       first = middle + 1;
-       }
-       g_assert (first == last);
-       return first;
-}
-
-static void
-find_optimized_pin_queue_area (void *start, void *end, int *first, int *last)
-{
-       *first = optimized_pin_queue_search (start);
-       *last = optimized_pin_queue_search (end);
-}
-
-static void
-realloc_pin_queue (void)
-{
-       int new_size = pin_queue_size? pin_queue_size + pin_queue_size/2: 1024;
-       void **new_pin = get_internal_mem (sizeof (void*) * new_size, INTERNAL_MEM_PIN_QUEUE);
-       memcpy (new_pin, pin_queue, sizeof (void*) * next_pin_slot);
-       free_internal_mem (pin_queue, INTERNAL_MEM_PIN_QUEUE);
-       pin_queue = new_pin;
-       pin_queue_size = new_size;
-       DEBUG (4, fprintf (gc_debug_file, "Reallocated pin queue to size: %d\n", new_size));
-}
-
-#include "sgen-pinning.c"
-
 /* 
  * Scan the memory between start and end and queue values which could be pointers
  * to the area between start_nursery and end_nursery for later consideration.
@@ -2506,25 +2501,6 @@ conservatively_pin_objects_from (void **start, void **end, void *start_nursery,
        DEBUG (7, if (count) fprintf (gc_debug_file, "found %d potential pinned heap pointers\n", count));
 }
 
-/* 
- * If generation is 0, just mark objects in the nursery, the others we don't care,
- * since they are not going to move anyway.
- * There are different areas that are scanned for pinned pointers:
- * *) the thread stacks (when jit support is ready only the unmanaged frames)
- * *) the pinned handle table
- * *) the pinned roots
- *
- * Note: when we'll use a write barrier for old to new gen references, we need to
- * keep track of old gen objects that point to pinned new gen objects because in that
- * case the referenced object will be moved maybe at the next collection, but there
- * is no write in the old generation area where the pinned object is referenced
- * and we may not consider it as reachable.
- */
-static G_GNUC_UNUSED void
-mark_pinned_objects (int generation)
-{
-}
-
 /*
  * Debugging function: find in the conservative roots where @obj is being pinned.
  */
@@ -2581,19 +2557,6 @@ pin_from_roots (void *start_nursery, void *end_nursery)
        evacuate_pin_staging_area ();
 }
 
-/* Copy function called from user defined mark functions */
-static char *user_copy_n_start;
-static char *user_copy_n_end;
-
-static void*
-user_copy (void *addr)
-{
-       if (addr)
-               return copy_object (addr, user_copy_n_start, user_copy_n_end);
-       else
-               return NULL;
-}
-
 /*
  * The memory area from start_root to end_root contains pointers to objects.
  * Their position is precisely described by @desc (this means that the pointer
@@ -2601,16 +2564,16 @@ user_copy (void *addr)
  * This functions copies them to to_space updates them.
  */
 static void
-precisely_scan_objects_from (void** start_root, void** end_root, char* n_start, char *n_end, mword desc)
+precisely_scan_objects_from (CopyOrMarkObjectFunc copy_func, void** start_root, void** end_root, char* n_start, char *n_end, mword desc)
 {
        switch (desc & ROOT_DESC_TYPE_MASK) {
        case ROOT_DESC_BITMAP:
                desc >>= ROOT_DESC_TYPE_SHIFT;
                while (desc) {
                        if ((desc & 1) && *start_root) {
-                               *start_root = copy_object (*start_root, n_start, n_end);
+                               copy_func (start_root);
                                DEBUG (9, fprintf (gc_debug_file, "Overwrote root at %p with %p\n", start_root, *start_root));
-                               drain_gray_stack (n_start, n_end);
+                               drain_gray_stack ();
                        }
                        desc >>= 1;
                        start_root++;
@@ -2626,9 +2589,9 @@ precisely_scan_objects_from (void** start_root, void** end_root, char* n_start,
                        void **objptr = start_run;
                        while (bmap) {
                                if ((bmap & 1) && *objptr) {
-                                       *objptr = copy_object (*objptr, n_start, n_end);
+                                       copy_func (objptr);
                                        DEBUG (9, fprintf (gc_debug_file, "Overwrote root at %p with %p\n", objptr, *objptr));
-                                       drain_gray_stack (n_start, n_end);
+                                       drain_gray_stack ();
                                }
                                bmap >>= 1;
                                ++objptr;
@@ -2638,11 +2601,8 @@ precisely_scan_objects_from (void** start_root, void** end_root, char* n_start,
                break;
        }
        case ROOT_DESC_USER: {
-               MonoGCMarkFunc marker = user_descriptors [desc >> ROOT_DESC_TYPE_SHIFT];
-
-               user_copy_n_start = n_start;
-               user_copy_n_end = n_end;
-               marker (start_root, user_copy);
+               MonoGCRootMarkFunc marker = user_descriptors [desc >> ROOT_DESC_TYPE_SHIFT];
+               marker (start_root, copy_func);
                break;
        }
        case ROOT_DESC_RUN_LEN:
@@ -2668,21 +2628,21 @@ alloc_fragment (void)
 
 /* size must be a power of 2 */
 static void*
-get_os_memory_aligned (mword size, gboolean activate)
+get_os_memory_aligned (mword size, mword alignment, gboolean activate)
 {
        /* Allocate twice the memory to be able to put the block on an aligned address */
-       char *mem = get_os_memory (size * 2, activate);
+       char *mem = get_os_memory (size + alignment, activate);
        char *aligned;
 
        g_assert (mem);
 
-       aligned = (char*)((mword)(mem + (size - 1)) & ~(size - 1));
-       g_assert (aligned >= mem && aligned + size <= mem + size * 2 && !((mword)aligned & (size - 1)));
+       aligned = (char*)((mword)(mem + (alignment - 1)) & ~(alignment - 1));
+       g_assert (aligned >= mem && aligned + size <= mem + size + alignment && !((mword)aligned & (alignment - 1)));
 
        if (aligned > mem)
                free_os_memory (mem, aligned - mem);
-       if (aligned + size < mem + size * 2)
-               free_os_memory (aligned + size, (mem + size * 2) - (aligned + size));
+       if (aligned + size < mem + size + alignment)
+               free_os_memory (aligned + size, (mem + size + alignment) - (aligned + size));
 
        return aligned;
 }
@@ -2713,7 +2673,7 @@ alloc_nursery (void)
        g_assert (nursery_size == DEFAULT_NURSERY_SIZE);
        alloc_size = nursery_size;
 #ifdef ALIGN_NURSERY
-       data = get_os_memory_aligned (alloc_size, TRUE);
+       data = get_os_memory_aligned (alloc_size, alloc_size, TRUE);
 #else
        data = get_os_memory (alloc_size, TRUE);
 #endif
@@ -2730,10 +2690,7 @@ alloc_nursery (void)
        section->scan_starts = get_internal_mem (sizeof (char*) * scan_starts, INTERNAL_MEM_SCAN_STARTS);
        section->num_scan_start = scan_starts;
        section->block.role = MEMORY_ROLE_GEN0;
-
-       /* add to the section list */
-       section->block.next = section_list;
-       section_list = section;
+       section->block.next = NULL;
 
        nursery_section = section;
 
@@ -2747,51 +2704,15 @@ alloc_nursery (void)
 }
 
 static void
-scan_finalizer_entries (FinalizeEntry *list, char *start, char *end) {
+scan_finalizer_entries (CopyOrMarkObjectFunc copy_func, FinalizeEntry *list) {
        FinalizeEntry *fin;
 
        for (fin = list; fin; fin = fin->next) {
                if (!fin->object)
                        continue;
                DEBUG (5, fprintf (gc_debug_file, "Scan of fin ready object: %p (%s)\n", fin->object, safe_name (fin->object)));
-               fin->object = copy_object (fin->object, start, end);
-       }
-}
-
-/*
- * Update roots in the old generation. Since we currently don't have the
- * info from the write barriers, we just scan all the objects.
- */
-static G_GNUC_UNUSED void
-scan_old_generation (char *start, char* end)
-{
-       GCMemSection *section;
-       LOSObject *big_object;
-       char *p;
-
-       for (section = section_list; section; section = section->block.next) {
-               if (section == nursery_section)
-                       continue;
-               DEBUG (2, fprintf (gc_debug_file, "Scan of old section: %p-%p, size: %d\n", section->data, section->next_data, (int)(section->next_data - section->data)));
-               /* we have to deal with zeroed holes in old generation (truncated strings ...) */
-               p = section->data;
-               while (p < section->next_data) {
-                       if (!*(void**)p) {
-                               p += ALLOC_ALIGN;
-                               continue;
-                       }
-                       DEBUG (8, fprintf (gc_debug_file, "Precise old object scan of %p (%s)\n", p, safe_name (p)));
-                       p = scan_object (p, start, end);
-               }
-       }
-       /* scan the old object space, too */
-       for (big_object = los_object_list; big_object; big_object = big_object->next) {
-               DEBUG (5, fprintf (gc_debug_file, "Scan of big object: %p (%s), size: %zd\n", big_object->data, safe_name (big_object->data), big_object->size));
-               scan_object (big_object->data, start, end);
+               copy_func (&fin->object);
        }
-       /* scan the list of objects ready for finalization */
-       scan_finalizer_entries (fin_ready_list, start, end);
-       scan_finalizer_entries (critical_fin_list, start, end);
 }
 
 static mword fragment_total = 0;
@@ -2824,23 +2745,6 @@ add_nursery_frag (size_t frag_size, char* frag_start, char* frag_end)
        }
 }
 
-static int
-scan_needed_big_objects (char *start_addr, char *end_addr)
-{
-       LOSObject *big_object;
-       int count = 0;
-       for (big_object = los_object_list; big_object; big_object = big_object->next) {
-               if (!big_object->scanned && object_is_pinned (big_object->data)) {
-                       DEBUG (5, fprintf (gc_debug_file, "Scan of big object: %p (%s), size: %zd\n", big_object->data, safe_name (big_object->data), big_object->size));
-                       scan_object (big_object->data, start_addr, end_addr);
-                       drain_gray_stack (start_addr, end_addr);
-                       big_object->scanned = TRUE;
-                       count++;
-               }
-       }
-       return count;
-}
-
 static const char*
 generation_name (int generation)
 {
@@ -2871,79 +2775,13 @@ get_finalize_entry_hash_table (int generation)
        }
 }
 
-static void
-new_to_space_section (void)
-{
-       /* FIXME: if the current to_space_section is empty, we don't
-          have to allocate a new one */
-
-       to_space_section = alloc_major_section ();
-       to_space_bumper = to_space_section->next_data;
-       to_space_top = to_space_section->end_data;
-}
-
-static void
-to_space_set_next_data (void)
-{
-       g_assert (to_space_bumper >= to_space_section->next_data && to_space_bumper <= to_space_section->end_data);
-       to_space_section->next_data = to_space_bumper;
-}
-
-static void
-to_space_expand (void)
-{
-       if (to_space_section) {
-               g_assert (to_space_top == to_space_section->end_data);
-               to_space_set_next_data ();
-       }
-
-       new_to_space_section ();
-}
-
-static void
-unset_to_space (void)
-{
-       /* between collections the to_space_bumper is invalidated
-          because degraded allocations might occur, so we set it to
-          NULL, just to make it explicit */
-       to_space_bumper = NULL;
-
-       /* don't unset to_space_section if we implement the FIXME in
-          new_to_space_section */
-       to_space_section = NULL;
-}
-
-static gboolean
-object_is_in_to_space (char *obj)
-{
-       mword objsize;
-
-       /* nursery */
-       if (ptr_in_nursery (obj))
-               return FALSE;
-
-       objsize = safe_object_get_size ((MonoObject*)obj);
-       objsize += ALLOC_ALIGN - 1;
-       objsize &= ~(ALLOC_ALIGN - 1);
-
-       /* LOS */
-       if (objsize > MAX_SMALL_OBJ_SIZE)
-               return FALSE;
-
-       /* pinned chunk */
-       if (obj_is_from_pinned_alloc (obj))
-               return FALSE;
-
-       /* now we know it's in a major heap section */
-       return MAJOR_SECTION_FOR_OBJECT (obj)->is_to_space;
-}
-
 static void
 finish_gray_stack (char *start_addr, char *end_addr, int generation)
 {
        TV_DECLARE (atv);
        TV_DECLARE (btv);
-       int fin_ready, bigo_scanned_num;
+       int fin_ready;
+       CopyOrMarkObjectFunc copy_func = current_collection_generation == GENERATION_NURSERY ? copy_object : major_copy_or_mark_object;
 
        /*
         * We copied all the reachable objects. Now it's the time to copy
@@ -2958,9 +2796,8 @@ finish_gray_stack (char *start_addr, char *end_addr, int generation)
         *   To achieve better cache locality and cache usage, we drain the gray stack 
         * frequently, after each object is copied, and just finish the work here.
         */
-       drain_gray_stack (start_addr, end_addr);
+       drain_gray_stack ();
        TV_GETTIME (atv);
-       //scan_old_generation (start_addr, end_addr);
        DEBUG (2, fprintf (gc_debug_file, "%s generation done\n", generation_name (generation)));
        /* walk the finalization queue and move also the objects that need to be
         * finalized: use the finalized objects as new roots so the objects they depend
@@ -2971,15 +2808,14 @@ finish_gray_stack (char *start_addr, char *end_addr, int generation)
         */
        do {
                fin_ready = num_ready_finalizers;
-               finalize_in_range (start_addr, end_addr, generation);
+               finalize_in_range (copy_func, start_addr, end_addr, generation);
                if (generation == GENERATION_OLD)
-                       finalize_in_range (nursery_start, nursery_real_end, GENERATION_NURSERY);
-               bigo_scanned_num = scan_needed_big_objects (start_addr, end_addr);
+                       finalize_in_range (copy_func, nursery_start, nursery_real_end, GENERATION_NURSERY);
 
                /* drain the new stack that might have been created */
                DEBUG (6, fprintf (gc_debug_file, "Precise scan of gray area post fin\n"));
-               drain_gray_stack (start_addr, end_addr);
-       } while (fin_ready != num_ready_finalizers || bigo_scanned_num);
+               drain_gray_stack ();
+       } while (fin_ready != num_ready_finalizers);
        TV_GETTIME (btv);
        DEBUG (2, fprintf (gc_debug_file, "Finalize queue handling scan for %s generation: %d usecs\n", generation_name (generation), TV_ELAPSED (atv, btv)));
 
@@ -2993,36 +2829,38 @@ finish_gray_stack (char *start_addr, char *end_addr, int generation)
         */
        g_assert (gray_object_queue_is_empty ());
        for (;;) {
-               null_link_in_range (start_addr, end_addr, generation);
+               null_link_in_range (copy_func, start_addr, end_addr, generation);
                if (generation == GENERATION_OLD)
-                       null_link_in_range (start_addr, end_addr, GENERATION_NURSERY);
+                       null_link_in_range (copy_func, start_addr, end_addr, GENERATION_NURSERY);
                if (gray_object_queue_is_empty ())
                        break;
-               drain_gray_stack (start_addr, end_addr);
+               drain_gray_stack ();
        }
 
        g_assert (gray_object_queue_is_empty ());
-       /* DEBUG (2, fprintf (gc_debug_file, "Copied from %s to old space: %d bytes (%p-%p)\n", generation_name (generation), (int)(to_space_bumper - to_space), to_space, to_space_bumper)); */
-       to_space_set_next_data ();
 }
 
 static void
-check_scan_starts (void)
+check_section_scan_starts (GCMemSection *section)
 {
-       GCMemSection *section;
        int i;
-       if (!do_scan_starts_check)
-               return;
-       for (section = section_list; section; section = section->block.next) {
-               for (i = 0; i < section->num_scan_start; ++i) {
-                       if (section->scan_starts [i]) {
-                               guint size = safe_object_get_size ((MonoObject*) section->scan_starts [i]);
-                               g_assert (size >= sizeof (MonoObject) && size <= MAX_SMALL_OBJ_SIZE);
-                       }
+       for (i = 0; i < section->num_scan_start; ++i) {
+               if (section->scan_starts [i]) {
+                       guint size = safe_object_get_size ((MonoObject*) section->scan_starts [i]);
+                       g_assert (size >= sizeof (MonoObject) && size <= MAX_SMALL_OBJ_SIZE);
                }
        }
 }
 
+static void
+check_scan_starts (void)
+{
+       if (!do_scan_starts_check)
+               return;
+       check_section_scan_starts (nursery_section);
+       major_check_scan_starts ();
+}
+
 static int last_num_pinned = 0;
 
 static void
@@ -3074,58 +2912,15 @@ build_nursery_fragments (int start_pin, int end_pin)
        clear_tlabs ();
 }
 
-/* FIXME: later reduce code duplication here with the above
- * We don't keep track of section fragments for non-nursery sections yet, so
- * just memset to 0.
- */
-static void
-build_section_fragments (GCMemSection *section)
-{
-       int i;
-       char *frag_start, *frag_end;
-       size_t frag_size;
-
-       /* clear scan starts */
-       memset (section->scan_starts, 0, section->num_scan_start * sizeof (gpointer));
-       frag_start = section->data;
-       section->next_data = section->data;
-       for (i = section->pin_queue_start; i < section->pin_queue_end; ++i) {
-               frag_end = pin_queue [i];
-               /* remove the pin bit from pinned objects */
-               unpin_object (frag_end);
-               if (frag_end >= section->data + section->size) {
-                       frag_end = section->data + section->size;
-               } else {
-                       section->scan_starts [((char*)frag_end - (char*)section->data)/SCAN_START_SIZE] = frag_end;
-               }
-               frag_size = frag_end - frag_start;
-               if (frag_size) {
-                       binary_protocol_empty (frag_start, frag_size);
-                       memset (frag_start, 0, frag_size);
-               }
-               frag_size = safe_object_get_size ((MonoObject*)pin_queue [i]);
-               frag_size += ALLOC_ALIGN - 1;
-               frag_size &= ~(ALLOC_ALIGN - 1);
-               frag_start = (char*)pin_queue [i] + frag_size;
-               section->next_data = MAX (section->next_data, frag_start);
-       }
-       frag_end = section->end_data;
-       frag_size = frag_end - frag_start;
-       if (frag_size) {
-               binary_protocol_empty (frag_start, frag_size);
-               memset (frag_start, 0, frag_size);
-       }
-}
-
 static void
-scan_from_registered_roots (char *addr_start, char *addr_end, int root_type)
+scan_from_registered_roots (CopyOrMarkObjectFunc copy_func, char *addr_start, char *addr_end, int root_type)
 {
        int i;
        RootRecord *root;
        for (i = 0; i < roots_hash_size [root_type]; ++i) {
                for (root = roots_hash [root_type][i]; root; root = root->next) {
                        DEBUG (6, fprintf (gc_debug_file, "Precise root scan %p-%p (desc: %p)\n", root->start_root, root->end_root, (void*)root->root_desc));
-                       precisely_scan_objects_from ((void**)root->start_root, (void**)root->end_root, addr_start, addr_end, root->root_desc);
+                       precisely_scan_objects_from (copy_func, (void**)root->start_root, (void**)root->end_root, addr_start, addr_end, root->root_desc);
                }
        }
 }
@@ -3187,6 +2982,43 @@ dump_section (GCMemSection *section, const char *type)
        fprintf (heap_dump_file, "</section>\n");
 }
 
+static void
+dump_object (MonoObject *obj, gboolean dump_location)
+{
+       static char class_name [1024];
+
+       MonoClass *class = mono_object_class (obj);
+       int i, j;
+
+       /*
+        * Python's XML parser is too stupid to parse angle brackets
+        * in strings, so we just ignore them;
+        */
+       i = j = 0;
+       while (class->name [i] && j < sizeof (class_name) - 1) {
+               if (!strchr ("<>\"", class->name [i]))
+                       class_name [j++] = class->name [i];
+               ++i;
+       }
+       g_assert (j < sizeof (class_name));
+       class_name [j] = 0;
+
+       fprintf (heap_dump_file, "<object class=\"%s.%s\" size=\"%d\"",
+                       class->name_space, class_name,
+                       safe_object_get_size (obj));
+       if (dump_location) {
+               const char *location;
+               if (ptr_in_nursery (obj))
+                       location = "nursery";
+               else if (safe_object_get_size (obj) <= MAX_SMALL_OBJ_SIZE)
+                       location = "major";
+               else
+                       location = "LOS";
+               fprintf (heap_dump_file, " location=\"%s\"", location);
+       }
+       fprintf (heap_dump_file, "/>\n");
+}
+
 static void
 dump_heap (const char *type, int num, const char *reason)
 {
@@ -3195,7 +3027,7 @@ dump_heap (const char *type, int num, const char *reason)
                                                     "dislink", "roots-table", "root-record", "statistics",
                                                     "remset", "gray-queue", "store-remset" };
 
-       GCMemSection *section;
+       ObjectList *list;
        LOSObject *bigobj;
        int i;
 
@@ -3212,22 +3044,18 @@ dump_heap (const char *type, int num, const char *reason)
        /* fprintf (heap_dump_file, "<pinned type=\"static-data\" bytes=\"%d\"/>\n", pinned_byte_counts [PIN_TYPE_STATIC_DATA]); */
        fprintf (heap_dump_file, "<pinned type=\"other\" bytes=\"%zu\"/>\n", pinned_byte_counts [PIN_TYPE_OTHER]);
 
+       fprintf (heap_dump_file, "<pinned-objects>\n");
+       for (list = pinned_objects; list; list = list->next)
+               dump_object (list->obj, TRUE);
+       fprintf (heap_dump_file, "</pinned-objects>\n");
+
        dump_section (nursery_section, "nursery");
 
-       for (section = section_list; section; section = section->block.next) {
-               if (section != nursery_section)
-                       dump_section (section, "old");
-       }
+       major_dump_non_pinned_sections ();
 
        fprintf (heap_dump_file, "<los>\n");
-       for (bigobj = los_object_list; bigobj; bigobj = bigobj->next) {
-               MonoObject *obj = (MonoObject*) bigobj->data;
-               MonoClass *class = mono_object_class (obj);
-
-               fprintf (heap_dump_file, "<object class=\"%s.%s\" size=\"%d\"/>\n",
-                               class->name_space, class->name,
-                               safe_object_get_size (obj));
-       }
+       for (bigobj = los_object_list; bigobj; bigobj = bigobj->next)
+               dump_object ((MonoObject*)bigobj->data, FALSE);
        fprintf (heap_dump_file, "</los>\n");
 
        fprintf (heap_dump_file, "</collection>\n");
@@ -3246,6 +3074,27 @@ init_stats (void)
        if (inited)
                return;
 
+       mono_counters_register ("Minor fragment clear", MONO_COUNTER_GC | MONO_COUNTER_LONG, &time_minor_pre_collection_fragment_clear);
+       mono_counters_register ("Minor pinning", MONO_COUNTER_GC | MONO_COUNTER_LONG, &time_minor_pinning);
+       mono_counters_register ("Minor scan remsets", MONO_COUNTER_GC | MONO_COUNTER_LONG, &time_minor_scan_remsets);
+       mono_counters_register ("Minor scan pinned", MONO_COUNTER_GC | MONO_COUNTER_LONG, &time_minor_scan_pinned);
+       mono_counters_register ("Minor scan registered roots", MONO_COUNTER_GC | MONO_COUNTER_LONG, &time_minor_scan_registered_roots);
+       mono_counters_register ("Minor scan thread data", MONO_COUNTER_GC | MONO_COUNTER_LONG, &time_minor_scan_thread_data);
+       mono_counters_register ("Minor finish gray stack", MONO_COUNTER_GC | MONO_COUNTER_LONG, &time_minor_finish_gray_stack);
+       mono_counters_register ("Minor fragment creation", MONO_COUNTER_GC | MONO_COUNTER_LONG, &time_minor_fragment_creation);
+
+       mono_counters_register ("Major fragment clear", MONO_COUNTER_GC | MONO_COUNTER_LONG, &time_major_pre_collection_fragment_clear);
+       mono_counters_register ("Major pinning", MONO_COUNTER_GC | MONO_COUNTER_LONG, &time_major_pinning);
+       mono_counters_register ("Major scan pinned", MONO_COUNTER_GC | MONO_COUNTER_LONG, &time_major_scan_pinned);
+       mono_counters_register ("Major scan registered roots", MONO_COUNTER_GC | MONO_COUNTER_LONG, &time_major_scan_registered_roots);
+       mono_counters_register ("Major scan thread data", MONO_COUNTER_GC | MONO_COUNTER_LONG, &time_major_scan_thread_data);
+       mono_counters_register ("Major scan alloc_pinned", MONO_COUNTER_GC | MONO_COUNTER_LONG, &time_major_scan_alloc_pinned);
+       mono_counters_register ("Major scan finalized", MONO_COUNTER_GC | MONO_COUNTER_LONG, &time_major_scan_finalized);
+       mono_counters_register ("Major scan big objects", MONO_COUNTER_GC | MONO_COUNTER_LONG, &time_major_scan_big_objects);
+       mono_counters_register ("Major finish gray stack", MONO_COUNTER_GC | MONO_COUNTER_LONG, &time_major_finish_gray_stack);
+       mono_counters_register ("Major sweep", MONO_COUNTER_GC | MONO_COUNTER_LONG, &time_major_sweep);
+       mono_counters_register ("Major fragment creation", MONO_COUNTER_GC | MONO_COUNTER_LONG, &time_major_fragment_creation);
+
 #ifdef HEAVY_STATISTICS
        mono_counters_register ("WBarrier set field", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_set_field);
        mono_counters_register ("WBarrier set arrayref", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_set_arrayref);
@@ -3257,7 +3106,10 @@ init_stats (void)
        mono_counters_register ("WBarrier object copy", MONO_COUNTER_GC | MONO_COUNTER_INT, &stat_wbarrier_object_copy);
 
        mono_counters_register ("# objects allocated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_objects_alloced);
+       mono_counters_register ("bytes allocated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_bytes_alloced);
        mono_counters_register ("# objects allocated degraded", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_objects_alloced_degraded);
+       mono_counters_register ("bytes allocated degraded", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_bytes_alloced_degraded);
+       mono_counters_register ("bytes allocated in LOS", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_bytes_alloced_los);
        mono_counters_register ("# copy_object() called (nursery)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_copy_object_called_nursery);
        mono_counters_register ("# objects copied (nursery)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_objects_copied_nursery);
        mono_counters_register ("# copy_object() called (major)", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_copy_object_called_major);
@@ -3303,17 +3155,14 @@ static gboolean
 collect_nursery (size_t requested_size)
 {
        size_t max_garbage_amount;
-       int i;
        char *orig_nursery_next;
-       Fragment *frag;
-       GCMemSection *section;
-       int old_num_major_sections = num_major_sections;
-       int sections_alloced;
        TV_DECLARE (all_atv);
        TV_DECLARE (all_btv);
        TV_DECLARE (atv);
        TV_DECLARE (btv);
 
+       current_collection_generation = GENERATION_NURSERY;
+
        init_stats ();
        binary_protocol_collection (GENERATION_NURSERY);
        check_scan_starts ();
@@ -3328,366 +3177,92 @@ collect_nursery (size_t requested_size)
        max_garbage_amount = nursery_next - nursery_start;
        g_assert (nursery_section->size >= max_garbage_amount);
 
-       /* Clear all remaining nursery fragments, pinning depends on this */
-       if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION) {
-               g_assert (orig_nursery_next <= nursery_frag_real_end);
-               memset (orig_nursery_next, 0, nursery_frag_real_end - orig_nursery_next);
-               for (frag = nursery_fragments; frag; frag = frag->next) {
-                       memset (frag->fragment_start, 0, frag->fragment_end - frag->fragment_start);
-               }
-       }
+       /* world must be stopped already */
+       TV_GETTIME (all_atv);
+       TV_GETTIME (atv);
+
+       /* Pinning depends on this */
+       clear_nursery_fragments (orig_nursery_next);
+
+       TV_GETTIME (btv);
+       time_minor_pre_collection_fragment_clear += TV_ELAPSED_MS (atv, btv);
 
        if (xdomain_checks)
                check_for_xdomain_refs ();
 
        nursery_section->next_data = nursery_next;
 
-       if (!to_space_section) {
-               new_to_space_section ();
-       } else {
-               /* we might have done degraded allocation since the
-                  last collection */
-               g_assert (to_space_bumper <= to_space_section->next_data);
-               to_space_bumper = to_space_section->next_data;
+       major_start_nursery_collection ();
 
-               to_space_section->is_to_space = TRUE;
-       }
        gray_object_queue_init ();
 
        num_minor_gcs++;
        mono_stats.minor_gc_count ++;
-       /* world must be stopped already */
-       TV_GETTIME (all_atv);
-       TV_GETTIME (atv);
        /* pin from pinned handles */
        init_pinning ();
        pin_from_roots (nursery_start, nursery_next);
        /* identify pinned objects */
        optimize_pin_queue (0);
        next_pin_slot = pin_objects_from_addresses (nursery_section, pin_queue, pin_queue + next_pin_slot, nursery_start, nursery_next);
-       TV_GETTIME (btv);
-       DEBUG (2, fprintf (gc_debug_file, "Finding pinned pointers: %d in %d usecs\n", next_pin_slot, TV_ELAPSED (atv, btv)));
+       nursery_section->pin_queue_start = 0;
+       nursery_section->pin_queue_end = next_pin_slot;
+       TV_GETTIME (atv);
+       time_minor_pinning += TV_ELAPSED_MS (btv, atv);
+       DEBUG (2, fprintf (gc_debug_file, "Finding pinned pointers: %d in %d usecs\n", next_pin_slot, TV_ELAPSED (btv, atv)));
        DEBUG (4, fprintf (gc_debug_file, "Start scan with %d pinned objects\n", next_pin_slot));
 
        if (consistency_check_at_minor_collection)
                check_consistency ();
 
        /* 
-        * walk all the roots and copy the young objects to the old generation,
-        * starting from to_space
-        */
-
-       scan_from_remsets (nursery_start, nursery_next);
-       /* we don't have complete write barrier yet, so we scan all the old generation sections */
-       TV_GETTIME (atv);
-       DEBUG (2, fprintf (gc_debug_file, "Old generation scan: %d usecs\n", TV_ELAPSED (btv, atv)));
-
-       /* the pinned objects are roots */
-       for (i = 0; i < next_pin_slot; ++i) {
-               DEBUG (6, fprintf (gc_debug_file, "Precise object scan %d of pinned %p (%s)\n", i, pin_queue [i], safe_name (pin_queue [i])));
-               scan_object (pin_queue [i], nursery_start, nursery_next);
-       }
-       /* registered roots, this includes static fields */
-       scan_from_registered_roots (nursery_start, nursery_next, ROOT_TYPE_NORMAL);
-       scan_from_registered_roots (nursery_start, nursery_next, ROOT_TYPE_WBARRIER);
-       scan_thread_data (nursery_start, nursery_next, TRUE);
-       /* alloc_pinned objects */
-       scan_from_pinned_objects (nursery_start, nursery_next);
-       TV_GETTIME (btv);
-       DEBUG (2, fprintf (gc_debug_file, "Root scan: %d usecs\n", TV_ELAPSED (atv, btv)));
-
-       finish_gray_stack (nursery_start, nursery_next, GENERATION_NURSERY);
-
-       /* walk the pin_queue, build up the fragment list of free memory, unmark
-        * pinned objects as we go, memzero() the empty fragments so they are ready for the
-        * next allocations.
-        */
-       build_nursery_fragments (0, next_pin_slot);
-       TV_GETTIME (atv);
-       DEBUG (2, fprintf (gc_debug_file, "Fragment creation: %d usecs, %zd bytes available\n", TV_ELAPSED (btv, atv), fragment_total));
-
-       for (section = section_list; section; section = section->block.next) {
-               if (section->is_to_space)
-                       section->is_to_space = FALSE;
-       }
-
-       TV_GETTIME (all_btv);
-       mono_stats.minor_gc_time_usecs += TV_ELAPSED (all_atv, all_btv);
-
-       if (heap_dump_file)
-               dump_heap ("minor", num_minor_gcs - 1, NULL);
-
-       /* prepare the pin queue for the next collection */
-       last_num_pinned = next_pin_slot;
-       next_pin_slot = 0;
-       if (fin_ready_list || critical_fin_list) {
-               DEBUG (4, fprintf (gc_debug_file, "Finalizer-thread wakeup: ready %d\n", num_ready_finalizers));
-               mono_gc_finalize_notify ();
-       }
-       pin_stats_reset ();
-
-       g_assert (gray_object_queue_is_empty ());
-
-       commit_stats (GENERATION_NURSERY);
-
-       check_scan_starts ();
-
-       sections_alloced = num_major_sections - old_num_major_sections;
-       minor_collection_sections_alloced += sections_alloced;
-
-       return minor_collection_sections_alloced > minor_collection_section_allowance;
-}
-
-static void
-scan_from_pinned_chunk_if_marked (PinnedChunk *chunk, char *obj, size_t size, void *dummy)
-{
-       if (object_is_pinned (obj))
-               scan_object (obj, NULL, (char*)-1);
-}
-
-static void
-major_collection (const char *reason)
-{
-       GCMemSection *section, *prev_section;
-       LOSObject *bigobj, *prevbo;
-       int i;
-       PinnedChunk *chunk;
-       Fragment *frag;
-       TV_DECLARE (all_atv);
-       TV_DECLARE (all_btv);
-       TV_DECLARE (atv);
-       TV_DECLARE (btv);
-       /* FIXME: only use these values for the precise scan
-        * note that to_space pointers should be excluded anyway...
-        */
-       char *heap_start = NULL;
-       char *heap_end = (char*)-1;
-       size_t copy_space_required = 0;
-       int old_num_major_sections = num_major_sections;
-       int num_major_sections_saved, save_target, allowance_target;
-
-       init_stats ();
-       binary_protocol_collection (GENERATION_OLD);
-       check_scan_starts ();
-
-       degraded_mode = 0;
-       DEBUG (1, fprintf (gc_debug_file, "Start major collection %d\n", num_major_gcs));
-       num_major_gcs++;
-       mono_stats.major_gc_count ++;
-
-       /* Clear all remaining nursery fragments, pinning depends on this */
-       if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION) {
-               g_assert (nursery_next <= nursery_frag_real_end);
-               memset (nursery_next, 0, nursery_frag_real_end - nursery_next);
-               for (frag = nursery_fragments; frag; frag = frag->next) {
-                       memset (frag->fragment_start, 0, frag->fragment_end - frag->fragment_start);
-               }
-       }
-
-       if (xdomain_checks)
-               check_for_xdomain_refs ();
-
-       /* 
-        * FIXME: implement Mark/Compact
-        * Until that is done, we can just apply mostly the same alg as for the nursery:
-        * this means we need a big section to potentially copy all the other sections, so
-        * it is not ideal specially with large heaps.
-        */
-       if (g_getenv ("MONO_GC_NO_MAJOR")) {
-               collect_nursery (0);
-               return;
-       }
-       TV_GETTIME (all_atv);
-       /* FIXME: make sure the nursery next_data ptr is updated */
-       nursery_section->next_data = nursery_real_end;
-       /* we should also coalesce scanning from sections close to each other
-        * and deal with pointers outside of the sections later.
-        */
-       /* The remsets are not useful for a major collection */
-       clear_remsets ();
-       /* world must be stopped already */
-       TV_GETTIME (atv);
-       init_pinning ();
-       DEBUG (6, fprintf (gc_debug_file, "Collecting pinned addresses\n"));
-       pin_from_roots ((void*)lowest_heap_address, (void*)highest_heap_address);
-       optimize_pin_queue (0);
-
-       /*
-        * pin_queue now contains all candidate pointers, sorted and
-        * uniqued.  We must do two passes now to figure out which
-        * objects are pinned.
-        *
-        * The first is to find within the pin_queue the area for each
-        * section.  This requires that the pin_queue be sorted.  We
-        * also process the LOS objects and pinned chunks here.
-        *
-        * The second, destructive, pass is to reduce the section
-        * areas to pointers to the actually pinned objects.
-        */
-       DEBUG (6, fprintf (gc_debug_file, "Pinning from sections\n"));
-       /* first pass for the sections */
-       for (section = section_list; section; section = section->block.next) {
-               int start, end;
-               DEBUG (6, fprintf (gc_debug_file, "Pinning from section %p (%p-%p)\n", section, section->data, section->end_data));
-               find_optimized_pin_queue_area (section->data, section->end_data, &start, &end);
-               DEBUG (6, fprintf (gc_debug_file, "Found %d pinning addresses in section %p (%d-%d)\n",
-                                               end - start, section, start, end));
-               section->pin_queue_start = start;
-               section->pin_queue_end = end;
-       }
-       /* identify possible pointers to the insize of large objects */
-       DEBUG (6, fprintf (gc_debug_file, "Pinning from large objects\n"));
-       for (bigobj = los_object_list; bigobj; bigobj = bigobj->next) {
-               int start, end;
-               find_optimized_pin_queue_area (bigobj->data, (char*)bigobj->data + bigobj->size, &start, &end);
-               if (start != end) {
-                       pin_object (bigobj->data);
-                       if (heap_dump_file)
-                               pin_stats_register_object ((char*) bigobj->data, safe_object_get_size ((MonoObject*) bigobj->data));
-                       DEBUG (6, fprintf (gc_debug_file, "Marked large object %p (%s) size: %zd from roots\n", bigobj->data, safe_name (bigobj->data), bigobj->size));
-               }
-       }
-       /* look for pinned addresses for pinned-alloc objects */
-       DEBUG (6, fprintf (gc_debug_file, "Pinning from pinned-alloc objects\n"));
-       for (chunk = pinned_chunk_list; chunk; chunk = chunk->block.next) {
-               int start, end;
-               find_optimized_pin_queue_area (chunk->start_data, (char*)chunk + chunk->num_pages * FREELIST_PAGESIZE, &start, &end);
-               if (start != end)
-                       mark_pinned_from_addresses (chunk, pin_queue + start, pin_queue + end);
-       }
-       /* second pass for the sections */
-       for (section = section_list; section; section = section->block.next) {
-               int start = section->pin_queue_start;
-               int end = section->pin_queue_end;
-               if (start != end) {
-                       int reduced_to;
-                       reduced_to = pin_objects_from_addresses (section, pin_queue + start, pin_queue + end,
-                                       section->data, section->next_data);
-                       section->pin_queue_start = start;
-                       section->pin_queue_end = start + reduced_to;
-               }
-               copy_space_required += (char*)section->next_data - (char*)section->data;
-       }
+        * walk all the roots and copy the young objects to the old generation,
+        * starting from to_space
+        */
 
+       scan_from_remsets (nursery_start, nursery_next);
+       /* we don't have complete write barrier yet, so we scan all the old generation sections */
        TV_GETTIME (btv);
-       DEBUG (2, fprintf (gc_debug_file, "Finding pinned pointers: %d in %d usecs\n", next_pin_slot, TV_ELAPSED (atv, btv)));
-       DEBUG (4, fprintf (gc_debug_file, "Start scan with %d pinned objects\n", next_pin_slot));
+       time_minor_scan_remsets += TV_ELAPSED_MS (atv, btv);
+       DEBUG (2, fprintf (gc_debug_file, "Old generation scan: %d usecs\n", TV_ELAPSED (atv, btv)));
 
-       new_to_space_section ();
-       gray_object_queue_init ();
+       drain_gray_stack ();
 
-       /* the old generation doesn't need to be scanned (no remembered sets or card
-        * table needed either): the only objects that must survive are those pinned and
-        * those referenced by the precise roots.
-        * mark any section without pinned objects, so we can free it since we will be able to
-        * move all the objects.
-        */
-       /* the pinned objects are roots (big objects are included in this list, too) */
-       for (section = section_list; section; section = section->block.next) {
-               for (i = section->pin_queue_start; i < section->pin_queue_end; ++i) {
-                       DEBUG (6, fprintf (gc_debug_file, "Precise object scan %d of pinned %p (%s)\n",
-                                                       i, pin_queue [i], safe_name (pin_queue [i])));
-                       scan_object (pin_queue [i], heap_start, heap_end);
-               }
-       }
-       for (bigobj = los_object_list; bigobj; bigobj = bigobj->next) {
-               if (object_is_pinned (bigobj->data)) {
-                       DEBUG (6, fprintf (gc_debug_file, "Precise object scan pinned LOS object %p (%s)\n",
-                                                       bigobj->data, safe_name (bigobj->data)));
-                       scan_object (bigobj->data, heap_start, heap_end);
-               }
-       }
-       scan_pinned_objects (scan_from_pinned_chunk_if_marked, NULL);
+       TV_GETTIME (atv);
+       time_minor_scan_pinned += TV_ELAPSED_MS (btv, atv);
        /* registered roots, this includes static fields */
-       scan_from_registered_roots (heap_start, heap_end, ROOT_TYPE_NORMAL);
-       scan_from_registered_roots (heap_start, heap_end, ROOT_TYPE_WBARRIER);
-       /* Threads */
-       scan_thread_data (heap_start, heap_end, TRUE);
-       /* alloc_pinned objects */
-       scan_from_pinned_objects (heap_start, heap_end);
-       /* scan the list of objects ready for finalization */
-       scan_finalizer_entries (fin_ready_list, heap_start, heap_end);
-       scan_finalizer_entries (critical_fin_list, heap_start, heap_end);
+       scan_from_registered_roots (copy_object, nursery_start, nursery_next, ROOT_TYPE_NORMAL);
+       scan_from_registered_roots (copy_object, nursery_start, nursery_next, ROOT_TYPE_WBARRIER);
+       TV_GETTIME (btv);
+       time_minor_scan_registered_roots += TV_ELAPSED_MS (atv, btv);
+       /* thread data */
+       scan_thread_data (nursery_start, nursery_next, TRUE);
        TV_GETTIME (atv);
-       DEBUG (2, fprintf (gc_debug_file, "Root scan: %d usecs\n", TV_ELAPSED (btv, atv)));
+       time_minor_scan_thread_data += TV_ELAPSED_MS (btv, atv);
+       btv = atv;
 
-       /* we need to go over the big object list to see if any was marked and scan it
-        * And we need to make this in a loop, considering that objects referenced by finalizable
-        * objects could reference big objects (this happens in finish_gray_stack ())
-        */
-       scan_needed_big_objects (heap_start, heap_end);
-       /* all the objects in the heap */
-       finish_gray_stack (heap_start, heap_end, GENERATION_OLD);
-
-       unset_to_space ();
-
-       /* sweep the big objects list */
-       prevbo = NULL;
-       for (bigobj = los_object_list; bigobj;) {
-               if (object_is_pinned (bigobj->data)) {
-                       unpin_object (bigobj->data);
-                       bigobj->scanned = FALSE;
-               } else {
-                       LOSObject *to_free;
-                       /* not referenced anywhere, so we can free it */
-                       if (prevbo)
-                               prevbo->next = bigobj->next;
-                       else
-                               los_object_list = bigobj->next;
-                       to_free = bigobj;
-                       bigobj = bigobj->next;
-                       free_large_object (to_free);
-                       continue;
-               }
-               prevbo = bigobj;
-               bigobj = bigobj->next;
-       }
-       /* unpin objects from the pinned chunks and free the unmarked ones */
-       sweep_pinned_objects ();
-
-       /* free the unused sections */
-       prev_section = NULL;
-       for (section = section_list; section;) {
-               /* to_space doesn't need handling here and the nursery is special */
-               if (section->is_to_space || section == nursery_section) {
-                       if (section->is_to_space)
-                               section->is_to_space = FALSE;
-                       prev_section = section;
-                       section = section->block.next;
-                       continue;
-               }
-               /* no pinning object, so the section is free */
-               if (section->pin_queue_start == section->pin_queue_end) {
-                       GCMemSection *to_free;
-                       if (prev_section)
-                               prev_section->block.next = section->block.next;
-                       else
-                               section_list = section->block.next;
-                       to_free = section;
-                       section = section->block.next;
-                       free_major_section (to_free);
-                       continue;
-               } else {
-                       DEBUG (6, fprintf (gc_debug_file, "Section %p has still pinned objects (%d)\n", section, section->pin_queue_end - section->pin_queue_start));
-                       build_section_fragments (section);
-               }
-               prev_section = section;
-               section = section->block.next;
-       }
+       finish_gray_stack (nursery_start, nursery_next, GENERATION_NURSERY);
+       TV_GETTIME (atv);
+       time_minor_finish_gray_stack += TV_ELAPSED_MS (btv, atv);
 
        /* walk the pin_queue, build up the fragment list of free memory, unmark
         * pinned objects as we go, memzero() the empty fragments so they are ready for the
         * next allocations.
         */
-       build_nursery_fragments (nursery_section->pin_queue_start, nursery_section->pin_queue_end);
+       build_nursery_fragments (0, next_pin_slot);
+       TV_GETTIME (btv);
+       time_minor_fragment_creation += TV_ELAPSED_MS (atv, btv);
+       DEBUG (2, fprintf (gc_debug_file, "Fragment creation: %d usecs, %zd bytes available\n", TV_ELAPSED (atv, btv), fragment_total));
+
+       major_finish_nursery_collection ();
 
        TV_GETTIME (all_btv);
-       mono_stats.major_gc_time_usecs += TV_ELAPSED (all_atv, all_btv);
+       mono_stats.minor_gc_time_usecs += TV_ELAPSED (all_atv, all_btv);
 
        if (heap_dump_file)
-               dump_heap ("major", num_major_gcs - 1, reason);
+               dump_heap ("minor", num_minor_gcs - 1, NULL);
 
        /* prepare the pin queue for the next collection */
+       last_num_pinned = next_pin_slot;
        next_pin_slot = 0;
        if (fin_ready_list || critical_fin_list) {
                DEBUG (4, fprintf (gc_debug_file, "Finalizer-thread wakeup: ready %d\n", num_ready_finalizers));
@@ -3697,67 +3272,26 @@ major_collection (const char *reason)
 
        g_assert (gray_object_queue_is_empty ());
 
-       commit_stats (GENERATION_OLD);
-
-       num_major_sections_saved = MAX (old_num_major_sections - num_major_sections, 1);
-
-       save_target = num_major_sections / 2;
-       allowance_target = save_target * minor_collection_sections_alloced / num_major_sections_saved;
-
-       minor_collection_section_allowance = MAX (MIN (allowance_target, num_major_sections), MIN_MINOR_COLLECTION_SECTION_ALLOWANCE);
-
-       /*
-       printf ("alloced %d  saved %d  target %d  allowance %d\n",
-                       minor_collection_sections_alloced, num_major_sections_saved, allowance_target,
-                       minor_collection_section_allowance);
-       */
-
-       minor_collection_sections_alloced = 0;
+       commit_stats (GENERATION_NURSERY);
 
        check_scan_starts ();
-}
-
-/*
- * Allocate a new section of memory to be used as old generation.
- */
-static GCMemSection*
-alloc_major_section (void)
-{
-       GCMemSection *section;
-       int scan_starts;
-
-       section = get_os_memory_aligned (MAJOR_SECTION_SIZE, TRUE);
-       section->next_data = section->data = (char*)section + SIZEOF_GC_MEM_SECTION;
-       g_assert (!((mword)section->data & 7));
-       section->size = MAJOR_SECTION_SIZE - SIZEOF_GC_MEM_SECTION;
-       section->end_data = section->data + section->size;
-       UPDATE_HEAP_BOUNDARIES (section->data, section->end_data);
-       total_alloc += section->size;
-       DEBUG (3, fprintf (gc_debug_file, "New major heap section: (%p-%p), total: %zd\n", section->data, section->end_data, total_alloc));
-       scan_starts = (section->size + SCAN_START_SIZE - 1) / SCAN_START_SIZE;
-       section->scan_starts = get_internal_mem (sizeof (char*) * scan_starts, INTERNAL_MEM_SCAN_STARTS);
-       section->num_scan_start = scan_starts;
-       section->block.role = MEMORY_ROLE_GEN1;
-       section->is_to_space = TRUE;
 
-       /* add to the section list */
-       section->block.next = section_list;
-       section_list = section;
+       current_collection_generation = -1;
 
-       ++num_major_sections;
-
-       return section;
+       return major_need_major_collection ();
 }
 
 static void
-free_major_section (GCMemSection *section)
+major_collection (const char *reason)
 {
-       DEBUG (3, fprintf (gc_debug_file, "Freed major section %p (%p-%p)\n", section, section->data, section->end_data));
-       free_internal_mem (section->scan_starts, INTERNAL_MEM_SCAN_STARTS);
-       free_os_memory (section, MAJOR_SECTION_SIZE);
-       total_alloc -= MAJOR_SECTION_SIZE - SIZEOF_GC_MEM_SECTION;
+       if (g_getenv ("MONO_GC_NO_MAJOR")) {
+               collect_nursery (0);
+               return;
+       }
 
-       --num_major_sections;
+       current_collection_generation = GENERATION_OLD;
+       major_do_collection (reason);
+       current_collection_generation = -1;
 }
 
 /*
@@ -3872,120 +3406,7 @@ report_internal_mem_usage (void) {
                report_pinned_chunk (chunk, i++);
        }
        printf ("Pinned memory usage:\n");
-       i = 0;
-       for (chunk = pinned_chunk_list; chunk; chunk = chunk->block.next) {
-               report_pinned_chunk (chunk, i++);
-       }
-}
-
-/*
- * the array of pointers from @start to @end contains conservative
- * pointers to objects inside @chunk: mark each referenced object
- * with the PIN bit.
- */
-static void
-mark_pinned_from_addresses (PinnedChunk *chunk, void **start, void **end)
-{
-       for (; start < end; start++) {
-               char *addr = *start;
-               int offset = (char*)addr - (char*)chunk;
-               int page = offset / FREELIST_PAGESIZE;
-               int obj_offset = page == 0? offset - ((char*)chunk->start_data - (char*)chunk): offset % FREELIST_PAGESIZE;
-               int slot_size = chunk->page_sizes [page];
-               void **ptr;
-               /* the page is not allocated */
-               if (!slot_size)
-                       continue;
-               /* would be faster if we restrict the sizes to power of two,
-                * but that's a waste of memory: need to measure. it could reduce
-                * fragmentation since there are less pages needed, if for example
-                * someone interns strings of each size we end up with one page per
-                * interned string (still this is just ~40 KB): with more fine-grained sizes
-                * this increases the number of used pages.
-                */
-               if (page == 0) {
-                       obj_offset /= slot_size;
-                       obj_offset *= slot_size;
-                       addr = (char*)chunk->start_data + obj_offset;
-               } else {
-                       obj_offset /= slot_size;
-                       obj_offset *= slot_size;
-                       addr = (char*)chunk + page * FREELIST_PAGESIZE + obj_offset;
-               }
-               ptr = (void**)addr;
-               /* if the vtable is inside the chunk it's on the freelist, so skip */
-               if (*ptr && (*ptr < (void*)chunk->start_data || *ptr > (void*)((char*)chunk + chunk->num_pages * FREELIST_PAGESIZE))) {
-                       binary_protocol_pin (addr, (gpointer)LOAD_VTABLE (addr), safe_object_get_size ((MonoObject*)addr));
-                       pin_object (addr);
-                       if (heap_dump_file)
-                               pin_stats_register_object ((char*) addr, safe_object_get_size ((MonoObject*) addr));
-                       DEBUG (6, fprintf (gc_debug_file, "Marked pinned object %p (%s) from roots\n", addr, safe_name (addr)));
-               }
-       }
-}
-
-static void
-scan_pinned_objects (ScanPinnedObjectCallbackFunc callback, void *callback_data)
-{
-       PinnedChunk *chunk;
-       int i, obj_size;
-       char *p, *endp;
-       void **ptr;
-       void *end_chunk;
-       for (chunk = pinned_chunk_list; chunk; chunk = chunk->block.next) {
-               end_chunk = (char*)chunk + chunk->num_pages * FREELIST_PAGESIZE;
-               DEBUG (6, fprintf (gc_debug_file, "Scanning pinned chunk %p (range: %p-%p)\n", chunk, chunk->start_data, end_chunk));
-               for (i = 0; i < chunk->num_pages; ++i) {
-                       obj_size = chunk->page_sizes [i];
-                       if (!obj_size)
-                               continue;
-                       p = i? (char*)chunk + i * FREELIST_PAGESIZE: chunk->start_data;
-                       endp = i? p + FREELIST_PAGESIZE: (char*)chunk + FREELIST_PAGESIZE;
-                       DEBUG (6, fprintf (gc_debug_file, "Page %d (size: %d, range: %p-%p)\n", i, obj_size, p, endp));
-                       while (p + obj_size <= endp) {
-                               ptr = (void**)p;
-                               DEBUG (9, fprintf (gc_debug_file, "Considering %p (vtable: %p)\n", ptr, *ptr));
-                               /* if the first word (the vtable) is outside the chunk we have an object */
-                               if (*ptr && (*ptr < (void*)chunk || *ptr >= end_chunk))
-                                       callback (chunk, (char*)ptr, obj_size, callback_data);
-                               p += obj_size;
-                       }
-               }
-       }
-}
-
-static void
-sweep_pinned_objects_callback (PinnedChunk *chunk, char *ptr, size_t size, void *data)
-{
-       if (object_is_pinned (ptr)) {
-               unpin_object (ptr);
-               DEBUG (6, fprintf (gc_debug_file, "Unmarked pinned object %p (%s)\n", ptr, safe_name (ptr)));
-       } else {
-               DEBUG (6, fprintf (gc_debug_file, "Freeing unmarked pinned object %p (%s)\n", ptr, safe_name (ptr)));
-               free_pinned_object (chunk, ptr, size);
-       }
-}
-
-static void
-sweep_pinned_objects (void)
-{
-       scan_pinned_objects (sweep_pinned_objects_callback, NULL);
-}
-
-static void
-scan_object_callback (PinnedChunk *chunk, char *ptr, size_t size, char **data)
-{
-       DEBUG (6, fprintf (gc_debug_file, "Precise object scan of alloc_pinned %p (%s)\n", ptr, safe_name (ptr)));
-       /* FIXME: Put objects without references into separate chunks
-          which do not need to be scanned */
-       scan_object (ptr, data [0], data [1]);
-}
-
-static void
-scan_from_pinned_objects (char *addr_start, char *addr_end)
-{
-       char *data [2] = { addr_start, addr_end };
-       scan_pinned_objects ((ScanPinnedObjectCallbackFunc)scan_object_callback, data);
+       major_report_pinned_memory_usage ();
 }
 
 /*
@@ -4033,9 +3454,9 @@ alloc_pinned_chunk (void)
 {
        PinnedChunk *chunk;
        int offset;
-       int size = MAJOR_SECTION_SIZE;
+       int size = PINNED_CHUNK_SIZE;
 
-       chunk = get_os_memory_aligned (size, TRUE);
+       chunk = get_os_memory_aligned (size, size, TRUE);
        chunk->block.role = MEMORY_ROLE_PINNED;
 
        UPDATE_HEAP_BOUNDARIES (chunk, ((char*)chunk + size));
@@ -4059,8 +3480,6 @@ alloc_pinned_chunk (void)
        chunk->page_sizes [0] = PINNED_FIRST_SLOT_SIZE;
        build_freelist (chunk, slot_for_size (PINNED_FIRST_SLOT_SIZE), PINNED_FIRST_SLOT_SIZE, chunk->start_data, ((char*)chunk + FREELIST_PAGESIZE));
        DEBUG (4, fprintf (gc_debug_file, "Allocated pinned chunk %p, size: %d\n", chunk, size));
-       min_pinned_chunk_addr = MIN (min_pinned_chunk_addr, (char*)chunk->start_data);
-       max_pinned_chunk_addr = MAX (max_pinned_chunk_addr, ((char*)chunk + size));
        return chunk;
 }
 
@@ -4093,40 +3512,7 @@ get_chunk_freelist (PinnedChunk *chunk, int slot)
        return NULL;
 }
 
-static void*
-alloc_from_freelist (size_t size)
-{
-       int slot;
-       void *res = NULL;
-       PinnedChunk *pchunk;
-       slot = slot_for_size (size);
-       /*g_print ("using slot %d for size %d (slot size: %d)\n", slot, size, freelist_sizes [slot]);*/
-       g_assert (size <= freelist_sizes [slot]);
-       for (pchunk = pinned_chunk_list; pchunk; pchunk = pchunk->block.next) {
-               void **p = pchunk->free_list [slot];
-               if (p) {
-                       /*g_print ("found freelist for slot %d in chunk %p, returning %p, next %p\n", slot, pchunk, p, *p);*/
-                       pchunk->free_list [slot] = *p;
-                       return p;
-               }
-       }
-       for (pchunk = pinned_chunk_list; pchunk; pchunk = pchunk->block.next) {
-               res = get_chunk_freelist (pchunk, slot);
-               if (res)
-                       return res;
-       }
-       pchunk = alloc_pinned_chunk ();
-       /* FIXME: handle OOM */
-       pchunk->block.next = pinned_chunk_list;
-       pinned_chunk_list = pchunk;
-       res = get_chunk_freelist (pchunk, slot);
-       return res;
-}
-
 /* used for the GC-internal data structures */
-/* FIXME: add support for bigger sizes by allocating more than one page
- * in the chunk.
- */
 static void*
 get_internal_mem (size_t size, int type)
 {
@@ -4244,18 +3630,41 @@ alloc_large_inner (MonoVTable *vtable, size_t size)
        LOSObject *obj;
        void **vtslot;
        size_t alloc_size;
-       int just_did_major_gc = FALSE;
 
        g_assert (size > MAX_SMALL_OBJ_SIZE);
 
        if (los_memory_usage > next_los_collection) {
+               static mword last_los_memory_usage = 0;
+
+               mword los_memory_alloced;
+               mword old_los_memory_usage;
+               mword los_memory_saved;
+               mword save_target;
+               mword allowance_target;
+               mword allowance;
+
                DEBUG (4, fprintf (gc_debug_file, "Should trigger major collection: req size %zd (los already: %zu, limit: %zu)\n", size, los_memory_usage, next_los_collection));
-               just_did_major_gc = TRUE;
                stop_world ();
+
+               g_assert (los_memory_usage >= last_los_memory_usage);
+               los_memory_alloced = los_memory_usage - last_los_memory_usage;
+               old_los_memory_usage = los_memory_usage;
+
                major_collection ("LOS overflow");
+
+               los_memory_saved = MAX (old_los_memory_usage - los_memory_usage, 1);
+               save_target = los_memory_usage / 2;
+               /*
+                * see the comment at the end of major_collection()
+                * for the explanation for this calculation.
+                */
+               allowance_target = (mword)((double)save_target * (double)los_memory_alloced / (double)los_memory_saved);
+               allowance = MAX (MIN (allowance_target, los_memory_usage), MIN_LOS_ALLOWANCE);
+               next_los_collection = los_memory_usage + allowance;
+
+               last_los_memory_usage = los_memory_usage;
+
                restart_world ();
-               /* later increase based on a percent of the heap size */
-               next_los_collection = los_memory_usage + 5*1024*1024;
        }
        alloc_size = size;
        alloc_size += sizeof (LOSObject);
@@ -4263,6 +3672,7 @@ alloc_large_inner (MonoVTable *vtable, size_t size)
        alloc_size &= ~(pagesize - 1);
        /* FIXME: handle OOM */
        obj = get_os_memory (alloc_size, TRUE);
+       g_assert (!((mword)obj->data & (ALLOC_ALIGN - 1)));
        obj->size = size;
        vtslot = (void**)obj->data;
        *vtslot = vtable;
@@ -4312,35 +3722,6 @@ search_fragment_for_size (size_t size)
        return FALSE;
 }
 
-/*
- * size is already rounded up and we hold the GC lock.
- */
-static void*
-alloc_degraded (MonoVTable *vtable, size_t size)
-{
-       GCMemSection *section;
-       void **p = NULL;
-       g_assert (size <= MAX_SMALL_OBJ_SIZE);
-       HEAVY_STAT (++stat_objects_alloced_degraded);
-       for (section = section_list; section; section = section->block.next) {
-               if (section != nursery_section && (section->end_data - section->next_data) >= size) {
-                       p = (void**)section->next_data;
-                       break;
-               }
-       }
-       if (!p) {
-               section = alloc_major_section ();
-               section->is_to_space = FALSE;
-               /* FIXME: handle OOM */
-               p = (void**)section->next_data;
-       }
-       section->next_data += size;
-       degraded_mode += size;
-       DEBUG (3, fprintf (gc_debug_file, "Allocated (degraded) object %p, vtable: %p (%s), size: %zd in section %p\n", p, vtable, vtable->klass->name, size, section));
-       *p = vtable;
-       return p;
-}
-
 /*
  * Provide a variant that takes just the vtable for small fixed-size objects.
  * The aligned size is already computed and stored in vt->gc_descr.
@@ -4359,6 +3740,10 @@ mono_gc_alloc_obj_nolock (MonoVTable *vtable, size_t size)
        TLAB_ACCESS_INIT;
 
        HEAVY_STAT (++stat_objects_alloced);
+       if (size <= MAX_SMALL_OBJ_SIZE)
+               HEAVY_STAT (stat_bytes_alloced += size);
+       else
+               HEAVY_STAT (stat_bytes_alloced_los += size);
 
        size += ALLOC_ALIGN - 1;
        size &= ~(ALLOC_ALIGN - 1);
@@ -4544,6 +3929,7 @@ mono_gc_try_alloc_obj_nolock (MonoVTable *vtable, size_t size)
                         */
 
                        HEAVY_STAT (++stat_objects_alloced);
+                       HEAVY_STAT (stat_bytes_alloced += size);
 
                        DEBUG (6, fprintf (gc_debug_file, "Allocated object %p, vtable: %p (%s), size: %zd\n", p, vtable, vtable->klass->name, size));
                        binary_protocol_alloc (p, vtable, size);
@@ -4579,7 +3965,7 @@ mono_gc_alloc_obj (MonoVTable *vtable, size_t size)
 }
 
 void*
-mono_gc_alloc_vector (MonoVTable *vtable, size_t size, mono_array_size_t max_length)
+mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length)
 {
        MonoArray *arr;
 #ifndef DISABLE_CRITICAL_REGION
@@ -4605,7 +3991,7 @@ mono_gc_alloc_vector (MonoVTable *vtable, size_t size, mono_array_size_t max_len
 }
 
 void*
-mono_gc_alloc_array (MonoVTable *vtable, size_t size, mono_array_size_t max_length, mono_array_size_t bounds_size)
+mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uintptr_t bounds_size)
 {
        MonoArray *arr;
        MonoArrayBounds *bounds;
@@ -4661,12 +4047,11 @@ mono_gc_alloc_pinned_obj (MonoVTable *vtable, size_t size)
        size += ALLOC_ALIGN - 1;
        size &= ~(ALLOC_ALIGN - 1);
        LOCK_GC;
-       if (size > MAX_FREELIST_SIZE) {
+       if (size > MAX_SMALL_OBJ_SIZE) {
                /* large objects are always pinned anyway */
                p = alloc_large_inner (vtable, size);
        } else {
-               p = alloc_from_freelist (size);
-               memset (p, 0, size);
+               p = major_alloc_small_pinned_obj (size);
        }
        DEBUG (6, fprintf (gc_debug_file, "Allocated pinned object %p, vtable: %p (%s), size: %zd\n", p, vtable, vtable->klass->name, size));
        binary_protocol_alloc (p, vtable, size);
@@ -4750,7 +4135,7 @@ rehash_fin_table_if_necessary (FinalizeEntryHashTable *hash_table)
 
 /* LOCKING: requires that the GC lock is held */
 static void
-finalize_in_range (char *start, char *end, int generation)
+finalize_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int generation)
 {
        FinalizeEntryHashTable *hash_table = get_finalize_entry_hash_table (generation);
        FinalizeEntry *entry, *prev;
@@ -4763,9 +4148,10 @@ finalize_in_range (char *start, char *end, int generation)
        for (i = 0; i < finalizable_hash_size; ++i) {
                prev = NULL;
                for (entry = finalizable_hash [i]; entry;) {
-                       if ((char*)entry->object >= start && (char*)entry->object < end && !object_is_in_to_space (entry->object)) {
+                       if ((char*)entry->object >= start && (char*)entry->object < end && !major_is_object_live (entry->object)) {
                                gboolean is_fin_ready = object_is_fin_ready (entry->object);
-                               char *copy = copy_object (entry->object, start, end);
+                               char *copy = entry->object;
+                               copy_func ((void**)&copy);
                                if (is_fin_ready) {
                                        char *from;
                                        FinalizeEntry *next;
@@ -4825,7 +4211,7 @@ finalize_in_range (char *start, char *end, int generation)
 
 /* LOCKING: requires that the GC lock is held */
 static void
-null_link_in_range (char *start, char *end, int generation)
+null_link_in_range (CopyOrMarkObjectFunc copy_func, char *start, char *end, int generation)
 {
        DisappearingLinkHashTable *hash = get_dislink_hash_table (generation);
        DisappearingLink **disappearing_link_hash = hash->table;
@@ -4838,7 +4224,7 @@ null_link_in_range (char *start, char *end, int generation)
                prev = NULL;
                for (entry = disappearing_link_hash [i]; entry;) {
                        char *object = DISLINK_OBJECT (entry);
-                       if (object >= start && object < end && !object_is_in_to_space (object)) {
+                       if (object >= start && object < end && !major_is_object_live (object)) {
                                gboolean track = DISLINK_TRACK (entry);
                                if (!track && object_is_fin_ready (object)) {
                                        void **p = entry->link;
@@ -4856,7 +4242,8 @@ null_link_in_range (char *start, char *end, int generation)
                                        hash->num_links--;
                                        continue;
                                } else {
-                                       char *copy = copy_object (object, start, end);
+                                       char *copy = object;
+                                       copy_func ((void**)&copy);
 
                                        /* Update pointer if it's moved.  If the object
                                         * has been moved out of the nursery, we need to
@@ -5446,12 +4833,14 @@ signal_desc (int signum)
  */
 //#define XDOMAIN_CHECKS_IN_WBARRIER
 
+#ifndef BINARY_PROTOCOL
 #ifndef HEAVY_STATISTICS
 #define MANAGED_ALLOCATION
 #ifndef XDOMAIN_CHECKS_IN_WBARRIER
 #define MANAGED_WBARRIER
 #endif
 #endif
+#endif
 
 static gboolean
 is_ip_in_managed_allocator (MonoDomain *domain, gpointer ip);
@@ -5649,6 +5038,18 @@ restart_handler (int sig)
        errno = old_errno;
 }
 
+static void
+acquire_gc_locks (void)
+{
+       LOCK_INTERRUPTION;
+}
+
+static void
+release_gc_locks (void)
+{
+       UNLOCK_INTERRUPTION;
+}
+
 static TV_DECLARE (stop_world_time);
 static unsigned long max_pause_usec = 0;
 
@@ -5658,6 +5059,8 @@ stop_world (void)
 {
        int count;
 
+       acquire_gc_locks ();
+
        update_current_thread_stack (&count);
 
        global_stop_count++;
@@ -5693,6 +5096,8 @@ restart_world (void)
                }
        }
 
+       release_gc_locks ();
+
        count = thread_handshake (restart_signal_num);
        TV_GETTIME (end_sw);
        usec = TV_ELAPSED (stop_world_time, end_sw);
@@ -5721,9 +5126,13 @@ mono_gc_conservatively_scan_area (void *start, void *end)
 void*
 mono_gc_scan_object (void *obj)
 {
-       return copy_object (obj, scan_area_arg_start, scan_area_arg_end);
+       if (current_collection_generation == GENERATION_NURSERY)
+               copy_object (&obj);
+       else
+               major_copy_or_mark_object (&obj);
+       return obj;
 }
-       
+
 /*
  * Mark from thread stacks and registers.
  */
@@ -5739,7 +5148,7 @@ scan_thread_data (void *start_nursery, void *end_nursery, gboolean precise)
        for (i = 0; i < THREAD_HASH_SIZE; ++i) {
                for (info = thread_table [i]; info; info = info->next) {
                        if (info->skip) {
-                               DEBUG (2, fprintf (gc_debug_file, "Skipping dead thread %p, range: %p-%p, size: %zd\n", info, info->stack_start, info->stack_end, (char*)info->stack_end - (char*)info->stack_start));
+                               DEBUG (3, fprintf (gc_debug_file, "Skipping dead thread %p, range: %p-%p, size: %zd\n", info, info->stack_start, info->stack_end, (char*)info->stack_end - (char*)info->stack_start));
                                continue;
                        }
                        DEBUG (3, fprintf (gc_debug_file, "Scanning thread %p, range: %p-%p, size: %zd, pinned=%d\n", info, info->stack_start, info->stack_end, (char*)info->stack_end - (char*)info->stack_start, next_pin_slot));
@@ -5807,7 +5216,7 @@ handle_remset (mword *p, void *start_nursery, void *end_nursery, gboolean global
                //__builtin_prefetch (ptr);
                if (((void*)ptr < start_nursery || (void*)ptr >= end_nursery)) {
                        gpointer old = *ptr;
-                       *ptr = copy_object (*ptr, start_nursery, end_nursery);
+                       copy_object (ptr);
                        DEBUG (9, fprintf (gc_debug_file, "Overwrote remset at %p with %p\n", ptr, *ptr));
                        if (old)
                                binary_protocol_ptr_update (ptr, old, *ptr, (gpointer)LOAD_VTABLE (*ptr), safe_object_get_size (*ptr));
@@ -5829,7 +5238,7 @@ handle_remset (mword *p, void *start_nursery, void *end_nursery, gboolean global
                        return p + 2;
                count = p [1];
                while (count-- > 0) {
-                       *ptr = copy_object (*ptr, start_nursery, end_nursery);
+                       copy_object (ptr);
                        DEBUG (9, fprintf (gc_debug_file, "Overwrote remset at %p with %p (count: %d)\n", ptr, *ptr, (int)count));
                        if (!global && *ptr >= start_nursery && *ptr < end_nursery)
                                add_to_global_remset (ptr, FALSE);
@@ -5840,7 +5249,7 @@ handle_remset (mword *p, void *start_nursery, void *end_nursery, gboolean global
                ptr = (void**)(*p & ~REMSET_TYPE_MASK);
                if (((void*)ptr >= start_nursery && (void*)ptr < end_nursery))
                        return p + 1;
-               scan_object ((char*)ptr, start_nursery, end_nursery);
+               scan_object ((char*)ptr);
                return p + 1;
        case REMSET_OTHER: {
                ptr = (void**)(*p & ~REMSET_TYPE_MASK);
@@ -5856,7 +5265,7 @@ handle_remset (mword *p, void *start_nursery, void *end_nursery, gboolean global
                        return p + 4;
                case REMSET_ROOT_LOCATION:
                        /* Same as REMSET_LOCATION, but the address is not required to be in the heap */
-                       *ptr = copy_object (*ptr, start_nursery, end_nursery);
+                       copy_object (ptr);
                        DEBUG (9, fprintf (gc_debug_file, "Overwrote root location remset at %p with %p\n", ptr, *ptr));
                        if (!global && *ptr >= start_nursery && *ptr < end_nursery) {
                                /*
@@ -6124,7 +5533,7 @@ clear_remsets (void)
                                next = remset->next;
                                remset->next = NULL;
                                if (remset != info->remset) {
-                                       DEBUG (1, fprintf (gc_debug_file, "Freed remset at %p\n", remset->data));
+                                       DEBUG (3, fprintf (gc_debug_file, "Freed remset at %p\n", remset->data));
                                        free_internal_mem (remset, INTERNAL_MEM_REMSET);
                                }
                        }
@@ -6220,6 +5629,7 @@ gc_register_current_thread (void *addr)
        }
 #elif defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
                 info->stack_end = (char*)pthread_get_stackaddr_np (pthread_self ());
+                info->stack_start_limit = (char*)info->stack_end - pthread_get_stacksize_np (pthread_self ());
 #else
        {
                /* FIXME: we assume the stack grows down */
@@ -6427,9 +5837,7 @@ alloc_remset (int size, gpointer id) {
  * Note: the write barriers first do the needed GC work and then do the actual store:
  * this way the value is visible to the conservative GC scan after the write barrier
  * itself. If a GC interrupts the barrier in the middle, value will be kept alive by
- * the conservative scan, otherwise by the remembered set scan. FIXME: figure out what
- * happens when we need to record which pointers contain references to the new generation.
- * The write barrier will be executed, but the pointer is still not stored.
+ * the conservative scan, otherwise by the remembered set scan.
  */
 void
 mono_gc_wbarrier_set_field (MonoObject *obj, gpointer field_ptr, MonoObject* value)
@@ -6548,7 +5956,7 @@ find_object_for_ptr_in_area (char *ptr, char *start, char *end)
 static char *found_obj;
 
 static void
-find_object_for_ptr_in_pinned_chunk_callback (PinnedChunk *chunk, char *obj, size_t size, char *ptr)
+find_object_for_ptr_callback (char *obj, size_t size, char *ptr)
 {
        if (ptr >= obj && ptr < obj + size) {
                g_assert (!found_obj);
@@ -6561,21 +5969,22 @@ char* find_object_for_ptr (char *ptr);
 char*
 find_object_for_ptr (char *ptr)
 {
-       GCMemSection *section;
        LOSObject *bigobj;
 
-       for (section = section_list; section; section = section->block.next) {
-               if (ptr >= section->data && ptr < section->end_data)
-                       return find_object_for_ptr_in_area (ptr, section->data, section->end_data);
-       }
+       if (ptr >= nursery_section->data && ptr < nursery_section->end_data)
+               return find_object_for_ptr_in_area (ptr, nursery_section->data, nursery_section->end_data);
 
        for (bigobj = los_object_list; bigobj; bigobj = bigobj->next) {
                if (ptr >= bigobj->data && ptr < bigobj->data + bigobj->size)
                        return bigobj->data;
        }
 
+       /*
+        * Very inefficient, but this is debugging code, supposed to
+        * be called from gdb, so we don't care.
+        */
        found_obj = NULL;
-       scan_pinned_objects ((ScanPinnedObjectCallbackFunc)find_object_for_ptr_in_pinned_chunk_callback, ptr);
+       major_iterate_objects (TRUE, TRUE, (IterateObjectCallbackFunc)find_object_for_ptr_callback, ptr);
        return found_obj;
 }
 
@@ -6745,7 +6154,7 @@ mono_gc_wbarrier_object_copy (MonoObject* obj, MonoObject *src)
        TLAB_ACCESS_INIT;
        HEAVY_STAT (++stat_wbarrier_object_copy);
        rs = REMEMBERED_SET;
-       DEBUG (1, fprintf (gc_debug_file, "Adding object remset for %p\n", obj));
+       DEBUG (6, fprintf (gc_debug_file, "Adding object remset for %p\n", obj));
        size = mono_object_class (obj)->instance_size;
        LOCK_GC;
        /* do not copy the sync state */
@@ -6790,7 +6199,6 @@ const char*descriptor_types [] = {
 void
 describe_ptr (char *ptr)
 {
-       GCMemSection *section;
        MonoVTable *vtable;
        mword desc;
        int type;
@@ -6798,13 +6206,7 @@ describe_ptr (char *ptr)
        if (ptr_in_nursery (ptr)) {
                printf ("Pointer inside nursery.\n");
        } else {
-               for (section = section_list; section;) {
-                       if (ptr >= section->data && ptr < section->data + section->size)
-                               break;
-                       section = section->block.next;
-               }
-
-               if (section) {
+               if (major_ptr_is_in_non_pinned_space (ptr)) {
                        printf ("Pointer inside oldspace.\n");
                } else if (obj_is_from_pinned_alloc (ptr)) {
                        printf ("Pointer is inside a pinned chunk.\n");
@@ -6991,29 +6393,17 @@ static gboolean missing_remsets;
        } while (0)
 
 /*
- * Check that each object reference inside the area which points into the nursery
- * can be found in the remembered sets.
+ * Check that each object reference which points into the nursery can
+ * be found in the remembered sets.
  */
-static void __attribute__((noinline))
-check_remsets_for_area (char *start, char *end)
+static void
+check_consistency_callback (char *start, size_t size, void *dummy)
 {
-       GCVTable *vt;
-       int type_str = 0, type_rlen = 0, type_bitmap = 0, type_vector = 0, type_lbit = 0, type_complex = 0;
-       while (start < end) {
-               if (!*(void**)start) {
-                       start += sizeof (void*); /* should be ALLOC_ALIGN, really */
-                       continue;
-               }
-               vt = (GCVTable*)LOAD_VTABLE (start);
-               DEBUG (8, fprintf (gc_debug_file, "Scanning object %p, vtable: %p (%s)\n", start, vt, vt->klass->name));
-               if (0) {
-                       MonoObject *obj = (MonoObject*)start;
-                       g_print ("found at %p (0x%lx): %s.%s\n", start, (long)vt->desc, obj->vtable->klass->name_space, obj->vtable->klass->name);
-               }
+       GCVTable *vt = (GCVTable*)LOAD_VTABLE (start);
+       DEBUG (8, fprintf (gc_debug_file, "Scanning object %p, vtable: %p (%s)\n", start, vt, vt->klass->name));
 
-#define SCAN_OBJECT_ACTION COUNT_OBJECT_TYPES
+#define SCAN_OBJECT_ACTION
 #include "sgen-scan-object.h"
-       }
 }
 
 /*
@@ -7021,25 +6411,17 @@ check_remsets_for_area (char *start, char *end)
  *
  * Assumes the world is stopped.
  */
-void
+static void
 check_consistency (void)
 {
-       GCMemSection *section;
-
        // Need to add more checks
-       // FIXME: Create a general heap enumeration function and use that
 
        missing_remsets = FALSE;
 
        DEBUG (1, fprintf (gc_debug_file, "Begin heap consistency check...\n"));
 
        // Check that oldspace->newspace pointers are registered with the collector
-       for (section = section_list; section; section = section->block.next) {
-               if (section->block.role == MEMORY_ROLE_GEN0)
-                       continue;
-               DEBUG (2, fprintf (gc_debug_file, "Scan of old section: %p-%p, size: %d\n", section->data, section->next_data, (int)(section->next_data - section->data)));
-               check_remsets_for_area (section->data, section->next_data);
-       }
+       major_iterate_objects (TRUE, TRUE, (IterateObjectCallbackFunc)check_consistency_callback, NULL);
 
        DEBUG (1, fprintf (gc_debug_file, "Heap consistency check done.\n"));
 
@@ -7108,23 +6490,20 @@ mono_gc_collection_count (int generation)
        return num_major_gcs;
 }
 
-gint64
+int64_t
 mono_gc_get_used_size (void)
 {
        gint64 tot = 0;
-       GCMemSection *section;
        LOCK_GC;
        tot = los_memory_usage;
-       for (section = section_list; section; section = section->block.next) {
-               /* this is approximate... */
-               tot += section->next_data - section->data;
-       }
+       tot += nursery_section->next_data - nursery_section->data;
+       tot += major_get_used_size ();
        /* FIXME: account for pinned objects */
        UNLOCK_GC;
        return tot;
 }
 
-gint64
+int64_t
 mono_gc_get_heap_size (void)
 {
        return total_alloc;
@@ -7207,7 +6586,7 @@ mono_gc_make_descr_from_bitmap (gsize *bitmap, int numbits)
 }
 
 void*
-mono_gc_make_root_descr_user (MonoGCMarkFunc marker)
+mono_gc_make_root_descr_user (MonoGCRootMarkFunc marker)
 {
        void *descr;
 
@@ -7239,6 +6618,16 @@ mono_gc_free_fixed (void* addr)
        free (addr);
 }
 
+void*
+mono_gc_invoke_with_gc_lock (MonoGCLockedCallbackFunc func, void *data)
+{
+       void *result;
+       LOCK_INTERRUPTION;
+       result = func (data);
+       UNLOCK_INTERRUPTION;
+       return result;
+}
+
 gboolean
 mono_gc_is_gc_thread (void)
 {
@@ -7249,6 +6638,53 @@ mono_gc_is_gc_thread (void)
        return result;
 }
 
+#ifdef USER_CONFIG
+
+/* Tries to extract a number from the passed string, taking in to account m, k
+ * and g suffixes */
+static gboolean
+parse_environment_string_extract_number (gchar *str, glong *out)
+{
+       char *endptr;
+       int len = strlen (str), shift = 0;
+       glong val;
+       gboolean is_suffix = FALSE;
+       char suffix;
+
+       switch (str [len - 1]) {
+               case 'g':
+               case 'G':
+                       shift += 10;
+               case 'm':
+               case 'M':
+                       shift += 10;
+               case 'k':
+               case 'K':
+                       shift += 10;
+                       is_suffix = TRUE;
+                       suffix = str [len - 1];
+                       break;
+       }
+
+       errno = 0;
+       val = strtol (str, &endptr, 10);
+
+       if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
+                       || (errno != 0 && val == 0) || (endptr == str))
+               return FALSE;
+
+       if (is_suffix) {
+               if (*(endptr + 1)) /* Invalid string. */
+                       return FALSE;
+               val <<= shift;
+       }
+
+       *out = val;
+       return TRUE;
+}
+
+#endif 
+
 void
 mono_gc_base_init (void)
 {
@@ -7264,6 +6700,44 @@ mono_gc_base_init (void)
        }
        pagesize = mono_pagesize ();
        gc_debug_file = stderr;
+
+#ifdef USER_CONFIG
+
+       if ((env = getenv ("MONO_GC_PARAMS"))) {
+               if (g_str_has_prefix (env, "nursery-size")) {
+                       int index = 0;
+                       long val;
+                       while (env [index] && env [index++] != '=')
+                               ;
+                       if (env [index] && parse_environment_string_extract_number (env
+                                       + index, &val)) {
+                               default_nursery_size = val;
+#ifdef ALIGN_NURSERY
+                               if ((val & (val - 1))) {
+                                       fprintf (stderr, "The nursery size must be a power of two.\n");
+                                       exit (1);
+                               }
+
+                               default_nursery_bits = 0;
+                               while (1 << (++ default_nursery_bits) != default_nursery_size)
+                                       ;
+#endif
+                       } else {
+                               fprintf (stderr, "nursery-size must be an integer.\n");
+                               exit (1);
+                       }
+               } else {
+                       fprintf (stderr, "MONO_GC_PARAMS must be of the form 'nursery-size=N' (where N is an integer, possibly with a k, m or a g suffix).\n");
+                       exit (1);
+               }
+       }
+
+#endif
+
+       nursery_size = DEFAULT_NURSERY_SIZE;
+
+       major_init ();
+
        if ((env = getenv ("MONO_GC_DEBUG"))) {
                opts = g_strsplit (env, ",", -1);
                for (ptr = opts; ptr && *ptr; ptr ++) {
@@ -7746,6 +7220,10 @@ mono_gc_get_write_barrier (void)
        MonoMethodSignature *sig;
 #ifdef MANAGED_WBARRIER
        int label_no_wb_1, label_no_wb_2, label_no_wb_3, label_no_wb_4, label_need_wb, label_slow_path;
+#ifndef ALIGN_NURSERY
+       int label_continue_1, label_continue_2, label_no_wb_5;
+       int dereferenced_var;
+#endif
        int buffer_var, buffer_index_var, dummy_var;
 
 #ifdef HAVE_KW_THREAD
@@ -7797,10 +7275,41 @@ mono_gc_get_write_barrier (void)
                mono_mb_emit_icon (mb, (mword)nursery_start >> DEFAULT_NURSERY_BITS);
                label_no_wb_2 = mono_mb_emit_branch (mb, CEE_BNE_UN);
 #else
-               // FIXME:
-               g_assert_not_reached ();
-#endif
 
+               // if (ptr < (nursery_start)) goto continue;
+               mono_mb_emit_ldarg (mb, 0);
+               mono_mb_emit_ptr (mb, (gpointer) nursery_start);
+               label_continue_1 = mono_mb_emit_branch (mb, CEE_BLT);
+
+               // if (ptr >= nursery_real_end)) goto continue;
+               mono_mb_emit_ldarg (mb, 0);
+               mono_mb_emit_ptr (mb, (gpointer) nursery_real_end);
+               label_continue_2 = mono_mb_emit_branch (mb, CEE_BGE);
+
+               // Otherwise return
+               label_no_wb_1 = mono_mb_emit_branch (mb, CEE_BR);
+
+               // continue:
+               mono_mb_patch_branch (mb, label_continue_1);
+               mono_mb_patch_branch (mb, label_continue_2);
+
+               // Dereference and store in local var
+               dereferenced_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
+               mono_mb_emit_ldarg (mb, 0);
+               mono_mb_emit_byte (mb, CEE_LDIND_I);
+               mono_mb_emit_stloc (mb, dereferenced_var);
+
+               // if (*ptr < nursery_start) return;
+               mono_mb_emit_ldloc (mb, dereferenced_var);
+               mono_mb_emit_ptr (mb, (gpointer) nursery_start);
+               label_no_wb_2 = mono_mb_emit_branch (mb, CEE_BLT);
+
+               // if (*ptr >= nursery_end) return;
+               mono_mb_emit_ldloc (mb, dereferenced_var);
+               mono_mb_emit_ptr (mb, (gpointer) nursery_real_end);
+               label_no_wb_5 = mono_mb_emit_branch (mb, CEE_BGE);
+
+#endif 
                // if (ptr >= stack_end) goto need_wb;
                mono_mb_emit_ldarg (mb, 0);
                EMIT_TLS_ACCESS (mb, stack_end, stack_end_offset);
@@ -7867,6 +7376,9 @@ mono_gc_get_write_barrier (void)
                mono_mb_patch_branch (mb, label_no_wb_2);
                mono_mb_patch_branch (mb, label_no_wb_3);
                mono_mb_patch_branch (mb, label_no_wb_4);
+#ifndef ALIGN_NURSERY
+               mono_mb_patch_branch (mb, label_no_wb_5);
+#endif
                mono_mb_emit_byte (mb, CEE_RET);
 
                // slow path
index 1f8037e3b9612cd3fa54bd3c39c3a78682005412..126bd4a1529cb118cf6551ebcd6a8cecce30957e 100644 (file)
@@ -1,3 +1,26 @@
+/*
+ * Copyright 2001-2003 Ximian, Inc
+ * Copyright 2003-2010 Novell, Inc.
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
 #ifndef __MONO_SGENGC_H__
 #define __MONO_SGENGC_H__
 
@@ -15,6 +38,8 @@
 #define LOCK_INIT(name)
 #define LOCK_GC pthread_mutex_lock (&gc_mutex)
 #define UNLOCK_GC pthread_mutex_unlock (&gc_mutex)
+#define LOCK_INTERRUPTION pthread_mutex_lock (&interruption_mutex)
+#define UNLOCK_INTERRUPTION pthread_mutex_unlock (&interruption_mutex)
 
 /* non-pthread will need to provide their own version of start/stop */
 #define USE_SIGNAL_BASED_START_STOP_WORLD 1
index 5db675164082b1797381fcea503191e407948017..035f77a7b360315debe21471104f770cb7fd7ccd 100644 (file)
@@ -1,3 +1,26 @@
+/*
+ * Copyright 2001-2003 Ximian, Inc
+ * Copyright 2003-2010 Novell, Inc.
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
 #define GRAY_QUEUE_SECTION_SIZE        (128 - 3)
 #define GRAY_QUEUE_LENGTH_LIMIT        64
 
@@ -61,27 +84,28 @@ gray_object_free_queue_section (GrayQueueSection *section)
        --num_gray_queue_sections;
 }
 
-/* 
- * The following three functions are called in the inner loops of the collector, so they
- * need to be as fast as possible.
+static inline gboolean
+gray_object_queue_is_empty (void)
+{
+       return gray_queue_end == NULL;
+}
+
+/*
+ * The following two functions are called in the inner loops of the
+ * collector, so they need to be as fast as possible.  We have macros
+ * for them below.
  */
 
 static inline void
 gray_object_enqueue (char *obj)
 {
-       g_assert (obj);
+       DEBUG (9, g_assert (obj));
        if (G_UNLIKELY (!gray_queue_end || gray_queue_end->end == GRAY_QUEUE_SECTION_SIZE))
                gray_object_alloc_queue_section ();
-       g_assert (gray_queue_end && gray_queue_end->end < GRAY_QUEUE_SECTION_SIZE);
+       DEBUG (9, g_assert (gray_queue_end && gray_queue_end->end < GRAY_QUEUE_SECTION_SIZE));
        gray_queue_end->objects [gray_queue_end->end++] = obj;
 
-       ++gray_queue_balance;
-}
-
-static inline gboolean
-gray_object_queue_is_empty (void)
-{
-       return gray_queue_end == NULL;
+       DEBUG (9, ++gray_queue_balance);
 }
 
 static inline char*
@@ -92,18 +116,38 @@ gray_object_dequeue (void)
        if (gray_object_queue_is_empty ())
                return NULL;
 
-       g_assert (gray_queue_end->end);
+       DEBUG (9, g_assert (gray_queue_end->end));
 
        obj = gray_queue_end->objects [--gray_queue_end->end];
 
        if (G_UNLIKELY (gray_queue_end->end == 0))
                gray_queue_end = gray_queue_end->prev;
 
-       --gray_queue_balance;
+       DEBUG (9, --gray_queue_balance);
 
        return obj;
 }
 
+#if MAX_DEBUG_LEVEL >= 9
+#define GRAY_OBJECT_ENQUEUE gray_object_enqueue
+#define GRAY_OBJECT_DEQUEUE(o) ((o) = gray_object_dequeue ())
+#else
+#define GRAY_OBJECT_ENQUEUE(o) do {                                    \
+               if (G_UNLIKELY (!gray_queue_end || gray_queue_end->end == GRAY_QUEUE_SECTION_SIZE)) \
+                       gray_object_alloc_queue_section ();             \
+               gray_queue_end->objects [gray_queue_end->end++] = (o);  \
+       } while (0)
+#define GRAY_OBJECT_DEQUEUE(o) do {                                    \
+               if (!gray_queue_end) {                                  \
+                       (o) = NULL;                                     \
+               } else {                                                \
+                       (o) = gray_queue_end->objects [--gray_queue_end->end]; \
+                       if (G_UNLIKELY (gray_queue_end->end == 0))      \
+                               gray_queue_end = gray_queue_end->prev;  \
+               }                                                       \
+       } while (0)
+#endif
+
 static void
 gray_object_queue_init (void)
 {
@@ -112,7 +156,7 @@ gray_object_queue_init (void)
 
        g_assert (gray_object_queue_is_empty ());
        g_assert (sizeof (GrayQueueSection) < MAX_FREELIST_SIZE);
-       g_assert (gray_queue_balance == 0);
+       DEBUG (9, g_assert (gray_queue_balance == 0));
 
        /* Free the extra sections allocated during the last collection */
        i = 0;
diff --git a/mono/metadata/sgen-major-copying.c b/mono/metadata/sgen-major-copying.c
new file mode 100644 (file)
index 0000000..fd817e1
--- /dev/null
@@ -0,0 +1,880 @@
+/*
+ * sgen-major-copying.c: Simple generational GC.
+ *
+ * Author:
+ *     Paolo Molaro (lupus@ximian.com)
+ *
+ * Copyright 2005-2010 Novell, Inc (http://www.novell.com)
+ *
+ * Thread start/stop adapted from Boehm's GC:
+ * Copyright (c) 1994 by Xerox Corporation.  All rights reserved.
+ * Copyright (c) 1996 by Silicon Graphics.  All rights reserved.
+ * Copyright (c) 1998 by Fergus Henderson.  All rights reserved.
+ * Copyright (c) 2000-2004 by Hewlett-Packard Company.  All rights reserved.
+ *
+ * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
+ * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
+ *
+ * Permission is hereby granted to use or copy this program
+ * for any purpose,  provided the above notices are retained on all copies.
+ * Permission to modify the code and to distribute modified code is granted,
+ * provided the above notices are retained, and a notice that the code was
+ * modified is included with the above copyright notice.
+ *
+ *
+ * Copyright 2001-2003 Ximian, Inc
+ * Copyright 2003-2010 Novell, Inc.
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#define MAJOR_SECTION_SIZE             PINNED_CHUNK_SIZE
+#define BLOCK_FOR_OBJECT(o)            ((Block*)(((mword)(o)) & ~(MAJOR_SECTION_SIZE - 1)))
+#define MAJOR_SECTION_FOR_OBJECT(o)    ((GCMemSection*)BLOCK_FOR_OBJECT ((o)))
+#define MIN_MINOR_COLLECTION_SECTION_ALLOWANCE (DEFAULT_NURSERY_SIZE * 3 / MAJOR_SECTION_SIZE)
+
+#define MAJOR_OBJ_IS_IN_TO_SPACE(o)    (MAJOR_SECTION_FOR_OBJECT ((o))->is_to_space)
+
+static int minor_collection_section_allowance;
+static int minor_collection_sections_alloced = 0;
+static int num_major_sections = 0;
+
+static GCMemSection *section_list = NULL;
+
+/* pinned_chunk_list is used for allocations of objects that are never moved */
+static PinnedChunk *pinned_chunk_list = NULL;
+
+/*
+ * used when moving the objects
+ */
+static char *to_space_bumper = NULL;
+static char *to_space_top = NULL;
+static GCMemSection *to_space_section = NULL;
+
+static gboolean
+obj_is_from_pinned_alloc (char *p)
+{
+       return BLOCK_FOR_OBJECT (p)->role == MEMORY_ROLE_PINNED;
+}
+
+static void
+free_pinned_object (char *obj, size_t size)
+{
+       PinnedChunk *chunk = (PinnedChunk*) BLOCK_FOR_OBJECT (obj);
+       void **p = (void**)obj;
+       int slot = slot_for_size (size);
+
+       g_assert (obj >= (char*)chunk->start_data && obj < ((char*)chunk + chunk->num_pages * FREELIST_PAGESIZE));
+       *p = chunk->free_list [slot];
+       chunk->free_list [slot] = p;
+}
+
+/*
+ * Allocate a new section of memory to be used as old generation.
+ */
+static GCMemSection*
+alloc_major_section (void)
+{
+       GCMemSection *section;
+       int scan_starts;
+
+       section = get_os_memory_aligned (MAJOR_SECTION_SIZE, MAJOR_SECTION_SIZE, TRUE);
+       section->next_data = section->data = (char*)section + SIZEOF_GC_MEM_SECTION;
+       g_assert (!((mword)section->data & 7));
+       section->size = MAJOR_SECTION_SIZE - SIZEOF_GC_MEM_SECTION;
+       section->end_data = section->data + section->size;
+       UPDATE_HEAP_BOUNDARIES (section->data, section->end_data);
+       total_alloc += section->size;
+       DEBUG (3, fprintf (gc_debug_file, "New major heap section: (%p-%p), total: %zd\n", section->data, section->end_data, total_alloc));
+       scan_starts = (section->size + SCAN_START_SIZE - 1) / SCAN_START_SIZE;
+       section->scan_starts = get_internal_mem (sizeof (char*) * scan_starts, INTERNAL_MEM_SCAN_STARTS);
+       section->num_scan_start = scan_starts;
+       section->block.role = MEMORY_ROLE_GEN1;
+       section->is_to_space = TRUE;
+
+       /* add to the section list */
+       section->block.next = section_list;
+       section_list = section;
+
+       ++num_major_sections;
+
+       return section;
+}
+
+static void
+free_major_section (GCMemSection *section)
+{
+       DEBUG (3, fprintf (gc_debug_file, "Freed major section %p (%p-%p)\n", section, section->data, section->end_data));
+       free_internal_mem (section->scan_starts, INTERNAL_MEM_SCAN_STARTS);
+       free_os_memory (section, MAJOR_SECTION_SIZE);
+       total_alloc -= MAJOR_SECTION_SIZE - SIZEOF_GC_MEM_SECTION;
+
+       --num_major_sections;
+}
+
+static void
+new_to_space_section (void)
+{
+       /* FIXME: if the current to_space_section is empty, we don't
+          have to allocate a new one */
+
+       to_space_section = alloc_major_section ();
+       to_space_bumper = to_space_section->next_data;
+       to_space_top = to_space_section->end_data;
+}
+
+static void
+to_space_set_next_data (void)
+{
+       g_assert (to_space_bumper >= to_space_section->next_data && to_space_bumper <= to_space_section->end_data);
+       to_space_section->next_data = to_space_bumper;
+}
+
+static void
+to_space_expand (void)
+{
+       if (to_space_section) {
+               g_assert (to_space_top == to_space_section->end_data);
+               to_space_set_next_data ();
+       }
+
+       new_to_space_section ();
+}
+
+#define MAJOR_GET_COPY_OBJECT_SPACE(dest, size) do {                   \
+               (dest) = to_space_bumper;                               \
+               /* Make sure we have enough space available */          \
+               if ((dest) + (size) > to_space_top) {                   \
+                       to_space_expand ();                             \
+                       (dest) = to_space_bumper;                       \
+                       DEBUG (8, g_assert ((dest) + (objsize) <= to_space_top)); \
+               }                                                       \
+               to_space_bumper += objsize;                             \
+               DEBUG (8, g_assert (to_space_bumper <= to_space_top));  \
+               to_space_section->scan_starts [((dest) - (char*)to_space_section->data)/SCAN_START_SIZE] = (dest); \
+       } while (0)
+
+static void
+unset_to_space (void)
+{
+       /* between collections the to_space_bumper is invalidated
+          because degraded allocations might occur, so we set it to
+          NULL, just to make it explicit */
+       to_space_bumper = NULL;
+
+       /* don't unset to_space_section if we implement the FIXME in
+          new_to_space_section */
+       to_space_section = NULL;
+}
+
+static gboolean
+major_is_object_live (char *obj)
+{
+       mword objsize;
+
+       /* nursery */
+       if (ptr_in_nursery (obj))
+               return FALSE;
+
+       objsize = safe_object_get_size ((MonoObject*)obj);
+       objsize += ALLOC_ALIGN - 1;
+       objsize &= ~(ALLOC_ALIGN - 1);
+
+       /* LOS */
+       if (objsize > MAX_SMALL_OBJ_SIZE)
+               return FALSE;
+
+       /* pinned chunk */
+       if (obj_is_from_pinned_alloc (obj))
+               return FALSE;
+
+       /* now we know it's in a major heap section */
+       return MAJOR_SECTION_FOR_OBJECT (obj)->is_to_space;
+}
+
+/* size is a multiple of ALLOC_ALIGN */
+static void*
+major_alloc_small_pinned_obj (size_t size)
+{
+       int slot;
+       void *res = NULL;
+       PinnedChunk *pchunk;
+       slot = slot_for_size (size);
+       /*g_print ("using slot %d for size %d (slot size: %d)\n", slot, size, freelist_sizes [slot]);*/
+       g_assert (size <= freelist_sizes [slot]);
+       for (pchunk = pinned_chunk_list; pchunk; pchunk = pchunk->block.next) {
+               void **p = pchunk->free_list [slot];
+               if (p) {
+                       /*g_print ("found freelist for slot %d in chunk %p, returning %p, next %p\n", slot, pchunk, p, *p);*/
+                       pchunk->free_list [slot] = *p;
+                       res = p;
+                       goto found;
+               }
+       }
+       for (pchunk = pinned_chunk_list; pchunk; pchunk = pchunk->block.next) {
+               res = get_chunk_freelist (pchunk, slot);
+               if (res)
+                       goto found;
+       }
+       pchunk = alloc_pinned_chunk ();
+       /* FIXME: handle OOM */
+       pchunk->block.next = pinned_chunk_list;
+       pinned_chunk_list = pchunk;
+       res = get_chunk_freelist (pchunk, slot);
+ found:
+       memset (res, 0, size);
+       return res;
+}
+
+/*
+ * size is already rounded up and we hold the GC lock.
+ */
+static void*
+alloc_degraded (MonoVTable *vtable, size_t size)
+{
+       GCMemSection *section;
+       void **p = NULL;
+       g_assert (size <= MAX_SMALL_OBJ_SIZE);
+       HEAVY_STAT (++stat_objects_alloced_degraded);
+       HEAVY_STAT (stat_bytes_alloced_degraded += size);
+       for (section = section_list; section; section = section->block.next) {
+               if ((section->end_data - section->next_data) >= size) {
+                       p = (void**)section->next_data;
+                       break;
+               }
+       }
+       if (!p) {
+               section = alloc_major_section ();
+               section->is_to_space = FALSE;
+               /* FIXME: handle OOM */
+               p = (void**)section->next_data;
+       }
+       section->next_data += size;
+       degraded_mode += size;
+       DEBUG (3, fprintf (gc_debug_file, "Allocated (degraded) object %p, vtable: %p (%s), size: %zd in section %p\n", p, vtable, vtable->klass->name, size, section));
+       *p = vtable;
+       return p;
+}
+
+static void
+major_copy_or_mark_object (void **obj_slot)
+{
+       char *forwarded;
+       char *obj = *obj_slot;
+       mword objsize;
+
+       DEBUG (9, g_assert (current_collection_generation == GENERATION_OLD));
+
+       HEAVY_STAT (++num_copy_object_called);
+
+       DEBUG (9, fprintf (gc_debug_file, "Precise copy of %p from %p", obj, obj_slot));
+
+       /*
+        * obj must belong to one of:
+        *
+        * 1. the nursery
+        * 2. the LOS
+        * 3. a pinned chunk
+        * 4. a non-to-space section of the major heap
+        * 5. a to-space section of the major heap
+        *
+        * In addition, objects in 1, 2 and 4 might also be pinned.
+        * Objects in 1 and 4 might be forwarded.
+        *
+        * Before we can copy the object we must make sure that we are
+        * allowed to, i.e. that the object not pinned, not already
+        * forwarded and doesn't belong to the LOS, a pinned chunk, or
+        * a to-space section.
+        *
+        * We are usually called for to-space objects (5) when we have
+        * two remset entries for the same reference.  The first entry
+        * copies the object and updates the reference and the second
+        * calls us with the updated reference that points into
+        * to-space.  There might also be other circumstances where we
+        * get to-space objects.
+        */
+
+       if ((forwarded = object_is_forwarded (obj))) {
+               DEBUG (9, g_assert (((MonoVTable*)LOAD_VTABLE(obj))->gc_descr));
+               DEBUG (9, fprintf (gc_debug_file, " (already forwarded to %p)\n", forwarded));
+               HEAVY_STAT (++stat_copy_object_failed_forwarded);
+               *obj_slot = forwarded;
+               return;
+       }
+       if (object_is_pinned (obj)) {
+               DEBUG (9, g_assert (((MonoVTable*)LOAD_VTABLE(obj))->gc_descr));
+               DEBUG (9, fprintf (gc_debug_file, " (pinned, no change)\n"));
+               HEAVY_STAT (++stat_copy_object_failed_pinned);
+               return;
+       }
+
+       if (ptr_in_nursery (obj))
+               goto copy;
+
+       /*
+        * At this point we know obj is not pinned, not forwarded and
+        * belongs to 2, 3, 4, or 5.
+        *
+        * LOS object (2) are simple, at least until we always follow
+        * the rule: if objsize > MAX_SMALL_OBJ_SIZE, pin the object
+        * and return it.  At the end of major collections, we walk
+        * the los list and if the object is pinned, it is marked,
+        * otherwise it can be freed.
+        *
+        * Pinned chunks (3) and major heap sections (4, 5) both
+        * reside in blocks, which are always aligned, so once we've
+        * eliminated LOS objects, we can just access the block and
+        * see whether it's a pinned chunk or a major heap section.
+        */
+
+       objsize = safe_object_get_size ((MonoObject*)obj);
+       objsize += ALLOC_ALIGN - 1;
+       objsize &= ~(ALLOC_ALIGN - 1);
+
+       if (G_UNLIKELY (objsize > MAX_SMALL_OBJ_SIZE || obj_is_from_pinned_alloc (obj))) {
+               if (object_is_pinned (obj))
+                       return;
+               DEBUG (9, fprintf (gc_debug_file, " (marked LOS/Pinned %p (%s), size: %zd)\n", obj, safe_name (obj), objsize));
+               binary_protocol_pin (obj, (gpointer)LOAD_VTABLE (obj), safe_object_get_size ((MonoObject*)obj));
+               pin_object (obj);
+               GRAY_OBJECT_ENQUEUE (obj);
+               HEAVY_STAT (++stat_copy_object_failed_large_pinned);
+               return;
+       }
+
+       /*
+        * Now we know the object is in a major heap section.  All we
+        * need to do is check whether it's already in to-space (5) or
+        * not (4).
+        */
+       if (MAJOR_OBJ_IS_IN_TO_SPACE (obj)) {
+               DEBUG (9, g_assert (objsize <= MAX_SMALL_OBJ_SIZE));
+               DEBUG (9, fprintf (gc_debug_file, " (already copied)\n"));
+               HEAVY_STAT (++stat_copy_object_failed_to_space);
+               return;
+       }
+
+ copy:
+       *obj_slot = copy_object_no_checks (obj);
+}
+
+/* FIXME: later reduce code duplication here with build_nursery_fragments().
+ * We don't keep track of section fragments for non-nursery sections yet, so
+ * just memset to 0.
+ */
+static void
+build_section_fragments (GCMemSection *section)
+{
+       int i;
+       char *frag_start, *frag_end;
+       size_t frag_size;
+
+       /* clear scan starts */
+       memset (section->scan_starts, 0, section->num_scan_start * sizeof (gpointer));
+       frag_start = section->data;
+       section->next_data = section->data;
+       for (i = section->pin_queue_start; i < section->pin_queue_end; ++i) {
+               frag_end = pin_queue [i];
+               /* remove the pin bit from pinned objects */
+               unpin_object (frag_end);
+               if (frag_end >= section->data + section->size) {
+                       frag_end = section->data + section->size;
+               } else {
+                       section->scan_starts [((char*)frag_end - (char*)section->data)/SCAN_START_SIZE] = frag_end;
+               }
+               frag_size = frag_end - frag_start;
+               if (frag_size) {
+                       binary_protocol_empty (frag_start, frag_size);
+                       memset (frag_start, 0, frag_size);
+               }
+               frag_size = safe_object_get_size ((MonoObject*)pin_queue [i]);
+               frag_size += ALLOC_ALIGN - 1;
+               frag_size &= ~(ALLOC_ALIGN - 1);
+               frag_start = (char*)pin_queue [i] + frag_size;
+               section->next_data = MAX (section->next_data, frag_start);
+       }
+       frag_end = section->end_data;
+       frag_size = frag_end - frag_start;
+       if (frag_size) {
+               binary_protocol_empty (frag_start, frag_size);
+               memset (frag_start, 0, frag_size);
+       }
+}
+
+static void
+scan_pinned_objects (IterateObjectCallbackFunc callback, void *callback_data)
+{
+       PinnedChunk *chunk;
+       int i, obj_size;
+       char *p, *endp;
+       void **ptr;
+       void *end_chunk;
+       for (chunk = pinned_chunk_list; chunk; chunk = chunk->block.next) {
+               end_chunk = (char*)chunk + chunk->num_pages * FREELIST_PAGESIZE;
+               DEBUG (6, fprintf (gc_debug_file, "Scanning pinned chunk %p (range: %p-%p)\n", chunk, chunk->start_data, end_chunk));
+               for (i = 0; i < chunk->num_pages; ++i) {
+                       obj_size = chunk->page_sizes [i];
+                       if (!obj_size)
+                               continue;
+                       p = i? (char*)chunk + i * FREELIST_PAGESIZE: chunk->start_data;
+                       endp = i? p + FREELIST_PAGESIZE: (char*)chunk + FREELIST_PAGESIZE;
+                       DEBUG (6, fprintf (gc_debug_file, "Page %d (size: %d, range: %p-%p)\n", i, obj_size, p, endp));
+                       while (p + obj_size <= endp) {
+                               ptr = (void**)p;
+                               DEBUG (9, fprintf (gc_debug_file, "Considering %p (vtable: %p)\n", ptr, *ptr));
+                               /* if the first word (the vtable) is outside the chunk we have an object */
+                               if (*ptr && (*ptr < (void*)chunk || *ptr >= end_chunk))
+                                       callback ((char*)ptr, obj_size, callback_data);
+                               p += obj_size;
+                       }
+               }
+       }
+}
+
+/*
+ * the array of pointers from @start to @end contains conservative
+ * pointers to objects inside @chunk: mark each referenced object
+ * with the PIN bit.
+ */
+static void
+mark_pinned_from_addresses (PinnedChunk *chunk, void **start, void **end)
+{
+       for (; start < end; start++) {
+               char *addr = *start;
+               int offset = (char*)addr - (char*)chunk;
+               int page = offset / FREELIST_PAGESIZE;
+               int obj_offset = page == 0? offset - ((char*)chunk->start_data - (char*)chunk): offset % FREELIST_PAGESIZE;
+               int slot_size = chunk->page_sizes [page];
+               void **ptr;
+               /* the page is not allocated */
+               if (!slot_size)
+                       continue;
+               /* would be faster if we restrict the sizes to power of two,
+                * but that's a waste of memory: need to measure. it could reduce
+                * fragmentation since there are less pages needed, if for example
+                * someone interns strings of each size we end up with one page per
+                * interned string (still this is just ~40 KB): with more fine-grained sizes
+                * this increases the number of used pages.
+                */
+               if (page == 0) {
+                       obj_offset /= slot_size;
+                       obj_offset *= slot_size;
+                       addr = (char*)chunk->start_data + obj_offset;
+               } else {
+                       obj_offset /= slot_size;
+                       obj_offset *= slot_size;
+                       addr = (char*)chunk + page * FREELIST_PAGESIZE + obj_offset;
+               }
+               ptr = (void**)addr;
+               /* if the vtable is inside the chunk it's on the freelist, so skip */
+               if (*ptr && (*ptr < (void*)chunk->start_data || *ptr > (void*)((char*)chunk + chunk->num_pages * FREELIST_PAGESIZE))) {
+                       binary_protocol_pin (addr, (gpointer)LOAD_VTABLE (addr), safe_object_get_size ((MonoObject*)addr));
+                       if (heap_dump_file && !object_is_pinned (addr))
+                               pin_stats_register_object ((char*) addr, safe_object_get_size ((MonoObject*) addr));
+                       pin_object (addr);
+                       GRAY_OBJECT_ENQUEUE (addr);
+                       DEBUG (6, fprintf (gc_debug_file, "Marked pinned object %p (%s) from roots\n", addr, safe_name (addr)));
+               }
+       }
+}
+
+static void
+sweep_pinned_objects_callback (char *ptr, size_t size, void *data)
+{
+       if (object_is_pinned (ptr)) {
+               unpin_object (ptr);
+               DEBUG (6, fprintf (gc_debug_file, "Unmarked pinned object %p (%s)\n", ptr, safe_name (ptr)));
+       } else {
+               DEBUG (6, fprintf (gc_debug_file, "Freeing unmarked pinned object %p (%s)\n", ptr, safe_name (ptr)));
+               free_pinned_object (ptr, size);
+       }
+}
+
+static void
+sweep_pinned_objects (void)
+{
+       scan_pinned_objects (sweep_pinned_objects_callback, NULL);
+}
+
+static void
+major_iterate_objects (gboolean non_pinned, gboolean pinned, IterateObjectCallbackFunc callback, void *data)
+{
+       if (non_pinned) {
+               GCMemSection *section;
+               for (section = section_list; section; section = section->block.next)
+                       scan_area_with_callback (section->data, section->end_data, callback, data);
+       }
+       if (pinned)
+               scan_pinned_objects (callback, data);
+}
+
+static void
+major_free_non_pinned_object (char *obj, size_t size)
+{
+       memset (obj, 0, size);
+}
+
+static void
+major_do_collection (const char *reason)
+{
+       GCMemSection *section, *prev_section;
+       LOSObject *bigobj, *prevbo;
+       PinnedChunk *chunk;
+       TV_DECLARE (all_atv);
+       TV_DECLARE (all_btv);
+       TV_DECLARE (atv);
+       TV_DECLARE (btv);
+       /* FIXME: only use these values for the precise scan
+        * note that to_space pointers should be excluded anyway...
+        */
+       char *heap_start = NULL;
+       char *heap_end = (char*)-1;
+       int old_num_major_sections = num_major_sections;
+       int num_major_sections_saved, save_target, allowance_target;
+
+       init_stats ();
+       binary_protocol_collection (GENERATION_OLD);
+       check_scan_starts ();
+       gray_object_queue_init ();
+
+       degraded_mode = 0;
+       DEBUG (1, fprintf (gc_debug_file, "Start major collection %d\n", num_major_gcs));
+       num_major_gcs++;
+       mono_stats.major_gc_count ++;
+
+       /* world must be stopped already */
+       TV_GETTIME (all_atv);
+       TV_GETTIME (atv);
+
+       /* Pinning depends on this */
+       clear_nursery_fragments (nursery_next);
+
+       TV_GETTIME (btv);
+       time_major_pre_collection_fragment_clear += TV_ELAPSED_MS (atv, btv);
+
+       if (xdomain_checks)
+               check_for_xdomain_refs ();
+
+       nursery_section->next_data = nursery_real_end;
+       /* we should also coalesce scanning from sections close to each other
+        * and deal with pointers outside of the sections later.
+        */
+       /* The remsets are not useful for a major collection */
+       clear_remsets ();
+
+       TV_GETTIME (atv);
+       init_pinning ();
+       DEBUG (6, fprintf (gc_debug_file, "Collecting pinned addresses\n"));
+       pin_from_roots ((void*)lowest_heap_address, (void*)highest_heap_address);
+       optimize_pin_queue (0);
+
+       /*
+        * pin_queue now contains all candidate pointers, sorted and
+        * uniqued.  We must do two passes now to figure out which
+        * objects are pinned.
+        *
+        * The first is to find within the pin_queue the area for each
+        * section.  This requires that the pin_queue be sorted.  We
+        * also process the LOS objects and pinned chunks here.
+        *
+        * The second, destructive, pass is to reduce the section
+        * areas to pointers to the actually pinned objects.
+        */
+       DEBUG (6, fprintf (gc_debug_file, "Pinning from sections\n"));
+       /* first pass for the sections */
+       find_section_pin_queue_start_end (nursery_section);
+       for (section = section_list; section; section = section->block.next)
+               find_section_pin_queue_start_end (section);
+       /* identify possible pointers to the insize of large objects */
+       DEBUG (6, fprintf (gc_debug_file, "Pinning from large objects\n"));
+       for (bigobj = los_object_list; bigobj; bigobj = bigobj->next) {
+               int start, end;
+               find_optimized_pin_queue_area (bigobj->data, (char*)bigobj->data + bigobj->size, &start, &end);
+               if (start != end) {
+                       pin_object (bigobj->data);
+                       GRAY_OBJECT_ENQUEUE (bigobj->data);
+                       if (heap_dump_file)
+                               pin_stats_register_object ((char*) bigobj->data, safe_object_get_size ((MonoObject*) bigobj->data));
+                       DEBUG (6, fprintf (gc_debug_file, "Marked large object %p (%s) size: %zd from roots\n", bigobj->data, safe_name (bigobj->data), bigobj->size));
+               }
+       }
+       /* look for pinned addresses for pinned-alloc objects */
+       DEBUG (6, fprintf (gc_debug_file, "Pinning from pinned-alloc objects\n"));
+       for (chunk = pinned_chunk_list; chunk; chunk = chunk->block.next) {
+               int start, end;
+               find_optimized_pin_queue_area (chunk->start_data, (char*)chunk + chunk->num_pages * FREELIST_PAGESIZE, &start, &end);
+               if (start != end)
+                       mark_pinned_from_addresses (chunk, pin_queue + start, pin_queue + end);
+       }
+       /* second pass for the sections */
+       pin_objects_in_section (nursery_section);
+       for (section = section_list; section; section = section->block.next)
+               pin_objects_in_section (section);
+
+       TV_GETTIME (btv);
+       time_major_pinning += TV_ELAPSED_MS (atv, btv);
+       DEBUG (2, fprintf (gc_debug_file, "Finding pinned pointers: %d in %d usecs\n", next_pin_slot, TV_ELAPSED (atv, btv)));
+       DEBUG (4, fprintf (gc_debug_file, "Start scan with %d pinned objects\n", next_pin_slot));
+
+       new_to_space_section ();
+
+       drain_gray_stack ();
+
+       TV_GETTIME (atv);
+       time_major_scan_pinned += TV_ELAPSED_MS (btv, atv);
+
+       /* registered roots, this includes static fields */
+       scan_from_registered_roots (major_copy_or_mark_object, heap_start, heap_end, ROOT_TYPE_NORMAL);
+       scan_from_registered_roots (major_copy_or_mark_object, heap_start, heap_end, ROOT_TYPE_WBARRIER);
+       TV_GETTIME (btv);
+       time_major_scan_registered_roots += TV_ELAPSED_MS (atv, btv);
+
+       /* Threads */
+       /* FIXME: this is the wrong place for this, because it does
+          pinning */
+       scan_thread_data (heap_start, heap_end, TRUE);
+       TV_GETTIME (atv);
+       time_major_scan_thread_data += TV_ELAPSED_MS (btv, atv);
+
+       TV_GETTIME (btv);
+       time_major_scan_alloc_pinned += TV_ELAPSED_MS (atv, btv);
+
+       /* scan the list of objects ready for finalization */
+       scan_finalizer_entries (major_copy_or_mark_object, fin_ready_list);
+       scan_finalizer_entries (major_copy_or_mark_object, critical_fin_list);
+       TV_GETTIME (atv);
+       time_major_scan_finalized += TV_ELAPSED_MS (btv, atv);
+       DEBUG (2, fprintf (gc_debug_file, "Root scan: %d usecs\n", TV_ELAPSED (btv, atv)));
+
+       TV_GETTIME (btv);
+       time_major_scan_big_objects += TV_ELAPSED_MS (atv, btv);
+
+       /* all the objects in the heap */
+       finish_gray_stack (heap_start, heap_end, GENERATION_OLD);
+       TV_GETTIME (atv);
+       time_major_finish_gray_stack += TV_ELAPSED_MS (btv, atv);
+
+       to_space_set_next_data ();
+       unset_to_space ();
+
+       /* sweep the big objects list */
+       prevbo = NULL;
+       for (bigobj = los_object_list; bigobj;) {
+               if (object_is_pinned (bigobj->data)) {
+                       unpin_object (bigobj->data);
+               } else {
+                       LOSObject *to_free;
+                       /* not referenced anywhere, so we can free it */
+                       if (prevbo)
+                               prevbo->next = bigobj->next;
+                       else
+                               los_object_list = bigobj->next;
+                       to_free = bigobj;
+                       bigobj = bigobj->next;
+                       free_large_object (to_free);
+                       continue;
+               }
+               prevbo = bigobj;
+               bigobj = bigobj->next;
+       }
+       /* unpin objects from the pinned chunks and free the unmarked ones */
+       sweep_pinned_objects ();
+
+       TV_GETTIME (btv);
+       time_major_sweep += TV_ELAPSED_MS (atv, btv);
+
+       /* free the unused sections */
+       prev_section = NULL;
+       for (section = section_list; section;) {
+               /* to_space doesn't need handling here */
+               if (section->is_to_space) {
+                       section->is_to_space = FALSE;
+                       prev_section = section;
+                       section = section->block.next;
+                       continue;
+               }
+               /* no pinning object, so the section is free */
+               if (section->pin_queue_start == section->pin_queue_end) {
+                       GCMemSection *to_free;
+                       if (prev_section)
+                               prev_section->block.next = section->block.next;
+                       else
+                               section_list = section->block.next;
+                       to_free = section;
+                       section = section->block.next;
+                       free_major_section (to_free);
+                       continue;
+               } else {
+                       DEBUG (6, fprintf (gc_debug_file, "Section %p has still pinned objects (%d)\n", section, section->pin_queue_end - section->pin_queue_start));
+                       build_section_fragments (section);
+               }
+               prev_section = section;
+               section = section->block.next;
+       }
+
+       /* walk the pin_queue, build up the fragment list of free memory, unmark
+        * pinned objects as we go, memzero() the empty fragments so they are ready for the
+        * next allocations.
+        */
+       build_nursery_fragments (nursery_section->pin_queue_start, nursery_section->pin_queue_end);
+
+       TV_GETTIME (atv);
+       time_major_fragment_creation += TV_ELAPSED_MS (btv, atv);
+
+       TV_GETTIME (all_btv);
+       mono_stats.major_gc_time_usecs += TV_ELAPSED (all_atv, all_btv);
+
+       if (heap_dump_file)
+               dump_heap ("major", num_major_gcs - 1, reason);
+
+       /* prepare the pin queue for the next collection */
+       next_pin_slot = 0;
+       if (fin_ready_list || critical_fin_list) {
+               DEBUG (4, fprintf (gc_debug_file, "Finalizer-thread wakeup: ready %d\n", num_ready_finalizers));
+               mono_gc_finalize_notify ();
+       }
+       pin_stats_reset ();
+
+       g_assert (gray_object_queue_is_empty ());
+
+       commit_stats (GENERATION_OLD);
+
+       num_major_sections_saved = MAX (old_num_major_sections - num_major_sections, 1);
+
+       save_target = num_major_sections / 2;
+       /*
+        * We aim to allow the allocation of as many sections as is
+        * necessary to reclaim save_target sections in the next
+        * collection.  We assume the collection pattern won't change.
+        * In the last cycle, we had num_major_sections_saved for
+        * minor_collection_sections_alloced.  Assuming things won't
+        * change, this must be the same ratio as save_target for
+        * allowance_target, i.e.
+        *
+        *    num_major_sections_saved            save_target
+        * --------------------------------- == ----------------
+        * minor_collection_sections_alloced    allowance_target
+        *
+        * hence:
+        */
+       allowance_target = save_target * minor_collection_sections_alloced / num_major_sections_saved;
+
+       minor_collection_section_allowance = MAX (MIN (allowance_target, num_major_sections), MIN_MINOR_COLLECTION_SECTION_ALLOWANCE);
+
+       minor_collection_sections_alloced = 0;
+
+       check_scan_starts ();
+}
+
+static void
+major_check_scan_starts (void)
+{
+       GCMemSection *section;
+       for (section = section_list; section; section = section->block.next)
+               check_section_scan_starts (section);
+}
+
+static void
+major_dump_non_pinned_sections (void)
+{
+       GCMemSection *section;
+       for (section = section_list; section; section = section->block.next)
+               dump_section (section, "old");
+}
+
+static gint64
+major_get_used_size (void)
+{
+       gint64 tot = 0;
+       GCMemSection *section;
+       for (section = section_list; section; section = section->block.next) {
+               /* this is approximate... */
+               tot += section->next_data - section->data;
+       }
+       return tot;
+}
+
+static void
+major_init (void)
+{
+       minor_collection_section_allowance = MIN_MINOR_COLLECTION_SECTION_ALLOWANCE;
+}
+
+/* only valid during minor collections */
+static int old_num_major_sections;
+
+static void
+major_start_nursery_collection (void)
+{
+       old_num_major_sections = num_major_sections;
+
+       if (!to_space_section) {
+               new_to_space_section ();
+       } else {
+               /* we might have done degraded allocation since the
+                  last collection */
+               g_assert (to_space_bumper <= to_space_section->next_data);
+               to_space_bumper = to_space_section->next_data;
+
+               to_space_section->is_to_space = TRUE;
+       }
+}
+
+static void
+major_finish_nursery_collection (void)
+{
+       GCMemSection *section;
+       int sections_alloced;
+
+       to_space_set_next_data ();
+
+       for (section = section_list; section; section = section->block.next)
+               section->is_to_space = FALSE;
+
+       sections_alloced = num_major_sections - old_num_major_sections;
+       minor_collection_sections_alloced += sections_alloced;
+}
+
+static gboolean
+major_need_major_collection (void)
+{
+       return minor_collection_sections_alloced > minor_collection_section_allowance;
+}
+
+static gboolean
+major_ptr_is_in_non_pinned_space (char *ptr)
+{
+       GCMemSection *section;
+       for (section = section_list; section;) {
+               if (ptr >= section->data && ptr < section->data + section->size)
+                       return TRUE;
+               section = section->block.next;
+       }
+       return FALSE;
+}
+
+static void
+major_report_pinned_memory_usage (void)
+{
+       PinnedChunk *chunk;
+       int i = 0;
+       for (chunk = pinned_chunk_list; chunk; chunk = chunk->block.next)
+               report_pinned_chunk (chunk, i++);
+}
diff --git a/mono/metadata/sgen-marksweep.c b/mono/metadata/sgen-marksweep.c
new file mode 100644 (file)
index 0000000..ec6b0b9
--- /dev/null
@@ -0,0 +1,967 @@
+#include <math.h>
+
+#define MS_BLOCK_SIZE  (16*1024)
+
+/*
+ * Don't allocate single blocks, but alloc a contingent of this many
+ * blocks in one swoop.
+ */
+#define MS_BLOCK_ALLOC_NUM     32
+
+/*
+ * Number of bytes before the first object in a block.  At the start
+ * of a block is the MSBlockHeader, then opional padding, then come
+ * the objects, so this must be >= sizeof (MSBlockHeader).
+ */
+#define MS_BLOCK_SKIP  16
+
+#define MS_BLOCK_FREE  (MS_BLOCK_SIZE - MS_BLOCK_SKIP)
+
+#define MS_NUM_MARK_WORDS(c)   (((c) + sizeof (mword) * 8 - 1) / (sizeof (mword) * 8))
+
+#if MAX_SMALL_OBJ_SIZE > MS_BLOCK_FREE / 2
+#error MAX_SMALL_OBJ_SIZE must be at most (MS_BLOCK_SIZE - MS_BLOCK_SKIP) / 2
+#endif
+
+typedef struct _MSBlockInfo MSBlockInfo;
+struct _MSBlockInfo {
+       int obj_size;
+       gboolean pinned;
+       char *block;
+       void **free_list;
+       MSBlockInfo *next_free;
+       MSBlockInfo *next;
+       int pin_queue_start;
+       int pin_queue_end;
+       mword mark_words [1];
+};
+
+#define MS_BLOCK_OBJ(b,i)      ((b)->block + MS_BLOCK_SKIP + (b)->obj_size * (i))
+
+typedef struct {
+       MSBlockInfo *info;
+} MSBlockHeader;
+
+#define MS_BLOCK_FOR_OBJ(o)    (((MSBlockHeader*)((mword)(o) & ~(MS_BLOCK_SIZE-1)))->info)
+
+#define MS_BLOCK_OBJ_INDEX(o,b)        (((char*)(o) - ((b)->block + MS_BLOCK_SKIP)) / (b)->obj_size)
+
+#define MS_CALC_MARK_BIT(w,b,i)        do {            \
+               if (sizeof (mword) == 4) {      \
+                       (w) = (i) >> 5;         \
+                       (b) = (i) & 31;         \
+               } else {                        \
+                       (w) = (i) >> 6;         \
+                       (b) = (i) & 63;         \
+               }                               \
+       } while (0)
+
+#define MS_MARK_BIT(bl,w,b)    ((bl)->mark_words [(w)] & (1L << (b)))
+#define MS_SET_MARK_BIT(bl,w,b)        ((bl)->mark_words [(w)] |= (1L << (b)))
+
+#define MS_OBJ_ALLOCED(o,b)    (*(void**)(o) && (*(char**)(o) < (b)->block || *(char**)(o) >= (b)->block + MS_BLOCK_SIZE))
+
+#define MS_BLOCK_OBJ_SIZE_FACTOR       (sqrt (2.0))
+
+#define MIN_MINOR_COLLECTION_SECTION_ALLOWANCE (DEFAULT_NURSERY_SIZE * 3 / MS_BLOCK_SIZE)
+
+static int minor_collection_section_allowance;
+static int minor_collection_sections_alloced = 0;
+
+/*
+ * This way we can lookup block object size indexes for sizes up to
+ * 256 bytes with a single load.
+ */
+#define MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES     32
+
+static int *block_obj_sizes;
+static int num_block_obj_sizes;
+static int fast_block_obj_size_indexes [MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES];
+
+/* all blocks in the system */
+static MSBlockInfo *all_blocks;
+static int num_major_sections = 0;
+/* one free block list for each block object size */
+static MSBlockInfo **free_non_pinned_blocks;
+static MSBlockInfo **free_pinned_blocks;
+
+static long stat_major_blocks_alloced = 0;
+static long stat_major_blocks_freed = 0;
+
+static int
+ms_find_block_obj_size_index (int size)
+{
+       int i;
+       DEBUG (9, g_assert (size <= MAX_SMALL_OBJ_SIZE));
+       for (i = 0; i < num_block_obj_sizes; ++i)
+               if (block_obj_sizes [i] >= size)
+                       return i;
+       g_assert_not_reached ();
+}
+
+#define FREE_BLOCKS(pinned) ((pinned) ? free_pinned_blocks : free_non_pinned_blocks)
+
+#define MS_BLOCK_OBJ_SIZE_INDEX(s)                             \
+       (((s)+7)>>3 < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES ?      \
+        fast_block_obj_size_indexes [((s)+7)>>3] :             \
+        ms_find_block_obj_size_index ((s)))
+
+void *empty_blocks = NULL;
+int num_empty_blocks = 0;
+
+static void*
+ms_get_empty_block (void)
+{
+       char *p;
+       int i;
+       void *block;
+
+       if (!empty_blocks) {
+               g_assert (num_empty_blocks == 0);
+
+               p = get_os_memory_aligned (MS_BLOCK_SIZE * MS_BLOCK_ALLOC_NUM, MS_BLOCK_SIZE, TRUE);
+
+               for (i = 0; i < MS_BLOCK_ALLOC_NUM; ++i) {
+                       block = p;
+                       *(void**)block = empty_blocks;
+                       empty_blocks = block;
+                       p += MS_BLOCK_SIZE;
+               }
+
+               num_empty_blocks += MS_BLOCK_ALLOC_NUM;
+       }
+
+       g_assert (empty_blocks);
+
+       block = empty_blocks;
+       empty_blocks = *(void**)empty_blocks;
+
+       --num_empty_blocks;
+
+       *(void**)block = NULL;
+
+       g_assert (!((mword)block & (MS_BLOCK_SIZE - 1)));
+
+       return block;
+}
+
+static void
+ms_free_block (void *block)
+{
+       memset (block, 0, MS_BLOCK_SIZE);
+
+       *(void**)block = empty_blocks;
+       empty_blocks = block;
+
+       ++num_empty_blocks;
+}
+
+static void
+check_block_free_list (MSBlockInfo *block, int size, gboolean pinned)
+{
+       MSBlockInfo *b;
+
+       for (; block; block = block->next_free) {
+               g_assert (block->obj_size == size);
+               g_assert ((pinned && block->pinned) || (!pinned && !block->pinned));
+
+               /* blocks in the free lists must have at least
+                  one free slot */
+               g_assert (block->free_list);
+
+               /* the block must be in the all_blocks list */
+               for (b = all_blocks; b; b = b->next) {
+                       if (b == block)
+                               break;
+               }
+               g_assert (b == block);
+       }
+}
+
+static void
+consistency_check (void)
+{
+       MSBlockInfo *block;
+       int i;
+
+       /* check all blocks */
+       for (block = all_blocks; block; block = block->next) {
+               int count = MS_BLOCK_FREE / block->obj_size;
+               int num_mark_words = MS_NUM_MARK_WORDS (count);
+               int num_free = 0;
+               void **free;
+
+               /* check block header */
+               g_assert (((MSBlockHeader*)block->block)->info == block);
+
+               /* count number of free slots */
+               for (i = 0; i < count; ++i) {
+                       void **obj = (void**) MS_BLOCK_OBJ (block, i);
+                       if (!MS_OBJ_ALLOCED (obj, block))
+                               ++num_free;
+               }
+
+               /* check free list */
+               for (free = block->free_list; free; free = (void**)*free) {
+                       g_assert (MS_BLOCK_FOR_OBJ (free) == block);
+                       --num_free;
+               }
+               g_assert (num_free == 0);
+
+               /* check all mark words are zero */
+               for (i = 0; i < num_mark_words; ++i)
+                       g_assert (block->mark_words [i] == 0);
+       }
+
+       /* check free blocks */
+       for (i = 0; i < num_block_obj_sizes; ++i) {
+               check_block_free_list (free_non_pinned_blocks [i], block_obj_sizes [i], FALSE);
+               check_block_free_list (free_pinned_blocks [i], block_obj_sizes [i], TRUE);
+       }
+}
+
+static void
+ms_alloc_block (int size_index, gboolean pinned)
+{
+       int size = block_obj_sizes [size_index];
+       int count = MS_BLOCK_FREE / size;
+       int num_mark_words = MS_NUM_MARK_WORDS (count);
+       int block_info_size = sizeof (MSBlockInfo) + sizeof (mword) * (num_mark_words - 1);
+       MSBlockInfo *info = get_internal_mem (block_info_size, INTERNAL_MEM_MS_BLOCK_INFO);
+       MSBlockHeader *header;
+       MSBlockInfo **free_blocks = FREE_BLOCKS (pinned);
+       char *obj_start;
+       int i;
+
+       DEBUG (9, g_assert (count >= 2));
+
+       info->obj_size = size;
+       info->pinned = pinned;
+       info->block = ms_get_empty_block ();
+
+       header = (MSBlockHeader*) info->block;
+       header->info = info;
+
+       /* build free list */
+       obj_start = info->block + MS_BLOCK_SKIP;
+       info->free_list = (void**)obj_start;
+       /* we're skipping the last one - it's already NULL */
+       for (i = 0; i < count - 1; ++i) {
+               char *next_obj_start = obj_start + size;
+               *(void**)obj_start = next_obj_start;
+               obj_start = next_obj_start;
+       }
+
+       info->next_free = free_blocks [size_index];
+       free_blocks [size_index] = info;
+
+       info->next = all_blocks;
+       all_blocks = info;
+
+       ++num_major_sections;
+
+       ++stat_major_blocks_alloced;
+}
+
+static gboolean
+obj_is_from_pinned_alloc (char *obj)
+{
+       MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
+       return block->pinned;
+}
+
+static void*
+alloc_obj (int size, gboolean pinned)
+{
+       int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
+       MSBlockInfo **free_blocks = FREE_BLOCKS (pinned);
+       MSBlockInfo *block;
+       void *obj;
+
+       if (!free_blocks [size_index])
+               ms_alloc_block (size_index, pinned);
+
+       block = free_blocks [size_index];
+       DEBUG (9, g_assert (block));
+
+       obj = block->free_list;
+       DEBUG (9, g_assert (obj));
+
+       block->free_list = *(void**)obj;
+       if (!block->free_list) {
+               free_blocks [size_index] = block->next_free;
+               block->next_free = NULL;
+       }
+
+       /*
+        * FIXME: This should not be necessary because it'll be
+        * overwritten by the vtable immediately.
+        */
+       *(void**)obj = NULL;
+
+       return obj;
+}
+
+static void*
+ms_alloc_obj (int size)
+{
+       return alloc_obj (size, FALSE);
+}
+
+/* FIXME: inline fast path */
+#define MAJOR_GET_COPY_OBJECT_SPACE(dest, size) do {   \
+               (dest) = ms_alloc_obj ((size));         \
+       } while (0)
+
+/*
+ * We're not freeing the block if it's empty.  We leave that work for
+ * the next major collection.
+ */
+static void
+free_object (char *obj, size_t size, gboolean pinned)
+{
+       MSBlockInfo *block = MS_BLOCK_FOR_OBJ (obj);
+       int word, bit;
+       DEBUG (9, g_assert ((pinned && block->pinned) || (!pinned && !block->pinned)));
+       DEBUG (9, g_assert (MS_OBJ_ALLOCED (obj, block)));
+       MS_CALC_MARK_BIT (word, bit, MS_BLOCK_OBJ_INDEX (obj, block));
+       DEBUG (9, g_assert (!MS_MARK_BIT (block, word, bit)));
+       if (!block->free_list) {
+               MSBlockInfo **free_blocks = FREE_BLOCKS (pinned);
+               int size_index = MS_BLOCK_OBJ_SIZE_INDEX (size);
+               DEBUG (9, g_assert (!block->next_free));
+               block->next_free = free_blocks [size_index];
+               free_blocks [size_index] = block;
+       }
+       memset (obj, 0, size);
+       *(void**)obj = block->free_list;
+       block->free_list = (void**)obj;
+}
+
+static void
+major_free_non_pinned_object (char *obj, size_t size)
+{
+       free_object (obj, size, FALSE);
+}
+
+/* size is a multiple of ALLOC_ALIGN */
+static void*
+major_alloc_small_pinned_obj (size_t size)
+{
+       return alloc_obj (size, TRUE);
+}
+
+static void
+free_pinned_object (char *obj, size_t size)
+{
+       free_object (obj, size, TRUE);
+}
+
+/*
+ * size is already rounded up and we hold the GC lock.
+ */
+static void*
+alloc_degraded (MonoVTable *vtable, size_t size)
+{
+       void *obj = alloc_obj (size, FALSE);
+       *(MonoVTable**)obj = vtable;
+       return obj;
+}
+
+#define MAJOR_OBJ_IS_IN_TO_SPACE(obj)  FALSE
+
+/*
+ * obj is some object.  If it's not in the major heap (i.e. if it's in
+ * the nursery or LOS), return FALSE.  Otherwise return whether it's
+ * been marked or copied.
+ */
+static gboolean
+major_is_object_live (char *obj)
+{
+       MSBlockInfo *block;
+       int word, bit;
+       mword objsize;
+
+       if (ptr_in_nursery (obj))
+               return FALSE;
+
+       objsize = safe_object_get_size ((MonoObject*)obj);
+       objsize += ALLOC_ALIGN - 1;
+       objsize &= ~(ALLOC_ALIGN - 1);
+
+       /* LOS */
+       if (objsize > MAX_SMALL_OBJ_SIZE)
+               return FALSE;
+
+       /* now we know it's in a major block */
+       block = MS_BLOCK_FOR_OBJ (obj);
+       DEBUG (9, g_assert (!block->pinned));
+       MS_CALC_MARK_BIT (word, bit, MS_BLOCK_OBJ_INDEX (obj, block));
+       return MS_MARK_BIT (block, word, bit) ? TRUE : FALSE;
+}
+
+static gboolean
+major_ptr_is_in_non_pinned_space (char *ptr)
+{
+       g_assert_not_reached ();
+}
+
+static void
+major_iterate_objects (gboolean non_pinned, gboolean pinned, IterateObjectCallbackFunc callback, void *data)
+{
+       MSBlockInfo *block;
+
+       for (block = all_blocks; block; block = block->next) {
+               int count = MS_BLOCK_FREE / block->obj_size;
+               int i;
+
+               if (block->pinned && !pinned)
+                       continue;
+               if (!block->pinned && !non_pinned)
+                       continue;
+
+               for (i = 0; i < count; ++i) {
+                       void **obj = (void**) MS_BLOCK_OBJ (block, i);
+                       if (MS_OBJ_ALLOCED (obj, block))
+                               callback ((char*)obj, block->obj_size, data);
+               }
+       }
+}
+
+#define major_check_scan_starts()
+
+static void
+major_dump_non_pinned_sections (void)
+{
+       g_assert_not_reached ();
+}
+
+#define MS_MARK_INDEX_IN_BLOCK_AND_ENQUEUE_CHECKED(obj,block,index) do { \
+               int __word, __bit;                                      \
+               MS_CALC_MARK_BIT (__word, __bit, (index));              \
+               DEBUG (9, g_assert ((obj) == MS_BLOCK_OBJ ((block), (index)))); \
+               if (!MS_MARK_BIT ((block), __word, __bit) && MS_OBJ_ALLOCED ((obj), (block))) { \
+                       MS_SET_MARK_BIT ((block), __word, __bit);       \
+                       GRAY_OBJECT_ENQUEUE ((obj));                    \
+                       binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), safe_object_get_size ((MonoObject*)(obj))); \
+               }                                                       \
+       } while (0)
+#define MS_MARK_INDEX_IN_BLOCK_AND_ENQUEUE(obj,block,index) do {       \
+               int __word, __bit;                                      \
+               MS_CALC_MARK_BIT (__word, __bit, (index));              \
+               DEBUG (9, g_assert ((obj) == MS_BLOCK_OBJ ((block), (index)))); \
+               g_assert (MS_OBJ_ALLOCED ((obj), (block)));             \
+               if (!MS_MARK_BIT ((block), __word, __bit)) {            \
+                       MS_SET_MARK_BIT ((block), __word, __bit);       \
+                       GRAY_OBJECT_ENQUEUE ((obj));                    \
+                       binary_protocol_mark ((obj), (gpointer)LOAD_VTABLE ((obj)), safe_object_get_size ((MonoObject*)(obj))); \
+               }                                                       \
+       } while (0)
+
+static void
+major_copy_or_mark_object (void **ptr)
+{
+       void *obj = *ptr;
+       mword objsize;
+       MSBlockInfo *block;
+       int index;
+       int count;
+
+       DEBUG (9, g_assert (obj));
+       DEBUG (9, g_assert (current_collection_generation == GENERATION_OLD));
+
+       if (ptr_in_nursery (obj)) {
+               int word, bit;
+               char *forwarded;
+
+               if ((forwarded = object_is_forwarded (obj))) {
+                       *ptr = forwarded;
+                       return;
+               }
+               if (object_is_pinned (obj))
+                       return;
+
+               obj = copy_object_no_checks (obj);
+               *ptr = obj;
+
+               /*
+                * FIXME: See comment for copy_object_no_checks().  If
+                * we have that, we can let the allocation function
+                * give us the block info, too, and we won't have to
+                * re-fetch it.
+                */
+               block = MS_BLOCK_FOR_OBJ (obj);
+               index = MS_BLOCK_OBJ_INDEX (obj, block);
+               DEBUG (9, g_assert (obj == MS_BLOCK_OBJ (block, index)));
+               MS_CALC_MARK_BIT (word, bit, (index));
+               DEBUG (9, g_assert (!MS_MARK_BIT (block, word, bit)));
+               MS_SET_MARK_BIT (block, word, bit);
+               return;
+       }
+
+       objsize = safe_object_get_size ((MonoObject*)obj);
+       objsize += ALLOC_ALIGN - 1;
+       objsize &= ~(ALLOC_ALIGN - 1);
+
+       if (objsize > MAX_SMALL_OBJ_SIZE) {
+               if (object_is_pinned (obj))
+                       return;
+               binary_protocol_pin (obj, (gpointer)LOAD_VTABLE (obj), safe_object_get_size ((MonoObject*)obj));
+               pin_object (obj);
+               GRAY_OBJECT_ENQUEUE (obj);
+               return;
+       }
+
+       block = MS_BLOCK_FOR_OBJ (obj);
+       index = MS_BLOCK_OBJ_INDEX (obj, block);
+       count = MS_BLOCK_FREE / block->obj_size;
+       DEBUG (9, g_assert (index >= 0 && index < count));
+       MS_MARK_INDEX_IN_BLOCK_AND_ENQUEUE (obj, block, index);
+}
+
+static void
+mark_pinned_objects_in_block (MSBlockInfo *block)
+{
+       int i;
+       int last_index = -1;
+       int count = MS_BLOCK_FREE / block->obj_size;
+
+       for (i = block->pin_queue_start; i < block->pin_queue_end; ++i) {
+               int index = MS_BLOCK_OBJ_INDEX (pin_queue [i], block);
+               DEBUG (9, g_assert (index >= 0 && index < count));
+               if (index == last_index)
+                       continue;
+               MS_MARK_INDEX_IN_BLOCK_AND_ENQUEUE_CHECKED (MS_BLOCK_OBJ (block, index), block, index);
+               last_index = index;
+       }
+}
+
+static void
+major_sweep (void)
+{
+       MSBlockInfo *empty_blocks = NULL;
+       MSBlockInfo **iter;
+       int i;
+
+       /* traverse all blocks, free and zero unmarked objects */
+       iter = &all_blocks;
+       while (*iter) {
+               MSBlockInfo *block = *iter;
+               int count = MS_BLOCK_FREE / block->obj_size;
+               gboolean have_live = FALSE;
+               int word_index = 0;
+               int obj_index = 0;
+
+               block->free_list = NULL;
+
+               do {
+                       mword word = block->mark_words [word_index];
+
+                       if (word == (mword)-1L) {
+                               obj_index += 8 * sizeof (mword);
+                               have_live = TRUE;
+                       } else {
+                               int num_bits = MIN (count - obj_index, 8 * sizeof (mword));
+                               for (i = 0; i < num_bits; ++i) {
+                                       void *obj = MS_BLOCK_OBJ (block, obj_index);
+                                       if (word & 1) {
+                                               DEBUG (9, g_assert (MS_OBJ_ALLOCED (obj, block)));
+                                               have_live = TRUE;
+                                       } else {
+                                               /* an unmarked object */
+                                               void *obj = MS_BLOCK_OBJ (block, obj_index);
+                                               if (MS_OBJ_ALLOCED (obj, block)) {
+                                                       binary_protocol_empty (obj, block->obj_size);
+                                                       memset (obj, 0, block->obj_size);
+                                               }
+                                               *(void**)obj = block->free_list;
+                                               block->free_list = obj;
+                                       }
+                                       word >>= 1;
+                                       ++obj_index;
+                               }
+                       }
+
+                       /* reset mark bits */
+                       block->mark_words [word_index] = 0;
+
+                       ++word_index;
+               } while (obj_index < count);
+
+               /*
+                * FIXME: reverse free list so that it's in address
+                * order
+                */
+
+               if (have_live) {
+                       iter = &block->next;
+                       continue;
+               }
+
+               /*
+                * blocks without live objects are removed from the
+                * block list and marked with obj_size = -1
+                */
+               *iter = block->next;
+               block->next = empty_blocks;
+               empty_blocks = block;
+
+               block->obj_size = -1;
+       }
+
+       /* if there are no blocks to be freed, we're done */
+       if (!empty_blocks)
+               return;
+
+       /* go through all free lists and remove the blocks to be freed */
+       for (i = 0; i < num_block_obj_sizes; ++i) {
+               int pinned;
+               for (pinned = 0; pinned <= 1; ++pinned) {
+                       MSBlockInfo **free_blocks = FREE_BLOCKS (pinned);
+                       iter = &(free_blocks [i]);
+                       while (*iter) {
+                               MSBlockInfo *block = *iter;
+                               if (block->obj_size < 0)
+                                       *iter = block->next_free;
+                               else
+                                       iter = &block->next_free;
+                       }
+               }
+       }
+
+       /* now free the blocks */
+       while (empty_blocks) {
+               MSBlockInfo *next = empty_blocks->next;
+
+               ms_free_block (empty_blocks->block);
+               free_internal_mem (empty_blocks, INTERNAL_MEM_MS_BLOCK_INFO);
+
+               empty_blocks = next;
+
+               --num_major_sections;
+
+               ++stat_major_blocks_freed;
+       }
+}
+
+static void
+major_do_collection (const char *reason)
+{
+       LOSObject *bigobj, *prevbo;
+       MSBlockInfo *block;
+       TV_DECLARE (all_atv);
+       TV_DECLARE (all_btv);
+       TV_DECLARE (atv);
+       TV_DECLARE (btv);
+       /* FIXME: only use these values for the precise scan
+        * note that to_space pointers should be excluded anyway...
+        */
+       char *heap_start = NULL;
+       char *heap_end = (char*)-1;
+       int old_num_major_sections = num_major_sections;
+       int num_major_sections_saved, save_target, allowance_target;
+
+       //consistency_check ();
+
+       init_stats ();
+       binary_protocol_collection (GENERATION_OLD);
+       check_scan_starts ();
+       gray_object_queue_init ();
+
+       degraded_mode = 0;
+       DEBUG (1, fprintf (gc_debug_file, "Start major collection %d\n", num_major_gcs));
+       num_major_gcs++;
+       mono_stats.major_gc_count ++;
+
+       /* world must be stopped already */
+       TV_GETTIME (all_atv);
+       TV_GETTIME (atv);
+
+       /* Pinning depends on this */
+       clear_nursery_fragments (nursery_next);
+
+       TV_GETTIME (btv);
+       time_major_pre_collection_fragment_clear += TV_ELAPSED_MS (atv, btv);
+
+       if (xdomain_checks)
+               check_for_xdomain_refs ();
+
+       nursery_section->next_data = nursery_real_end;
+       /* we should also coalesce scanning from sections close to each other
+        * and deal with pointers outside of the sections later.
+        */
+       /* The remsets are not useful for a major collection */
+       clear_remsets ();
+
+       TV_GETTIME (atv);
+       init_pinning ();
+       DEBUG (6, fprintf (gc_debug_file, "Collecting pinned addresses\n"));
+       pin_from_roots ((void*)lowest_heap_address, (void*)highest_heap_address);
+       optimize_pin_queue (0);
+
+       /*
+        * pin_queue now contains all candidate pointers, sorted and
+        * uniqued.  We must do two passes now to figure out which
+        * objects are pinned.
+        *
+        * The first is to find within the pin_queue the area for each
+        * section.  This requires that the pin_queue be sorted.  We
+        * also process the LOS objects and pinned chunks here.
+        *
+        * The second, destructive, pass is to reduce the section
+        * areas to pointers to the actually pinned objects.
+        */
+       DEBUG (6, fprintf (gc_debug_file, "Pinning from sections\n"));
+       /* first pass for the sections */
+       find_section_pin_queue_start_end (nursery_section);
+       for (block = all_blocks; block; block = block->next) {
+               find_optimized_pin_queue_area (block->block + MS_BLOCK_SKIP, block->block + MS_BLOCK_SIZE,
+                               &block->pin_queue_start, &block->pin_queue_end);
+       }
+       /* identify possible pointers to the insize of large objects */
+       DEBUG (6, fprintf (gc_debug_file, "Pinning from large objects\n"));
+       for (bigobj = los_object_list; bigobj; bigobj = bigobj->next) {
+               int start, end;
+               find_optimized_pin_queue_area (bigobj->data, (char*)bigobj->data + bigobj->size, &start, &end);
+               if (start != end) {
+                       pin_object (bigobj->data);
+                       GRAY_OBJECT_ENQUEUE (bigobj->data);
+                       if (heap_dump_file)
+                               pin_stats_register_object ((char*) bigobj->data, safe_object_get_size ((MonoObject*) bigobj->data));
+                       DEBUG (6, fprintf (gc_debug_file, "Marked large object %p (%s) size: %zd from roots\n", bigobj->data, safe_name (bigobj->data), bigobj->size));
+               }
+       }
+       /* second pass for the sections */
+       pin_objects_in_section (nursery_section);
+       for (block = all_blocks; block; block = block->next)
+               mark_pinned_objects_in_block (block);
+
+       TV_GETTIME (btv);
+       time_major_pinning += TV_ELAPSED_MS (atv, btv);
+       DEBUG (2, fprintf (gc_debug_file, "Finding pinned pointers: %d in %d usecs\n", next_pin_slot, TV_ELAPSED (atv, btv)));
+       DEBUG (4, fprintf (gc_debug_file, "Start scan with %d pinned objects\n", next_pin_slot));
+
+       drain_gray_stack ();
+
+       TV_GETTIME (atv);
+       time_major_scan_pinned += TV_ELAPSED_MS (btv, atv);
+
+       /* registered roots, this includes static fields */
+       scan_from_registered_roots (major_copy_or_mark_object, heap_start, heap_end, ROOT_TYPE_NORMAL);
+       scan_from_registered_roots (major_copy_or_mark_object, heap_start, heap_end, ROOT_TYPE_WBARRIER);
+       TV_GETTIME (btv);
+       time_major_scan_registered_roots += TV_ELAPSED_MS (atv, btv);
+
+       /* Threads */
+       /* FIXME: This is the wrong place for this, because it does
+          pinning */
+       scan_thread_data (heap_start, heap_end, TRUE);
+       TV_GETTIME (atv);
+       time_major_scan_thread_data += TV_ELAPSED_MS (btv, atv);
+
+       TV_GETTIME (btv);
+       time_major_scan_alloc_pinned += TV_ELAPSED_MS (atv, btv);
+
+       /* scan the list of objects ready for finalization */
+       scan_finalizer_entries (major_copy_or_mark_object, fin_ready_list);
+       scan_finalizer_entries (major_copy_or_mark_object, critical_fin_list);
+       TV_GETTIME (atv);
+       time_major_scan_finalized += TV_ELAPSED_MS (btv, atv);
+       DEBUG (2, fprintf (gc_debug_file, "Root scan: %d usecs\n", TV_ELAPSED (btv, atv)));
+
+       TV_GETTIME (btv);
+       time_major_scan_big_objects += TV_ELAPSED_MS (atv, btv);
+
+       /* all the objects in the heap */
+       finish_gray_stack (heap_start, heap_end, GENERATION_OLD);
+       TV_GETTIME (atv);
+       time_major_finish_gray_stack += TV_ELAPSED_MS (btv, atv);
+
+       /* sweep the big objects list */
+       prevbo = NULL;
+       for (bigobj = los_object_list; bigobj;) {
+               if (object_is_pinned (bigobj->data)) {
+                       unpin_object (bigobj->data);
+               } else {
+                       LOSObject *to_free;
+                       /* not referenced anywhere, so we can free it */
+                       if (prevbo)
+                               prevbo->next = bigobj->next;
+                       else
+                               los_object_list = bigobj->next;
+                       to_free = bigobj;
+                       bigobj = bigobj->next;
+                       free_large_object (to_free);
+                       continue;
+               }
+               prevbo = bigobj;
+               bigobj = bigobj->next;
+       }
+
+       major_sweep ();
+
+       TV_GETTIME (btv);
+       time_major_sweep += TV_ELAPSED_MS (atv, btv);
+
+       /* walk the pin_queue, build up the fragment list of free memory, unmark
+        * pinned objects as we go, memzero() the empty fragments so they are ready for the
+        * next allocations.
+        */
+       build_nursery_fragments (nursery_section->pin_queue_start, nursery_section->pin_queue_end);
+
+       TV_GETTIME (atv);
+       time_major_fragment_creation += TV_ELAPSED_MS (btv, atv);
+
+       TV_GETTIME (all_btv);
+       mono_stats.major_gc_time_usecs += TV_ELAPSED (all_atv, all_btv);
+
+       if (heap_dump_file)
+               dump_heap ("major", num_major_gcs - 1, reason);
+
+       /* prepare the pin queue for the next collection */
+       next_pin_slot = 0;
+       if (fin_ready_list || critical_fin_list) {
+               DEBUG (4, fprintf (gc_debug_file, "Finalizer-thread wakeup: ready %d\n", num_ready_finalizers));
+               mono_gc_finalize_notify ();
+       }
+       pin_stats_reset ();
+
+       g_assert (gray_object_queue_is_empty ());
+
+       commit_stats (GENERATION_OLD);
+
+       num_major_sections_saved = MAX (old_num_major_sections - num_major_sections, 1);
+
+       save_target = num_major_sections / 2;
+       /*
+        * We aim to allow the allocation of as many sections as is
+        * necessary to reclaim save_target sections in the next
+        * collection.  We assume the collection pattern won't change.
+        * In the last cycle, we had num_major_sections_saved for
+        * minor_collection_sections_alloced.  Assuming things won't
+        * change, this must be the same ratio as save_target for
+        * allowance_target, i.e.
+        *
+        *    num_major_sections_saved            save_target
+        * --------------------------------- == ----------------
+        * minor_collection_sections_alloced    allowance_target
+        *
+        * hence:
+        */
+       allowance_target = save_target * minor_collection_sections_alloced / num_major_sections_saved;
+
+       minor_collection_section_allowance = MAX (MIN (allowance_target, num_major_sections), MIN_MINOR_COLLECTION_SECTION_ALLOWANCE);
+
+       minor_collection_sections_alloced = 0;
+
+       check_scan_starts ();
+
+       //consistency_check ();
+}
+
+static int
+ms_calculate_block_obj_sizes (double factor, int *arr)
+{
+       double target_size = sizeof (MonoObject);
+       int num_sizes = 0;
+       int last_size = 0;
+
+       do {
+               int target_count = ceil (MS_BLOCK_FREE / target_size);
+               int size = MIN ((MS_BLOCK_FREE / target_count) & ~(ALLOC_ALIGN - 1), MAX_SMALL_OBJ_SIZE);
+
+               if (size != last_size) {
+                       if (arr)
+                               arr [num_sizes] = size;
+                       ++num_sizes;
+                       last_size = size;
+               }
+
+               target_size *= factor;
+       } while (last_size < MAX_SMALL_OBJ_SIZE);
+
+       return num_sizes;
+}
+
+static void
+major_init (void)
+{
+       int i;
+
+       num_block_obj_sizes = ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, NULL);
+       block_obj_sizes = get_internal_mem (sizeof (int) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES);
+       ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, block_obj_sizes);
+
+       /*
+       {
+               int i;
+               g_print ("block object sizes:\n");
+               for (i = 0; i < num_block_obj_sizes; ++i)
+                       g_print ("%d\n", block_obj_sizes [i]);
+       }
+       */
+
+       free_pinned_blocks = get_internal_mem (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES);
+       free_non_pinned_blocks = get_internal_mem (sizeof (MSBlockInfo*) * num_block_obj_sizes, INTERNAL_MEM_MS_TABLES);
+
+       for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES; ++i)
+               fast_block_obj_size_indexes [i] = ms_find_block_obj_size_index (i * 8);
+       for (i = 0; i < MS_NUM_FAST_BLOCK_OBJ_SIZE_INDEXES * 8; ++i)
+               g_assert (MS_BLOCK_OBJ_SIZE_INDEX (i) == ms_find_block_obj_size_index (i));
+
+       mono_counters_register ("# major blocks allocated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_major_blocks_alloced);
+       mono_counters_register ("# major blocks freed", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_major_blocks_freed);
+
+       minor_collection_section_allowance = MIN_MINOR_COLLECTION_SECTION_ALLOWANCE;
+}
+
+/* only valid during minor collections */
+static int old_num_major_sections;
+
+static void
+major_start_nursery_collection (void)
+{
+       //consistency_check ();
+
+       old_num_major_sections = num_major_sections;
+}
+
+static void
+major_finish_nursery_collection (void)
+{
+       int sections_alloced;
+
+       //consistency_check ();
+
+       sections_alloced = num_major_sections - old_num_major_sections;
+       minor_collection_sections_alloced += sections_alloced;
+}
+
+static gboolean
+major_need_major_collection (void)
+{
+       return minor_collection_sections_alloced > minor_collection_section_allowance;
+}
+
+static void
+major_report_pinned_memory_usage (void)
+{
+       g_assert_not_reached ();
+}
+
+static gint64
+major_get_used_size (void)
+{
+       gint64 size = 0;
+       MSBlockInfo *block;
+
+       for (block = all_blocks; block; block = block->next) {
+               int count = MS_BLOCK_FREE / block->obj_size;
+               void **iter;
+               size += count * block->obj_size;
+               for (iter = block->free_list; iter; iter = (void**)*iter)
+                       size -= block->obj_size;
+       }
+
+       return size;
+}
index 4f1998513da86288ea78ee386f4c6e61233038e2..68871c75f6ad6b916dda988d7c87d8aabca67d48 100644 (file)
@@ -1,3 +1,26 @@
+/*
+ * Copyright 2001-2003 Ximian, Inc
+ * Copyright 2003-2010 Novell, Inc.
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
 enum {
        PIN_TYPE_STACK,
        PIN_TYPE_STATIC_DATA,
@@ -13,9 +36,17 @@ struct _PinStatAddress {
        PinStatAddress *right;
 };
 
+typedef struct _ObjectList ObjectList;
+struct _ObjectList {
+       MonoObject *obj;
+       ObjectList *next;
+};
+
 static PinStatAddress *pin_stat_addresses = NULL;
 static size_t pinned_byte_counts [PIN_TYPE_MAX];
 
+static ObjectList *pinned_objects = NULL;
+
 static void
 pin_stats_tree_free (PinStatAddress *node)
 {
@@ -34,6 +65,11 @@ pin_stats_reset (void)
        pin_stat_addresses = NULL;
        for (i = 0; i < PIN_TYPE_MAX; ++i)
                pinned_byte_counts [i] = 0;
+       while (pinned_objects) {
+               ObjectList *next = pinned_objects->next;
+               free_internal_mem (pinned_objects, INTERNAL_MEM_STATISTICS);
+               pinned_objects = next;
+       }
 }
 
 static void
@@ -88,5 +124,9 @@ static void
 pin_stats_register_object (char *obj, size_t size)
 {
        int pin_types = 0;
+       ObjectList *list = get_internal_mem (sizeof (ObjectList), INTERNAL_MEM_STATISTICS);
        pin_stats_count_object_from_tree (obj, size, pin_stat_addresses, &pin_types);
+       list->obj = (MonoObject*)obj;
+       list->next = pinned_objects;
+       pinned_objects = list;
 }
index 77a822f49b575f150d697bde28cd1ddacceab995..a4a45e758915b71455c2515186edaad8bea09f1f 100644 (file)
@@ -1,14 +1,53 @@
+/*
+ * Copyright 2001-2003 Ximian, Inc
+ * Copyright 2003-2010 Novell, Inc.
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
 #define PIN_STAGING_AREA_SIZE  1024
 
 static void* pin_staging_area [PIN_STAGING_AREA_SIZE];
 static int pin_staging_area_index;
 
+static void** pin_queue;
+static int pin_queue_size = 0;
+static int next_pin_slot = 0;
+
 static void
 init_pinning (void)
 {
        pin_staging_area_index = 0;
 }
 
+static void
+realloc_pin_queue (void)
+{
+       int new_size = pin_queue_size? pin_queue_size + pin_queue_size/2: 1024;
+       void **new_pin = get_internal_mem (sizeof (void*) * new_size, INTERNAL_MEM_PIN_QUEUE);
+       memcpy (new_pin, pin_queue, sizeof (void*) * next_pin_slot);
+       free_internal_mem (pin_queue, INTERNAL_MEM_PIN_QUEUE);
+       pin_queue = new_pin;
+       pin_queue_size = new_size;
+       DEBUG (4, fprintf (gc_debug_file, "Reallocated pin queue to size: %d\n", new_size));
+}
+
 static void
 evacuate_pin_staging_area (void)
 {
@@ -51,3 +90,37 @@ pin_stage_ptr (void *ptr)
 
        pin_staging_area [pin_staging_area_index++] = ptr;
 }
+
+static int
+optimized_pin_queue_search (void *addr)
+{
+       int first = 0, last = next_pin_slot;
+       while (first < last) {
+               int middle = first + ((last - first) >> 1);
+               if (addr <= pin_queue [middle])
+                       last = middle;
+               else
+                       first = middle + 1;
+       }
+       g_assert (first == last);
+       return first;
+}
+
+static void
+find_optimized_pin_queue_area (void *start, void *end, int *first, int *last)
+{
+       *first = optimized_pin_queue_search (start);
+       *last = optimized_pin_queue_search (end);
+}
+
+static void
+find_section_pin_queue_start_end (GCMemSection *section)
+{
+       int start, end;
+       DEBUG (6, fprintf (gc_debug_file, "Pinning from section %p (%p-%p)\n", section, section->data, section->end_data));
+       find_optimized_pin_queue_area (section->data, section->end_data, &start, &end);
+       DEBUG (6, fprintf (gc_debug_file, "Found %d pinning addresses in section %p (%d-%d)\n",
+                                       end - start, section, start, end));
+       section->pin_queue_start = start;
+       section->pin_queue_end = end;
+}
index c6966412907f2618d0d97ba365af024dae0897a0..66f9ce7e7f5c4b049e28331c03411ebf70fb464c 100644 (file)
@@ -1,3 +1,26 @@
+/*
+ * Copyright 2001-2003 Ximian, Inc
+ * Copyright 2003-2010 Novell, Inc.
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
 #ifdef BINARY_PROTOCOL
 
 #include "sgen-protocol.h"
@@ -68,6 +91,13 @@ binary_protocol_pin (gpointer obj, gpointer vtable, int size)
        protocol_entry (SGEN_PROTOCOL_PIN, &entry, sizeof (SGenProtocolPin));
 }
 
+static void
+binary_protocol_mark (gpointer obj, gpointer vtable, int size)
+{
+       SGenProtocolMark entry = { obj, vtable, size };
+       protocol_entry (SGEN_PROTOCOL_MARK, &entry, sizeof (SGenProtocolMark));
+}
+
 static void
 binary_protocol_wbarrier (gpointer ptr, gpointer value, gpointer value_vtable)
 {
@@ -141,6 +171,7 @@ binary_protocol_missing_remset (gpointer obj, gpointer obj_vtable, int offset, g
 #define binary_protocol_alloc(obj, vtable, size)
 #define binary_protocol_copy(from, to, vtable, size)
 #define binary_protocol_pin(obj, vtable, size)
+#define binary_protocol_mark(obj, vtable, size)
 #define binary_protocol_wbarrier(ptr, value, value_vtable)
 #define binary_protocol_global_remset(ptr, value, value_vtable)
 #define binary_protocol_ptr_update(ptr, old_value, new_value, vtable, size)
index 1574a2f5f90685b3fe00af1958cd30cd081ae40f..c8287c9dafd6e73c2d5df61f6fa0f843a494adff 100644 (file)
@@ -1,8 +1,32 @@
+/*
+ * Copyright 2001-2003 Ximian, Inc
+ * Copyright 2003-2010 Novell, Inc.
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
 enum {
        SGEN_PROTOCOL_COLLECTION,
        SGEN_PROTOCOL_ALLOC,
        SGEN_PROTOCOL_COPY,
        SGEN_PROTOCOL_PIN,
+       SGEN_PROTOCOL_MARK,
        SGEN_PROTOCOL_WBARRIER,
        SGEN_PROTOCOL_GLOBAL_REMSET,
        SGEN_PROTOCOL_PTR_UPDATE,
@@ -37,6 +61,12 @@ typedef struct {
        int size;
 } SGenProtocolPin;
 
+typedef struct {
+       gpointer obj;
+       gpointer vtable;
+       int size;
+} SGenProtocolMark;
+
 typedef struct {
        gpointer ptr;
        gpointer value;
index 6c4b62ab30cf73c16dcf1c49221bf9c78780b6de..0ceaa727ef28eba20065246d239e69075749f93b 100644 (file)
@@ -1,4 +1,27 @@
 /*
+ * Copyright 2001-2003 Ximian, Inc
+ * Copyright 2003-2010 Novell, Inc.
+ * 
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ * 
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ * 
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *
  * Scans one object, using the OBJ_XXX macros.  The start of the
  * object must be given in the variable "char* start".  Afterwards,
  * "start" will point to the start of the next object.
index cec33b9dd243c1b7e32401be54dd808145cda77b..53dd0d8b13cb13f2c2bf9707771ac059a13b0102 100644 (file)
@@ -141,11 +141,15 @@ static gint32 convert_family(MonoAddressFamily mono_family)
                break;
                
        case AddressFamily_Sna:
+#ifdef AF_SNA
                family=AF_SNA;
+#endif
                break;
                
        case AddressFamily_DecNet:
+#ifdef AF_DECnet
                family=AF_DECnet;
+#endif
                break;
                
        case AddressFamily_AppleTalk:
@@ -192,13 +196,17 @@ static MonoAddressFamily convert_to_mono_family(guint16 af_family)
                break;
 #endif
                
+#ifdef AF_SNA
        case AF_SNA:
                family=AddressFamily_Sna;
                break;
+#endif
                
+#ifdef AF_DECnet
        case AF_DECnet:
                family=AddressFamily_DecNet;
                break;
+#endif
                
        case AF_APPLETALK:
                family=AddressFamily_AppleTalk;
@@ -240,7 +248,9 @@ static gint32 convert_type(MonoSocketType mono_type)
                break;
 
        case SocketType_Rdm:
+#ifdef SOCK_RDM
                type=SOCK_RDM;
+#endif
                break;
 
        case SocketType_Seqpacket:
@@ -1633,7 +1643,7 @@ void ves_icall_System_Net_Sockets_Socket_Select_internal(MonoArray **sockets, gi
        MonoClass *sock_arr_class;
        MonoArray *socks;
        time_t start;
-       mono_array_size_t socks_size;
+       uintptr_t socks_size;
        
        MONO_ARCH_SAVE_REGS;
 
@@ -1712,7 +1722,7 @@ void ves_icall_System_Net_Sockets_Socket_Select_internal(MonoArray **sockets, gi
        }
 
        sock_arr_class= ((MonoObject *)*sockets)->vtable->klass;
-       socks_size = ((mono_array_size_t)ret) + 3; /* space for the NULL delimiters */
+       socks_size = ((uintptr_t)ret) + 3; /* space for the NULL delimiters */
        socks = mono_array_new_full (mono_domain_get (), sock_arr_class, &socks_size, NULL);
 
        mode = idx = 0;
@@ -1934,7 +1944,6 @@ static struct in_addr ipaddress_to_struct_in_addr(MonoObject *ipaddr)
        
        return(inaddr);
 }
-#endif
 
 #ifdef AF_INET6
 static struct in6_addr ipaddress_to_struct_in6_addr(MonoObject *ipaddr)
@@ -1961,6 +1970,7 @@ static struct in6_addr ipaddress_to_struct_in6_addr(MonoObject *ipaddr)
        return(in6addr);
 }
 #endif /* AF_INET6 */
+#endif
 
 void ves_icall_System_Net_Sockets_Socket_SetSocketOption_internal(SOCKET sock, gint32 level, gint32 name, MonoObject *obj_val, MonoArray *byte_val, gint32 int_val, gint32 *error)
 {
@@ -2851,9 +2861,13 @@ MonoBoolean ves_icall_System_Net_Dns_GetHostByName_internal(MonoString *host, Mo
        }
 #endif
 
+#ifndef HOST_WIN32
        he = NULL;
        if (*hostname)
                he = _wapi_gethostbyname (hostname);
+#else
+       he = _wapi_gethostbyname (hostname);
+#endif
        g_free(hostname);
 
        if (*hostname && he==NULL)
index 639f295032233df96407d2f048a2227186a3e392..fde7641dffb0b181fe94765bb5b874c2e24488d4 100644 (file)
@@ -6,20 +6,17 @@
  *   Gonzalo Paniagua Javier (gonzalo@ximian.com)
  *
  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
- * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
+ * Copyright 2004-2010 Novell, Inc (http://www.novell.com)
  */
 
 #include <config.h>
 #include <glib.h>
 
 #ifdef MONO_SMALL_CONFIG
-#define THREADS_PER_CPU        2 /* 8 + THREADS_PER_CPU * number of CPUs = max threads */
-#define INITIAL_QUEUE_LENGTH 16
+#define QUEUE_LENGTH 16 /* Must be 2^N */
 #else
-#define THREADS_PER_CPU        10 /* 8 + THREADS_PER_CPU * number of CPUs = max threads */
-#define INITIAL_QUEUE_LENGTH 128
+#define QUEUE_LENGTH 64 /* Must be 2^N */
 #endif
-#define THREAD_EXIT_TIMEOUT 1000
 
 #include <mono/metadata/domain-internals.h>
 #include <mono/metadata/tabledefs.h>
 #include <mono/metadata/marshal.h>
 #include <mono/metadata/mono-perfcounters.h>
 #include <mono/metadata/socket-io.h>
+#include <mono/metadata/mono-wsq.h>
 #include <mono/io-layer/io-layer.h>
 #include <mono/metadata/gc-internal.h>
 #include <mono/utils/mono-time.h>
 #include <mono/utils/mono-proclib.h>
+#include <mono/utils/mono-semaphore.h>
 #include <errno.h>
 #ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
 #define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
                                                ThreadState_SuspendRequested)) != 0)
 
-#undef EPOLL_DEBUG
-//
+#define SPIN_TRYLOCK(i) (InterlockedCompareExchange (&(i), 1, 0) == 0)
+#define SPIN_LOCK(i) do { \
+                               if (SPIN_TRYLOCK (i)) \
+                                       break; \
+                       } while (1)
+
+#define SPIN_UNLOCK(i) i = 0
+
+#define EPOLL_DEBUG(...)
+#define EPOLL_DEBUG_STMT(...)
+#define TP_DEBUG(...)
+#define TP_DEBUG_STMT(...)
+
+/* DEBUG: prints tp data every 2s */
+#undef DEBUG 
+
+/*
+#define EPOLL_DEBUG(...) g_message(__VA_ARGS__)
+#define EPOLL_DEBUG_STMT(...) do { __VA_ARGS__ } while (0)
+#define TP_DEBUG(...) g_message(__VA_ARGS__)
+#define TP_DEBUG_STMT(...) do { __VA_ARGS__ } while (0)
+*/
+
 /* map of CounterSample.cs */
 struct _MonoCounterSample {
        gint64 rawValue;
@@ -79,13 +99,11 @@ struct _MonoCounterSample {
 };
 
 /* mono_thread_pool_init called */
-static int tp_inited;
-
-static int pending_io_items;
+static volatile int tp_inited;
 
 typedef struct {
        CRITICAL_SECTION io_lock; /* access to sock_to_state */
-       int inited;
+       int inited; // 0 -> not initialized , 1->initializing, 2->initialized, 3->cleaned up
        int pipe [2];
        MonoGHashTable *sock_to_state;
 
@@ -108,49 +126,51 @@ typedef struct {
        MonoObject        *state;
        MonoObject        *res;
        MonoArray         *out_args;
-       /* This is a HANDLE, we use guint64 so the managed object layout remains constant */
-       /* THIS FIELD IS NOT USED ANY MORE. Remove it when we feel like breaking corlib compatibility with 2.6 */
-       guint64           wait_event;
 } ASyncCall;
 
 typedef struct {
-       CRITICAL_SECTION lock;
-       MonoArray *array;
-       int first_elem;
-       int next_elem;
+       MonoSemType lock;
+       MonoMList *first; /* GC root */
+       MonoMList *last;
+       MonoMList *unused; /* Up to 20 chunks. GC root */
+       gint head;
+       gint tail;
+       MonoSemType new_job;
+       volatile gint waiting; /* threads waiting for a work item */
 
        /**/
-       GQueue *idle_threads;
-       int idle_started; /* Have we started the idle threads? Interlocked */
+       volatile gint pool_status; /* 0 -> not initialized, 1 -> initialized, 2 -> cleaning up */
        /* min, max, n and busy -> Interlocked */
-       int min_threads;
-       int max_threads;
-       int nthreads;
-       int busy_threads;
+       volatile gint min_threads;
+       volatile gint max_threads;
+       volatile gint nthreads;
+       volatile gint busy_threads;
 
        void (*async_invoke) (gpointer data);
        void *pc_nitems; /* Performance counter for total number of items in added */
-       /* We don't need the rate here since we can compute the different ourselves */
-       /* void *perfc_rate; */
-       MonoCounterSample last_sample;
-
+       void *pc_nthreads; /* Performance counter for total number of active threads */
+       /**/
+       volatile gint destroy_thread;
+       volatile gint ignore_times; /* Used when there's a thread being created or destroyed */
+       volatile gint sp_lock; /* spin lock used to protect ignore_times */
+       volatile gint64 last_check;
+       volatile gint64 time_sum;
+       volatile gint n_sum;
+       gint64 averages [2];
+       /**/
+       //TP_DEBUG_ONLY (gint nodes_created);
+       //TP_DEBUG_ONLY (gint nodes_reused);
+       gboolean is_io;
 } ThreadPool;
 
 static ThreadPool async_tp;
 static ThreadPool async_io_tp;
 
-typedef struct {
-       HANDLE wait_handle;
-       gpointer data;
-       gint timeout;
-       gboolean die;
-} IdleThreadData;
 static void async_invoke_thread (gpointer data);
-static void mono_async_invoke (MonoAsyncResult *ares);
+static MonoObject *mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares);
 static void threadpool_free_queue (ThreadPool *tp);
 static void threadpool_append_job (ThreadPool *tp, MonoObject *ar);
-static void *threadpool_queue_idle_thread (ThreadPool *tp, IdleThreadData *it);
+static void threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs);
 static void threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer));
 static void threadpool_start_idle_threads (ThreadPool *tp);
 static void threadpool_kill_idle_threads (ThreadPool *tp);
@@ -159,6 +179,9 @@ static MonoClass *async_call_klass;
 static MonoClass *socket_async_call_klass;
 static MonoClass *process_async_call_klass;
 
+static GPtrArray *wsqs;
+CRITICAL_SECTION wsqs_lock;
+
 /* Hooks */
 static MonoThreadPoolFunc tp_start_func;
 static MonoThreadPoolFunc tp_finish_func;
@@ -188,17 +211,21 @@ enum {
 static void
 socket_io_cleanup (SocketIOData *data)
 {
-       if (data->inited == 0)
+       EnterCriticalSection (&data->io_lock);
+       if (data->inited != 2) {
+               LeaveCriticalSection (&data->io_lock);
                return;
+       }
+       data->inited = 3;
 
-       EnterCriticalSection (&data->io_lock);
-       data->inited = 0;
 #ifdef HOST_WIN32
        closesocket (data->pipe [0]);
        closesocket (data->pipe [1]);
 #else
-       close (data->pipe [0]);
-       close (data->pipe [1]);
+       if (data->pipe [0] > -1)
+               close (data->pipe [0]);
+       if (data->pipe [1] > -1)
+               close (data->pipe [1]);
 #endif
        data->pipe [0] = -1;
        data->pipe [1] = -1;
@@ -207,10 +234,6 @@ socket_io_cleanup (SocketIOData *data)
        data->new_sem = NULL;
        mono_g_hash_table_destroy (data->sock_to_state);
        data->sock_to_state = NULL;
-       EnterCriticalSection (&async_io_tp.lock);
-       threadpool_free_queue (&async_io_tp);
-       threadpool_kill_idle_threads (&async_io_tp);
-       LeaveCriticalSection (&async_io_tp.lock);
        g_free (data->newpfd);
        data->newpfd = NULL;
 #ifdef HAVE_EPOLL
@@ -236,7 +259,7 @@ get_event_from_state (MonoSocketAsyncResult *state)
        case AIO_OP_CONNECT:
                return MONO_POLLOUT;
        default: /* Should never happen */
-               g_print ("get_event_from_state: unknown value in switch!!!\n");
+               g_message ("get_event_from_state: unknown value in switch!!!");
                return 0;
        }
 }
@@ -284,105 +307,38 @@ threadpool_jobs_dec (MonoObject *obj)
        return FALSE;
 }
 
-#ifndef DISABLE_SOCKETS
-static void
-async_invoke_io_thread (gpointer data)
+#ifdef HAVE_EPOLL
+static MonoObject *
+get_io_event (MonoMList **list, gint event)
 {
-       MonoDomain *domain;
-       MonoInternalThread *thread;
-       IdleThreadData idle_data = {0};
-  
-       idle_data.timeout = INFINITE;
-       idle_data.wait_handle = CreateEvent (NULL, FALSE, FALSE, NULL);
-
-       thread = mono_thread_internal_current ();
-       if (tp_start_func)
-               tp_start_func (tp_hooks_user_data);
-
-       for (;;) {
-               MonoSocketAsyncResult *state;
-               MonoAsyncResult *ar;
-
-               state = (MonoSocketAsyncResult *) data;
-               if (state) {
-                       InterlockedDecrement (&pending_io_items);
-                       ar = state->ares;
-                       switch (state->operation) {
-                       case AIO_OP_RECEIVE:
-                               state->total = ICALL_RECV (state);
-                               break;
-                       case AIO_OP_SEND:
-                               state->total = ICALL_SEND (state);
-                               break;
-                       }
-
-                       /* worker threads invokes methods in different domains,
-                        * so we need to set the right domain here */
-                       domain = ((MonoObject *)ar)->vtable->domain;
-
-                       g_assert (domain);
+       MonoObject *state;
+       MonoMList *current;
+       MonoMList *prev;
 
-                       if (domain->state == MONO_APPDOMAIN_UNLOADED || domain->state == MONO_APPDOMAIN_UNLOADING) {
-                               threadpool_jobs_dec ((MonoObject *)ar);
-                               data = NULL;
-                       } else {
-                               mono_thread_push_appdomain_ref (domain);
-                               if (threadpool_jobs_dec ((MonoObject *)ar)) {
-                                       data = NULL;
-                                       mono_thread_pop_appdomain_ref ();
-                                       continue;
-                               }
-                               if (mono_domain_set (domain, FALSE)) {
-                                       /* ASyncCall *ac; */
-
-                                       if (tp_item_begin_func)
-                                               tp_item_begin_func (tp_item_user_data);
-                                       mono_async_invoke (ar);
-                                       if (tp_item_end_func)
-                                               tp_item_end_func (tp_item_user_data);
-                                       /*
-                                       ac = (ASyncCall *) ar->object_data;
-                                       if (ac->msg->exc != NULL)
-                                               mono_unhandled_exception (ac->msg->exc);
-                                       */
-                                       mono_domain_set (mono_get_root_domain (), TRUE);
-                               }
-                               mono_thread_pop_appdomain_ref ();
-                               InterlockedDecrement (&async_io_tp.busy_threads);
-                               /* If the callee changes the background status, set it back to TRUE */
-                               if (!mono_thread_test_state (thread , ThreadState_Background))
-                                       ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
-                       }
-               }
+       current = *list;
+       prev = NULL;
+       state = NULL;
+       while (current) {
+               state = mono_mlist_get_data (current);
+               if (get_event_from_state ((MonoSocketAsyncResult *) state) == event)
+                       break;
 
-               data = threadpool_queue_idle_thread (&async_io_tp, &idle_data);
-               while (!idle_data.die && !data) {
-                       guint32 wr;
-                       wr = WaitForSingleObjectEx (idle_data.wait_handle, idle_data.timeout, TRUE);
-                       if (THREAD_WANTS_A_BREAK (thread))
-                               mono_thread_interruption_checkpoint ();
-               
-                       if (wr != WAIT_TIMEOUT && wr != WAIT_IO_COMPLETION) {
-                               data = idle_data.data;
-                               idle_data.data = NULL;
-                               break; /* We have to exit */
-                       }
-               }
+               state = NULL;
+               prev = current;
+               current = mono_mlist_next (current);
+       }
 
-               if (!data) {
-                       InterlockedDecrement (&async_io_tp.nthreads);
-                       CloseHandle (idle_data.wait_handle);
-                       idle_data.wait_handle = NULL;
-                       if (tp_finish_func)
-                               tp_finish_func (tp_hooks_user_data);
-                       return;
+       if (current) {
+               if (prev) {
+                       mono_mlist_set_next (prev, mono_mlist_next (current));
+               } else {
+                       *list = mono_mlist_next (*list);
                }
-               
-               InterlockedIncrement (&async_io_tp.busy_threads);
        }
 
-       g_assert_not_reached ();
+       return state;
 }
+#endif
 
 static MonoMList *
 process_io_event (MonoMList *list, int event)
@@ -402,10 +358,7 @@ process_io_event (MonoMList *list, int event)
 
        if (list != NULL) {
                oldlist = mono_mlist_remove_item (oldlist, list);
-#ifdef EPOLL_DEBUG
-               g_print ("Dispatching event %d on socket %p\n", event, state->handle);
-#endif
-               InterlockedIncrement (&pending_io_items);
+               EPOLL_DEBUG ("Dispatching event %d on socket %p", event, state->handle);
                threadpool_append_job (&async_io_tp, (MonoObject *) state);
        }
 
@@ -507,7 +460,8 @@ socket_io_poll_main (gpointer p)
 
                        for (i = 1; i < allocated; i++) {
                                pfd = &pfds [i];
-                               if (pfd->fd == -1 || pfd->fd == data->newpfd->fd)
+                               if (pfd->fd == -1 || data->newpfd == NULL ||
+                                       pfd->fd == data->newpfd->fd)
                                        break;
                        }
 
@@ -543,7 +497,7 @@ socket_io_poll_main (gpointer p)
                        continue;
 
                EnterCriticalSection (&data->io_lock);
-               if (data->inited == 0) {
+               if (data->inited == 3) {
                        g_free (pfds);
                        LeaveCriticalSection (&data->io_lock);
                        return; /* cleanup called */
@@ -580,6 +534,7 @@ socket_io_poll_main (gpointer p)
 
 #ifdef HAVE_EPOLL
 #define EPOLL_ERRORS (EPOLLERR | EPOLLHUP)
+#define EPOLL_NEVENTS  128
 static void
 socket_io_epoll_main (gpointer p)
 {
@@ -587,13 +542,14 @@ socket_io_epoll_main (gpointer p)
        int epollfd;
        MonoInternalThread *thread;
        struct epoll_event *events, *evt;
-       const int nevents = 512;
        int ready = 0, i;
+       gpointer async_results [EPOLL_NEVENTS * 2]; // * 2 because each loop can add up to 2 results here
+       gint nresults;
 
        data = p;
        epollfd = data->epollfd;
        thread = mono_thread_internal_current ();
-       events = g_new0 (struct epoll_event, nevents);
+       events = g_new0 (struct epoll_event, EPOLL_NEVENTS);
 
        while (1) {
                do {
@@ -601,83 +557,80 @@ socket_io_epoll_main (gpointer p)
                                if (THREAD_WANTS_A_BREAK (thread))
                                        mono_thread_interruption_checkpoint ();
                        }
-#ifdef EPOLL_DEBUG
-                       g_print ("epoll_wait init\n");
-#endif
-                       ready = epoll_wait (epollfd, events, nevents, -1);
-#ifdef EPOLL_DEBUG
-                       {
-                       int err = errno;
-                       g_print ("epoll_wait end with %d ready sockets (%d %s).\n", ready, err, (err) ? g_strerror (err) : "");
-                       errno = err;
-                       }
-#endif
+                       EPOLL_DEBUG ("epoll_wait init");
+                       ready = epoll_wait (epollfd, events, EPOLL_NEVENTS, -1);
+                       EPOLL_DEBUG_STMT(
+                               int err = errno;
+                               EPOLL_DEBUG ("epoll_wait end with %d ready sockets (%d %s).", ready, err, (ready == -1) ? g_strerror (err) : "");
+                               errno = err;
+                       );
                } while (ready == -1 && errno == EINTR);
 
                if (ready == -1) {
                        int err = errno;
                        g_free (events);
                        if (err != EBADF)
-                               g_warning ("epoll_wait: %d %s\n", err, g_strerror (err));
+                               g_warning ("epoll_wait: %d %s", err, g_strerror (err));
 
                        close (epollfd);
                        return;
                }
 
                EnterCriticalSection (&data->io_lock);
-               if (data->inited == 0) {
-#ifdef EPOLL_DEBUG
-                       g_print ("data->inited == 0\n");
-#endif
+               if (data->inited == 3) {
                        g_free (events);
                        close (epollfd);
+                       LeaveCriticalSection (&data->io_lock);
                        return; /* cleanup called */
                }
 
+               nresults = 0;
                for (i = 0; i < ready; i++) {
                        int fd;
                        MonoMList *list;
+                       MonoObject *ares;
 
                        evt = &events [i];
                        fd = evt->data.fd;
                        list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
-#ifdef EPOLL_DEBUG
-                       g_print ("Event %d on %d list length: %d\n", evt->events, fd, mono_mlist_length (list));
-#endif
+                       EPOLL_DEBUG ("Event %d on %d list length: %d", evt->events, fd, mono_mlist_length (list));
                        if (list != NULL && (evt->events & (EPOLLIN | EPOLL_ERRORS)) != 0) {
-                               list = process_io_event (list, MONO_POLLIN);
+                               ares = get_io_event (&list, MONO_POLLIN);
+                               if (ares != NULL)
+                                       async_results [nresults++] = ares;
                        }
 
                        if (list != NULL && (evt->events & (EPOLLOUT | EPOLL_ERRORS)) != 0) {
-                               list = process_io_event (list, MONO_POLLOUT);
+                               ares = get_io_event (&list, MONO_POLLOUT);
+                               if (ares != NULL)
+                                       async_results [nresults++] = ares;
                        }
 
                        if (list != NULL) {
                                mono_g_hash_table_replace (data->sock_to_state, GINT_TO_POINTER (fd), list);
                                evt->events = get_events_from_list (list);
-#ifdef EPOLL_DEBUG
-                               g_print ("MOD %d to %d\n", fd, evt->events);
-#endif
+                               EPOLL_DEBUG ("MOD %d to %d", fd, evt->events);
                                if (epoll_ctl (epollfd, EPOLL_CTL_MOD, fd, evt)) {
                                        if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fd, evt) == -1) {
-#ifdef EPOLL_DEBUG
-                                               int err = errno;
-                                               g_message ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
-                                               errno = err;
-#endif
+                                               EPOLL_DEBUG_STMT (
+                                                       int err = errno;
+                                                       EPOLL_DEBUG ("epoll_ctl(MOD): %d %s fd: %d events: %d", err, g_strerror (err), fd, evt->events);
+                                                       errno = err;
+                                               );
                                        }
                                }
                        } else {
                                mono_g_hash_table_remove (data->sock_to_state, GINT_TO_POINTER (fd));
-#ifdef EPOLL_DEBUG
-                               g_print ("DEL %d\n", fd);
-#endif
+                               EPOLL_DEBUG ("DEL %d", fd);
                                epoll_ctl (epollfd, EPOLL_CTL_DEL, fd, evt);
                        }
                }
                LeaveCriticalSection (&data->io_lock);
+               threadpool_append_jobs (&async_io_tp, (MonoObject **) async_results, nresults);
+               memset (async_results, 0, sizeof (gpointer) * nresults);
        }
 }
+#undef EPOLL_NEVENTS
 #endif
 
 /*
@@ -690,14 +643,17 @@ mono_thread_pool_remove_socket (int sock)
        MonoMList *list, *next;
        MonoSocketAsyncResult *state;
 
-       if (socket_io_data.inited == FALSE)
+       if (socket_io_data.inited == 0)
                return;
 
        EnterCriticalSection (&socket_io_data.io_lock);
+       if (socket_io_data.sock_to_state == NULL) {
+               LeaveCriticalSection (&socket_io_data.io_lock);
+               return;
+       }
        list = mono_g_hash_table_lookup (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
-       if (list) {
+       if (list)
                mono_g_hash_table_remove (socket_io_data.sock_to_state, GINT_TO_POINTER (sock));
-       }
        LeaveCriticalSection (&socket_io_data.io_lock);
        
        while (list) {
@@ -726,7 +682,7 @@ connect_hack (gpointer x)
        while (connect ((SOCKET) socket_io_data.pipe [1], (SOCKADDR *) addr, sizeof (struct sockaddr_in))) {
                Sleep (500);
                if (++count > 3) {
-                       g_warning ("Error initializing async. sockets %d.\n", WSAGetLastError ());
+                       g_warning ("Error initializing async. sockets %d.", WSAGetLastError ());
                        g_assert (WSAGetLastError ());
                }
        }
@@ -743,18 +699,22 @@ socket_io_init (SocketIOData *data)
        int len;
 #endif
        int inited;
+       guint32 stack_size;
 
-       inited = InterlockedCompareExchange (&data->inited, -1, -1);
-       if (inited == 1)
+       if (data->inited >= 2) // 2 -> initialized, 3-> cleaned up
                return;
 
-       EnterCriticalSection (&data->io_lock);
-       inited = InterlockedCompareExchange (&data->inited, -1, -1);
-       if (inited == 1) {
-               LeaveCriticalSection (&data->io_lock);
-               return;
+       inited = InterlockedCompareExchange (&data->inited, 1, 0);
+       if (inited >= 1) {
+               while (TRUE) {
+                       if (data->inited >= 2)
+                               return;
+                       SleepEx (1, FALSE);
+               }
        }
 
+       EnterCriticalSection (&data->io_lock);
+
 #ifdef HAVE_EPOLL
        data->epoll_disabled = (g_getenv ("MONO_DISABLE_AIO") != NULL);
        if (FALSE == data->epoll_disabled) {
@@ -804,12 +764,14 @@ socket_io_init (SocketIOData *data)
        closesocket (srv);
 #endif
        data->sock_to_state = mono_g_hash_table_new_type (g_direct_hash, g_direct_equal, MONO_HASH_VALUE_GC);
-       mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE);
 
        if (data->epoll_disabled) {
                data->new_sem = CreateSemaphore (NULL, 1, 1, NULL);
                g_assert (data->new_sem != NULL);
        }
+
+       stack_size = mono_threads_get_default_stacksize ();
+       mono_threads_set_default_stacksize (128 * 1024);
        if (data->epoll_disabled) {
                mono_thread_create_internal (mono_get_root_domain (), socket_io_poll_main, data, TRUE);
        }
@@ -818,8 +780,9 @@ socket_io_init (SocketIOData *data)
                mono_thread_create_internal (mono_get_root_domain (), socket_io_epoll_main, data, TRUE);
        }
 #endif
-       InterlockedCompareExchange (&data->inited, 1, 0);
+       mono_threads_set_default_stacksize (stack_size);
        LeaveCriticalSection (&data->io_lock);
+       data->inited = 2;
 }
 
 static void
@@ -831,11 +794,15 @@ socket_io_add_poll (MonoSocketAsyncResult *state)
        SocketIOData *data = &socket_io_data;
        int w;
 
+       if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
+               return;
+
 #if defined(PLATFORM_MACOSX) || defined(PLATFORM_BSD) || defined(HOST_WIN32) || defined(PLATFORM_SOLARIS)
        /* select() for connect() does not work well on the Mac. Bug #75436. */
        /* Bug #77637 for the BSD 6 case */
        /* Bug #78888 for the Windows case */
        if (state->operation == AIO_OP_CONNECT && state->blocking == TRUE) {
+               //FIXME: increment number of threads while this one is waiting?
                threadpool_append_job (&async_io_tp, (MonoObject *) state);
                return;
        }
@@ -845,6 +812,11 @@ socket_io_add_poll (MonoSocketAsyncResult *state)
                data->newpfd = g_new0 (mono_pollfd, 1);
 
        EnterCriticalSection (&data->io_lock);
+       if (data->sock_to_state == NULL) {
+               LeaveCriticalSection (&data->io_lock);
+               return;
+       }
+
        /* FIXME: 64 bit issue: handle can be a pointer on windows? */
        list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (state->handle));
        if (list == NULL) {
@@ -876,9 +848,16 @@ socket_io_add_epoll (MonoSocketAsyncResult *state)
        int epoll_op, ievt;
        int fd;
 
+       if (mono_runtime_is_shutting_down () || data->inited == 3 || data->sock_to_state == NULL)
+               return TRUE;
+
        memset (&event, 0, sizeof (struct epoll_event));
        fd = GPOINTER_TO_INT (state->handle);
        EnterCriticalSection (&data->io_lock);
+       if (data->sock_to_state == NULL) {
+               LeaveCriticalSection (&data->io_lock);
+               return TRUE;
+       }
        list = mono_g_hash_table_lookup (data->sock_to_state, GINT_TO_POINTER (fd));
        if (list == NULL) {
                list = mono_mlist_alloc ((MonoObject*)state);
@@ -896,20 +875,18 @@ socket_io_add_epoll (MonoSocketAsyncResult *state)
 
        mono_g_hash_table_replace (data->sock_to_state, state->handle, list);
        event.data.fd = fd;
-#ifdef EPOLL_DEBUG
-       g_print ("%s %d with %d\n", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
-#endif
+       EPOLL_DEBUG ("%s %d with %d", epoll_op == EPOLL_CTL_ADD ? "ADD" : "MOD", fd, event.events);
        if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
                int err = errno;
                if (epoll_op == EPOLL_CTL_ADD && err == EEXIST) {
                        epoll_op = EPOLL_CTL_MOD;
                        if (epoll_ctl (data->epollfd, epoll_op, fd, &event) == -1) {
-                               g_message ("epoll_ctl(MOD): %d %s\n", err, g_strerror (err));
+                               g_message ("epoll_ctl(MOD): %d %s", err, g_strerror (err));
                        }
                }
        }
-
        LeaveCriticalSection (&data->io_lock);
+
        return TRUE;
 }
 #endif
@@ -917,7 +894,11 @@ socket_io_add_epoll (MonoSocketAsyncResult *state)
 static void
 socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
 {
+       if (async_tp.pool_status == 2 || mono_runtime_is_shutting_down ())
+               return;
+
        socket_io_init (&socket_io_data);
+
        MONO_OBJECT_SETREF (state, ares, ares);
 #ifdef HAVE_EPOLL
        if (socket_io_data.epoll_disabled == FALSE) {
@@ -928,6 +909,7 @@ socket_io_add (MonoAsyncResult *ares, MonoSocketAsyncResult *state)
        socket_io_add_poll (state);
 }
 
+#ifndef DISABLE_SOCKETS
 static gboolean
 socket_io_filter (MonoObject *target, MonoObject *state)
 {
@@ -973,8 +955,9 @@ socket_io_filter (MonoObject *target, MonoObject *state)
 }
 #endif /* !DISABLE_SOCKETS */
 
-static void
-mono_async_invoke (MonoAsyncResult *ares)
+/* Returns the exception thrown when invoking, if any */
+static MonoObject *
+mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
 {
        ASyncCall *ac = (ASyncCall *)ares->object_data;
        MonoObject *res, *exc = NULL;
@@ -989,30 +972,36 @@ mono_async_invoke (MonoAsyncResult *ares)
                ares->original_context = NULL;
        }
 
-       ac->msg->exc = NULL;
-       res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
-       MONO_OBJECT_SETREF (ac, res, res);
-       MONO_OBJECT_SETREF (ac, msg->exc, exc);
-       MONO_OBJECT_SETREF (ac, out_args, out_args);
-
-       mono_monitor_enter ((MonoObject *) ares);
-       ares->completed = 1;
-       if (ares->handle != NULL)
-               wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
-       mono_monitor_exit ((MonoObject *) ares);
-       /* notify listeners */
-       if (wait_event != NULL)
-               SetEvent (wait_event);
-
-       /* call async callback if cb_method != null*/
-       if (ac->cb_method) {
-               MonoObject *exc = NULL;
-               void *pa = &ares;
-               mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &exc);
-               /* 'exc' will be the previous ac->msg->exc if not NULL and not
-                * catched. If catched, this will be set to NULL and the
-                * exception will not be printed. */
-               MONO_OBJECT_SETREF (ac->msg, exc, exc);
+       if (ac == NULL) {
+               /* Fast path from ThreadPool.*QueueUserWorkItem */
+               void *pa = ares->async_state;
+               mono_runtime_delegate_invoke (ares->async_delegate, &pa, &exc);
+       } else {
+               ac->msg->exc = NULL;
+               res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
+               MONO_OBJECT_SETREF (ac, res, res);
+               MONO_OBJECT_SETREF (ac, msg->exc, exc);
+               MONO_OBJECT_SETREF (ac, out_args, out_args);
+
+               mono_monitor_enter ((MonoObject *) ares);
+               ares->completed = 1;
+               if (ares->handle != NULL)
+                       wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
+               mono_monitor_exit ((MonoObject *) ares);
+               /* notify listeners */
+               if (wait_event != NULL)
+                       SetEvent (wait_event);
+
+               /* call async callback if cb_method != null*/
+               if (ac != NULL && ac->cb_method) {
+                       MonoObject *exc = NULL;
+                       void *pa = &ares;
+                       mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &exc);
+                       /* 'exc' will be the previous ac->msg->exc if not NULL and not
+                        * catched. If catched, this will be set to NULL and the
+                        * exception will not be printed. */
+                       MONO_OBJECT_SETREF (ac->msg, exc, exc);
+               }
        }
 
        /* restore original thread execution context if flow isn't suppressed, i.e. non null */
@@ -1020,23 +1009,25 @@ mono_async_invoke (MonoAsyncResult *ares)
                mono_thread_set_execution_context (ares->original_context);
                ares->original_context = NULL;
        }
-
+       return exc;
 }
 
 static void
 threadpool_start_idle_threads (ThreadPool *tp)
 {
-       int needed;
-       int existing;
+       int n;
 
-       needed = (int) InterlockedCompareExchange (&tp->min_threads, 0, -1); 
        do {
-               existing = (int) InterlockedCompareExchange (&tp->nthreads, 0, -1); 
-               if (existing >= needed)
-                       break;
-               InterlockedIncrement (&tp->nthreads);
-               mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, NULL, TRUE);
-               SleepEx (250, TRUE);
+               while (1) {
+                       n = tp->nthreads;
+                       if (n >= tp->min_threads)
+                               return;
+                       if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n)
+                               break;
+               }
+               mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
+               mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE);
+               SleepEx (100, TRUE);
        } while (1);
 }
 
@@ -1044,11 +1035,11 @@ static void
 threadpool_init (ThreadPool *tp, int min_threads, int max_threads, void (*async_invoke) (gpointer))
 {
        memset (tp, 0, sizeof (ThreadPool));
-       InitializeCriticalSection (&tp->lock);
+       MONO_SEM_INIT (&tp->lock, 1);
        tp->min_threads = min_threads;
        tp->max_threads = max_threads;
        tp->async_invoke = async_invoke;
-       tp->idle_threads = g_queue_new ();
+       MONO_SEM_INIT (&tp->new_job, 0);
 }
 
 static void *
@@ -1070,41 +1061,116 @@ init_perf_counter (const char *category, const char *counter)
        return mono_perfcounter_get_impl (category_str, counter_str, NULL, machine, &type, &custom);
 }
 
+#ifdef DEBUG
+static void
+print_pool_info (ThreadPool *tp)
+{
+
+//     if (tp->tail - tp->head == 0)
+//             return;
+
+       g_print ("Pool status? %d\n", InterlockedCompareExchange (&tp->pool_status, 0, 0));
+       g_print ("Min. threads: %d\n", InterlockedCompareExchange (&tp->min_threads, 0, 0));
+       g_print ("Max. threads: %d\n", InterlockedCompareExchange (&tp->max_threads, 0, 0));
+       g_print ("nthreads: %d\n", InterlockedCompareExchange (&tp->nthreads, 0, 0));
+       g_print ("busy threads: %d\n", InterlockedCompareExchange (&tp->busy_threads, 0, 0));
+       g_print ("Waiting: %d\n", InterlockedCompareExchange (&tp->waiting, 0, 0));
+       g_print ("Queued: %d\n", (tp->tail - tp->head));
+       if (tp == &async_tp) {
+               int i;
+               EnterCriticalSection (&wsqs_lock);
+               for (i = 0; i < wsqs->len; i++) {
+                       g_print ("\tWSQ %d: %d\n", i, mono_wsq_count (g_ptr_array_index (wsqs, i)));
+               }
+               LeaveCriticalSection (&wsqs_lock);
+       } else {
+               g_print ("\tSockets: %d\n", mono_g_hash_table_size (socket_io_data.sock_to_state));
+       }
+       g_print ("-------------\n");
+}
+
+static void
+signal_handler (int signo)
+{
+       ThreadPool *tp;
+
+       tp = &async_tp;
+       MONO_SEM_WAIT (&tp->lock);
+       g_print ("\n-----Non-IO-----\n");
+       print_pool_info (tp);
+       MONO_SEM_POST (&tp->lock);
+       tp = &async_io_tp;
+       MONO_SEM_WAIT (&tp->lock);
+       g_print ("\n-----IO-----\n");
+       print_pool_info (tp);
+       MONO_SEM_POST (&tp->lock);
+       alarm (2);
+}
+#endif
+
 void
 mono_thread_pool_init ()
 {
-       int threads_per_cpu = THREADS_PER_CPU;
-       int cpu_count;
-       int n;
+       gint threads_per_cpu = 1;
+       gint thread_count;
+       gint cpu_count = mono_cpu_count ();
+       int result;
 
-       if ((int) InterlockedCompareExchange (&tp_inited, 1, 0) == 1)
+       if (tp_inited == 2)
                return;
 
+       result = InterlockedCompareExchange (&tp_inited, 1, 0);
+       if (result == 1) {
+               while (1) {
+                       SleepEx (1, FALSE);
+                       if (tp_inited == 2)
+                               return;
+               }
+       }
+
+       MONO_GC_REGISTER_ROOT (async_tp.first);
+       MONO_GC_REGISTER_ROOT (async_tp.last);
+       MONO_GC_REGISTER_ROOT (async_tp.unused);
+       MONO_GC_REGISTER_ROOT (async_io_tp.first);
+       MONO_GC_REGISTER_ROOT (async_io_tp.unused);
+       MONO_GC_REGISTER_ROOT (async_io_tp.last);
+
        MONO_GC_REGISTER_ROOT (socket_io_data.sock_to_state);
        InitializeCriticalSection (&socket_io_data.io_lock);
        if (g_getenv ("MONO_THREADS_PER_CPU") != NULL) {
                threads_per_cpu = atoi (g_getenv ("MONO_THREADS_PER_CPU"));
-               if (threads_per_cpu < THREADS_PER_CPU)
-                       threads_per_cpu = THREADS_PER_CPU;
+               if (threads_per_cpu < 1)
+                       threads_per_cpu = 1;
        }
 
-       cpu_count = mono_cpu_count ();
-       n = 8 + 2 * cpu_count; /* 8 is minFreeThreads for ASP.NET */
-       threadpool_init (&async_tp, n, n + threads_per_cpu * cpu_count, async_invoke_thread);
-#ifndef DISABLE_SOCKETS
-       threadpool_init (&async_io_tp, 2 * cpu_count, 8 * cpu_count, async_invoke_io_thread);
-#endif
+       thread_count = MIN (cpu_count * threads_per_cpu, 100 * cpu_count);
+       threadpool_init (&async_tp, thread_count, MAX (100 * cpu_count, thread_count), async_invoke_thread);
+       threadpool_init (&async_io_tp, cpu_count * 2, cpu_count * 4, async_invoke_thread);
+       async_io_tp.is_io = TRUE;
 
        async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
        g_assert (async_call_klass);
 
+       InitializeCriticalSection (&wsqs_lock);
+       wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
+       mono_wsq_init ();
+
        async_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "Work Items Added");
        g_assert (async_tp.pc_nitems);
-       mono_perfcounter_get_sample (async_tp.pc_nitems, FALSE, &async_tp.last_sample);
 
        async_io_tp.pc_nitems = init_perf_counter ("Mono Threadpool", "IO Work Items Added");
        g_assert (async_io_tp.pc_nitems);
-       mono_perfcounter_get_sample (async_io_tp.pc_nitems, FALSE, &async_io_tp.last_sample);
+
+       async_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of Threads");
+       g_assert (async_tp.pc_nthreads);
+
+       async_io_tp.pc_nthreads = init_perf_counter ("Mono Threadpool", "# of IO Threads");
+       g_assert (async_io_tp.pc_nthreads);
+       tp_inited = 2;
+#ifdef DEBUG
+       signal (SIGALRM, signal_handler);
+       alarm (2);
+#endif
 }
 
 MonoAsyncResult *
@@ -1115,7 +1181,7 @@ mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *
        MonoAsyncResult *ares;
        ASyncCall *ac;
 
-       ac = (ASyncCall*)mono_object_new (mono_domain_get (), async_call_klass);
+       ac = (ASyncCall*)mono_object_new (domain, async_call_klass);
        MONO_OBJECT_SETREF (ac, msg, msg);
        MONO_OBJECT_SETREF (ac, state, state);
 
@@ -1133,9 +1199,6 @@ mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *
                return ares;
        }
 #endif
-       if (InterlockedCompareExchange (&async_tp.idle_started, 1, 0) == 0)
-               mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE);
-       
        threadpool_append_job (&async_tp, (MonoObject *) ares);
        return ares;
 }
@@ -1153,8 +1216,7 @@ mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject
        mono_monitor_enter ((MonoObject *) ares);
        
        if (ares->endinvoke_called) {
-               *exc = (MonoObject *)mono_exception_from_name (mono_defaults.corlib, "System", 
-                                             "InvalidOperationException");
+               *exc = (MonoObject *) mono_get_exception_invalid_operation (NULL);
                mono_monitor_exit ((MonoObject *) ares);
                return NULL;
        }
@@ -1186,43 +1248,44 @@ mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject
 static void
 threadpool_kill_idle_threads (ThreadPool *tp)
 {
-       IdleThreadData *it;
-
-       if (!tp || !tp->idle_threads)
-               return;
+       gint n;
 
-       while ((it = g_queue_pop_head (tp->idle_threads)) != NULL) {
-               it->data = NULL;
-               it->die = TRUE;
-               SetEvent (it->wait_handle);
+       n = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
+       while (n) {
+               n--;
+               MONO_SEM_POST (&tp->new_job);
        }
-       g_queue_free (tp->idle_threads);
-       tp->idle_threads = NULL;
 }
 
 void
 mono_thread_pool_cleanup (void)
 {
-       EnterCriticalSection (&async_tp.lock);
+       if (async_tp.pool_status == 0 || async_tp.pool_status == 2)
+               return;
+
+       if (async_tp.pool_status == 1 && InterlockedCompareExchange (&async_tp.pool_status, 2, 1) == 2)
+               return;
+
+       InterlockedExchange (&async_io_tp.pool_status, 2);
+       MONO_SEM_WAIT (&async_tp.lock);
        threadpool_free_queue (&async_tp);
        threadpool_kill_idle_threads (&async_tp);
-       LeaveCriticalSection (&async_tp.lock);
-       socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
-       /* Do we want/need these?
-       DeleteCriticalSection (&async_tp.lock);
-       DeleteCriticalSection (&async_tp.table_lock);
-       DeleteCriticalSection (&socket_io_data.io_lock);
-       */
-}
+       MONO_SEM_POST (&async_tp.lock);
 
-static void
-null_array (MonoArray *a, int first, int last)
-{
-       /* We must null the old array because it might
-          contain cross-appdomain references, which
-          will crash the GC when the domains are
-          unloaded. */
-       memset (mono_array_addr (a, MonoObject*, first), 0, sizeof (MonoObject*) * (last - first));
+       socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
+       MONO_SEM_WAIT (&async_io_tp.lock);
+       threadpool_free_queue (&async_io_tp);
+       threadpool_kill_idle_threads (&async_io_tp);
+       MONO_SEM_POST (&async_io_tp.lock);
+       MONO_SEM_DESTROY (&async_io_tp.new_job);
+
+       EnterCriticalSection (&wsqs_lock);
+       mono_wsq_cleanup ();
+       if (wsqs)
+               g_ptr_array_free (wsqs, TRUE);
+       wsqs = NULL;
+       LeaveCriticalSection (&wsqs_lock);
+       MONO_SEM_DESTROY (&async_tp.new_job);
 }
 
 /* Caller must enter &tp->lock */
@@ -1230,208 +1293,198 @@ static MonoObject*
 dequeue_job_nolock (ThreadPool *tp)
 {
        MonoObject *ar;
-       int count;
+       MonoArray *array;
+       MonoMList *list;
 
-       if (!tp->array || tp->first_elem == tp->next_elem)
-               return NULL;
-       ar = mono_array_get (tp->array, MonoObject*, tp->first_elem);
-       mono_array_set (tp->array, MonoObject*, tp->first_elem, NULL);
-       tp->first_elem++;
-       count = tp->next_elem - tp->first_elem;
-       /* reduce the size of the array if it's mostly empty */
-       if (mono_array_length (tp->array) > INITIAL_QUEUE_LENGTH && count < (mono_array_length (tp->array) / 3)) {
-               MonoArray *newa = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (tp->array) / 2);
-               mono_array_memcpy_refs (newa, 0, tp->array, tp->first_elem, count);
-               null_array (tp->array, tp->first_elem, tp->next_elem);
-               tp->array = newa;
-               tp->first_elem = 0;
-               tp->next_elem = count;
-       }
+       list = tp->first;
+       do {
+               if (mono_runtime_is_shutting_down ())
+                       return NULL;
+               if (!list || tp->head == tp->tail)
+                       return NULL;
+
+               array = (MonoArray *) mono_mlist_get_data (list);
+               ar = mono_array_get (array, MonoObject *, tp->head % QUEUE_LENGTH);
+               mono_array_set (array, MonoObject *, tp->head % QUEUE_LENGTH, NULL);
+               tp->head++;
+               if ((tp->head % QUEUE_LENGTH) == 0) {
+                       list = tp->first;
+                       tp->first = mono_mlist_next (list);
+                       if (tp->first == NULL)
+                               tp->last = NULL;
+                       if (mono_mlist_length (tp->unused) < 20) {
+                               /* reuse this chunk */
+                               tp->unused = mono_mlist_set_next (list, tp->unused);
+                       }
+                       tp->head -= QUEUE_LENGTH;
+                       tp->tail -= QUEUE_LENGTH;
+               }
+               list = tp->first;
+       } while (ar == NULL);
        return ar;
 }
 
-/* Call after entering &tp->lock */
-static int
-signal_idle_threads (ThreadPool *tp)
+static gboolean
+threadpool_start_thread (ThreadPool *tp)
 {
-       IdleThreadData *it;
-       int result = 0;
-       int njobs;
-
-       njobs = tp->next_elem - tp->first_elem;
-       while (njobs > 0 && (it = g_queue_pop_head (tp->idle_threads)) != NULL) {
-               it->data = dequeue_job_nolock (tp);
-               if (it->data == NULL)
-                       break; /* Should never happen */
-               result++;
-               njobs--;
-               it->timeout = INFINITE;
-               SetEvent (it->wait_handle);
+       gint n;
+
+       while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
+               if (InterlockedCompareExchange (&tp->nthreads, n + 1, n) == n) {
+                       mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
+                       mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE);
+                       return TRUE;
+               }
        }
-       return njobs;
+
+       return FALSE;
 }
 
-/* Call after entering &tp->lock */
-static gboolean
-threadpool_start_thread (ThreadPool *tp, gpointer arg)
+static void
+pulse_on_new_job (ThreadPool *tp)
 {
-       gint max;
-       gint n;
+       if (tp->waiting)
+               MONO_SEM_POST (&tp->new_job);
+}
 
-       max = (gint) InterlockedCompareExchange (&tp->max_threads, 0, -1);
-       n = (gint) InterlockedCompareExchange (&tp->nthreads, 0, -1);
-       if (max <= n)
-               return FALSE;
-       InterlockedIncrement (&tp->nthreads);
-       mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, arg, TRUE);
-       return TRUE;
+void
+icall_append_job (MonoObject *ar)
+{
+       threadpool_append_job (&async_tp, ar);
 }
 
-/*
-static const char *
-get_queue_name (ThreadPool *tp)
+static void
+threadpool_append_job (ThreadPool *tp, MonoObject *ar)
 {
-       if (tp == &async_tp)
-               return "TP";
-       if (tp == &async_io_tp)
-               return "IO";
-       return "(Unknown)";
+       threadpool_append_jobs (tp, &ar, 1);
 }
-*/
 
-static gpointer
-threadpool_queue_idle_thread (ThreadPool *tp, IdleThreadData *it)
+static MonoMList *
+create_or_reuse_list (ThreadPool *tp)
 {
-       /*
-       MonoCounterSample sample;
-       float rate;
-       */
-       gpointer result = NULL;
-       CRITICAL_SECTION *cs = &tp->lock;
-
-       EnterCriticalSection (cs);
-       if (tp->idle_threads == NULL) {
-               it->die = TRUE;
-               LeaveCriticalSection (cs);
-               return NULL; /* We are shutting down */
-       }
-       /*
-       if (mono_100ns_ticks () - tp->last_sample.timeStamp > 10000 * 1000) {
-               float elapsed_ticks;
-               mono_perfcounter_get_sample (tp->pc_nitems, FALSE, &sample);
-
-               elapsed_ticks = (float) (sample.timeStamp - tp->last_sample.timeStamp);
-               rate = ((float) (sample.rawValue - tp->last_sample.rawValue)) / elapsed_ticks * 10000000;
-               printf ("Queue: %s NThreads: %d Rate: %.2f Total items: %lld Time(ms): %.2f\n", get_queue_name (tp),
-                                               InterlockedCompareExchange (&tp->nthreads, 0, -1), rate,
-                                               sample.rawValue - tp->last_sample.rawValue, elapsed_ticks / 10000);
-               memcpy (&tp->last_sample, &sample, sizeof (sample));
-       }
-       */
+       MonoMList *list;
+       MonoArray *array;
 
-       it->data = result = dequeue_job_nolock (tp);
-       if (result != NULL) {
-               signal_idle_threads (tp);
+       list = NULL;
+       if (tp->unused) {
+               list = tp->unused;
+               tp->unused = mono_mlist_next (list);
+               mono_mlist_set_next (list, NULL);
+               //TP_DEBUG (tp->nodes_reused++);
        } else {
-               int min, n;
-               min = (gint) InterlockedCompareExchange (&tp->min_threads, 0, -1);
-               n = (gint) InterlockedCompareExchange (&tp->nthreads, 0, -1);
-               if (n <= min) {
-                       g_queue_push_tail (tp->idle_threads, it);
-               } else {
-                       /* TODO: figure out when threads should be told to die */
-                       /* it->die = TRUE; */
-                       g_queue_push_tail (tp->idle_threads, it);
-               }
+               array = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, QUEUE_LENGTH);
+               list = mono_mlist_alloc ((MonoObject *) array);
+               //TP_DEBUG (tp->nodes_created++);
        }
-       LeaveCriticalSection (cs);
-       return result;
+       return list;
 }
 
 static void
-threadpool_append_job (ThreadPool *tp, MonoObject *ar)
+threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
 {
-       CRITICAL_SECTION *cs;
-
-       cs = &tp->lock;
-       threadpool_jobs_inc (ar); 
-       EnterCriticalSection (cs);
-       if (tp->idle_threads == NULL) { 
-               LeaveCriticalSection (cs);
-               return; /* We are shutting down */
-       }
-       if (ar->vtable->domain->state == MONO_APPDOMAIN_UNLOADING ||
-                       ar->vtable->domain->state == MONO_APPDOMAIN_UNLOADED) {
-               LeaveCriticalSection (cs);
+       static int job_counter;
+       MonoArray *array;
+       MonoMList *list;
+       MonoObject *ar;
+       gint i;
+       gboolean lock_taken = FALSE; /* We won't take the lock when the local queue is used */
+
+       if (mono_runtime_is_shutting_down ())
                return;
-       }
 
-       mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
-       if (tp->array && (tp->next_elem < mono_array_length (tp->array))) {
-               mono_array_setref (tp->array, tp->next_elem, ar);
-               tp->next_elem++;
-               if (signal_idle_threads (tp) > 0 && threadpool_start_thread (tp, ar)) {
-                       tp->next_elem--;
-                       mono_array_setref (tp->array, tp->next_elem, NULL);
+       if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0)
+               mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, tp, TRUE);
+
+       for (i = 0; i < njobs; i++) {
+               ar = jobs [i];
+               if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
+                       continue; /* Might happen when cleaning domain jobs */
+               if (!tp->is_io && (InterlockedIncrement (&job_counter) % 10) == 0) {
+                       MonoAsyncResult *o = (MonoAsyncResult *) ar;
+                       o->add_time = mono_100ns_ticks ();
                }
-               LeaveCriticalSection (cs);
-               return;
-       }
+               threadpool_jobs_inc (ar); 
+               mono_perfcounter_update_value (tp->pc_nitems, TRUE, 1);
+               if (!tp->is_io && mono_wsq_local_push (ar))
+                       continue;
 
-       if (!tp->array) {
-               MONO_GC_REGISTER_ROOT (tp->array);
-               tp->array = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, INITIAL_QUEUE_LENGTH);
-       } else {
-               int count = tp->next_elem - tp->first_elem;
-               /* slide the array or create a larger one if it's full */
-               if (tp->first_elem) {
-                       mono_array_memcpy_refs (tp->array, 0, tp->array, tp->first_elem, count);
-                       null_array (tp->array, count, tp->next_elem);
-               } else {
-                       MonoArray *newa = mono_array_new_cached (mono_get_root_domain (), mono_defaults.object_class, mono_array_length (tp->array) * 2);
-                       mono_array_memcpy_refs (newa, 0, tp->array, tp->first_elem, count);
-                       null_array (tp->array, count, tp->next_elem);
-                       tp->array = newa;
+               if (!lock_taken) {
+                       MONO_SEM_WAIT (&tp->lock);
+                       lock_taken = TRUE;
                }
-               tp->first_elem = 0;
-               tp->next_elem = count;
+               if ((tp->tail % QUEUE_LENGTH) == 0) {
+                       list = create_or_reuse_list (tp);
+                       if (tp->last != NULL)
+                               mono_mlist_set_next (tp->last, list);
+                       tp->last = list;
+                       if (tp->first == NULL)
+                               tp->first = tp->last;
+               }
+
+               array = (MonoArray *) mono_mlist_get_data (tp->last);
+               mono_array_setref (array, tp->tail % QUEUE_LENGTH, ar);
+               tp->tail++;
        }
-       mono_array_setref (tp->array, tp->next_elem, ar);
-       tp->next_elem++;
-       if (signal_idle_threads (tp) > 0 && threadpool_start_thread (tp, ar)) {
-               tp->next_elem--;
-               mono_array_setref (tp->array, tp->next_elem, NULL);
+       if (lock_taken)
+               MONO_SEM_POST (&tp->lock);
+
+       if (!tp->is_io && tp->waiting == 0) {
+               gint64 ticks = mono_100ns_ticks ();
+
+               if (tp->last_check == 0 || (ticks - tp->last_check) > 5000000) {
+                       SPIN_LOCK (tp->sp_lock);
+                       tp->last_check = ticks;
+                       SPIN_UNLOCK (tp->sp_lock);
+                       threadpool_start_thread (tp);
+               }
        }
-       LeaveCriticalSection (cs);
+       for (i = 0; i < MIN(njobs, tp->max_threads); i++)
+               pulse_on_new_job (tp);
 }
 
-
 static void
 threadpool_clear_queue (ThreadPool *tp, MonoDomain *domain)
 {
-       int i, count = 0;
-       EnterCriticalSection (&tp->lock);
-       /*remove*/
-       for (i = tp->first_elem; i < tp->next_elem; ++i) {
-               MonoObject *obj = mono_array_get (tp->array, MonoObject*, i);
-               if (obj->vtable->domain == domain) {
-                       mono_array_set (tp->array, MonoObject*, i, NULL);
-                       InterlockedDecrement (&domain->threadpool_jobs);
-                       ++count;
+       MonoMList *current;
+       MonoArray *array;
+       MonoObject *obj;
+       int domain_count;
+       int i;
+
+       domain_count = 0;
+       MONO_SEM_WAIT (&tp->lock);
+       current = tp->first;
+       while (current) {
+               array = (MonoArray *) mono_mlist_get_data (current);
+               for (i = 0; i < QUEUE_LENGTH; i++) {
+                       obj = mono_array_get (array, MonoObject*, i);
+                       if (obj != NULL && obj->vtable->domain == domain) {
+                               domain_count++;
+                               mono_array_setref (array, i, NULL);
+                               threadpool_jobs_dec (obj);
+                       }
                }
+               current = mono_mlist_next (current);
        }
-       /*compact*/
-       if (count) {
-               int idx = 0;
-               for (i = tp->first_elem; i < tp->next_elem; ++i) {
-                       MonoObject *obj = mono_array_get (tp->array, MonoObject*, i);
-                       if (obj)
-                               mono_array_set (tp->array, MonoObject*, idx++, obj);
-               }
-               tp->first_elem = 0;
-               tp->next_elem = count;
+
+       if (!domain_count) {
+               MONO_SEM_POST (&tp->lock);
+               return;
+       }
+
+       current = tp->first;
+       tp->first = NULL;
+       tp->last = NULL;
+       tp->head = 0;
+       tp->tail = 0;
+       MONO_SEM_POST (&tp->lock);
+       /* Re-add everything but the nullified elements */
+       while (current) {
+               array = (MonoArray *) mono_mlist_get_data (current);
+               threadpool_append_jobs (tp, mono_array_addr (array, MonoObject *, 0), QUEUE_LENGTH);
+               memset (mono_array_addr (array, MonoObject *, 0), 0, sizeof (MonoObject *) * QUEUE_LENGTH);
+               current = mono_mlist_next (current);
        }
-       LeaveCriticalSection (&tp->lock);
 }
 
 /*
@@ -1456,7 +1509,7 @@ mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
         * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
         */
        sem_handle = CreateSemaphore (NULL, 0, 1, NULL);
-       
+
        domain->cleanup_semaphore = sem_handle;
        /*
         * The memory barrier here is required to have global ordering between assigning to cleanup_semaphone
@@ -1483,16 +1536,187 @@ mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
 static void
 threadpool_free_queue (ThreadPool *tp)
 {
-       if (tp->array)
-               null_array (tp->array, tp->first_elem, tp->next_elem);
-       tp->array = NULL;
-       tp->first_elem = tp->next_elem = 0;
+       tp->head = tp->tail = 0;
+       tp->first = NULL;
+       tp->unused = NULL;
 }
 
 gboolean
 mono_thread_pool_is_queue_array (MonoArray *o)
 {
-       return o == async_tp.array || o == async_io_tp.array;
+       gpointer obj = o;
+
+       // FIXME: need some fix in sgen code.
+       // There are roots at: async*tp.unused (MonoMList) and wsqs [n]->queue (MonoArray)
+       return obj == async_tp.first || obj == async_io_tp.first;
+}
+
+static void
+add_wsq (MonoWSQ *wsq)
+{
+       int i;
+
+       if (wsq == NULL)
+               return;
+
+       EnterCriticalSection (&wsqs_lock);
+       if (wsqs == NULL) {
+               LeaveCriticalSection (&wsqs_lock);
+               return;
+       }
+       for (i = 0; i < wsqs->len; i++) {
+               if (g_ptr_array_index (wsqs, i) == NULL) {
+                       wsqs->pdata [i] = wsq;
+                       LeaveCriticalSection (&wsqs_lock);
+                       return;
+               }
+       }
+       g_ptr_array_add (wsqs, wsq);
+       LeaveCriticalSection (&wsqs_lock);
+}
+
+static void
+remove_wsq (MonoWSQ *wsq)
+{
+       if (wsq == NULL)
+               return;
+
+       EnterCriticalSection (&wsqs_lock);
+       if (wsqs == NULL) {
+               LeaveCriticalSection (&wsqs_lock);
+               return;
+       }
+       g_ptr_array_remove_fast (wsqs, wsq);
+       LeaveCriticalSection (&wsqs_lock);
+}
+
+static void
+try_steal (gpointer *data, gboolean retry)
+{
+       int i;
+       int ms;
+
+       if (wsqs == NULL || data == NULL || *data != NULL)
+               return;
+
+       ms = 0;
+       do {
+               if (mono_runtime_is_shutting_down ())
+                       return;
+               for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
+                       if (mono_runtime_is_shutting_down ()) {
+                               return;
+                       }
+                       mono_wsq_try_steal (wsqs->pdata [i], data, ms);
+                       if (*data != NULL) {
+                               return;
+                       }
+               }
+               ms += 10;
+       } while (retry && ms < 11);
+}
+
+static gboolean
+dequeue_or_steal (ThreadPool *tp, gpointer *data)
+{
+       if (mono_runtime_is_shutting_down ())
+               return FALSE;
+       TP_DEBUG ("Dequeue");
+       MONO_SEM_WAIT (&tp->lock);
+       *data = dequeue_job_nolock (tp);
+       MONO_SEM_POST (&tp->lock);
+       if (!tp->is_io && !*data)
+               try_steal (data, FALSE);
+       return (*data != NULL);
+}
+
+static void
+process_idle_times (ThreadPool *tp, gint64 t)
+{
+       gint64 ticks;
+       gint64 avg;
+       gboolean compute_avg;
+       gint new_threads;
+       gint64 per1;
+
+       if (tp->ignore_times || t <= 0)
+               return;
+
+       compute_avg = FALSE;
+       ticks = mono_100ns_ticks ();
+       t = ticks - t;
+       SPIN_LOCK (tp->sp_lock);
+       if (tp->ignore_times) {
+               SPIN_UNLOCK (tp->sp_lock);
+               return;
+       }
+       tp->time_sum += t;
+       tp->n_sum++;
+       if (tp->last_check == 0)
+               tp->last_check = ticks;
+       else if (tp->last_check > 0 && (ticks - tp->last_check) > 5000000) {
+               tp->ignore_times = 1;
+               compute_avg = TRUE;
+       }
+       SPIN_UNLOCK (tp->sp_lock);
+
+       if (!compute_avg)
+               return;
+
+       //printf ("Items: %d Time elapsed: %.3fs\n", tp->n_sum, (ticks - tp->last_check) / 10000.0);
+       tp->last_check = ticks;
+       new_threads = 0;
+       avg = tp->time_sum / tp->n_sum;
+       if (tp->averages [1] == 0) {
+               tp->averages [1] = avg;
+       } else {
+               per1 = ((100 * (ABS (avg - tp->averages [1]))) / tp->averages [1]);
+               if (per1 > 5) {
+                       if (avg > tp->averages [1]) {
+                               if (tp->averages [1] < tp->averages [0]) {
+                                       new_threads = -1;
+                               } else {
+                                       new_threads = 1;
+                               }
+                       } else if (avg < tp->averages [1] && tp->averages [1] < tp->averages [0]) {
+                               new_threads = 1;
+                       }
+               } else {
+                       int min, n;
+                       min = tp->min_threads;
+                       n = tp->nthreads;
+                       if ((n - min) < min && tp->busy_threads == n)
+                               new_threads = 1;
+               }
+               /*
+               if (new_threads != 0) {
+                       printf ("n: %d per1: %lld avg=%lld avg1=%lld avg0=%lld\n", new_threads, per1, avg, tp->averages [1], tp->averages [0]);
+               }
+               */
+       }
+
+       tp->time_sum = 0;
+       tp->n_sum = 0;
+
+       tp->averages [0] = tp->averages [1];
+       tp->averages [1] = avg;
+       tp->ignore_times = 0;
+
+       if (tp->waiting == 0 && new_threads == 1) {
+               threadpool_start_thread (tp);
+       } else if (new_threads == -1) {
+               if (tp->destroy_thread == 0 && InterlockedCompareExchange (&tp->destroy_thread, 1, 0) == 0)
+                       pulse_on_new_job (tp);
+       }
+}
+
+static gboolean
+should_i_die (ThreadPool *tp)
+{
+       gboolean result = FALSE;
+       if (tp->destroy_thread == 1 && InterlockedCompareExchange (&tp->destroy_thread, 0, 1) == 1)
+               result = (tp->nthreads > tp->min_threads);
+       return result;
 }
 
 static void
@@ -1500,33 +1724,62 @@ async_invoke_thread (gpointer data)
 {
        MonoDomain *domain;
        MonoInternalThread *thread;
-       IdleThreadData idle_data = {0};
+       MonoWSQ *wsq;
+       ThreadPool *tp;
+       gboolean must_die;
   
-       idle_data.timeout = INFINITE;
-       idle_data.wait_handle = CreateEvent (NULL, FALSE, FALSE, NULL);
+       tp = data;
+       wsq = NULL;
+       if (!tp->is_io) {
+               wsq = mono_wsq_create ();
+               add_wsq (wsq);
+       }
+
        thread = mono_thread_internal_current ();
        if (tp_start_func)
                tp_start_func (tp_hooks_user_data);
+       data = NULL;
        for (;;) {
                MonoAsyncResult *ar;
+               gboolean is_io_task;
+               int n_naps = 0;
 
+               is_io_task = FALSE;
                ar = (MonoAsyncResult *) data;
                if (ar) {
+                       InterlockedIncrement (&tp->busy_threads);
+#ifndef DISABLE_SOCKETS
+                       is_io_task = (strcmp (((MonoObject *) data)->vtable->klass->name, "AsyncResult"));
+                       if (is_io_task) {
+                               MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
+                               ar = state->ares;
+                               switch (state->operation) {
+                               case AIO_OP_RECEIVE:
+                                       state->total = ICALL_RECV (state);
+                                       break;
+                               case AIO_OP_SEND:
+                                       state->total = ICALL_SEND (state);
+                                       break;
+                               }
+                       }
+#endif
                        /* worker threads invokes methods in different domains,
                         * so we need to set the right domain here */
                        domain = ((MonoObject *)ar)->vtable->domain;
-
                        g_assert (domain);
 
-                       if (domain->state == MONO_APPDOMAIN_UNLOADED || domain->state == MONO_APPDOMAIN_UNLOADING) {
+                       if (mono_domain_is_unloading (domain) || mono_runtime_is_shutting_down ()) {
                                threadpool_jobs_dec ((MonoObject *)ar);
                                data = NULL;
+                               ar = NULL;
+                               InterlockedDecrement (&tp->busy_threads);
                        } else {
                                mono_thread_push_appdomain_ref (domain);
                                if (threadpool_jobs_dec ((MonoObject *)ar)) {
                                        data = NULL;
+                                       ar = NULL;
                                        mono_thread_pop_appdomain_ref ();
+                                       InterlockedDecrement (&tp->busy_threads);
                                        continue;
                                }
 
@@ -1535,7 +1788,11 @@ async_invoke_thread (gpointer data)
 
                                        if (tp_item_begin_func)
                                                tp_item_begin_func (tp_item_user_data);
-                                       mono_async_invoke (ar);
+
+                                       if (!is_io_task && ar->add_time > 0)
+                                               process_idle_times (tp, ar->add_time);
+                                       /*FIXME: Do something with the exception returned? */
+                                       mono_async_invoke (tp, ar);
                                        if (tp_item_end_func)
                                                tp_item_end_func (tp_item_user_data);
                                        /*
@@ -1546,36 +1803,79 @@ async_invoke_thread (gpointer data)
                                        mono_domain_set (mono_get_root_domain (), TRUE);
                                }
                                mono_thread_pop_appdomain_ref ();
-                               InterlockedDecrement (&async_tp.busy_threads);
+                               InterlockedDecrement (&tp->busy_threads);
                                /* If the callee changes the background status, set it back to TRUE */
                                if (!mono_thread_test_state (thread , ThreadState_Background))
                                        ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
                        }
                }
-               data = threadpool_queue_idle_thread (&async_tp, &idle_data);
-               while (!idle_data.die && !data) {
-                       guint32 wr;
-                       wr = WaitForSingleObjectEx (idle_data.wait_handle, idle_data.timeout, TRUE);
-                       if (THREAD_WANTS_A_BREAK (thread))
-                               mono_thread_interruption_checkpoint ();
-               
-                       if (wr != WAIT_TIMEOUT && wr != WAIT_IO_COMPLETION) {
-                               data = idle_data.data;
-                               break; /* We have to exit */
+
+               ar = NULL;
+               data = NULL;
+               must_die = should_i_die (tp);
+               TP_DEBUG ("Trying to get a job");
+               if (!must_die && (tp->is_io || !mono_wsq_local_pop (&data)))
+                       dequeue_or_steal (tp, &data);
+               TP_DEBUG ("Done trying to get a job %p", data);
+
+               n_naps = 0;
+               while (!must_die && !data && n_naps < 4) {
+                       gboolean res;
+
+                       TP_DEBUG ("Waiting");
+                       InterlockedIncrement (&tp->waiting);
+#if defined(__OpenBSD__)
+                       while ((res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
+#else
+                       while ((res = mono_sem_timedwait (&tp->new_job, 2000, TRUE)) == -1) {// && errno == EINTR) {
+#endif
+                               if (mono_runtime_is_shutting_down ())
+                                       break;
+                               if (THREAD_WANTS_A_BREAK (thread))
+                                       mono_thread_interruption_checkpoint ();
+                       }
+                       TP_DEBUG ("Done waiting");
+                       InterlockedDecrement (&tp->waiting);
+                       if (mono_runtime_is_shutting_down ())
+                               break;
+                       must_die = should_i_die (tp);
+                       dequeue_or_steal (tp, &data);
+                       n_naps++;
+               }
+
+               if (!data && tp->is_io && !mono_runtime_is_shutting_down ()) {
+                       mono_wsq_local_pop (&data);
+                       if (data && must_die) {
+                               InterlockedCompareExchange (&tp->destroy_thread, 1, 0);
+                               pulse_on_new_job (tp);
                        }
                }
-               idle_data.data = NULL;
 
                if (!data) {
-                       InterlockedDecrement (&async_tp.nthreads);
-                       CloseHandle (idle_data.wait_handle);
-                       idle_data.wait_handle = NULL;
-                       if (tp_finish_func)
-                               tp_finish_func (tp_hooks_user_data);
-                       return;
+                       gint nt;
+                       gboolean down;
+                       while (1) {
+                               nt = tp->nthreads;
+                               down = mono_runtime_is_shutting_down ();
+                               if (!down && nt <= tp->min_threads)
+                                       break;
+                               if (down || InterlockedCompareExchange (&tp->nthreads, nt - 1, nt) == nt) {
+                                       mono_perfcounter_update_value (tp->pc_nthreads, TRUE, -1);
+                                       TP_DEBUG ("DIE");
+                                       if (!tp->is_io) {
+                                               remove_wsq (wsq);
+                                               while (mono_wsq_local_pop (&data)) {
+                                                       threadpool_jobs_dec (data);
+                                                       data = NULL;
+                                               }
+                                               mono_wsq_destroy (wsq);
+                                       }
+                                       if (tp_finish_func)
+                                               tp_finish_func (tp_hooks_user_data);
+                                       return;
+                               }
+                       }
                }
-               
-               InterlockedIncrement (&async_tp.busy_threads);
        }
 
        g_assert_not_reached ();
@@ -1584,83 +1884,61 @@ async_invoke_thread (gpointer data)
 void
 ves_icall_System_Threading_ThreadPool_GetAvailableThreads (gint *workerThreads, gint *completionPortThreads)
 {
-       gint busy, busy_io;
-
-       MONO_ARCH_SAVE_REGS;
-
-       busy = (gint) InterlockedCompareExchange (&async_tp.busy_threads, 0, -1);
-       busy_io = (gint) InterlockedCompareExchange (&async_io_tp.busy_threads, 0, -1);
-       *workerThreads = async_tp.max_threads - busy;
-       *completionPortThreads = async_io_tp.max_threads - busy_io;
+       *workerThreads = async_tp.max_threads - async_tp.busy_threads;
+       *completionPortThreads = async_io_tp.max_threads - async_io_tp.busy_threads;
 }
 
 void
 ves_icall_System_Threading_ThreadPool_GetMaxThreads (gint *workerThreads, gint *completionPortThreads)
 {
-       MONO_ARCH_SAVE_REGS;
-
-       *workerThreads = (gint) InterlockedCompareExchange (&async_tp.max_threads, 0, -1);
-       *completionPortThreads = (gint) InterlockedCompareExchange (&async_io_tp.max_threads, 0, -1);
+       *workerThreads = async_tp.max_threads;
+       *completionPortThreads = async_io_tp.max_threads;
 }
 
 void
 ves_icall_System_Threading_ThreadPool_GetMinThreads (gint *workerThreads, gint *completionPortThreads)
 {
-       gint workers, workers_io;
-
-       MONO_ARCH_SAVE_REGS;
-
-       workers = (gint) InterlockedCompareExchange (&async_tp.min_threads, 0, -1);
-       workers_io = (gint) InterlockedCompareExchange (&async_io_tp.min_threads, 0, -1);
-
-       *workerThreads = workers;
-       *completionPortThreads = workers_io;
-}
-
-static void
-start_idle_threads (void)
-{
-       threadpool_start_idle_threads (&async_tp);
+       *workerThreads = async_tp.min_threads;
+       *completionPortThreads = async_io_tp.min_threads;
 }
 
 MonoBoolean
 ves_icall_System_Threading_ThreadPool_SetMinThreads (gint workerThreads, gint completionPortThreads)
 {
-       int max_threads;
-       int max_io_threads;
-
-       MONO_ARCH_SAVE_REGS;
+       gint max_threads;
+       gint max_io_threads;
 
-       max_threads = InterlockedCompareExchange (&async_tp.max_threads, -1, -1);
+       max_threads = async_tp.max_threads;
        if (workerThreads <= 0 || workerThreads > max_threads)
                return FALSE;
 
-       max_io_threads = InterlockedCompareExchange (&async_io_tp.max_threads, -1, -1);
+       max_io_threads = async_io_tp.max_threads;
        if (completionPortThreads <= 0 || completionPortThreads > max_io_threads)
                return FALSE;
 
        InterlockedExchange (&async_tp.min_threads, workerThreads);
        InterlockedExchange (&async_io_tp.min_threads, completionPortThreads);
-       mono_thread_create_internal (mono_get_root_domain (), start_idle_threads, NULL, TRUE);
+       if (workerThreads > async_tp.nthreads)
+               mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_tp, TRUE);
+       if (completionPortThreads > async_io_tp.nthreads)
+               mono_thread_create_internal (mono_get_root_domain (), threadpool_start_idle_threads, &async_io_tp, TRUE);
        return TRUE;
 }
 
 MonoBoolean
 ves_icall_System_Threading_ThreadPool_SetMaxThreads (gint workerThreads, gint completionPortThreads)
 {
-       int min_threads;
-       int min_io_threads;
-       int cpu_count;
-
-       MONO_ARCH_SAVE_REGS;
+       gint min_threads;
+       gint min_io_threads;
+       gint cpu_count;
 
        cpu_count = mono_cpu_count ();
-       min_threads = InterlockedCompareExchange (&async_tp.min_threads, -1, -1);
+       min_threads = async_tp.min_threads;
        if (workerThreads < min_threads || workerThreads < cpu_count)
                return FALSE;
 
        /* We don't really have the concept of completion ports. Do we care here? */
-       min_io_threads = InterlockedCompareExchange (&async_io_tp.min_threads, -1, -1);
+       min_io_threads = async_io_tp.min_threads;
        if (completionPortThreads < min_io_threads || completionPortThreads < cpu_count)
                return FALSE;
 
@@ -1704,4 +1982,3 @@ mono_install_threadpool_item_hooks (MonoThreadPoolItemFunc begin_func, MonoThrea
        tp_item_user_data = user_data;
 }
 
-
index edf35561ced26176a2a9ba65ac1938b7a20632a7..003ba6a124f5ea35b5809483a501394d971b4040 100644 (file)
@@ -7,6 +7,7 @@
 /* No managed code here */
 void mono_thread_pool_init (void) MONO_INTERNAL;
 
+void icall_append_job (MonoObject *ar) MONO_INTERNAL;
 MonoAsyncResult *
 mono_thread_pool_add     (MonoObject *target, MonoMethodMessage *msg, 
                          MonoDelegate *async_callback, MonoObject *state) MONO_INTERNAL;
index c00ac865c1cba72c8af50be97c78a23178319dc5..c1a625e394e1b4b250cf1ad27b7210169a809a2d 100644 (file)
@@ -223,4 +223,9 @@ void mono_thread_interruption_checkpoint (void) MONO_INTERNAL;
 void mono_thread_force_interruption_checkpoint (void) MONO_INTERNAL;
 gint32* mono_thread_interruption_request_flag (void) MONO_INTERNAL;
 
+uint32_t mono_alloc_special_static_data (uint32_t static_type, uint32_t size, uint32_t align, uintptr_t *bitmap, int max_set) MONO_INTERNAL;
+void*    mono_get_special_static_data   (uint32_t offset) MONO_INTERNAL;
+
+MonoException* mono_thread_resume_interruption (void) MONO_INTERNAL;
+
 #endif /* _MONO_METADATA_THREADS_TYPES_H_ */
index 94e92076f3f371605feb14334a6d261fc33610e2..7a2bb5c90ba3e175a62c635fb5245e1bdf5e6fc4 100644 (file)
 #include <signal.h>
 #include <string.h>
 
+#if defined(__OpenBSD__)
+#include <pthread.h>
+#include <pthread_np.h>
+#endif
+
 #include <mono/metadata/object.h>
 #include <mono/metadata/domain-internals.h>
 #include <mono/metadata/profiler-private.h>
 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
 #define LIBGC_DEBUG(a)
 
+#define SPIN_TRYLOCK(i) (InterlockedCompareExchange (&(i), 1, 0) == 0)
+#define SPIN_LOCK(i) do { \
+                               if (SPIN_TRYLOCK (i)) \
+                                       break; \
+                       } while (1)
+
+#define SPIN_UNLOCK(i) i = 0
+
 /* Provide this for systems with glib < 2.6 */
 #ifndef G_GSIZE_FORMAT
 #   if GLIB_SIZEOF_LONG == 8
@@ -165,6 +178,7 @@ static guint32 default_stacksize = 0;
 #define default_stacksize_for_thread(thread) ((thread)->stack_size? (thread)->stack_size: default_stacksize)
 
 static void thread_adjust_static_data (MonoInternalThread *thread);
+static void mono_free_static_data (gpointer* static_data, gboolean threadlocal);
 static void mono_init_static_data_info (StaticDataInfo *static_data);
 static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32 size, guint32 align);
 static gboolean mono_thread_resume (MonoInternalThread* thread);
@@ -561,7 +575,7 @@ static void thread_cleanup (MonoInternalThread *thread)
 
        thread->cached_culture_info = NULL;
 
-       mono_gc_free_fixed (thread->static_data);
+       mono_free_static_data (thread->static_data, TRUE);
        thread->static_data = NULL;
 
        /*
@@ -856,7 +870,7 @@ MonoInternalThread* mono_thread_create_internal (MonoDomain *domain, gpointer fu
        }
        if (threads_starting_up == NULL) {
                MONO_GC_REGISTER_ROOT (threads_starting_up);
-               threads_starting_up = mono_g_hash_table_new (NULL, NULL);
+               threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
        }
 
        register_thread_start_argument (thread, start_info);
@@ -931,6 +945,15 @@ mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
 #    elif defined(sun)
        *staddr = NULL;
        pthread_attr_getstacksize (&attr, &stsize);
+#    elif defined(__OpenBSD__)
+       stack_t ss;
+       int rslt;
+
+       rslt = pthread_stackseg_np(pthread_self(), &ss);
+       g_assert (rslt == 0);
+
+       *staddr = (guint8*)((size_t)ss.ss_sp - ss.ss_size);
+       *stsize = ss.ss_size;
 #    else
        *staddr = NULL;
        *stsize = 0;
@@ -938,8 +961,10 @@ mono_thread_get_stack_bounds (guint8 **staddr, size_t *stsize)
 #    endif
 #  endif
 
-#  ifndef sun
+#  if !defined(sun)
+#    if !defined(__OpenBSD__)
        pthread_attr_getstack (&attr, (void**)staddr, stsize);
+#    endif
        if (*staddr)
                g_assert ((current > *staddr) && (current < *staddr + *stsize));
 #  endif
@@ -1133,7 +1158,7 @@ HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
                register_thread_start_argument (this, start_info);
                if (threads_starting_up == NULL) {
                        MONO_GC_REGISTER_ROOT (threads_starting_up);
-                       threads_starting_up = mono_g_hash_table_new (NULL, NULL);
+                       threads_starting_up = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_VALUE_GC);
                }
                mono_g_hash_table_insert (threads_starting_up, this, this);
                mono_threads_unlock (); 
@@ -2321,28 +2346,26 @@ void
 ves_icall_System_Threading_Thread_ResetAbort (void)
 {
        MonoInternalThread *thread = mono_thread_internal_current ();
+       gboolean was_aborting;
 
        ensure_synch_cs_set (thread);
        
        EnterCriticalSection (thread->synch_cs);
-
+       was_aborting = thread->state & ThreadState_AbortRequested;
        thread->state &= ~ThreadState_AbortRequested;
-       
-       if (!thread->abort_exc) {
+       LeaveCriticalSection (thread->synch_cs);
+
+       if (!was_aborting) {
                const char *msg = "Unable to reset abort because no abort was requested";
-               LeaveCriticalSection (thread->synch_cs);
                mono_raise_exception (mono_get_exception_thread_state (msg));
-       } else {
-               thread->abort_exc = NULL;
-               if (thread->abort_state_handle) {
-                       mono_gchandle_free (thread->abort_state_handle);
-                       /* This is actually not necessary - the handle
-                          only counts if the exception is set */
-                       thread->abort_state_handle = 0;
-               }
        }
-       
-       LeaveCriticalSection (thread->synch_cs);
+       thread->abort_exc = NULL;
+       if (thread->abort_state_handle) {
+               mono_gchandle_free (thread->abort_state_handle);
+               /* This is actually not necessary - the handle
+                  only counts if the exception is set */
+               thread->abort_state_handle = 0;
+       }
 }
 
 void
@@ -3178,6 +3201,8 @@ void mono_thread_suspend_all_other_threads (void)
 
                                if (thread == NULL)
                                        continue;
+
+                               ensure_synch_cs_set (thread);
                        
                                EnterCriticalSection (thread->synch_cs);
                                if ((thread->state & ThreadState_Suspended) != 0) {
@@ -3278,9 +3303,9 @@ mono_thread_push_appdomain_ref (MonoDomain *domain)
 
        if (thread) {
                /* printf ("PUSH REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, domain->friendly_name); */
-               mono_threads_lock ();
+               SPIN_LOCK (thread->lock_thread_id);
                thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
-               mono_threads_unlock ();
+               SPIN_UNLOCK (thread->lock_thread_id);
        }
 }
 
@@ -3291,11 +3316,11 @@ mono_thread_pop_appdomain_ref (void)
 
        if (thread) {
                /* printf ("POP REF: %"G_GSIZE_FORMAT" -> %s.\n", (gsize)thread->tid, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
-               mono_threads_lock ();
                /* FIXME: How can the list be empty ? */
+               SPIN_LOCK (thread->lock_thread_id);
                if (thread->appdomain_refs)
                        thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
-               mono_threads_unlock ();
+               SPIN_UNLOCK (thread->lock_thread_id);
        }
 }
 
@@ -3303,9 +3328,9 @@ gboolean
 mono_thread_internal_has_appdomain_ref (MonoInternalThread *thread, MonoDomain *domain)
 {
        gboolean res;
-       mono_threads_lock ();
+       SPIN_LOCK (thread->lock_thread_id);
        res = g_slist_find (thread->appdomain_refs, domain) != NULL;
-       mono_threads_unlock ();
+       SPIN_UNLOCK (thread->lock_thread_id);
        return res;
 }
 
@@ -3465,20 +3490,55 @@ static const int static_data_size [NUM_STATIC_DATA_IDX] = {
 };
 #endif
 
+static uintptr_t* static_reference_bitmaps [NUM_STATIC_DATA_IDX];
+
+#ifdef HAVE_SGEN_GC
+static void
+mark_tls_slots (void *addr, MonoGCMarkFunc mark_func)
+{
+       int i;
+       gpointer *static_data = addr;
+       for (i = 0; i < NUM_STATIC_DATA_IDX; ++i) {
+               int j, numwords;
+               void **ptr;
+               if (!static_data [i])
+                       continue;
+               numwords = 1 + static_data_size [i] / sizeof (gpointer) / (sizeof(uintptr_t) * 8);
+               ptr = static_data [i];
+               for (j = 0; j < numwords; ++j, ptr += sizeof (uintptr_t) * 8) {
+                       uintptr_t bmap = static_reference_bitmaps [i][j];
+                       void ** p = ptr;
+                       while (bmap) {
+                               if ((bmap & 1) && *p) {
+                                       mark_func (p);
+                               }
+                               p++;
+                               bmap >>= 1;
+                       }
+               }
+       }
+}
+#endif
+
 /*
  *  mono_alloc_static_data
  *
  *   Allocate memory blocks for storing threads or context static data
  */
 static void 
-mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
+mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset, gboolean threadlocal)
 {
        guint idx = (offset >> 24) - 1;
        int i;
 
        gpointer* static_data = *static_data_ptr;
        if (!static_data) {
-               static_data = mono_gc_alloc_fixed (static_data_size [0], NULL);
+               static void* tls_desc = NULL;
+#ifdef HAVE_SGEN_GC
+               if (!tls_desc)
+                       tls_desc = mono_gc_make_root_descr_user (mark_tls_slots);
+#endif
+               static_data = mono_gc_alloc_fixed (static_data_size [0], threadlocal?tls_desc:NULL);
                *static_data_ptr = static_data;
                static_data [0] = static_data;
        }
@@ -3486,8 +3546,31 @@ mono_alloc_static_data (gpointer **static_data_ptr, guint32 offset)
        for (i = 1; i <= idx; ++i) {
                if (static_data [i])
                        continue;
+#ifdef HAVE_SGEN_GC
+               static_data [i] = threadlocal?g_malloc0 (static_data_size [i]):mono_gc_alloc_fixed (static_data_size [i], NULL);
+#else
                static_data [i] = mono_gc_alloc_fixed (static_data_size [i], NULL);
+#endif
+       }
+}
+
+static void 
+mono_free_static_data (gpointer* static_data, gboolean threadlocal)
+{
+       int i;
+       for (i = 1; i < NUM_STATIC_DATA_IDX; ++i) {
+               if (!static_data [i])
+                       continue;
+#ifdef HAVE_SGEN_GC
+               if (threadlocal)
+                       g_free (static_data [i]);
+               else
+                       mono_gc_free_fixed (static_data [i]);
+#else
+               mono_gc_free_fixed (static_data [i]);
+#endif
        }
+       mono_gc_free_fixed (static_data);
 }
 
 /*
@@ -3546,7 +3629,7 @@ thread_adjust_static_data (MonoInternalThread *thread)
        if (thread_static_info.offset || thread_static_info.idx > 0) {
                /* get the current allocated size */
                offset = thread_static_info.offset | ((thread_static_info.idx + 1) << 24);
-               mono_alloc_static_data (&(thread->static_data), offset);
+               mono_alloc_static_data (&(thread->static_data), offset, TRUE);
        }
        mono_threads_unlock ();
 }
@@ -3557,7 +3640,7 @@ alloc_thread_static_data_helper (gpointer key, gpointer value, gpointer user)
        MonoInternalThread *thread = value;
        guint32 offset = GPOINTER_TO_UINT (user);
 
-       mono_alloc_static_data (&(thread->static_data), offset);
+       mono_alloc_static_data (&(thread->static_data), offset, TRUE);
 }
 
 static MonoThreadDomainTls*
@@ -3578,6 +3661,39 @@ search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32
        return NULL;
 }
 
+static void
+update_tls_reference_bitmap (guint32 offset, uintptr_t *bitmap, int max_set)
+{
+       int i;
+       int idx = (offset >> 24) - 1;
+       uintptr_t *rb;
+       if (!static_reference_bitmaps [idx])
+               static_reference_bitmaps [idx] = g_new0 (uintptr_t, 1 + static_data_size [idx] / sizeof(gpointer) / (sizeof(uintptr_t) * 8));
+       rb = static_reference_bitmaps [idx];
+       offset &= 0xffffff;
+       offset /= sizeof (gpointer);
+       /* offset is now the bitmap offset */
+       for (i = 0; i < max_set; ++i) {
+               if (bitmap [i / sizeof (uintptr_t)] & (1L << (i & (sizeof (uintptr_t) * 8 -1))))
+                       rb [(offset + i) / (sizeof (uintptr_t) * 8)] |= (1L << ((offset + i) & (sizeof (uintptr_t) * 8 -1)));
+       }
+}
+
+static void
+clear_reference_bitmap (guint32 offset, guint32 size)
+{
+       int idx = (offset >> 24) - 1;
+       uintptr_t *rb;
+       rb = static_reference_bitmaps [idx];
+       offset &= 0xffffff;
+       offset /= sizeof (gpointer);
+       size /= sizeof (gpointer);
+       size += offset;
+       /* offset is now the bitmap offset */
+       for (; offset < size; ++offset)
+               rb [offset / (sizeof (uintptr_t) * 8)] &= ~(1L << (offset & (sizeof (uintptr_t) * 8 -1)));
+}
+
 /*
  * The offset for a special static variable is composed of three parts:
  * a bit that indicates the type of static data (0:thread, 1:context),
@@ -3587,11 +3703,10 @@ search_tls_slot_in_freelist (StaticDataInfo *static_data, guint32 size, guint32
  */
 
 guint32
-mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align)
+mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align, uintptr_t *bitmap, int max_set)
 {
        guint32 offset;
-       if (static_type == SPECIAL_STATIC_THREAD)
-       {
+       if (static_type == SPECIAL_STATIC_THREAD) {
                MonoThreadDomainTls *item;
                mono_threads_lock ();
                item = search_tls_slot_in_freelist (&thread_static_info, size, align);
@@ -3602,13 +3717,12 @@ mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align
                } else {
                        offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
                }
+               update_tls_reference_bitmap (offset, bitmap, max_set);
                /* This can be called during startup */
                if (threads != NULL)
                        mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
                mono_threads_unlock ();
-       }
-       else
-       {
+       } else {
                g_assert (static_type == SPECIAL_STATIC_CONTEXT);
                mono_contexts_lock ();
                offset = mono_alloc_static_data_slot (&context_static_info, size, align);
@@ -3638,7 +3752,7 @@ mono_get_special_static_data (guint32 offset)
                MonoAppContext *context = mono_context_get ();
                if (!context->static_data || !context->static_data [idx]) {
                        mono_contexts_lock ();
-                       mono_alloc_static_data (&(context->static_data), offset);
+                       mono_alloc_static_data (&(context->static_data), offset, FALSE);
                        mono_contexts_unlock ();
                }
                return ((char*) context->static_data [idx]) + (offset & 0xffffff);      
@@ -3679,6 +3793,7 @@ do_free_special (gpointer key, gpointer value, gpointer data)
                MonoThreadDomainTls *item = g_new0 (MonoThreadDomainTls, 1);
                data.offset = offset & 0x7fffffff;
                data.size = size;
+               clear_reference_bitmap (data.offset, data.size);
                if (threads != NULL)
                        mono_g_hash_table_foreach (threads, free_thread_static_data_helper, &data);
                item->offset = offset;
@@ -3913,6 +4028,37 @@ mono_thread_request_interruption (gboolean running_managed)
        }
 }
 
+/*This function should be called by a thread after it has exited all of
+ * its handle blocks at interruption time.*/
+MonoException*
+mono_thread_resume_interruption (void)
+{
+       MonoInternalThread *thread = mono_thread_internal_current ();
+       gboolean still_aborting;
+
+       /* The thread may already be stopping */
+       if (thread == NULL)
+               return NULL;
+
+       ensure_synch_cs_set (thread);
+       EnterCriticalSection (thread->synch_cs);
+       still_aborting = (thread->state & ThreadState_AbortRequested) != 0;
+       LeaveCriticalSection (thread->synch_cs);
+
+       /*This can happen if the protected block called Thread::ResetAbort*/
+       if (!still_aborting)
+               return FALSE;
+
+       if (InterlockedCompareExchange (&thread->interruption_requested, 1, 0) == 1)
+               return NULL;
+       InterlockedIncrement (&thread_interruption_requested);
+
+#ifndef HOST_WIN32
+       wapi_self_interrupt ();
+#endif
+       return mono_thread_execute_interruption (thread);
+}
+
 gboolean mono_thread_interruption_requested ()
 {
        if (thread_interruption_requested) {
index 41e97cef4dbe3cd0ebc7e8f7e613bdff93dd15fd..cd084ae50ce8e517ab39b61f586e3fc2d356c507 100644 (file)
@@ -46,8 +46,6 @@ void     mono_thread_set_manage_callback (MonoThread *thread, MonoThreadManageCa
 
 extern void mono_threads_set_default_stacksize (uint32_t stacksize);
 extern uint32_t mono_threads_get_default_stacksize (void);
-uint32_t  mono_alloc_special_static_data (uint32_t static_type, uint32_t size, uint32_t align);
-void* mono_get_special_static_data   (uint32_t offset);
 
 void mono_threads_request_thread_dump (void);
 
index 6019b3184fb54bdca04d88bcff99582ee28f479e..348792da4553d3234574d289f2f2ad79a78c86d4 100644 (file)
@@ -40,6 +40,8 @@ gboolean mono_verifier_verify_standalone_signature (MonoImage *image, guint32 of
 gboolean mono_verifier_verify_typespec_signature (MonoImage *image, guint32 offset, guint32 token, GSList **error_list) MONO_INTERNAL;
 gboolean mono_verifier_verify_methodspec_signature (MonoImage *image, guint32 offset, GSList **error_list) MONO_INTERNAL;
 gboolean mono_verifier_verify_string_signature (MonoImage *image, guint32 offset, GSList **error_list) MONO_INTERNAL;
+gboolean mono_verifier_verify_cattr_blob (MonoImage *image, guint32 offset, GSList **error_list) MONO_INTERNAL;
+gboolean mono_verifier_verify_cattr_content (MonoImage *image, MonoMethod *ctor, const guchar *data, guint32 size, GSList **error_list) MONO_INTERNAL;
 gboolean mono_verifier_is_sig_compatible (MonoImage *image, MonoMethod *method, MonoMethodSignature *signature) MONO_INTERNAL;
 
 G_END_DECLS
index 92c6c632f37d3dad201cbc851374248e6ccf6c51..b01b272e45004924c686d4eef53fc62b06cae126 100644 (file)
@@ -24,6 +24,7 @@
 #include <mono/metadata/security-core-clr.h>
 #include <mono/metadata/tokentype.h>
 #include <mono/metadata/mono-basic-block.h>
+#include <mono/utils/mono-counters.h>
 #include <string.h>
 #include <signal.h>
 #include <ctype.h>
@@ -162,7 +163,7 @@ typedef struct {
 
 typedef struct {
        ILStackDesc *stack;
-       guint16 size;
+       guint16 size, max_size;
        guint16 flags;
 } ILCodeDesc;
 
@@ -295,6 +296,51 @@ enum {
 };
 //////////////////////////////////////////////////////////////////
 
+#ifdef ENABLE_VERIFIER_STATS
+
+#define MEM_ALLOC(amt) do { allocated_memory += (amt); working_set += (amt); } while (0)
+#define MEM_FREE(amt) do { working_set -= (amt); } while (0)
+
+static int allocated_memory;
+static int working_set;
+static int max_allocated_memory;
+static int max_working_set;
+static int total_allocated_memory;
+
+static void
+finish_collect_stats (void)
+{
+       max_allocated_memory = MAX (max_allocated_memory, allocated_memory);
+       max_working_set = MAX (max_working_set, working_set);
+       total_allocated_memory += allocated_memory;
+       allocated_memory = working_set = 0;
+}
+
+static void
+init_verifier_stats (void)
+{
+       static gboolean inited;
+       if (!inited) {
+               inited = TRUE;
+               mono_counters_register ("Maximum memory allocated during verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &max_allocated_memory);
+               mono_counters_register ("Maximum memory used during verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &max_working_set);
+               mono_counters_register ("Total memory allocated for verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &total_allocated_memory);
+       }
+}
+
+#else
+
+#define MEM_ALLOC(amt) do {} while (0)
+#define MEM_FREE(amt) do { } while (0)
+
+#define finish_collect_stats()
+#define init_verifier_stats()
+
+#endif
+
+
+//////////////////////////////////////////////////////////////////
+
 
 /*Token validation macros and functions */
 #define IS_MEMBER_REF(token) (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF)
@@ -324,6 +370,8 @@ static MonoType *
 mono_type_create_fnptr_from_mono_method (VerifyContext *ctx, MonoMethod *method)
 {
        MonoType *res = g_new0 (MonoType, 1);
+       MEM_ALLOC (sizeof (MonoType));
+
        //FIXME use mono_method_get_signature_full
        res->data.method = mono_method_signature (method);
        res->type = MONO_TYPE_FNPTR;
@@ -938,18 +986,30 @@ stack_slot_stack_type_full_name (ILStackDesc *value)
 {
        GString *str = g_string_new ("");
        char *result;
+       gboolean has_pred = FALSE, first = TRUE;
 
        if ((value->stype & TYPE_MASK) != value->stype) {
-               gboolean first = TRUE;
                g_string_append(str, "[");
                APPEND_WITH_PREDICATE (stack_slot_is_this_pointer, "this");
                APPEND_WITH_PREDICATE (stack_slot_is_boxed_value, "boxed");
                APPEND_WITH_PREDICATE (stack_slot_is_null_literal, "null");
                APPEND_WITH_PREDICATE (stack_slot_is_managed_mutability_pointer, "cmmp");
                APPEND_WITH_PREDICATE (stack_slot_is_managed_pointer, "mp");
-               g_string_append(str, "] ");
+               has_pred = TRUE;
+       }
+
+       if (mono_type_is_generic_argument (value->type) && !stack_slot_is_boxed_value (value)) {
+               if (!has_pred)
+                       g_string_append(str, "[");
+               if (!first)
+                       g_string_append (str, ", ");
+               g_string_append (str, "unboxed");
+               has_pred = TRUE;
        }
 
+       if (has_pred)
+               g_string_append(str, "] ");
+
        g_string_append (str, stack_slot_get_name (value));
        result = str->str;
        g_string_free (str, FALSE);
@@ -998,625 +1058,6 @@ mono_free_verify_list (GSList *list)
                (list) = g_slist_prepend ((list), vinfo);       \
        } while (0)
 
-static const char
-valid_cultures[][9] = {
-       "ar-SA", "ar-IQ", "ar-EG", "ar-LY",
-       "ar-DZ", "ar-MA", "ar-TN", "ar-OM",
-       "ar-YE", "ar-SY", "ar-JO", "ar-LB",
-       "ar-KW", "ar-AE", "ar-BH", "ar-QA",
-       "bg-BG", "ca-ES", "zh-TW", "zh-CN",
-       "zh-HK", "zh-SG", "zh-MO", "cs-CZ",
-       "da-DK", "de-DE", "de-CH", "de-AT",
-       "de-LU", "de-LI", "el-GR", "en-US",
-       "en-GB", "en-AU", "en-CA", "en-NZ",
-       "en-IE", "en-ZA", "en-JM", "en-CB",
-       "en-BZ", "en-TT", "en-ZW", "en-PH",
-       "es-ES-Ts", "es-MX", "es-ES-Is", "es-GT",
-       "es-CR", "es-PA", "es-DO", "es-VE",
-       "es-CO", "es-PE", "es-AR", "es-EC",
-       "es-CL", "es-UY", "es-PY", "es-BO",
-       "es-SV", "es-HN", "es-NI", "es-PR",
-       "Fi-FI", "fr-FR", "fr-BE", "fr-CA",
-       "Fr-CH", "fr-LU", "fr-MC", "he-IL",
-       "hu-HU", "is-IS", "it-IT", "it-CH",
-       "Ja-JP", "ko-KR", "nl-NL", "nl-BE",
-       "nb-NO", "nn-NO", "pl-PL", "pt-BR",
-       "pt-PT", "ro-RO", "ru-RU", "hr-HR",
-       "Lt-sr-SP", "Cy-sr-SP", "sk-SK", "sq-AL",
-       "sv-SE", "sv-FI", "th-TH", "tr-TR",
-       "ur-PK", "id-ID", "uk-UA", "be-BY",
-       "sl-SI", "et-EE", "lv-LV", "lt-LT",
-       "fa-IR", "vi-VN", "hy-AM", "Lt-az-AZ",
-       "Cy-az-AZ",
-       "eu-ES", "mk-MK", "af-ZA",
-       "ka-GE", "fo-FO", "hi-IN", "ms-MY",
-       "ms-BN", "kk-KZ", "ky-KZ", "sw-KE",
-       "Lt-uz-UZ", "Cy-uz-UZ", "tt-TA", "pa-IN",
-       "gu-IN", "ta-IN", "te-IN", "kn-IN",
-       "mr-IN", "sa-IN", "mn-MN", "gl-ES",
-       "kok-IN", "syr-SY", "div-MV"
-};
-
-static int
-is_valid_culture (const char *cname)
-{
-       int i;
-       int found;
-
-       found = *cname == 0;
-       for (i = 0; i < G_N_ELEMENTS (valid_cultures); ++i) {
-               if (g_ascii_strcasecmp (valid_cultures [i], cname)) {
-                       found = 1;
-                       break;
-               }
-       }
-       return found;
-}
-
-static int
-is_valid_assembly_flags (guint32 flags) {
-       /* Metadata: 22.1.2 */
-       flags &= ~(0x8000 | 0x4000); /* ignore reserved bits 0x0030? */
-       return ((flags == 1) || (flags == 0));
-}
-
-static int
-is_valid_blob (MonoImage *image, guint32 blob_index, int notnull)
-{
-       guint32 size;
-       const char *p, *blob_end;
-
-       if (blob_index >= image->heap_blob.size)
-               return 0;
-       p = mono_metadata_blob_heap (image, blob_index);
-       size = mono_metadata_decode_blob_size (p, &blob_end);
-       if (blob_index + size + (blob_end-p) > image->heap_blob.size)
-               return 0;
-       if (notnull && !size)
-               return 0;
-       return 1;
-}
-
-static const char*
-is_valid_string (MonoImage *image, guint32 str_index, int notnull)
-{
-       const char *p, *blob_end, *res;
-
-       if (str_index >= image->heap_strings.size)
-               return NULL;
-       res = p = mono_metadata_string_heap (image, str_index);
-       blob_end = mono_metadata_string_heap (image, image->heap_strings.size - 1);
-       if (notnull && !*p)
-               return 0;
-       /* 
-        * FIXME: should check it's a valid utf8 string, too.
-        */
-       while (p <= blob_end) {
-               if (!*p)
-                       return res;
-               ++p;
-       }
-       return *p? NULL: res;
-}
-
-static int
-is_valid_cls_ident (const char *p)
-{
-       /*
-        * FIXME: we need the full unicode glib support for this.
-        * Check: http://www.unicode.org/unicode/reports/tr15/Identifier.java
-        * We do the lame thing for now.
-        */
-       if (!isalpha (*p))
-               return 0;
-       ++p;
-       while (*p) {
-               if (!isalnum (*p) && *p != '_')
-                       return 0;
-               ++p;
-       }
-       return 1;
-}
-
-static int
-is_valid_filename (const char *p)
-{
-       if (!*p)
-               return 0;
-       return strpbrk (p, "\\//:")? 0: 1;
-}
-
-static GSList*
-verify_assembly_table (MonoImage *image, GSList *list, int level)
-{
-       MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLY];
-       guint32 cols [MONO_ASSEMBLY_SIZE];
-       const char *p;
-
-       if (level & MONO_VERIFY_ERROR) {
-               if (t->rows > 1)
-                       ADD_ERROR (list, g_strdup ("Assembly table may only have 0 or 1 rows"));
-               mono_metadata_decode_row (t, 0, cols, MONO_ASSEMBLY_SIZE);
-
-               switch (cols [MONO_ASSEMBLY_HASH_ALG]) {
-               case ASSEMBLY_HASH_NONE:
-               case ASSEMBLY_HASH_MD5:
-               case ASSEMBLY_HASH_SHA1:
-                       break;
-               default:
-                       ADD_ERROR (list, g_strdup_printf ("Hash algorithm 0x%x unknown", cols [MONO_ASSEMBLY_HASH_ALG]));
-               }
-
-               if (!is_valid_assembly_flags (cols [MONO_ASSEMBLY_FLAGS]))
-                       ADD_ERROR (list, g_strdup_printf ("Invalid flags in assembly: 0x%x", cols [MONO_ASSEMBLY_FLAGS]));
-
-               if (!is_valid_blob (image, cols [MONO_ASSEMBLY_PUBLIC_KEY], FALSE))
-                       ADD_ERROR (list, g_strdup ("Assembly public key is an invalid index"));
-
-               if (!(p = is_valid_string (image, cols [MONO_ASSEMBLY_NAME], TRUE))) {
-                       ADD_ERROR (list, g_strdup ("Assembly name is invalid"));
-               } else {
-                       if (strpbrk (p, ":\\/."))
-                               ADD_ERROR (list, g_strdup_printf ("Assembly name `%s' contains invalid chars", p));
-               }
-
-               if (!(p = is_valid_string (image, cols [MONO_ASSEMBLY_CULTURE], FALSE))) {
-                       ADD_ERROR (list, g_strdup ("Assembly culture is an invalid index"));
-               } else {
-                       if (!is_valid_culture (p))
-                               ADD_ERROR (list, g_strdup_printf ("Assembly culture `%s' is invalid", p));
-               }
-       }
-       return list;
-}
-
-static GSList*
-verify_assemblyref_table (MonoImage *image, GSList *list, int level)
-{
-       MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
-       guint32 cols [MONO_ASSEMBLYREF_SIZE];
-       const char *p;
-       int i;
-
-       if (level & MONO_VERIFY_ERROR) {
-               for (i = 0; i < t->rows; ++i) {
-                       mono_metadata_decode_row (t, i, cols, MONO_ASSEMBLYREF_SIZE);
-                       if (!is_valid_assembly_flags (cols [MONO_ASSEMBLYREF_FLAGS]))
-                               ADD_ERROR (list, g_strdup_printf ("Invalid flags in assemblyref row %d: 0x%x", i + 1, cols [MONO_ASSEMBLY_FLAGS]));
-
-                       if (!is_valid_blob (image, cols [MONO_ASSEMBLYREF_PUBLIC_KEY], FALSE))
-                               ADD_ERROR (list, g_strdup_printf ("AssemblyRef public key in row %d is an invalid index", i + 1));
-
-                       if (!(p = is_valid_string (image, cols [MONO_ASSEMBLYREF_CULTURE], FALSE))) {
-                               ADD_ERROR (list, g_strdup_printf ("AssemblyRef culture in row %d is invalid", i + 1));
-                       } else {
-                               if (!is_valid_culture (p))
-                                       ADD_ERROR (list, g_strdup_printf ("AssemblyRef culture `%s' in row %d is invalid", p, i + 1));
-                       }
-
-                       if (cols [MONO_ASSEMBLYREF_HASH_VALUE] && !is_valid_blob (image, cols [MONO_ASSEMBLYREF_HASH_VALUE], TRUE))
-                               ADD_ERROR (list, g_strdup_printf ("AssemblyRef hash value in row %d is invalid or not null and empty", i + 1));
-               }
-       }
-       if (level & MONO_VERIFY_WARNING) {
-               /* check for duplicated rows */
-               for (i = 0; i < t->rows; ++i) {
-               }
-       }
-       return list;
-}
-
-static GSList*
-verify_class_layout_table (MonoImage *image, GSList *list, int level)
-{
-       MonoTableInfo *t = &image->tables [MONO_TABLE_CLASSLAYOUT];
-       MonoTableInfo *tdef = &image->tables [MONO_TABLE_TYPEDEF];
-       guint32 cols [MONO_CLASS_LAYOUT_SIZE];
-       guint32 value, i;
-
-       if (level & MONO_VERIFY_ERROR) {
-               for (i = 0; i < t->rows; ++i) {
-                       mono_metadata_decode_row (t, i, cols, MONO_CLASS_LAYOUT_SIZE);
-
-                       if (cols [MONO_CLASS_LAYOUT_PARENT] > tdef->rows || !cols [MONO_CLASS_LAYOUT_PARENT]) {
-                               ADD_ERROR (list, g_strdup_printf ("Parent in class layout is invalid in row %d", i + 1));
-                       } else {
-                               value = mono_metadata_decode_row_col (tdef, cols [MONO_CLASS_LAYOUT_PARENT] - 1, MONO_TYPEDEF_FLAGS);
-                               if (value & TYPE_ATTRIBUTE_INTERFACE)
-                                       ADD_ERROR (list, g_strdup_printf ("Parent in class layout row %d is an interface", i + 1));
-                               if (value & TYPE_ATTRIBUTE_AUTO_LAYOUT)
-                                       ADD_ERROR (list, g_strdup_printf ("Parent in class layout row %d is AutoLayout", i + 1));
-                               if (value & TYPE_ATTRIBUTE_SEQUENTIAL_LAYOUT) {
-                                       switch (cols [MONO_CLASS_LAYOUT_PACKING_SIZE]) {
-                                       case 0: case 1: case 2: case 4: case 8: case 16:
-                                       case 32: case 64: case 128: break;
-                                       default:
-                                               ADD_ERROR (list, g_strdup_printf ("Packing size %d in class layout row %d is invalid", cols [MONO_CLASS_LAYOUT_PACKING_SIZE], i + 1));
-                                       }
-                               } else if (value & TYPE_ATTRIBUTE_EXPLICIT_LAYOUT) {
-                                       /*
-                                        * FIXME: LAMESPEC: it claims it must be 0 (it's 1, instead).
-                                       if (cols [MONO_CLASS_LAYOUT_PACKING_SIZE])
-                                               ADD_ERROR (list, g_strdup_printf ("Packing size %d in class layout row %d is invalid with explicit layout", cols [MONO_CLASS_LAYOUT_PACKING_SIZE], i + 1));
-                                       */
-                               }
-                               /*
-                                * FIXME: we need to check that if class size != 0, 
-                                * it needs to be greater than the class calculated size.
-                                * If parent is a valuetype it also needs to be smaller than
-                                * 1 MByte (0x100000 bytes).
-                                * To do both these checks we need to load the referenced 
-                                * assemblies, though (the spec claims we didn't have to, bah).
-                                */
-                               /* 
-                                * We need to check that the parent types have the same layout 
-                                * type as well.
-                                */
-                       }
-               }
-       }
-
-       return list;
-}
-
-static GSList*
-verify_constant_table (MonoImage *image, GSList *list, int level)
-{
-       MonoTableInfo *t = &image->tables [MONO_TABLE_CONSTANT];
-       guint32 cols [MONO_CONSTANT_SIZE];
-       guint32 value, i;
-       GHashTable *dups = g_hash_table_new (NULL, NULL);
-
-       for (i = 0; i < t->rows; ++i) {
-               mono_metadata_decode_row (t, i, cols, MONO_CONSTANT_SIZE);
-
-               if (level & MONO_VERIFY_ERROR)
-                       if (g_hash_table_lookup (dups, GUINT_TO_POINTER (cols [MONO_CONSTANT_PARENT])))
-                               ADD_ERROR (list, g_strdup_printf ("Parent 0x%08x is duplicated in Constant row %d", cols [MONO_CONSTANT_PARENT], i + 1));
-               g_hash_table_insert (dups, GUINT_TO_POINTER (cols [MONO_CONSTANT_PARENT]),
-                               GUINT_TO_POINTER (cols [MONO_CONSTANT_PARENT]));
-
-               switch (cols [MONO_CONSTANT_TYPE]) {
-               case MONO_TYPE_U1: /* LAMESPEC: it says I1...*/
-               case MONO_TYPE_U2:
-               case MONO_TYPE_U4:
-               case MONO_TYPE_U8:
-                       if (level & MONO_VERIFY_CLS)
-                               ADD_WARN (list, MONO_VERIFY_CLS, g_strdup_printf ("Type 0x%x not CLS compliant in Constant row %d", cols [MONO_CONSTANT_TYPE], i + 1));
-               case MONO_TYPE_BOOLEAN:
-               case MONO_TYPE_CHAR:
-               case MONO_TYPE_I1:
-               case MONO_TYPE_I2:
-               case MONO_TYPE_I4:
-               case MONO_TYPE_I8:
-               case MONO_TYPE_R4:
-               case MONO_TYPE_R8:
-               case MONO_TYPE_STRING:
-               case MONO_TYPE_CLASS:
-                       break;
-               default:
-                       if (level & MONO_VERIFY_ERROR)
-                               ADD_ERROR (list, g_strdup_printf ("Type 0x%x is invalid in Constant row %d", cols [MONO_CONSTANT_TYPE], i + 1));
-               }
-               if (level & MONO_VERIFY_ERROR) {
-                       value = cols [MONO_CONSTANT_PARENT] >> MONO_HASCONSTANT_BITS;
-                       switch (cols [MONO_CONSTANT_PARENT] & MONO_HASCONSTANT_MASK) {
-                       case MONO_HASCONSTANT_FIEDDEF:
-                               if (value > image->tables [MONO_TABLE_FIELD].rows)
-                                       ADD_ERROR (list, g_strdup_printf ("Parent (field) is invalid in Constant row %d", i + 1));
-                               break;
-                       case MONO_HASCONSTANT_PARAM:
-                               if (value > image->tables [MONO_TABLE_PARAM].rows)
-                                       ADD_ERROR (list, g_strdup_printf ("Parent (param) is invalid in Constant row %d", i + 1));
-                               break;
-                       case MONO_HASCONSTANT_PROPERTY:
-                               if (value > image->tables [MONO_TABLE_PROPERTY].rows)
-                                       ADD_ERROR (list, g_strdup_printf ("Parent (property) is invalid in Constant row %d", i + 1));
-                               break;
-                       default:
-                               ADD_ERROR (list, g_strdup_printf ("Parent is invalid in Constant row %d", i + 1));
-                               break;
-                       }
-               }
-               if (level & MONO_VERIFY_CLS) {
-                       /* 
-                        * FIXME: verify types is consistent with the enum type
-                        * is parent is an enum.
-                        */
-               }
-       }
-       g_hash_table_destroy (dups);
-       return list;
-}
-
-static GSList*
-verify_event_map_table (MonoImage *image, GSList *list, int level)
-{
-       MonoTableInfo *t = &image->tables [MONO_TABLE_EVENTMAP];
-       guint32 cols [MONO_EVENT_MAP_SIZE];
-       guint32 i, last_event;
-       GHashTable *dups = g_hash_table_new (NULL, NULL);
-
-       last_event = 0;
-
-       for (i = 0; i < t->rows; ++i) {
-               mono_metadata_decode_row (t, i, cols, MONO_EVENT_MAP_SIZE);
-               if (level & MONO_VERIFY_ERROR)
-                       if (g_hash_table_lookup (dups, GUINT_TO_POINTER (cols [MONO_EVENT_MAP_PARENT])))
-                               ADD_ERROR (list, g_strdup_printf ("Parent 0x%08x is duplicated in Event Map row %d", cols [MONO_EVENT_MAP_PARENT], i + 1));
-               g_hash_table_insert (dups, GUINT_TO_POINTER (cols [MONO_EVENT_MAP_PARENT]),
-                               GUINT_TO_POINTER (cols [MONO_EVENT_MAP_PARENT]));
-               if (level & MONO_VERIFY_ERROR) {
-                       if (cols [MONO_EVENT_MAP_PARENT] > image->tables [MONO_TABLE_TYPEDEF].rows)
-                               ADD_ERROR (list, g_strdup_printf ("Parent 0x%08x is invalid in Event Map row %d", cols [MONO_EVENT_MAP_PARENT], i + 1));
-                       if (cols [MONO_EVENT_MAP_EVENTLIST] > image->tables [MONO_TABLE_EVENT].rows)
-                               ADD_ERROR (list, g_strdup_printf ("EventList 0x%08x is invalid in Event Map row %d", cols [MONO_EVENT_MAP_EVENTLIST], i + 1));
-
-                       if (cols [MONO_EVENT_MAP_EVENTLIST] <= last_event)
-                               ADD_ERROR (list, g_strdup_printf ("EventList overlap in Event Map row %d", i + 1));
-                       last_event = cols [MONO_EVENT_MAP_EVENTLIST];
-               }
-       }
-
-       g_hash_table_destroy (dups);
-       return list;
-}
-
-static GSList*
-verify_event_table (MonoImage *image, GSList *list, int level)
-{
-       MonoTableInfo *t = &image->tables [MONO_TABLE_EVENT];
-       guint32 cols [MONO_EVENT_SIZE];
-       const char *p;
-       guint32 value, i;
-
-       for (i = 0; i < t->rows; ++i) {
-               mono_metadata_decode_row (t, i, cols, MONO_EVENT_SIZE);
-
-               if (cols [MONO_EVENT_FLAGS] & ~(EVENT_SPECIALNAME|EVENT_RTSPECIALNAME)) {
-                       if (level & MONO_VERIFY_ERROR)
-                               ADD_ERROR (list, g_strdup_printf ("Flags 0x%04x invalid in Event row %d", cols [MONO_EVENT_FLAGS], i + 1));
-               }
-               if (!(p = is_valid_string (image, cols [MONO_EVENT_NAME], TRUE))) {
-                       if (level & MONO_VERIFY_ERROR)
-                               ADD_ERROR (list, g_strdup_printf ("Invalid name in Event row %d", i + 1));
-               } else {
-                       if (level & MONO_VERIFY_CLS) {
-                               if (!is_valid_cls_ident (p))
-                                       ADD_WARN (list, MONO_VERIFY_CLS, g_strdup_printf ("Invalid CLS name '%s` in Event row %d", p, i + 1));
-                       }
-               }
-
-               if (level & MONO_VERIFY_ERROR && cols [MONO_EVENT_TYPE]) {
-                       value = cols [MONO_EVENT_TYPE] >> MONO_TYPEDEFORREF_BITS;
-                       switch (cols [MONO_EVENT_TYPE] & MONO_TYPEDEFORREF_MASK) {
-                       case MONO_TYPEDEFORREF_TYPEDEF:
-                               if (!value || value > image->tables [MONO_TABLE_TYPEDEF].rows)
-                                       ADD_ERROR (list, g_strdup_printf ("Type invalid in Event row %d", i + 1));
-                               break;
-                       case MONO_TYPEDEFORREF_TYPEREF:
-                               if (!value || value > image->tables [MONO_TABLE_TYPEREF].rows)
-                                       ADD_ERROR (list, g_strdup_printf ("Type invalid in Event row %d", i + 1));
-                               break;
-                       case MONO_TYPEDEFORREF_TYPESPEC:
-                               if (!value || value > image->tables [MONO_TABLE_TYPESPEC].rows)
-                                       ADD_ERROR (list, g_strdup_printf ("Type invalid in Event row %d", i + 1));
-                               break;
-                       default:
-                               ADD_ERROR (list, g_strdup_printf ("Type invalid in Event row %d", i + 1));
-                       }
-               }
-               /*
-                * FIXME: check that there is 1 add and remove row in methodsemantics
-                * and 0 or 1 raise and 0 or more other (maybe it's better to check for 
-                * these while checking methodsemantics).
-                * check for duplicated names for the same type [ERROR]
-                * check for CLS duplicate names for the same type [CLS]
-                */
-       }
-       return list;
-}
-
-static GSList*
-verify_field_table (MonoImage *image, GSList *list, int level)
-{
-       MonoTableInfo *t = &image->tables [MONO_TABLE_FIELD];
-       guint32 cols [MONO_FIELD_SIZE];
-       const char *p;
-       guint32 i, flags;
-
-       for (i = 0; i < t->rows; ++i) {
-               mono_metadata_decode_row (t, i, cols, MONO_FIELD_SIZE);
-               /*
-                * Check this field has only one owner and that the owner is not 
-                * an interface (done in verify_typedef_table() )
-                */
-               flags = cols [MONO_FIELD_FLAGS];
-               switch (flags & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK) {
-               case FIELD_ATTRIBUTE_COMPILER_CONTROLLED:
-               case FIELD_ATTRIBUTE_PRIVATE:
-               case FIELD_ATTRIBUTE_FAM_AND_ASSEM:
-               case FIELD_ATTRIBUTE_ASSEMBLY:
-               case FIELD_ATTRIBUTE_FAMILY:
-               case FIELD_ATTRIBUTE_FAM_OR_ASSEM:
-               case FIELD_ATTRIBUTE_PUBLIC:
-                       break;
-               default:
-                       if (level & MONO_VERIFY_ERROR)
-                               ADD_ERROR (list, g_strdup_printf ("Invalid access mask in Field row %d", i + 1));
-                       break;
-               }
-               if (level & MONO_VERIFY_ERROR) {
-                       if ((flags & FIELD_ATTRIBUTE_LITERAL) && (flags & FIELD_ATTRIBUTE_INIT_ONLY))
-                               ADD_ERROR (list, g_strdup_printf ("Literal and InitOnly cannot be both set in Field row %d", i + 1));
-                       if ((flags & FIELD_ATTRIBUTE_LITERAL) && !(flags & FIELD_ATTRIBUTE_STATIC))
-                               ADD_ERROR (list, g_strdup_printf ("Literal needs also Static set in Field row %d", i + 1));
-                       if ((flags & FIELD_ATTRIBUTE_RT_SPECIAL_NAME) && !(flags & FIELD_ATTRIBUTE_SPECIAL_NAME))
-                               ADD_ERROR (list, g_strdup_printf ("RTSpecialName needs also SpecialName set in Field row %d", i + 1));
-                       /*
-                        * FIXME: check there is only one owner in the respective table.
-                        * if (flags & FIELD_ATTRIBUTE_HAS_FIELD_MARSHAL)
-                        * if (flags & FIELD_ATTRIBUTE_HAS_DEFAULT)
-                        * if (flags & FIELD_ATTRIBUTE_HAS_FIELD_RVA)
-                        */
-               }
-               if (!(p = is_valid_string (image, cols [MONO_FIELD_NAME], TRUE))) {
-                       if (level & MONO_VERIFY_ERROR)
-                               ADD_ERROR (list, g_strdup_printf ("Invalid name in Field row %d", i + 1));
-               } else {
-                       if (level & MONO_VERIFY_CLS) {
-                               if (!is_valid_cls_ident (p))
-                                       ADD_WARN (list, MONO_VERIFY_CLS, g_strdup_printf ("Invalid CLS name '%s` in Field row %d", p, i + 1));
-                       }
-               }
-               /*
-                * check signature.
-                * if owner is module needs to be static, access mask needs to be compilercontrolled,
-                * public or private (not allowed in cls mode).
-                * if owner is an enum ...
-                */
-
-
-       }
-       return list;
-}
-
-static GSList*
-verify_file_table (MonoImage *image, GSList *list, int level)
-{
-       MonoTableInfo *t = &image->tables [MONO_TABLE_FILE];
-       guint32 cols [MONO_FILE_SIZE];
-       const char *p;
-       guint32 i;
-       GHashTable *dups = g_hash_table_new (g_str_hash, g_str_equal);
-
-       for (i = 0; i < t->rows; ++i) {
-               mono_metadata_decode_row (t, i, cols, MONO_FILE_SIZE);
-               if (level & MONO_VERIFY_ERROR) {
-                       if (cols [MONO_FILE_FLAGS] != FILE_CONTAINS_METADATA && cols [MONO_FILE_FLAGS] != FILE_CONTAINS_NO_METADATA)
-                               ADD_ERROR (list, g_strdup_printf ("Invalid flags in File row %d", i + 1));
-                       if (!is_valid_blob (image, cols [MONO_FILE_HASH_VALUE], TRUE))
-                               ADD_ERROR (list, g_strdup_printf ("File hash value in row %d is invalid or not null and empty", i + 1));
-               }
-               if (!(p = is_valid_string (image, cols [MONO_FILE_NAME], TRUE))) {
-                       if (level & MONO_VERIFY_ERROR)
-                               ADD_ERROR (list, g_strdup_printf ("Invalid name in File row %d", i + 1));
-               } else {
-                       if (level & MONO_VERIFY_ERROR) {
-                               if (!is_valid_filename (p))
-                                       ADD_ERROR (list, g_strdup_printf ("Invalid name '%s` in File row %d", p, i + 1));
-                               else if (g_hash_table_lookup (dups, p)) {
-                                       ADD_ERROR (list, g_strdup_printf ("Duplicate name '%s` in File row %d", p, i + 1));
-                               }
-                               g_hash_table_insert (dups, (gpointer)p, (gpointer)p);
-                       }
-               }
-               /*
-                * FIXME: I don't understand what this means:
-                * If this module contains a row in the Assembly table (that is, if this module "holds the manifest") 
-                * then there shall not be any row in the File table for this module - i.e., no self-reference  [ERROR]
-                */
-
-       }
-       if (level & MONO_VERIFY_WARNING) {
-               if (!t->rows && image->tables [MONO_TABLE_EXPORTEDTYPE].rows)
-                       ADD_WARN (list, MONO_VERIFY_WARNING, g_strdup ("ExportedType table should be empty if File table is empty"));
-       }
-       g_hash_table_destroy (dups);
-       return list;
-}
-
-static GSList*
-verify_moduleref_table (MonoImage *image, GSList *list, int level)
-{
-       MonoTableInfo *t = &image->tables [MONO_TABLE_MODULEREF];
-       MonoTableInfo *tfile = &image->tables [MONO_TABLE_FILE];
-       guint32 cols [MONO_MODULEREF_SIZE];
-       const char *p, *pf;
-       guint32 found, i, j, value;
-       GHashTable *dups = g_hash_table_new (g_str_hash, g_str_equal);
-
-       for (i = 0; i < t->rows; ++i) {
-               mono_metadata_decode_row (t, i, cols, MONO_MODULEREF_SIZE);
-               if (!(p = is_valid_string (image, cols [MONO_MODULEREF_NAME], TRUE))) {
-                       if (level & MONO_VERIFY_ERROR)
-                               ADD_ERROR (list, g_strdup_printf ("Invalid name in ModuleRef row %d", i + 1));
-               } else {
-                       if (level & MONO_VERIFY_ERROR) {
-                               if (!is_valid_filename (p))
-                                       ADD_ERROR (list, g_strdup_printf ("Invalid name '%s` in ModuleRef row %d", p, i + 1));
-                               else if (g_hash_table_lookup (dups, p)) {
-                                       ADD_WARN (list, MONO_VERIFY_WARNING, g_strdup_printf ("Duplicate name '%s` in ModuleRef row %d", p, i + 1));
-                                       g_hash_table_insert (dups, (gpointer)p, (gpointer)p);
-                                       found = 0;
-                                       for (j = 0; j < tfile->rows; ++j) {
-                                               value = mono_metadata_decode_row_col (tfile, j, MONO_FILE_NAME);
-                                               if ((pf = is_valid_string (image, value, TRUE)))
-                                                       if (strcmp (p, pf) == 0) {
-                                                               found = 1;
-                                                               break;
-                                                       }
-                                       }
-                                       if (!found)
-                                               ADD_ERROR (list, g_strdup_printf ("Name '%s` in ModuleRef row %d doesn't have a match in File table", p, i + 1));
-                               }
-                       }
-               }
-       }
-       g_hash_table_destroy (dups);
-       return list;
-}
-
-static GSList*
-verify_standalonesig_table (MonoImage *image, GSList *list, int level)
-{
-       MonoTableInfo *t = &image->tables [MONO_TABLE_STANDALONESIG];
-       guint32 cols [MONO_STAND_ALONE_SIGNATURE_SIZE];
-       const char *p;
-       guint32 i;
-
-       for (i = 0; i < t->rows; ++i) {
-               mono_metadata_decode_row (t, i, cols, MONO_STAND_ALONE_SIGNATURE_SIZE);
-               if (level & MONO_VERIFY_ERROR) {
-                       if (!is_valid_blob (image, cols [MONO_STAND_ALONE_SIGNATURE], TRUE)) {
-                               ADD_ERROR (list, g_strdup_printf ("Signature is invalid in StandAloneSig row %d", i + 1));
-                       } else {
-                               p = mono_metadata_blob_heap (image, cols [MONO_STAND_ALONE_SIGNATURE]);
-                               /* FIXME: check it's a valid locals or method sig.*/
-                       }
-               }
-       }
-       return list;
-}
-
-GSList*
-mono_image_verify_tables (MonoImage *image, int level)
-{
-       GSList *error_list = NULL;
-
-       error_list = verify_assembly_table (image, error_list, level);
-       /* 
-        * AssemblyOS, AssemblyProcessor, AssemblyRefOs and
-        * AssemblyRefProcessor should be ignored, 
-        * though we may want to emit a warning, since it should not 
-        * be present in a PE file.
-        */
-       error_list = verify_assemblyref_table (image, error_list, level);
-       error_list = verify_class_layout_table (image, error_list, level);
-       error_list = verify_constant_table (image, error_list, level);
-       /*
-        * cutom attribute, declsecurity 
-        */
-       error_list = verify_event_map_table (image, error_list, level);
-       error_list = verify_event_table (image, error_list, level);
-       error_list = verify_field_table (image, error_list, level);
-       error_list = verify_file_table (image, error_list, level);
-       error_list = verify_moduleref_table (image, error_list, level);
-       error_list = verify_standalonesig_table (image, error_list, level);
-
-       return g_slist_reverse (error_list);
-}
-
 #define ADD_INVALID(list,msg)  \
        do {    \
                MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1);      \
@@ -1910,22 +1351,53 @@ mono_type_from_stack_slot (ILStackDesc *slot)
 
 /*Stack manipulation code*/
 
+static void
+ensure_stack_size (ILCodeDesc *stack, int required)
+{
+       int new_size = 8;
+       ILStackDesc *tmp;
+
+       if (required < stack->max_size)
+               return;
+
+       /* We don't have to worry about the exponential growth since stack_copy prune unused space */
+       new_size = MAX (8, MAX (required, stack->max_size * 2));
+
+       g_assert (new_size >= stack->size);
+       g_assert (new_size >= required);
+
+       tmp = g_new0 (ILStackDesc, new_size);
+       MEM_ALLOC (sizeof (ILStackDesc) * new_size);
+
+       if (stack->stack) {
+               if (stack->size)
+                       memcpy (tmp, stack->stack, stack->size * sizeof (ILStackDesc));
+               g_free (stack->stack);
+               MEM_FREE (sizeof (ILStackDesc) * stack->max_size);
+       }
+
+       stack->stack = tmp;
+       stack->max_size = new_size;
+}
+
 static void
 stack_init (VerifyContext *ctx, ILCodeDesc *state) 
 {
        if (state->flags & IL_CODE_FLAG_STACK_INITED)
                return;
-       state->size = 0;
+       state->size = state->max_size = 0;
        state->flags |= IL_CODE_FLAG_STACK_INITED;
-       if (!state->stack)
-               state->stack = g_new0 (ILStackDesc, ctx->max_stack);
 }
 
 static void
 stack_copy (ILCodeDesc *to, ILCodeDesc *from)
 {
+       ensure_stack_size (to, from->size);
        to->size = from->size;
-       memcpy (to->stack, from->stack, sizeof (ILStackDesc) * from->size);
+
+       /*stack copy happens at merge points, which have small stacks*/
+       if (from->size)
+               memcpy (to->stack, from->stack, sizeof (ILStackDesc) * from->size);
 }
 
 static void
@@ -1978,11 +1450,14 @@ check_unverifiable_type (VerifyContext *ctx, MonoType *type)
        return 1;
 }
 
-
 static ILStackDesc *
 stack_push (VerifyContext *ctx)
 {
        g_assert (ctx->eval.size < ctx->max_stack);
+       g_assert (ctx->eval.size <= ctx->eval.max_size);
+
+       ensure_stack_size (&ctx->eval, ctx->eval.size + 1);
+
        return & ctx->eval.stack [ctx->eval.size++];
 }
 
@@ -2016,6 +1491,14 @@ stack_pop_safe (VerifyContext *ctx)
        return ctx->eval.stack + --ctx->eval.size;
 }
 
+/*Positive number distance from stack top. [0] is stack top, [1] is the one below*/
+static ILStackDesc*
+stack_peek (VerifyContext *ctx, int distance)
+{
+       g_assert (ctx->eval.size - distance > 0);
+       return ctx->eval.stack + (ctx->eval.size - 1 - distance);
+}
+
 static ILStackDesc *
 stack_push_stack_val (VerifyContext *ctx, ILStackDesc *value)
 {
@@ -2311,15 +1794,6 @@ handle_enum:
        case MONO_TYPE_ARRAY:
                return TYPE_COMPLEX | mask;
 
-       case MONO_TYPE_GENERICINST:
-               if (mono_type_is_enum_type (type)) {
-                       type = mono_type_get_underlying_type_any (type);
-                       type_kind = type->type;
-                       goto handle_enum;
-               } else {
-                       return TYPE_COMPLEX | mask;
-               }
-
        case MONO_TYPE_I8:
        case MONO_TYPE_U8:
                return TYPE_I8 | mask;
@@ -2328,9 +1802,12 @@ handle_enum:
        case MONO_TYPE_R8:
                return TYPE_R8 | mask;
 
+       case MONO_TYPE_GENERICINST:
        case MONO_TYPE_VALUETYPE:
                if (mono_type_is_enum_type (type)) {
                        type = mono_type_get_underlying_type_any (type);
+                       if (!type)
+                               return FALSE;
                        type_kind = type->type;
                        goto handle_enum;
                } else {
@@ -2390,16 +1867,6 @@ handle_enum:
                stack->stype = TYPE_COMPLEX | mask;
                break;
                
-       case MONO_TYPE_GENERICINST:
-               if (mono_type_is_enum_type (type)) {
-                       type = mono_type_get_underlying_type_any (type);
-                       type_kind = type->type;
-                       goto handle_enum;
-               } else {
-                       stack->stype = TYPE_COMPLEX | mask;
-                       break;
-               }
-
        case MONO_TYPE_I8:
        case MONO_TYPE_U8:
                stack->stype = TYPE_I8 | mask;
@@ -2408,9 +1875,15 @@ handle_enum:
        case MONO_TYPE_R8:
                stack->stype = TYPE_R8 | mask;
                break;
+       case MONO_TYPE_GENERICINST:
        case MONO_TYPE_VALUETYPE:
                if (mono_type_is_enum_type (type)) {
-                       type = mono_type_get_underlying_type_any (type);
+                       MonoType *utype = mono_type_get_underlying_type_any (type);
+                       if (!utype) {
+                               ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve underlying type of %x at %d", type->type, ctx->ip_offset));
+                               return FALSE;
+                       }
+                       type = utype;
                        type_kind = type->type;
                        goto handle_enum;
                } else {
@@ -2451,6 +1924,7 @@ init_stack_with_value_at_exception_boundary (VerifyContext *ctx, ILCodeDesc *cod
        }
 
        stack_init (ctx, code);
+       ensure_stack_size (code, 1);
        set_stack_value (ctx, code->stack, type, FALSE);
        ctx->exception_types = g_slist_prepend (ctx->exception_types, type);
        code->size = 1;
@@ -2548,8 +2022,17 @@ handle_enum:
                MonoClass *candidate_klass;
                if (mono_type_is_enum_type (target)) {
                        target = mono_type_get_underlying_type_any (target);
+                       if (!target)
+                               return FALSE;
                        goto handle_enum;
                }
+               /*
+                * VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
+                * to take boxing status into account.
+                */
+               if (mono_type_is_generic_argument (original_candidate))
+                       return FALSE;
+
                target_klass = mono_class_from_mono_type (target);
                candidate_klass = mono_class_from_mono_type (candidate);
                if (mono_class_is_nullable (target_klass)) {
@@ -2571,6 +2054,10 @@ handle_enum:
                 */
                if (mono_type_is_generic_argument (original_candidate))
                        return FALSE;
+
+               if (candidate->type == MONO_TYPE_VALUETYPE)
+                       return FALSE;
+
                /* If candidate is an enum it should return true for System.Enum and supertypes.
                 * That's why here we use the original type and not the underlying type.
                 */ 
@@ -2585,8 +2072,9 @@ handle_enum:
                if (candidate->type != MONO_TYPE_SZARRAY)
                        return FALSE;
 
-               left = mono_class_from_mono_type (target)->element_class;
-               right = mono_class_from_mono_type (candidate)->element_class;
+               left = mono_class_from_mono_type (target);
+               right = mono_class_from_mono_type (candidate);
+
                return mono_class_is_assignable_from (left, right);
        }
 
@@ -2599,13 +2087,20 @@ handle_enum:
                return candidate->type == MONO_TYPE_TYPEDBYREF;
 
        case MONO_TYPE_VALUETYPE: {
-               MonoClass *target_klass  = mono_class_from_mono_type (target);
-               MonoClass *candidate_klass = mono_class_from_mono_type (candidate);
+               MonoClass *target_klass;
+               MonoClass *candidate_klass;
 
+               if (candidate->type == MONO_TYPE_CLASS)
+                       return FALSE;
+
+               target_klass = mono_class_from_mono_type (target);
+               candidate_klass = mono_class_from_mono_type (candidate);
                if (target_klass == candidate_klass)
                        return TRUE;
                if (mono_type_is_enum_type (target)) {
                        target = mono_type_get_underlying_type_any (target);
+                       if (!target)
+                               return FALSE;
                        goto handle_enum;
                }
                return FALSE;
@@ -3342,7 +2837,7 @@ do_invoke_method (VerifyContext *ctx, int method_token, gboolean virtual)
                if (method->flags & METHOD_ATTRIBUTE_ABSTRACT) 
                        CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use call with an abstract method at 0x%04x", ctx->ip_offset));
                
-               if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL)) {
+               if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED)) {
                        virt_check_this = TRUE;
                        ctx->code [ctx->ip_offset].flags |= IL_CODE_CALL_NONFINAL_VIRTUAL;
                }
@@ -3407,7 +2902,7 @@ do_invoke_method (VerifyContext *ctx, int method_token, gboolean virtual)
                copy.stype &= ~POINTER_MASK;
 
                if (virt_check_this && !stack_slot_is_this_pointer (value) && !(method->klass->valuetype || stack_slot_is_boxed_value (value)))
-                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a non-final virtual method from an objet diferent thant the this pointer at 0x%04x", ctx->ip_offset));
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use the call opcode with a non-final virtual method on an object diferent thant the this pointer at 0x%04x", ctx->ip_offset));
 
                if (constrained && virtual) {
                        if (!stack_slot_is_managed_pointer (value))
@@ -3560,8 +3055,13 @@ check_is_valid_type_for_field_ops (VerifyContext *ctx, int token, ILStackDesc *o
                if (field->parent->valuetype && stack_slot_is_boxed_value (obj))
                        CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is a boxed valuetype and is not compatible to reference the field at 0x%04x", ctx->ip_offset));
 
-               if (!stack_slot_is_null_literal (obj) && !verify_stack_type_compatibility_full (ctx, &field->parent->byval_arg, obj, TRUE, FALSE))
-                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is not compatible to reference the field at 0x%04x", ctx->ip_offset));
+               if (!stack_slot_is_null_literal (obj) && !verify_stack_type_compatibility_full (ctx, &field->parent->byval_arg, obj, TRUE, FALSE)) {
+                       char *found = stack_slot_full_name (obj);
+                       char *expected = mono_type_full_name (&field->parent->byval_arg);
+                       CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected type '%s' but found '%s' referencing the 'this' argument at 0x%04x", expected, found, ctx->ip_offset));
+                       g_free (found);
+                       g_free (expected);
+               }
 
                if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, mono_class_from_mono_type (obj->type)))
                        CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
@@ -4900,6 +4400,8 @@ mono_method_verify (MonoMethod *method, int level)
        GSList *tmp;
        VERIFIER_DEBUG ( printf ("Verify IL for method %s %s %s\n",  method->klass->name_space,  method->klass->name, method->name); );
 
+       init_verifier_stats ();
+
        if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
                        (method->flags & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT))) {
                return NULL;
@@ -4911,11 +4413,14 @@ mono_method_verify (MonoMethod *method, int level)
        ctx.signature = mono_method_signature (method);
        if (!ctx.signature) {
                ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method signature"));
+
+               finish_collect_stats ();
                return ctx.list;
        }
        ctx.header = mono_method_get_header (method);
        if (!ctx.header) {
                ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method header"));
+               finish_collect_stats ();
                return ctx.list;
        }
        ctx.method = method;
@@ -4931,17 +4436,20 @@ mono_method_verify (MonoMethod *method, int level)
 
        ctx.code = g_new (ILCodeDesc, ctx.header->code_size);
        ctx.code_size = ctx.header->code_size;
+       MEM_ALLOC (sizeof (ILCodeDesc) * ctx.header->code_size);
 
        memset(ctx.code, 0, sizeof (ILCodeDesc) * ctx.header->code_size);
 
-
        ctx.num_locals = ctx.header->num_locals;
        ctx.locals = g_memdup (ctx.header->locals, sizeof (MonoType*) * ctx.header->num_locals);
+       MEM_ALLOC (sizeof (MonoType*) * ctx.header->num_locals);
 
        if (ctx.num_locals > 0 && !ctx.header->init_locals)
                CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Method with locals variable but without init locals set"));
 
        ctx.params = g_new (MonoType*, ctx.max_args);
+       MEM_ALLOC (sizeof (MonoType*) * ctx.max_args);
+
        if (ctx.signature->hasthis)
                ctx.params [0] = method->klass->valuetype ? &method->klass->this_arg : &method->klass->byval_arg;
        memcpy (ctx.params + ctx.signature->hasthis, ctx.signature->params, sizeof (MonoType *) * ctx.signature->param_count);
@@ -5402,14 +4910,13 @@ mono_method_verify (MonoMethod *method, int level)
                        break; 
 
                case CEE_DUP: {
-                       ILStackDesc * top;
+                       ILStackDesc *top;
                        if (!check_underflow (&ctx, 1))
                                break;
                        if (!check_overflow (&ctx))
                                break;
-                       top = stack_pop_safe (&ctx);
-                       copy_stack_value (stack_push (&ctx), top); 
-                       copy_stack_value (stack_push (&ctx), top);
+                       top = stack_push (&ctx);
+                       copy_stack_value (top, stack_peek (&ctx, 1));
                        ++ip;
                        break;
                }
@@ -5489,7 +4996,6 @@ mono_method_verify (MonoMethod *method, int level)
                        code_bounds_check (sizeof (guint32) * entries);
                        
                        do_switch (&ctx, entries, ip);
-                       start = 1;
                        ip += sizeof (guint32) * entries;
                        break;
                }
@@ -6048,6 +5554,7 @@ cleanup:
        mono_basic_block_free (original_bb);
        mono_metadata_free_mh (ctx.header);
 
+       finish_collect_stats ();
        return ctx.list;
 }
 
@@ -6075,7 +5582,7 @@ mono_verifier_is_enabled_for_method (MonoMethod *method)
 gboolean
 mono_verifier_is_enabled_for_class (MonoClass *klass)
 {
-       return verify_all || (verifier_mode > MONO_VERIFIER_MODE_OFF && !klass->image->assembly->in_gac && klass->image != mono_defaults.corlib);
+       return verify_all || (verifier_mode > MONO_VERIFIER_MODE_OFF && !(klass->image->assembly && klass->image->assembly->in_gac) && klass->image != mono_defaults.corlib);
 }
 
 gboolean
@@ -6103,7 +5610,7 @@ mono_verifier_is_class_full_trust (MonoClass *klass)
 {
        /* under CoreCLR code is trusted if it is part of the "platform" otherwise all code inside the GAC is trusted */
        gboolean trusted_location = (mono_security_get_mode () != MONO_SECURITY_MODE_CORE_CLR) ? 
-               klass->image->assembly->in_gac : mono_security_core_clr_is_platform_image (klass->image);
+               (klass->image->assembly && klass->image->assembly->in_gac) : mono_security_core_clr_is_platform_image (klass->image);
 
        if (verify_all && verifier_mode == MONO_VERIFIER_MODE_OFF)
                return trusted_location || klass->image == mono_defaults.corlib;
@@ -6360,10 +5867,4 @@ mono_free_verify_list (GSList *list)
        /* will always be null if verifier is disabled */
 }
 
-GSList*
-mono_image_verify_tables (MonoImage *image, int level)
-{
-       /* The verifier was disabled at compile time */
-       return NULL;
-}      
 #endif
index aee678598f6751a47f935f1406fb1c6bb0e6a56a..dd81fe49a8127b6de3dd8a6106479243da58cef9 100644 (file)
@@ -52,7 +52,6 @@ typedef struct {
 } MonoVerifyInfoExtended;
 
 
-GSList* mono_image_verify_tables (MonoImage *image, int level);
 GSList* mono_method_verify       (MonoMethod *method, int level);
 void    mono_free_verify_list    (GSList *list);
 char*   mono_verify_corlib       (void);
index 15c45dcce7516433ca22edf4d1839b3f4d1974b0..d6b54239edb56d7f96c8c9c3100d28eb7758e6e7 100644 (file)
@@ -1,8 +1,10 @@
 /Makefile
 /Makefile.in
 /*.o
+/*.so
 /*.exe
 /*.dll
+/*.mdb
 /*.lo
 /*.loT
 /*.la
@@ -27,3 +29,4 @@
 /iltests.il
 /version.h
 /buildver.h
+/TAGS
index 35afd94cbbbf80b6769c3efa23b92d0785c94bff..1b11f56cf404ad1aaff51695930b9c76c94d6103 100755 (executable)
@@ -1,3 +1,551 @@
+2010-04-26  Zoltan Varga  <vargaz@gmail.com>
+
+       * method-to-ir.c (mono_op_to_op_imm_noemul): Fix a warning.
+
+2010-04-24  Mark Probst  <mark.probst@gmail.com>
+
+       * mini.c, driver.c: Initialize mono_use_llvm in mono_main(), not
+       in the initializer, because it's non-constant.
+
+2010-04-23  Miguel de Icaza  <miguel@novell.com>
+
+       * mini.c: Use MONO_USE_LLVM as an environment flag to turn the use
+       of LLVM on by default.   Used for buildbots and other setups.
+
+2010-04-24  Zoltan Varga  <vargaz@gmail.com>
+
+       * mini.c: Set mono_use_llvm to FALSE even if mono is compiled with LLVM.
+
+2010-04-23  Kornel Pal  <kornelpal@gmail.com>
+
+       * method-to-ir.c (mono_method_to_ir): Enable inlining of pointer-sized unmanaged
+       initonly static fields when using moving GC.
+
+       Contributed under MIT/X11 license.
+
+2010-04-23  Geoff Norton  <gnorton@novell.com>
+
+       * mini-amd64.h: Darwin x86_64 support.
+
+2010-04-20  Jonathan Pryor  <jpryor@novell.com>
+
+       * exceptions-arm.c: Remove platform checks in favor of configure checks.
+
+2010-04-19  Jonathan Pryor  <jpryor@novell.com>
+
+       * exceptions-arm.c: Add Android support for sigcontext structure.
+
+2010-04-16  Zoltan Varga  <vargaz@gmail.com>
+
+       * mini.c (mono_jit_compile_method_inner): Implement the check for native func
+       wrappers correctly now that their wrapper info is NULL.
+
+2010-04-16  Zoltan Varga  <vargaz@gmail.com>
+
+       * mini.c (mono_jit_compile_method_inner): Avoid calling
+       mono_marshal_method_from_wrapper () for native func wrappers. Fixes #597189.
+
+2010-04-16  Zoltan Varga  <vargaz@gmail.com>
+
+       * genmdesc.c (inst_name): Define this as a copy of mono_inst_name in helpers.c,
+       so the latter can be #ifndef DISABLE_JIT-ed.
+
+       * helpers.c: Comment out the opstr array if DISABLE_JIT is set.
+
+2010-04-16  Zoltan Varga  <vargaz@gmail.com>
+
+       * method-to-ir.c driver.c: Disable a few more things when DISABLE_JIT is set.
+
+2010-04-16  Zoltan Varga  <vargaz@gmail.com>
+
+       * mini-llvm.c (emit_entry_bb): Fix support for simd arguments passed on the
+       stack.
+
+2010-04-15  Zoltan Varga  <vargaz@gmail.com>
+
+       * debugger-agent.c (type_commands): Call mono_class_setup_methods () before
+       calling mono_class_num_methods (). Fixes #592244.
+
+2010-04-14  Zoltan Varga  <vargaz@gmail.com>
+
+       * mini-x86.c (mono_arch_get_llvm_call_info): Handle empty structures correctly.
+
+       * mini-llvm.c: Disable LLVM for calls with non-default calling conventions.
+
+2010-04-14  Zoltan Varga  <vargaz@gmail.com>
+
+       * method-to-ir.c (handle_box_inst): Merge into handle_box, simplify the merged
+       version.
+       * (handle_alloc): Ditto.
+       (mono_method_to_ir): Remove the constrained call restriction added by a previous
+       change, its not needed anymore.
+
+2010-04-12 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * mini-posix.c (sigusr1_signal_handler): Fix build on
+       non x86/amd64 systems.
+
+2010-04-13  Zoltan Varga  <vargaz@gmail.com>
+
+       * method-to-ir.c (mono_method_to_ir): Disable generic sharing for constrained
+       calls where the constrained class needs a context. Fixes #595863.
+
+       * iltests.il.in: Add a test.
+
+2010-04-13  Zoltan Varga  <vargaz@gmail.com>
+
+       * mini.c (mini_method_compile): Disable llvm+methods with clauses again, llvm
+       2.6/SVN seems to have broken support for them.
+
+2010-04-13  Zoltan Varga  <vargaz@gmail.com>
+
+       * mini-llvm.c: Fix support for LLVM 2.6.
+
+2010-04-10  Zoltan Varga  <vargaz@gmail.com>
+
+       * debugger-agent.c (thread_commands): Add a GET_ID command to get the
+       MonoInternalThread belonging to the thread.
+
+Fri Apr 9 15:28:01 CEST 2010 Paolo Molaro <lupus@ximian.com>
+
+       * driver.c, optflags-def.h, ir-emit.h: introduce an unsupported
+       unsafe optimization that will remove bound checks.
+
+2010-04-08  Kornel Pal  <kornelpal@gmail.com>
+
+       * method-to-ir.c (mini_emit_inst_for_method): Fix a typo that caused
+       CompareExchange not to be inlined for I8.
+
+       Contributed under MIT/X11 license.
+
+2010-04-07 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * array.cs: Add tests for cast between primitive array types.
+
+2010-04-07 Andreia Gaita  <avidigal@novell.com>
+
+       * Makefile.am: create a convenience library for moon to link with
+
+2010-04-07 Paolo Molaro <lupus@ximian.com>
+
+       * method-to-ir.c: optimize array accesses from generic interfaces.
+
+2010-04-06  Zoltan Varga  <vargaz@gmail.com>
+
+       * mini-llvm.c: Update after the memset/memcpy intrinsics changes in LLVM SVN.
+
+2010-04-05 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * method-to-ir.c (mono_method_to_ir): Handle call to virtual final methods
+       of marshalbyref classes.
+
+       Fixes #515884.
+
+2010-04-05 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * aot-compiler.c (emit_exception_debug_info): Encode try holes
+       information.
+
+       * aot-runtime.c (decode_exception_debug_info): Decode try holes
+       information.
+
+       * mini.h: Increase AOT version.
+
+2010-04-04  Andreas Faerber  <andreas.faerber@web.de>
+
+       * mini-x86.h: Only enable soft debugger when using sigaction or on
+       Windows. Fixes build on Haiku (lacks siginfo_t).
+
+       Code is contributed under MIT/X11 license.
+
+2010-04-02  Andreas Faerber  <andreas.faerber@web.de>
+
+       * mini.h, mini-x86.h: Suppress sigaction for Haiku, add support for
+       BeOS-style signal handlers.
+
+       Code is contributed under MIT/X11 license.
+       
+2010-04-02  Zoltan Varga  <vargaz@gmail.com>
+
+       * mini-posix.c (sigusr1_signal_handler): Fix openbsd support.
+
+2010-04-01 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * mini-exceptions.c: Fix win32 build.
+
+2010-04-01  Mark Probst  <mark.probst@gmail.com>
+
+       * mini.c, driver.c: Call mono_gc_base_init() before
+       mono_debug_init().
+
+2010-04-01  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * method-to-ir.c (ensure_method_is_allowed_to_[access_field|
+       call_method]): Delegate the actual work in security-core-clr.c
+       to ease code sharing.
+
+2010-04-01  Zoltan Varga  <vargaz@gmail.com>
+
+       * decompose.c (mono_decompose_opcode): Set the cfg exception if the unsupported
+       float conv.ovf.un opcodes are encountered, instead of asserting later.
+       Fixes #566296.
+
+2010-04-01  Zoltan Varga  <vargaz@gmail.com>
+
+       * decompose.c (mono_decompose_opcode): Add OP_ICONV_TO_U4_UN as a no-op.
+
+       * iltests.il.in: Add a test.
+
+2010-04-01  Zoltan Varga  <vargaz@gmail.com>
+
+       * mini-amd64.c (mono_arch_emit_call): Fail compilation if an argument is too
+       large. Fixes #567040.
+
+       * method-to-ir.c: Call CHECK_CFG_EXCEPTION after emitting a call.
+
+2010-04-01  Zoltan Varga  <vargaz@gmail.com>
+
+       * method-to-ir.c (handle_ccastclass): Call save_cast_details (). Fixes
+       #592711.
+
+2010-03-31 Rolf Bjarne Kvinge <RKvinge@novell.com>
+
+       * mini-trampolines.c: Surround mono_handler_block_guard_trampoline and
+       mono_create_handler_block_trampoline with the proper #ifdef so that it
+       compiles on amd64.
+
+2010-03-30 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * mini-exceptions.c: Introduce mono_walk_stack_full, which
+       allows to select if it's new or old context that is passed to 
+       the callback.
+
+       * mini-exceptions.c (mono_handle_exception_internal): Handle the
+       case when executing a guarded handler from the EH machinery.
+
+       * mini-exceptions.c (mono_install_handler_block_guard): New function
+       responsible for checking for handler blocks, installing the guard and
+       clearing abort state.
+
+       * mini-posix.c (sigusr1_signal_handler): Call mono_install_handler_block_guard
+       to check for handler blocks and skip interruption logic if one was found.
+
+       * mini-trampolines.c (mono_handler_block_guard_trampoline): Function called
+       by the handler block guard trampoline. Resumes interruption by raising the
+       pending ThreadAbortException.
+
+       * mini.c (create_jit_info): Calculate the end address of a finally block.
+
+       * mini-x86.c (mono_arch_install_handler_block_guard): Patch the return address
+       of a finally block to a specified address and return the old one.
+
+       * tramp-x86.c (mono_arch_create_handler_block_trampoline): The handler block
+       trampoline patches the original return address and calls the trampoline function.
+
+2010-03-30  Zoltan Varga  <vargaz@gmail.com>
+
+       * mini-trampolines.c (mono_aot_trampoline): Remove some dead code.
+
+       * aot-runtime.c (mono_aot_patch_plt_entry): New helper function, which only
+       does the patching if the callee is in the same domain.
+
+       * aot-runtime.c mini-trampolines.c: Call mono_aot_patch_plt_entry instead
+       of mono_arch_patch_plt_entry ().
+
+2010-03-30 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * mini.c (create_jit_info): Fix try block hole length encoding.
+
+2010-03-30 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * mini.c (create_jit_info): Emit saner debug spew. Now it doesn't
+       duplicate information and print offsets instead of absolute addresses.
+
+2010-03-29  Zoltan Varga  <vargaz@gmail.com>
+
+       * debugger-agent.c (jit_end): Send type loads for types loaded before the VMStart
+       event is sent. Fixes #591733.
+
+2010-03-26  Zoltan Varga  <vargaz@gmail.com>
+
+       * mini-posix.c (SIG_HANDLER_SIGNATURE): Handle the case when ctx is NULL on
+       OpenBSD.
+
+2010-03-26  Zoltan Varga  <vargaz@gmail.com>
+
+       * debugger-agent.c (mono_debugger_agent_init): Set the GC type of the
+       thread_to_tls hash table.
+
+       * image-writer.c (bin_writer_emit_writeout): Fix the size of the got.plt
+       section. Fixes #591000.
+
+2010-03-26  Andreas Faerber  <andreas.faerber@web.de>
+
+       * Makefile.am (version.h): Check for pure .git directory only,
+       fixes SVN revision when using git without git-svn.
+
+       Contributed under MIT/X11 license.
+
+2010-03-26  Zoltan Varga  <vargaz@gmail.com>
+
+       * aot-runtime.c: Apply some openbsd changes from openbsd ports.
+
+2010-03-24 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * basic-simd.cs: Test for vector x scalar binary operators.
+
+2010-03-24 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * simd-intrincs.c (simd_intrinsic_emit_binary): Support binary
+       intrinsics with expanded scalar arguments.
+
+2010-03-24 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * mini-exceptions.c (get_exception_catch_class): Non catch clauses
+       don't have an exception class, so don't decode it. This would crash
+       with filter clauses.
+
+2010-03-24  U-anarquia\miguel  <miguel@anarquia>
+
+       Make sure that trunk builds with DISABLE_JIT, an update to the
+       PlayStation 3 port.
+       
+       * mini.c (mini_get_shared_method): this code seems to be necessary
+       regardless of whether DISABLE_JIT has been defined.
+
+       (mono_jit_compile_method_inner): it seems that this method is
+       required even in full AOT mode, so ifdef out only the pieces that
+       try to genrate code (the body of code that applies patches to the
+       code).  
+
+       (mini_method_compile): do not compile when using DISABLE_JIT.
+
+       * mini-ppc.c (mono_arch_get_allocatable_int_vars)
+       (mono_arch_output_basic_block, mono-arch_emit_exceptions): Do not
+       compile when DISABLE_JIT is set.
+
+2010-03-24  Mark Probst  <mark.probst@gmail.com>
+
+       * mini.c (mono_create_tls_get): Only create a TLS operation if the
+       arch really supports it.
+
+2010-03-24  Mark Probst  <mark.probst@gmail.com>
+
+       * mini-x86.c, mini-x86.h, mini.c: CEE_MONO_TLS support for Darwin/x86.
+
+2010-03-23  Neale Ferguson <neale@sinenomine.net>
+
+       * exceptions-s390x.c: Add support for
+       mono_arch_get_throw_corlib_exception and fix throw by name.
+
+       * mini-s390x.c: Add IMT support; Fix stack parameter passing
+       logic (especially for varargs); Correct localloc sizing; Add
+       mono_arch_get_this_arg_from_call and
+       mono_arch_get_this_arg_from_call.
+
+       * mini-s390x.h: Add support for facility list extraction;
+       Correct/update MONO_ARCH_xxx settings.
+
+       * mini-s390.c: Minor corrections to instruction output for
+       varargs. No IMT implementation - I think it's time to deprecate
+       s390 and just leave s390x.
+
+       * tramp-s390x.c: Correct creation of trampoline instruction
+
+
+       * cpu-s390x.md: Update some instruction lengths
+
+2010-03-23  Zoltan Varga  <vargaz@gmail.com>
+
+       * mini-generic-sharing.c (fill_in_rgctx_template_slot): Remove an assert which
+       can be hit with partial sharing.
+
+       * mini-generic-sharing.c (get_shared_class): Handle partially shared methods
+       in non-shared classes correctly.
+       (generic_inst_is_sharable): Allow all primitive types in partial sharing.
+       Turn on partial sharing.
+
+2010-03-23  Zoltan Varga  <vargaz@gmail.com>
+
+       * mini-amd64.h: Put back MONO_ARCH_NOMAP32BIT for OpenBSD which was removed
+       by mistake.
+
+2010-03-23  Zoltan Varga  <vargaz@gmail.com>
+
+       * method-to-ir.c (mono_method_to_ir): Handle the failure of
+       mono_method_signature ().
+
+       * mini-trampolines.c (mono_delegate_trampoline): Ditto.
+
+       * mini.c (mini_method_compile): Get the signature of cfg->method early with
+       error checking, so later calls do not need error checking.
+
+2010-03-22  Zoltan Varga  <vargaz@gmail.com>
+
+       * exceptions-amd64.c: Add support for OpenBSD which has no UCONTEXT_GREGS.
+
+       * mini-amd64.h: Enable MONO_ARCH_USE_SIGACTION on OpenBSD as well.
+
+2010-03-22 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * mini-exceptions.c (mono_handle_exception_internal): Don't
+       check try_end for archs different than s390. 
+
+       * mini.c (create_jit_info): Don't crash if the finallt block is the
+       last one.
+
+2010-03-22 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * driver.c (mono_main): Don't free global codeman under linux since
+       glic now peeks at code on stack for more archs than just amd64.
+
+Mon Mar 22 18:09:09 CET 2010 Paolo Molaro <lupus@ximian.com>
+
+       * mini.c, method-to-ir.c: changes to support compressed interface
+       bitmaps.
+
+2010-03-22  Zoltan Varga  <vargaz@gmail.com>
+
+       * mini-x86.h: Applied patch from Robert Nagy (Robert@openbsd.org).
+       Use sigaction on OpenBSD too.
+
+2010-03-22  Zoltan Varga  <vargaz@gmail.com>
+
+       * debugger-agent.c (event_req_matches_assembly): Handle request modifiers too.
+
+2010-03-21  Andreas Faerber  <andreas.faerber@web.de>
+
+       * debugger-agent.c: #include sys/select.h for fd_set.
+
+       Code is contributed under MIT/X11 license.
+
+2010-03-21  Zoltan Varga  <vargaz@gmail.com>
+
+       * mini.c (SIG_HANDLER_SIGNATURE): Fix the build on platforms without sigaction
+       (openbsd+amd64 ?).
+
+2010-03-21  Zoltan Varga  <vargaz@gmail.com>
+
+       * mini-ppc.c (mono_arch_emit_exceptions): Avoid an assert in ppc_patch () for
+       some large methods with lots of exception handlers. Fixes #440924.
+
+Sat Mar 20 11:56:24 CET 2010 Paolo Molaro <lupus@ximian.com>
+
+       * method-to-ir.c: remove code duplication for interface checks.
+
+2010-03-19  Zoltan Varga  <vargaz@gmail.com>
+
+       * debugger-agent.c (clear_event_requests_for_assembly): New helper function.
+       (assembly_unload): Clear all event requests referencing the to-be unloaded
+       assembly.
+
+
+Fri Mar 19 16:45:20 CET 2010 Paolo Molaro <lupus@ximian.com>
+
+       * mini.h, mini-exceptions.c: restore the state of the stack
+       guard page permissions.
+
+2010-03-19  Zoltan Varga  <vargaz@gmail.com>
+
+       * mini-trampolines.c (common_call_trampoline): Remove the condition guarding the
+       call site patching code, it doesn't appear to be needed.
+
+2010-03-19  Zoltan Varga  <vargaz@gmail.com>
+
+       * mini-generic-sharing.c: Add infrastructure for partial sharing, ie.
+       sharing generic methods whose type arguments are a mix of reference and
+       non-reference types. Not yet turned on.
+
+       * mini.c (mini_get_shared_method): New helper function to return
+       the method which will be compiled/registered in the JIT tables when doing
+       generic sharing.
+       (mono_domain_lookup_shared_generic): Moved to mini.c from mini-generic-sharing.c,
+       use mini_get_shared_method ().
+
+       * mini.c (mini_method_compile): Register the same method which is compiled when
+       doing generic sharing.
+
+       * mini.c aot-compiler.c aot-runtime.c: Add support for partial sharing.
+
+       * generics.cs: Add partial sharing tests.
+
+2010-03-17 Jerry Maine  <crashfourit@gmail.com>
+
+       * mini.h : Changed the SIMD_VERSION* enum values to match those in Mono.Simd.AccelMode.
+                  Add an enum value that or's all possable values together. Add an enum value
+                  that marks the end of the used bit indexes.
+
+       * mini-amd64.c : Make changes to match the changes in mini.h 
+
+       * mini-x86.c : Make changes to match the changes in mini.h
+
+       * simd-intrinsics.c : Reorder the SimdIntrinsc struct to add more bits to
+                  simd_version to support more simd versions. Changed the name of
+                  simd_version to simd_version_flags to make it more intuitive that
+                  it now contains bit flags. Reordered the *_intrinsics arrays to
+                  match the changes above. Changed emit_intrinsics() to use the new
+                  setup mentioned above.
+
+       Code is contributed under MIT/X11 license.
+
+2010-03-17 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * mini-*.c (mono_arch_output_basic_block): Record try block holes on all
+       remaining archs. Alpha and hppa maintainers, please stand up.
+
+2010-03-17  Zoltan Varga  <vargaz@gmail.com>
+
+       * mini-ppc.c (mono_arch_build_imt_thunk): Always save and restore r11 since it
+       is needed even when fail_tramp!=NULL.
+
+2010-03-17  Zoltan Varga  <vargaz@gmail.com>
+
+       * debugger-agent.c (insert_breakpoint): Write a log message.
+
+2010-03-16 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * iltests.il.in: Add a few tests for LEAVE going over multiple
+       finally clauses.
+
+2010-03-16 Rodrigo Kumpera  <rkumpera@novell.com>
+
+        * mini-x86.c (mono_arch_output_basic_block): Record try block holes.
+
+2010-03-16 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * mini.h (MonoBasicBlock): Add native_length field.
+       * mini.h (MonoCompile): Add try_block_holes field.
+       * mini.h (MonoInst): Add exception_clause pointer to
+       the data union.
+
+       * mini.c (mono_codegen): Calculate MonoBasicBlock::native_length.
+       * mini.c (mono_cfg_add_try_hole): New function to register possible
+       holes in try blocks.
+       * mini.c (create_jit_info): Fill in the holes information.
+
+       * mini-exceptions.c: Verify for holes when checking if an IP is covered
+       by a try block.
+
+       * method-to-ir.c: Add the EH clause to the CALL_HANDLE instruction.
+
+Tue Mar 16 13:16:16 CET 2010 Paolo Molaro <lupus@ximian.com>
+
+       * jit-icalls.c: adjusted for the array API changes.
+
+2010-03-16  Zoltan Varga  <vargaz@gmail.com>
+
+       * iltests.il.in: Disable the fconv_to_i test on sparc too.
+
+2010-03-16  Zoltan Varga  <vargaz@gmail.com>
+
+       * debugger-agent.c: Simplify the way breakpoints are processed by removing
+       the 'pending' flag. This fixes support for appdomains too.
+
+
+Mon Mar 15 18:25:49 CET 2010 Paolo Molaro <lupus@ximian.com>
+
+       * mini-amd64.c, mini-ia64.c: remove direct access to method->header.
+
 2010-03-12  Zoltan Varga  <vargaz@gmail.com>
 
        * simd-intrinsics.c (simd_intrinsic_emit_getter): Don't emit shuffle opcodes
index 4fe7052d646598acd68ea5513fc55231baf1da1e..edb97fa8171a95473e07a05fdfbef46e1d0ab9dc 100644 (file)
@@ -78,6 +78,11 @@ noinst_PROGRAMS = genmdesc
 
 lib_LTLIBRARIES = libmono-2.0.la
 noinst_LTLIBRARIES = libmono-static.la
+
+if MOONLIGHT
+noinst_LTLIBRARIES += libmono-moon.la
+endif
+
 endif
 
 mono_SOURCES = \
@@ -425,6 +430,10 @@ endif
 
 libmono_2_0_la_SOURCES = $(common_sources) $(llvm_sources) $(arch_sources) $(os_sources)
 
+if MOONLIGHT
+libmono_moon_la_SOURCES = $(libmono_2_0_la_SOURCES)
+endif
+
 libmono_static_la_SOURCES = $(libmono_2_0_la_SOURCES)
 nodist_libmono_static_la_SOURCES = $(nodist_libmono_la_SOURCES)
 libmono_static_la_LDFLAGS = -static
@@ -439,6 +448,10 @@ libmonoinclude_HEADERS = jit.h
 libmono_2_0_la_LIBADD = \
        $(libs) $(LIBMONO_DTRACE_OBJECT)
 
+if MOONLIGHT
+libmono_moon_la_LIBADD = $(libmono_2_0_la_LIBADD)
+endif
+
 basic-simd.exe: basic-simd.cs
        $(MCS) -out:$@ $< -r:TestDriver.dll -r:Mono.Simd.dll
 
@@ -586,7 +599,7 @@ EXTRA_DIST = $(common_BURGSRC) TestDriver.cs ldscript ldscript.mono \
        $(posix_sources)
 
 version.h: Makefile
-       if test -d $(top_srcdir)/.git/svn; then svn_info="git log --no-color --first-parent -n1 --grep=git-svn-id: --pretty=format:%b | sed -n -e 's,git-svn-id: \(.*\)@\(.*\) .*,URL: \1 Revision: \2,p'"; fi; \
+       if test -d $(top_srcdir)/.git; then svn_info="git log --no-color --first-parent -n1 --grep=git-svn-id: --pretty=format:%b | sed -n -e 's,git-svn-id: \(.*\)@\(.*\) .*,URL: \1 Revision: \2,p'"; fi; \
        if test -d $(srcdir)/.svn; then svn_info='svn info'; fi; \
        if test -n "$$svn_info"; then \
                (cd $(top_srcdir); \
index a9b498587db92adc85b5a21c8f405ece09ceecf0..a62bcd583021514a93ea5699ea9eef3024d159f2 100644 (file)
@@ -2360,7 +2360,7 @@ add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
 
        iter = NULL;
        while ((method = mono_class_get_methods (klass, &iter))) {
-               if (mono_method_is_generic_sharable_impl (method, FALSE))
+               if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
                        /* Already added */
                        continue;
 
@@ -2481,18 +2481,98 @@ add_generic_instances (MonoAotCompile *acfg)
                token = MONO_TOKEN_METHOD_SPEC | (i + 1);
                method = mono_get_method (acfg->image, token, NULL);
 
-               context = mono_method_get_context (method);
-               if (context && ((context->class_inst && context->class_inst->is_open) ||
-                                               (context->method_inst && context->method_inst->is_open)))
+               if (method->klass->image != acfg->image)
                        continue;
 
-               if (method->klass->image != acfg->image)
+               context = mono_method_get_context (method);
+
+               if (context && ((context->class_inst && context->class_inst->is_open)))
                        continue;
 
-               if (mono_method_is_generic_sharable_impl (method, FALSE))
-                       /* Already added */
+               /*
+                * For open methods, create an instantiation which can be passed to the JIT.
+                * FIXME: Handle class_inst as well.
+                */
+               if (context && context->method_inst && context->method_inst->is_open) {
+                       MonoGenericContext shared_context;
+                       MonoGenericInst *inst;
+                       MonoType **type_argv;
+                       int i;
+                       MonoMethod *declaring_method;
+                       gboolean supported = TRUE;
+
+                       /* Check that the context doesn't contain open constructed types */
+                       if (context->class_inst) {
+                               inst = context->class_inst;
+                               for (i = 0; i < inst->type_argc; ++i) {
+                                       if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
+                                               continue;
+                                       if (mono_class_is_open_constructed_type (inst->type_argv [i]))
+                                               supported = FALSE;
+                               }
+                       }
+                       if (context->method_inst) {
+                               inst = context->method_inst;
+                               for (i = 0; i < inst->type_argc; ++i) {
+                                       if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
+                                               continue;
+                                       if (mono_class_is_open_constructed_type (inst->type_argv [i]))
+                                               supported = FALSE;
+                               }
+                       }
+
+                       if (!supported)
+                               continue;
+
+                       memset (&shared_context, 0, sizeof (MonoGenericContext));
+
+                       inst = context->class_inst;
+                       if (inst) {
+                               type_argv = g_new0 (MonoType*, inst->type_argc);
+                               for (i = 0; i < inst->type_argc; ++i) {
+                                       if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
+                                               type_argv [i] = &mono_defaults.object_class->byval_arg;
+                                       else
+                                               type_argv [i] = inst->type_argv [i];
+                               }
+                               
+                               shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
+                               g_free (type_argv);
+                       }
+
+                       inst = context->method_inst;
+                       if (inst) {
+                               type_argv = g_new0 (MonoType*, inst->type_argc);
+                               for (i = 0; i < inst->type_argc; ++i) {
+                                       if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
+                                               type_argv [i] = &mono_defaults.object_class->byval_arg;
+                                       else
+                                               type_argv [i] = inst->type_argv [i];
+                               }
+
+                               shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
+                               g_free (type_argv);
+                       }
+
+                       if (method->is_generic || method->klass->generic_container)
+                               declaring_method = method;
+                       else
+                               declaring_method = mono_method_get_declaring_generic_method (method);
+
+                       method = mono_class_inflate_generic_method (declaring_method, &shared_context);
+               }
+
+               /* 
+                * If the method is fully sharable, it was already added in place of its
+                * generic definition.
+                */
+               if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
                        continue;
 
+               /*
+                * FIXME: Partially shared methods are not shared here, so we end up with
+                * many identical methods.
+                */
                add_extra_method (acfg, method);
        }
 
@@ -3168,7 +3248,7 @@ emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
        use_unwind_ops = cfg->unwind_ops != NULL;
 #endif
 
-       flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points ? 8 : 0) | (cfg->compile_llvm ? 16 : 0);
+       flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points ? 8 : 0) | (cfg->compile_llvm ? 16 : 0) | (jinfo->has_try_block_holes ? 32 : 0);
 
        encode_value (flags, p, &p);
 
@@ -3187,6 +3267,12 @@ emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
                encode_value (jinfo->used_regs, p, &p);
        }
 
+       /*Encode the number of holes before the number of clauses to make decoding easier*/
+       if (jinfo->has_try_block_holes) {
+               MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
+               encode_value (table->num_holes, p, &p);
+       }
+
        /* Exception table */
        if (cfg->compile_llvm) {
                /* The assembly might be CIL stripped so emit the data ourselves */
@@ -3216,7 +3302,7 @@ emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
                        encode_value (ei->flags, p, &p);
                        encode_value (ei->exvar_offset, p, &p);
 
-                       if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
+                       if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
                                encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
                        else {
                                if (ei->data.catch_class) {
@@ -3247,6 +3333,16 @@ emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
                encode_method_ref (acfg, jinfo->method, p, &p);
        }
 
+       if (jinfo->has_try_block_holes) {
+               MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
+               for (i = 0; i < table->num_holes; ++i) {
+                       MonoTryBlockHoleJitInfo *hole = &table->holes [i];
+                       encode_value (hole->clause, p, &p);
+                       encode_value (hole->length, p, &p);
+                       encode_value (hole->offset, p, &p);
+               }
+       }
+
        if (seq_points) {
                int il_offset, native_offset, last_il_offset, last_native_offset, j;
 
@@ -4821,6 +4917,8 @@ emit_extra_methods (MonoAotCompile *acfg)
 
                nmethods ++;
 
+               method = cfg->method_to_register;
+
                name = NULL;
                if (method->wrapper_type) {
                        /* 
index 31900e6b9b4125eebdd9c8fa3fba73649ce1004a..f15bee6bb5b726b299b880f0eea55c1611d9a091 100644 (file)
@@ -953,7 +953,7 @@ find_symbol (MonoDl *module, gpointer *globals, const char *name, gpointer *valu
 #define SHT_ARM_EXIDX 0x70000001
 #endif
 
-#ifdef HAVE_DL_ITERATE_PHDR
+#if defined(HAVE_DL_ITERATE_PHDR) && defined(PT_GNU_EH_FRAME)
 static int
 dl_callback (struct dl_phdr_info *info, size_t size, void *data)
 {
@@ -1208,7 +1208,7 @@ load_aot_module (MonoAssembly *assembly, gpointer user_data)
 
        assembly->image->aot_module = amodule;
  
-#ifdef HAVE_DL_ITERATE_PHDR
+#if defined(HAVE_DL_ITERATE_PHDR) && defined(PT_GNU_EH_FRAME)
        /* Lookup the address of the .eh_frame_hdr () section if available */
        dl_iterate_phdr (dl_callback, amodule);
 #endif 
@@ -1933,10 +1933,10 @@ decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain,
        int i, buf_len;
        MonoJitInfo *jinfo;
        guint used_int_regs, flags;
-       gboolean has_generic_jit_info, has_dwarf_unwind_info, has_clauses, has_seq_points;
+       gboolean has_generic_jit_info, has_dwarf_unwind_info, has_clauses, has_seq_points, has_try_block_holes;
        gboolean from_llvm;
        guint8 *p;
-       int generic_info_size;
+       int generic_info_size, try_holes_info_size, num_holes;
 
        /* Load the method info from the AOT file */
 
@@ -1947,6 +1947,8 @@ decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain,
        has_clauses = (flags & 4) != 0;
        has_seq_points = (flags & 8) != 0;
        from_llvm = (flags & 16) != 0;
+       has_try_block_holes = (flags & 32) != 0;
+
        if (has_dwarf_unwind_info) {
                guint32 offset;
 
@@ -1961,12 +1963,18 @@ decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain,
        else
                generic_info_size = 0;
 
+       if (has_try_block_holes) {
+               num_holes = decode_value (p, &p);
+               try_holes_info_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
+       } else {
+               num_holes = try_holes_info_size = 0;
+       }
        /* Exception table */
        if (has_clauses) {
                int num_clauses = decode_value (p, &p);
 
                jinfo = 
-                       mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * num_clauses) + generic_info_size);
+                       mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + (sizeof (MonoJitExceptionInfo) * num_clauses) + generic_info_size + try_holes_info_size);
                jinfo->num_clauses = num_clauses;
 
                for (i = 0; i < num_clauses; ++i) {
@@ -1984,7 +1992,7 @@ decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain,
 
                        ei->exvar_offset = decode_value (p, &p);
 
-                       if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
+                       if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
                                ei->data.filter = code + decode_value (p, &p);
                        else {
                                if (decode_value (p, &p))
@@ -1997,7 +2005,7 @@ decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain,
                }
        }
        else {
-               jinfo = mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + generic_info_size);
+               jinfo = mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO + generic_info_size + try_holes_info_size);
        }
 
        if (from_llvm) {
@@ -2036,6 +2044,23 @@ decode_exception_debug_info (MonoAotModule *amodule, MonoDomain *domain,
                jinfo->method = decode_method_ref_2 (amodule, p, &p);
        }
 
+       if (has_try_block_holes) {
+               MonoTryBlockHoleTableJitInfo *table;
+
+               jinfo->has_try_block_holes = 1;
+
+               table = mono_jit_info_get_try_block_hole_table_info (jinfo);
+               g_assert (table);
+
+               table->num_holes = (guint16)num_holes;
+               for (i = 0; i < num_holes; ++i) {
+                       MonoTryBlockHoleJitInfo *hole = &table->holes [i];
+                       hole->clause = decode_value (p, &p);
+                       hole->length = decode_value (p, &p);
+                       hole->offset = decode_value (p, &p);
+               }
+       }
+
        if (has_seq_points) {
                MonoSeqPointInfo *seq_points;
                int il_offset, native_offset, last_il_offset, last_native_offset, j;
@@ -2948,7 +2973,11 @@ mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
        g_assert (klass->inited);
 
        /* Find method index */
-       if (method->is_inflated && mono_method_is_generic_sharable_impl (method, FALSE)) {
+       if (method->is_inflated && mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE)) {
+               /* 
+                * For generic methods, we store the fully shared instance in place of the
+                * original method.
+                */
                method = mono_method_get_declaring_generic_method (method);
                method_index = mono_metadata_token_index (method->token) - 1;
        } else if (method->is_inflated || !method->token) {
@@ -3012,6 +3041,11 @@ mono_aot_get_method (MonoDomain *domain, MonoMethod *method)
                                return code;
                }
 
+               if (method_index == 0xffffff && method->is_inflated && mono_method_is_generic_sharable_impl_full (method, FALSE, TRUE)) {
+                       /* Partial sharing */
+                       method_index = find_extra_method (mini_get_shared_method (method), &amodule);
+               }
+
                if (method_index == 0xffffff) {
                        if (mono_aot_only && mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_AOT)) {
                                char *full_name;
@@ -3127,6 +3161,19 @@ find_aot_module (guint8 *code)
        return user_data.module;
 }
 
+void
+mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
+{
+       /*
+        * Since AOT code is only used in the root domain, 
+        * mono_domain_get () != mono_get_root_domain () means the calling method
+        * is AppDomain:InvokeInDomain, so this is the same check as in 
+        * mono_method_same_domain () but without loading the metadata for the method.
+        */
+       if (mono_domain_get () == mono_get_root_domain ())
+               mono_arch_patch_plt_entry (code, got, regs, addr);
+}
+
 /*
  * mono_aot_plt_resolve:
  *
@@ -3198,7 +3245,7 @@ mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code
        /* Patch the PLT entry with target which might be the actual method not a trampoline */
        plt_entry = mono_aot_get_plt_entry (code);
        g_assert (plt_entry);
-       mono_arch_patch_plt_entry (plt_entry, module->got, NULL, target);
+       mono_aot_patch_plt_entry (plt_entry, module->got, NULL, target);
 
        return target;
 #else
@@ -3830,6 +3877,11 @@ mono_aot_plt_resolve (gpointer aot_module, guint32 plt_info_offset, guint8 *code
        return NULL;
 }
 
+void
+mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
+{
+}
+
 gpointer
 mono_aot_get_method_from_vt_slot (MonoDomain *domain, MonoVTable *vtable, int slot)
 {
index 464dfa565cc2ee07d930a67d3f5d3693798231fb..65606e0d2b2e90403dbe9a77d332055f0d5095ef 100644 (file)
@@ -617,6 +617,108 @@ class Tests {
                return 0;
        }
 
+       public enum IntEnum {
+               A,B,C
+       }
+
+       public enum UintEnum : uint {
+               A,B,C
+       }
+
+       static bool TryCast<T> (object o) {
+               return o is T[];
+       }
+
+       public static int test_0_primitive_array_cast () {
+               object a = new int[1];
+               object b = new uint[1];
+               object c = new IntEnum[1];
+               object d = new UintEnum[1];
+
+               object[] arr = new object[] { a, b, c, d };
+               int err = 1;
+
+               foreach (var v in arr) {
+                       if (!TryCast<int> (v))
+                               return err;
+                       if (!TryCast<uint> (v))
+                               return err + 1;
+                       if (!TryCast<IntEnum> (v))
+                               return err + 2;
+                       if (!TryCast<UintEnum> (v))
+                               return err + 3;
+                       err += 4;
+               }
+
+               foreach (var v in arr) {
+                       if (!(v is int[]))
+                               return err;
+                       if (!(v is uint[]))
+                               return err;
+                       if (!(v is IntEnum[]))
+                               return err;
+                       if (!(v is UintEnum[]))
+                               return err;
+                       err += 4;
+               }
+               return 0;
+       }
+
+       public static int test_0_intptr_array_cast () {
+               object[] a = new object[] { new int[1], new uint[1] };
+               object[] b = new object[] { new long[1], new ulong[1] };
+               object[] c = new object[] { new IntPtr[1], new UIntPtr[1] };
+
+               int err = 1;
+               if (IntPtr.Size == 4) {
+                       foreach (var v in a) {
+                               if (!(v is IntPtr[]))
+                                       return err;
+                               if (!(v is IntPtr[]))
+                                       return err;
+                               err += 2;
+                       }
+                       foreach (var v in b) {
+                               if (v is IntPtr[])
+                                       return err;
+                               if (v is IntPtr[])
+                                       return err;
+                               err += 2;
+                       }
+
+                       foreach (var v in c) {
+                               if (!(v is int[]))
+                                       return err;
+                               if (!(v is uint[]))
+                                       return err;
+                               err += 2;
+                       }
+               } else {
+                       foreach (var v in a) {
+                               if (v is IntPtr[])
+                                       return err;
+                               if (v is IntPtr[])
+                                       return err;
+                               err += 2;
+                       }
+                       foreach (var v in b) {
+                               if (!(v is IntPtr[]))
+                                       return err;
+                               if (!(v is IntPtr[]))
+                                       return err;
+                               err += 2;
+                       }
+                       foreach (var v in c) {
+                               if (!(v is long[]))
+                                       return err;
+                               if (!(v is ulong[]))
+                                       return err;
+                               err += 2;
+                       }
+               }
+               return 0;
+       }
+
        public static int long_indices () {
                int[] arr = new int [10];
                int[,] arr2 = new int [10, 10];
index f03c47ef4507f16b128c03d8f64bce4a2b8a8129..9784983e184f245f97c1b7d63edc0ca6b9ba4fcc 100644 (file)
@@ -3122,6 +3122,20 @@ public class SimdTests {
                return 0;
        }
 
+
+       public static int test_0_scala_vector4f_mul () {
+               Vector4f a = new Vector4f (1, 2, 3, 4);
+               Vector4f b = 2 * a;
+               Vector4f c = a * 3;
+
+               if (b.X != 2f || b.Y != 4f || b.Z != 6f || b.W != 8f )
+                       return 1;
+               if (c.X != 3f || c.Y != 6f || c.Z != 9f || c.W != 12f )
+                       return 1;
+
+               return 0;
+       }
+
        public static int Main (String[] args) {
                return TestDriver.RunTests (typeof (SimdTests), args);
        }
index 8f8a5078da00a13cb07c5415b7d0b27cf25f6500..d0de41a208cc0a2293c32b9a2e7af256411dafb3 100644 (file)
@@ -92,7 +92,7 @@ cond_exc_no: len:8
 cond_exc_ov: len:8
 div_imm: dest:i src1:i src2:i len:24
 div_un_imm: dest:i src1:i src2:i len:24
-endfinally: len:28
+endfinally: len:8
 fcall: dest:g len:26 clob:c
 fcall_membase: dest:g src1:b len:14 clob:c
 fcall_reg: dest:g src1:i len:10 clob:c
@@ -262,7 +262,7 @@ int_shr_un: dest:i src1:i src2:i clob:s len:12
 int_shr_un_imm: dest:i src1:i len:10
 int_subcc: dest:i src1:i src2:i len:12
 int_sub: dest:i src1:i src2:i len:12
-int_sub_imm: dest:i src1:i len:18
+int_sub_imm: dest:i src1:i len:20
 int_xor: dest:i src1:i src2:i len:12
 int_xor_imm: dest:i src1:i len:24
 int_conv_to_r4: dest:f src1:i len:16
index 1ca3f469918abe0aaac12317cf989a361c0ccb6a..12322925ee1204b4465a686398b26f307304e3fa 100644 (file)
@@ -14,6 +14,9 @@
 #ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
+#ifdef HAVE_SYS_SELECT_H
+#include <sys/select.h>
+#endif
 #ifdef HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
@@ -339,7 +342,8 @@ typedef enum {
        CMD_THREAD_GET_FRAME_INFO = 1,
        CMD_THREAD_GET_NAME = 2,
        CMD_THREAD_GET_STATE = 3,
-       CMD_THREAD_GET_INFO = 4
+       CMD_THREAD_GET_INFO = 4,
+       CMD_THREAD_GET_ID = 5
 } CmdThread;
 
 typedef enum {
@@ -535,6 +539,9 @@ static GHashTable *loaded_classes;
 /* Assemblies whose assembly load event has no been sent yet */
 static GPtrArray *pending_assembly_loads;
 
+/* Types whose type load event has no been sent yet */
+static GPtrArray *pending_type_loads;
+
 /* Whenever the debugger thread has exited */
 static gboolean debugger_thread_exited;
 
@@ -597,6 +604,8 @@ static void stop_single_stepping (void);
 
 static void suspend_current (void);
 
+static void clear_event_requests_for_assembly (MonoAssembly *assembly);
+
 /* Submodule init/cleanup */
 static void breakpoints_init (void);
 static void breakpoints_cleanup (void);
@@ -759,7 +768,7 @@ mono_debugger_agent_init (void)
 
        debugger_tls_id = TlsAlloc ();
 
-       thread_to_tls = mono_g_hash_table_new (NULL, NULL);
+       thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
        MONO_GC_REGISTER_ROOT (thread_to_tls);
 
        tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
@@ -770,6 +779,7 @@ mono_debugger_agent_init (void)
 
        loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
        pending_assembly_loads = g_ptr_array_new ();
+       pending_type_loads = g_ptr_array_new ();
 
        log_level = agent_config.log_level;
 
@@ -2413,7 +2423,7 @@ process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
                info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
        }
 
-       DEBUG (1, fprintf (stderr, "\tFrame: %s %d %d %d\n", mono_method_full_name (method, TRUE), info->native_offset, info->il_offset, info->managed));
+       DEBUG (1, fprintf (log_file, "\tFrame: %s %d %d %d\n", mono_method_full_name (method, TRUE), info->native_offset, info->il_offset, info->managed));
 
        if (!info->managed && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD) {
                /*
@@ -2911,6 +2921,8 @@ static void
 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
 {
        process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
+
+       clear_event_requests_for_assembly (assembly);
 }
 
 static void
@@ -2967,6 +2979,21 @@ end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
        mono_loader_unlock ();
 }
 
+static void
+send_type_load (MonoClass *klass)
+{
+       gboolean type_load = FALSE;
+
+       mono_loader_lock ();
+       if (!g_hash_table_lookup (loaded_classes, klass)) {
+               type_load = TRUE;
+               g_hash_table_insert (loaded_classes, klass, klass);
+       }
+       mono_loader_unlock ();
+       if (type_load)
+               process_profiler_event (EVENT_KIND_TYPE_LOAD, klass);
+}
+
 static void
 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
 {
@@ -2976,8 +3003,6 @@ jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
         * loader lock held. They could also occur in the debugger thread.
         * Same for assembly load events.
         */
-       gboolean type_load = FALSE;
-
        while (TRUE) {
                MonoAssembly *assembly = NULL;
 
@@ -2995,14 +3020,30 @@ jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
                        break;
        }
 
-       mono_loader_lock ();
-       if (!g_hash_table_lookup (loaded_classes, method->klass)) {
-               type_load = TRUE;
-               g_hash_table_insert (loaded_classes, method->klass, method->klass);
+       if (!vm_start_event_sent) {
+               /* Save these so they can be sent after the vm start event */
+               mono_loader_lock ();
+               g_ptr_array_add (pending_type_loads, method->klass);
+               mono_loader_unlock ();
+       } else {
+               /* Send all pending type load events */
+               MonoClass *klass;
+               while (TRUE) {
+                       klass = NULL;
+                       mono_loader_lock ();
+                       if (pending_type_loads->len > 0) {
+                               klass = g_ptr_array_index (pending_type_loads, 0);
+                               g_ptr_array_remove_index (pending_type_loads, 0);
+                       }
+                       mono_loader_unlock ();
+                       if (klass)
+                               send_type_load (klass);
+                       else
+                               break;
+               }
+
+               send_type_load (method->klass);
        }
-       mono_loader_unlock ();
-       if (type_load)
-               process_profiler_event (EVENT_KIND_TYPE_LOAD, method->klass);
 
        if (!result)
                add_pending_breakpoints (method, jinfo);
@@ -3018,7 +3059,6 @@ jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
 typedef struct {
        long il_offset, native_offset;
        guint8 *ip;
-       gboolean pending, entry;
        MonoJitInfo *ji;
 } BreakpointInstance;
 
@@ -3034,7 +3074,6 @@ typedef struct {
         */
        MonoMethod *method;
        long il_offset;
-       gboolean pending, entry;
        EventRequest *req;
        /* 
         * A list of BreakpointInstance structures describing where the breakpoint
@@ -3082,7 +3121,7 @@ static void
 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoJitInfo *ji, MonoBreakpoint *bp)
 {
        int i, count;
-       gint32 il_offset, native_offset;
+       gint32 il_offset = -1, native_offset;
        BreakpointInstance *inst;
 
        native_offset = 0;
@@ -3118,6 +3157,8 @@ insert_breakpoint (MonoSeqPointInfo *seq_points, MonoJitInfo *ji, MonoBreakpoint
                NOT_IMPLEMENTED;
 #endif
        }
+
+       DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)il_offset));      
 }
 
 static void
@@ -3143,6 +3184,12 @@ remove_breakpoint (BreakpointInstance *inst)
 #endif
 }      
 
+static inline gboolean
+bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
+{
+       return (!bp->method || method == bp->method || (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method));
+}
+
 /*
  * add_pending_breakpoints:
  *
@@ -3151,7 +3198,7 @@ remove_breakpoint (BreakpointInstance *inst)
 static void
 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
 {
-       int i;
+       int i, j;
        MonoSeqPointInfo *seq_points;
        MonoDomain *domain;
 
@@ -3164,8 +3211,19 @@ add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
 
        for (i = 0; i < breakpoints->len; ++i) {
                MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
+               gboolean found = FALSE;
 
-               if (bp->pending && (bp->method == method || !bp->method || (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method))) {
+               if (!bp_matches_method (bp, method))
+                       continue;
+
+               for (j = 0; j < bp->children->len; ++j) {
+                       BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
+
+                       if (inst->ji == ji)
+                               found = TRUE;
+               }
+
+               if (!found) {
                        mono_domain_lock (domain);
                        seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
                        mono_domain_unlock (domain);
@@ -3208,15 +3266,8 @@ set_bp_in_method_cb (gpointer key, gpointer value, gpointer user_data)
        MonoBreakpoint *bp = user_data;
        MonoDomain *domain = mono_domain_get ();
 
-       if (bp->method) {
-               if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method) {
-                       /* Generic instance */
-                       set_bp_in_method (domain, method, seq_points, bp);
-               }
-       } else {
-               /* Method entry/exit */
+       if (bp_matches_method (bp, method))
                set_bp_in_method (domain, method, seq_points, bp);
-       }
 }
 
 /*
@@ -3230,13 +3281,11 @@ set_bp_in_method_cb (gpointer key, gpointer value, gpointer user_data)
 static MonoBreakpoint*
 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req)
 {
-       MonoSeqPointInfo *seq_points;
        MonoDomain *domain;
        MonoBreakpoint *bp;
 
        // FIXME: 
        // - suspend/resume the vm to prevent code patching problems
-       // - appdomains
        // - multiple breakpoints on the same location
        // - dynamic methods
        // - races
@@ -3251,22 +3300,7 @@ set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req)
 
        domain = mono_domain_get ();
        mono_domain_lock (domain);
-       if (method) {
-               seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
-               if (seq_points) {
-                       set_bp_in_method (domain, method, seq_points, bp);
-               } else {
-                       if (method->is_generic)
-                               /* There might be already JITted instances */
-                               g_hash_table_foreach (domain_jit_info (domain)->seq_points, set_bp_in_method_cb, bp);
-
-                       /* Not yet JITted */
-                       bp->pending = TRUE;
-               }
-       } else {
-               g_hash_table_foreach (domain_jit_info (domain)->seq_points, set_bp_in_method_cb, bp);
-               bp->pending = TRUE;
-       }
+       g_hash_table_foreach (domain_jit_info (domain)->seq_points, set_bp_in_method_cb, bp);
        mono_domain_unlock (domain);
 
        mono_loader_lock ();
@@ -3298,6 +3332,12 @@ clear_breakpoint (MonoBreakpoint *bp)
        g_free (bp);
 }
 
+static gboolean
+breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
+{
+       return bp->method && bp->method->klass->image->assembly == assembly;
+}
+
 static void
 process_breakpoint_inner (DebuggerTlsData *tls, MonoContext *ctx)
 {
@@ -4401,6 +4441,58 @@ clear_event_request (int req_id, int etype)
        mono_loader_unlock ();
 }
 
+static gboolean
+event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
+{
+       if (req->event_kind == EVENT_KIND_BREAKPOINT)
+               return breakpoint_matches_assembly (req->info, assembly);
+       else {
+               int i, j;
+
+               for (i = 0; i < req->nmodifiers; ++i) {
+                       Modifier *m = &req->modifiers [i];
+
+                       if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
+                               return TRUE;
+                       if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
+                               for (j = 0; m->data.assemblies [j]; ++j)
+                                       if (m->data.assemblies [j] == assembly)
+                                               return TRUE;
+                       }
+               }
+       }
+
+       return FALSE;
+}
+
+/*
+ * clear_event_requests_for_assembly:
+ *
+ *   Clear all events requests which reference ASSEMBLY.
+ */
+static void
+clear_event_requests_for_assembly (MonoAssembly *assembly)
+{
+       int i;
+       gboolean found;
+
+       mono_loader_lock ();
+       found = TRUE;
+       while (found) {
+               found = FALSE;
+               for (i = 0; i < event_requests->len; ++i) {
+                       EventRequest *req = g_ptr_array_index (event_requests, i);
+
+                       if (event_req_matches_assembly (req, assembly)) {
+                               clear_event_request (req->id, req->event_kind);
+                               found = TRUE;
+                               break;
+                       }
+               }
+       }
+       mono_loader_unlock ();
+}
+
 static void
 add_thread (gpointer key, gpointer value, gpointer user_data)
 {
@@ -4994,6 +5086,7 @@ event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
                                        return err;
                                req->modifiers [i].caught = decode_byte (p, &p, end);
                                req->modifiers [i].uncaught = decode_byte (p, &p, end);
+                               DEBUG(1, fprintf (log_file, "[dbg] \tEXCEPTION_ONLY filter (%s%s%s).\n", exc_class ? exc_class->name : "all", req->modifiers [i].caught ? ", caught" : "", req->modifiers [i].uncaught ? ", uncaught" : ""));
                                if (exc_class) {
                                        req->modifiers [i].data.exc_class = exc_class;
 
@@ -5450,6 +5543,8 @@ type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
                gpointer iter = NULL;
                MonoMethod *m;
 
+               mono_class_setup_methods (klass);
+
                nmethods = mono_class_num_methods (klass);
 
                buffer_add_int (buf, nmethods);
@@ -5980,6 +6075,9 @@ thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
        case CMD_THREAD_GET_INFO:
                buffer_add_byte (buf, thread->threadpool_thread);
                break;
+       case CMD_THREAD_GET_ID:
+               buffer_add_long (buf, (guint64)thread);
+               break;
        default:
                return ERR_NOT_IMPLEMENTED;
        }
index c3133b0990efa9b4a877fb367683027afbe89ad3..8fa6bb3eb3c00b8d2165ed54cc2eef8dcee851d6 100644 (file)
@@ -28,6 +28,7 @@ void mini_emit_initobj (MonoCompile *cfg, MonoInst *dest, const guchar *ip, Mono
  * Returns a MonoInst which represents the result of the decomposition, and can
  * be pushed on the IL stack. This is needed because the original instruction is
  * nullified.
+ * Sets the cfg exception if an opcode is not supported.
  */
 MonoInst*
 mono_decompose_opcode (MonoCompile *cfg, MonoInst *ins)
@@ -136,6 +137,7 @@ mono_decompose_opcode (MonoCompile *cfg, MonoInst *ins)
        case OP_ICONV_TO_I4:
        case OP_ICONV_TO_U4:
        case OP_ICONV_TO_OVF_I4:
+       case OP_ICONV_TO_OVF_U4_UN:
 #if SIZEOF_REGISTER == 4
        case OP_ICONV_TO_OVF_I:
        case OP_ICONV_TO_OVF_U_UN:
@@ -161,6 +163,20 @@ mono_decompose_opcode (MonoCompile *cfg, MonoInst *ins)
                ins->opcode = OP_FMOVE;
                break;
 
+       case OP_FCONV_TO_OVF_I1_UN:
+       case OP_FCONV_TO_OVF_I2_UN:
+       case OP_FCONV_TO_OVF_I4_UN:
+       case OP_FCONV_TO_OVF_I8_UN:
+       case OP_FCONV_TO_OVF_U1_UN:
+       case OP_FCONV_TO_OVF_U2_UN:
+       case OP_FCONV_TO_OVF_U4_UN:
+       case OP_FCONV_TO_OVF_U8_UN:
+       case OP_FCONV_TO_OVF_I_UN:
+       case OP_FCONV_TO_OVF_U_UN:
+               cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
+               cfg->exception_message = g_strdup_printf ("float conv.ovf.un opcodes not supported.");
+               break;
+
                /* Long opcodes on 64 bit machines */
 #if SIZEOF_REGISTER == 8
        case OP_LCONV_TO_I4:
index 3607a96baa9e1af401ca4e8c3188221b0f109c56..3f885b0547c2abf9f17919b8b0bff12d7b44fb61 100644 (file)
@@ -133,7 +133,7 @@ opt_funcs [sizeof (int) * 8] = {
        MONO_OPT_SIMD | \
        MONO_OPT_AOT)
 
-#define EXCLUDED_FROM_ALL (MONO_OPT_SHARED | MONO_OPT_PRECOMP)
+#define EXCLUDED_FROM_ALL (MONO_OPT_SHARED | MONO_OPT_PRECOMP | MONO_OPT_UNSAFE)
 
 static guint32
 parse_optimizations (const char* p)
@@ -1339,6 +1339,8 @@ mono_main (int argc, char* argv[])
        g_log_set_always_fatal (G_LOG_LEVEL_ERROR);
        g_log_set_fatal_mask (G_LOG_DOMAIN, G_LOG_LEVEL_ERROR);
 
+       mono_use_llvm = getenv ("MONO_USE_LLVM") != NULL;
+
        opt = parse_optimizations (NULL);
 
        for (i = 1; i < argc; ++i) {
@@ -1628,6 +1630,12 @@ mono_main (int argc, char* argv[])
        }
 #endif
 
+       /*
+        * This must be called before mono_debug_init(), because the
+        * latter registers GC roots.
+        */
+       mono_gc_base_init ();
+
        if (action == DO_DEBUGGER) {
                enable_debugging = TRUE;
 
@@ -1770,6 +1778,7 @@ mono_main (int argc, char* argv[])
         * shut down), it will crash:
         * http://mail-archives.apache.org/mod_mbox/harmony-dev/200801.mbox/%3C200801130327.41572.gshimansky@apache.org%3E
         * Testcase: tests/main-exit-background-change.exe.
+        * Testcase: test/main-returns-background-abort-resetabort.exe.
         * To make this race less frequent, we avoid freeing the global code manager.
         * Since mono_main () is hopefully only used by the runtime executable, this 
         * will only cause a shutdown leak. This workaround also has the advantage
@@ -1777,8 +1786,11 @@ mono_main (int argc, char* argv[])
         * FIXME: Fix this properly by waiting for threads to really exit using 
         * pthread_join (). This cannot be done currently as the io-layer calls
         * pthread_detach ().
+        *
+        * This used to be an amd64 only crash, but it looks like now most glibc targets do unwinding
+        * that requires reading the target code.
         */
-#ifdef __x86_64__
+#ifdef __linux__
                mono_dont_free_global_codeman = TRUE;
 #endif
 
@@ -1822,6 +1834,7 @@ mono_main (int argc, char* argv[])
                return 3;
        }
 
+#ifndef DISABLE_JIT
        if (action == DO_DRAW) {
                int part = 0;
 
@@ -1913,6 +1926,7 @@ mono_main (int argc, char* argv[])
                cfg = mini_method_compile (method, opt, mono_get_root_domain (), FALSE, FALSE, 0);
                mono_destroy_compile (cfg);
        }
+#endif
 
        mini_cleanup (domain);
        return 0;
index fede465efb2c046cb00cd790f70f469c02e09e8e..7ab4d62976dfa514b8a3756e945be6b1127a62c1 100644 (file)
@@ -698,7 +698,7 @@ mono_arch_handle_exception (void *sigctx, gpointer obj, gboolean test_only)
        return TRUE;
 }
 
-#ifdef MONO_ARCH_USE_SIGACTION
+#if defined(MONO_ARCH_USE_SIGACTION) && defined(UCONTEXT_GREGS)
 static inline guint64*
 gregs_from_ucontext (ucontext_t *ctx)
 {
@@ -708,7 +708,7 @@ gregs_from_ucontext (ucontext_t *ctx)
 void
 mono_arch_sigctx_to_monoctx (void *sigctx, MonoContext *mctx)
 {
-#ifdef MONO_ARCH_USE_SIGACTION
+#if defined(MONO_ARCH_USE_SIGACTION) && defined(UCONTEXT_GREGS)
        ucontext_t *ctx = (ucontext_t*)sigctx;
 
     guint64 *gregs = gregs_from_ucontext (ctx);
@@ -726,6 +726,22 @@ mono_arch_sigctx_to_monoctx (void *sigctx, MonoContext *mctx)
        mctx->r13 = gregs [REG_R13];
        mctx->r14 = gregs [REG_R14];
        mctx->r15 = gregs [REG_R15];
+#elif defined(MONO_ARCH_USE_SIGACTION)
+       ucontext_t *ctx = (ucontext_t*)sigctx;
+
+       mctx->rax = UCONTEXT_REG_RAX (ctx);
+       mctx->rbx = UCONTEXT_REG_RBX (ctx);
+       mctx->rcx = UCONTEXT_REG_RCX (ctx);
+       mctx->rdx = UCONTEXT_REG_RDX (ctx);
+       mctx->rbp = UCONTEXT_REG_RBP (ctx);
+       mctx->rsp = UCONTEXT_REG_RSP (ctx);
+       mctx->rsi = UCONTEXT_REG_RSI (ctx);
+       mctx->rdi = UCONTEXT_REG_RDI (ctx);
+       mctx->rip = UCONTEXT_REG_RIP (ctx);
+       mctx->r12 = UCONTEXT_REG_R12 (ctx);
+       mctx->r13 = UCONTEXT_REG_R13 (ctx);
+       mctx->r14 = UCONTEXT_REG_R14 (ctx);
+       mctx->r15 = UCONTEXT_REG_R15 (ctx);
 #else
        MonoContext *ctx = (MonoContext *)sigctx;
 
@@ -748,7 +764,7 @@ mono_arch_sigctx_to_monoctx (void *sigctx, MonoContext *mctx)
 void
 mono_arch_monoctx_to_sigctx (MonoContext *mctx, void *sigctx)
 {
-#ifdef MONO_ARCH_USE_SIGACTION
+#if defined(MONO_ARCH_USE_SIGACTION) && defined(UCONTEXT_GREGS)
        ucontext_t *ctx = (ucontext_t*)sigctx;
 
     guint64 *gregs = gregs_from_ucontext (ctx);
@@ -766,6 +782,22 @@ mono_arch_monoctx_to_sigctx (MonoContext *mctx, void *sigctx)
        gregs [REG_R13] = mctx->r13;
        gregs [REG_R14] = mctx->r14;
        gregs [REG_R15] = mctx->r15;
+#elif defined(MONO_ARCH_USE_SIGACTION)
+       ucontext_t *ctx = (ucontext_t*)sigctx;
+
+       UCONTEXT_REG_RAX (ctx) = mctx->rax;
+       UCONTEXT_REG_RBX (ctx) = mctx->rbx;
+       UCONTEXT_REG_RCX (ctx) = mctx->rcx;
+       UCONTEXT_REG_RDX (ctx) = mctx->rdx;
+       UCONTEXT_REG_RBP (ctx) = mctx->rbp;
+       UCONTEXT_REG_RSP (ctx) = mctx->rsp;
+       UCONTEXT_REG_RSI (ctx) = mctx->rsi;
+       UCONTEXT_REG_RDI (ctx) = mctx->rdi;
+       UCONTEXT_REG_RIP (ctx) = mctx->rip;
+       UCONTEXT_REG_R12 (ctx) = mctx->r12;
+       UCONTEXT_REG_R13 (ctx) = mctx->r13;
+       UCONTEXT_REG_R14 (ctx) = mctx->r14;
+       UCONTEXT_REG_R15 (ctx) = mctx->r15;
 #else
        MonoContext *ctx = (MonoContext *)sigctx;
 
@@ -788,14 +820,16 @@ mono_arch_monoctx_to_sigctx (MonoContext *mctx, void *sigctx)
 gpointer
 mono_arch_ip_from_context (void *sigctx)
 {
-       
-#ifdef MONO_ARCH_USE_SIGACTION
-
+#if defined(MONO_ARCH_USE_SIGACTION) && defined(UCONTEXT_GREGS)
        ucontext_t *ctx = (ucontext_t*)sigctx;
 
     guint64 *gregs = gregs_from_ucontext (ctx);
 
        return (gpointer)gregs [REG_RIP];
+#elif defined(MONO_ARCH_USE_SIGACTION)
+       ucontext_t *ctx = (ucontext_t*)sigctx;
+
+       return (gpointer)UCONTEXT_REG_RIP (ctx);
 #else
        MonoContext *ctx = sigctx;
        return (gpointer)ctx->rip;
@@ -852,7 +886,7 @@ altstack_handle_and_restore (void *sigctx, gpointer obj, gboolean stack_ovf)
 void
 mono_arch_handle_altstack_exception (void *sigctx, gpointer fault_addr, gboolean stack_ovf)
 {
-#ifdef MONO_ARCH_USE_SIGACTION
+#if defined(MONO_ARCH_USE_SIGACTION) && defined(UCONTEXT_GREGS)
        MonoException *exc = NULL;
        ucontext_t *ctx = (ucontext_t*)sigctx;
        guint64 *gregs = gregs_from_ucontext (ctx);
index f9c486c594ddc8c39bc2640d29d7481f8474b63b..bc17e5509d0fd9c0ccf6ba842ec52d6631ac47b7 100644 (file)
 #include <glib.h>
 #include <signal.h>
 #include <string.h>
+#ifdef HAVE_ASM_SIGCONTEXT_H
+#include <asm/sigcontext.h>
+#endif  /* def HAVE_ASM_SIGCONTEXT_H */
+#ifdef HAVE_UCONTEXT_H
 #include <ucontext.h>
+#endif  /* def HAVE_UCONTEXT_H */
 
 #include <mono/arch/arm/arm-codegen.h>
 #include <mono/metadata/appdomain.h>
index 91d7859f5795e203ccc0e5177091213d8f0437a9..abb48d2a0516ca70fe6382fcc59a9614d7ba8bdc 100644 (file)
@@ -27,7 +27,7 @@
 
 #define S390_THROWSTACK_ACCPRM         S390_MINIMAL_STACK_SIZE
 #define S390_THROWSTACK_FPCPRM         (S390_THROWSTACK_ACCPRM+sizeof(gpointer))
-#define S390_THROWSTACK_RETHROW                (S390_THROWSTACK_FPCPRM+sizeof(gint32))
+#define S390_THROWSTACK_RETHROW                (S390_THROWSTACK_FPCPRM+sizeof(gulong))
 #define S390_THROWSTACK_INTREGS                (S390_THROWSTACK_RETHROW+sizeof(gboolean))
 #define S390_THROWSTACK_FLTREGS                (S390_THROWSTACK_INTREGS+(16*sizeof(gulong)))
 #define S390_THROWSTACK_ACCREGS                (S390_THROWSTACK_FLTREGS+(16*sizeof(gdouble)))
@@ -74,6 +74,12 @@ gboolean mono_arch_handle_exception (void     *ctx,
 /*                 G l o b a l   V a r i a b l e s                  */
 /*------------------------------------------------------------------*/
 
+typedef enum {
+       by_none,
+       by_name,
+       by_token
+} throwType;
+
 /*====================== End of Global Variables ===================*/
 
 /*------------------------------------------------------------------*/
@@ -128,21 +134,21 @@ mono_arch_get_call_filter (void)
        /*------------------------------------------------------*/
        /* save general registers on stack                      */
        /*------------------------------------------------------*/
-       s390_stmg (code, s390_r0, s390_r13, STK_BASE, S390_CALLFILTER_INTREGS);
+       s390_stmg (code, s390_r0, STK_BASE, STK_BASE, S390_CALLFILTER_INTREGS);
 
        /*------------------------------------------------------*/
        /* save floating point registers on stack               */
        /*------------------------------------------------------*/
-//     pos = S390_CALLFILTER_FLTREGS;
-//     for (i = 0; i < 16; ++i) {
-//             s390_std (code, i, 0, STK_BASE, pos);
-//             pos += sizeof (gdouble);
-//     }
+       pos = S390_CALLFILTER_FLTREGS;
+       for (i = 0; i < 16; ++i) {
+               s390_std (code, i, 0, STK_BASE, pos);
+               pos += sizeof (gdouble);
+       }
 
        /*------------------------------------------------------*/
        /* save access registers on stack                       */
        /*------------------------------------------------------*/
-//     s390_stam (code, s390_a0, s390_a15, STK_BASE, S390_CALLFILTER_ACCREGS);
+       s390_stam (code, s390_a0, s390_a15, STK_BASE, S390_CALLFILTER_ACCREGS);
 
        /*------------------------------------------------------*/
        /* Get A(Context)                                       */
@@ -171,7 +177,7 @@ mono_arch_get_call_filter (void)
        }
        
        /*------------------------------------------------------*/
-       /* Point at the copied stack frame and call the filter  */
+       /* Go call filter                                       */
        /*------------------------------------------------------*/
        s390_lgr  (code, s390_r1, s390_r0);
        s390_basr (code, s390_r14, s390_r1);
@@ -185,14 +191,14 @@ mono_arch_get_call_filter (void)
        /* Restore all the regs from the stack                  */
        /*------------------------------------------------------*/
        s390_lmg  (code, s390_r0, s390_r13, STK_BASE, S390_CALLFILTER_INTREGS);
-//     pos = S390_CALLFILTER_FLTREGS;
-//     for (i = 0; i < 16; ++i) {
-//             s390_ld (code, i, 0, STK_BASE, pos);
-//             pos += sizeof (gdouble);
-//     }
+       pos = S390_CALLFILTER_FLTREGS;
+       for (i = 0; i < 16; ++i) {
+               s390_ld (code, i, 0, STK_BASE, pos);
+               pos += sizeof (gdouble);
+       }
 
        s390_lgr  (code, s390_r2, s390_r14);
-//     s390_lam  (code, s390_a0, s390_a15, STK_BASE, S390_CALLFILTER_ACCREGS);
+       s390_lam  (code, s390_a0, s390_a15, STK_BASE, S390_CALLFILTER_ACCREGS);
        s390_aghi (code, s390_r15, alloc_size);
        s390_lmg  (code, s390_r6, s390_r14, STK_BASE, S390_REG_SAVE_OFFSET);
        s390_br   (code, s390_r14);
@@ -218,13 +224,17 @@ throw_exception (MonoObject *exc, unsigned long ip, unsigned long sp,
 {
        MonoContext ctx;
        int iReg;
+       static void (*restore_context) (MonoContext *);
+
+       if (!restore_context)
+               restore_context = mono_arch_get_restore_context();
        
        memset(&ctx, 0, sizeof(ctx));
 
        getcontext(&ctx);
 
        /* adjust eip so that it point into the call instruction */
-       ip -= 6;
+       ip -= 2;
 
        for (iReg = 0; iReg < 16; iReg++) {
                ctx.uc_mcontext.gregs[iReg]         = int_regs[iReg];
@@ -243,7 +253,7 @@ throw_exception (MonoObject *exc, unsigned long ip, unsigned long sp,
                        mono_ex->stack_trace = NULL;
        }
        mono_arch_handle_exception (&ctx, exc, FALSE);
-       setcontext(&ctx);
+       restore_context(&ctx);
 
        g_assert_not_reached ();
 }
@@ -264,7 +274,7 @@ throw_exception (MonoObject *exc, unsigned long ip, unsigned long sp,
 
 static gpointer 
 get_throw_exception_generic (guint8 *start, int size, 
-                            int by_name, gboolean rethrow)
+                            throwType type, gboolean rethrow)
 {
        guint8 *code;
        int alloc_size, pos, i;
@@ -276,17 +286,33 @@ get_throw_exception_generic (guint8 *start, int size,
        s390_lgr  (code, s390_r14, STK_BASE);
        s390_aghi (code, STK_BASE, -alloc_size);
        s390_stg  (code, s390_r14, 0, STK_BASE, 0);
-       if (by_name) {
+       switch (type) {
+       case by_name : 
                s390_lgr  (code, s390_r4, s390_r2);
+               s390_lg   (code, s390_r3, 0, s390_r2, G_STRUCT_OFFSET(MonoException, object));
                s390_basr (code, s390_r13, 0);
-               s390_j    (code, 14);
+               s390_j    (code, 10);
                s390_llong(code, mono_defaults.corlib);
-               s390_llong(code, "System");
                s390_llong(code, mono_exception_from_name);
+               s390_lg   (code, s390_r3, 0, s390_r3, G_STRUCT_OFFSET(MonoVTable, klass));
+               s390_lg   (code, s390_r2, 0, s390_r13, 4);
+               s390_lg   (code, s390_r1, 0, s390_r13, 12);
+               s390_lg   (code, s390_r4, 0, s390_r3, G_STRUCT_OFFSET(MonoClass, name));
+               s390_lg   (code, s390_r3, 0, s390_r3, G_STRUCT_OFFSET(MonoClass, name_space));
+               s390_basr (code, s390_r14, s390_r1);
+               break;
+       case by_token : 
+               s390_lgr  (code, s390_r3, s390_r2);
+               s390_basr (code, s390_r13, 0);
+               s390_j    (code, 10);
+               s390_llong(code, mono_defaults.exception_class->image);
+               s390_llong(code, mono_exception_from_token);
                s390_lg   (code, s390_r2, 0, s390_r13, 4);
-               s390_lg   (code, s390_r3, 0, s390_r13, 12);
-               s390_lg   (code, s390_r1, 0, s390_r13, 20);
+               s390_lg   (code, s390_r1, 0, s390_r13, 12);
                s390_basr (code, s390_r14, s390_r1);
+               break;
+       case by_none :
+               break;
        }
        /*------------------------------------------------------*/
        /* save the general registers on the stack              */
@@ -314,10 +340,11 @@ get_throw_exception_generic (guint8 *start, int size,
        s390_stam (code, s390_r0, s390_r15, STK_BASE, S390_THROWSTACK_ACCREGS);
 
        /*------------------------------------------------------*/
-       /* call throw_exception (exc, ip, sp, gr, fr, ar)       */
-       /* exc is already in place in r2                        */
+       /* call throw_exception (tkn, ip, sp, gr, fr, ar, re)   */
+       /* - r2 already contains *exc                           */
        /*------------------------------------------------------*/
        s390_lgr  (code, s390_r4, s390_r1);        /* caller sp */
+
        /*------------------------------------------------------*/
        /* pointer to the saved int regs                        */
        /*------------------------------------------------------*/
@@ -325,7 +352,7 @@ get_throw_exception_generic (guint8 *start, int size,
        s390_la   (code, s390_r6, 0, STK_BASE, S390_THROWSTACK_FLTREGS);
        s390_la   (code, s390_r7, 0, STK_BASE, S390_THROWSTACK_ACCREGS);
        s390_stg  (code, s390_r7, 0, STK_BASE, S390_THROWSTACK_ACCPRM);
-       s390_stfpc(code, STK_BASE, S390_THROWSTACK_FPCPRM);
+       s390_stfpc(code, STK_BASE, S390_THROWSTACK_FPCPRM+4);
        s390_lghi (code, s390_r7, rethrow);
        s390_stg  (code, s390_r7, 0, STK_BASE, S390_THROWSTACK_RETHROW);
        s390_basr (code, s390_r13, 0);
@@ -361,7 +388,7 @@ mono_arch_get_throw_exception (void)
        if (inited)
                return start;
        start = mono_global_codeman_reserve (SZ_THROW);
-       get_throw_exception_generic (start, SZ_THROW, FALSE, FALSE);
+       get_throw_exception_generic (start, SZ_THROW, by_none, FALSE);
        inited = 1;
        return start;
 }
@@ -395,6 +422,33 @@ mono_arch_get_rethrow_exception (void)
 
 /*========================= End of Function ========================*/
 
+/*------------------------------------------------------------------*/
+/*                                                                  */
+/* Name                - arch_get_corlib_exception                         */
+/*                                                                  */
+/* Function    - Return a function pointer which can be used to    */
+/*                raise corlib exceptions. The return function has  */
+/*                the following signature:                          */
+/*                void (*func) (guint32 token, guint32 offset)     */
+/*                                                                  */
+/*------------------------------------------------------------------*/
+
+gpointer 
+mono_arch_get_throw_corlib_exception(void)
+{
+       static guint8 *start;
+       static int inited = 0;
+
+       if (inited)
+               return start;
+       start = mono_global_codeman_reserve (SZ_THROW);
+       get_throw_exception_generic (start, SZ_THROW, by_token, FALSE);
+       inited = 1;
+       return start;
+}      
+
+/*========================= End of Function ========================*/
+
 /*------------------------------------------------------------------*/
 /*                                                                  */
 /* Name                - arch_get_throw_exception_by_name                  */
@@ -415,7 +469,7 @@ mono_arch_get_throw_exception_by_name (void)
        if (inited)
                return start;
        start = mono_global_codeman_reserve (SZ_THROW);
-       get_throw_exception_generic (start, SZ_THROW, TRUE, FALSE);
+       get_throw_exception_generic (start, SZ_THROW, by_name, FALSE);
        inited = 1;
        return start;
 }      
index d1901330dda11b3c64d4bae67e5f574a9b175316..a75e3ad59a8f5c5a21a2c5a0b29374f3787d9914 100644 (file)
@@ -563,10 +563,54 @@ class Tests {
                return 0;
        }
 
+       public static int test_0_partial_sharing () {
+               if (PartialShared1 (new List<string> (), 1) != typeof (string))
+                       return 1;
+               if (PartialShared1 (new List<Tests> (), 1) != typeof (Tests))
+                       return 2;
+               if (PartialShared2 (new List<string> (), 1) != typeof (int))
+                       return 3;
+               if (PartialShared2 (new List<Tests> (), 1) != typeof (int))
+                       return 4;
+               return 0;
+       }
+
+       public static int test_6_partial_sharing_linq () {
+               var messages = new List<Message> ();
+
+               messages.Add (new Message () { MessageID = 5 });
+               messages.Add (new Message () { MessageID = 6 });
+
+               return messages.Max(i => i.MessageID);
+       }
+
+       public static int test_0_partial_shared_method_in_nonshared_class () {
+               var c = new Class1<double> ();
+               return (c.Foo<string> (5).GetType () == typeof (Class1<string>)) ? 0 : 1;
+       }
+
+       class Message {
+               public int MessageID {
+                       get; set;
+               }
+       }
+
+       public static Type PartialShared1<T, K> (List<T> list, K k) {
+               return typeof (T);
+       }
+
+       public static Type PartialShared2<T, K> (List<T> list, K k) {
+               return typeof (K);
+       }
+
     public class Class1<T> {
                public virtual void Do (Class2<T> t) {
                        t.Foo ();
                }
+
+               public virtual object Foo<U> (T t) {
+                       return new Class1<U> ();
+               }
        }
 
        public interface IFace1<T> {
index ef840c63cb1701d6150004f56cc7fa5e51d73173..7d34d3561a89e5460ba5b29a23ace680680025f2 100644 (file)
 #include <string.h>
 #include <mono/metadata/opcodes.h>
 
+#define MINI_OP(a,b,dest,src1,src2) b,
+#define MINI_OP3(a,b,dest,src1,src2,src3) b,
+/* keep in sync with the enum in mini.h */
+static const char* const
+opnames[] = {
+#include "mini-ops.h"
+};
+#undef MINI_OP
+#undef MINI_OP3
+
+/*
+ * Duplicate this from helpers.c, so the opcode name array can be omitted when 
+ * DISABLE_JIT is set.
+ */
+static const char*
+inst_name (int op) {
+       if (op >= OP_LOAD && op <= OP_LAST)
+               return opnames [op - OP_LOAD];
+       if (op < OP_LOAD)
+               return mono_opcode_name (op);
+       g_error ("unknown opcode name for %d", op);
+       return NULL;
+}
+
 typedef struct {
        int num;
        const char *name;
@@ -165,7 +189,7 @@ init_table (void) {
        for (i = OP_LOAD; i < OP_LAST; ++i) {
                desc = opcodes + i;
                desc->num = i;
-               desc->name = mono_inst_name (i);
+               desc->name = inst_name (i);
                g_hash_table_insert (table, (char *)desc->name, desc);
        }
 }
index af1235e317512555450b1e21e15e82fb1756237e..0e02f46ad9d41729dee48f66029a434085c19158 100644 (file)
@@ -11,6 +11,8 @@
 #include <unistd.h>
 #endif
 
+#ifndef DISABLE_LOGGING
+
 #ifdef MINI_OP
 #undef MINI_OP
 #endif
@@ -56,6 +58,8 @@ opnames[] = {
 
 #endif
 
+#endif /* DISABLE_LOGGING */
+
 #if defined(__i386__) || defined(__x86_64__)
 #define emit_debug_info  TRUE
 #else
@@ -67,6 +71,7 @@ opnames[] = {
 
 const char*
 mono_inst_name (int op) {
+#ifndef DISABLE_LOGGING
        if (op >= OP_LOAD && op <= OP_LAST)
 #ifdef HAVE_ARRAY_ELEM_INIT
                return (const char*)&opstr + opidx [op - OP_LOAD];
@@ -77,6 +82,9 @@ mono_inst_name (int op) {
                return mono_opcode_name (op);
        g_error ("unknown opcode name for %d", op);
        return NULL;
+#else
+       g_assert_not_reached ();
+#endif
 }
 
 void
index 1363799ad4b4bb53e3b190963a950cd321d29cd9..d151b2d9f62329479a29c8bcfd2079af22141380 100644 (file)
@@ -957,7 +957,7 @@ COND:   ldloc.0
                ret
        }
 
-#if !defined(__ppc__) && !defined(__powerpc__) && !defined(__arm__)
+#if !defined(__ppc__) && !defined(__powerpc__) && !defined(__arm__) && !defined(__sparc__)
        // PPC handles overflow by clipping, but this test assumes
        // no overflow handling.  According to ECMA the result of
        // float->int conversion is undefined if overflow occurs, so
@@ -1116,6 +1116,18 @@ COND:   ldloc.0
         ret
        }
 
+       .method public static int32 test_7_conv_ovf_u4_un () {
+       .maxstack  2
+        .locals    init (unsigned int32)
+
+        ldc.i4.7
+        conv.ovf.u4.un
+        stloc.0
+               ldloc.0
+               conv.i4
+        ret
+       }
+
        .method public static int32 test_1_bug_74591 () {
                .maxstack 16
                .locals init (int32)
@@ -2448,4 +2460,117 @@ OK_2:
         IL_004b:  ret
     }
 
+       .method public static int32 test_2_leave_multiple_blocks_from_end ()
+       {
+               .locals init (int32 V_0)
+
+               .try {
+                       .try {
+                               nop
+                               nop
+                               leave END
+                       } finally {
+                               ldloc.0
+                               ldc.i4.1
+                               add
+                               stloc.0
+                               endfinally
+                       }
+                       nop
+                       leave END
+               } finally {
+                       ldloc.0
+                       ldc.i4.1
+                       add
+                       stloc.0
+                       endfinally
+               }
+END:
+               ldloc.0
+               ret
+       }
+
+       .method public static int32 test_3_leave_multiple_blocks_from_hole ()
+       {
+               .locals init (int32 V_0)
+
+               .try {
+                       .try {
+                               ldloc.0
+                               brtrue REST
+                               leave BEFORE_END
+REST:
+                               nop
+                               nop
+                               leave END
+                       } finally {
+                               ldloc.0
+                               ldc.i4.1
+                               add
+                               stloc.0
+                               endfinally
+                       }
+                       nop
+                       leave END
+               } finally {
+                       ldloc.0
+                       ldc.i4.1
+                       add
+                       stloc.0
+                       endfinally
+               }
+BEFORE_END:
+               ldloc.0
+               ldc.i4.1
+               add
+               stloc.0
+END:
+               ldloc.0
+               ret
+       }
+
+       .class nested private auto ansi sealed beforefieldinit Pair`2<TKey,TValue>
+                  extends [mscorlib]System.ValueType
+       {
+               .field  public  !0 key
+       .field  public  !1 'value'
+       }
+
+    .method private static hidebysig 
+           default bool ContentEquals<TKey,TValue> (valuetype Tests/Pair`2<!!TKey, !!TValue> v)  cil managed 
+    {
+       .maxstack 8
+       IL_0000:  ldarga.s 0 
+       IL_0006:  ldnull 
+                         constrained. valuetype Tests/Pair`2<!!0,!!1>
+       IL_0007:  callvirt instance bool class [mscorlib]System.Object::Equals(object)
+                         ret
+    }
+
+    .method public static hidebysig default int32 test_0_constrained_gshared_595863 () cil managed
+    {
+               .locals init (
+               valuetype Tests/Pair`2<string, string>  V_0,
+               valuetype Tests/Pair`2<string, string>  V_1)
+       IL_0000:  ldloca.s 0
+       IL_0002:  initobj valuetype Tests/Pair`2<string,string>
+       IL_0008:  ldloc.0 
+       IL_0009:  stloc.1 
+       IL_000a:  ldloca.s 1
+       IL_000c:  ldstr "A"
+       IL_0011:  stfld !0 valuetype Tests/Pair`2<string,string>::key
+       IL_0016:  ldloca.s 1
+       IL_0018:  ldstr "B"
+       IL_001d:  stfld !1 valuetype Tests/Pair`2<string,string>::'value'
+       IL_0022:  ldloc.1 
+       IL_0023:  stloc.0 
+       IL_0024:  ldloc.0 
+       IL_0025:  call bool class Tests::ContentEquals<string, string> (valuetype Tests/Pair`2<!!0,!!1>)
+                         brfalse SUCCESS
+                         ldc.i4.1
+                         ret
+       SUCCESS:
+                         ldc.i4.0
+                         ret
+    }
 }
index d60501ff651fbfcaa6789da9eb15e55f15839504..8b2242e3634f6a417891c297435d39dee7b983e1 100644 (file)
@@ -1175,7 +1175,7 @@ bin_writer_emit_writeout (MonoImageWriter *acfg)
        virt_offset = ALIGN_TO (virt_offset, secth [SECT_GOT_PLT].sh_addralign);
        secth [SECT_GOT_PLT].sh_addr = virt_offset;
        secth [SECT_GOT_PLT].sh_offset = file_offset;
-       size = 12;
+       size = 3 * SIZEOF_VOID_P;
        secth [SECT_GOT_PLT].sh_size = size;
        file_offset += size;
        virt_offset += size;
@@ -1260,6 +1260,11 @@ bin_writer_emit_writeout (MonoImageWriter *acfg)
        secth [SECT_STRTAB].sh_size = size;
        file_offset += size;
 
+       for (i = 1; i < SECT_NUM; ++i) {
+               if (section_info [i].esize != 0)
+                       g_assert (secth [i].sh_size % section_info [i].esize == 0);
+       }
+
        file_offset += 4-1;
        file_offset &= ~(4-1);
 
index 83bab8d4ee76bb1cb328c5e8793f086480381996..348802b65ecec93abc9c63a4eed1286a826f0c13 100755 (executable)
@@ -809,6 +809,7 @@ static int ccount = 0;
  * index_reg is the vreg holding the index
  */
 #define MONO_EMIT_BOUNDS_CHECK(cfg, array_reg, array_type, array_length_field, index_reg) do { \
+               if (!(cfg->opt & MONO_OPT_UNSAFE)) {                                                    \
                if (!(cfg->opt & MONO_OPT_ABCREM)) {                                                    \
                        MONO_EMIT_NULL_CHECK (cfg, array_reg);                                          \
                        MONO_ARCH_EMIT_BOUNDS_CHECK ((cfg), (array_reg), G_STRUCT_OFFSET (array_type, array_length_field), (index_reg)); \
@@ -822,6 +823,7 @@ static int ccount = 0;
                        (cfg)->flags |= MONO_CFG_HAS_ARRAY_ACCESS;                                      \
                        (cfg)->cbb->has_array_access = TRUE;                                            \
                }                                                                                                                               \
+               }                                                                                                                               \
     } while (0)
 
 G_END_DECLS
index 54c8010d0b675620efb42691a783d813ff9c78a7..fd1de882efff4dae1fadada00b49555dc741d9f9 100644 (file)
@@ -637,8 +637,8 @@ mono_array_new_va (MonoMethod *cm, ...)
 {
        MonoDomain *domain = mono_domain_get ();
        va_list ap;
-       guint32 *lengths;
-       guint32 *lower_bounds;
+       uintptr_t *lengths;
+       intptr_t *lower_bounds;
        int pcount;
        int rank;
        int i, d;
@@ -650,22 +650,22 @@ mono_array_new_va (MonoMethod *cm, ...)
 
        va_start (ap, cm);
        
-       lengths = alloca (sizeof (guint32) * pcount);
+       lengths = alloca (sizeof (uintptr_t) * pcount);
        for (i = 0; i < pcount; ++i)
                lengths [i] = d = va_arg(ap, int);
 
        if (rank == pcount) {
                /* Only lengths provided. */
                if (cm->klass->byval_arg.type == MONO_TYPE_ARRAY) {
-                       lower_bounds = alloca (sizeof (guint32) * rank);
-                       memset (lower_bounds, 0, sizeof (guint32) * rank);
+                       lower_bounds = alloca (sizeof (intptr_t) * rank);
+                       memset (lower_bounds, 0, sizeof (intptr_t) * rank);
                } else {
                        lower_bounds = NULL;
                }
        } else {
                g_assert (pcount == (rank * 2));
                /* lower bounds are first. */
-               lower_bounds = lengths;
+               lower_bounds = (intptr_t*)lengths;
                lengths += rank;
        }
        va_end(ap);
@@ -678,8 +678,8 @@ MonoArray *
 mono_array_new_1 (MonoMethod *cm, guint32 length)
 {
        MonoDomain *domain = mono_domain_get ();
-       guint32 lengths [1];
-       guint32 *lower_bounds;
+       uintptr_t lengths [1];
+       intptr_t *lower_bounds;
        int pcount;
        int rank;
 
@@ -693,8 +693,8 @@ mono_array_new_1 (MonoMethod *cm, guint32 length)
        g_assert (rank == pcount);
 
        if (cm->klass->byval_arg.type == MONO_TYPE_ARRAY) {
-               lower_bounds = alloca (sizeof (guint32) * rank);
-               memset (lower_bounds, 0, sizeof (guint32) * rank);
+               lower_bounds = alloca (sizeof (intptr_t) * rank);
+               memset (lower_bounds, 0, sizeof (intptr_t) * rank);
        } else {
                lower_bounds = NULL;
        }
@@ -706,8 +706,8 @@ MonoArray *
 mono_array_new_2 (MonoMethod *cm, guint32 length1, guint32 length2)
 {
        MonoDomain *domain = mono_domain_get ();
-       guint32 lengths [2];
-       guint32 *lower_bounds;
+       uintptr_t lengths [2];
+       intptr_t *lower_bounds;
        int pcount;
        int rank;
 
@@ -722,8 +722,8 @@ mono_array_new_2 (MonoMethod *cm, guint32 length1, guint32 length2)
        g_assert (rank == pcount);
 
        if (cm->klass->byval_arg.type == MONO_TYPE_ARRAY) {
-               lower_bounds = alloca (sizeof (guint32) * rank);
-               memset (lower_bounds, 0, sizeof (guint32) * rank);
+               lower_bounds = alloca (sizeof (intptr_t) * rank);
+               memset (lower_bounds, 0, sizeof (intptr_t) * rank);
        } else {
                lower_bounds = NULL;
        }
@@ -735,8 +735,8 @@ MonoArray *
 mono_array_new_3 (MonoMethod *cm, guint32 length1, guint32 length2, guint32 length3)
 {
        MonoDomain *domain = mono_domain_get ();
-       guint32 lengths [3];
-       guint32 *lower_bounds;
+       uintptr_t lengths [3];
+       intptr_t *lower_bounds;
        int pcount;
        int rank;
 
@@ -752,8 +752,8 @@ mono_array_new_3 (MonoMethod *cm, guint32 length1, guint32 length2, guint32 leng
        g_assert (rank == pcount);
 
        if (cm->klass->byval_arg.type == MONO_TYPE_ARRAY) {
-               lower_bounds = alloca (sizeof (guint32) * rank);
-               memset (lower_bounds, 0, sizeof (guint32) * rank);
+               lower_bounds = alloca (sizeof (intptr_t) * rank);
+               memset (lower_bounds, 0, sizeof (intptr_t) * rank);
        } else {
                lower_bounds = NULL;
        }
index 9ee967d577aaa031f5f09dc9061b75af18d0d509..5ae9f41d06e578a9fe5d7e56044e2352bf8707d1 100644 (file)
@@ -495,7 +495,6 @@ mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *targe
 {
        MonoMethodHeader *header = cfg->header;
        MonoExceptionClause *clause;
-       MonoBasicBlock *handler;
        int i;
        GList *res = NULL;
 
@@ -503,11 +502,8 @@ mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *targe
                clause = &header->clauses [i];
                if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) && 
                    (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
-                       if (clause->flags == type) {
-                               handler = cfg->cil_offset_to_bb [clause->handler_offset];
-                               g_assert (handler);
-                               res = g_list_append (res, handler);
-                       }
+                       if (clause->flags == type)
+                               res = g_list_append (res, clause);
                }
        }
        return res;
@@ -1374,17 +1370,26 @@ mini_emit_load_intf_reg_vtable (MonoCompile *cfg, int intf_reg, int vtable_reg,
        }
 }
 
-/* 
- * Emit code which loads into "intf_bit_reg" a nonzero value if the MonoClass
- * stored in "klass_reg" implements the interface "klass".
- */
 static void
-mini_emit_load_intf_bit_reg_class (MonoCompile *cfg, int intf_bit_reg, int klass_reg, MonoClass *klass)
+mini_emit_interface_bitmap_check (MonoCompile *cfg, int intf_bit_reg, int base_reg, int offset, MonoClass *klass)
 {
        int ibitmap_reg = alloc_preg (cfg);
+#ifdef COMPRESSED_INTERFACE_BITMAP
+       MonoInst *args [2];
+       MonoInst *res, *ins;
+       NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, ibitmap_reg, base_reg, offset);
+       MONO_ADD_INS (cfg->cbb, ins);
+       args [0] = ins;
+       if (cfg->compile_aot)
+               EMIT_NEW_AOTCONST (cfg, args [1], MONO_PATCH_INFO_IID, klass);
+       else
+               EMIT_NEW_ICONST (cfg, args [1], klass->interface_id);
+       res = mono_emit_jit_icall (cfg, mono_class_interface_match, args);
+       MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, intf_bit_reg, res->dreg);
+#else
        int ibitmap_byte_reg = alloc_preg (cfg);
 
-       MONO_EMIT_NEW_LOAD_MEMBASE (cfg, ibitmap_reg, klass_reg, G_STRUCT_OFFSET (MonoClass, interface_bitmap));
+       MONO_EMIT_NEW_LOAD_MEMBASE (cfg, ibitmap_reg, base_reg, offset);
 
        if (cfg->compile_aot) {
                int iid_reg = alloc_preg (cfg);
@@ -1405,6 +1410,17 @@ mini_emit_load_intf_bit_reg_class (MonoCompile *cfg, int intf_bit_reg, int klass
                MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI1_MEMBASE, ibitmap_byte_reg, ibitmap_reg, klass->interface_id >> 3);
                MONO_EMIT_NEW_BIALU_IMM (cfg, OP_AND_IMM, intf_bit_reg, ibitmap_byte_reg, 1 << (klass->interface_id & 7));
        }
+#endif
+}
+
+/* 
+ * Emit code which loads into "intf_bit_reg" a nonzero value if the MonoClass
+ * stored in "klass_reg" implements the interface "klass".
+ */
+static void
+mini_emit_load_intf_bit_reg_class (MonoCompile *cfg, int intf_bit_reg, int klass_reg, MonoClass *klass)
+{
+       mini_emit_interface_bitmap_check (cfg, intf_bit_reg, klass_reg, G_STRUCT_OFFSET (MonoClass, interface_bitmap), klass);
 }
 
 /* 
@@ -1414,30 +1430,7 @@ mini_emit_load_intf_bit_reg_class (MonoCompile *cfg, int intf_bit_reg, int klass
 static void
 mini_emit_load_intf_bit_reg_vtable (MonoCompile *cfg, int intf_bit_reg, int vtable_reg, MonoClass *klass)
 {
-       int ibitmap_reg = alloc_preg (cfg);
-       int ibitmap_byte_reg = alloc_preg (cfg);
-       MONO_EMIT_NEW_LOAD_MEMBASE (cfg, ibitmap_reg, vtable_reg, G_STRUCT_OFFSET (MonoVTable, interface_bitmap));
-
-       if (cfg->compile_aot) {
-               int iid_reg = alloc_preg (cfg);
-               int shifted_iid_reg = alloc_preg (cfg);
-               int ibitmap_byte_address_reg = alloc_preg (cfg);
-               int masked_iid_reg = alloc_preg (cfg);
-               int iid_one_bit_reg = alloc_preg (cfg);
-               int iid_bit_reg = alloc_preg (cfg);
-               MONO_EMIT_NEW_AOTCONST (cfg, iid_reg, klass, MONO_PATCH_INFO_IID);
-               MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHR_IMM, shifted_iid_reg, iid_reg, 3);
-               MONO_EMIT_NEW_BIALU (cfg, OP_PADD, ibitmap_byte_address_reg, ibitmap_reg, shifted_iid_reg);
-               MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, ibitmap_byte_reg, ibitmap_byte_address_reg, 0);
-               MONO_EMIT_NEW_BIALU_IMM (cfg, OP_AND_IMM, masked_iid_reg, iid_reg, 7);
-               MONO_EMIT_NEW_ICONST (cfg, iid_one_bit_reg, 1);
-               MONO_EMIT_NEW_BIALU (cfg, OP_ISHL, iid_bit_reg, iid_one_bit_reg, masked_iid_reg);
-               MONO_EMIT_NEW_BIALU (cfg, OP_IAND, intf_bit_reg, ibitmap_byte_reg, iid_bit_reg);
-       } else {
-               MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI1_MEMBASE, ibitmap_byte_reg, ibitmap_reg, klass->interface_id >> 3);
-               MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, intf_bit_reg, ibitmap_byte_reg, 1 << (klass->interface_id & 7));
-       }
+       mini_emit_interface_bitmap_check (cfg, intf_bit_reg, vtable_reg, G_STRUCT_OFFSET (MonoVTable, interface_bitmap), klass);
 }
 
 /* 
@@ -1720,8 +1713,6 @@ mini_emit_memset (MonoCompile *cfg, int destreg, int offset, int size, int val,
        }
 }
 
-#endif /* DISABLE_JIT */
-
 void 
 mini_emit_memcpy (MonoCompile *cfg, int destreg, int doffset, int srcreg, int soffset, int size, int align)
 {
@@ -1784,8 +1775,6 @@ mini_emit_memcpy (MonoCompile *cfg, int destreg, int doffset, int srcreg, int so
        }
 }
 
-#ifndef DISABLE_JIT
-
 static int
 ret_type_to_call_opcode (MonoType *type, int calli, int virt, MonoGenericSharingContext *gsctx)
 {
@@ -2979,11 +2968,42 @@ handle_unbox (MonoCompile *cfg, MonoClass *klass, MonoInst **sp, int context_use
  * Returns NULL and set the cfg exception on error.
  */
 static MonoInst*
-handle_alloc (MonoCompile *cfg, MonoClass *klass, gboolean for_box)
+handle_alloc (MonoCompile *cfg, MonoClass *klass, gboolean for_box, int context_used)
 {
        MonoInst *iargs [2];
        void *alloc_ftn;
 
+       if (context_used) {
+               MonoInst *data;
+               int rgctx_info;
+               MonoInst *iargs [2];
+
+               /*
+                 FIXME: we cannot get managed_alloc here because we can't get
+                 the class's vtable (because it's not a closed class)
+
+                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
+                 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, for_box);
+               */
+
+               if (cfg->opt & MONO_OPT_SHARED)
+                       rgctx_info = MONO_RGCTX_INFO_KLASS;
+               else
+                       rgctx_info = MONO_RGCTX_INFO_VTABLE;
+               data = emit_get_rgctx_klass (cfg, context_used, klass, rgctx_info);
+
+               if (cfg->opt & MONO_OPT_SHARED) {
+                       EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
+                       iargs [1] = data;
+                       alloc_ftn = mono_object_new;
+               } else {
+                       iargs [0] = data;
+                       alloc_ftn = mono_object_new_specific;
+               }
+
+               return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
+       }
+
        if (cfg->opt & MONO_OPT_SHARED) {
                EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
                EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
@@ -3027,54 +3047,32 @@ handle_alloc (MonoCompile *cfg, MonoClass *klass, gboolean for_box)
 
        return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
 }
-
-static MonoInst*
-handle_alloc_from_inst (MonoCompile *cfg, MonoClass *klass, MonoInst *data_inst,
-                                               gboolean for_box)
-{
-       MonoInst *iargs [2];
-       MonoMethod *managed_alloc = NULL;
-       void *alloc_ftn;
-
-       /*
-         FIXME: we cannot get managed_alloc here because we can't get
-         the class's vtable (because it's not a closed class)
-
-       MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
-       MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, for_box);
-       */
-
-       if (cfg->opt & MONO_OPT_SHARED) {
-               EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
-               iargs [1] = data_inst;
-               alloc_ftn = mono_object_new;
-       } else {
-               if (managed_alloc) {
-                       iargs [0] = data_inst;
-                       return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
-               }
-
-               iargs [0] = data_inst;
-               alloc_ftn = mono_object_new_specific;
-       }
-
-       return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
-}
        
 /*
  * Returns NULL and set the cfg exception on error.
  */    
 static MonoInst*
-handle_box (MonoCompile *cfg, MonoInst *val, MonoClass *klass)
+handle_box (MonoCompile *cfg, MonoInst *val, MonoClass *klass, int context_used)
 {
        MonoInst *alloc, *ins;
 
        if (mono_class_is_nullable (klass)) {
                MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
-               return mono_emit_method_call (cfg, method, &val, NULL);
+
+               if (context_used) {
+                       /* FIXME: What if the class is shared?  We might not
+                          have to get the method address from the RGCTX. */
+                       MonoInst *addr = emit_get_rgctx_method (cfg, context_used, method,
+                                                                                                       MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
+                       MonoInst *rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
+
+                       return mono_emit_rgctx_calli (cfg, mono_method_signature (method), &val, addr, rgctx);
+               } else {
+                       return mono_emit_method_call (cfg, method, &val, NULL);
+               }
        }
 
-       alloc = handle_alloc (cfg, klass, TRUE);
+       alloc = handle_alloc (cfg, klass, TRUE, context_used);
        if (!alloc)
                return NULL;
 
@@ -3083,29 +3081,6 @@ handle_box (MonoCompile *cfg, MonoInst *val, MonoClass *klass)
        return alloc;
 }
 
-static MonoInst *
-handle_box_from_inst (MonoCompile *cfg, MonoInst *val, MonoClass *klass, int context_used, MonoInst *data_inst)
-{
-       MonoInst *alloc, *ins;
-
-       if (mono_class_is_nullable (klass)) {
-               MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
-               /* FIXME: What if the class is shared?  We might not
-                  have to get the method address from the RGCTX. */
-               MonoInst *addr = emit_get_rgctx_method (cfg, context_used, method,
-                       MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
-               MonoInst *rgctx = emit_get_rgctx (cfg, cfg->current_method, context_used);
-
-               return mono_emit_rgctx_calli (cfg, mono_method_signature (method), &val, addr, rgctx);
-       } else {
-               alloc = handle_alloc_from_inst (cfg, klass, data_inst, TRUE);
-
-               EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, alloc->dreg, sizeof (MonoObject), val->dreg);
-
-               return alloc;
-       }
-}
-
 // FIXME: This doesn't work yet (class libs tests fail?)
 #define is_complex_isinst(klass) (TRUE || (klass->flags & TYPE_ATTRIBUTE_INTERFACE) || klass->rank || mono_class_is_nullable (klass) || klass->marshalbyref || (klass->flags & TYPE_ATTRIBUTE_SEALED) || mono_class_has_variant_generic_params (klass) || klass->byval_arg.type == MONO_TYPE_VAR || klass->byval_arg.type == MONO_TYPE_MVAR)
 
@@ -3425,6 +3400,8 @@ handle_ccastclass (MonoCompile *cfg, MonoClass *klass, MonoInst *src)
        MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, obj_reg, 0);
        MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, ok_result_bb);
 
+       save_cast_details (cfg, klass, obj_reg);
+
        if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
                NEW_BBLOCK (cfg, interface_fail_bb);
        
@@ -3498,7 +3475,7 @@ handle_delegate_ctor (MonoCompile *cfg, MonoClass *klass, MonoInst *target, Mono
        MonoDomain *domain;
        guint8 **code_slot;
 
-       obj = handle_alloc (cfg, klass, FALSE);
+       obj = handle_alloc (cfg, klass, FALSE, 0);
        if (!obj)
                return NULL;
 
@@ -3736,7 +3713,7 @@ mini_field_access_needs_cctor_run (MonoCompile *cfg, MonoMethod *method, MonoVTa
 }
 
 static MonoInst*
-mini_emit_ldelema_1_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, MonoInst *index)
+mini_emit_ldelema_1_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, MonoInst *index, gboolean bcheck)
 {
        MonoInst *ins;
        guint32 size;
@@ -3767,7 +3744,8 @@ mini_emit_ldelema_1_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, Mono
        }
 #endif
 
-       MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index2_reg);
+       if (bcheck)
+               MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index2_reg);
 
 #if defined(TARGET_X86) || defined(TARGET_AMD64)
        if (size == 1 || size == 2 || size == 4 || size == 8) {
@@ -3861,7 +3839,7 @@ mini_emit_ldelema_ins (MonoCompile *cfg, MonoMethod *cmethod, MonoInst **sp, uns
        rank = mono_method_signature (cmethod)->param_count - (is_set? 1: 0);
 
        if (rank == 1)
-               return mini_emit_ldelema_1_ins (cfg, cmethod->klass->element_class, sp [0], sp [1]);
+               return mini_emit_ldelema_1_ins (cfg, cmethod->klass->element_class, sp [0], sp [1], TRUE);
 
 #ifndef MONO_ARCH_EMULATE_MUL_DIV
        /* emit_ldelema_2 depends on OP_LMUL */
@@ -3924,6 +3902,25 @@ should_insert_brekpoint (MonoMethod *method) {
        }
 }
 
+/* optimize the simple GetGenericValueImpl/SetGenericValueImpl generic icalls */
+static MonoInst*
+emit_array_generic_access (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, int is_set)
+{
+       MonoInst *addr, *store, *load;
+       MonoClass *eklass = mono_class_from_mono_type (fsig->params [2]);
+
+       /* the bounds check is already done by the callers */
+       addr = mini_emit_ldelema_1_ins (cfg, eklass, args [0], args [1], FALSE);
+       if (is_set) {
+               EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, args [2]->dreg, 0);
+               EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, addr->dreg, 0, load->dreg);
+       } else {
+               EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, addr->dreg, 0);
+               EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, args [2]->dreg, 0, load->dreg);
+       }
+       return store;
+}
+
 static MonoInst*
 mini_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
 {
@@ -4012,6 +4009,8 @@ mini_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSign
                } else
                        return NULL;
        } else if (cmethod->klass == mono_defaults.array_class) {
+               if (strcmp (cmethod->name + 1, "etGenericValueImpl") == 0)
+                       return emit_array_generic_access (cfg, fsig, args, *cmethod->name == 'S');
                if (cmethod->name [0] != 'g')
                        return NULL;
 
@@ -4102,15 +4101,6 @@ mini_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSign
 
                return (MonoInst*)mono_emit_method_call (cfg, fast_method, args, NULL);
 #endif
-       } else if (mini_class_is_system_array (cmethod->klass) &&
-                       strcmp (cmethod->name, "GetGenericValueImpl") == 0) {
-               MonoInst *addr, *store, *load;
-               MonoClass *eklass = mono_class_from_mono_type (fsig->params [1]);
-
-               addr = mini_emit_ldelema_1_ins (cfg, eklass, args [0], args [1]);
-               EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, addr->dreg, 0);
-               EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, args [2]->dreg, 0, load->dreg);
-               return store;
        } else if (cmethod->klass->image == mono_defaults.corlib &&
                           (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
                           (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
@@ -4257,7 +4247,7 @@ mini_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSign
                                size = 4;
                        else if (is_ref || fsig->params [1]->type == MONO_TYPE_I)
                                size = sizeof (gpointer);
-                       else if (sizeof (gpointer) == 8 && fsig->params [1]->type == MONO_TYPE_I4)
+                       else if (sizeof (gpointer) == 8 && fsig->params [1]->type == MONO_TYPE_I8)
                                size = 8;
                        if (size == 4) {
                                MONO_INST_NEW (cfg, ins, OP_ATOMIC_CAS_I4);
@@ -4892,36 +4882,20 @@ static void
 ensure_method_is_allowed_to_access_field (MonoCompile *cfg, MonoMethod *caller, MonoClassField *field,
                                          MonoBasicBlock *bblock, unsigned char *ip)
 {
-       /* there's no restriction to access Transparent or SafeCritical fields, so we only check calls to Critical methods */
-       if (mono_security_core_clr_class_level (mono_field_get_parent (field)) != MONO_SECURITY_CORE_CLR_CRITICAL)
-               return;
-
        /* we can't get the coreclr security level on wrappers since they don't have the attributes */
-       caller = get_original_method (caller);
-       if (!caller)
-               return;
-
-       /* caller is Critical! only SafeCritical and Critical callers can access the field, so we throw if caller is Transparent */
-       if (mono_security_core_clr_method_level (caller, TRUE) == MONO_SECURITY_CORE_CLR_TRANSPARENT)
-               emit_throw_exception (cfg, mono_get_exception_field_access ());
+       MonoException *ex = mono_security_core_clr_is_field_access_allowed (get_original_method (caller), field);
+       if (ex)
+               emit_throw_exception (cfg, ex);
 }
 
 static void
 ensure_method_is_allowed_to_call_method (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee,
                                         MonoBasicBlock *bblock, unsigned char *ip)
 {
-       /* there's no restriction to call Transparent or SafeCritical code, so we only check calls to Critical methods */
-       if (mono_security_core_clr_method_level (callee, TRUE) != MONO_SECURITY_CORE_CLR_CRITICAL)
-               return;
-
        /* we can't get the coreclr security level on wrappers since they don't have the attributes */
-       caller = get_original_method (caller);
-       if (!caller)
-               return;
-
-       /* caller is Critical! only SafeCritical and Critical callers can call it, so we throw if the caller is Transparent */
-       if (mono_security_core_clr_method_level (caller, TRUE) == MONO_SECURITY_CORE_CLR_TRANSPARENT)
-               emit_throw_exception (cfg, mono_get_exception_method_access ());
+       MonoException *ex = mono_security_core_clr_is_call_allowed (get_original_method (caller), callee);
+       if (ex)
+               emit_throw_exception (cfg, ex);
 }
 
 /*
@@ -6079,6 +6053,19 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                        /* MS.NET seems to silently convert this to a callvirt */
                                        virtual = 1;
 
+                               {
+                                       /*
+                                        * MS.NET accepts non virtual calls to virtual final methods of transparent proxy classes and
+                                        * converts to a callvirt.
+                                        *
+                                        * tests/bug-515884.il is an example of this behavior
+                                        */
+                                       const int test_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL | METHOD_ATTRIBUTE_STATIC;
+                                       const int expected_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL;
+                                       if (!virtual && cmethod->klass->marshalbyref && (cmethod->flags & test_flags) == expected_flags && cfg->method->wrapper_type == MONO_WRAPPER_NONE)
+                                               virtual = 1;
+                               }
+
                                if (!cmethod->klass->inited)
                                        if (!mono_class_init (cmethod->klass))
                                                goto load_error;
@@ -6088,7 +6075,12 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                        array_rank = cmethod->klass->rank;
                                        fsig = mono_method_signature (cmethod);
                                } else {
-                                       if (mono_method_signature (cmethod)->pinvoke) {
+                                       fsig = mono_method_signature (cmethod);
+
+                                       if (!fsig)
+                                               goto load_error;
+
+                                       if (fsig->pinvoke) {
                                                MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod,
                                                        check_for_pending_exc, FALSE);
                                                fsig = mono_method_signature (wrapper);
@@ -6137,7 +6129,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                         */
                                        EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_call->byval_arg, sp [0]->dreg, 0);
                                        ins->klass = constrained_call;
-                                       sp [0] = handle_box (cfg, ins, constrained_call);
+                                       sp [0] = handle_box (cfg, ins, constrained_call, mono_class_check_context_used (constrained_call));
                                        CHECK_CFG_EXCEPTION;
                                } else if (!constrained_call->valuetype) {
                                        int dreg = alloc_preg (cfg);
@@ -6319,6 +6311,8 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                if (!MONO_TYPE_IS_VOID (fsig->ret))
                                        *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
 
+                               CHECK_CFG_EXCEPTION;
+
                                ip += 5;
                                ins_flag = 0;
                                break;
@@ -6365,6 +6359,9 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                MONO_ADD_INS (bblock, ins);
                                link_bblock (cfg, bblock, end_bblock);                  
                                start_new_bblock = 1;
+
+                               CHECK_CFG_EXCEPTION;
+
                                /* skip CEE_RET as well */
                                ip += 6;
                                ins_flag = 0;
@@ -6379,6 +6376,8 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                        sp++;
                                }
 
+                               CHECK_CFG_EXCEPTION;
+
                                ip += 5;
                                ins_flag = 0;
                                break;
@@ -6523,6 +6522,8 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                if (!MONO_TYPE_IS_VOID (fsig->ret))
                                        *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
 
+                               CHECK_CFG_EXCEPTION;
+
                                ip += 5;
                                ins_flag = 0;
                                break;
@@ -6562,6 +6563,8 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                        g_assert_not_reached ();
                                }
 
+                               CHECK_CFG_EXCEPTION;
+
                                ip += 5;
                                ins_flag = 0;
                                break;
@@ -6572,6 +6575,8 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                if (!MONO_TYPE_IS_VOID (fsig->ret))
                                        *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
 
+                               CHECK_CFG_EXCEPTION;
+
                                ip += 5;
                                ins_flag = 0;
                                break;
@@ -6591,6 +6596,8 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                        if (!MONO_TYPE_IS_VOID (fsig->ret))
                                *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
 
+                       CHECK_CFG_EXCEPTION;
+
                        ip += 5;
                        ins_flag = 0;
                        break;
@@ -7152,6 +7159,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                case CEE_CONV_U:
                        CHECK_STACK (1);
                        ADD_UNOP (*ip);
+                       CHECK_CFG_EXCEPTION;
                        ip++;
                        break;
                case CEE_ADD_OVF:
@@ -7457,16 +7465,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                         * will be transformed into a normal call there.
                                         */
                                } else if (context_used) {
-                                       MonoInst *data;
-                                       int rgctx_info;
-
-                                       if (cfg->opt & MONO_OPT_SHARED)
-                                               rgctx_info = MONO_RGCTX_INFO_KLASS;
-                                       else
-                                               rgctx_info = MONO_RGCTX_INFO_VTABLE;
-                                       data = emit_get_rgctx_klass (cfg, context_used, cmethod->klass, rgctx_info);
-
-                                       alloc = handle_alloc_from_inst (cfg, cmethod->klass, data, FALSE);
+                                       alloc = handle_alloc (cfg, cmethod->klass, FALSE, context_used);
                                        *sp = alloc;
                                } else {
                                        MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
@@ -7485,7 +7484,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                                class_inits = g_slist_prepend (class_inits, vtable);
                                        }
 
-                                       alloc = handle_alloc (cfg, cmethod->klass, FALSE);
+                                       alloc = handle_alloc (cfg, cmethod->klass, FALSE, 0);
                                        *sp = alloc;
                                }
                                CHECK_CFG_EXCEPTION; /*for handle_alloc*/
@@ -7791,19 +7790,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                break;
                        }
 
-                       if (context_used) {
-                               MonoInst *data;
-                               int rgctx_info;
-
-                               if (cfg->opt & MONO_OPT_SHARED)
-                                       rgctx_info = MONO_RGCTX_INFO_KLASS;
-                               else
-                                       rgctx_info = MONO_RGCTX_INFO_VTABLE;
-                               data = emit_get_rgctx_klass (cfg, context_used, klass, rgctx_info);
-                               *sp++ = handle_box_from_inst (cfg, val, klass, context_used, data);
-                       } else {
-                               *sp++ = handle_box (cfg, val, klass);
-                       }
+                       *sp++ = handle_box (cfg, val, klass, context_used);
 
                        CHECK_CFG_EXCEPTION;
                        ip += 5;
@@ -8260,21 +8247,21 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                                EMIT_NEW_ICONST (cfg, *sp, *((guint32 *)addr));
                                                sp++;
                                                break;
-#ifndef HAVE_MOVING_COLLECTOR
                                        case MONO_TYPE_I:
                                        case MONO_TYPE_U:
+                                       case MONO_TYPE_PTR:
+                                       case MONO_TYPE_FNPTR:
+#ifndef HAVE_MOVING_COLLECTOR
                                        case MONO_TYPE_STRING:
                                        case MONO_TYPE_OBJECT:
                                        case MONO_TYPE_CLASS:
                                        case MONO_TYPE_SZARRAY:
-                                       case MONO_TYPE_PTR:
-                                       case MONO_TYPE_FNPTR:
                                        case MONO_TYPE_ARRAY:
+#endif
                                                EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
                                                type_to_eval_stack_type ((cfg), field->type, *sp);
                                                sp++;
                                                break;
-#endif
                                        case MONO_TYPE_I8:
                                        case MONO_TYPE_U8:
                                                EMIT_NEW_I8CONST (cfg, *sp, *((gint64 *)addr));
@@ -8355,7 +8342,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                   allocator because we can't get the
                                   open generic class's vtable.  We
                                   have the same problem in
-                                  handle_alloc_from_inst().  This
+                                  handle_alloc().  This
                                   needs to be solved so that we can
                                   have managed allocs of shared
                                   generic classes. */
@@ -8476,7 +8463,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                        }
 
                        readonly = FALSE;
-                       ins = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1]);
+                       ins = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
                        *sp++ = ins;
                        ip += 5;
                        break;
@@ -8520,7 +8507,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
                                EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset);
                        } else {
-                               addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1]);
+                               addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
                                EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
                        }
                        *sp++ = ins;
@@ -8584,7 +8571,7 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
                                        MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
                                        EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset, sp [2]->dreg);
                                } else {
-                                       addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1]);
+                                       addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
                                        EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0, sp [2]->dreg);
                                }
                        }
@@ -8930,11 +8917,16 @@ mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_b
 
                        if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
                                GList *tmp;
+                               MonoExceptionClause *clause;
+
                                for (tmp = handlers; tmp; tmp = tmp->next) {
-                                       tblock = tmp->data;
+                                       clause = tmp->data;
+                                       tblock = cfg->cil_offset_to_bb [clause->handler_offset];
+                                       g_assert (tblock);
                                        link_bblock (cfg, bblock, tblock);
                                        MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
                                        ins->inst_target_bb = tblock;
+                                       ins->inst_eh_block = clause;
                                        MONO_ADD_INS (bblock, ins);
                                        bblock->has_call_handler = 1;
                                        if (COMPILE_LLVM (cfg)) {
@@ -10321,14 +10313,15 @@ mono_op_to_op_imm_noemul (int opcode)
        case OP_LSHR:
        case OP_LSHL:
        case OP_LSHR_UN:
+               return -1;
 #endif
 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
        case OP_IDIV:
        case OP_IDIV_UN:
        case OP_IREM:
        case OP_IREM_UN:
-#endif
                return -1;
+#endif
        default:
                return mono_op_to_op_imm (opcode);
        }
index 61fdb31e7819e06c732210e03df591871152ee62..e331e9300251adbcb3e1f6df6e59e119cc339f01 100644 (file)
@@ -985,17 +985,17 @@ mono_arch_cpu_enumerate_simd_versions (void)
 
        if (cpuid (1, &eax, &ebx, &ecx, &edx)) {
                if (edx & (1 << 25))
-                       sse_opts |= 1 << SIMD_VERSION_SSE1;
+                       sse_opts |= SIMD_VERSION_SSE1;
                if (edx & (1 << 26))
-                       sse_opts |= 1 << SIMD_VERSION_SSE2;
+                       sse_opts |= SIMD_VERSION_SSE2;
                if (ecx & (1 << 0))
-                       sse_opts |= 1 << SIMD_VERSION_SSE3;
+                       sse_opts |= SIMD_VERSION_SSE3;
                if (ecx & (1 << 9))
-                       sse_opts |= 1 << SIMD_VERSION_SSSE3;
+                       sse_opts |= SIMD_VERSION_SSSE3;
                if (ecx & (1 << 19))
-                       sse_opts |= 1 << SIMD_VERSION_SSE41;
+                       sse_opts |= SIMD_VERSION_SSE41;
                if (ecx & (1 << 20))
-                       sse_opts |= 1 << SIMD_VERSION_SSE42;
+                       sse_opts |= SIMD_VERSION_SSE42;
        }
 
        /* Yes, all this needs to be done to check for sse4a.
@@ -1006,7 +1006,7 @@ mono_arch_cpu_enumerate_simd_versions (void)
                if ((((unsigned int) eax) >= 0x80000001) && (ebx == 0x68747541) && (ecx == 0x444D4163) && (edx == 0x69746E65)) {
                        cpuid (0x80000001, &eax, &ebx, &ecx, &edx);
                        if (ecx & (1 << 6))
-                               sse_opts |= 1 << SIMD_VERSION_SSE4a;
+                               sse_opts |= SIMD_VERSION_SSE4a;
                }
        }
 
@@ -1771,6 +1771,7 @@ mono_arch_get_llvm_call_info (MonoCompile *cfg, MonoMethodSignature *sig)
        ArgInfo *ainfo;
        int j;
        LLVMCallInfo *linfo;
+       MonoType *t;
 
        n = sig->param_count + sig->hasthis;
 
@@ -1804,6 +1805,11 @@ mono_arch_get_llvm_call_info (MonoCompile *cfg, MonoMethodSignature *sig)
        for (i = 0; i < n; ++i) {
                ainfo = cinfo->args + i;
 
+               if (i >= sig->hasthis)
+                       t = sig->params [i - sig->hasthis];
+               else
+                       t = &mono_defaults.int_class->byval_arg;
+
                linfo->args [i].storage = LLVMArgNone;
 
                switch (ainfo->storage) {
@@ -1815,16 +1821,15 @@ mono_arch_get_llvm_call_info (MonoCompile *cfg, MonoMethodSignature *sig)
                        linfo->args [i].storage = LLVMArgInFPReg;
                        break;
                case ArgOnStack:
-                       if ((i >= sig->hasthis) && (MONO_TYPE_ISSTRUCT(sig->params [i - sig->hasthis]))) {
+                       if (MONO_TYPE_ISSTRUCT (t)) {
                                linfo->args [i].storage = LLVMArgVtypeByVal;
                        } else {
                                linfo->args [i].storage = LLVMArgInIReg;
-                               if (!sig->params [i - sig->hasthis]->byref) {
-                                       if (sig->params [i - sig->hasthis]->type == MONO_TYPE_R4) {
+                               if (!t->byref) {
+                                       if (t->type == MONO_TYPE_R4)
                                                linfo->args [i].storage = LLVMArgInFPReg;
-                                       } else if (sig->params [i - sig->hasthis]->type == MONO_TYPE_R8) {
+                                       else if (t->type == MONO_TYPE_R8)
                                                linfo->args [i].storage = LLVMArgInFPReg;
-                                       }
                                }
                        }
                        break;
@@ -1964,6 +1969,13 @@ mono_arch_emit_call (MonoCompile *cfg, MonoCallInst *call)
                                }
                                g_assert (in->klass);
 
+                               if (ainfo->storage == ArgOnStack && size >= 10000) {
+                                       /* Avoid asserts in emit_memcpy () */
+                                       cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
+                                       cfg->exception_message = g_strdup_printf ("Passing an argument of size '%d'.", size);
+                                       /* Continue normally */
+                               }
+
                                if (size > 0) {
                                        MONO_INST_NEW (cfg, arg, OP_OUTARG_VT);
                                        arg->sreg1 = in->dreg;
@@ -4320,6 +4332,7 @@ mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
                        amd64_alu_reg_imm (code, X86_SUB, AMD64_RSP, 8);
                        mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_target_bb);
                        amd64_call_imm (code, 0);
+                       mono_cfg_add_try_hole (cfg, ins->inst_eh_block, code, bb);
                        /* Restore stack alignment */
                        amd64_alu_reg_imm (code, X86_ADD, AMD64_RSP, 8);
                        break;
@@ -5679,7 +5692,7 @@ mono_arch_emit_prolog (MonoCompile *cfg)
        gboolean args_clobbered = FALSE;
        gboolean trace = FALSE;
 
-       cfg->code_size =  MAX (((MonoMethodNormal *)method)->header->code_size * 4, 10240);
+       cfg->code_size =  MAX (cfg->header->code_size * 4, 10240);
 
        code = cfg->native_code = g_malloc (cfg->code_size);
 
index 982a98fbc725d821539cb47af7ddaeeb89593e85..5a510259791df70d0a78eb429fb161436e7b2763 100644 (file)
@@ -256,13 +256,13 @@ typedef struct {
 
 #endif
 
-#ifdef __OpenBSD__
-#undef MONO_ARCH_USE_SIGACTION
-#endif
-
 #endif /* HOST_WIN32 */
 
-#if defined (__NetBSD__)
+#if defined (__APPLE__)
+
+#define MONO_ARCH_NOMAP32BIT
+
+#elif defined (__NetBSD__)
 
 #define REG_RAX 14
 #define REG_RCX 3
@@ -284,7 +284,11 @@ typedef struct {
 
 #define MONO_ARCH_NOMAP32BIT
 
-#elif defined (__FreeBSD__) || defined (__OpenBSD__)
+#elif defined (__OpenBSD__)
+
+#define MONO_ARCH_NOMAP32BIT
+
+#elif defined (__FreeBSD__)
 
 #define REG_RAX 7
 #define REG_RCX 4
index d6d11211af2e7cb0680d7897387777f2e0b3eaf3..0a72637f062ad53b5efd0e90572c5925241fab7c 100644 (file)
@@ -3817,6 +3817,7 @@ mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
                case OP_CALL_HANDLER: 
                        mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_target_bb);
                        ARM_BL (code, 0);
+                       mono_cfg_add_try_hole (cfg, ins->inst_eh_block, code, bb);
                        break;
                case OP_LABEL:
                        ins->inst_c0 = code - cfg->native_code;
index fa2ab771e2b9b61712391b06a9c3faef1879e10f..5aa521164e4b0609cd017da49d821ab2b37a6f54 100644 (file)
@@ -63,6 +63,7 @@ static gpointer restore_stack_protection_tramp = NULL;
 
 static void try_more_restore (void);
 static void restore_stack_protection (void);
+static void mono_walk_stack_full (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoContext *start_ctx, MonoStackFrameWalk func, gboolean use_new_ctx, gpointer user_data);
 
 void
 mono_exceptions_init (void)
@@ -197,6 +198,34 @@ mono_get_throw_corlib_exception (void)
        return throw_corlib_exception_func;
 }
 
+static gboolean
+is_address_protected (MonoJitInfo *ji, MonoJitExceptionInfo *ei, gpointer ip)
+{
+       MonoTryBlockHoleTableJitInfo *table;
+       int i;
+       guint32 offset;
+       guint16 clause;
+
+       /*FIXME check if under s390 it should be ei->try_start >= ip*/
+       if (ei->try_start > ip || ip >= ei->try_end)
+               return FALSE;
+
+       if (!ji->has_try_block_holes)
+               return TRUE;
+
+       table = mono_jit_info_get_try_block_hole_table_info (ji);
+       offset = (guint32)((char*)ip - (char*)ji->code_start);
+       clause = (guint16)(ei - ji->clauses);
+       g_assert (clause < ji->num_clauses);
+
+       for (i = 0; i < table->num_holes; ++i) {
+               MonoTryBlockHoleJitInfo *hole = &table->holes [i];
+               if (hole->clause == clause && hole->offset <= offset && hole->offset + hole->length > offset)
+                       return FALSE;
+       }
+       return TRUE;
+}
+
 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
 
 /*
@@ -454,7 +483,7 @@ get_generic_context_from_stack_frame (MonoJitInfo *ji, gpointer generic_info)
                class = generic_info;
        }
 
-       g_assert (!ji->method->klass->generic_container);
+       //g_assert (!ji->method->klass->generic_container);
        if (ji->method->klass->generic_class)
                method_container_class = ji->method->klass->generic_class->container_class;
        else
@@ -630,6 +659,12 @@ ves_icall_get_trace (MonoException *exc, gint32 skip, MonoBoolean need_file_info
  */
 void
 mono_walk_stack (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoContext *start_ctx, MonoStackFrameWalk func, gpointer user_data)
+{
+       mono_walk_stack_full (domain, jit_tls, start_ctx, func, TRUE, user_data);
+}
+
+static void
+mono_walk_stack_full (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoContext *start_ctx, MonoStackFrameWalk func, gboolean use_new_ctx, gpointer user_data)
 {
        MonoLMF *lmf = mono_get_lmf ();
        MonoJitInfo *ji, rji;
@@ -648,7 +683,7 @@ mono_walk_stack (MonoDomain *domain, MonoJitTlsData *jit_tls, MonoContext *start
                if (!ji || ji == (gpointer)-1)
                        return;
 
-               if (func (domain, &new_ctx, ji, user_data))
+               if (func (domain, use_new_ctx ? &new_ctx : &ctx, ji, user_data))
                        return;
 
                ctx = new_ctx;
@@ -1045,7 +1080,8 @@ get_exception_catch_class (MonoJitExceptionInfo *ei, MonoJitInfo *ji, MonoContex
        MonoType *inflated_type;
        MonoGenericContext context;
 
-       if (!catch_class)
+       /*MonoJitExceptionInfo::data is an union used by filter and finally clauses too.*/
+       if (!catch_class || ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
                return NULL;
 
        if (!ji->has_generic_jit_info || !mono_jit_info_get_generic_jit_info (ji)->has_this)
@@ -1140,6 +1176,7 @@ mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer origina
        gboolean has_dynamic_methods = FALSE;
        gint32 filter_idx, first_filter_idx;
 
+
        g_assert (ctx != NULL);
        if (!obj) {
                MonoException *ex = mono_get_exception_null_reference ();
@@ -1300,11 +1337,10 @@ mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer origina
                                         * a call which causes an exception. Testcase: tests/exception8.cs.
                                         * FIXME: Clean this up.
                                         */
-                                       if (ei->try_start < MONO_CONTEXT_GET_IP (ctx) && 
+                                       if (ei->try_start < MONO_CONTEXT_GET_IP (ctx) && MONO_CONTEXT_GET_IP (ctx) <= ei->try_end) {
 #else
-                                       if (ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
+                                       if (is_address_protected (ji, ei, MONO_CONTEXT_GET_IP (ctx))) {
 #endif
-                                           MONO_CONTEXT_GET_IP (ctx) <= ei->try_end) { 
                                                /* catch block */
                                                MonoClass *catch_class = get_exception_catch_class (ei, ji, ctx);
 
@@ -1355,6 +1391,41 @@ mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer origina
 
                                                                return TRUE;
                                                        }
+                                                       /*
+                                                        * This guards against the situation that we abort a thread that is executing a finally clause
+                                                        * that was called by the EH machinery. It won't have a guard trampoline installed, so we must
+                                                        * check for this situation here and resume interruption if we are below the guarded block.
+                                                        */
+                                                       if (G_UNLIKELY (jit_tls->handler_block_return_address)) {
+                                                               gboolean is_outside = FALSE;
+                                                               gpointer prot_bp = MONO_CONTEXT_GET_BP (&jit_tls->ex_ctx);
+                                                               gpointer catch_bp = MONO_CONTEXT_GET_BP (ctx);
+                                                               //FIXME make this stack direction aware
+                                                               if (catch_bp > prot_bp) {
+                                                                       is_outside = TRUE;
+                                                               } else if (catch_bp == prot_bp) {
+                                                                       /* Can be either try { try { } catch {} } finally {} or try { try { } finally {} } catch {}
+                                                                        * So we check if the catch handler_start is protected by the guarded handler protected region
+                                                                        *
+                                                                        * Assumptions:
+                                                                        *      If there is an outstanding guarded_block return address, it means the current thread must be aborted.
+                                                                        *      This is the only way to reach out the guarded block as other cases are handled by the trampoline.
+                                                                        *      There aren't any further finally/fault handler blocks down the stack over this exception.
+                                                                        *   This must be ensured by the code that installs the guard trampoline.
+                                                                        */
+                                                                       g_assert (ji == mini_jit_info_table_find (domain, MONO_CONTEXT_GET_IP (&jit_tls->ex_ctx), NULL));
+
+                                                                       if (!is_address_protected (ji, jit_tls->handler_block, ei->handler_start)) {
+                                                                               is_outside = TRUE;
+                                                                       }
+                                                               }
+                                                               if (is_outside) {
+                                                                       jit_tls->handler_block_return_address = NULL;
+                                                                       jit_tls->handler_block = NULL;
+                                                                       mono_thread_resume_interruption (); /*We ignore the exception here, it will be raised later*/
+                                                               }
+                                                       }
+
                                                        if (mono_trace_is_enabled () && mono_trace_eval (ji->method))
                                                                g_print ("EXCEPTION: catch found at clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
                                                        mono_profiler_exception_clause_handler (ji->method, ei->flags, i);
@@ -1367,8 +1438,7 @@ mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer origina
 
                                                        return 0;
                                                }
-                                               if (!test_only && ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
-                                                   MONO_CONTEXT_GET_IP (ctx) < ei->try_end &&
+                                               if (!test_only && is_address_protected (ji, ei, MONO_CONTEXT_GET_IP (ctx)) &&
                                                    (ei->flags == MONO_EXCEPTION_CLAUSE_FAULT)) {
                                                        if (mono_trace_is_enabled () && mono_trace_eval (ji->method))
                                                                g_print ("EXCEPTION: fault clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
@@ -1376,8 +1446,7 @@ mono_handle_exception_internal (MonoContext *ctx, gpointer obj, gpointer origina
                                                        mono_debugger_call_exception_handler (ei->handler_start, MONO_CONTEXT_GET_SP (ctx), obj);
                                                        call_filter (ctx, ei->handler_start);
                                                }
-                                               if (!test_only && ei->try_start <= MONO_CONTEXT_GET_IP (ctx) && 
-                                                   MONO_CONTEXT_GET_IP (ctx) < ei->try_end &&
+                                               if (!test_only && is_address_protected (ji, ei, MONO_CONTEXT_GET_IP (ctx)) &&
                                                    (ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
                                                        if (mono_trace_is_enabled () && mono_trace_eval (ji->method))
                                                                g_print ("EXCEPTION: finally clause %d of %s\n", i, mono_method_full_name (ji->method, TRUE));
@@ -1537,8 +1606,7 @@ mono_debugger_run_finally (MonoContext *start_ctx)
        for (i = 0; i < ji->num_clauses; i++) {
                MonoJitExceptionInfo *ei = &ji->clauses [i];
 
-               if ((ei->try_start <= MONO_CONTEXT_GET_IP (&ctx)) && 
-                   (MONO_CONTEXT_GET_IP (&ctx) < ei->try_end) &&
+               if (is_address_protected (ji, ei, MONO_CONTEXT_GET_IP (&ctx)) &&
                    (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
                        call_filter (&ctx, ei->handler_start);
                }
@@ -1593,6 +1661,7 @@ mono_setup_altstack (MonoJitTlsData *tls)
                /* mprotect can fail for the main thread stack */
                gpointer gaddr = mono_valloc (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size, MONO_MMAP_NONE|MONO_MMAP_PRIVATE|MONO_MMAP_ANON|MONO_MMAP_FIXED);
                g_assert (gaddr == tls->stack_ovf_guard_base);
+               tls->stack_ovf_valloced = TRUE;
        }
 
        /*
@@ -1629,6 +1698,10 @@ mono_free_altstack (MonoJitTlsData *tls)
 
        if (tls->signal_stack)
                mono_vfree (tls->signal_stack, MONO_ARCH_SIGNAL_STACK_SIZE);
+       if (tls->stack_ovf_valloced)
+               mono_vfree (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size);
+       else
+               mono_mprotect (tls->stack_ovf_guard_base, tls->stack_ovf_guard_size, MONO_MMAP_READ|MONO_MMAP_WRITE);
 }
 
 #else /* !MONO_ARCH_SIGSEGV_ON_ALTSTACK */
@@ -1998,3 +2071,113 @@ mono_resume_unwind (void)
 
        restore_context (&ctx);
 }
+
+#ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
+
+typedef struct {
+       MonoJitInfo *ji;
+       MonoContext ctx;
+       MonoJitExceptionInfo *ei;
+} FindHandlerBlockData;
+
+static gboolean
+find_last_handler_block (MonoDomain *domain, MonoContext *ctx, MonoJitInfo *ji, gpointer data)
+{
+       int i;
+       gpointer ip;
+       FindHandlerBlockData *pdata = data;
+
+       if (ji->method->wrapper_type)
+               return FALSE;
+
+       ip = MONO_CONTEXT_GET_IP (ctx);
+
+       for (i = 0; i < ji->num_clauses; ++i) {
+               MonoJitExceptionInfo *ei = ji->clauses + i;
+               if (ei->flags != MONO_EXCEPTION_CLAUSE_FINALLY)
+                       continue;
+               /*If ip points to the first instruction it means the handler block didn't start
+                so we can leave its execution to the EH machinery*/
+               if (ei->handler_start < ip && ip < ei->data.handler_end) {
+                       pdata->ji = ji;
+                       pdata->ei = ei;
+                       pdata->ctx = *ctx;
+                       break;
+               }
+       }
+       return FALSE;
+}
+
+
+static gpointer
+install_handler_block_guard (MonoJitInfo *ji, MonoContext *ctx)
+{
+       int i;
+       MonoJitExceptionInfo *clause = NULL;
+       gpointer ip;
+
+       ip = MONO_CONTEXT_GET_IP (ctx);
+
+       for (i = 0; i < ji->num_clauses; ++i) {
+               clause = &ji->clauses [i];
+               if (clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY)
+                       continue;
+               if (clause->handler_start < ip && clause->data.handler_end > ip)
+                       break;
+       }
+
+       /*no matching finally */
+       if (i == ji->num_clauses)
+               return NULL;
+
+       /*If we stopped on the instruction right before the try, we haven't actually started executing it*/
+       if (ip == clause->handler_start)
+               return NULL;
+
+       return mono_arch_install_handler_block_guard (ji, clause, ctx, mono_create_handler_block_trampoline ());
+}
+
+/*
+ * Finds the bottom handler block running and install a block guard if needed.
+ */
+gboolean
+mono_install_handler_block_guard (MonoInternalThread *thread, MonoContext *ctx)
+{
+       FindHandlerBlockData data = { 0 };
+       MonoDomain *domain = mono_domain_get ();
+       MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
+       gpointer resume_ip;
+
+       if (jit_tls->handler_block_return_address)
+               return FALSE;
+
+       mono_walk_stack_full (domain, jit_tls, ctx, find_last_handler_block, FALSE, &data);
+
+       if (!data.ji)
+               return FALSE;
+
+       memcpy (&jit_tls->ex_ctx, &data.ctx, sizeof (MonoContext));
+
+       resume_ip = install_handler_block_guard (data.ji, &data.ctx);
+       if (resume_ip == NULL)
+               return FALSE;
+
+       jit_tls->handler_block_return_address = resume_ip;
+       jit_tls->handler_block = data.ei;
+
+#ifndef HOST_WIN32
+       /*Clear current thread from been wapi interrupted otherwise things can go south*/
+       wapi_clear_interruption ();
+#endif
+       return TRUE;
+}
+
+#else
+gboolean
+mono_install_handler_block_guard (MonoInternalThread *thread, MonoContext *ctx)
+{
+       return FALSE;
+}
+
+#endif
+
index 758cf85bf78174bccc1333cfbbb6cda9a1bbb364..8f378285da1b76ddd130e917d1fd207a99c85b07 100644 (file)
@@ -14,6 +14,9 @@
 
 #include "mini.h"
 
+//#define ALLOW_PARTIAL_SHARING TRUE
+#define ALLOW_PARTIAL_SHARING FALSE
+
 static void
 mono_class_unregister_image_generic_subclasses (MonoImage *image, gpointer user_data);
 
@@ -582,7 +585,122 @@ free_inflated_info (int info_type, gpointer info)
 }
 
 static MonoRuntimeGenericContextOtherInfoTemplate
-class_get_rgctx_template_oti (MonoClass *class, int type_argc, guint32 slot, gboolean temporary, gboolean *do_free);
+class_get_rgctx_template_oti (MonoClass *class, int type_argc, guint32 slot, gboolean temporary, gboolean shared, gboolean *do_free);
+static MonoClass*
+class_uninstantiated (MonoClass *class)
+{
+       if (class->generic_class)
+               return class->generic_class->container_class;
+       return class;
+}
+
+static gboolean
+generic_inst_is_sharable (MonoGenericInst *inst, gboolean allow_type_vars,
+                                                 gboolean allow_partial)
+{
+       gboolean has_refs;
+       int i;
+
+       has_refs = FALSE;
+       for (i = 0; i < inst->type_argc; ++i) {
+               MonoType *type = inst->type_argv [i];
+
+               if (MONO_TYPE_IS_REFERENCE (type) || (allow_type_vars && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)))
+                       has_refs = TRUE;
+       }
+       for (i = 0; i < inst->type_argc; ++i) {
+               MonoType *type = inst->type_argv [i];
+
+               if (MONO_TYPE_IS_REFERENCE (type) || (allow_type_vars && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)))
+                       continue;
+               /*
+                * Allow non ref arguments, if there is at least one ref argument
+                * (partial sharing).
+                * FIXME: Allow more types
+                */
+               if (allow_partial && !type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
+                       continue;
+
+               return FALSE;
+       }
+
+       return TRUE;
+}
+
+/*
+ * mono_is_partially_sharable_inst:
+ *
+ *   Return TRUE if INST has ref and non-ref type arguments.
+ */
+gboolean
+mono_is_partially_sharable_inst (MonoGenericInst *inst)
+{
+       int i;
+       gboolean has_refs = FALSE, has_non_refs = FALSE;
+
+       for (i = 0; i < inst->type_argc; ++i) {
+               if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
+                       has_refs = TRUE;
+               else
+                       has_non_refs = TRUE;
+       }
+
+       return has_refs && has_non_refs;
+}
+
+/*
+ * get_shared_class:
+ *
+ *   Return the class used to store information when using generic sharing.
+ * For fully shared classes, it is the generic definition, for partially shared
+ * classes, it is an instance with all ref type arguments replaced by the type parameters
+ * of its generic definition.
+ */
+static MonoClass*
+get_shared_class (MonoClass *class)
+{
+       /*
+        * FIXME: This conflicts with normal instances. Also, some code in this file
+        * like class_get_rgctx_template_oti treats these as normal generic instances
+        * instead of generic classes.
+        */
+       //g_assert_not_reached ();
+
+       if (class->is_inflated) {
+               MonoGenericContext *context = &class->generic_class->context;
+               MonoGenericContext *container_context;
+               MonoGenericContext shared_context;
+               MonoGenericInst *inst;
+               MonoType **type_argv;
+               int i;
+
+               inst = context->class_inst;
+               if (mono_is_partially_sharable_inst (inst)) {
+                       container_context = &class->generic_class->container_class->generic_container->context;
+                       type_argv = g_new0 (MonoType*, inst->type_argc);
+                       for (i = 0; i < inst->type_argc; ++i) {
+                               if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
+                                       type_argv [i] = container_context->class_inst->type_argv [i];
+                               else
+                                       type_argv [i] = inst->type_argv [i];
+                       }
+
+                       memset (&shared_context, 0, sizeof (MonoGenericContext));
+                       shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
+                       g_free (type_argv);
+
+                       return mono_class_inflate_generic_class (class->generic_class->container_class, &shared_context);
+               } else if (!generic_inst_is_sharable (inst, TRUE, FALSE)) {
+                       /* Happens for partially shared methods of nono-sharable generic class */
+                       return class;
+               }
+       }
+
+       return class_uninstantiated (class);
+}
 
 /*
  * mono_class_get_runtime_generic_context_template:
@@ -597,8 +715,6 @@ mono_class_get_runtime_generic_context_template (MonoClass *class)
        MonoRuntimeGenericContextTemplate *parent_template, *template;
        guint32 i;
 
-       g_assert (!class->generic_class);
-
        mono_loader_lock ();
        template = class_lookup_rgctx_template (class);
        mono_loader_unlock ();
@@ -606,6 +722,8 @@ mono_class_get_runtime_generic_context_template (MonoClass *class)
        if (template)
                return template;
 
+       //g_assert (get_shared_class (class) == class);
+
        template = alloc_template (class);
 
        mono_loader_lock ();
@@ -627,7 +745,7 @@ mono_class_get_runtime_generic_context_template (MonoClass *class)
                                for (i = 0; i < num_entries; ++i) {
                                        MonoRuntimeGenericContextOtherInfoTemplate oti;
 
-                                       oti = class_get_rgctx_template_oti (class->parent, type_argc, i, FALSE, NULL);
+                                       oti = class_get_rgctx_template_oti (class->parent, type_argc, i, FALSE, FALSE, NULL);
                                        if (oti.data && oti.data != MONO_RGCTX_SLOT_USED_MARKER) {
                                                rgctx_template_set_other_slot (class->image, template, type_argc, i,
                                                        oti.data, oti.info_type);
@@ -679,16 +797,16 @@ mono_class_get_runtime_generic_context_template (MonoClass *class)
  * LOCKING: loader lock
  */
 static MonoRuntimeGenericContextOtherInfoTemplate
-class_get_rgctx_template_oti (MonoClass *class, int type_argc, guint32 slot, gboolean temporary, gboolean *do_free)
+class_get_rgctx_template_oti (MonoClass *class, int type_argc, guint32 slot, gboolean temporary, gboolean shared, gboolean *do_free)
 {
        g_assert ((temporary && do_free) || (!temporary && !do_free));
 
-       if (class->generic_class) {
+       if (class->generic_class && !shared) {
                MonoRuntimeGenericContextOtherInfoTemplate oti;
                gboolean tmp_do_free;
 
                oti = class_get_rgctx_template_oti (class->generic_class->container_class,
-                       type_argc, slot, TRUE, &tmp_do_free);
+                                                                                       type_argc, slot, TRUE, FALSE, &tmp_do_free);
                if (oti.data) {
                        gpointer info = oti.data;
                        oti.data = inflate_other_info (&oti, &class->generic_class->context, class, temporary);
@@ -714,14 +832,6 @@ class_get_rgctx_template_oti (MonoClass *class, int type_argc, guint32 slot, gbo
        }
 }
 
-static MonoClass*
-class_uninstantiated (MonoClass *class)
-{
-       if (class->generic_class)
-               return class->generic_class->container_class;
-       return class;
-}
-
 static gpointer
 class_type_info (MonoDomain *domain, MonoClass *class, int info_type)
 {
@@ -840,8 +950,6 @@ fill_in_rgctx_template_slot (MonoClass *class, int type_argc, int index, gpointe
        MonoRuntimeGenericContextTemplate *template = mono_class_get_runtime_generic_context_template (class);
        MonoClass *subclass;
 
-       g_assert (!class->generic_class);
-
        rgctx_template_set_other_slot (class->image, template, type_argc, index, data, info_type);
 
        /* Recurse for all subclasses */
@@ -854,10 +962,9 @@ fill_in_rgctx_template_slot (MonoClass *class, int type_argc, int index, gpointe
                MonoRuntimeGenericContextOtherInfoTemplate subclass_oti;
                MonoRuntimeGenericContextTemplate *subclass_template = class_lookup_rgctx_template (subclass);
 
-               g_assert (!subclass->generic_class);
                g_assert (subclass_template);
 
-               subclass_oti = class_get_rgctx_template_oti (subclass->parent, type_argc, index, FALSE, NULL);
+               subclass_oti = class_get_rgctx_template_oti (subclass->parent, type_argc, index, FALSE, FALSE, NULL);
                g_assert (subclass_oti.data);
 
                fill_in_rgctx_template_slot (subclass, type_argc, index, subclass_oti.data, info_type);
@@ -950,9 +1057,6 @@ lookup_or_register_other_info (MonoClass *class, int type_argc, gpointer data, i
        MonoRuntimeGenericContextOtherInfoTemplate *oti_list, *oti;
        int i;
 
-       g_assert (!class->generic_class);
-       g_assert (class->generic_container || type_argc);
-
        mono_loader_lock ();
 
        oti_list = get_other_info_templates (rgctx_template, type_argc);
@@ -1134,8 +1238,8 @@ fill_runtime_generic_context (MonoVTable *class_vtable, MonoRuntimeGenericContex
 
        mono_domain_unlock (domain);
 
-       oti = class_get_rgctx_template_oti (class_uninstantiated (class),
-                       method_inst ? method_inst->type_argc : 0, slot, TRUE, &do_free);
+       oti = class_get_rgctx_template_oti (get_shared_class (class),
+                                                                               method_inst ? method_inst->type_argc : 0, slot, TRUE, TRUE, &do_free);
        /* This might take the loader lock */
        info = instantiate_other_info (domain, &oti, &context, class);
 
@@ -1289,49 +1393,36 @@ mono_method_lookup_rgctx (MonoVTable *class_vtable, MonoGenericInst *method_inst
        return mrgctx;
 }
 
-static gboolean
-generic_inst_is_sharable (MonoGenericInst *inst, gboolean allow_type_vars)
-{
-       int i;
-
-       for (i = 0; i < inst->type_argc; ++i) {
-               MonoType *type = inst->type_argv [i];
-               int type_type;
-
-               if (MONO_TYPE_IS_REFERENCE (type))
-                       continue;
-
-               type_type = mono_type_get_type (type);
-               if (allow_type_vars && (type_type == MONO_TYPE_VAR || type_type == MONO_TYPE_MVAR))
-                       continue;
-
-               return FALSE;
-       }
-
-       return TRUE;
-}
-
 /*
- * mono_generic_context_is_sharable:
+ * mono_generic_context_is_sharable_full:
  * @context: a generic context
  *
  * Returns whether the generic context is sharable.  A generic context
- * is sharable iff all of its type arguments are reference type.
+ * is sharable iff all of its type arguments are reference type, or some of them have a
+ * reference type, and ALLOW_PARTIAL is TRUE.
  */
 gboolean
-mono_generic_context_is_sharable (MonoGenericContext *context, gboolean allow_type_vars)
+mono_generic_context_is_sharable_full (MonoGenericContext *context,
+                                                                          gboolean allow_type_vars,
+                                                                          gboolean allow_partial)
 {
        g_assert (context->class_inst || context->method_inst);
 
-       if (context->class_inst && !generic_inst_is_sharable (context->class_inst, allow_type_vars))
+       if (context->class_inst && !generic_inst_is_sharable (context->class_inst, allow_type_vars, allow_partial))
                return FALSE;
 
-       if (context->method_inst && !generic_inst_is_sharable (context->method_inst, allow_type_vars))
+       if (context->method_inst && !generic_inst_is_sharable (context->method_inst, allow_type_vars, allow_partial))
                return FALSE;
 
        return TRUE;
 }
 
+gboolean
+mono_generic_context_is_sharable (MonoGenericContext *context, gboolean allow_type_vars)
+{
+       return mono_generic_context_is_sharable_full (context, allow_type_vars, ALLOW_PARTIAL_SHARING);
+}
+
 /*
  * mono_method_is_generic_impl:
  * @method: a method
@@ -1375,16 +1466,18 @@ has_constraints (MonoGenericContainer *container)
 }
 
 /*
- * mono_method_is_generic_sharable_impl:
+ * mono_method_is_generic_sharable_impl_full:
  * @method: a method
  * @allow_type_vars: whether to regard type variables as reference types
+ * @alloc_partial: whether to allow partial sharing
  *
  * Returns TRUE iff the method is inflated or part of an inflated
  * class, its context is sharable and it has no constraints on its
  * type parameters.  Otherwise returns FALSE.
  */
 gboolean
-mono_method_is_generic_sharable_impl (MonoMethod *method, gboolean allow_type_vars)
+mono_method_is_generic_sharable_impl_full (MonoMethod *method, gboolean allow_type_vars,
+                                                                                  gboolean allow_partial)
 {
        if (!mono_method_is_generic_impl (method))
                return FALSE;
@@ -1393,7 +1486,7 @@ mono_method_is_generic_sharable_impl (MonoMethod *method, gboolean allow_type_va
                MonoMethodInflated *inflated = (MonoMethodInflated*)method;
                MonoGenericContext *context = &inflated->context;
 
-               if (!mono_generic_context_is_sharable (context, allow_type_vars))
+               if (!mono_generic_context_is_sharable_full (context, allow_type_vars, allow_partial))
                        return FALSE;
 
                g_assert (inflated->declaring);
@@ -1405,7 +1498,7 @@ mono_method_is_generic_sharable_impl (MonoMethod *method, gboolean allow_type_va
        }
 
        if (method->klass->generic_class) {
-               if (!mono_generic_context_is_sharable (&method->klass->generic_class->context, allow_type_vars))
+               if (!mono_generic_context_is_sharable_full (&method->klass->generic_class->context, allow_type_vars, allow_partial))
                        return FALSE;
 
                g_assert (method->klass->generic_class->container_class &&
@@ -1421,6 +1514,12 @@ mono_method_is_generic_sharable_impl (MonoMethod *method, gboolean allow_type_va
        return TRUE;
 }
 
+gboolean
+mono_method_is_generic_sharable_impl (MonoMethod *method, gboolean allow_type_vars)
+{
+       return mono_method_is_generic_sharable_impl_full (method, allow_type_vars, ALLOW_PARTIAL_SHARING);
+}
+
 gboolean
 mono_method_needs_static_rgctx_invoke (MonoMethod *method, gboolean allow_type_vars)
 {
@@ -1486,46 +1585,6 @@ mono_method_construct_object_context (MonoMethod *method)
        return object_context;
 }
 
-/*
- * mono_domain_lookup_shared_generic:
- * @domain: a domain
- * @open_method: an open generic method
- *
- * Looks up the jit info for method via the domain's jit code hash.
- */
-MonoJitInfo*
-mono_domain_lookup_shared_generic (MonoDomain *domain, MonoMethod *open_method)
-{
-       static gboolean inited = FALSE;
-       static int lookups = 0;
-       static int failed_lookups = 0;
-
-       MonoGenericContext object_context;
-       MonoMethod *object_method;
-       MonoJitInfo *ji;
-
-       object_context = mono_method_construct_object_context (open_method);
-       object_method = mono_class_inflate_generic_method (open_method, &object_context);
-
-       mono_domain_jit_code_hash_lock (domain);
-       ji = mono_internal_hash_table_lookup (&domain->jit_code_hash, object_method);
-       if (ji && !ji->has_generic_jit_info)
-               ji = NULL;
-       mono_domain_jit_code_hash_unlock (domain);
-
-       if (!inited) {
-               mono_counters_register ("Shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &lookups);
-               mono_counters_register ("Failed shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &failed_lookups);
-               inited = TRUE;
-       }
-
-       ++lookups;
-       if (!ji)
-               ++failed_lookups;
-
-       return ji;
-}
-
 static gboolean gshared_supported;
 
 void
index 5d5cc6e900728e1c9e3429cc5be9193b2e310cdc..6a504588ceaa746eac3893f270649ba55714c15f 100644 (file)
@@ -3007,6 +3007,8 @@ mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
                        ia64_movl (code, GP_SCRATCH_REG2, 0);
                        ia64_mov_to_br (code, IA64_B6, GP_SCRATCH_REG2);
                        ia64_br_cond_reg (code, IA64_B6);
+                       // FIXME:
+                       //mono_cfg_add_try_hole (cfg, ins->inst_eh_block, code, bb);
                        ia64_codegen_set_one_ins_per_bundle (code, FALSE);
                        break;
                case OP_START_HANDLER: {
@@ -3809,7 +3811,7 @@ mono_arch_emit_prolog (MonoCompile *cfg)
 
        cinfo = get_call_info (cfg, cfg->mempool, sig, FALSE);
 
-       cfg->code_size =  MAX (((MonoMethodNormal *)method)->header->code_size * 4, 512);
+       cfg->code_size =  MAX (cfg->header->code_size * 4, 512);
 
        if (mono_jit_trace_calls != NULL && mono_trace_eval (method))
                cfg->code_size += 1024;
index 55a77833babc8f64bc64ac8d26e3d7ae02eff935..b389a677e48761d5ded10aa842f423c99945af5a 100644 (file)
@@ -168,6 +168,10 @@ static guint32 current_cfg_tls_id;
 
 static MonoLLVMModule jit_module, aot_module;
 static gboolean jit_module_inited;
+static int memset_param_count, memcpy_param_count;
+static const char *memset_func_name;
+static const char *memcpy_func_name;
+static const char *eh_selector_name;
 
 static void init_jit_module (void);
 
@@ -1293,6 +1297,11 @@ emit_entry_bb (EmitContext *ctx, LLVMBuilderRef builder, int *pindexes)
                        }
                } else if (ainfo->storage == LLVMArgVtypeByVal) {
                        ctx->addresses [reg] = LLVMGetParam (ctx->lmethod, pindexes [i]);
+
+                       if (MONO_CLASS_IS_SIMD (ctx->cfg, mono_class_from_mono_type (sig->params [i]))) {
+                               /* Treat these as normal values */
+                               ctx->values [reg] = LLVMBuildLoad (builder, ctx->addresses [reg], "");
+                       }
                } else {
                        ctx->values [reg] = convert (ctx, ctx->values [reg], llvm_type_to_stack_type (type_to_llvm_type (ctx, sig->params [i])));
                }
@@ -1627,7 +1636,7 @@ mono_llvm_emit_method (MonoCompile *cfg)
                                LLVM_FAILURE (ctx, "handler without invokes");
                        }
 
-                       eh_selector = LLVMGetNamedFunction (module, "llvm.eh.selector");
+                       eh_selector = LLVMGetNamedFunction (module, eh_selector_name);
 
                        if (cfg->compile_aot) {
                                /* Use a dummy personality function */
@@ -2376,13 +2385,14 @@ mono_llvm_emit_method (MonoCompile *cfg)
                                v = mono_llvm_build_alloca (builder, LLVMInt8Type (), LLVMConstInt (LLVMInt32Type (), size, FALSE), MONO_ARCH_FRAME_ALIGNMENT, "");
 
                                if (ins->flags & MONO_INST_INIT) {
-                                       LLVMValueRef args [4];
+                                       LLVMValueRef args [5];
 
                                        args [0] = v;
                                        args [1] = LLVMConstInt (LLVMInt8Type (), 0, FALSE);
                                        args [2] = LLVMConstInt (LLVMInt32Type (), size, FALSE);
                                        args [3] = LLVMConstInt (LLVMInt32Type (), MONO_ARCH_FRAME_ALIGNMENT, FALSE);
-                                       LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.memset.i32"), args, 4, "");
+                                       args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
+                                       LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
                                }
 
                                values [ins->dreg] = v;
@@ -2396,13 +2406,14 @@ mono_llvm_emit_method (MonoCompile *cfg)
                                v = mono_llvm_build_alloca (builder, LLVMInt8Type (), size, MONO_ARCH_FRAME_ALIGNMENT, "");
 
                                if (ins->flags & MONO_INST_INIT) {
-                                       LLVMValueRef args [4];
+                                       LLVMValueRef args [5];
 
                                        args [0] = v;
                                        args [1] = LLVMConstInt (LLVMInt8Type (), 0, FALSE);
                                        args [2] = size;
                                        args [3] = LLVMConstInt (LLVMInt32Type (), MONO_ARCH_FRAME_ALIGNMENT, FALSE);
-                                       LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.memset.i32"), args, 4, "");
+                                       args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
+                                       LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
                                }
                                values [ins->dreg] = v;
                                break;
@@ -2549,6 +2560,9 @@ mono_llvm_emit_method (MonoCompile *cfg)
                                int *pindexes;
                                gboolean virtual, calli;
 
+                               if (call->signature->call_convention != MONO_CALL_DEFAULT)
+                                       LLVM_FAILURE (ctx, "non-default callconv");
+
                                cinfo = call->cinfo;
 
                                vretaddr = cinfo && cinfo->ret.storage == LLVMArgVtypeRetAddr;
@@ -3029,7 +3043,7 @@ mono_llvm_emit_method (MonoCompile *cfg)
                         */
                        case OP_VZERO: {
                                MonoClass *klass = ins->klass;
-                               LLVMValueRef args [4];
+                               LLVMValueRef args [5];
 
                                if (!klass) {
                                        // FIXME:
@@ -3044,7 +3058,8 @@ mono_llvm_emit_method (MonoCompile *cfg)
                                args [2] = LLVMConstInt (LLVMInt32Type (), mono_class_value_size (klass, NULL), FALSE);
                                // FIXME: Alignment
                                args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
-                               LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.memset.i32"), args, 4, "");
+                               args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
+                               LLVMBuildCall (builder, LLVMGetNamedFunction (module, memset_func_name), args, memset_param_count, "");
                                break;
                        }
 
@@ -3052,7 +3067,7 @@ mono_llvm_emit_method (MonoCompile *cfg)
                        case OP_LOADV_MEMBASE:
                        case OP_VMOVE: {
                                MonoClass *klass = ins->klass;
-                               LLVMValueRef src, dst, args [4];
+                               LLVMValueRef src, dst, args [5];
                                gboolean done = FALSE;
 
                                if (!klass) {
@@ -3101,7 +3116,8 @@ mono_llvm_emit_method (MonoCompile *cfg)
                                args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
                                // FIXME: Alignment
                                args [3] = LLVMConstInt (LLVMInt32Type (), 0, FALSE);
-                               LLVMBuildCall (builder, LLVMGetNamedFunction (module, "llvm.memcpy.i32"), args, 4, "");
+                               args [4] = LLVMConstInt (LLVMInt1Type (), 0, FALSE);
+                               LLVMBuildCall (builder, LLVMGetNamedFunction (module, memcpy_func_name), args, memcpy_param_count, "");
                                break;
                        }
                        case OP_LLVM_OUTARG_VT:
@@ -3682,15 +3698,30 @@ add_intrinsics (LLVMModuleRef module)
 {
        /* Emit declarations of instrinsics */
        {
-               LLVMTypeRef memset_params [] = { LLVMPointerType (LLVMInt8Type (), 0), LLVMInt8Type (), LLVMInt32Type (), LLVMInt32Type () };
+               LLVMTypeRef memset_params [] = { LLVMPointerType (LLVMInt8Type (), 0), LLVMInt8Type (), LLVMInt32Type (), LLVMInt32Type (), LLVMInt1Type () };
 
-               LLVMAddFunction (module, "llvm.memset.i32", LLVMFunctionType (LLVMVoidType (), memset_params, 4, FALSE));
+#if LLVM_MAJOR_VERSION > 2 || LLVM_MINOR_VERSION >= 8
+               memset_param_count = 5;
+               memset_func_name = "llvm.memset.p0i8.i32";
+#else
+               memset_param_count = 4;
+               memset_func_name = "llvm.memset.i32";
+#endif
+               LLVMAddFunction (module, memset_func_name, LLVMFunctionType (LLVMVoidType (), memset_params, memset_param_count, FALSE));
        }
 
        {
-               LLVMTypeRef memcpy_params [] = { LLVMPointerType (LLVMInt8Type (), 0), LLVMPointerType (LLVMInt8Type (), 0), LLVMInt32Type (), LLVMInt32Type () };
+               LLVMTypeRef memcpy_params [] = { LLVMPointerType (LLVMInt8Type (), 0), LLVMPointerType (LLVMInt8Type (), 0), LLVMInt32Type (), LLVMInt32Type (), LLVMInt1Type () };
 
-               LLVMAddFunction (module, "llvm.memcpy.i32", LLVMFunctionType (LLVMVoidType (), memcpy_params, 4, FALSE));
+#if LLVM_MAJOR_VERSION > 2 || LLVM_MINOR_VERSION >= 8
+               memcpy_param_count = 5;
+               memcpy_func_name = "llvm.memcpy.p0i8.p0i8.i32";
+#else
+               memcpy_param_count = 4;
+               memcpy_func_name = "llvm.memcpy.i32";
+#endif
+
+               LLVMAddFunction (module, memcpy_func_name, LLVMFunctionType (LLVMVoidType (), memcpy_params, memcpy_param_count, FALSE));
        }
 
        {
@@ -3753,10 +3784,23 @@ add_intrinsics (LLVMModuleRef module)
        /* EH intrinsics */
        {
                LLVMTypeRef arg_types [2];
+               LLVMTypeRef ret_type;
 
                arg_types [0] = LLVMPointerType (LLVMInt8Type (), 0);
                arg_types [1] = LLVMPointerType (LLVMInt8Type (), 0);
-               LLVMAddFunction (module, "llvm.eh.selector", LLVMFunctionType (LLVMInt32Type (), arg_types, 2, TRUE));
+#if LLVM_MAJOR_VERSION > 2 || LLVM_MINOR_VERSION >= 8
+               eh_selector_name = "llvm.eh.selector";
+               ret_type = LLVMInt32Type ();
+#else
+#if SIZEOF_VOID_P == 8
+               eh_selector_name = "llvm.eh.selector.i64";
+               ret_type = LLVMInt64Type ();
+#else
+               eh_selector_name = "llvm.eh.selector.i32";
+               ret_type = LLVMInt32Type ();
+#endif
+#endif
+               LLVMAddFunction (module, eh_selector_name, LLVMFunctionType (ret_type, arg_types, 2, TRUE));
 
                LLVMAddFunction (module, "llvm.eh.exception", LLVMFunctionType (LLVMPointerType (LLVMInt8Type (), 0), NULL, 0, FALSE));
 
index 8d6f8f1509d372dec71e2f71f4ce74b3a02b66c0..de827e33b96e4cf1990eee0ac3df1461e9c3e9cb 100644 (file)
@@ -3813,6 +3813,8 @@ mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
                        mips_addiu (code, mips_t9, mips_t9, 0);
                        mips_jalr (code, mips_t9, mips_ra);
                        mips_nop (code);
+                       /*FIXME should it be before the NOP or not? Does MIPS has a delay slot like sparc?*/
+                       mono_cfg_add_try_hole (cfg, ins->inst_eh_block, code, bb);
                        break;
                case OP_LABEL:
                        ins->inst_c0 = code - cfg->native_code;
index 823d93b79a3bc2a9f2f07a2d23a0fa0fd13ba059..ff0dfca92b77231e4a191a4733a2054b1f919c90 100644 (file)
@@ -159,6 +159,7 @@ SIG_HANDLER_SIGNATURE (sigabrt_signal_handler)
 static void
 SIG_HANDLER_SIGNATURE (sigusr1_signal_handler)
 {
+       MonoContext mctx;
        gboolean running_managed;
        MonoException *exc;
        MonoInternalThread *thread = mono_thread_internal_current ();
@@ -179,17 +180,37 @@ SIG_HANDLER_SIGNATURE (sigusr1_signal_handler)
        }
 
        /*
-        * FIXME:
         * This is an async signal, so the code below must not call anything which
         * is not async safe. That includes the pthread locking functions. If we
         * know that we interrupted managed code, then locking is safe.
         */
-       ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
-       running_managed = ji != NULL;
+       /*
+        * On OpenBSD, ctx can be NULL if we are interrupting poll ().
+        */
+       if (ctx) {
+               ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
+               running_managed = ji != NULL;
+
+               if (mono_debugger_agent_thread_interrupt (ctx, ji))
+                       return;
+       } else {
+               running_managed = FALSE;
+       }
+
+       /* We can't do handler block checking from metadata since it requires doing
+        * a stack walk with context.
+        *
+        * FIXME add full-aot support.
+        */
+#ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
+       if (!mono_aot_only && ctx) {
+               mono_arch_sigctx_to_monoctx (ctx, &mctx);
+               if (mono_install_handler_block_guard (thread, &mctx)) {
+                       return;
+               }
+       }
+#endif
 
-       if (mono_debugger_agent_thread_interrupt (ctx, ji))
-               return;
-       
        exc = mono_thread_request_interruption (running_managed); 
        if (!exc)
                return;
index 4223529a783629d60de84b102dd2bfb0260915a5..6c962bab95f38d31e8e65deb1a67816919d2108a 100755 (executable)
@@ -752,6 +752,7 @@ is_regsize_var (MonoType *t) {
        return FALSE;
 }
 
+#ifndef DISABLE_JIT
 GList *
 mono_arch_get_allocatable_int_vars (MonoCompile *cfg)
 {
@@ -779,6 +780,7 @@ mono_arch_get_allocatable_int_vars (MonoCompile *cfg)
 
        return vars;
 }
+#endif /* ifndef DISABLE_JIT */
 
 GList *
 mono_arch_get_global_int_regs (MonoCompile *cfg)
@@ -3238,6 +3240,7 @@ emit_unreserve_param_area (MonoCompile *cfg, guint8 *code)
 
 #define MASK_SHIFT_IMM(i)      ((i) & MONO_PPC_32_64_CASE (0x1f, 0x3f))
 
+#ifndef DISABLE_JIT
 void
 mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
 {
@@ -4148,6 +4151,7 @@ mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
                case OP_CALL_HANDLER: 
                        mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_target_bb);
                        ppc_bl (code, 0);
+                       mono_cfg_add_try_hole (cfg, ins->inst_eh_block, code, bb);
                        break;
                case OP_LABEL:
                        ins->inst_c0 = code - cfg->native_code;
@@ -4653,6 +4657,7 @@ mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
 
        cfg->code_len = code - cfg->native_code;
 }
+#endif /* !DISABLE_JIT */
 
 void
 mono_arch_register_lowlevel_calls (void)
@@ -4678,6 +4683,7 @@ mono_arch_register_lowlevel_calls (void)
        } while (0)
 #endif
 
+#ifndef DISABLE_JIT
 void
 mono_arch_patch_code (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *ji, gboolean run_cctors)
 {
@@ -5413,6 +5419,7 @@ mono_arch_emit_epilog (MonoCompile *cfg)
        g_assert (cfg->code_len < cfg->code_size);
 
 }
+#endif /* ifndef DISABLE_JIT */
 
 /* remove once throw_exception_by_name is eliminated */
 static int
@@ -5436,6 +5443,7 @@ exception_id_by_name (const char *name)
        return 0;
 }
 
+#ifndef DISABLE_JIT
 void
 mono_arch_emit_exceptions (MonoCompile *cfg)
 {
@@ -5523,7 +5531,7 @@ mono_arch_emit_exceptions (MonoCompile *cfg)
 
                        unsigned char *ip = patch_info->ip.i + cfg->native_code;
                        i = exception_id_by_name (patch_info->data.target);
-                       if (exc_throw_pos [i]) {
+                       if (exc_throw_pos [i] && !(ip > exc_throw_pos [i] && ip - exc_throw_pos [i] > 50000)) {
                                ppc_patch (ip, exc_throw_pos [i]);
                                patch_info->type = MONO_PATCH_INFO_NONE;
                                break;
@@ -5561,6 +5569,7 @@ mono_arch_emit_exceptions (MonoCompile *cfg)
 
        g_assert (cfg->code_len <= cfg->code_size);
 }
+#endif
 
 #if DEAD_CODE
 static int
@@ -5782,26 +5791,26 @@ mono_arch_build_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckI
                }
                size += item->chunk_size;
        }
+       /* the initial load of the vtable address */
+       size += PPC_LOAD_SEQUENCE_LENGTH + LOADSTORE_SIZE;
        if (fail_tramp) {
                code = mono_method_alloc_generic_virtual_thunk (domain, size);
        } else {
-               /* the initial load of the vtable address */
-               size += PPC_LOAD_SEQUENCE_LENGTH + LOADSTORE_SIZE;
                code = mono_domain_code_reserve (domain, size);
        }
        start = code;
-       if (!fail_tramp) {
-               /*
-                * We need to save and restore r11 because it might be
-                * used by the caller as the vtable register, so
-                * clobbering it will trip up the magic trampoline.
-                *
-                * FIXME: Get rid of this by making sure that r11 is
-                * not used as the vtable register in interface calls.
-                */
-               ppc_stptr (code, ppc_r11, PPC_RET_ADDR_OFFSET, ppc_sp);
-               ppc_load (code, ppc_r11, (gsize)(& (vtable->vtable [0])));
-       }
+
+       /*
+        * We need to save and restore r11 because it might be
+        * used by the caller as the vtable register, so
+        * clobbering it will trip up the magic trampoline.
+        *
+        * FIXME: Get rid of this by making sure that r11 is
+        * not used as the vtable register in interface calls.
+        */
+       ppc_stptr (code, ppc_r11, PPC_RET_ADDR_OFFSET, ppc_sp);
+       ppc_load (code, ppc_r11, (gsize)(& (vtable->vtable [0])));
+
        for (i = 0; i < count; ++i) {
                MonoIMTCheckItem *item = imt_entries [i];
                item->code_target = code;
index a35c4f527b131fe3935b996fabda0d9161c7b594..3168f5183a607f4dcc089b9b5e8194c1d98bbdd4 100644 (file)
@@ -107,21 +107,18 @@ if (ins->inst_target_bb->native_offset) {                                         \
                 MonoInst *inst;                                                \
                int tmpr = 0;                                                   \
                int sReg, dReg;                                                 \
-               MONO_INST_NEW (cfg, inst, OP_NOP);                                                              \
+               MONO_INST_NEW (cfg, inst, OP_NOP);                              \
                if (size > 256) {                                               \
-                       tmpr = mono_alloc_preg (cfg); \
-                       MONO_EMIT_NEW_ICONST(cfg,tmpr,size);                    \
                        inst->dreg        = dest;                               \
                        inst->inst_offset = offset;                             \
                        inst->sreg1       = src;                                \
                        inst->inst_imm    = imm;                                \
-                       inst->sreg2       = tmpr;                               \
                } else {                                                        \
                        if (s390_is_uimm12(offset)) {                           \
                                inst->dreg        = dest;                       \
                                inst->inst_offset = offset;                     \
                        } else {                                                \
-                               dReg = mono_alloc_preg (cfg); \
+                               dReg = mono_alloc_preg (cfg);                   \
                                MONO_EMIT_NEW_BIALU_IMM(cfg, OP_ADD_IMM,        \
                                        dReg, dest, offset);                    \
                                inst->dreg        = dReg;                       \
@@ -131,16 +128,16 @@ if (ins->inst_target_bb->native_offset) {                                         \
                                inst->sreg1       = src;                        \
                                inst->inst_imm    = imm;                        \
                        } else {                                                \
-                               sReg = mono_alloc_preg (cfg); \
+                               sReg = mono_alloc_preg (cfg);                   \
                                MONO_EMIT_NEW_BIALU_IMM(cfg, OP_ADD_IMM,        \
                                        sReg, src, imm);                        \
                                inst->sreg1       = sReg;                       \
                                inst->inst_imm    = 0;                          \
                        }                                                       \
                }                                                               \
-                inst->opcode     = OP_S390_MOVE;                               \
-               inst->backend.size        = size;                                       \
-        MONO_ADD_INS (cfg->cbb, inst); \
+                inst->opcode           = OP_S390_MOVE;                         \
+               inst->backend.size      = size;                                 \
+        MONO_ADD_INS (cfg->cbb, inst);                                                 \
        } while (0)
 
 #define MONO_OUTPUT_VTR(cfg, size, dr, sr, so) do {                            \
@@ -3778,6 +3775,7 @@ mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
                        mono_add_patch_info (cfg, code-cfg->native_code, 
                                             MONO_PATCH_INFO_BB, ins->inst_target_bb);
                        s390_brasl (code, s390_r14, 0);
+                       mono_cfg_add_try_hole (cfg, ins->inst_eh_block, code, bb);
                }
                        break;
                case OP_LABEL: {
@@ -4193,34 +4191,39 @@ mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
                                        s390_mvc  (code, ins->backend.size, ins->dreg, 
                                                   ins->inst_offset, ins->sreg1, ins->inst_imm);
                                } else {
-                                       s390_lr   (code, s390_r0, ins->dreg);
+                                       s390_lr  (code, s390_r0, ins->dreg);
                                        if (s390_is_imm16 (ins->inst_offset)) {
                                                s390_ahi  (code, s390_r0, ins->inst_offset);
                                        } else {
                                                s390_basr (code, s390_r13, 0);
-                                               s390_j    (code, 4);
-                                               s390_word (code, ins->inst_offset);
+                                               s390_j    (code, 6);
+                                               s390_long (code, ins->inst_offset);
                                                s390_a    (code, s390_r0, 0, s390_r13, 4);
                                        }
-                                       s390_lr   (code, s390_r14, s390_r12);
-                                       s390_lr   (code, s390_r12, ins->sreg1);
+                                       s390_lr  (code, s390_r12, ins->sreg1);
                                        if (s390_is_imm16 (ins->inst_imm)) {
                                                s390_ahi  (code, s390_r12, ins->inst_imm);
                                        } else {
                                                s390_basr (code, s390_r13, 0);
-                                               s390_j    (code, 4);
-                                               s390_word (code, ins->inst_imm);
+                                               s390_j    (code, 6);
+                                               s390_long (code, ins->inst_imm);
                                                s390_a    (code, s390_r12, 0, s390_r13, 4);
                                        }
-                                       s390_lr   (code, s390_r1, ins->sreg1);
+                                       if (s390_is_imm16 (ins->backend.size)) {
+                                               s390x_lhi (code, s390_r1, ins->backend.size);
+                                       } else {
+                                               s390_basr (code, s390_r13, 0);
+                                               s390_j    (code, 6);
+                                               s390_long (code, ins->backend.size);
+                                               s390_l    (code, s390_r1, 0, s390_r13, 4);
+                                       }
+                                       s390_lr   (code, s390_r1, ins->backend.size);
                                        s390_lr   (code, s390_r13, s390_r1);
                                        s390_mvcle(code, s390_r0, s390_r12, 0, 0);
                                        s390_jo   (code, -2);
-                                       s390_lr   (code, s390_r12, s390_r14);
                                }
                        }
                }
-                       break;
                case OP_ATOMIC_ADD_I4: {
                        s390_lr  (code, s390_r1, ins->sreg2);
                        s390_l   (code, s390_r0, 0, ins->inst_basereg, ins->inst_offset);
index bfdfdefdc388994430ae58bdf5d917d31605f31a..b3526a659fb8cb8d9da84fd08064b209e3d15cf4 100644 (file)
 /*                 D e f i n e s                                    */
 /*------------------------------------------------------------------*/
 
-#define EMIT_COND_BRANCH(ins,cond)                                                     \
-{                                                                                      \
+#define MAX_ARCH_DELEGATE_PARAMS 7
+
+#define EMIT_COND_BRANCH(ins,cond)                                             \
+{                                                                              \
 if (ins->inst_true_bb->native_offset) {                                        \
        int displace;                                                           \
        displace = ((cfg->native_code +                                         \
@@ -36,8 +38,8 @@ if (ins->inst_true_bb->native_offset) {                                       \
 }                                                                              \
 }
 
-#define EMIT_UNCOND_BRANCH(ins)                                                        \
-{                                                                                      \
+#define EMIT_UNCOND_BRANCH(ins)                                                \
+{                                                                              \
 if (ins->inst_target_bb->native_offset) {                                      \
        int displace;                                                           \
        displace = ((cfg->native_code +                                         \
@@ -126,23 +128,19 @@ if (ins->inst_target_bb->native_offset) {                                         \
 
 #define MONO_EMIT_NEW_MOVE(cfg,dest,offset,src,imm,size) do {                  \
                 MonoInst *inst;                                                \
-               int tmpr = 0;                                                   \
                int sReg, dReg;                                                 \
-               MONO_INST_NEW (cfg, inst, OP_NOP);                                                              \
+               MONO_INST_NEW (cfg, inst, OP_NOP);                              \
                if (size > 256) {                                               \
-                       tmpr = mono_alloc_preg (cfg); \
-                       MONO_EMIT_NEW_ICONST(cfg,tmpr,size);                    \
                        inst->dreg        = dest;                               \
                        inst->inst_offset = offset;                             \
                        inst->sreg1       = src;                                \
                        inst->inst_imm    = imm;                                \
-                       inst->sreg2       = tmpr;                               \
                } else {                                                        \
                        if (s390_is_uimm12(offset)) {                           \
                                inst->dreg        = dest;                       \
                                inst->inst_offset = offset;                     \
                        } else {                                                \
-                               dReg = mono_alloc_preg (cfg); \
+                               dReg = mono_alloc_preg (cfg);                   \
                                MONO_EMIT_NEW_BIALU_IMM(cfg, OP_ADD_IMM,        \
                                        dReg, dest, offset);                    \
                                inst->dreg        = dReg;                       \
@@ -152,16 +150,16 @@ if (ins->inst_target_bb->native_offset) {                                         \
                                inst->sreg1       = src;                        \
                                inst->inst_imm    = imm;                        \
                        } else {                                                \
-                               sReg = mono_alloc_preg (cfg); \
+                               sReg = mono_alloc_preg (cfg);                   \
                                MONO_EMIT_NEW_BIALU_IMM(cfg, OP_ADD_IMM,        \
                                        sReg, src, imm);                        \
                                inst->sreg1       = sReg;                       \
                                inst->inst_imm    = 0;                          \
                        }                                                       \
                }                                                               \
-                inst->opcode     = OP_S390_MOVE;                               \
-               inst->backend.size        = size;                                       \
-        MONO_ADD_INS (cfg->cbb, inst); \
+                inst->opcode           = OP_S390_MOVE;                         \
+               inst->backend.size      = size;                                 \
+        MONO_ADD_INS (cfg->cbb, inst);                                         \
        } while (0)
 
 #define MONO_OUTPUT_VTR(cfg, size, dr, sr, so) do {                            \
@@ -187,7 +185,7 @@ if (ins->inst_target_bb->native_offset) {                                   \
                                reg, sr, so);                                   \
                break;                                                          \
        }                                                                       \
-       mono_call_inst_add_outarg_reg(cfg, call, reg, dr, FALSE);       \
+       mono_call_inst_add_outarg_reg(cfg, call, reg, dr, FALSE);               \
 } while (0)
 
 #define MONO_OUTPUT_VTS(cfg, size, dr, dx, sr, so) do {                                \
@@ -207,14 +205,14 @@ if (ins->inst_target_bb->native_offset) {                                         \
                                dr, dx, tmpr);                                  \
                break;                                                          \
                case 2:                                                         \
-                       tmpr = mono_alloc_preg (cfg); \
+                       tmpr = mono_alloc_preg (cfg);                           \
                        MONO_EMIT_NEW_LOAD_MEMBASE_OP(cfg, OP_LOADU2_MEMBASE,   \
                                tmpr, sr, so);                                  \
                        MONO_EMIT_NEW_STORE_MEMBASE(cfg, OP_STORE_MEMBASE_REG,  \
                                dr, dx, tmpr);                                  \
                break;                                                          \
                case 4:                                                         \
-                       tmpr = mono_alloc_preg (cfg);   \
+                       tmpr = mono_alloc_preg (cfg);                           \
                        MONO_EMIT_NEW_LOAD_MEMBASE_OP(cfg, OP_LOADI4_MEMBASE,   \
                                tmpr, sr, so);                                  \
                        MONO_EMIT_NEW_STORE_MEMBASE(cfg, OP_STORE_MEMBASE_REG,  \
@@ -235,6 +233,16 @@ if (ins->inst_target_bb->native_offset) {                                  \
 
 #define MAX(a, b) ((a) > (b) ? (a) : (b))
 
+/*
+ * imt thunking size values
+ */
+#define CMP_SIZE       24
+#define LOADCON_SIZE   20
+#define LOAD_SIZE      6
+#define BR_SIZE                2
+#define JUMP_SIZE      6
+#define ENABLE_WRONG_METHOD_CHECK 0
+
 /*========================= End of Defines =========================*/
 
 /*------------------------------------------------------------------*/
@@ -370,6 +378,8 @@ pthread_key_t lmf_addr_key;
 
 gboolean lmf_addr_key_inited = FALSE; 
 
+facilityList_t facs;
+
 #if 0
 
 extern __thread MonoDomain *tls_appdomain;
@@ -1136,23 +1146,51 @@ mono_arch_cpu_init (void)
 
 /*========================= End of Function ========================*/
 
+/*------------------------------------------------------------------*/
+/*                                                                  */
+/* Name                - mono_arch_init.                                   */
+/*                                                                  */
+/* Function    - Initialize architecture specific code.            */
+/*                                                                 */
+/*------------------------------------------------------------------*/
 
-/*
- * Initialize architecture specific code.
- */
 void
 mono_arch_init (void)
 {
+#if 0
+       /*
+        * When we do an architectural level set at z9 or better 
+        * we can use the STFLE instruction to show us
+        * what hardware facilities are available
+        */
+       int lFacility = sizeof(facs) % 8;
+
+       memset((char *) &facs, 0, sizeof(facs));
+
+       __asm__ ("      lgfr    0,%1\n"
+                "      stfle   %0\n"
+                : "=m" (facs) : "r" (lFacility) : "0", "cc");
+#endif
+
 }
 
-/*
- * Cleanup architecture specific code.
- */
+/*========================= End of Function ========================*/
+
+/*------------------------------------------------------------------*/
+/*                                                                  */
+/* Name                - mono_arch_cleanup.                                */
+/*                                                                  */
+/* Function    - Cleanup architecture specific code    .           */
+/*                                                                 */
+/*------------------------------------------------------------------*/
+
 void
 mono_arch_cleanup (void)
 {
 }
 
+/*========================= End of Function ========================*/
+
 /*------------------------------------------------------------------*/
 /*                                                                  */
 /* Name                - mono_arch_cpu_optimizazions                       */
@@ -1309,7 +1347,8 @@ mono_arch_flush_icache (guint8 *code, gint size)
 /*                                                                  */
 /*------------------------------------------------------------------*/
 
-static void inline
+// static void inline
+static void 
 add_general (guint *gr, size_data *sz, ArgInfo *ainfo)
 {
        if (*gr > S390_LAST_ARG_REG) {
@@ -1398,7 +1437,7 @@ add_float (guint *fr,  size_data *sz, ArgInfo *ainfo)
 
 /*------------------------------------------------------------------*/
 /*                                                                  */
-/* Name                - get_call_info                                   */
+/* Name                - get_call_info                                     */
 /*                                                                  */
 /* Function    - Determine the amount of space required for code   */
 /*               and stack. In addition determine starting points  */
@@ -1522,6 +1561,13 @@ enum_retvalue:
                nParm++;
        }
 
+       if ((sig->call_convention == MONO_CALL_VARARG) && (sig->param_count == 0)) {
+               gr = S390_LAST_ARG_REG + 1;
+
+               /* Emit the signature cookie just before the implicit arguments */
+               add_general (&gr, sz, &cinfo->sigCookie);
+       }
+
        /*----------------------------------------------------------*/
        /* We determine the size of the parameter code and stack    */
        /* requirements by checking the types and sizes of the      */
@@ -1702,6 +1748,8 @@ enum_retvalue:
        /* Handle the case where there are no implicit arguments    */
        /*----------------------------------------------------------*/
        if ((sig->call_convention == MONO_CALL_VARARG) &&
+           (nParm > 0) &&
+           (!sig->pinvoke) &&
            (sig->param_count == sig->sentinelpos)) {
                gr = S390_LAST_ARG_REG + 1;
                add_general (&gr, sz, &cinfo->sigCookie);
@@ -1804,7 +1852,11 @@ mono_arch_allocate_vars (MonoCompile *cfg)
        /* to point at the local variables.                             */
        /* add parameter area size for called functions                 */
        /*--------------------------------------------------------------*/
-       offset          = (cfg->param_area + S390_MINIMAL_STACK_SIZE);
+       if (cfg->param_area == 0)
+               offset = S390_MINIMAL_STACK_SIZE;
+       else
+               offset = cfg->param_area;
+
        cfg->sig_cookie = 0;
 
        if (cinfo->struct_ret) {
@@ -1935,9 +1987,9 @@ mono_arch_allocate_vars (MonoCompile *cfg)
                        continue;
 
                /*--------------------------------------------------*/
-               /* inst->backend.is_pinvoke indicates native sized value types, */
-               /* this is used by the pinvoke wrappers when they   */
-               /* call functions returning structure               */
+               /* inst->backend.is_pinvoke indicates native sized  */
+               /* value typs this is used by the pinvoke wrappers  */
+               /* when they call functions returning structure     */
                /*--------------------------------------------------*/
                if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (inst->inst_vtype))
                        size = mono_class_native_size (mono_class_from_mono_type(inst->inst_vtype), 
@@ -1971,13 +2023,25 @@ mono_arch_allocate_vars (MonoCompile *cfg)
        /*------------------------------------------------------*/
        cfg->stack_offset = S390_ALIGN(offset, S390_STACK_ALIGNMENT);
 
+       /*------------------------------------------------------*/
+       /* Fix offsets for args whose value is in parent frame  */
+       /*------------------------------------------------------*/
+       for (iParm = sArg; iParm < eArg; ++iParm) {
+               inst = cfg->args [iParm];
+
+               if (inst->opcode == OP_S390_STKARG) {
+                       inst->opcode = OP_REGOFFSET;
+                       inst->inst_offset += cfg->stack_offset;
+               }
+       }
 }
 
 /*========================= End of Function ========================*/
 
 /*------------------------------------------------------------------*/
 /*                                                                  */
-/* Name                - mono_arch_create_vars                                 */
+/* Name                - mono_arch_create_vars                             */
+/*                                                                  */
 /*------------------------------------------------------------------*/
 
 void
@@ -2001,6 +2065,12 @@ mono_arch_create_vars (MonoCompile *cfg)
 
 /*========================= End of Function ========================*/
 
+/*------------------------------------------------------------------*/
+/*                                                                  */
+/* Name                - add_outarg_reg2.                                  */
+/*                                                                  */
+/*------------------------------------------------------------------*/
+
 static void
 add_outarg_reg2 (MonoCompile *cfg, MonoCallInst *call, ArgStorage storage, int reg, MonoInst *tree)
 {
@@ -2033,6 +2103,14 @@ add_outarg_reg2 (MonoCompile *cfg, MonoCallInst *call, ArgStorage storage, int r
        }
 }
 
+/*========================= End of Function ========================*/
+
+/*------------------------------------------------------------------*/
+/*                                                                  */
+/* Name                - emit_sig_cookie.                                  */
+/*                                                                  */
+/*------------------------------------------------------------------*/
+
 static void
 emit_sig_cookie (MonoCompile *cfg, MonoCallInst *call, CallInfo *cinfo)
 {
@@ -2061,12 +2139,14 @@ emit_sig_cookie (MonoCompile *cfg, MonoCallInst *call, CallInfo *cinfo)
        MONO_ADD_INS (cfg->cbb, sig_arg);
 
        MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, STK_BASE, 
-                                                                cinfo->sigCookie.offset, sig_arg->dreg);
+                                    cinfo->sigCookie.offset, sig_arg->dreg);
 }
 
+/*========================= End of Function ========================*/
+
 /*------------------------------------------------------------------*/
 /*                                                                  */
-/* Name                - mono_arch_emit_call                                   */
+/* Name                - mono_arch_emit_call                               */
 /*                                                                  */
 /*------------------------------------------------------------------*/
 
@@ -2079,7 +2159,9 @@ mono_arch_emit_call (MonoCompile *cfg, MonoCallInst *call)
        int i, n, lParamArea;
        CallInfo *cinfo;
        ArgInfo *ainfo = NULL;
-       int stackSize;
+       int stackSize;    
+       MonoMethodHeader *header;
+       int frmReg;
 
        sig = call->signature;
        n = sig->param_count + sig->hasthis;
@@ -2087,7 +2169,8 @@ mono_arch_emit_call (MonoCompile *cfg, MonoCallInst *call)
        
        cinfo = get_call_info (cfg, cfg->mempool, sig, sig->pinvoke);
 
-       stackSize         = cinfo->sz.stack_size + cinfo->sz.local_size + cinfo->sz.parm_size + cinfo->sz.offset;
+       stackSize         = cinfo->sz.stack_size + cinfo->sz.local_size + 
+                           cinfo->sz.parm_size + cinfo->sz.offset;
        call->stack_usage = MAX(stackSize, call->stack_usage);
        lParamArea        = MAX((call->stack_usage-S390_MINIMAL_STACK_SIZE-cinfo->sz.parm_size), 0);
        cfg->param_area   = MAX(((signed) cfg->param_area), lParamArea);
@@ -2101,6 +2184,12 @@ mono_arch_emit_call (MonoCompile *cfg, MonoCallInst *call)
                mono_call_inst_add_outarg_reg (cfg, call, ins->dreg, cinfo->ret.reg, FALSE);
        }
 
+       header = mono_method_get_header (cfg->method);
+       if ((cfg->flags & MONO_CFG_HAS_ALLOCA) || header->num_clauses)
+               frmReg = s390_r11;
+       else
+               frmReg = STK_BASE;
+
        for (i = 0; i < n; ++i) {
                MonoType *t;
 
@@ -2114,6 +2203,7 @@ mono_arch_emit_call (MonoCompile *cfg, MonoCallInst *call)
                in = call->args [i];
 
                if ((sig->call_convention == MONO_CALL_VARARG) &&
+                   (!sig->pinvoke) &&
                    (i == sig->sentinelpos)) {
                        emit_sig_cookie (cfg, call, cinfo);
                }
@@ -2178,33 +2268,34 @@ mono_arch_emit_call (MonoCompile *cfg, MonoCallInst *call)
                                 */
                                int treg = mono_alloc_preg (cfg);
                                MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, treg, 
-                                                                                STK_BASE, ainfo->offparm);
+                                                        frmReg, ainfo->offparm);
                                mono_call_inst_add_outarg_reg (cfg, call, treg, ainfo->reg, FALSE);
                        } else if (ainfo->regtype == RegTypeStructByAddrOnStack) {
                                /* The address of the valuetype is passed on the stack */
                                int treg = mono_alloc_preg (cfg);
                                MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, treg, 
-                                                                                STK_BASE, ainfo->offparm);
+                                                        frmReg, ainfo->offparm);
                                MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG,
-                                                                                        ainfo->reg, ainfo->offset, treg);
+                                                            ainfo->reg, ainfo->offset, treg);
                        }
                        break;
                }
                case RegTypeBase:
                        if (!t->byref && t->type == MONO_TYPE_R4) {
                                MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORER4_MEMBASE_REG, 
-                                                                                        STK_BASE, ainfo->offset + 4,
-                                                                                        in->dreg);
+                                                            STK_BASE, ainfo->offset + 4,
+                                                            in->dreg);
                        } else if (!t->byref && (t->type == MONO_TYPE_R8)) {
                                MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORER8_MEMBASE_REG, 
-                                                                                        STK_BASE, ainfo->offset,
-                                                                                        in->dreg);
+                                                            STK_BASE, ainfo->offset,
+                                                            in->dreg);
                        } else {
                                MONO_INST_NEW (cfg, ins, OP_STORE_MEMBASE_REG);
                                ins->inst_destbasereg = STK_BASE;
                                ins->inst_offset = ainfo->offset;
                                ins->sreg1 = in->dreg;
 
+#if 0
                                /* This is needed by MonoTypedRef->value to point to the correct data */
                                if ((sig->call_convention == MONO_CALL_VARARG) &&
                                        (i >= sig->sentinelpos)) {
@@ -2222,6 +2313,7 @@ mono_arch_emit_call (MonoCompile *cfg, MonoCallInst *call)
                                                break;
                                        }
                                }
+#endif
 
                                MONO_ADD_INS (cfg->cbb, ins);
                        }
@@ -2236,6 +2328,7 @@ mono_arch_emit_call (MonoCompile *cfg, MonoCallInst *call)
         * Handle the case where there are no implicit arguments 
         */
        if ((sig->call_convention == MONO_CALL_VARARG) &&
+           (!sig->pinvoke) &&
            (i == sig->sentinelpos)) {
                emit_sig_cookie (cfg, call, cinfo);
        }
@@ -2245,7 +2338,7 @@ mono_arch_emit_call (MonoCompile *cfg, MonoCallInst *call)
 
 /*------------------------------------------------------------------*/
 /*                                                                  */
-/* Name                - mono_arch_emit_outarg_vt                              */
+/* Name                - mono_arch_emit_outarg_vt                          */
 /*                                                                  */
 /*------------------------------------------------------------------*/
 
@@ -2284,14 +2377,25 @@ mono_arch_emit_outarg_vt (MonoCompile *cfg, MonoInst *ins, MonoInst *src)
 
                mono_call_inst_add_outarg_reg (cfg, call, dreg, ainfo->reg, TRUE);
        } else {
-               MONO_EMIT_NEW_MOVE (cfg, STK_BASE, ainfo->offparm,
+               MonoMethodHeader *header;
+               int srcReg;
+
+               header = mono_method_get_header (cfg->method);
+               if ((cfg->flags & MONO_CFG_HAS_ALLOCA) || header->num_clauses)
+                       srcReg = s390_r11;
+               else
+                       srcReg = STK_BASE;
+
+               MONO_EMIT_NEW_MOVE (cfg, srcReg, ainfo->offparm,
                                                         src->dreg, 0, size);
        }
 }
 
+/*========================= End of Function ========================*/
+
 /*------------------------------------------------------------------*/
 /*                                                                  */
-/* Name                - mono_arch_emit_setret                                 */
+/* Name                - mono_arch_emit_setret                             */
 /*                                                                  */
 /*------------------------------------------------------------------*/
 
@@ -2521,14 +2625,25 @@ handle_enum:
 
 /*========================= End of Function ========================*/
 
+/*------------------------------------------------------------------*/
+/*                                                                  */
+/* Name                - mono_arch_peephole_pass_1                         */
+/*                                                                  */
+/* Function    - Form a peephole pass at the code looking for      */
+/*               simple optimizations.                             */
+/*                                                                 */
+/*------------------------------------------------------------------*/
+
 void
 mono_arch_peephole_pass_1 (MonoCompile *cfg, MonoBasicBlock *bb)
 {
 }
 
+/*========================= End of Function ========================*/
+
 /*------------------------------------------------------------------*/
 /*                                                                  */
-/* Name                - mono_arch_peephole_pass                                     */
+/* Name                - mono_arch_peephole_pass_2                         */
 /*                                                                  */
 /* Function    - Form a peephole pass at the code looking for      */
 /*               simple optimizations.                             */
@@ -2547,6 +2662,12 @@ mono_arch_peephole_pass_2 (MonoCompile *cfg, MonoBasicBlock *bb)
 
 /*========================= End of Function ========================*/
 
+/*------------------------------------------------------------------*/
+/*                                                                  */
+/* Name                - mono_arch_lowering_pass.                          */
+/*                                                                  */
+/*------------------------------------------------------------------*/
+
 void
 mono_arch_lowering_pass (MonoCompile *cfg, MonoBasicBlock *bb)
 {
@@ -3885,8 +4006,15 @@ mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
                }
                        break;
                case OP_LOCALLOC: {
-                       int alloca_skip = S390_MINIMAL_STACK_SIZE + cfg->param_area;
-                       int area_offset = S390_ALIGN(alloca_skip, S390_STACK_ALIGNMENT);
+                       int alloca_skip;
+                       int area_offset;
+
+                       if (cfg->param_area == 0)
+                               alloca_skip = S390_MINIMAL_STACK_SIZE;
+                       else
+                               alloca_skip = cfg->param_area;
+
+                       area_offset = S390_ALIGN(alloca_skip, S390_STACK_ALIGNMENT);
                        s390_lgr  (code, s390_r1, ins->sreg1);
                        if (ins->flags & MONO_INST_INIT)
                                s390_lgr  (code, s390_r0, ins->sreg1);
@@ -3984,6 +4112,7 @@ mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
                        mono_add_patch_info (cfg, code-cfg->native_code, 
                                             MONO_PATCH_INFO_BB, ins->inst_target_bb);
                        s390_brasl (code, s390_r14, 0);
+                       mono_cfg_add_try_hole (cfg, ins->inst_eh_block, code, bb);
                }
                        break;
                case OP_LABEL: {
@@ -4396,24 +4525,35 @@ mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
                                                   ins->inst_offset, ins->sreg1, ins->inst_imm);
                                } else {
                                        s390_lgr  (code, s390_r0, ins->dreg);
-                                       if (s390_is_imm16 (ins->inst_offset)) {
-                                               s390_aghi (code, s390_r0, ins->inst_offset);
-                                       } else {
-                                               s390_basr (code, s390_r13, 0);
-                                               s390_j    (code, 6);
-                                               s390_llong(code, ins->inst_offset);
-                                               s390_a    (code, s390_r0, 0, s390_r13, 4);
+                                       if (ins->inst_offset > 0) {
+                                               if (s390_is_imm16 (ins->inst_offset)) {
+                                                       s390_aghi (code, s390_r0, ins->inst_offset);
+                                               } else {
+                                                       s390_basr (code, s390_r13, 0);
+                                                       s390_j    (code, 6);
+                                                       s390_llong(code, ins->inst_offset);
+                                                       s390_ag   (code, s390_r0, 0, s390_r13, 4);
+                                               }
                                        }
                                        s390_lgr  (code, s390_r12, ins->sreg1);
-                                       if (s390_is_imm16 (ins->inst_imm)) {
-                                               s390_aghi (code, s390_r12, ins->inst_imm);
+                                       if (ins->inst_imm > 0) {
+                                               if (s390_is_imm16 (ins->inst_imm)) {
+                                                       s390_aghi (code, s390_r12, ins->inst_imm);
+                                               } else {
+                                                       s390_basr (code, s390_r13, 0);
+                                                       s390_j    (code, 6);
+                                                       s390_llong(code, ins->inst_imm);
+                                                       s390_ag   (code, s390_r12, 0, s390_r13, 4);
+                                               }
+                                       }
+                                       if (s390_is_imm16 (ins->backend.size)) {
+                                               s390_lghi (code, s390_r1, ins->backend.size);
                                        } else {
                                                s390_basr (code, s390_r13, 0);
                                                s390_j    (code, 6);
-                                               s390_llong(code, ins->inst_imm);
-                                               s390_ag   (code, s390_r12, 0, s390_r13, 4);
+                                               s390_llong(code, ins->backend.size);
+                                               s390_lg   (code, s390_r1, 0, s390_r13, 4);
                                        }
-                                       s390_lgr  (code, s390_r1, ins->sreg1);
                                        s390_lgr  (code, s390_r13, s390_r1);
                                        s390_mvcle(code, s390_r0, s390_r12, 0, 0);
                                        s390_jo   (code, -2);
@@ -4903,13 +5043,13 @@ mono_arch_emit_prolog (MonoCompile *cfg)
                /*---------------------------------------------------------------*/
                /* On return from this call r2 have the address of the &lmf      */
                /*---------------------------------------------------------------*/
-               s390_basr(code, s390_r10, 0);
+               s390_basr(code, s390_r14, 0);
                s390_j   (code, 6);
                mono_add_patch_info (cfg, code - cfg->native_code, 
                                     MONO_PATCH_INFO_INTERNAL_METHOD, 
                                     (gpointer)"mono_get_lmf_addr");
                s390_llong(code, 0);
-               s390_lg   (code, s390_r1, 0, s390_r10, 4);
+               s390_lg   (code, s390_r1, 0, s390_r14, 4);
                s390_basr (code, s390_r14, s390_r1);
 
                /*---------------------------------------------------------------*/     
@@ -5114,7 +5254,8 @@ mono_arch_emit_exceptions (MonoCompile *cfg)
                                /*---------------------------------------------*/
                                s390_basr (code, s390_r13, 0);
                                s390_j    (code, 6);
-                               s390_llong(code, patch_info->data.target);
+//                             s390_llong(code, patch_info->data.target);
+                               s390_llong(code, exc_class->type_token);
                                /*---------------------------------------------*/
                                /* Load return address & parameter register    */
                                /*---------------------------------------------*/
@@ -5127,7 +5268,7 @@ mono_arch_emit_exceptions (MonoCompile *cfg)
                                s390_basr (code, s390_r13, 0);
                                s390_j    (code, 6);
                                patch_info->type      = MONO_PATCH_INFO_INTERNAL_METHOD;
-                               patch_info->data.name = "mono_arch_throw_exception_by_name";
+                               patch_info->data.name = "mono_arch_throw_corlib_exception";
                                patch_info->ip.i      = code - cfg->native_code;
                                s390_llong(code, 0);
                                s390_lg   (code, s390_r1, 0, s390_r13, 4);
@@ -5468,3 +5609,366 @@ mono_arch_context_get_int_reg (MonoContext *ctx, int reg)
 }
 
 /*========================= End of Function ========================*/
+
+/*------------------------------------------------------------------*/
+/*                                                                  */
+/* Name                - mono_arch_get_this_arg_from_call.                 */
+/*                                                                  */
+/* Function    -                                                   */
+/*                                                                 */
+/*------------------------------------------------------------------*/
+
+gpointer
+mono_arch_get_this_arg_from_call (MonoGenericSharingContext *gsctx, MonoMethodSignature *sig, mgreg_t *regs, guint8 *code)
+{
+       MonoLMF *lmf = (MonoLMF *) ((gchar *) regs - sizeof(MonoLMF));
+
+       /* FIXME: handle returning a struct */
+       if (MONO_TYPE_ISSTRUCT (sig->ret))
+               return (gpointer) lmf->gregs [s390_r3];
+       return (gpointer) lmf->gregs [s390_r2];
+}
+
+/*========================= End of Function ========================*/
+
+/*------------------------------------------------------------------*/
+/*                                                                  */
+/* Name                - get_delegate_invoke_impl.                         */
+/*                                                                  */
+/* Function    -                                                   */
+/*                                                                 */
+/*------------------------------------------------------------------*/
+
+static gpointer
+get_delegate_invoke_impl (gboolean has_target, guint32 param_count, guint32 *code_len, gboolean aot)
+{
+       guint8 *code, *start;
+
+       if (has_target) {
+               int size = 32;
+
+               start = code = mono_global_codeman_reserve (size);
+
+               /* Replace the this argument with the target */
+               s390_lg   (code, s390_r1, 0, s390_r2, G_STRUCT_OFFSET(MonoDelegate, method_ptr));
+               s390_lg   (code, s390_r2, 0, s390_r2, G_STRUCT_OFFSET(MonoDelegate, target));
+               s390_br   (code, s390_r1);
+               g_assert ((code - start) <= size);
+
+               mono_arch_flush_icache (start, size);
+       } else {
+               int size, i;
+
+               size = 32 + param_count * 8;
+               start = code = mono_global_codeman_reserve (size);
+
+               s390_lg   (code, s390_r1, 0, s390_r2, G_STRUCT_OFFSET(MonoDelegate, method_ptr));
+               /* slide down the arguments */
+               for (i = 0; i < param_count; ++i) {
+                       s390_lgr (code, (s390_r2 + i), (s390_r2 + i + 1));
+               }
+               s390_br   (code, s390_r1);
+
+               g_assert ((code - start) <= size);
+
+               mono_arch_flush_icache (start, size);
+       }
+
+       if (code_len)
+               *code_len = code - start;
+
+       return start;
+}
+
+/*========================= End of Function ========================*/
+
+/*------------------------------------------------------------------*/
+/*                                                                  */
+/* Name                - mono_arch_get_delegate_invoke_impls.              */
+/*                                                                  */
+/* Function    -                                                   */
+/*                                                                 */
+/*------------------------------------------------------------------*/
+
+GSList*
+mono_arch_get_delegate_invoke_impls (void)
+{
+       GSList *res = NULL;
+       guint8 *code;
+       guint32 code_len;
+       int i;
+
+       code = get_delegate_invoke_impl (TRUE, 0, &code_len, TRUE);
+       res = g_slist_prepend (res, mono_aot_tramp_info_create (g_strdup ("delegate_invoke_impl_has_target"), code, code_len));
+
+       for (i = 0; i < MAX_ARCH_DELEGATE_PARAMS; ++i) {
+               code = get_delegate_invoke_impl (FALSE, i, &code_len, TRUE);
+               res = g_slist_prepend (res, mono_aot_tramp_info_create (g_strdup_printf ("delegate_invoke_impl_target_%d", i), code, code_len));
+       }
+
+       return res;
+}
+
+/*========================= End of Function ========================*/
+
+/*------------------------------------------------------------------*/
+/*                                                                  */
+/* Name                - mono_arch_get_delegate_invoke_impl.               */
+/*                                                                  */
+/* Function    -                                                   */
+/*                                                                 */
+/*------------------------------------------------------------------*/
+
+gpointer
+mono_arch_get_delegate_invoke_impl (MonoMethodSignature *sig, gboolean has_target)
+{
+       guint8 *code, *start;
+
+       /* FIXME: Support more cases */
+       if (MONO_TYPE_ISSTRUCT (sig->ret))
+               return NULL;
+
+       if (has_target) {
+               static guint8* cached = NULL;
+
+               if (cached)
+                       return cached;
+
+               if (mono_aot_only)
+                       start = mono_aot_get_named_code ("delegate_invoke_impl_has_target");
+               else
+                       start = get_delegate_invoke_impl (TRUE, 0, NULL, FALSE);
+
+               mono_memory_barrier ();
+
+               cached = start;
+       } else {
+               static guint8* cache [MAX_ARCH_DELEGATE_PARAMS + 1] = {NULL};
+               int i;
+
+               if (sig->param_count > MAX_ARCH_DELEGATE_PARAMS)
+                       return NULL;
+               for (i = 0; i < sig->param_count; ++i)
+                       if (!mono_is_regsize_var (sig->params [i]))
+                               return NULL;
+
+
+               code = cache [sig->param_count];
+               if (code)
+                       return code;
+
+               if (mono_aot_only) {
+                       char *name = g_strdup_printf ("delegate_invoke_impl_target_%d", sig->param_count);
+                       start = mono_aot_get_named_code (name);
+                       g_free (name);
+               } else {
+                       start = get_delegate_invoke_impl (FALSE, sig->param_count, NULL, FALSE);
+               }
+
+               mono_memory_barrier ();
+
+               cache [sig->param_count] = start;
+       }
+       return start;
+}
+
+/*========================= End of Function ========================*/
+
+/*------------------------------------------------------------------*/
+/*                                                                  */
+/* Name                - mono_arch_build_imt_thunk.                        */
+/*                                                                  */
+/* Function    -                                                   */
+/*                                                                 */
+/*------------------------------------------------------------------*/
+
+gpointer
+mono_arch_build_imt_thunk (MonoVTable *vtable, MonoDomain *domain, 
+                          MonoIMTCheckItem **imt_entries, int count,
+                          gpointer fail_tramp)
+{
+       int i;
+       int size = 0;
+       guchar *code, *start;
+
+       for (i = 0; i < count; ++i) {
+               MonoIMTCheckItem *item = imt_entries [i];
+               if (item->is_equals) {
+                       if (item->check_target_idx) {
+                               if (!item->compare_done)
+                                       item->chunk_size += CMP_SIZE + JUMP_SIZE;
+                               if (item->has_target_code)
+                                       item->chunk_size += BR_SIZE + JUMP_SIZE + LOADCON_SIZE;
+                               else
+                                       item->chunk_size += BR_SIZE + JUMP_SIZE + LOADCON_SIZE + 
+                                                           LOAD_SIZE;
+                       } else {
+                               if (fail_tramp) {
+                                       item->chunk_size += CMP_SIZE + 2 * BR_SIZE + JUMP_SIZE + 
+                                                           2 * LOADCON_SIZE;
+                                       if (!item->has_target_code)
+                                               item->chunk_size += LOAD_SIZE;
+                               } else {
+                                       item->chunk_size += LOADCON_SIZE + LOAD_SIZE + BR_SIZE;
+#if ENABLE_WRONG_METHOD_CHECK
+                                       item->chunk_size += CMP_SIZE + JUMP_SIZE;
+#endif
+                               }
+                       }
+               } else {
+                       item->chunk_size += CMP_SIZE + JUMP_SIZE;
+                       imt_entries [item->check_target_idx]->compare_done = TRUE;
+               }
+               size += item->chunk_size;
+       }
+
+       if (fail_tramp)
+               code = mono_method_alloc_generic_virtual_thunk (domain, size);
+       else
+               code = mono_domain_code_reserve (domain, size);
+
+       start = code;
+
+       for (i = 0; i < count; ++i) {
+               MonoIMTCheckItem *item = imt_entries [i];
+               item->code_target = (guint8 *) code;
+               if (item->is_equals) {
+                       if (item->check_target_idx) {
+                               if (!item->compare_done) {
+                                       s390_basr (code, s390_r13, s390_r0);
+                                       s390_j    (code, 6);
+                                       s390_llong(code, item->key);
+                                       s390_lg   (code, s390_r0, 0, s390_r13, 4);
+                                       s390_cgr  (code, s390_r0, MONO_ARCH_IMT_REG);
+                               }
+                               item->jmp_code = (guint8*) code;
+                               s390_jcl (code, S390_CC_NE, 0);
+                               
+                               s390_basr (code, s390_r13, s390_r0);
+                               s390_j    (code, 6);
+                               if (item->has_target_code)  {
+                                       s390_llong(code, item->value.target_code);
+                                       s390_lg   (code, s390_r1, 0, s390_r13, 4);
+                               } else {        
+                                       s390_llong(code, (&(vtable->vtable [item->value.vtable_slot])));
+                                       s390_lg   (code, s390_r1, 0, s390_r13, 4);
+                                       s390_lg   (code, s390_r1, 0, s390_r1, 0);
+                               }
+                               s390_br   (code, s390_r1);
+                       } else {
+                               if (fail_tramp) {
+                                       gint64  target;
+
+                                       s390_basr (code, s390_r13, s390_r0);
+                                       s390_j    (code, 6);
+                                       s390_llong(code, item->key);
+                                       s390_lg   (code, s390_r0, 0, s390_r13, 4);
+                                       s390_cgr  (code, s390_r0, MONO_ARCH_IMT_REG);
+                                       item->jmp_code = (guint8*) code;
+                                       s390_jcl  (code, S390_CC_NE, 0);
+                                       s390_basr (code, s390_r13, s390_r0);
+                                       s390_j    (code, 6);
+                                       if (item->has_target_code) {
+                                               s390_llong(code, item->value.target_code);
+                                               s390_lg   (code, s390_r1, 0, s390_r13, 4);
+                                       } else {
+                                               g_assert (vtable);
+                                               s390_llong(code, (&(vtable->vtable [item->value.vtable_slot])));
+                                               s390_lg   (code, s390_r1, 0, s390_r13, 4);
+                                               s390_lg   (code, s390_r1, 0, s390_r1, 0);
+                                       }
+                                       s390_br   (code, s390_r1);
+                                       target = S390_RELATIVE(item->jmp_code, code);
+                                       s390_patch_rel(item->jmp_code+2, target);
+                                       s390_basr (code, s390_r13, s390_r0);
+                                       s390_j    (code, 6);
+                                       s390_llong(code, fail_tramp);
+                                       s390_lg   (code, s390_r1, 0, s390_r13, 4);
+                                       s390_br   (code, s390_r1);
+                                       item->jmp_code = NULL;
+                               } else {
+                               /* enable the commented code to assert on wrong method */
+#if ENABLE_WRONG_METHOD_CHECK
+                                       g_assert_not_reached ();
+#endif
+                                       s390_basr (code, s390_r13, s390_r0);
+                                       s390_j    (code, 6);
+                                       s390_llong(code, (&(vtable->vtable [item->value.vtable_slot])));
+                                       s390_lg   (code, s390_r1, 0, s390_r13, 4);
+                                       s390_lg   (code, s390_r1, 0, s390_r1, 0);
+                                       s390_br   (code, s390_r1);
+#if ENABLE_WRONG_METHOD_CHECK
+                                       g_assert_not_reached ();
+#endif
+                               }
+                       }
+               } else {
+                       s390_basr (code, s390_r13, s390_r0);
+                       s390_j    (code, 6);
+                       s390_llong(code, item->key);
+                       s390_lg   (code, s390_r0, 0, s390_r13, 4);
+                       s390_cgr  (code, MONO_ARCH_IMT_REG, s390_r0);
+                       item->jmp_code = (guint8 *) code;
+                       s390_jcl  (code, S390_CC_GE, 0);
+               }
+       }
+       /* patch the branches to get to the target items */
+       for (i = 0; i < count; ++i) {
+               MonoIMTCheckItem *item = imt_entries [i];
+               if (item->jmp_code) {
+                       if (item->check_target_idx) {
+                               gint64 offset;
+                               offset = S390_RELATIVE(imt_entries [item->check_target_idx]->code_target,
+                                                      item->jmp_code);
+                               s390_patch_rel ((guchar *) item->jmp_code + 2, (guint64) offset);
+                       }
+               }
+       }
+
+       mono_arch_flush_icache ((guint8*)start, (code - start));
+
+       if (!fail_tramp)
+               mono_stats.imt_thunks_size += (code - start);
+
+       g_assert (code - start <= size);
+
+       return (start);
+}
+
+/*========================= End of Function ========================*/
+
+/*------------------------------------------------------------------*/
+/*                                                                  */
+/* Name                - mono_arch_find_imt_method.                        */
+/*                                                                  */
+/* Function    - Get the method address from MONO_ARCH_IMT_REG     */
+/*               found in the save area.                           */
+/*                                                                 */
+/*------------------------------------------------------------------*/
+
+MonoMethod*
+mono_arch_find_imt_method (mgreg_t *regs, guint8 *code)
+{
+       MonoLMF *lmf = (MonoLMF *) ((gchar *) regs - sizeof(MonoLMF));
+
+       return ((MonoMethod *) lmf->gregs [MONO_ARCH_IMT_REG]);
+}
+
+/*========================= End of Function ========================*/
+
+/*------------------------------------------------------------------*/
+/*                                                                  */
+/* Name                - mono_arch_find_this_argument.                     */
+/*                                                                  */
+/* Function    -                                                   */
+/*                                                                 */
+/*------------------------------------------------------------------*/
+
+MonoObject *
+mono_arch_find_this_argument (mgreg_t *regs, MonoMethod *method, 
+                             MonoGenericSharingContext *gsctx)
+{
+        return mono_arch_get_this_arg_from_call (gsctx, mono_method_signature (method), regs, NULL);
+}  
+
+/*========================= End of Function ========================*/
index 62545a57e87c29fd89ae5f9e83c1b1d6371c6d29..f15de7cfef7cb3964f47d5d77892f3851d39b116 100644 (file)
@@ -63,17 +63,60 @@ typedef struct
        void *return_address;
 } MonoS390StackFrame;
 
+typedef struct
+{
+       char    n3:1;           // N3 instructions present
+       char    zArch:1;        // z/Architecture mode installed
+       char    zAct:1;         // z/Architecture mode active
+       char    date:1;         // DATE enhancement facility
+       char    idte1:1;        // IDTE present (PST)
+       char    idte2:1;        // IDTE present (REG)
+       char    asnlx:1;        // ASN and LX reuse facility
+       char    stfle:1;        // STFLE installed
+       char    zDATe:1;        // Enhanced DAT in z mode
+       char    srstat:1;       // Sense running status facility
+       char    cSSKE:1;        // Conditional SSKE facility
+       char    topo:1;         // COnfiguration topology facility
+       char    xTrans2:1;      // Extended translation facility 2
+       char    msgSec:1;       // Message security facility
+       char    longDsp:1;      // Long displacement facility
+       char    hiPerfLD:1;     // High performance long displacement facility
+       char    hfpMAS:1;       // HFP multiply-and-add/subtrace facility
+       char    xImm:1;         // Extended immediate facility
+       char    xTrans3:1;      // Extended translation facility 3
+       char    hfpUnX:1;       // HFP unnormalized extension facility
+       char    etf2:1;         // ETF2-enhancement facility
+       char    stckf:1;        // Store-clock-fast facility
+       char    parse:1;        // Parsing enhancement facility
+       char    mvcos:1;        // MVCOS facility
+       char    todSteer:1;     // TOD-clock steering facility
+       char    etf3:1;         // ETF3-enhancement facility
+       char    xCPUtm:1;       // Extract CPU time facility
+       char    csst:1;         // Compare-swap-and-store facility
+       char    csst2:1;        // Compare-swap-and-store facility 2
+       char    giX:1;          // General instructions extension facility
+       char    exX:1;          // Execute extensions facility
+       char    ibm:1;          // IBM internal use
+       char    fps:1;          // Floating point support enhancement
+       char    dfp:1;          // Decimal floating point facility
+       char    hiDFP:1;        // High Performance DFP facility
+       char    pfpo:1;         // PFPO instruction facility
+} __attribute__((aligned(8))) facilityList_t;
+       
 // #define MONO_ARCH_SIGSEGV_ON_ALTSTACK               1
-#define MONO_ARCH_EMULATE_LCONV_TO_R8_UN       1
-#define MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS     1
-#define MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS    1
-#define MONO_ARCH_HAVE_IS_INT_OVERFLOW         1
-#define MONO_ARCH_NEED_DIV_CHECK               1
-#define MONO_ARCH_HAVE_ATOMIC_ADD 1
-#define MONO_ARCH_HAVE_ATOMIC_EXCHANGE 1
-#define MONO_ARCH_SIGNAL_STACK_SIZE            256*1024
-#define MONO_ARCH_HAVE_DECOMPOSE_OPTS 1
-// #define MONO_ARCH_HAVE_THROW_CORLIB_EXCEPTION       1
+#define MONO_ARCH_EMULATE_LCONV_TO_R8_UN               1
+#define MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS             1
+#define MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS            1
+#define MONO_ARCH_HAVE_IS_INT_OVERFLOW                 1
+#define MONO_ARCH_NEED_DIV_CHECK                       1
+#define MONO_ARCH_HAVE_ATOMIC_ADD                      1
+#define MONO_ARCH_HAVE_ATOMIC_EXCHANGE                         1
+#define MONO_ARCH_SIGNAL_STACK_SIZE                    256*1024
+#define MONO_ARCH_HAVE_DECOMPOSE_OPTS                  1
+#define MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE      1
+#define MONO_ARCH_HAVE_THROW_CORLIB_EXCEPTION          1
+#define MONO_ARCH_HAVE_IMT                             1
+#define MONO_ARCH_IMT_REG                              s390_r9
 #define MONO_ARCH_HAVE_THROW_EXCEPTION_BY_NAME 1
 
 #define MONO_ARCH_USE_SIGACTION        1
index 985ce563c6dc39405e32099a1e72d053b25ef39d..eb94c7c862b2c0a1480b51266c098b00f931e09f 100644 (file)
@@ -3214,6 +3214,7 @@ mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
                        /* This is a jump inside the method, so call_simple works even on V9 */
                        sparc_call_simple (code, 0);
                        sparc_nop (code);
+                       mono_cfg_add_try_hole (cfg, ins->inst_eh_block, code, bb);
                        break;
                case OP_LABEL:
                        ins->inst_c0 = (guint8*)code - cfg->native_code;
index 9eef82842b836c6f5af1fdcda2011c0429c1c148..94a4f480ce3fb378f5d143c75cce637ea6577bb3 100644 (file)
@@ -7,6 +7,7 @@
 #include <mono/metadata/marshal.h>
 #include <mono/metadata/tabledefs.h>
 #include <mono/utils/mono-counters.h>
+#include <mono/utils/mono-error-internals.h>
 
 #include "mini.h"
 #include "debug-mini.h"
@@ -559,9 +560,8 @@ common_call_trampoline (mgreg_t *regs, guint8 *code, gpointer arg, guint8* tramp
                guint8 *plt_entry = mono_aot_get_plt_entry (code);
 
                if (plt_entry) {
-                       mono_arch_patch_plt_entry (plt_entry, NULL, regs, addr);
-               } else if (!generic_shared || (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
-                       mono_domain_lookup_shared_generic (mono_domain_get (), declaring)) {
+                               mono_aot_patch_plt_entry (plt_entry, NULL, regs, addr);
+               } else {
                        if (generic_shared) {
                                if (m->wrapper_type != MONO_WRAPPER_NONE)
                                        m = mono_marshal_method_from_wrapper (m);
@@ -569,9 +569,7 @@ common_call_trampoline (mgreg_t *regs, guint8 *code, gpointer arg, guint8* tramp
                        }
 
                        /* Patch calling code */
-                       if (plt_entry) {
-
-                       } else {
+                       {
                                MonoJitInfo *target_ji = 
                                        mono_jit_info_table_find (mono_domain_get (), mono_get_addr_from_ftnptr (compiled_method));
 
@@ -706,9 +704,7 @@ mono_aot_trampoline (mgreg_t *regs, guint8 *code, guint8 *token_info,
        MonoMethod *method = NULL;
        gpointer addr;
        gpointer *vtable_slot;
-       gboolean is_got_entry;
        guint8 *plt_entry;
-       gboolean need_rgctx_tramp = FALSE;
 
        trampoline_calls ++;
 
@@ -734,25 +730,7 @@ mono_aot_trampoline (mgreg_t *regs, guint8 *code, guint8 *token_info,
        plt_entry = mono_aot_get_plt_entry (code);
        g_assert (plt_entry);
 
-       mono_arch_patch_plt_entry (plt_entry, NULL, regs, addr);
-
-       is_got_entry = FALSE;
-
-       /*
-        * Since AOT code is only used in the root domain, 
-        * mono_domain_get () != mono_get_root_domain () means the calling method
-        * is AppDomain:InvokeInDomain, so this is the same check as in 
-        * mono_method_same_domain () but without loading the metadata for the method.
-        */
-       if ((is_got_entry && (mono_domain_get () == mono_get_root_domain ())) || mono_domain_owns_vtable_slot (mono_domain_get (), vtable_slot)) {
-#ifdef MONO_ARCH_HAVE_IMT
-               gboolean variance_used = FALSE;
-               if (!method)
-                       method = mono_get_method (image, token, NULL);
-               vtable_slot = mono_convert_imt_slot_to_vtable_slot (vtable_slot, regs, code, method, NULL, &need_rgctx_tramp, &variance_used);
-#endif
-               *vtable_slot = addr;
-       }
+       mono_aot_patch_plt_entry (plt_entry, NULL, regs, addr);
 
        return addr;
 }
@@ -882,6 +860,8 @@ mono_delegate_trampoline (mgreg_t *regs, guint8 *code, gpointer *tramp_data, gui
        MonoMethod *invoke = tramp_data [0];
        guint8 *impl_this = tramp_data [1];
        guint8 *impl_nothis = tramp_data [2];
+       MonoError err;
+       MonoMethodSignature *sig;
 
        trampoline_calls ++;
 
@@ -910,14 +890,29 @@ mono_delegate_trampoline (mgreg_t *regs, guint8 *code, gpointer *tramp_data, gui
 #endif
                                method = mono_marshal_get_remoting_invoke (method);
                }
-               else if (mono_method_signature (method)->hasthis && method->klass->valuetype)
-                       method = mono_marshal_get_unbox_wrapper (method);
+               else {
+                       mono_error_init (&err);
+                       sig = mono_method_signature_checked (method, &err);
+                       if (!sig)
+                               mono_error_raise_exception (&err);
+                               
+                       if (sig->hasthis && method->klass->valuetype)
+                               method = mono_marshal_get_unbox_wrapper (method);
+               }
        } else {
                ji = mono_jit_info_table_find (domain, mono_get_addr_from_ftnptr (delegate->method_ptr));
                if (ji)
                        method = ji->method;
        }
-       callvirt = !delegate->target && method && mono_method_signature (method)->hasthis;
+
+       if (method) {
+               mono_error_init (&err);
+               sig = mono_method_signature_checked (method, &err);
+               if (!sig)
+                       mono_error_raise_exception (&err);
+
+               callvirt = !delegate->target && sig->hasthis;
+       }
 
        if (method && method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
                method = mono_marshal_get_synchronized_wrapper (method);
@@ -971,6 +966,60 @@ mono_delegate_trampoline (mgreg_t *regs, guint8 *code, gpointer *tramp_data, gui
 
 #endif
 
+#ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
+static gpointer
+mono_handler_block_guard_trampoline (mgreg_t *regs, guint8 *code, gpointer *tramp_data, guint8* tramp)
+{
+       MonoContext ctx;
+       MonoException *exc;
+       MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
+       gpointer resume_ip = jit_tls->handler_block_return_address;
+
+       memcpy (&ctx, &jit_tls->ex_ctx, sizeof (MonoContext));
+       MONO_CONTEXT_SET_IP (&ctx, jit_tls->handler_block_return_address);
+
+       jit_tls->handler_block_return_address = NULL;
+       jit_tls->handler_block = NULL;
+
+       if (!resume_ip) /*this should not happen, but we should avoid crashing */
+               exc = mono_get_exception_execution_engine ("Invalid internal state, resuming abort after handler block but no resume ip found");
+       else
+               exc = mono_thread_resume_interruption ();
+
+       if (exc) {
+               static void (*restore_context) (MonoContext *);
+
+               if (!restore_context)
+                       restore_context = mono_get_restore_context ();
+
+               mono_handle_exception (&ctx, exc, NULL, FALSE);
+               restore_context (&ctx);
+       }
+
+       return resume_ip;
+}
+
+gpointer
+mono_create_handler_block_trampoline (void)
+{
+       static gpointer code;
+
+       if (mono_aot_only) {
+               g_assert (0);
+               return code;
+       }
+
+       mono_trampolines_lock ();
+
+       if (!code)
+               code = mono_arch_create_handler_block_trampoline ();
+
+       mono_trampolines_unlock ();
+
+       return code;
+}
+#endif
+
 /*
  * mono_get_trampoline_func:
  *
@@ -1011,6 +1060,10 @@ mono_get_trampoline_func (MonoTrampolineType tramp_type)
 #ifdef MONO_ARCH_LLVM_SUPPORTED
        case MONO_TRAMPOLINE_LLVM_VCALL:
                return mono_llvm_vcall_trampoline;
+#endif
+#ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
+       case MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD:
+               return mono_handler_block_guard_trampoline;
 #endif
        default:
                g_assert_not_reached ();
@@ -1045,6 +1098,10 @@ mono_trampolines_init (void)
 #ifdef MONO_ARCH_LLVM_SUPPORTED
        mono_trampoline_code [MONO_TRAMPOLINE_LLVM_VCALL] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_LLVM_VCALL);
 #endif
+#ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
+       mono_trampoline_code [MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD);
+       mono_create_handler_block_trampoline ();
+#endif
 
        mono_counters_register ("Calls to trampolines", MONO_COUNTER_JIT | MONO_COUNTER_INT, &trampoline_calls);
 }
index 31e84791f5305a9bd9e865729f127e9f4ed9c5d8..4f2715a6f4849a95b341b1b28342e3198bc7587c 100644 (file)
@@ -733,17 +733,17 @@ mono_arch_cpu_enumerate_simd_versions (void)
 
        if (cpuid (1, &eax, &ebx, &ecx, &edx)) {
                if (edx & (1 << 25))
-                       sse_opts |= 1 << SIMD_VERSION_SSE1;
+                       sse_opts |= SIMD_VERSION_SSE1;
                if (edx & (1 << 26))
-                       sse_opts |= 1 << SIMD_VERSION_SSE2;
+                       sse_opts |= SIMD_VERSION_SSE2;
                if (ecx & (1 << 0))
-                       sse_opts |= 1 << SIMD_VERSION_SSE3;
+                       sse_opts |= SIMD_VERSION_SSE3;
                if (ecx & (1 << 9))
-                       sse_opts |= 1 << SIMD_VERSION_SSSE3;
+                       sse_opts |= SIMD_VERSION_SSSE3;
                if (ecx & (1 << 19))
-                       sse_opts |= 1 << SIMD_VERSION_SSE41;
+                       sse_opts |= SIMD_VERSION_SSE41;
                if (ecx & (1 << 20))
-                       sse_opts |= 1 << SIMD_VERSION_SSE42;
+                       sse_opts |= SIMD_VERSION_SSE42;
        }
 
        /* Yes, all this needs to be done to check for sse4a.
@@ -754,7 +754,7 @@ mono_arch_cpu_enumerate_simd_versions (void)
                if ((((unsigned int) eax) >= 0x80000001) && (ebx == 0x68747541) && (ecx == 0x444D4163) && (edx == 0x69746E65)) {
                        cpuid (0x80000001, &eax, &ebx, &ecx, &edx);
                        if (ecx & (1 << 6))
-                               sse_opts |= 1 << SIMD_VERSION_SSE4a;
+                               sse_opts |= SIMD_VERSION_SSE4a;
                }
        }
 
@@ -1163,6 +1163,7 @@ mono_arch_get_llvm_call_info (MonoCompile *cfg, MonoMethodSignature *sig)
        CallInfo *cinfo;
        ArgInfo *ainfo;
        LLVMCallInfo *linfo;
+       MonoType *t;
 
        n = sig->param_count + sig->hasthis;
 
@@ -1206,6 +1207,11 @@ mono_arch_get_llvm_call_info (MonoCompile *cfg, MonoMethodSignature *sig)
        for (i = 0; i < n; ++i) {
                ainfo = cinfo->args + i;
 
+               if (i >= sig->hasthis)
+                       t = sig->params [i - sig->hasthis];
+               else
+                       t = &mono_defaults.int_class->byval_arg;
+
                linfo->args [i].storage = LLVMArgNone;
 
                switch (ainfo->storage) {
@@ -1217,16 +1223,19 @@ mono_arch_get_llvm_call_info (MonoCompile *cfg, MonoMethodSignature *sig)
                        linfo->args [i].storage = LLVMArgInFPReg;
                        break;
                case ArgOnStack:
-                       if ((i >= sig->hasthis) && (MONO_TYPE_ISSTRUCT(sig->params [i - sig->hasthis]))) {
-                               linfo->args [i].storage = LLVMArgVtypeByVal;
+                       if (MONO_TYPE_ISSTRUCT (t)) {
+                               if (mono_class_value_size (mono_class_from_mono_type (t), NULL) == 0)
+                               /* LLVM seems to allocate argument space for empty structures too */
+                                       linfo->args [i].storage = LLVMArgNone;
+                               else
+                                       linfo->args [i].storage = LLVMArgVtypeByVal;
                        } else {
                                linfo->args [i].storage = LLVMArgInIReg;
-                               if (!sig->params [i - sig->hasthis]->byref) {
-                                       if (sig->params [i - sig->hasthis]->type == MONO_TYPE_R4) {
+                               if (t->byref) {
+                                       if (t->type == MONO_TYPE_R4)
                                                linfo->args [i].storage = LLVMArgInFPReg;
-                                       } else if (sig->params [i - sig->hasthis]->type == MONO_TYPE_R8) {
+                                       else if (t->type == MONO_TYPE_R8)
                                                linfo->args [i].storage = LLVMArgInFPReg;
-                                       }
                                }
                        }
                        break;
@@ -2029,6 +2038,23 @@ emit_move_return_value (MonoCompile *cfg, MonoInst *ins, guint8 *code)
        return code;
 }
 
+gboolean
+mono_x86_have_tls_get (void)
+{
+#ifdef __APPLE__
+       guint32 *ins = (guint32*)pthread_getspecific;
+       /*
+        * We're looking for these two instructions:
+        *
+        * mov    0x4(%esp),%eax
+        * mov    %gs:0x48(,%eax,4),%eax
+        */
+       return ins [0] == 0x0424448b && ins [1] == 0x85048b65 && ins [2] == 0x00000048;
+#else
+       return TRUE;
+#endif
+}
+
 /*
  * mono_x86_emit_tls_get:
  * @code: buffer to store code to
@@ -2044,7 +2070,10 @@ emit_move_return_value (MonoCompile *cfg, MonoInst *ins, guint8 *code)
 guint8*
 mono_x86_emit_tls_get (guint8* code, int dreg, int tls_offset)
 {
-#ifdef TARGET_WIN32
+#if defined(__APPLE__)
+       x86_prefix (code, X86_GS_PREFIX);
+       x86_mov_reg_mem (code, dreg, 0x48 + tls_offset * 4, 4);
+#elif defined(TARGET_WIN32)
        /* 
         * See the Under the Hood article in the May 1996 issue of Microsoft Systems 
         * Journal and/or a disassembly of the TlsGet () function.
@@ -2981,6 +3010,7 @@ mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb)
                        x86_alu_reg_imm (code, X86_SUB, X86_ESP, MONO_ARCH_FRAME_ALIGNMENT - 4);
                        mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_target_bb);
                        x86_call_imm (code, 0);
+                       mono_cfg_add_try_hole (cfg, ins->inst_eh_block, code, bb);
                        x86_alu_reg_imm (code, X86_ADD, X86_ESP, MONO_ARCH_FRAME_ALIGNMENT - 4);
                        break;
                case OP_START_HANDLER: {
@@ -5783,6 +5813,50 @@ mono_arch_decompose_long_opts (MonoCompile *cfg, MonoInst *long_ins)
 #endif /* MONO_ARCH_SIMD_INTRINSICS */
 }
 
+/*MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD*/
+gpointer
+mono_arch_install_handler_block_guard (MonoJitInfo *ji, MonoJitExceptionInfo *clause, MonoContext *ctx, gpointer new_value)
+{
+       int offset;
+       gpointer *sp, old_value;
+       char *bp;
+       const unsigned char *handler;
+
+       /*Decode the first instruction to figure out where did we store the spvar*/
+       /*Our jit MUST generate the following:
+        mov %esp, -?(%ebp)
+        Which is encoded as: 0x89 mod_rm.
+        mod_rm (esp, ebp, imm) which can be: (imm will never be zero)
+               mod (reg + imm8):  01 reg(esp): 100 rm(ebp): 101 -> 01100101 (0x65)
+               mod (reg + imm32): 10 reg(esp): 100 rm(ebp): 101 -> 10100101 (0xA5)
+       */
+       handler = clause->handler_start;
+
+       if (*handler != 0x89)
+               return NULL;
+
+       ++handler;
+
+       if (*handler == 0x65)
+               offset = *(signed char*)(handler + 1);
+       else if (*handler == 0xA5)
+               offset = *(int*)(handler + 1);
+       else
+               return NULL;
+
+       /*Load the spvar*/
+       bp = MONO_CONTEXT_GET_BP (ctx);
+       sp = *(gpointer*)(bp + offset);
+
+       old_value = *sp;
+       if (old_value < ji->code_start || (char*)old_value > ((char*)ji->code_start + ji->code_size))
+               return old_value;
+
+       *sp = new_value;
+
+       return old_value;
+}
+
 #if __APPLE__
 #define DBG_SIGNAL SIGBUS
 #else
index bfd8d282a7fc786c3d9d8c00ebe22f5ce5961195..f3680d0b5235fb7d607b4ad85317fbe8ea0c3b8d 100644 (file)
@@ -44,7 +44,14 @@ LONG CALLBACK seh_handler(EXCEPTION_POINTERS* ep);
 
 #endif /* HOST_WIN32 */
 
-#if defined( __linux__) || defined(__sun) || defined(__APPLE__) || defined(__NetBSD__) || defined(__FreeBSD__)
+#ifdef __HAIKU__
+struct sigcontext {
+       vregs regs;
+};
+#endif /* __HAIKU__ */
+
+#if defined( __linux__) || defined(__sun) || defined(__APPLE__) || defined(__NetBSD__) || \
+       defined(__FreeBSD__) || defined(__OpenBSD__)
 #define MONO_ARCH_USE_SIGACTION
 #endif
 
@@ -58,7 +65,10 @@ LONG CALLBACK seh_handler(EXCEPTION_POINTERS* ep);
 #ifndef __sun
 #define MONO_ARCH_SIGSEGV_ON_ALTSTACK
 #endif
+/* Haiku doesn't have SA_SIGINFO */
+#ifndef __HAIKU__
 #define MONO_ARCH_USE_SIGACTION
+#endif /* __HAIKU__ */
 
 #endif /* HAVE_WORKING_SIGALTSTACK */
 #endif /* !HOST_WIN32 */
@@ -160,6 +170,16 @@ typedef struct {
 # define SC_ESP sc_esp
 # define SC_EDI sc_edi
 # define SC_ESI sc_esi
+#elif defined(__HAIKU__)
+# define SC_EAX regs.eax
+# define SC_EBX regs._reserved_2[2]
+# define SC_ECX regs.ecx
+# define SC_EDX regs.edx
+# define SC_EBP regs.ebp
+# define SC_EIP regs.eip
+# define SC_ESP regs.esp
+# define SC_EDI regs._reserved_2[0]
+# define SC_ESI regs._reserved_2[1]
 #else
 # define SC_EAX eax
 # define SC_EBX ebx
@@ -242,7 +262,7 @@ typedef struct {
 #define MONO_ARCH_HAVE_ATOMIC_EXCHANGE 1
 #define MONO_ARCH_HAVE_ATOMIC_CAS 1
 #define MONO_ARCH_HAVE_IMT 1
-#define MONO_ARCH_HAVE_TLS_GET 1
+#define MONO_ARCH_HAVE_TLS_GET (mono_x86_have_tls_get ())
 #define MONO_ARCH_IMT_REG X86_EDX
 #define MONO_ARCH_VTABLE_REG X86_EDX
 #define MONO_ARCH_RGCTX_REG X86_EDX
@@ -274,9 +294,14 @@ typedef struct {
 #define MONO_ARCH_GSHARED_SUPPORTED 1
 #define MONO_ARCH_HAVE_LLVM_IMT_TRAMPOLINE 1
 #define MONO_ARCH_LLVM_SUPPORTED 1
+
+#if defined(MONO_ARCH_USE_SIGACTION) || defined(TARGET_WIN32)
 #define MONO_ARCH_SOFT_DEBUG_SUPPORTED 1
+#endif
+
 #define MONO_ARCH_HAVE_FIND_JIT_INFO_EXT 1
 #define MONO_ARCH_HAVE_EXCEPTIONS_INIT 1
+#define MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD 1
 
 /* Used for optimization, not complete */
 #define MONO_ARCH_IS_OP_MEMBASE(opcode) ((opcode) == OP_X86_PUSH_MEMBASE)
@@ -304,5 +329,8 @@ mono_x86_emit_tls_get (guint8* code, int dreg, int tls_offset) MONO_INTERNAL;
 guint32
 mono_x86_get_this_arg_offset (MonoGenericSharingContext *gsctx, MonoMethodSignature *sig) MONO_INTERNAL;
 
+gboolean
+mono_x86_have_tls_get (void) MONO_INTERNAL;
+
 #endif /* __MONO_MINI_X86_H__ */  
 
index 797fe2417142a0a861f314276da8286e124a9d5d..87b7cc6c73fb7e304f754cc9580ad03a52e9a6fb 100644 (file)
@@ -114,18 +114,13 @@ static int methods_with_llvm, methods_without_llvm;
 /*
  * This flag controls whenever the runtime uses LLVM compiled code.
  * Enabling this causes different/slower code paths to be used, which is why it
- * defaults to FALSE if ENABLE_LLVM is not defined, i.e. the runtime is only capable of
- * running AOT code compiled by LLVM.
+ * defaults to FALSE.
  * Changes when this flag is set include:
  * - a per method vtable trampoline is used to handle virtual calls, instead of only
  *   one trampoline.
  * - fast generic virtual calls are not supported.
  */
-#ifdef ENABLE_LLVM
-gboolean mono_use_llvm = TRUE;
-#else
 gboolean mono_use_llvm = FALSE;
-#endif
 
 #define mono_jit_lock() EnterCriticalSection (&jit_mutex)
 #define mono_jit_unlock() LeaveCriticalSection (&jit_mutex)
@@ -169,6 +164,12 @@ mono_running_on_valgrind (void)
                return FALSE;
 }
 
+typedef struct {
+       MonoExceptionClause *clause;
+       MonoBasicBlock *basic_block;
+       int start_offset;
+} TryBlockHole;
+
 typedef struct {
        void *ip;
        MonoMethod *method;
@@ -2461,18 +2462,19 @@ static MonoInst*
 mono_create_tls_get (MonoCompile *cfg, int offset)
 {
 #ifdef MONO_ARCH_HAVE_TLS_GET
-       MonoInst* ins;
-       
-       if (offset == -1)
-               return NULL;
-       
-       MONO_INST_NEW (cfg, ins, OP_TLS_GET);
-       ins->dreg = mono_alloc_preg (cfg);
-       ins->inst_offset = offset;
-       return ins;
-#else
-       return NULL;
+       if (MONO_ARCH_HAVE_TLS_GET) {
+               MonoInst* ins;
+
+               if (offset == -1)
+                       return NULL;
+
+               MONO_INST_NEW (cfg, ins, OP_TLS_GET);
+               ins->dreg = mono_alloc_preg (cfg);
+               ins->inst_offset = offset;
+               return ins;
+       }
 #endif
+       return NULL;
 }
 
 MonoInst*
@@ -3244,6 +3246,7 @@ mono_codegen (MonoCompile *cfg)
                bb->native_offset = cfg->code_len;
                //if ((bb == cfg->bb_entry) || !(bb->region == -1 && !bb->dfn))
                        mono_arch_output_basic_block (cfg, bb);
+               bb->native_length = cfg->code_len - bb->native_offset;
 
                if (bb == cfg->bb_exit) {
                        cfg->epilog_begin = cfg->code_len;
@@ -3363,10 +3366,12 @@ compute_reachable (MonoBasicBlock *bb)
 static MonoJitInfo*
 create_jit_info (MonoCompile *cfg, MonoMethod *method_to_compile)
 {
+       GSList *tmp;
        MonoMethodHeader *header;
        MonoJitInfo *jinfo;
        int num_clauses;
        int generic_info_size;
+       int holes_size = 0, num_holes = 0;
 
        g_assert (method_to_compile == cfg->method);
        header = cfg->header;
@@ -3376,6 +3381,24 @@ create_jit_info (MonoCompile *cfg, MonoMethod *method_to_compile)
        else
                generic_info_size = 0;
 
+       if (cfg->try_block_holes) {
+               for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
+                       TryBlockHole *hole = tmp->data;
+                       MonoExceptionClause *ec = hole->clause;
+                       int hole_end = hole->basic_block->native_offset + hole->basic_block->native_length;
+                       MonoBasicBlock *clause_last_bb = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
+                       g_assert (clause_last_bb);
+
+                       /* Holes at the end of a try region can be represented by simply reducing the size of the block itself.*/
+                       if (clause_last_bb->native_offset != hole_end)
+                               ++num_holes;
+               }
+               if (num_holes)
+                       holes_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
+               if (G_UNLIKELY (cfg->verbose_level >= 4))
+                       printf ("Number of try block holes %d\n", num_holes);
+       }
+
        if (COMPILE_LLVM (cfg))
                num_clauses = cfg->llvm_ex_info_len;
        else
@@ -3383,11 +3406,11 @@ create_jit_info (MonoCompile *cfg, MonoMethod *method_to_compile)
 
        if (cfg->method->dynamic) {
                jinfo = g_malloc0 (MONO_SIZEOF_JIT_INFO + (num_clauses * sizeof (MonoJitExceptionInfo)) +
-                               generic_info_size);
+                               generic_info_size + holes_size);
        } else {
                jinfo = mono_domain_alloc0 (cfg->domain, MONO_SIZEOF_JIT_INFO +
                                (num_clauses * sizeof (MonoJitExceptionInfo)) +
-                               generic_info_size);
+                               generic_info_size + holes_size);
        }
 
        jinfo->method = cfg->method_to_register;
@@ -3446,6 +3469,39 @@ create_jit_info (MonoCompile *cfg, MonoMethod *method_to_compile)
                }
        }
 
+       if (num_holes) {
+               MonoTryBlockHoleTableJitInfo *table;
+               int i;
+
+               jinfo->has_try_block_holes = 1;
+               table = mono_jit_info_get_try_block_hole_table_info (jinfo);
+               table->num_holes = (guint16)num_holes;
+               i = 0;
+               for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
+                       guint32 start_bb_offset;
+                       MonoTryBlockHoleJitInfo *hole;
+                       TryBlockHole *hole_data = tmp->data;
+                       MonoExceptionClause *ec = hole_data->clause;
+                       int hole_end = hole_data->basic_block->native_offset + hole_data->basic_block->native_length;
+                       MonoBasicBlock *clause_last_bb = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
+                       g_assert (clause_last_bb);
+
+                       /* Holes at the end of a try region can be represented by simply reducing the size of the block itself.*/
+                       if (clause_last_bb->native_offset == hole_end)
+                               continue;
+
+                       start_bb_offset = hole_data->start_offset - hole_data->basic_block->native_offset;
+                       hole = &table->holes [i++];
+                       hole->clause = hole_data->clause - &header->clauses [0];
+                       hole->offset = (guint32)hole_data->start_offset;
+                       hole->length = (guint16)(hole_data->basic_block->native_length - start_bb_offset);
+
+                       if (G_UNLIKELY (cfg->verbose_level >= 4))
+                               printf ("\tTry block hole at eh clause %d offset %x length %x\n", hole->clause, hole->offset, hole->length);
+               }
+               g_assert (i == num_holes);
+       }
+
        if (COMPILE_LLVM (cfg)) {
                if (num_clauses)
                        memcpy (&jinfo->clauses [0], &cfg->llvm_ex_info [0], num_clauses * sizeof (MonoJitExceptionInfo));
@@ -3482,7 +3538,43 @@ create_jit_info (MonoCompile *cfg, MonoMethod *method_to_compile)
                        tblock = cfg->cil_offset_to_bb [ec->handler_offset];
                        g_assert (tblock);
                        ei->handler_start = cfg->native_code + tblock->native_offset;
+
+                       for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
+                               TryBlockHole *hole = tmp->data;
+                               gpointer hole_end = cfg->native_code + (hole->basic_block->native_offset + hole->basic_block->native_length);
+                               if (hole->clause == ec && hole_end == ei->try_end) {
+                                       if (G_UNLIKELY (cfg->verbose_level >= 4))
+                                               printf ("\tShortening try block %d from %x to %x\n", i, (int)((guint8*)ei->try_end - cfg->native_code), hole->start_offset);
+
+                                       ei->try_end = cfg->native_code + hole->start_offset;
+                                       break;
+                               }
+                       }
+
+                       if (ec->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
+                               int end_offset;
+                               if (ec->handler_offset + ec->handler_len < header->code_size) {
+                                       tblock = cfg->cil_offset_to_bb [ec->handler_offset + ec->handler_len];
+                                       g_assert (tblock);
+                                       end_offset = tblock->native_offset;
+                               } else {
+                                       end_offset = cfg->epilog_begin;
+                               }
+                               ei->data.handler_end = cfg->native_code + end_offset;
+                       }
                }
+
+               if (G_UNLIKELY (cfg->verbose_level >= 4)) {
+                       for (i = 0; i < jinfo->num_clauses; i++) {
+                               MonoJitExceptionInfo *ei = &jinfo->clauses [i];
+                               int start = (guint8*)ei->try_start - cfg->native_code;
+                               int end = (guint8*)ei->try_end - cfg->native_code;
+                               int handler = (guint8*)ei->handler_start - cfg->native_code;
+
+                               printf ("JitInfo EH clause %d flags %x try %x-%x handler %x\n", i, ei->flags, start, end, handler);
+                       }
+               }
+
        }
 
        /* 
@@ -3504,7 +3596,80 @@ create_jit_info (MonoCompile *cfg, MonoMethod *method_to_compile)
 
        return jinfo;
 }
+#endif
 
+/*
+ * mini_get_shared_method:
+ *
+ *   Return the method which is actually compiled/registered when doing generic sharing.
+ */
+MonoMethod*
+mini_get_shared_method (MonoMethod *method)
+{
+       MonoGenericContext shared_context;
+       MonoMethod *declaring_method, *res;
+       int i;
+       gboolean partial = FALSE;
+
+       if (method->is_generic || method->klass->generic_container)
+               declaring_method = method;
+       else
+               declaring_method = mono_method_get_declaring_generic_method (method);
+
+       if (declaring_method->is_generic)
+               shared_context = mono_method_get_generic_container (declaring_method)->context;
+       else
+               shared_context = declaring_method->klass->generic_container->context;
+
+       /* Handle partial sharing */
+       if (method != declaring_method && method->is_inflated && !mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE)) {
+               MonoGenericContext *context = mono_method_get_context (method);
+               MonoGenericInst *inst;
+               MonoType **type_argv;
+
+               /* 
+                * Create the shared context by replacing the ref type arguments with
+                * type parameters, and keeping the rest.
+                */
+               partial = TRUE;
+               inst = context->class_inst;
+               if (inst) {
+                       type_argv = g_new0 (MonoType*, inst->type_argc);
+                       for (i = 0; i < inst->type_argc; ++i) {
+                               if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
+                                       type_argv [i] = shared_context.class_inst->type_argv [i];
+                               else
+                                       type_argv [i] = inst->type_argv [i];
+                       }
+
+                       shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
+                       g_free (type_argv);
+               }
+
+               inst = context->method_inst;
+               if (inst) {
+                       type_argv = g_new0 (MonoType*, inst->type_argc);
+                       for (i = 0; i < inst->type_argc; ++i) {
+                               if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
+                                       type_argv [i] = shared_context.method_inst->type_argv [i];
+                               else
+                                       type_argv [i] = inst->type_argv [i];
+                       }
+
+                       shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
+                       g_free (type_argv);
+               }
+       }
+
+    res = mono_class_inflate_generic_method (declaring_method, &shared_context);
+       if (!partial) {
+               /* The result should be an inflated method whose parent is not inflated */
+               g_assert (!res->klass->is_inflated);
+       }
+       return res;
+}
+
+#ifndef DISABLE_JIT
 /*
  * mini_method_compile:
  * @method: the method to compile
@@ -3521,6 +3686,8 @@ MonoCompile*
 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts)
 {
        MonoMethodHeader *header;
+       MonoMethodSignature *sig;
+       MonoError err;
        guint8 *ip;
        MonoCompile *cfg;
        int dfn, i, code_size_ratio;
@@ -3535,9 +3702,13 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gbool
                MONO_PROBE_METHOD_COMPILE_BEGIN (method);
  
        if (compile_aot)
-               /* We are passed the original generic method definition */
+               /* 
+                * We might get passed the original generic method definition or
+                * instances with type parameters.
+                * FIXME: Remove the method->klass->generic_class limitation.
+                */
                try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
-                       (opts & MONO_OPT_GSHARED) && (method->is_generic || method->klass->generic_container);
+                       (opts & MONO_OPT_GSHARED) && ((method->is_generic || method->klass->generic_container) || (!method->klass->generic_class && mono_method_is_generic_sharable_impl (method, TRUE)));
        else
                try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
                        (opts & MONO_OPT_GSHARED) && mono_method_is_generic_sharable_impl (method, FALSE);
@@ -3557,25 +3728,7 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gbool
 
  restart_compile:
        if (try_generic_shared) {
-               MonoMethod *declaring_method;
-               MonoGenericContext *shared_context;
-
-               if (compile_aot) {
-                       declaring_method = method;
-               } else {
-                       declaring_method = mono_method_get_declaring_generic_method (method);
-                       if (method->klass->generic_class)
-                               g_assert (method->klass->generic_class->container_class == declaring_method->klass);
-                       else
-                               g_assert (method->klass == declaring_method->klass);
-               }
-
-               if (declaring_method->is_generic)
-                       shared_context = &(mono_method_get_generic_container (declaring_method)->context);
-               else
-                       shared_context = &declaring_method->klass->generic_container->context;
-
-               method_to_compile = mono_class_inflate_generic_method (declaring_method, shared_context);
+               method_to_compile = mini_get_shared_method (method);
                g_assert (method_to_compile);
        } else {
                method_to_compile = method;
@@ -3609,9 +3762,7 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gbool
        }
 
        if (cfg->generic_sharing_context) {
-               MonoGenericContext object_context = mono_method_construct_object_context (method_to_compile);
-
-               method_to_register = mono_class_inflate_generic_method (method_to_compile, &object_context);
+               method_to_register = method_to_compile;
        } else {
                g_assert (method == method_to_compile);
                method_to_register = method;
@@ -3637,6 +3788,17 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gbool
                }
        }
 
+       mono_error_init (&err);
+       sig = mono_method_signature_checked (cfg->method, &err);        
+       if (!sig) {
+               cfg->exception_type = MONO_EXCEPTION_TYPE_LOAD;
+               cfg->exception_message = g_strdup (mono_error_get_message (&err));
+               mono_error_cleanup (&err);
+               if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
+                       MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
+               return cfg;
+       }
+
        header = cfg->header;
        if (!header) {
                MonoLoaderError *error;
@@ -3652,11 +3814,10 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gbool
                return cfg;
        }
 
-       if (FALSE && header->clauses) {
-               /* 
-                * Cannot be enabled until LLVM supports implicit exceptions, or we use
-                * explicit checks, or we disable this for methods which might throw implicit
-                * exceptions inside clauses.
+       if (header->clauses) {
+               /*
+                * FIXME: LLLVM 2.6/SVN no longer seems to generate correct exception info
+                * for JITted code.
                 */
                cfg->exception_message = g_strdup ("clauses");
                cfg->disable_llvm = TRUE;
@@ -3745,7 +3906,7 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gbool
        if (getenv ("MONO_VERBOSE_METHOD")) {
                char *name = getenv ("MONO_VERBOSE_METHOD");
 
-               if (strchr (name, '.') || strchr (name, ':')) {
+               if ((strchr (name, '.') > name) || strchr (name, ':')) {
                        MonoMethodDesc *desc;
                        
                        desc = mono_method_desc_new (name, TRUE);
@@ -3767,7 +3928,7 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gbool
                if (COMPILE_LLVM (cfg))
                        g_print ("converting llvm method %s\n", mono_method_full_name (method, TRUE));
                else if (cfg->generic_sharing_context)
-                       g_print ("converting shared method %s\n", mono_method_full_name (method, TRUE));
+                       g_print ("converting shared method %s\n", mono_method_full_name (method_to_compile, TRUE));
                else
                        g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
        }
@@ -4328,17 +4489,29 @@ mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gbool
 
 #endif /* DISABLE_JIT */
 
-static MonoJitInfo*
-lookup_generic_method (MonoDomain *domain, MonoMethod *method)
+MonoJitInfo*
+mono_domain_lookup_shared_generic (MonoDomain *domain, MonoMethod *method)
 {
-       MonoMethod *open_method;
+       static gboolean inited = FALSE;
+       static int lookups = 0;
+       static int failed_lookups = 0;
+       MonoJitInfo *ji;
 
-       if (!mono_method_is_generic_sharable_impl (method, FALSE))
-               return NULL;
+       ji = mono_internal_hash_table_lookup (&domain->jit_code_hash, mini_get_shared_method (method));
+       if (ji && !ji->has_generic_jit_info)
+               ji = NULL;
+
+       if (!inited) {
+               mono_counters_register ("Shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &lookups);
+               mono_counters_register ("Failed shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &failed_lookups);
+               inited = TRUE;
+       }
 
-       open_method = mono_method_get_declaring_generic_method (method);
+       ++lookups;
+       if (!ji)
+               ++failed_lookups;
 
-       return mono_domain_lookup_shared_generic (domain, open_method);
+       return ji;
 }
 
 /*
@@ -4352,7 +4525,9 @@ lookup_method_inner (MonoDomain *domain, MonoMethod *method)
        if (ji)
                return ji;
 
-       return lookup_generic_method (domain, method);
+       if (!mono_method_is_generic_sharable_impl (method, FALSE))
+               return NULL;
+       return mono_domain_lookup_shared_generic (domain, method);
 }
 
 static MonoJitInfo*
@@ -4427,6 +4602,7 @@ mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, in
        }
 #endif
 
+#ifndef DISABLE_JIT
        if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
            (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
                MonoMethod *nm;
@@ -4485,6 +4661,7 @@ mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, in
                }
                return NULL;
        }
+#endif
 
        if (mono_aot_only) {
                char *fullname = mono_method_full_name (method, TRUE);
@@ -4612,6 +4789,7 @@ mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, in
 
        mono_destroy_compile (cfg);
 
+#ifndef DISABLE_JIT
        if (domain_jit_info (target_domain)->jump_target_hash) {
                MonoJumpInfo patch_info;
                GSList *list, *tmp;
@@ -4629,6 +4807,7 @@ mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, in
        }
 
        mono_emit_jit_map (jinfo);
+#endif
        mono_domain_unlock (target_domain);
        mono_loader_unlock ();
 
@@ -4641,11 +4820,15 @@ mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, in
        }
 
        if (prof_options & MONO_PROFILE_JIT_COMPILATION) {
-               if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
-                       /* The profiler doesn't know about wrappers, so pass the original icall method */
-                       mono_profiler_method_end_jit (mono_marshal_method_from_wrapper (method), jinfo, MONO_PROFILE_OK);
-               else
+               if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
+                       if (mono_marshal_method_from_wrapper (method)) {
+                               /* Native func wrappers have no method */
+                               /* The profiler doesn't know about wrappers, so pass the original icall method */
+                               mono_profiler_method_end_jit (mono_marshal_method_from_wrapper (method), jinfo, MONO_PROFILE_OK);
+                       }
+               } else {
                        mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
+               }
        }
 
        mono_runtime_class_init (vtable);
@@ -5093,18 +5276,19 @@ SIG_HANDLER_SIGNATURE (mono_sigill_signal_handler)
        mono_arch_handle_exception (ctx, exc, FALSE);
 }
 
+#if defined(MONO_ARCH_USE_SIGACTION) || defined(HOST_WIN32)
+#define HAVE_SIG_INFO
+#endif
+
 void
 SIG_HANDLER_SIGNATURE (mono_sigsegv_signal_handler)
 {
-#ifndef MONO_ARCH_SIGSEGV_ON_ALTSTACK
-       MonoException *exc = NULL;
-#endif
        MonoJitInfo *ji;
        MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
 
        GET_CONTEXT;
 
-#ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
+#if defined(MONO_ARCH_SOFT_DEBUG_SUPPORTED) && defined(HAVE_SIG_INFO)
        if (mono_arch_is_single_step_event (info, ctx)) {
                mono_debugger_agent_single_step_event (ctx);
                return;
@@ -5114,7 +5298,7 @@ SIG_HANDLER_SIGNATURE (mono_sigsegv_signal_handler)
        }
 #endif
 
-#ifndef HOST_WIN32
+#if !defined(HOST_WIN32) && defined(HAVE_SIG_INFO)
        if (mono_aot_is_pagefault (info->si_addr)) {
                mono_aot_handle_pagefault (info->si_addr);
                return;
@@ -5164,7 +5348,7 @@ SIG_HANDLER_SIGNATURE (mono_sigsegv_signal_handler)
                mono_handle_native_sigsegv (SIGSEGV, ctx);
        }
                        
-       mono_arch_handle_exception (ctx, exc, FALSE);
+       mono_arch_handle_exception (ctx, NULL, FALSE);
 #endif
 }
 
@@ -5429,7 +5613,7 @@ mini_init (const char *filename, const char *runtime_version)
 #endif
 
 #ifdef MONO_ARCH_HAVE_TLS_GET
-       mono_runtime_set_has_tls_get (TRUE);
+       mono_runtime_set_has_tls_get (MONO_ARCH_HAVE_TLS_GET);
 #else
        mono_runtime_set_has_tls_get (FALSE);
 #endif
@@ -5486,8 +5670,6 @@ mini_init (const char *filename, const char *runtime_version)
        if (!g_thread_supported ())
                g_thread_init (NULL);
 
-       mono_gc_base_init ();
-
        mono_jit_tls_id = TlsAlloc ();
        setup_jit_tls_data ((gpointer)-1, mono_thread_abort);
 
@@ -5739,6 +5921,10 @@ mini_init (const char *filename, const char *runtime_version)
        register_icall (mono_isfinite, "mono_isfinite", "uint32 double", FALSE);
 #endif
 
+#ifdef COMPRESSED_INTERFACE_BITMAP
+       register_icall (mono_class_interface_match, "mono_class_interface_match", "uint32 ptr int32", TRUE);
+#endif
+
 #if SIZEOF_REGISTER == 4
        mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "uint32 double", mono_fconv_u4, TRUE);
 #endif
@@ -6054,4 +6240,15 @@ mono_arch_instrument_epilog (MonoCompile *cfg, void *func, void *p, gboolean ena
        return mono_arch_instrument_epilog_full (cfg, func, p, enable_arguments, FALSE);
 }
 
+void
+mono_cfg_add_try_hole (MonoCompile *cfg, MonoExceptionClause *clause, guint8 *start, MonoBasicBlock *bb)
+{
+       TryBlockHole *hole = mono_mempool_alloc (cfg->mempool, sizeof (TryBlockHole));
+       hole->clause = clause;
+       hole->start_offset = start - cfg->native_code;
+       hole->basic_block = bb;
+
+       cfg->try_block_holes = g_slist_append_mempool (cfg->mempool, cfg->try_block_holes, hole);
+}
+
 #endif
index 6fc3632a8335d61329e1ca3fe88ce231ae4bdce2..5d9c7658998c6b32fbdace3cfe338e28e1ac7f3e 100644 (file)
@@ -95,7 +95,7 @@ typedef gint64 mgreg_t;
 #endif
 
 /* Version number of the AOT file format */
-#define MONO_AOT_FILE_VERSION "67"
+#define MONO_AOT_FILE_VERSION "68"
 
 //TODO: This is x86/amd64 specific.
 #define mono_simd_shuffle_mask(a,b,c,d) ((a) | ((b) << 2) | ((c) << 4) | ((d) << 6))
@@ -465,8 +465,9 @@ struct MonoBasicBlock {
        /* Length of the CIL block */
        gint32 cil_length;
 
-       /* The address of the generated code, used for fixups */
+       /* The offset of the generated code, used for fixups */
        int native_offset;
+       int native_length;
        int max_offset;
        int max_length;
 
@@ -609,6 +610,7 @@ struct MonoInst {
                        MonoClass *klass;
                        int *phi_args;
                        MonoCallInst *call_inst;
+                       MonoExceptionClause *exception_clause;
                } op [2];
                gint64 i8const;
                double r8const;
@@ -730,6 +732,7 @@ enum {
 #define inst_call   data.op[1].call_inst
 
 #define inst_phi_args   data.op[1].phi_args
+#define inst_eh_block   data.op[1].exception_clause
 
 /* instruction description for use in regalloc/scheduling */
 enum {
@@ -809,14 +812,19 @@ typedef struct {
        guint32          signal_stack_size;
        gpointer         stack_ovf_guard_base;
        guint32          stack_ovf_guard_size;
+       guint            stack_ovf_valloced : 1;
        void            (*abort_func) (MonoObject *object);
        /* Used to implement --debug=casts */
        MonoClass       *class_cast_from, *class_cast_to;
 
-       /* Stores state needed by mono_resume_unwind () */
+       /* Stores state needed by mono_resume_unwind () and the handler block with a guard */
        MonoContext     ex_ctx;
        /* FIXME: GC */
        gpointer        ex_obj;
+       /* handle block return address */
+       gpointer handler_block_return_address;
+       /* handler block been guarded */
+       MonoJitExceptionInfo *handler_block;
 } MonoJitTlsData;
 
 typedef enum {
@@ -906,6 +914,9 @@ typedef enum {
        MONO_TRAMPOLINE_MONITOR_EXIT,
 #ifdef MONO_ARCH_LLVM_SUPPORTED
        MONO_TRAMPOLINE_LLVM_VCALL,
+#endif
+#ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
+       MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD,
 #endif
        MONO_TRAMPOLINE_NUM
 } MonoTrampolineType;
@@ -1141,6 +1152,8 @@ typedef struct {
 
        MonoJitExceptionInfo *llvm_ex_info;
        guint32 llvm_ex_info_len;
+
+       GSList *try_block_holes;
 } MonoCompile;
 
 typedef enum {
@@ -1526,6 +1539,7 @@ gboolean  mono_aot_get_cached_class_info    (MonoClass *klass, MonoCachedClassIn
 gboolean  mono_aot_get_class_from_name      (MonoImage *image, const char *name_space, const char *name, MonoClass **klass) MONO_INTERNAL;
 MonoJitInfo* mono_aot_find_jit_info         (MonoDomain *domain, MonoImage *image, gpointer addr) MONO_INTERNAL;
 gpointer mono_aot_plt_resolve               (gpointer aot_module, guint32 plt_info_offset, guint8 *code) MONO_INTERNAL;
+void     mono_aot_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr) MONO_INTERNAL;
 gpointer mono_aot_get_method_from_vt_slot   (MonoDomain *domain, MonoVTable *vtable, int slot) MONO_INTERNAL;
 gpointer mono_aot_create_specific_trampoline   (MonoImage *image, gpointer arg1, MonoTrampolineType tramp_type, MonoDomain *domain, guint32 *code_len) MONO_INTERNAL;
 gpointer mono_aot_get_named_code            (const char *name) MONO_INTERNAL;
@@ -1794,6 +1808,12 @@ MonoVTable* mono_arch_find_static_call_vtable   (mgreg_t *regs, guint8 *code) MO
 gpointer    mono_arch_build_imt_thunk           (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp) MONO_INTERNAL;
 void    mono_arch_notify_pending_exc            (void) MONO_INTERNAL;
 
+/* Handle block guard */
+gpointer mono_arch_install_handler_block_guard (MonoJitInfo *ji, MonoJitExceptionInfo *clause, MonoContext *ctx, gpointer new_value) MONO_INTERNAL;
+gpointer mono_arch_create_handler_block_trampoline (void) MONO_INTERNAL;
+gpointer mono_create_handler_block_trampoline (void) MONO_INTERNAL;
+gboolean mono_install_handler_block_guard (MonoInternalThread *thread, MonoContext *ctx) MONO_INTERNAL;
+
 /* Exception handling */
 
 /* Same as MonoStackWalk, but pass the context/frame type as well */
@@ -1947,11 +1967,21 @@ mono_class_check_context_used (MonoClass *class) MONO_INTERNAL;
 gboolean
 mono_generic_context_is_sharable (MonoGenericContext *context, gboolean allow_type_vars) MONO_INTERNAL;
 
+gboolean
+mono_generic_context_is_sharable_full (MonoGenericContext *context, gboolean allow_type_vars, gboolean allow_partial) MONO_INTERNAL;
+
 gboolean
 mono_method_is_generic_impl (MonoMethod *method) MONO_INTERNAL;
+
 gboolean
 mono_method_is_generic_sharable_impl (MonoMethod *method, gboolean allow_type_vars) MONO_INTERNAL;
 
+gboolean
+mono_method_is_generic_sharable_impl_full (MonoMethod *method, gboolean allow_type_vars, gboolean allow_partial) MONO_INTERNAL;
+
+gboolean
+mono_is_partially_sharable_inst (MonoGenericInst *inst) MONO_INTERNAL;
+
 MonoGenericSharingContext* mono_get_generic_context_from_code (guint8 *code) MONO_INTERNAL;
 
 MonoGenericContext* mini_method_get_context (MonoMethod *method) MONO_INTERNAL;
@@ -1971,12 +2001,16 @@ MonoGenericContext* mini_class_get_context (MonoClass *class) MONO_INTERNAL;
 
 MonoType* mini_get_basic_type_from_generic (MonoGenericSharingContext *gsctx, MonoType *type) MONO_INTERNAL;
 MonoType* mini_type_get_underlying_type (MonoGenericSharingContext *gsctx, MonoType *type) MONO_INTERNAL;
+MonoMethod* mini_get_shared_method (MonoMethod *method) MONO_INTERNAL;
+MonoMethod* mini_get_shared_method_to_register (MonoMethod *method) MONO_INTERNAL;
 
 int mini_type_stack_size (MonoGenericSharingContext *gsctx, MonoType *t, int *align) MONO_INTERNAL;
 int mini_type_stack_size_full (MonoGenericSharingContext *gsctx, MonoType *t, guint32 *align, gboolean pinvoke) MONO_INTERNAL;
 void type_to_eval_stack_type (MonoCompile *cfg, MonoType *type, MonoInst *inst) MONO_INTERNAL;
 guint mono_type_to_regmove (MonoCompile *cfg, MonoType *type) MONO_INTERNAL;
 
+void mono_cfg_add_try_hole (MonoCompile *cfg, MonoExceptionClause *clause, guint8 *start, MonoBasicBlock *bb) MONO_INTERNAL;
+
 /* wapihandles.c */
 int mini_wapi_hps (int argc, char **argv) MONO_INTERNAL;
 
@@ -1988,18 +2022,28 @@ int mini_wapi_seminfo (int argc, char **argv) MONO_INTERNAL;
 
 /*
 This enum MUST be kept in sync with its managed mirror Mono.Simd.AccelMode.
-The AccelMode values are masks while the ones here are the bit indexes.
  */
 enum {
-       SIMD_VERSION_SSE1       = 0,
-       SIMD_VERSION_SSE2       = 1,
-       SIMD_VERSION_SSE3       = 2,
-       SIMD_VERSION_SSSE3      = 3,
-       SIMD_VERSION_SSE41      = 4,
-       SIMD_VERSION_SSE42      = 5,
-       SIMD_VERSION_SSE4a      = 6,
+       SIMD_VERSION_SSE1       = 1 << 0,
+       SIMD_VERSION_SSE2       = 1 << 1,
+       SIMD_VERSION_SSE3       = 1 << 2,
+       SIMD_VERSION_SSSE3      = 1 << 3,
+       SIMD_VERSION_SSE41      = 1 << 4,
+       SIMD_VERSION_SSE42      = 1 << 5,
+       SIMD_VERSION_SSE4a      = 1 << 6,
+       SIMD_VERSION_ALL        = SIMD_VERSION_SSE1 | SIMD_VERSION_SSE2 |
+                         SIMD_VERSION_SSE3 | SIMD_VERSION_SSSE3 |
+                         SIMD_VERSION_SSE41 | SIMD_VERSION_SSE42 |
+                         SIMD_VERSION_SSE4a,
+
+       /* this value marks the end of the bit indexes used in 
+        * this emum.
+        */
+       SIMD_VERSION_INDEX_END = 6 
 };
 
+#define MASK(x) (1 << x)
+
 enum {
        SIMD_COMP_EQ,
        SIMD_COMP_LT,
@@ -2062,6 +2106,9 @@ gboolean mono_gdb_render_native_backtraces (void) MONO_INTERNAL;
 #ifdef MONO_ARCH_USE_SIGACTION
 #define GET_CONTEXT \
     void *ctx = context;
+#elif defined(__HAIKU__)
+#define GET_CONTEXT \
+       void *ctx = &regs;
 #else
 #define GET_CONTEXT \
        void **_p = (void **)&_dummy; \
@@ -2076,6 +2123,9 @@ gboolean mono_gdb_render_native_backtraces (void) MONO_INTERNAL;
 #elif defined(HOST_WIN32)
 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, EXCEPTION_RECORD *info, void *context)
 #define SIG_HANDLER_PARAMS _dummy, info, context
+#elif defined(__HAIKU__)
+#define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, void *userData, vregs regs)
+#define SIG_HANDLER_PARAMS _dummy, userData, regs
 #else
 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy)
 #define SIG_HANDLER_PARAMS _dummy
index 572eeab06f928aa75c9dd30425cace727d1d0227..e0333ea456037c1cef8b91994452713af4c36c87 100644 (file)
@@ -23,3 +23,4 @@ OPTFLAG(SSA      ,21, "ssa",        "Use plain SSA form")
 OPTFLAG(SSE2     ,23, "sse2",       "SSE2 instructions on x86")
 OPTFLAG(GSHARED  ,24, "gshared",    "Share generics")
 OPTFLAG(SIMD    ,25, "simd",       "Simd intrinsics")
+OPTFLAG(UNSAFE  ,26, "unsafe",     "Remove bound checks and perform other dangerous changes")
index 15abb5e9951de52932e7749007a8fd878a58c29c..aaf6a1935df772c8d327bbe61f6b49cd49f27d1b 100644 (file)
@@ -121,392 +121,392 @@ enum {
 typedef struct {
        guint16 name;
        guint16 opcode;
+       guint8 simd_version_flags;
        guint8 simd_emit_mode : 4;
-       guint8 simd_version : 4;
-       guint8 flags;
+       guint8 flags : 4;
 } SimdIntrinsc;
 
 static const SimdIntrinsc vector4f_intrinsics[] = {
-       { SN_ctor, OP_EXPAND_R4, SIMD_EMIT_CTOR },
-       { SN_AddSub, OP_ADDSUBPS, SIMD_EMIT_BINARY, SIMD_VERSION_SSE3 },
-       { SN_AndNot, OP_ANDNPS, SIMD_EMIT_BINARY },
-       { SN_CompareEqual, OP_COMPPS, SIMD_EMIT_BINARY, SIMD_VERSION_SSE1, SIMD_COMP_EQ },
-       { SN_CompareLessEqual, OP_COMPPS, SIMD_EMIT_BINARY, SIMD_VERSION_SSE1, SIMD_COMP_LE },
-       { SN_CompareLessThan, OP_COMPPS, SIMD_EMIT_BINARY, SIMD_VERSION_SSE1, SIMD_COMP_LT },
-       { SN_CompareNotEqual, OP_COMPPS, SIMD_EMIT_BINARY, SIMD_VERSION_SSE1, SIMD_COMP_NEQ },
-       { SN_CompareNotLessEqual, OP_COMPPS, SIMD_EMIT_BINARY, SIMD_VERSION_SSE1, SIMD_COMP_NLE },
-       { SN_CompareNotLessThan, OP_COMPPS, SIMD_EMIT_BINARY, SIMD_VERSION_SSE1, SIMD_COMP_NLT },
-       { SN_CompareOrdered, OP_COMPPS, SIMD_EMIT_BINARY, SIMD_VERSION_SSE1, SIMD_COMP_ORD },
-       { SN_CompareUnordered, OP_COMPPS, SIMD_EMIT_BINARY, SIMD_VERSION_SSE1, SIMD_COMP_UNORD },
-       { SN_DuplicateHigh, OP_DUPPS_HIGH, SIMD_EMIT_UNARY, SIMD_VERSION_SSE3 },
-       { SN_DuplicateLow, OP_DUPPS_LOW, SIMD_EMIT_UNARY, SIMD_VERSION_SSE3 },
-       { SN_HorizontalAdd, OP_HADDPS, SIMD_EMIT_BINARY, SIMD_VERSION_SSE3 },
-       { SN_HorizontalSub, OP_HSUBPS, SIMD_EMIT_BINARY, SIMD_VERSION_SSE3 },   
-       { SN_InterleaveHigh, OP_UNPACK_HIGHPS, SIMD_EMIT_BINARY },
-       { SN_InterleaveLow, OP_UNPACK_LOWPS, SIMD_EMIT_BINARY },
-       { SN_InvSqrt, OP_RSQRTPS, SIMD_EMIT_UNARY },
-       { SN_LoadAligned, 0, SIMD_EMIT_LOAD_ALIGNED },
-       { SN_Max, OP_MAXPS, SIMD_EMIT_BINARY },
-       { SN_Min, OP_MINPS, SIMD_EMIT_BINARY },
-       { SN_PrefetchTemporalAllCacheLevels, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_0 },
-       { SN_PrefetchTemporal1stLevelCache, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_1 },
-       { SN_PrefetchTemporal2ndLevelCache, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_2 },
-       { SN_PrefetchNonTemporal, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_NTA },
-       { SN_Reciprocal, OP_RCPPS, SIMD_EMIT_UNARY },
-       { SN_Shuffle, OP_PSHUFLED, SIMD_EMIT_SHUFFLE },
-       { SN_Sqrt, OP_SQRTPS, SIMD_EMIT_UNARY },
-       { SN_StoreAligned, OP_STOREX_ALIGNED_MEMBASE_REG, SIMD_EMIT_STORE },
-       { SN_StoreNonTemporal, OP_STOREX_NTA_MEMBASE_REG, SIMD_EMIT_STORE },
-       { SN_get_W, 3, SIMD_EMIT_GETTER },
-       { SN_get_X, 0, SIMD_EMIT_GETTER },
-       { SN_get_Y, 1, SIMD_EMIT_GETTER },
-       { SN_get_Z, 2, SIMD_EMIT_GETTER },
-       { SN_op_Addition, OP_ADDPS, SIMD_EMIT_BINARY },
-       { SN_op_BitwiseAnd, OP_ANDPS, SIMD_EMIT_BINARY },
-       { SN_op_BitwiseOr, OP_ORPS, SIMD_EMIT_BINARY },
-       { SN_op_Division, OP_DIVPS, SIMD_EMIT_BINARY },
-       { SN_op_Equality, OP_COMPPS, SIMD_EMIT_EQUALITY, SIMD_VERSION_SSE1, SIMD_COMP_EQ },
-       { SN_op_ExclusiveOr, OP_XORPS, SIMD_EMIT_BINARY },
-       { SN_op_Explicit, 0, SIMD_EMIT_CAST }, 
-       { SN_op_Inequality, OP_COMPPS, SIMD_EMIT_EQUALITY, SIMD_VERSION_SSE1, SIMD_COMP_NEQ },
-       { SN_op_Multiply, OP_MULPS, SIMD_EMIT_BINARY },
-       { SN_op_Subtraction, OP_SUBPS, SIMD_EMIT_BINARY },
-       { SN_set_W, 3, SIMD_EMIT_SETTER },
-       { SN_set_X, 0, SIMD_EMIT_SETTER },
-       { SN_set_Y, 1, SIMD_EMIT_SETTER },
-       { SN_set_Z, 2, SIMD_EMIT_SETTER },
+       { SN_ctor, OP_EXPAND_R4, SIMD_VERSION_SSE1, SIMD_EMIT_CTOR },
+       { SN_AddSub, OP_ADDSUBPS, SIMD_VERSION_SSE3, SIMD_EMIT_BINARY},
+       { SN_AndNot, OP_ANDNPS, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY},
+       { SN_CompareEqual, OP_COMPPS, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY, SIMD_COMP_EQ },
+       { SN_CompareLessEqual, OP_COMPPS, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY, SIMD_COMP_LE },
+       { SN_CompareLessThan, OP_COMPPS, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY, SIMD_COMP_LT },
+       { SN_CompareNotEqual, OP_COMPPS, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY, SIMD_COMP_NEQ },
+       { SN_CompareNotLessEqual, OP_COMPPS, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY, SIMD_COMP_NLE },
+       { SN_CompareNotLessThan, OP_COMPPS, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY, SIMD_COMP_NLT },
+       { SN_CompareOrdered, OP_COMPPS, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY, SIMD_COMP_ORD },
+       { SN_CompareUnordered, OP_COMPPS, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY, SIMD_COMP_UNORD },
+       { SN_DuplicateHigh, OP_DUPPS_HIGH, SIMD_VERSION_SSE3, SIMD_EMIT_UNARY },
+       { SN_DuplicateLow, OP_DUPPS_LOW, SIMD_VERSION_SSE3, SIMD_EMIT_UNARY },
+       { SN_HorizontalAdd, OP_HADDPS, SIMD_VERSION_SSE3, SIMD_EMIT_BINARY },
+       { SN_HorizontalSub, OP_HSUBPS, SIMD_VERSION_SSE3, SIMD_EMIT_BINARY },   
+       { SN_InterleaveHigh, OP_UNPACK_HIGHPS, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_InterleaveLow, OP_UNPACK_LOWPS, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_InvSqrt, OP_RSQRTPS, SIMD_VERSION_SSE1, SIMD_EMIT_UNARY },
+       { SN_LoadAligned, 0, SIMD_VERSION_SSE1, SIMD_EMIT_LOAD_ALIGNED },
+       { SN_Max, OP_MAXPS, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_Min, OP_MINPS, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_PrefetchTemporalAllCacheLevels, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_0 },
+       { SN_PrefetchTemporal1stLevelCache, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_1 },
+       { SN_PrefetchTemporal2ndLevelCache, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_2 },
+       { SN_PrefetchNonTemporal, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_NTA },
+       { SN_Reciprocal, OP_RCPPS, SIMD_VERSION_SSE1, SIMD_EMIT_UNARY },
+       { SN_Shuffle, OP_PSHUFLED, SIMD_VERSION_SSE1, SIMD_EMIT_SHUFFLE },
+       { SN_Sqrt, OP_SQRTPS, SIMD_VERSION_SSE1, SIMD_EMIT_UNARY },
+       { SN_StoreAligned, OP_STOREX_ALIGNED_MEMBASE_REG, SIMD_VERSION_SSE1, SIMD_EMIT_STORE },
+       { SN_StoreNonTemporal, OP_STOREX_NTA_MEMBASE_REG, SIMD_VERSION_SSE1, SIMD_EMIT_STORE },
+       { SN_get_W, 3, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_X, 0, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_Y, 1, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_Z, 2, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_op_Addition, OP_ADDPS, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_BitwiseAnd, OP_ANDPS, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_BitwiseOr, OP_ORPS, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Division, OP_DIVPS, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Equality, OP_COMPPS, SIMD_VERSION_SSE1, SIMD_EMIT_EQUALITY, SIMD_COMP_EQ },
+       { SN_op_ExclusiveOr, OP_XORPS, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Explicit, 0, SIMD_VERSION_SSE1, SIMD_EMIT_CAST }, 
+       { SN_op_Inequality, OP_COMPPS, SIMD_VERSION_SSE1, SIMD_EMIT_EQUALITY, SIMD_COMP_NEQ },
+       { SN_op_Multiply, OP_MULPS, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Subtraction, OP_SUBPS, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_set_W, 3, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_X, 0, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_Y, 1, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_Z, 2, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER }
 };
 
 static const SimdIntrinsc vector2d_intrinsics[] = {
-       { SN_ctor, OP_EXPAND_R8, SIMD_EMIT_CTOR },
-       { SN_AddSub, OP_ADDSUBPD, SIMD_EMIT_BINARY, SIMD_VERSION_SSE3 },
-       { SN_AndNot, OP_ANDNPD, SIMD_EMIT_BINARY },
-       { SN_CompareEqual, OP_COMPPD, SIMD_EMIT_BINARY, SIMD_VERSION_SSE1, SIMD_COMP_EQ },
-       { SN_CompareLessEqual, OP_COMPPD, SIMD_EMIT_BINARY, SIMD_VERSION_SSE1, SIMD_COMP_LE },
-       { SN_CompareLessThan, OP_COMPPD, SIMD_EMIT_BINARY, SIMD_VERSION_SSE1, SIMD_COMP_LT },
-       { SN_CompareNotEqual, OP_COMPPD, SIMD_EMIT_BINARY, SIMD_VERSION_SSE1, SIMD_COMP_NEQ },
-       { SN_CompareNotLessEqual, OP_COMPPD, SIMD_EMIT_BINARY, SIMD_VERSION_SSE1, SIMD_COMP_NLE },
-       { SN_CompareNotLessThan, OP_COMPPD, SIMD_EMIT_BINARY, SIMD_VERSION_SSE1, SIMD_COMP_NLT },
-       { SN_CompareOrdered, OP_COMPPD, SIMD_EMIT_BINARY, SIMD_VERSION_SSE1, SIMD_COMP_ORD },
-       { SN_CompareUnordered, OP_COMPPD, SIMD_EMIT_BINARY, SIMD_VERSION_SSE1, SIMD_COMP_UNORD },
-       { SN_Duplicate, OP_DUPPD, SIMD_EMIT_UNARY, SIMD_VERSION_SSE3 },
-       { SN_HorizontalAdd, OP_HADDPD, SIMD_EMIT_BINARY, SIMD_VERSION_SSE3 },
-       { SN_HorizontalSub, OP_HSUBPD, SIMD_EMIT_BINARY, SIMD_VERSION_SSE3 },   
-       { SN_InterleaveHigh, OP_UNPACK_HIGHPD, SIMD_EMIT_BINARY },
-       { SN_InterleaveLow, OP_UNPACK_LOWPD, SIMD_EMIT_BINARY },
-       { SN_LoadAligned, 0, SIMD_EMIT_LOAD_ALIGNED },
-       { SN_Max, OP_MAXPD, SIMD_EMIT_BINARY },
-       { SN_Min, OP_MINPD, SIMD_EMIT_BINARY },
-       { SN_PrefetchTemporalAllCacheLevels, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_0 },
-       { SN_PrefetchTemporal1stLevelCache, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_1 },
-       { SN_PrefetchTemporal2ndLevelCache, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_2 },
-       { SN_PrefetchNonTemporal, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_NTA },
-       { SN_Sqrt, OP_SQRTPD, SIMD_EMIT_UNARY },
-       { SN_StoreAligned, OP_STOREX_ALIGNED_MEMBASE_REG, SIMD_EMIT_STORE },
-       { SN_get_X, 0, SIMD_EMIT_GETTER_QWORD },
-       { SN_get_Y, 1, SIMD_EMIT_GETTER_QWORD },
-       { SN_op_Addition, OP_ADDPD, SIMD_EMIT_BINARY },
-       { SN_op_BitwiseAnd, OP_ANDPD, SIMD_EMIT_BINARY },
-       { SN_op_BitwiseOr, OP_ORPD, SIMD_EMIT_BINARY },
-       { SN_op_Division, OP_DIVPD, SIMD_EMIT_BINARY },
-       { SN_op_ExclusiveOr, OP_XORPD, SIMD_EMIT_BINARY },
-       { SN_op_Explicit, 0, SIMD_EMIT_CAST }, 
-       { SN_op_Multiply, OP_MULPD, SIMD_EMIT_BINARY },
-       { SN_op_Subtraction, OP_SUBPD, SIMD_EMIT_BINARY },
-       { SN_set_X, 0, SIMD_EMIT_SETTER },
-       { SN_set_Y, 1, SIMD_EMIT_SETTER },
+       { SN_ctor, OP_EXPAND_R8, SIMD_VERSION_SSE1, SIMD_EMIT_CTOR },
+       { SN_AddSub, OP_ADDSUBPD, SIMD_VERSION_SSE3, SIMD_EMIT_BINARY,},
+       { SN_AndNot, OP_ANDNPD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_CompareEqual, OP_COMPPD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY, SIMD_COMP_EQ },
+       { SN_CompareLessEqual, OP_COMPPD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY, SIMD_COMP_LE },
+       { SN_CompareLessThan, OP_COMPPD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY, SIMD_COMP_LT },
+       { SN_CompareNotEqual, OP_COMPPD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY, SIMD_COMP_NEQ },
+       { SN_CompareNotLessEqual, OP_COMPPD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY, SIMD_COMP_NLE },
+       { SN_CompareNotLessThan, OP_COMPPD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY, SIMD_COMP_NLT },
+       { SN_CompareOrdered, OP_COMPPD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY, SIMD_COMP_ORD },
+       { SN_CompareUnordered, OP_COMPPD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY, SIMD_COMP_UNORD },
+       { SN_Duplicate, OP_DUPPD, SIMD_VERSION_SSE3, SIMD_EMIT_UNARY },
+       { SN_HorizontalAdd, OP_HADDPD, SIMD_VERSION_SSE3, SIMD_EMIT_BINARY },
+       { SN_HorizontalSub, OP_HSUBPD, SIMD_VERSION_SSE3, SIMD_EMIT_BINARY },   
+       { SN_InterleaveHigh, OP_UNPACK_HIGHPD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_InterleaveLow, OP_UNPACK_LOWPD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_LoadAligned, 0, SIMD_VERSION_SSE1, SIMD_EMIT_LOAD_ALIGNED },
+       { SN_Max, OP_MAXPD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_Min, OP_MINPD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_PrefetchTemporalAllCacheLevels, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_0 },
+       { SN_PrefetchTemporal1stLevelCache, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_1 },
+       { SN_PrefetchTemporal2ndLevelCache, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_2 },
+       { SN_PrefetchNonTemporal, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_NTA },
+       { SN_Sqrt, OP_SQRTPD, SIMD_VERSION_SSE1, SIMD_EMIT_UNARY },
+       { SN_StoreAligned, OP_STOREX_ALIGNED_MEMBASE_REG, SIMD_VERSION_SSE1, SIMD_EMIT_STORE },
+       { SN_get_X, 0, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER_QWORD },
+       { SN_get_Y, 1, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER_QWORD },
+       { SN_op_Addition, OP_ADDPD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_BitwiseAnd, OP_ANDPD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_BitwiseOr, OP_ORPD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Division, OP_DIVPD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_ExclusiveOr, OP_XORPD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Explicit, 0, SIMD_VERSION_SSE1, SIMD_EMIT_CAST }, 
+       { SN_op_Multiply, OP_MULPD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Subtraction, OP_SUBPD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_set_X, 0, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_Y, 1, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
 };
 
 static const SimdIntrinsc vector2ul_intrinsics[] = {
-       { SN_ctor, OP_EXPAND_I8, SIMD_EMIT_CTOR },
-       { SN_CompareEqual, OP_PCMPEQQ, SIMD_EMIT_BINARY, SIMD_VERSION_SSE41 },
-       { SN_LoadAligned, 0, SIMD_EMIT_LOAD_ALIGNED },
-       { SN_PrefetchTemporalAllCacheLevels, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_0 },
-       { SN_PrefetchTemporal1stLevelCache, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_1 },
-       { SN_PrefetchTemporal2ndLevelCache, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_2 },
-       { SN_PrefetchNonTemporal, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_NTA },
-       { SN_StoreAligned, OP_STOREX_ALIGNED_MEMBASE_REG, SIMD_EMIT_STORE },
-       { SN_UnpackHigh, OP_UNPACK_HIGHQ, SIMD_EMIT_BINARY },
-       { SN_UnpackLow, OP_UNPACK_LOWQ, SIMD_EMIT_BINARY },
-       { SN_get_X, 0, SIMD_EMIT_GETTER_QWORD },
-       { SN_get_Y, 1, SIMD_EMIT_GETTER_QWORD },
-       { SN_op_Addition, OP_PADDQ, SIMD_EMIT_BINARY },
-       { SN_op_BitwiseAnd, OP_PAND, SIMD_EMIT_BINARY },
-       { SN_op_BitwiseOr, OP_POR, SIMD_EMIT_BINARY },
-       { SN_op_ExclusiveOr, OP_PXOR, SIMD_EMIT_BINARY },
-       { SN_op_Explicit, 0, SIMD_EMIT_CAST },
-       { SN_op_LeftShift, OP_PSHLQ, SIMD_EMIT_SHIFT },
-       { SN_op_Multiply, OP_PMULQ, SIMD_EMIT_BINARY },
-       { SN_op_RightShift, OP_PSHRQ, SIMD_EMIT_SHIFT },
-       { SN_op_Subtraction, OP_PSUBQ, SIMD_EMIT_BINARY },
-       { SN_set_X, 0, SIMD_EMIT_SETTER },
-       { SN_set_Y, 1, SIMD_EMIT_SETTER },
+       { SN_ctor, OP_EXPAND_I8, SIMD_VERSION_SSE1, SIMD_EMIT_CTOR },
+       { SN_CompareEqual, OP_PCMPEQQ, SIMD_VERSION_SSE41, SIMD_EMIT_BINARY },
+       { SN_LoadAligned, 0, SIMD_VERSION_SSE1, SIMD_EMIT_LOAD_ALIGNED },
+       { SN_PrefetchTemporalAllCacheLevels, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_0 },
+       { SN_PrefetchTemporal1stLevelCache, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_1 },
+       { SN_PrefetchTemporal2ndLevelCache, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_2 },
+       { SN_PrefetchNonTemporal, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_NTA },
+       { SN_StoreAligned, OP_STOREX_ALIGNED_MEMBASE_REG, SIMD_VERSION_SSE1, SIMD_EMIT_STORE },
+       { SN_UnpackHigh, OP_UNPACK_HIGHQ, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_UnpackLow, OP_UNPACK_LOWQ, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_get_X, 0, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER_QWORD },
+       { SN_get_Y, 1, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER_QWORD },
+       { SN_op_Addition, OP_PADDQ, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_BitwiseAnd, OP_PAND, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_BitwiseOr, OP_POR, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_ExclusiveOr, OP_PXOR, SIMD_EMIT_BINARY, SIMD_VERSION_SSE1 },
+       { SN_op_Explicit, 0, SIMD_VERSION_SSE1, SIMD_EMIT_CAST },
+       { SN_op_LeftShift, OP_PSHLQ, SIMD_VERSION_SSE1, SIMD_EMIT_SHIFT },
+       { SN_op_Multiply, OP_PMULQ, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_RightShift, OP_PSHRQ, SIMD_VERSION_SSE1, SIMD_EMIT_SHIFT },
+       { SN_op_Subtraction, OP_PSUBQ, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_set_X, 0, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_Y, 1, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
 };
 
 static const SimdIntrinsc vector2l_intrinsics[] = {
-       { SN_ctor, OP_EXPAND_I8, SIMD_EMIT_CTOR },
-       { SN_CompareEqual, OP_PCMPEQQ, SIMD_EMIT_BINARY, SIMD_VERSION_SSE41 },
-       { SN_CompareGreaterThan, OP_PCMPGTQ, SIMD_EMIT_BINARY, SIMD_VERSION_SSE42 },
-       { SN_LoadAligned, 0, SIMD_EMIT_LOAD_ALIGNED },
-       { SN_LogicalRightShift, OP_PSHRQ, SIMD_EMIT_SHIFT },
-       { SN_PrefetchTemporalAllCacheLevels, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_0 },
-       { SN_PrefetchTemporal1stLevelCache, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_1 },
-       { SN_PrefetchTemporal2ndLevelCache, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_2 },
-       { SN_PrefetchNonTemporal, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_NTA },
-       { SN_StoreAligned, OP_STOREX_ALIGNED_MEMBASE_REG, SIMD_EMIT_STORE },
-       { SN_UnpackHigh, OP_UNPACK_HIGHQ, SIMD_EMIT_BINARY },
-       { SN_UnpackLow, OP_UNPACK_LOWQ, SIMD_EMIT_BINARY },
-       { SN_get_X, 0, SIMD_EMIT_GETTER_QWORD },
-       { SN_get_Y, 1, SIMD_EMIT_GETTER_QWORD },
-       { SN_op_Addition, OP_PADDQ, SIMD_EMIT_BINARY },
-       { SN_op_BitwiseAnd, OP_PAND, SIMD_EMIT_BINARY },
-       { SN_op_BitwiseOr, OP_POR, SIMD_EMIT_BINARY },
-       { SN_op_ExclusiveOr, OP_PXOR, SIMD_EMIT_BINARY },
-       { SN_op_Explicit, 0, SIMD_EMIT_CAST },
-       { SN_op_LeftShift, OP_PSHLQ, SIMD_EMIT_SHIFT },
-       { SN_op_Multiply, OP_PMULQ, SIMD_EMIT_BINARY },
-       { SN_op_Subtraction, OP_PSUBQ, SIMD_EMIT_BINARY },
-       { SN_set_X, 0, SIMD_EMIT_SETTER },
-       { SN_set_Y, 1, SIMD_EMIT_SETTER },
+       { SN_ctor, OP_EXPAND_I8, SIMD_VERSION_SSE1, SIMD_EMIT_CTOR },
+       { SN_CompareEqual, OP_PCMPEQQ, SIMD_VERSION_SSE41, SIMD_EMIT_BINARY },
+       { SN_CompareGreaterThan, OP_PCMPGTQ, SIMD_VERSION_SSE42, SIMD_EMIT_BINARY },
+       { SN_LoadAligned, 0, SIMD_VERSION_SSE1, SIMD_EMIT_LOAD_ALIGNED },
+       { SN_LogicalRightShift, OP_PSHRQ, SIMD_VERSION_SSE1, SIMD_EMIT_SHIFT },
+       { SN_PrefetchTemporalAllCacheLevels, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_0 },
+       { SN_PrefetchTemporal1stLevelCache, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_1 },
+       { SN_PrefetchTemporal2ndLevelCache, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_2 },
+       { SN_PrefetchNonTemporal, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_NTA },
+       { SN_StoreAligned, OP_STOREX_ALIGNED_MEMBASE_REG, SIMD_VERSION_SSE1, SIMD_EMIT_STORE },
+       { SN_UnpackHigh, OP_UNPACK_HIGHQ, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_UnpackLow, OP_UNPACK_LOWQ, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_get_X, 0, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER_QWORD },
+       { SN_get_Y, 1, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER_QWORD },
+       { SN_op_Addition, OP_PADDQ, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_BitwiseAnd, OP_PAND, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_BitwiseOr, OP_POR, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_ExclusiveOr, OP_PXOR, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Explicit, 0, SIMD_VERSION_SSE1, SIMD_EMIT_CAST },
+       { SN_op_LeftShift, OP_PSHLQ, SIMD_VERSION_SSE1, SIMD_EMIT_SHIFT },
+       { SN_op_Multiply, OP_PMULQ, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Subtraction, OP_PSUBQ, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_set_X, 0, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_Y, 1, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
 };
 
 static const SimdIntrinsc vector4ui_intrinsics[] = {
-       { SN_ctor, OP_EXPAND_I4, SIMD_EMIT_CTOR },
-       { SN_ArithmeticRightShift, OP_PSARD, SIMD_EMIT_SHIFT },
-       { SN_CompareEqual, OP_PCMPEQD, SIMD_EMIT_BINARY },
-       { SN_LoadAligned, 0, SIMD_EMIT_LOAD_ALIGNED },
-       { SN_Max, OP_PMAXD_UN, SIMD_EMIT_BINARY, SIMD_VERSION_SSE41 },
-       { SN_Min, OP_PMIND_UN, SIMD_EMIT_BINARY, SIMD_VERSION_SSE41 },
-       { SN_PrefetchTemporalAllCacheLevels, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_0 },
-       { SN_PrefetchTemporal1stLevelCache, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_1 },
-       { SN_PrefetchTemporal2ndLevelCache, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_2 },
-       { SN_PrefetchNonTemporal, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_NTA },
-       { SN_Shuffle, OP_PSHUFLED, SIMD_EMIT_SHUFFLE },
-       { SN_SignedPackWithSignedSaturation, OP_PACKD, SIMD_EMIT_BINARY },
-       { SN_SignedPackWithUnsignedSaturation, OP_PACKD_UN, SIMD_EMIT_BINARY, SIMD_VERSION_SSE41 },
-       { SN_StoreAligned, OP_STOREX_ALIGNED_MEMBASE_REG, SIMD_EMIT_STORE },
-       { SN_UnpackHigh, OP_UNPACK_HIGHD, SIMD_EMIT_BINARY },
-       { SN_UnpackLow, OP_UNPACK_LOWD, SIMD_EMIT_BINARY },
-       { SN_get_W, 3, SIMD_EMIT_GETTER },
-       { SN_get_X, 0, SIMD_EMIT_GETTER },
-       { SN_get_Y, 1, SIMD_EMIT_GETTER },
-       { SN_get_Z, 2, SIMD_EMIT_GETTER },
-       { SN_op_Addition, OP_PADDD, SIMD_EMIT_BINARY },
-       { SN_op_BitwiseAnd, OP_PAND, SIMD_EMIT_BINARY },
-       { SN_op_BitwiseOr, OP_POR, SIMD_EMIT_BINARY },
-       { SN_op_Equality, OP_PCMPEQD, SIMD_EMIT_EQUALITY, SIMD_VERSION_SSE1, SIMD_COMP_EQ },
-       { SN_op_ExclusiveOr, OP_PXOR, SIMD_EMIT_BINARY },
-       { SN_op_Explicit, 0, SIMD_EMIT_CAST },
-       { SN_op_Inequality, OP_PCMPEQD, SIMD_EMIT_EQUALITY, SIMD_VERSION_SSE1, SIMD_COMP_NEQ },
-       { SN_op_LeftShift, OP_PSHLD, SIMD_EMIT_SHIFT },
-       { SN_op_Multiply, OP_PMULD, SIMD_EMIT_BINARY, SIMD_VERSION_SSE41 },
-       { SN_op_RightShift, OP_PSHRD, SIMD_EMIT_SHIFT },
-       { SN_op_Subtraction, OP_PSUBD, SIMD_EMIT_BINARY },
-       { SN_set_W, 3, SIMD_EMIT_SETTER },
-       { SN_set_X, 0, SIMD_EMIT_SETTER },
-       { SN_set_Y, 1, SIMD_EMIT_SETTER },
-       { SN_set_Z, 2, SIMD_EMIT_SETTER },
+       { SN_ctor, OP_EXPAND_I4, SIMD_VERSION_SSE1, SIMD_EMIT_CTOR },
+       { SN_ArithmeticRightShift, OP_PSARD, SIMD_VERSION_SSE1, SIMD_EMIT_SHIFT },
+       { SN_CompareEqual, OP_PCMPEQD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_LoadAligned, 0, SIMD_VERSION_SSE1, SIMD_EMIT_LOAD_ALIGNED },
+       { SN_Max, OP_PMAXD_UN, SIMD_VERSION_SSE41, SIMD_EMIT_BINARY },
+       { SN_Min, OP_PMIND_UN, SIMD_VERSION_SSE41, SIMD_EMIT_BINARY },
+       { SN_PrefetchTemporalAllCacheLevels, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_0 },
+       { SN_PrefetchTemporal1stLevelCache, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_1 },
+       { SN_PrefetchTemporal2ndLevelCache, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_2 },
+       { SN_PrefetchNonTemporal, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_NTA },
+       { SN_Shuffle, OP_PSHUFLED, SIMD_VERSION_SSE1, SIMD_EMIT_SHUFFLE },
+       { SN_SignedPackWithSignedSaturation, OP_PACKD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_SignedPackWithUnsignedSaturation, OP_PACKD_UN, SIMD_VERSION_SSE41, SIMD_EMIT_BINARY },
+       { SN_StoreAligned, OP_STOREX_ALIGNED_MEMBASE_REG, SIMD_VERSION_SSE1, SIMD_EMIT_STORE },
+       { SN_UnpackHigh, OP_UNPACK_HIGHD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_UnpackLow, OP_UNPACK_LOWD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_get_W, 3, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_X, 0, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_Y, 1, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_Z, 2, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_op_Addition, OP_PADDD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_BitwiseAnd, OP_PAND, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_BitwiseOr, OP_POR, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Equality, OP_PCMPEQD, SIMD_VERSION_SSE1, SIMD_EMIT_EQUALITY, SIMD_COMP_EQ },
+       { SN_op_ExclusiveOr, OP_PXOR, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Explicit, 0, SIMD_VERSION_SSE1, SIMD_EMIT_CAST },
+       { SN_op_Inequality, OP_PCMPEQD, SIMD_VERSION_SSE1, SIMD_EMIT_EQUALITY, SIMD_COMP_NEQ },
+       { SN_op_LeftShift, OP_PSHLD, SIMD_VERSION_SSE1, SIMD_EMIT_SHIFT },
+       { SN_op_Multiply, OP_PMULD, SIMD_VERSION_SSE41, SIMD_EMIT_BINARY },
+       { SN_op_RightShift, OP_PSHRD, SIMD_VERSION_SSE1, SIMD_EMIT_SHIFT },
+       { SN_op_Subtraction, OP_PSUBD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_set_W, 3, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_X, 0, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_Y, 1, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_Z, 2, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
 };
 
 static const SimdIntrinsc vector4i_intrinsics[] = {
-       { SN_ctor, OP_EXPAND_I4, SIMD_EMIT_CTOR },
-       { SN_CompareEqual, OP_PCMPEQD, SIMD_EMIT_BINARY },
-       { SN_CompareGreaterThan, OP_PCMPGTD, SIMD_EMIT_BINARY },
-       { SN_LoadAligned, 0, SIMD_EMIT_LOAD_ALIGNED },
-       { SN_LogicalRightShift, OP_PSHRD, SIMD_EMIT_SHIFT },
-       { SN_Max, OP_PMAXD, SIMD_EMIT_BINARY, SIMD_VERSION_SSE41 },
-       { SN_Min, OP_PMIND, SIMD_EMIT_BINARY, SIMD_VERSION_SSE41 },
-       { SN_PackWithSignedSaturation, OP_PACKD, SIMD_EMIT_BINARY },
-       { SN_PackWithUnsignedSaturation, OP_PACKD_UN, SIMD_EMIT_BINARY, SIMD_VERSION_SSE41 },
-       { SN_PrefetchTemporalAllCacheLevels, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_0 },
-       { SN_PrefetchTemporal1stLevelCache, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_1 },
-       { SN_PrefetchTemporal2ndLevelCache, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_2 },
-       { SN_PrefetchNonTemporal, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_NTA },
-       { SN_Shuffle, OP_PSHUFLED, SIMD_EMIT_SHUFFLE },
-       { SN_StoreAligned, OP_STOREX_ALIGNED_MEMBASE_REG, SIMD_EMIT_STORE },
-       { SN_UnpackHigh, OP_UNPACK_HIGHD, SIMD_EMIT_BINARY },
-       { SN_UnpackLow, OP_UNPACK_LOWD, SIMD_EMIT_BINARY },
-       { SN_get_W, 3, SIMD_EMIT_GETTER },
-       { SN_get_X, 0, SIMD_EMIT_GETTER },
-       { SN_get_Y, 1, SIMD_EMIT_GETTER },
-       { SN_get_Z, 2, SIMD_EMIT_GETTER },
-       { SN_op_Addition, OP_PADDD, SIMD_EMIT_BINARY },
-       { SN_op_BitwiseAnd, OP_PAND, SIMD_EMIT_BINARY },
-       { SN_op_BitwiseOr, OP_POR, SIMD_EMIT_BINARY },
-       { SN_op_Equality, OP_PCMPEQD, SIMD_EMIT_EQUALITY, SIMD_VERSION_SSE1, SIMD_COMP_EQ },
-       { SN_op_ExclusiveOr, OP_PXOR, SIMD_EMIT_BINARY },
-       { SN_op_Explicit, 0, SIMD_EMIT_CAST },
-       { SN_op_Inequality, OP_PCMPEQD, SIMD_EMIT_EQUALITY, SIMD_VERSION_SSE1, SIMD_COMP_NEQ },
-       { SN_op_LeftShift, OP_PSHLD, SIMD_EMIT_SHIFT },
-       { SN_op_Multiply, OP_PMULD, SIMD_EMIT_BINARY, SIMD_VERSION_SSE41 },
-       { SN_op_RightShift, OP_PSARD, SIMD_EMIT_SHIFT },
-       { SN_op_Subtraction, OP_PSUBD, SIMD_EMIT_BINARY },
-       { SN_set_W, 3, SIMD_EMIT_SETTER },
-       { SN_set_X, 0, SIMD_EMIT_SETTER },
-       { SN_set_Y, 1, SIMD_EMIT_SETTER },
-       { SN_set_Z, 2, SIMD_EMIT_SETTER },
+       { SN_ctor, OP_EXPAND_I4, SIMD_VERSION_SSE1, SIMD_EMIT_CTOR },
+       { SN_CompareEqual, OP_PCMPEQD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_CompareGreaterThan, OP_PCMPGTD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_LoadAligned, 0, SIMD_VERSION_SSE1, SIMD_EMIT_LOAD_ALIGNED },
+       { SN_LogicalRightShift, OP_PSHRD, SIMD_VERSION_SSE1, SIMD_EMIT_SHIFT },
+       { SN_Max, OP_PMAXD, SIMD_VERSION_SSE41, SIMD_EMIT_BINARY },
+       { SN_Min, OP_PMIND, SIMD_VERSION_SSE41, SIMD_EMIT_BINARY },
+       { SN_PackWithSignedSaturation, OP_PACKD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_PackWithUnsignedSaturation, OP_PACKD_UN, SIMD_VERSION_SSE41, SIMD_EMIT_BINARY },
+       { SN_PrefetchTemporalAllCacheLevels, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_0 },
+       { SN_PrefetchTemporal1stLevelCache, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_1 },
+       { SN_PrefetchTemporal2ndLevelCache, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_2 },
+       { SN_PrefetchNonTemporal, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_NTA },
+       { SN_Shuffle, OP_PSHUFLED, SIMD_VERSION_SSE1, SIMD_EMIT_SHUFFLE },
+       { SN_StoreAligned, OP_STOREX_ALIGNED_MEMBASE_REG, SIMD_VERSION_SSE1, SIMD_EMIT_STORE },
+       { SN_UnpackHigh, OP_UNPACK_HIGHD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_UnpackLow, OP_UNPACK_LOWD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_get_W, 3, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_X, 0, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_Y, 1, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_Z, 2, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_op_Addition, OP_PADDD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_BitwiseAnd, OP_PAND, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_BitwiseOr, OP_POR, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Equality, OP_PCMPEQD, SIMD_VERSION_SSE1, SIMD_EMIT_EQUALITY, SIMD_COMP_EQ },
+       { SN_op_ExclusiveOr, OP_PXOR, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Explicit, 0, SIMD_VERSION_SSE1, SIMD_EMIT_CAST },
+       { SN_op_Inequality, OP_PCMPEQD, SIMD_VERSION_SSE1, SIMD_EMIT_EQUALITY, SIMD_COMP_NEQ },
+       { SN_op_LeftShift, OP_PSHLD, SIMD_VERSION_SSE1, SIMD_EMIT_SHIFT },
+       { SN_op_Multiply, OP_PMULD, SIMD_VERSION_SSE41, SIMD_EMIT_BINARY },
+       { SN_op_RightShift, OP_PSARD, SIMD_VERSION_SSE1, SIMD_EMIT_SHIFT },
+       { SN_op_Subtraction, OP_PSUBD, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_set_W, 3, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_X, 0, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_Y, 1, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_Z, 2, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
 };
 
 static const SimdIntrinsc vector8us_intrinsics[] = {
-       { SN_ctor, OP_EXPAND_I2, SIMD_EMIT_CTOR },
-       { SN_AddWithSaturation, OP_PADDW_SAT_UN, SIMD_EMIT_BINARY },
-       { SN_ArithmeticRightShift, OP_PSARW, SIMD_EMIT_SHIFT },
-       { SN_Average, OP_PAVGW_UN, SIMD_EMIT_BINARY },
-       { SN_CompareEqual, OP_PCMPEQW, SIMD_EMIT_BINARY },
-       { SN_LoadAligned, 0, SIMD_EMIT_LOAD_ALIGNED },
-       { SN_Max, OP_PMAXW_UN, SIMD_EMIT_BINARY, SIMD_VERSION_SSE41 },
-       { SN_Min, OP_PMINW_UN, SIMD_EMIT_BINARY, SIMD_VERSION_SSE41 },
-       { SN_MultiplyStoreHigh, OP_PMULW_HIGH_UN, SIMD_EMIT_BINARY },
-       { SN_PrefetchTemporalAllCacheLevels, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_0 },
-       { SN_PrefetchTemporal1stLevelCache, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_1 },
-       { SN_PrefetchTemporal2ndLevelCache, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_2 },
-       { SN_PrefetchNonTemporal, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_NTA },
-       { SN_ShuffleHigh, OP_PSHUFLEW_HIGH, SIMD_EMIT_SHUFFLE },
-       { SN_ShuffleLow, OP_PSHUFLEW_LOW, SIMD_EMIT_SHUFFLE },
-       { SN_SignedPackWithSignedSaturation, OP_PACKW, SIMD_EMIT_BINARY },
-       { SN_SignedPackWithUnsignedSaturation, OP_PACKW_UN, SIMD_EMIT_BINARY },
-       { SN_StoreAligned, OP_STOREX_ALIGNED_MEMBASE_REG, SIMD_EMIT_STORE },
-       { SN_SubtractWithSaturation, OP_PSUBW_SAT_UN, SIMD_EMIT_BINARY },
-       { SN_UnpackHigh, OP_UNPACK_HIGHW, SIMD_EMIT_BINARY },
-       { SN_UnpackLow, OP_UNPACK_LOWW, SIMD_EMIT_BINARY },
-       { SN_get_V0, 0, SIMD_EMIT_GETTER },
-       { SN_get_V1, 1, SIMD_EMIT_GETTER },
-       { SN_get_V2, 2, SIMD_EMIT_GETTER },
-       { SN_get_V3, 3, SIMD_EMIT_GETTER },
-       { SN_get_V4, 4, SIMD_EMIT_GETTER },
-       { SN_get_V5, 5, SIMD_EMIT_GETTER },
-       { SN_get_V6, 6, SIMD_EMIT_GETTER },
-       { SN_get_V7, 7, SIMD_EMIT_GETTER },
-       { SN_op_Addition, OP_PADDW, SIMD_EMIT_BINARY },
-       { SN_op_BitwiseAnd, OP_PAND, SIMD_EMIT_BINARY },
-       { SN_op_BitwiseOr, OP_POR, SIMD_EMIT_BINARY },
-       { SN_op_Equality, OP_PCMPEQW, SIMD_EMIT_EQUALITY, SIMD_VERSION_SSE1, SIMD_COMP_EQ },
-       { SN_op_ExclusiveOr, OP_PXOR, SIMD_EMIT_BINARY },
-       { SN_op_Explicit, 0, SIMD_EMIT_CAST },
-       { SN_op_Inequality, OP_PCMPEQW, SIMD_EMIT_EQUALITY, SIMD_VERSION_SSE1, SIMD_COMP_NEQ },
-       { SN_op_LeftShift, OP_PSHLW, SIMD_EMIT_SHIFT },
-       { SN_op_Multiply, OP_PMULW, SIMD_EMIT_BINARY },
-       { SN_op_RightShift, OP_PSHRW, SIMD_EMIT_SHIFT },
-       { SN_op_Subtraction, OP_PSUBW, SIMD_EMIT_BINARY },
-       { SN_set_V0, 0, SIMD_EMIT_SETTER },
-       { SN_set_V1, 1, SIMD_EMIT_SETTER },
-       { SN_set_V2, 2, SIMD_EMIT_SETTER },
-       { SN_set_V3, 3, SIMD_EMIT_SETTER },
-       { SN_set_V4, 4, SIMD_EMIT_SETTER },
-       { SN_set_V5, 5, SIMD_EMIT_SETTER },
-       { SN_set_V6, 6, SIMD_EMIT_SETTER },
-       { SN_set_V7, 7, SIMD_EMIT_SETTER },
+       { SN_ctor, OP_EXPAND_I2, SIMD_VERSION_SSE1, SIMD_EMIT_CTOR },
+       { SN_AddWithSaturation, OP_PADDW_SAT_UN, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_ArithmeticRightShift, OP_PSARW, SIMD_VERSION_SSE1, SIMD_EMIT_SHIFT },
+       { SN_Average, OP_PAVGW_UN, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_CompareEqual, OP_PCMPEQW, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY, SIMD_VERSION_SSE1 },
+       { SN_LoadAligned, 0, SIMD_VERSION_SSE1, SIMD_EMIT_LOAD_ALIGNED },
+       { SN_Max, OP_PMAXW_UN, SIMD_VERSION_SSE41, SIMD_EMIT_BINARY },
+       { SN_Min, OP_PMINW_UN, SIMD_VERSION_SSE41, SIMD_EMIT_BINARY },
+       { SN_MultiplyStoreHigh, OP_PMULW_HIGH_UN, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_PrefetchTemporalAllCacheLevels, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_0 },
+       { SN_PrefetchTemporal1stLevelCache, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_1 },
+       { SN_PrefetchTemporal2ndLevelCache, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_2 },
+       { SN_PrefetchNonTemporal, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_NTA },
+       { SN_ShuffleHigh, OP_PSHUFLEW_HIGH, SIMD_VERSION_SSE1, SIMD_EMIT_SHUFFLE },
+       { SN_ShuffleLow, OP_PSHUFLEW_LOW, SIMD_VERSION_SSE1, SIMD_EMIT_SHUFFLE },
+       { SN_SignedPackWithSignedSaturation, OP_PACKW, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_SignedPackWithUnsignedSaturation, OP_PACKW_UN, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_StoreAligned, OP_STOREX_ALIGNED_MEMBASE_REG, SIMD_VERSION_SSE1, SIMD_EMIT_STORE },
+       { SN_SubtractWithSaturation, OP_PSUBW_SAT_UN, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_UnpackHigh, OP_UNPACK_HIGHW, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_UnpackLow, OP_UNPACK_LOWW, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_get_V0, 0, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V1, 1, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V2, 2, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V3, 3, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V4, 4, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V5, 5, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V6, 6, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V7, 7, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_op_Addition, OP_PADDW, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_BitwiseAnd, OP_PAND, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_BitwiseOr, OP_POR, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Equality, OP_PCMPEQW, SIMD_VERSION_SSE1, SIMD_EMIT_EQUALITY, SIMD_COMP_EQ },
+       { SN_op_ExclusiveOr, OP_PXOR, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Explicit, 0, SIMD_VERSION_SSE1, SIMD_EMIT_CAST },
+       { SN_op_Inequality, OP_PCMPEQW, SIMD_VERSION_SSE1, SIMD_EMIT_EQUALITY, SIMD_COMP_NEQ },
+       { SN_op_LeftShift, OP_PSHLW, SIMD_VERSION_SSE1, SIMD_EMIT_SHIFT },
+       { SN_op_Multiply, OP_PMULW, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_RightShift, OP_PSHRW, SIMD_VERSION_SSE1, SIMD_EMIT_SHIFT },
+       { SN_op_Subtraction, OP_PSUBW, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_set_V0, 0, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V1, 1, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V2, 2, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V3, 3, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V4, 4, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V5, 5, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V6, 6, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V7, 7, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
 };
 
 static const SimdIntrinsc vector8s_intrinsics[] = {
-       { SN_ctor, OP_EXPAND_I2, SIMD_EMIT_CTOR },
-       { SN_AddWithSaturation, OP_PADDW_SAT, SIMD_EMIT_BINARY },
-       { SN_CompareEqual, OP_PCMPEQW, SIMD_EMIT_BINARY },
-       { SN_CompareGreaterThan, OP_PCMPGTW, SIMD_EMIT_BINARY },
-       { SN_LoadAligned, 0, SIMD_EMIT_LOAD_ALIGNED },
-       { SN_LogicalRightShift, OP_PSHRW, SIMD_EMIT_SHIFT },
-       { SN_Max, OP_PMAXW, SIMD_EMIT_BINARY },
-       { SN_Min, OP_PMINW, SIMD_EMIT_BINARY },
-       { SN_MultiplyStoreHigh, OP_PMULW_HIGH, SIMD_EMIT_BINARY },
-       { SN_PackWithSignedSaturation, OP_PACKW, SIMD_EMIT_BINARY },
-       { SN_PackWithUnsignedSaturation, OP_PACKW_UN, SIMD_EMIT_BINARY },
-       { SN_PrefetchTemporalAllCacheLevels, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_0 },
-       { SN_PrefetchTemporal1stLevelCache, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_1 },
-       { SN_PrefetchTemporal2ndLevelCache, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_2 },
-       { SN_PrefetchNonTemporal, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_NTA },
-       { SN_ShuffleHigh, OP_PSHUFLEW_HIGH, SIMD_EMIT_SHUFFLE },
-       { SN_ShuffleLow, OP_PSHUFLEW_LOW, SIMD_EMIT_SHUFFLE },
-       { SN_StoreAligned, OP_STOREX_ALIGNED_MEMBASE_REG, SIMD_EMIT_STORE },
-       { SN_SubtractWithSaturation, OP_PSUBW_SAT_UN, SIMD_EMIT_BINARY },
-       { SN_UnpackHigh, OP_UNPACK_HIGHW, SIMD_EMIT_BINARY },
-       { SN_UnpackLow, OP_UNPACK_LOWW, SIMD_EMIT_BINARY },
-       { SN_get_V0, 0, SIMD_EMIT_GETTER },
-       { SN_get_V1, 1, SIMD_EMIT_GETTER },
-       { SN_get_V2, 2, SIMD_EMIT_GETTER },
-       { SN_get_V3, 3, SIMD_EMIT_GETTER },
-       { SN_get_V4, 4, SIMD_EMIT_GETTER },
-       { SN_get_V5, 5, SIMD_EMIT_GETTER },
-       { SN_get_V6, 6, SIMD_EMIT_GETTER },
-       { SN_get_V7, 7, SIMD_EMIT_GETTER },
-       { SN_op_Addition, OP_PADDW, SIMD_EMIT_BINARY },
-       { SN_op_BitwiseAnd, OP_PAND, SIMD_EMIT_BINARY },
-       { SN_op_BitwiseOr, OP_POR, SIMD_EMIT_BINARY },
-       { SN_op_Equality, OP_PCMPEQW, SIMD_EMIT_EQUALITY, SIMD_VERSION_SSE1, SIMD_COMP_EQ },
-       { SN_op_ExclusiveOr, OP_PXOR, SIMD_EMIT_BINARY },
-       { SN_op_Explicit, 0, SIMD_EMIT_CAST },
-       { SN_op_Inequality, OP_PCMPEQW, SIMD_EMIT_EQUALITY, SIMD_VERSION_SSE1, SIMD_COMP_NEQ },
-       { SN_op_LeftShift, OP_PSHLW, SIMD_EMIT_SHIFT },
-       { SN_op_Multiply, OP_PMULW, SIMD_EMIT_BINARY },
-       { SN_op_RightShift, OP_PSARW, SIMD_EMIT_SHIFT },
-       { SN_op_Subtraction, OP_PSUBW, SIMD_EMIT_BINARY },
-       { SN_set_V0, 0, SIMD_EMIT_SETTER },
-       { SN_set_V1, 1, SIMD_EMIT_SETTER },
-       { SN_set_V2, 2, SIMD_EMIT_SETTER },
-       { SN_set_V3, 3, SIMD_EMIT_SETTER },
-       { SN_set_V4, 4, SIMD_EMIT_SETTER },
-       { SN_set_V5, 5, SIMD_EMIT_SETTER },
-       { SN_set_V6, 6, SIMD_EMIT_SETTER },
-       { SN_set_V7, 7, SIMD_EMIT_SETTER },
+       { SN_ctor, OP_EXPAND_I2, SIMD_VERSION_SSE1, SIMD_EMIT_CTOR },
+       { SN_AddWithSaturation, OP_PADDW_SAT, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_CompareEqual, OP_PCMPEQW, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_CompareGreaterThan, OP_PCMPGTW, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_LoadAligned, 0, SIMD_VERSION_SSE1, SIMD_EMIT_LOAD_ALIGNED },
+       { SN_LogicalRightShift, OP_PSHRW, SIMD_VERSION_SSE1, SIMD_EMIT_SHIFT },
+       { SN_Max, OP_PMAXW, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_Min, OP_PMINW, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_MultiplyStoreHigh, OP_PMULW_HIGH, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_PackWithSignedSaturation, OP_PACKW, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_PackWithUnsignedSaturation, OP_PACKW_UN, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_PrefetchTemporalAllCacheLevels, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_0 },
+       { SN_PrefetchTemporal1stLevelCache, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_1 },
+       { SN_PrefetchTemporal2ndLevelCache, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_2 },
+       { SN_PrefetchNonTemporal, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_NTA },
+       { SN_ShuffleHigh, OP_PSHUFLEW_HIGH, SIMD_VERSION_SSE1, SIMD_EMIT_SHUFFLE },
+       { SN_ShuffleLow, OP_PSHUFLEW_LOW, SIMD_VERSION_SSE1, SIMD_EMIT_SHUFFLE },
+       { SN_StoreAligned, OP_STOREX_ALIGNED_MEMBASE_REG, SIMD_VERSION_SSE1, SIMD_EMIT_STORE },
+       { SN_SubtractWithSaturation, OP_PSUBW_SAT_UN, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_UnpackHigh, OP_UNPACK_HIGHW, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_UnpackLow, OP_UNPACK_LOWW, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_get_V0, 0, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V1, 1, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V2, 2, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V3, 3, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V4, 4, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V5, 5, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V6, 6, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V7, 7, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_op_Addition, OP_PADDW, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_BitwiseAnd, OP_PAND, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_BitwiseOr, OP_POR, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Equality, OP_PCMPEQW, SIMD_VERSION_SSE1, SIMD_EMIT_EQUALITY, SIMD_COMP_EQ },
+       { SN_op_ExclusiveOr, OP_PXOR, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Explicit, 0, SIMD_VERSION_SSE1, SIMD_EMIT_CAST },
+       { SN_op_Inequality, OP_PCMPEQW, SIMD_VERSION_SSE1, SIMD_EMIT_EQUALITY, SIMD_COMP_NEQ },
+       { SN_op_LeftShift, OP_PSHLW, SIMD_VERSION_SSE1, SIMD_EMIT_SHIFT },
+       { SN_op_Multiply, OP_PMULW, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_RightShift, OP_PSARW, SIMD_VERSION_SSE1, SIMD_EMIT_SHIFT },
+       { SN_op_Subtraction, OP_PSUBW, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_set_V0, 0, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V1, 1, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V2, 2, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V3, 3, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V4, 4, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V5, 5, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V6, 6, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V7, 7, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
 };
 
 static const SimdIntrinsc vector16b_intrinsics[] = {
-       { SN_ctor, OP_EXPAND_I1, SIMD_EMIT_CTOR },
-       { SN_AddWithSaturation, OP_PADDB_SAT_UN, SIMD_EMIT_BINARY },
-       { SN_Average, OP_PAVGB_UN, SIMD_EMIT_BINARY },
-       { SN_CompareEqual, OP_PCMPEQB, SIMD_EMIT_BINARY },
-       { SN_ExtractByteMask, 0, SIMD_EMIT_EXTRACT_MASK },
-       { SN_LoadAligned, 0, SIMD_EMIT_LOAD_ALIGNED },
-       { SN_Max, OP_PMAXB_UN, SIMD_EMIT_BINARY },
-       { SN_Min, OP_PMINB_UN, SIMD_EMIT_BINARY },
-       { SN_PrefetchTemporalAllCacheLevels, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_0 },
-       { SN_PrefetchTemporal1stLevelCache, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_1 },
-       { SN_PrefetchTemporal2ndLevelCache, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_2 },
-       { SN_PrefetchNonTemporal, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_NTA },
-       { SN_StoreAligned, OP_STOREX_ALIGNED_MEMBASE_REG, SIMD_EMIT_STORE },
-       { SN_SubtractWithSaturation, OP_PSUBB_SAT_UN, SIMD_EMIT_BINARY },
-       { SN_SumOfAbsoluteDifferences, OP_PSUM_ABS_DIFF, SIMD_EMIT_BINARY },
-       { SN_UnpackHigh, OP_UNPACK_HIGHB, SIMD_EMIT_BINARY },
-       { SN_UnpackLow, OP_UNPACK_LOWB, SIMD_EMIT_BINARY },
-       { SN_get_V0, 0, SIMD_EMIT_GETTER },
-       { SN_get_V1, 1, SIMD_EMIT_GETTER },
-       { SN_get_V10, 10, SIMD_EMIT_GETTER },
-       { SN_get_V11, 11, SIMD_EMIT_GETTER },
-       { SN_get_V12, 12, SIMD_EMIT_GETTER },
-       { SN_get_V13, 13, SIMD_EMIT_GETTER },
-       { SN_get_V14, 14, SIMD_EMIT_GETTER },
-       { SN_get_V15, 15, SIMD_EMIT_GETTER },
-       { SN_get_V2, 2, SIMD_EMIT_GETTER },
-       { SN_get_V3, 3, SIMD_EMIT_GETTER },
-       { SN_get_V4, 4, SIMD_EMIT_GETTER },
-       { SN_get_V5, 5, SIMD_EMIT_GETTER },
-       { SN_get_V6, 6, SIMD_EMIT_GETTER },
-       { SN_get_V7, 7, SIMD_EMIT_GETTER },
-       { SN_get_V8, 8, SIMD_EMIT_GETTER },
-       { SN_get_V9, 9, SIMD_EMIT_GETTER },
-       { SN_op_Addition, OP_PADDB, SIMD_EMIT_BINARY },
-       { SN_op_BitwiseAnd, OP_PAND, SIMD_EMIT_BINARY },
-       { SN_op_BitwiseOr, OP_POR, SIMD_EMIT_BINARY },
-       { SN_op_Equality, OP_PCMPEQB, SIMD_EMIT_EQUALITY, SIMD_VERSION_SSE1, SIMD_COMP_EQ },
-       { SN_op_ExclusiveOr, OP_PXOR, SIMD_EMIT_BINARY },
-       { SN_op_Explicit, 0, SIMD_EMIT_CAST },
-       { SN_op_Inequality, OP_PCMPEQB, SIMD_EMIT_EQUALITY, SIMD_VERSION_SSE1, SIMD_COMP_NEQ },
-       { SN_op_Subtraction, OP_PSUBB, SIMD_EMIT_BINARY },
-       { SN_set_V0, 0, SIMD_EMIT_SETTER },
-       { SN_set_V1, 1, SIMD_EMIT_SETTER },
-       { SN_set_V10, 10, SIMD_EMIT_SETTER },
-       { SN_set_V11, 11, SIMD_EMIT_SETTER },
-       { SN_set_V12, 12, SIMD_EMIT_SETTER },
-       { SN_set_V13, 13, SIMD_EMIT_SETTER },
-       { SN_set_V14, 14, SIMD_EMIT_SETTER },
-       { SN_set_V15, 15, SIMD_EMIT_SETTER },
-       { SN_set_V2, 2, SIMD_EMIT_SETTER },
-       { SN_set_V3, 3, SIMD_EMIT_SETTER },
-       { SN_set_V4, 4, SIMD_EMIT_SETTER },
-       { SN_set_V5, 5, SIMD_EMIT_SETTER },
-       { SN_set_V6, 6, SIMD_EMIT_SETTER },
-       { SN_set_V7, 7, SIMD_EMIT_SETTER },
-       { SN_set_V8, 8, SIMD_EMIT_SETTER },
-       { SN_set_V9, 9, SIMD_EMIT_SETTER },
+       { SN_ctor, OP_EXPAND_I1, SIMD_VERSION_SSE1, SIMD_EMIT_CTOR },
+       { SN_AddWithSaturation, OP_PADDB_SAT_UN, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_Average, OP_PAVGB_UN, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_CompareEqual, OP_PCMPEQB, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_ExtractByteMask, 0, SIMD_VERSION_SSE1, SIMD_EMIT_EXTRACT_MASK },
+       { SN_LoadAligned, 0, SIMD_VERSION_SSE1, SIMD_EMIT_LOAD_ALIGNED },
+       { SN_Max, OP_PMAXB_UN, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_Min, OP_PMINB_UN, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_PrefetchTemporalAllCacheLevels, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_0 },
+       { SN_PrefetchTemporal1stLevelCache, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_1 },
+       { SN_PrefetchTemporal2ndLevelCache, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_2 },
+       { SN_PrefetchNonTemporal, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_NTA },
+       { SN_StoreAligned, OP_STOREX_ALIGNED_MEMBASE_REG, SIMD_VERSION_SSE1, SIMD_EMIT_STORE },
+       { SN_SubtractWithSaturation, OP_PSUBB_SAT_UN, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_SumOfAbsoluteDifferences, OP_PSUM_ABS_DIFF, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_UnpackHigh, OP_UNPACK_HIGHB, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_UnpackLow, OP_UNPACK_LOWB, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_get_V0, 0, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V1, 1, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V10, 10, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V11, 11, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V12, 12, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V13, 13, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V14, 14, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V15, 15, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V2, 2, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V3, 3, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V4, 4, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V5, 5, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V6, 6, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V7, 7, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V8, 8, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V9, 9, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_op_Addition, OP_PADDB, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_BitwiseAnd, OP_PAND, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_BitwiseOr, OP_POR, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Equality, OP_PCMPEQB, SIMD_VERSION_SSE1, SIMD_EMIT_EQUALITY, SIMD_COMP_EQ },
+       { SN_op_ExclusiveOr, OP_PXOR, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Explicit, 0, SIMD_VERSION_SSE1, SIMD_EMIT_CAST },
+       { SN_op_Inequality, OP_PCMPEQB, SIMD_VERSION_SSE1, SIMD_EMIT_EQUALITY, SIMD_COMP_NEQ },
+       { SN_op_Subtraction, OP_PSUBB, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_set_V0, 0, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V1, 1, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V10, 10, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V11, 11, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V12, 12, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V13, 13, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V14, 14, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V15, 15, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V2, 2, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V3, 3, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V4, 4, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V5, 5, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V6, 6, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V7, 7, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V8, 8, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V9, 9, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
 };
 
 /*
@@ -514,62 +514,62 @@ Missing:
 setters
  */
 static const SimdIntrinsc vector16sb_intrinsics[] = {
-       { SN_ctor, OP_EXPAND_I1, SIMD_EMIT_CTOR },
-       { SN_AddWithSaturation, OP_PADDB_SAT, SIMD_EMIT_BINARY },
-       { SN_CompareEqual, OP_PCMPEQB, SIMD_EMIT_BINARY },
-       { SN_CompareGreaterThan, OP_PCMPGTB, SIMD_EMIT_BINARY },
-       { SN_ExtractByteMask, 0, SIMD_EMIT_EXTRACT_MASK },
-       { SN_LoadAligned, 0, SIMD_EMIT_LOAD_ALIGNED },
-       { SN_Max, OP_PMAXB, SIMD_EMIT_BINARY, SIMD_VERSION_SSE41 },
-       { SN_Min, OP_PMINB, SIMD_EMIT_BINARY, SIMD_VERSION_SSE41 },
-       { SN_PrefetchTemporalAllCacheLevels, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_0 },
-       { SN_PrefetchTemporal1stLevelCache, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_1 },
-       { SN_PrefetchTemporal2ndLevelCache, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_2 },
-       { SN_PrefetchNonTemporal, 0, SIMD_EMIT_PREFETCH, SIMD_VERSION_SSE1, SIMD_PREFETCH_MODE_NTA },
-       { SN_StoreAligned, OP_STOREX_ALIGNED_MEMBASE_REG, SIMD_EMIT_STORE },
-       { SN_SubtractWithSaturation, OP_PSUBB_SAT, SIMD_EMIT_BINARY },
-       { SN_UnpackHigh, OP_UNPACK_HIGHB, SIMD_EMIT_BINARY },
-       { SN_UnpackLow, OP_UNPACK_LOWB, SIMD_EMIT_BINARY },
-       { SN_get_V0, 0, SIMD_EMIT_GETTER },
-       { SN_get_V1, 1, SIMD_EMIT_GETTER },
-       { SN_get_V10, 10, SIMD_EMIT_GETTER },
-       { SN_get_V11, 11, SIMD_EMIT_GETTER },
-       { SN_get_V12, 12, SIMD_EMIT_GETTER },
-       { SN_get_V13, 13, SIMD_EMIT_GETTER },
-       { SN_get_V14, 14, SIMD_EMIT_GETTER },
-       { SN_get_V15, 15, SIMD_EMIT_GETTER },
-       { SN_get_V2, 2, SIMD_EMIT_GETTER },
-       { SN_get_V3, 3, SIMD_EMIT_GETTER },
-       { SN_get_V4, 4, SIMD_EMIT_GETTER },
-       { SN_get_V5, 5, SIMD_EMIT_GETTER },
-       { SN_get_V6, 6, SIMD_EMIT_GETTER },
-       { SN_get_V7, 7, SIMD_EMIT_GETTER },
-       { SN_get_V8, 8, SIMD_EMIT_GETTER },
-       { SN_get_V9, 9, SIMD_EMIT_GETTER },
-       { SN_op_Addition, OP_PADDB, SIMD_EMIT_BINARY },
-       { SN_op_BitwiseAnd, OP_PAND, SIMD_EMIT_BINARY },
-       { SN_op_BitwiseOr, OP_POR, SIMD_EMIT_BINARY },
-       { SN_op_Equality, OP_PCMPEQB, SIMD_EMIT_EQUALITY, SIMD_VERSION_SSE1, SIMD_COMP_EQ },
-       { SN_op_ExclusiveOr, OP_PXOR, SIMD_EMIT_BINARY },
-       { SN_op_Explicit, 0, SIMD_EMIT_CAST },
-       { SN_op_Inequality, OP_PCMPEQB, SIMD_EMIT_EQUALITY, SIMD_VERSION_SSE1, SIMD_COMP_NEQ },
-       { SN_op_Subtraction, OP_PSUBB, SIMD_EMIT_BINARY },
-       { SN_set_V0, 0, SIMD_EMIT_SETTER },
-       { SN_set_V1, 1, SIMD_EMIT_SETTER },
-       { SN_set_V10, 10, SIMD_EMIT_SETTER },
-       { SN_set_V11, 11, SIMD_EMIT_SETTER },
-       { SN_set_V12, 12, SIMD_EMIT_SETTER },
-       { SN_set_V13, 13, SIMD_EMIT_SETTER },
-       { SN_set_V14, 14, SIMD_EMIT_SETTER },
-       { SN_set_V15, 15, SIMD_EMIT_SETTER },
-       { SN_set_V2, 2, SIMD_EMIT_SETTER },
-       { SN_set_V3, 3, SIMD_EMIT_SETTER },
-       { SN_set_V4, 4, SIMD_EMIT_SETTER },
-       { SN_set_V5, 5, SIMD_EMIT_SETTER },
-       { SN_set_V6, 6, SIMD_EMIT_SETTER },
-       { SN_set_V7, 7, SIMD_EMIT_SETTER },
-       { SN_set_V8, 8, SIMD_EMIT_SETTER },
-       { SN_set_V9, 9, SIMD_EMIT_SETTER },
+       { SN_ctor, OP_EXPAND_I1, SIMD_VERSION_SSE1, SIMD_EMIT_CTOR },
+       { SN_AddWithSaturation, OP_PADDB_SAT, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_CompareEqual, OP_PCMPEQB, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_CompareGreaterThan, OP_PCMPGTB, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_ExtractByteMask, 0, SIMD_VERSION_SSE1, SIMD_EMIT_EXTRACT_MASK },
+       { SN_LoadAligned, 0, SIMD_VERSION_SSE1, SIMD_EMIT_LOAD_ALIGNED },
+       { SN_Max, OP_PMAXB, SIMD_VERSION_SSE41, SIMD_EMIT_BINARY },
+       { SN_Min, OP_PMINB, SIMD_VERSION_SSE41, SIMD_EMIT_BINARY },
+       { SN_PrefetchTemporalAllCacheLevels, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_0 },
+       { SN_PrefetchTemporal1stLevelCache, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_1 },
+       { SN_PrefetchTemporal2ndLevelCache, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_2 },
+       { SN_PrefetchNonTemporal, 0, SIMD_VERSION_SSE1, SIMD_EMIT_PREFETCH, SIMD_PREFETCH_MODE_NTA },
+       { SN_StoreAligned, OP_STOREX_ALIGNED_MEMBASE_REG, SIMD_VERSION_SSE1, SIMD_EMIT_STORE },
+       { SN_SubtractWithSaturation, OP_PSUBB_SAT, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_UnpackHigh, OP_UNPACK_HIGHB, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_UnpackLow, OP_UNPACK_LOWB, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_get_V0, 0, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V1, 1, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V10, 10, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V11, 11, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V12, 12, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V13, 13, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V14, 14, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V15, 15, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V2, 2, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V3, 3, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V4, 4, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V5, 5, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V6, 6, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V7, 7, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V8, 8, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_get_V9, 9, SIMD_VERSION_SSE1, SIMD_EMIT_GETTER },
+       { SN_op_Addition, OP_PADDB, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_BitwiseAnd, OP_PAND, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_BitwiseOr, OP_POR, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Equality, OP_PCMPEQB, SIMD_VERSION_SSE1, SIMD_EMIT_EQUALITY, SIMD_COMP_EQ },
+       { SN_op_ExclusiveOr, OP_PXOR, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_op_Explicit, 0, SIMD_VERSION_SSE1, SIMD_EMIT_CAST },
+       { SN_op_Inequality, OP_PCMPEQB, SIMD_VERSION_SSE1, SIMD_EMIT_EQUALITY, SIMD_COMP_NEQ },
+       { SN_op_Subtraction, OP_PSUBB, SIMD_VERSION_SSE1, SIMD_EMIT_BINARY },
+       { SN_set_V0, 0, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V1, 1, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V10, 10, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V11, 11, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V12, 12, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V13, 13, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V14, 14, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V15, 15, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V2, 2, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V3, 3, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V4, 4, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V5, 5, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V6, 6, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V7, 7, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V8, 8, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
+       { SN_set_V9, 9, SIMD_VERSION_SSE1, SIMD_EMIT_SETTER },
 };
 
 static guint32 simd_supported_versions;
@@ -866,22 +866,74 @@ get_simd_ctor_spill_area (MonoCompile *cfg, MonoClass *avector_klass)
        return cfg->simd_ctor_var;
 }
 
+static int
+mono_type_to_expand_op (MonoType *type)
+{
+       switch (type->type) {
+       case MONO_TYPE_I1:
+       case MONO_TYPE_U1:
+               return OP_EXPAND_I1;
+       case MONO_TYPE_I2:
+       case MONO_TYPE_U2:
+               return OP_EXPAND_I2;
+       case MONO_TYPE_I4:
+       case MONO_TYPE_U4:
+               return OP_EXPAND_I4;
+       case MONO_TYPE_I8:
+       case MONO_TYPE_U8:
+               return OP_EXPAND_I8;
+       case MONO_TYPE_R4:
+               return OP_EXPAND_R4;
+       case MONO_TYPE_R8:
+               return OP_EXPAND_R8;
+       }
+       g_assert_not_reached ();
+}
+
+static int
+get_simd_vreg_or_expanded_scalar (MonoCompile *cfg, MonoMethod *cmethod, MonoInst *src, int position)
+{
+       MonoInst *ins;
+       MonoMethodSignature *sig = mono_method_signature (cmethod);
+       int expand_op;
+
+       g_assert (sig->param_count == 2);
+       g_assert (position == 0 || position == 1);
+
+       if (mono_class_from_mono_type (sig->params [position])->simd_type)
+               return get_simd_vreg (cfg, cmethod, src);
+
+       expand_op = mono_type_to_expand_op (sig->params [position]);
+       MONO_INST_NEW (cfg, ins, expand_op);
+       ins->klass = cmethod->klass;
+       ins->sreg1 = src->dreg;
+       ins->type = STACK_VTYPE;
+       ins->dreg = alloc_ireg (cfg);
+       MONO_ADD_INS (cfg->cbb, ins);
+
+       if (expand_op == OP_EXPAND_R4)
+               ins->backend.spill_var = get_int_to_float_spill_area (cfg);
+       else if (expand_op == OP_EXPAND_R8)
+               ins->backend.spill_var = get_double_spill_area (cfg);
+
+       return ins->dreg;
+}
+
 static MonoInst*
 simd_intrinsic_emit_binary (const SimdIntrinsc *intrinsic, MonoCompile *cfg, MonoMethod *cmethod, MonoInst **args)
 {
        MonoInst* ins;
        int left_vreg, right_vreg;
 
-       left_vreg = get_simd_vreg (cfg, cmethod, args [0]);
-       right_vreg = get_simd_vreg (cfg, cmethod, args [1]);
-       
+       left_vreg = get_simd_vreg_or_expanded_scalar (cfg, cmethod, args [0], 0);
+       right_vreg = get_simd_vreg_or_expanded_scalar (cfg, cmethod, args [1], 1);
+
 
        MONO_INST_NEW (cfg, ins, intrinsic->opcode);
        ins->klass = cmethod->klass;
        ins->sreg1 = left_vreg;
        ins->sreg2 = right_vreg;
        ins->type = STACK_VTYPE;
-       ins->klass = cmethod->klass;
        ins->dreg = alloc_ireg (cfg);
        ins->inst_c0 = intrinsic->flags;
        MONO_ADD_INS (cfg->cbb, ins);
@@ -1384,9 +1436,16 @@ emit_intrinsics (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsi
                        mono_print_ins (args [i]);
                }
        }
-       if (result->simd_version && !((1 << result->simd_version) & simd_supported_versions)) {
-               if (IS_DEBUG_ON (cfg))
-                       printf ("function %s::%s/%d requires unsuported SIMD instruction set %s \n", cmethod->klass->name, cmethod->name, fsig->param_count, simd_version_name (result->simd_version));
+       if (result->simd_version_flags && !(result->simd_version_flags & simd_supported_versions)) {
+               if (IS_DEBUG_ON (cfg)) {
+                       int x;
+                       printf ("function %s::%s/%d requires one of unsuported SIMD instruction set(s): ", cmethod->klass->name, cmethod->name, fsig->param_count);
+                       for (x = 1; x <= SIMD_VERSION_INDEX_END; x++)
+                               if (result->simd_version_flags & (1 << x))
+                                       printf ("%s ", simd_version_name (1 << x));
+
+                       printf ("\n");
+               }
                return NULL;
        }
 
index 0398aa6191e3c6c36600222c8075d912b92e4bfb..b635e7ce6b706970b1cf440d82c73976771d8813 100644 (file)
@@ -74,7 +74,7 @@
 
 /*------------------------------------------------------------------*/
 /*                                                                  */
-/* Name                - mono_arch_get_unbox_trampoline                        */
+/* Name                - mono_arch_get_unbox_trampoline                    */
 /*                                                                  */
 /* Function    - Return a pointer to a trampoline which does the   */
 /*               unboxing before calling the method.               */
@@ -119,9 +119,9 @@ mono_arch_get_unbox_trampoline (MonoGenericSharingContext *gsctx, MonoMethod *me
 
 /*------------------------------------------------------------------*/
 /*                                                                  */
-/* Name                - mono_arch_patch_callsite                              */
+/* Name                - mono_arch_patch_callsite                          */
 /*                                                                  */
-/* Function    - Patch a non-virtual callsite so it calls @addr.       */
+/* Function    - Patch a non-virtual callsite so it calls @addr.   */
 /*                                                                  */
 /*------------------------------------------------------------------*/
 
@@ -157,6 +157,14 @@ mono_arch_patch_callsite (guint8 *method_start, guint8 *orig_code, guint8 *addr)
 
 /*========================= End of Function ========================*/
 
+/*------------------------------------------------------------------*/
+/*                                                                  */
+/* Name                - mono_arch_patch_plt_entry.                        */
+/*                                                                  */
+/* Function    - Patch a PLT entry - unused as yet.                */
+/*                                                                  */
+/*------------------------------------------------------------------*/
+
 void
 mono_arch_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *addr)
 {
@@ -167,9 +175,9 @@ mono_arch_patch_plt_entry (guint8 *code, gpointer *got, mgreg_t *regs, guint8 *a
 
 /*------------------------------------------------------------------*/
 /*                                                                  */
-/* Name                - mono_arch_nullify_class_init_trampoline               */
+/* Name                - mono_arch_nullify_class_init_trampoline           */
 /*                                                                  */
-/* Function    - Nullify a call which calls a class init trampoline    */
+/* Function    - Nullify a call which calls a class init trampoline*/
 /*                                                                  */
 /*------------------------------------------------------------------*/
 
@@ -185,6 +193,14 @@ mono_arch_nullify_class_init_trampoline (guint8 *code, mgreg_t *regs)
 
 /*========================= End of Function ========================*/
 
+/*------------------------------------------------------------------*/
+/*                                                                  */
+/* Name                - mono_arch_nullify_plt_entry                       */
+/*                                                                  */
+/* Function    - Nullify a PLT entry call.                         */
+/*                                                                  */
+/*------------------------------------------------------------------*/
+
 void
 mono_arch_nullify_plt_entry (guint8 *code, mgreg_t *regs)
 {
@@ -195,9 +211,9 @@ mono_arch_nullify_plt_entry (guint8 *code, mgreg_t *regs)
 
 /*------------------------------------------------------------------*/
 /*                                                                  */
-/* Name                - mono_arch_get_vcall_slot                              */
+/* Name                - mono_arch_get_vcall_slot                          */
 /*                                                                  */
-/* Function    - This method is called by the arch independent         */
+/* Function    - This method is called by the arch independent     */
 /*            trampoline code to determine the vtable slot used by  */
 /*            the call which invoked the trampoline.                */
 /*                                                                  */
@@ -215,9 +231,13 @@ mono_arch_get_vcall_slot (guint8 *code, mgreg_t *regs, int *displacement)
        guchar* base;
        unsigned short opcode;
        char *sp;
+       MonoLMF *lmf = (MonoLMF *) ((gchar *) regs - sizeof(MonoLMF));
 
        // We are passed sp instead of the register array
-       sp = (char*)regs;
+#if 0
+       sp = (char *) regs;
+#endif
+       sp = (char *) lmf->gregs[s390_r15];
 
        *displacement = 0;
 
@@ -227,7 +247,7 @@ mono_arch_get_vcall_slot (guint8 *code, mgreg_t *regs, int *displacement)
                return NULL;
 
        /*-----------------------------------*/
-       /* This is a bras r14,Rz instruction */
+       /* This is a basr r14,Rz instruction */
        /* If it's preceded by a LG Rx,d(Ry) */
        /* If Rz == 1 then this is virtual   */
        /* call.                             */
@@ -238,8 +258,7 @@ mono_arch_get_vcall_slot (guint8 *code, mgreg_t *regs, int *displacement)
        /* If call is preceded by LGR then   */
        /* there's nothing to patch          */
        /*-----------------------------------*/
-       if ((code[0] == 0xb9) &&
-               (code[1] == 0x04))
+       if ((code[0] == 0xb9) && (code[1] == 0x04))
                return NULL;
 
        /*-----------------------------------*/
@@ -257,10 +276,15 @@ mono_arch_get_vcall_slot (guint8 *code, mgreg_t *regs, int *displacement)
        /* hh  = high 8 bits of displacement */
        /*-----------------------------------*/
        reg      = code[0] >> 4;
-       *displacement = (code[2] << 12) +
-               ((code[0] & 0x0f) << 8) +
-               code[1];
+       *displacement = (code[2] << 12) |
+                       ((code[0] & 0x0f) << 8) |
+                       code[1];
 
+       if (code[2] & 0x80)
+               *displacement |= 0xfff00000;
+
+       base = ((guchar *) lmf->gregs[reg]);
+#if 0
        if (reg > 5)
                base = *((guchar **) (sp + S390_REG_SAVE_OFFSET +
                                                          sizeof(long)*(reg-6)));
@@ -268,6 +292,7 @@ mono_arch_get_vcall_slot (guint8 *code, mgreg_t *regs, int *displacement)
                base = *((guchar **) ((sp - CREATE_STACK_SIZE) +
                                                          CREATE_GR_OFFSET +
                                                          sizeof(long)*(reg-2)));
+#endif
        if (lkReg != 1)
                /* Non virtual call */
                return NULL;
@@ -279,7 +304,7 @@ mono_arch_get_vcall_slot (guint8 *code, mgreg_t *regs, int *displacement)
 
 /*------------------------------------------------------------------*/
 /*                                                                  */
-/* Name                - mono_arch_create_trampoline_code                            */
+/* Name                - mono_arch_create_trampoline_code                  */
 /*                                                                  */
 /* Function    - Create the designated type of trampoline according*/
 /*                to the 'tramp_type' parameter.                    */
@@ -303,7 +328,7 @@ mono_arch_create_trampoline_code (MonoTrampolineType tramp_type)
          stack size big enough to save our registers.
          -----------------------------------------------------------*/
                
-       s390_stmg (buf, s390_r6, s390_r14, STK_BASE, S390_REG_SAVE_OFFSET);
+       s390_stmg (buf, s390_r6, s390_r15, STK_BASE, S390_REG_SAVE_OFFSET);
        s390_lgr  (buf, s390_r11, s390_r15);
        s390_aghi (buf, STK_BASE, -CREATE_STACK_SIZE);
        s390_stg  (buf, s390_r11, 0, STK_BASE, 0);
@@ -388,12 +413,14 @@ mono_arch_create_trampoline_code (MonoTrampolineType tramp_type)
        /*---------------------------------------------------------------*/     
        /* Save general and floating point registers                     */     
        /*---------------------------------------------------------------*/     
-       s390_stmg  (buf, s390_r2, s390_r12, s390_r13,
-                           G_STRUCT_OFFSET(MonoLMF, gregs[2]));                
-       for (i = 0; i < 16; i++) {
-               s390_std  (buf, i, 0, s390_r13,
-                                  G_STRUCT_OFFSET(MonoLMF, fregs[i]));
-       }                                               
+       s390_mvc   (buf, 4*sizeof(gulong), s390_r13, G_STRUCT_OFFSET(MonoLMF, gregs[2]), 
+                   STK_BASE, CREATE_GR_OFFSET);
+       s390_mvc   (buf, 10*sizeof(gulong), s390_r13, G_STRUCT_OFFSET(MonoLMF, gregs[6]), 
+                   s390_r11, S390_REG_SAVE_OFFSET);
+
+       /* Simply copy fpregs already saved above                        */
+       s390_mvc   (buf, 16*sizeof(double), s390_r13, G_STRUCT_OFFSET(MonoLMF, fregs[0]),
+                   STK_BASE, CREATE_FP_OFFSET);
 
        /*---------------------------------------------------------------*/
        /* STEP 2: call the C trampoline function                        */
@@ -402,8 +429,7 @@ mono_arch_create_trampoline_code (MonoTrampolineType tramp_type)
        /* Set arguments */
 
        /* Arg 1: mgreg_t *regs. We pass sp instead */
-       s390_lgr  (buf, s390_r2, STK_BASE);
-       s390_ahi  (buf, s390_r2, CREATE_STACK_SIZE);
+       s390_la  (buf, s390_r2, 0, STK_BASE, CREATE_STACK_SIZE);
                
        /* Arg 2: code (next address to the instruction that called us) */
        if (tramp_type == MONO_TRAMPOLINE_JUMP) {
@@ -474,9 +500,9 @@ mono_arch_create_trampoline_code (MonoTrampolineType tramp_type)
 
 /*------------------------------------------------------------------*/
 /*                                                                  */
-/* Name                - mono_arch_create_specific_trampoline                  */
+/* Name                - mono_arch_create_specific_trampoline              */
 /*                                                                  */
-/* Function    - Creates the given kind of specific trampoline         */
+/* Function    - Creates the given kind of specific trampoline     */
 /*                                                                  */
 /*------------------------------------------------------------------*/
 
@@ -516,10 +542,20 @@ mono_arch_create_specific_trampoline (gpointer arg1, MonoTrampolineType tramp_ty
 
 /*========================= End of Function ========================*/
 
+/*------------------------------------------------------------------*/
+/*                                                                  */
+/* Name                - mono_arch_create_rgctx_lazy_fetch_trampoline      */
+/*                                                                  */
+/* Function    -                                                   */
+/*                                                                  */
+/*------------------------------------------------------------------*/
+
 gpointer
 mono_arch_create_rgctx_lazy_fetch_trampoline (guint32 encoded_offset)
 {
        /* FIXME: implement! */
        g_assert_not_reached ();
        return NULL;
-}
+}      
+
+/*========================= End of Function ========================*/
index 5373ab46a733fe1af530617870ecbd42d7f01fed..3a9095e59271132daf01d8816b77af5ca76bf2b0 100644 (file)
@@ -832,3 +832,41 @@ mono_arch_invalidate_method (MonoJitInfo *ji, void *func, gpointer func_arg)
        x86_push_imm (code, func_arg);
        x86_call_code (code, (guint8*)func);
 }
+
+static void
+handler_block_trampoline_helper (gpointer *ptr)
+{
+       MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
+       *ptr = jit_tls->handler_block_return_address;
+}
+
+gpointer
+mono_arch_create_handler_block_trampoline (void)
+{
+       guint8 *tramp = mono_get_trampoline_code (MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD);
+       guint8 *code, *buf;
+       int tramp_size = 64;
+       code = buf = mono_global_codeman_reserve (tramp_size);
+
+       /*
+       This trampoline restore the call chain of the handler block then jumps into the code that deals with it.
+       */
+
+       if (mono_get_jit_tls_offset () != -1) {
+               code = mono_x86_emit_tls_get (code, X86_EAX, mono_get_jit_tls_offset ());
+               x86_mov_reg_membase (code, X86_EAX, X86_EAX, G_STRUCT_OFFSET (MonoJitTlsData, handler_block_return_address), 4);
+               /*simulate a call*/
+               x86_push_reg (code, X86_EAX);
+               x86_jump_code (code, tramp);
+       } else {
+               /*Slow path uses a c helper*/
+               x86_push_reg (code, X86_ESP);
+               x86_push_imm (code, tramp);
+               x86_jump_code (code, handler_block_trampoline_helper);
+       }
+
+       mono_arch_flush_icache (buf, code - buf);
+       g_assert (code - buf <= tramp_size);
+
+       return buf;
+}
index 92c3e36e0805d2f8a044e3c0d035d07bc20a27a0..38d83deb1bd154d0d5ecb3362b27ce2a9c6efcdd 100644 (file)
@@ -5,3 +5,4 @@
 /monograph
 /*.o
 /*.lo
+/TAGS
index 878ac915cbf839c928d87ddad574b3b4b59589fa..63c9b9cdb698f96b1d838fa4806641a868329813 100644 (file)
@@ -6,3 +6,4 @@
 /*.o
 /*.lo
 /*.la
+/TAGS
index bb39f27ad80caf1f1f992905cf86fd644cfa992d..2a4e1588da56c6046289121cffb6187bf254ffea 100644 (file)
@@ -1,4 +1,9 @@
 
+Tue Mar 16 11:20:14 CET 2010 Paolo Molaro <lupus@ximian.com>
+
+       * mono-profiler-iomap.c: fix some API usage and add a warning
+       about this code.
+
 Wed Mar 3 19:17:14 CET 2010 Paolo Molaro <lupus@ximian.com>
 
        * mono-profiler-iomap.c: use the normal allocation callback.
index 1b69c6a3e85728a0a4ec4ac92c4dfaedbbe105e3..d3f3f8e2970a8985fd4bccdc79303f2611cabeb2 100644 (file)
@@ -5,6 +5,9 @@
  *   Marek Habersack <mhabersack@novell.com>
  *
  * Copyright (c) 2009 Novell, Inc (http://novell.com)
+ *
+ * Note: this profiler is completely unsafe wrt handling managed objects,
+ * don't use and don't copy code from here.
  */
 #include "config.h"
 
@@ -225,7 +228,7 @@ static gboolean saved_strings_find_func (gpointer key, gpointer value, gpointer
        gchar *utf_str;
        guint32 hash;
 
-       if (!info || !saved || saved->string->length != info->len)
+       if (!info || !saved || mono_string_length (saved->string) != info->len)
                return FALSE;
 
        utf_str = mono_string_to_utf8 (saved->string);
@@ -475,7 +478,7 @@ static void mono_portability_remember_alloc (MonoProfiler *prof, MonoObject *obj
 {
        if (klass != string_class)
                return;
-       mono_portability_remember_string (prof, mono_object_domain (obj), (MonoString*)obj);
+       mono_portability_remember_string (prof, mono_object_get_domain (obj), (MonoString*)obj);
 }
 
 static void mono_portability_iomap_event (MonoProfiler *prof, const char *report, const char *pathname, const char *new_pathname)
index bca5d5809347f5564854cc649bb6b85a39dafecc..b6c7ae694ddf8423d8e18a9759188ba3ee1beedf 100644 (file)
@@ -1,6 +1,8 @@
 /Makefile.in
 /Makefile
 /*.stdout
+/*.stderr
+/*.aotlog
 /.deps
 /.libs
 /libtest.la
@@ -22,3 +24,4 @@
 /bin
 /page.aspx
 /tests-config
+/TAGS
index d425c055833a4dd2f13d7cc4bacf32b2e8fe5d51..c94f4cc17ea57c67e726151d48a36963050a3a6e 100644 (file)
@@ -1,3 +1,45 @@
+2010-04-10  Zoltan Varga  <vargaz@gmail.com>
+
+       * dtest.cs: Add a minimal test for Thread.ThreadId.
+
+2010-04-08  Zoltan Varga  <vargaz@gmail.com>
+
+       * exit-stress-threadpool.cs: New stress test.
+
+2010-04-07  Zoltan Varga  <vargaz@gmail.com>
+
+       * interlocked-2.2.cs: Add an Interlocked.CompareExchange(long) test.
+
+2010-04-06 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * bug-575941.cs: New regression test.
+
+2010-04-05 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * bug-515884.il: New regression test.
+
+2010-04-02  Zoltan Varga  <vargaz@gmail.com>
+
+       * libtest.c: Add OpenBSD to the list of defines.
+
+2010-03-26  Zoltan Varga  <vargaz@gmail.com>
+
+       * Makefile.am: Disable testbundle for now as it depends on having a system mono.
+
+2010-03-23  Zoltan Varga  <vargaz@gmail.com>
+
+       * Makefile.am (BASE_TEST_CS_SRC): Remove make-imt-test.cs, it is not a test.
+
+       * test-runner.cs: Add an option to run the tests with different optimization
+       sets.
+
+       * Makefile.am: Make it possible to run the normal+gshared tests using the managed
+       test runner by passing the M=1 option to make.
+
+2010-03-18  Zoltan Varga  <vargaz@gmail.com>
+
+       * Makefile.am (runtest): Save the output of the aot compiler into a file.
+
 2010-03-05  Robert Jordan  <robertj@gmx.net>
 
        * remoting4.cs: Add test for bug #504886.
index ad9d74609d8a23e32f6f8d8ce5202ce03eb6c060..ece41ac8d4bcbcd06c2fdc5bffec62bc8cb9895e 100644 (file)
@@ -20,17 +20,17 @@ JITTEST_PROG_RUN = MONO_SHARED_DIR=$(mono_build_root)/runtime MONO_CFG_DIR=$(mon
 RUNTIME_ARGS=--config tests-config --optimize=all --debug
 
 with_mono_path = MONO_PATH=$(mcs_topdir)/class/lib/net_2_0
-with_mono_path21 = MONO_PATH=$(mcs_topdir)/class/lib/net_2_1_raw
+with_mono_path_moonlight = MONO_PATH=$(mcs_topdir)/class/lib/moonlight_raw
 
 RUNTIME = $(with_mono_path) $(top_builddir)/runtime/mono-wrapper
-RUNTIME21 = $(with_mono_path21) $(top_builddir)/runtime/mono-wrapper
+RUNTIME_MOONLIGHT = $(with_mono_path_moonlight) $(top_builddir)/runtime/mono-wrapper
 
 MKBUNDLE = \
        PKG_CONFIG_PATH=$(top_builddir):$(PKG_CONFIG_PATH) \
        $(RUNTIME) $(mcs_topdir)/class/lib/net_2_0/mkbundle.exe
 
 MCS = $(RUNTIME) $(mcs_topdir)/class/lib/net_2_0/gmcs.exe -unsafe -nowarn:0162 -nowarn:0168 -nowarn:0219 -debug
-SMCS = $(RUNTIME21) --runtime=moonlight --security=temporary-smcs-hack $(mcs_topdir)/class/lib/net_2_1_raw/smcs.exe -unsafe -nowarn:0162 -nowarn:0168 -nowarn:0219
+SMCS = $(RUNTIME_MOONLIGHT) --runtime=moonlight --security=temporary-smcs-hack $(mcs_topdir)/class/lib/moonlight_raw/smcs.exe -unsafe -nowarn:0162 -nowarn:0168 -nowarn:0219
 ILASM = $(RUNTIME) $(mcs_topdir)/class/lib/net_2_0/ilasm.exe
 
 BENCHSRC=fib.cs random.cs nested-loops.cs ackermann.cs tight-loop.cs sieve.cs
@@ -250,7 +250,6 @@ BASE_TEST_CS_SRC=           \
        exists.cs               \
        handleref.cs    \
        transparentproxy.cs \
-       make-imt-test.cs \
        dbnull-missing.cs       \
        test-type-ctor.cs       \
        soft-float-tests.cs     \
@@ -365,8 +364,9 @@ BASE_TEST_CS_SRC=           \
        gc-altstack.cs  \
        large-gc-bitmap.cs      \
        bug-561239.cs   \
-       bug-562150.cs
-
+       bug-562150.cs   \
+       bug-575941.cs   \
+       bug-599469.cs
 
 TEST_CS_SRC_DIST=      \
        $(BASE_TEST_CS_SRC)     \
@@ -482,7 +482,8 @@ TEST_IL_SRC=                        \
        constraints-load.il     \
        array_load_exception.il \
        bug-481403.il   \
-       interface-with-static-method.il
+       interface-with-static-method.il \
+       bug-515884.il
 
 #      bug-318677.il
 
@@ -518,7 +519,9 @@ else
 if HOST_WIN32
 test_platform:
 else
-test_platform: testbundle test-iomap-regression
+# mkbundle uses the installed mono-2.pc so it won't work if there is no system mono
+#test_platform:        testbundle test-iomap-regression
+test_platform: test-iomap-regression
 endif
 endif
 
@@ -585,7 +588,7 @@ runtest: $(TESTSI_CS) $(TESTSI_IL) $(TESTBS) libtest.la $(PREREQSI_IL) $(PREREQS
        failed_tests="";\
        for i in $(TESTSI_CS) $(TESTBS) $(TESTSI_IL); do        \
                rm -f $${i}.so; \
-               if [ x$(AOT) = x1 ]; then if echo $(AOT_DISABLED_TESTS) | grep -v -q $${i}; then $(with_mono_path) $(JITTEST_PROG_RUN) --aot --debug $${i} > /dev/null || exit 1; fi; fi; \
+               if [ x$(AOT) = x1 ]; then if echo $(AOT_DISABLED_TESTS) | grep -v -q $${i}; then $(with_mono_path) $(JITTEST_PROG_RUN) --aot --debug $${i} > $${i}.aotlog 2>&1 || exit 1; fi; fi; \
                if $(srcdir)/test-driver '$(with_mono_path) $(JITTEST_PROG_RUN)' $$i '$(DISABLED_TESTS)' $(RUNTIME_ARGS); \
                then \
                        passed=`expr $${passed} + 1`; \
@@ -603,7 +606,7 @@ runtest-managed: test-runner.exe $(TESTSI_CS) $(TESTSI_IL) $(TESTBS) libtest.la
        @$(RUNTIME) ./test-runner.exe -j a --disabled '$(DISABLED_TESTS)' $(TESTSI_CS) $(TESTBS) $(TESTSI_IL)
 
 testjit:
-       @$(MAKE) runtest
+       @if test x$(M) != x; then $(MAKE) runtest-managed; else $(MAKE) runtest; fi
 
 testaot:
        @$(MAKE) AOT=1 runtest
@@ -758,7 +761,7 @@ coreclr-security.exe : coreclr-security.cs
 
 test-coreclr-security : coreclr-security.exe
        @echo "Testing coreclr-security.exe..."
-       @$(RUNTIME21) --security=core-clr-test coreclr-security.exe
+       @$(RUNTIME_MOONLIGHT) --security=core-clr-test coreclr-security.exe
 endif
 
 EXTRA_DIST += generic-unboxing.2.il
@@ -788,7 +791,8 @@ gshared: test-generic-sharing
 gshared-aot:
        @$(MAKE) AOT=1 gshared
 
-test-generic-sharing : generics-sharing.2.exe shared-generic-methods.2.exe     \
+GSHARED_TESTS = \
+               generics-sharing.2.exe shared-generic-methods.2.exe     \
                shared-generic-synchronized.2.exe generic-initobj.2.exe         \
                generics-sharing-other-exc.2.exe generic-box.2.exe              \
                generic-unbox.2.exe generic-delegate.2.exe generic-sizeof.2.exe \
@@ -813,6 +817,8 @@ test-generic-sharing : generics-sharing.2.exe shared-generic-methods.2.exe  \
                bug-472600.2.exe bug-473482.2.exe bug-473999.2.exe              \
                bug-479763.2.exe generic-xdomain.2.exe                          \
                generic-type-load-exception.2.exe
+
+test-generic-sharing-normal: $(GSHARED_TESTS)
        @for fn in $+ ; do      \
                echo "Testing $$fn ...";        \
                MONO_GENERIC_SHARING=all $(RUNTIME) -O=gshared                $$fn > $$fn.stdout || exit 1;     \
@@ -822,6 +828,12 @@ test-generic-sharing : generics-sharing.2.exe shared-generic-methods.2.exe \
                if [ x$(AOT) = x1 ]; then MONO_GENERIC_SHARING=all $(with_mono_path) $(JITTEST_PROG_RUN) --aot --debug $$fn > /dev/null || exit 1; MONO_GENERIC_SHARING=all $(RUNTIME) $$fn > $$fn.stdout || exit 1; fi; \
        done
 
+test-generic-sharing-managed: test-runner.exe $(GSHARED_TESTS)
+       @$(RUNTIME) ./test-runner.exe -j a --opt-sets "gshared gshared,shared gshared,-inline gshared,-inline,shared" $(GSHARED_TESTS)
+
+test-generic-sharing:
+       @if test x$(M) != x; then $(MAKE) test-generic-sharing-managed; else $(MAKE) test-generic-sharing-normal; fi
+
 EXTRA_DIST += async-exceptions.cs
 async-exceptions.exe : async-exceptions.cs
        $(MCS) -out:async-exceptions.exe $(srcdir)/async-exceptions.cs
@@ -871,4 +883,4 @@ endif
 libtest_la_SOURCES = libtest.c
 libtest_la_LIBADD = $(glib_libs)
 
-CLEANFILES = $(TESTSI_CS) $(TESTSI_IL) $(STRESS_TESTS) *.dll *.stdout *.exe stest.dat
+CLEANFILES = $(TESTSI_CS) $(TESTSI_IL) $(STRESS_TESTS) *.dll *.stdout *.aotlog *.exe stest.dat
index 0ec52b83b598d5f89749cffa32e7715674fa7351..3e7894c06c78af34a529a63556042bddb8cd4da1 100644 (file)
@@ -11,11 +11,11 @@ public class Test : MarshalByRefObject {
     }
 
     ~Test () {
-           Console.WriteLine ("in test desctructor");
+           Console.WriteLine ("in test destructor");
            GetIntDelegate del = new GetIntDelegate (getInt);
            AsyncCallback ac = new AsyncCallback (async_callback);
            if (del.BeginInvoke (ac, "bla") == null) {
-                   Console.WriteLine ("async recult is null");
+                   Console.WriteLine ("async result is null");
                    Environment.Exit (1);
            }
     }
diff --git a/mono/tests/bug-515884.il b/mono/tests/bug-515884.il
new file mode 100644 (file)
index 0000000..7e4972a
--- /dev/null
@@ -0,0 +1,37 @@
+.assembly extern mscorlib\r
+{\r
+  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )                         // .z\V.4..\r
+  .ver 2:0:0:0\r
+}\r
+.assembly ConsoleApplication1\r
+{\r
+  .hash algorithm 0x00008004\r
+  .ver 0:0:0:0\r
+}\r
+.module ConsoleApplication1.exe\r
+\r
+\r
+.class private auto ansi beforefieldinit ConsoleApplication1.Program extends [mscorlib]System.Object\r
+{\r
+       .method public hidebysig static int32 Main(string[] args) cil managed\r
+       {\r
+               .entrypoint\r
+               .maxstack 8\r
+               .locals init (class [mscorlib]System.AppDomain V_0)\r
+
+               ldstr "Test"\r
+               call class [mscorlib]System.AppDomain [mscorlib]System.AppDomain::CreateDomain(string)
+               call instance string [mscorlib]System.AppDomain::get_FriendlyName()\r
+
+               ldstr "Test"\r
+               callvirt instance bool [mscorlib]System.Object::Equals (object)
+               brfalse END
+
+               ldc.i4.0
+               ret
+
+END:
+               ldc.i4.1
+               ret
+       }\r
+}
diff --git a/mono/tests/bug-575941.cs b/mono/tests/bug-575941.cs
new file mode 100644 (file)
index 0000000..cade944
--- /dev/null
@@ -0,0 +1,55 @@
+using System;
+using System.Threading;
+using System.Reflection;
+using System.Reflection.Emit;
+
+public class Tests
+{
+       public static int Main (String[] args) {
+               AssemblyName assemblyName = new AssemblyName ();
+               assemblyName.Name = "foo";
+
+               AssemblyBuilder assembly =
+                       Thread.GetDomain ().DefineDynamicAssembly (
+                                                                                                          assemblyName, AssemblyBuilderAccess.RunAndSave);
+
+               ModuleBuilder module = assembly.DefineDynamicModule ("foo.dll");
+
+               TypeBuilder if_tb = module.DefineType ("IF`1", TypeAttributes.Public|TypeAttributes.Abstract|TypeAttributes.Interface);
+
+               GenericTypeParameterBuilder [] typeParams = if_tb.DefineGenericParameters ("T");
+
+               MethodBuilder if_mb = if_tb.DefineMethod ("foo", MethodAttributes.Public|MethodAttributes.Abstract|MethodAttributes.Virtual, typeParams [0], Type.EmptyTypes);
+
+
+               TypeBuilder tb = module.DefineType ("Foo`1", TypeAttributes.Public, typeof (object));
+               GenericTypeParameterBuilder [] tbTypeParams = tb.DefineGenericParameters ("T");
+
+
+               Type inst = if_tb.MakeGenericType (tbTypeParams [0]);
+
+               tb.AddInterfaceImplementation (inst);
+
+               var mb0 = tb.DefineMethod ("foo", MethodAttributes.Public|MethodAttributes.Virtual, typeParams [0], Type.EmptyTypes);
+               mb0.GetILGenerator ().Emit (OpCodes.Ret);
+
+               var mb = tb.DefineMethod ("__foo", MethodAttributes.Public|MethodAttributes.Virtual, typeParams [0],Type.EmptyTypes);
+               var gen = mb.GetILGenerator ();
+               var local = gen.DeclareLocal (typeParams [0], false);
+               gen.Emit (OpCodes.Ldloca, local);
+               gen.Emit (OpCodes.Initobj, typeParams [0]);
+               gen.Emit (OpCodes.Ldloc, local);
+               gen.Emit (OpCodes.Ret);
+
+               tb.DefineMethodOverride (mb, TypeBuilder.GetMethod (inst, if_mb));
+
+               var k = if_tb.CreateType ();
+
+               Type t = tb.CreateType ();
+               object obj = Activator.CreateInstance (t.MakeGenericType (new Type [] { typeof (string)}));
+               var info = k.MakeGenericType (new Type [] { typeof (string) }).GetMethod ("foo");
+               var res = info.Invoke (obj, null);
+               return res == null ? 0 : 1;
+       }
+}
+
diff --git a/mono/tests/bug-599469.cs b/mono/tests/bug-599469.cs
new file mode 100644 (file)
index 0000000..51c7c1f
--- /dev/null
@@ -0,0 +1,35 @@
+public class Grid<CT>
+        where CT : Grid<CT>.GPD.GC, new()
+{
+        public abstract class GPD
+        {
+                public GPD()
+                {
+                        ctInst = new CT();
+                }
+
+                public readonly CT ctInst;
+
+                public abstract class GC
+                {
+                }
+        }
+}
+
+public class H : Grid<H.MyCT>.GPD
+{
+        public class MyCT : GC
+        {
+                // When no explicit default constructor is present GMCS fails to compile the file.
+                // When it is present the execution crashes on mono.
+                public MyCT () {}
+        }
+}
+
+public class TheTest
+{
+        public static void Main (string[] args)
+        {
+                new H();
+        }
+}
\ No newline at end of file
index df7654f05e3fc19b8107e03715d4c3ead63dfc63..efc01e896e284e82bcc94dbe217930277605fec7 100644 (file)
@@ -1917,6 +1917,8 @@ public class DebuggerTests
 
                Assert.AreEqual (ThreadState.Running, e.Thread.ThreadState);
 
+               Assert.IsTrue (e.Thread.ThreadId > 0);
+
                vm.EnableEvents (EventType.ThreadStart, EventType.ThreadDeath);
 
                vm.Resume ();
diff --git a/mono/tests/exit-stress-threadpool.cs b/mono/tests/exit-stress-threadpool.cs
new file mode 100644 (file)
index 0000000..1294525
--- /dev/null
@@ -0,0 +1,19 @@
+// https://bugzilla.novell.com/show_bug.cgi?id=593955
+using System;
+using System.Threading;
+
+public class Tests
+{
+       public static void Main (String[] args) {
+               new Thread (delegate () {
+                               Thread.Sleep (100);
+                               Environment.Exit (0);
+               }).Start ();
+
+               while (true) {
+                       Action a = delegate () {
+                       };
+                       a.BeginInvoke (null, null);
+               }
+       }
+}
index ae7d30a067f11716c6666c48f9ca3c889c282bb5..c16f700f75facc8e1f56e0643e1e9003924e3e58 100644 (file)
@@ -85,6 +85,13 @@ public class InterlockTest
                if (lb != 0x12345678)
                        return 18;              
 
+               la = 1;
+               lb = Interlocked.CompareExchange (ref la, 2, 1);
+               if (la != 2)
+                       return 19;
+               if (lb != 1)
+                       return 20;
+
                Console.WriteLine ("done!");
 
                return 0;
index 8060d71b768dbf55ea35fa709b52d38c3ff8f5d6..57e8f700f6c57184f7007a278fd2292cff8f9e1e 100644 (file)
@@ -3191,7 +3191,7 @@ mono_test_marshal_ccw_itest (MonoComObject *pUnk)
  * mono_method_get_unmanaged_thunk tests
  */
 
-#if defined(__GNUC__) && ((defined(__i386__) && (defined(__linux__) || defined (__APPLE__)) || defined (__FreeBSD__)) || (defined(__ppc__) && defined(__APPLE__)))
+#if defined(__GNUC__) && ((defined(__i386__) && (defined(__linux__) || defined (__APPLE__)) || defined (__FreeBSD__) || defined(__OpenBSD__)) || (defined(__ppc__) && defined(__APPLE__)))
 #define ALIGN(size) __attribute__ ((aligned(size)))
 #else
 #define ALIGN(size)
index 0e22e696d570ef7a5b9eac2bfa20afd3f8035a7b..90152c1acc58c9dd690b568ab3d1bf094947ee6a 100644 (file)
@@ -1,3 +1,8 @@
+2010-04-13 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * Remove broken tests dues to aditional tests or relaxation
+       of existing constraints.
+
 2009-09-09  Rodrigo Kumpera  <rkumpera@novell.com>
 
        * badrt-recursive-struct.il: New test for structs with bad layout.
index d36b427132764a8e0e1f4f4cdf7899560678d0dc..263cde0c1f5027ac32731b38c2200d1ed7db6e9f 100644 (file)
@@ -74,7 +74,7 @@ TEST_BINARIES = assembly-with-resource.exe \
 
 
 gen-md-tests: gen-md-tests.c
-       gcc $(GLIB_CFLAGS) $(GLIB_LINK_FLAGS) -I../../../ gen-md-tests.c ../../mini/.libs/libmono.a -g -Wall -lpthread -lm -ldl -o gen-md-tests
+       gcc $(GLIB_CFLAGS) $(GLIB_LINK_FLAGS) -I../../../ gen-md-tests.c ../../mini/.libs/libmono-2.0.a -g -Wall -lpthread -lm -ldl -lrt -o gen-md-tests
 
 header-tests.ok: gen-md-tests header-tests.md simple-assembly.exe
        ./gen-md-tests header-tests.md
index 0b4762f2069ca8a3b90ce9125bedb8332fbf3fb5..cec99ac9f9d0efa0f12815014dfe65dc01a151c3 100644 (file)
@@ -178,7 +178,7 @@ typedef-table {
        valid offset table-row ( 2 0 ) + 8 set-ushort 0
        #make <module> extend the first typeref entry, which usually is sys.obj
        #LAMEIMPL MS ignores if <module> extend something.
-       invalid offset table-row ( 2 0 ) + 8 set-ushort 0x5
+       #invalid offset table-row ( 2 0 ) + 8 set-ushort 0x5
 }
 
 typedef-table-field-list {
@@ -288,9 +288,8 @@ methoddef-table {
        assembly assembly-with-methods.exe
 
        #bad implflags (3)
-       #unused bits 4,5,6,8,9,10,11,15
-       #LAMEIMPL MS doesn't check invalid bits  6,8,9,10,11,13,14,15
-       invalid offset table-row ( 6 0 ) + 4 set-bit 6
+       #unused bits 4,5,8,9,10,11,15
+       #LAMEIMPL MS doesn't check invalid bits  8,9,10,11,13,14,15
        invalid offset table-row ( 6 0 ) + 4 set-bit 8
        invalid offset table-row ( 6 0 ) + 4 set-bit 9
        invalid offset table-row ( 6 0 ) + 4 set-bit 10
@@ -645,8 +644,9 @@ cattr-table {
        #this uses 3 bits and only 0x2/0x3 are valid
        invalid offset table-row ( 0xC 0 ) + 2 set-ushort 0x0008
        invalid offset table-row ( 0xC 0 ) + 2 set-ushort 0x0009
-       valid offset table-row ( 0xC 0 ) + 2 set-ushort 0x000A
-       valid offset table-row ( 0xC 0 ) + 2 set-ushort 0x000B
+       #those two tests are invalid since they result in broken cattr
+       #valid offset table-row ( 0xC 0 ) + 2 set-ushort 0x000A
+       #valid offset table-row ( 0xC 0 ) + 2 set-ushort 0x000B
        invalid offset table-row ( 0xC 0 ) + 2 set-ushort 0x000C
        invalid offset table-row ( 0xC 0 ) + 2 set-ushort 0x000D
        invalid offset table-row ( 0xC 0 ) + 2 set-ushort 0x000E
index fdca71a76552d55239181dfa53cfca076b3fd2a9..ce0d65e74189bd049872cf8b414a8529a36f3348 100644 (file)
@@ -42,6 +42,10 @@ public class TestRunner
                public StreamWriter stdout, stderr;
        }
 
+       class TestInfo {
+               public string test, opt_set;
+       }
+
        public static int Main (String[] args) {
                // Defaults
                int concurrency = 1;
@@ -51,6 +55,7 @@ public class TestRunner
 
                string disabled_tests = null;
                string runtime = "mono";
+               var opt_sets = new List<string> ();
 
                // Process options
                int i = 0;
@@ -87,6 +92,14 @@ public class TestRunner
                                        }
                                        runtime = args [i + 1];
                                        i += 2;
+                               } else if (args [i] == "--opt-sets") {
+                                       if (i + i >= args.Length) {
+                                               Console.WriteLine ("Missing argument to --opt-sets command line option.");
+                                               return 1;
+                                       }
+                                       foreach (var s in args [i + 1].Split ())
+                                               opt_sets.Add (s);
+                                       i += 2;
                                } else {
                                        Console.WriteLine ("Unknown command line option: '" + args [i] + "'.");
                                        return 1;
@@ -123,7 +136,18 @@ public class TestRunner
                if (concurrency != 1)
                        Console.WriteLine ("Running tests: ");
 
-               foreach (string test in tests) {
+               var test_info = new List<TestInfo> ();
+               if (opt_sets.Count == 0) {
+                       foreach (string s in tests)
+                               test_info.Add (new TestInfo { test = s });
+               } else {
+                       foreach (string opt in opt_sets) {
+                               foreach (string s in tests)
+                                       test_info.Add (new TestInfo { test = s, opt_set = opt });
+                       }
+               }               
+
+               foreach (TestInfo ti in test_info) {
                        lock (monitor) {
                                while (processes.Count == concurrency) {
                                        /* Wait for one process to terminate */
@@ -142,11 +166,19 @@ public class TestRunner
                                terminated.Clear ();
                        }
 
+                       string test = ti.test;
+                       string opt_set = ti.opt_set;
+
                        if (concurrency == 1)
                                Console.Write ("Testing " + test + "... ");
 
                        /* Spawn a new process */
-                       ProcessStartInfo info = new ProcessStartInfo (runtime, test);
+                       string process_args;
+                       if (opt_set == null)
+                               process_args = test;
+                       else
+                               process_args = "-O=" + opt_set + " " + test;
+                       ProcessStartInfo info = new ProcessStartInfo (runtime, process_args);
                        info.UseShellExecute = false;
                        info.RedirectStandardOutput = true;
                        info.RedirectStandardError = true;
@@ -183,9 +215,13 @@ public class TestRunner
                                }
                        };
 
-                       data.stdout = new StreamWriter (new FileStream (test + ".stdout", FileMode.Create));
+                       string log_prefix = "";
+                       if (opt_set != null)
+                               log_prefix = "." + opt_set.Replace ("-", "no").Replace (",", "_");
+
+                       data.stdout = new StreamWriter (new FileStream (test + log_prefix + ".stdout", FileMode.Create));
 
-                       data.stderr = new StreamWriter (new FileStream (test + ".stderr", FileMode.Create));
+                       data.stderr = new StreamWriter (new FileStream (test + log_prefix + ".stderr", FileMode.Create));
 
                        p.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) {
                                Process p2 = (Process)sender;
index 15f9a06122ef23c27bbcb52fc3586e8c2a458a6b..f24213abffd027a7458c454dc748528a44c7e9a8 100644 (file)
@@ -1,3 +1,28 @@
+2010-04-09 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * valid_switch_with_value_on_stack.il: New test.
+
+2010-04-09 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       valid_call_to_virtual_method_on_sealed_class.il: New test.
+
+2010-04-07 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * valid_store_of_uint_to_int_array.il: Regression test
+       for #555950.
+
+2010-04-05 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * unverifiable_ginst_dont_reduce_to_gparam_with_constraint.il: Regression test
+       for #587849.
+
+2010-03-26 Rodrigo Kumpera  <rkumpera@novell.com>
+
+       * invalid_branch_in_between_prefix_and_instruction.il:
+       * invalid_empty_filter_block.il:
+       * make_endfilter_test.sh
+       * make_endfinally_test.sh: Silence which when gsed is not found.
+
 2010-02-04 Rodrigo Kumpera  <rkumpera@novell.com>
 
        * make_endfilter_test.sh: Fix this test to not have a throw that make some of the
index 1585014571ae8e1d7463b7cfa9214a172efe22c6..008d485bedfb405f73a80212d3b7e52366041a33 100755 (executable)
@@ -1,7 +1,7 @@
 #! /bin/sh
 
 SED="sed"
-if [ `which gsed` ] ; then 
+if [ `which gsed 2> /dev/null` ] ; then 
        SED="gsed"
 fi
 
index ed06fb3bbdd69f1cb71fc095a2d8167749502a31..5f6c53871d23e30c76fc6d56b1b2bca5c6257267 100755 (executable)
@@ -1,6 +1,6 @@
 #! /bin/sh
 SED="sed"
-if [ `which gsed` ] ; then 
+if [ `which gsed 2> /dev/null` ] ; then 
        SED="gsed"
 fi
 
index db0fe8684cdf0f71cb87df3c072e11d0b221f416..1038536faec81afbff2663a6e7e665bf348965d9 100755 (executable)
@@ -1,7 +1,7 @@
 #! /bin/sh
 
 SED="sed"
-if [ `which gsed` ] ; then 
+if [ `which gsed 2> /dev/null` ] ; then 
        SED="gsed"
 fi
 
index 4d15bfd486ea77a7d682415b82544d6a330c6bd9..1bf078b35dd01625e2ca7b2c5a77be047a346a5e 100755 (executable)
@@ -1,7 +1,7 @@
 #! /bin/sh
 
 SED="sed"
-if [ `which gsed` ] ; then 
+if [ `which gsed 2> /dev/null` ] ; then 
        SED="gsed"
 fi
 
index ac0c82530f7870c4ee1f2601c2aa03734a104e81..78e6081721aeba8b433e93ff2503baad86ce33b5 100755 (executable)
@@ -1,7 +1,7 @@
 #! /bin/sh
 
 SED="sed"
-if [ `which gsed` ] ; then 
+if [ `which gsed 2> /dev/null` ] ; then 
        SED="gsed"
 fi
 
@@ -81,4 +81,4 @@ $SED -e "s/VALIDITY/${TEST_VALIDITY}/g" -e "s/TYPE1/${TEST_TYPE1}/g" -e "s/TYPE2
 
        ret
 }
-//EOF
\ No newline at end of file
+//EOF
index 7091c3d260b099c7f35e23bb1ddea1624aad4fb5..95caf85f89cd64a44ac7957edd81f5207ce55d03 100755 (executable)
@@ -1,7 +1,7 @@
 #! /bin/sh
 
 SED="sed"
-if [ `which gsed` ] ; then 
+if [ `which gsed 2> /dev/null` ] ; then 
        SED="gsed"
 fi
 
diff --git a/mono/tests/verifier/unverifiable_ginst_dont_reduce_to_gparam_with_constraint.il b/mono/tests/verifier/unverifiable_ginst_dont_reduce_to_gparam_with_constraint.il
new file mode 100644 (file)
index 0000000..34bc3f2
--- /dev/null
@@ -0,0 +1,151 @@
+.assembly extern mscorlib
+{
+  .ver 2:0:0:0
+  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
+}
+.assembly 'gtest-314'
+{
+  .custom instance void class [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::'.ctor'() =  (
+               01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78   // ....T..WrapNonEx
+               63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01       ) // ceptionThrows.
+
+  .hash algorithm 0x00008004
+  .ver  0:0:0:0
+}
+.module 'gtest-314.exe' // GUID = {EDD5A7C2-306C-4E1F-985D-43A143A3ED18}
+
+
+.namespace test
+{
+  .class public auto ansi beforefieldinit App
+       extends [mscorlib]System.Object
+  {
+    .method public hidebysig  specialname  rtspecialname 
+           instance default void '.ctor' ()  cil managed 
+    {
+        // Method begins at RVA 0x20ec
+       // Code size 7 (0x7)
+       .maxstack 8
+       IL_0000:  ldarg.0 
+       IL_0001:  call instance void object::'.ctor'()
+       IL_0006:  ret 
+    } // end of method App::.ctor
+
+    // method line 2
+    .method public static  hidebysig 
+           default void Main ()  cil managed 
+    {
+        // Method begins at RVA 0x20f4
+       .entrypoint
+       // Code size 20 (0x14)
+       .maxstack 3
+       .locals init (
+               class test.Blarg        V_0,
+               class test.Bla  V_1)
+       IL_0000:  newobj instance void class test.Blarg::'.ctor'()
+       IL_0005:  stloc.0 
+       IL_0006:  newobj instance void class test.Bla::'.ctor'()
+       IL_000b:  stloc.1 
+       IL_000c:  ldloc.0 
+       IL_000d:  ldloc.1 
+       IL_000e:  callvirt instance void class test.OtherClass`2<class test.Blarg, class test.Bla>::Test(!1)
+       IL_0013:  ret 
+    }
+  }
+}
+
+.namespace test
+{
+  .class private auto ansi beforefieldinit Bla
+       extends class test.ThisClass`2<class test.Bla,class test.Blarg>
+  {
+
+    // method line 3
+    .method public hidebysig  specialname  rtspecialname 
+           instance default void '.ctor' ()  cil managed 
+    {
+        // Method begins at RVA 0x2114
+       // Code size 7 (0x7)
+       .maxstack 8
+       IL_0000:  ldarg.0 
+       IL_0001:  call instance void class test.ThisClass`2<class test.Bla, class test.Blarg>::'.ctor'()
+       IL_0006:  ret 
+    } // end of method Bla::.ctor
+
+  } // end of class test.Bla
+}
+
+.namespace test
+{
+  .class private auto ansi beforefieldinit Blarg
+       extends class test.OtherClass`2<class test.Blarg,class test.Bla>
+  {
+
+    // method line 4
+    .method public hidebysig  specialname  rtspecialname 
+           instance default void '.ctor' ()  cil managed 
+    {
+        // Method begins at RVA 0x211c
+       // Code size 7 (0x7)
+       .maxstack 8
+       IL_0000:  ldarg.0 
+       IL_0001:  call instance void class test.OtherClass`2<class test.Blarg, class test.Bla>::'.ctor'()
+       IL_0006:  ret 
+    } // end of method Blarg::.ctor
+
+  } // end of class test.Blarg
+}
+
+.namespace test
+{
+  .class public auto ansi beforefieldinit ThisClass`2<(class test.ThisClass`2<!T, !O>) T,(class test.OtherClass`2<!O, !T>) O>
+       extends [mscorlib]System.Object
+  {
+    .field  assembly  int32 dummy
+
+    // method line 5
+    .method public hidebysig  specialname  rtspecialname 
+           instance default void '.ctor' ()  cil managed 
+    {
+        // Method begins at RVA 0x2124
+       // Code size 7 (0x7)
+       .maxstack 8
+       IL_0000:  ldarg.0 
+       IL_0001:  call instance void object::'.ctor'()
+       IL_0006:  ret 
+    } // end of method ThisClass`2::.ctor
+
+  } // end of class test.ThisClass`2
+}
+
+.namespace test
+{
+  .class public auto ansi beforefieldinit OtherClass`2<(class test.OtherClass`2<!O, !T>) O,(class test.ThisClass`2<!T, !O>) T>
+       extends [mscorlib]System.Object
+  {
+
+    // method line 6
+    .method public hidebysig  specialname  rtspecialname 
+           instance default void '.ctor' ()  cil managed 
+    {
+        // Method begins at RVA 0x212c
+       // Code size 7 (0x7)
+       .maxstack 8
+       IL_0000:  ldarg.0 
+       IL_0001:  call instance void object::'.ctor'()
+       IL_0006:  ret 
+    } // end of method OtherClass`2::.ctor
+
+    .method public hidebysig 
+           instance default void Test (!T tc)  cil managed 
+    {
+       .maxstack 8
+       IL_0000:  ldarg.1 
+       IL_0001:  ldc.i4.0
+       //XXX ThisClass`2<!1,!0> can't be reduced to T even thou T has a 'ThisClass`2<!1,!0>' constaint.
+       IL_0002:  stfld int32 class test.ThisClass`2<!1,!0>::dummy
+       IL_0007:  ret 
+    }
+  }
+}
+
diff --git a/mono/tests/verifier/valid_call_to_virtual_method_on_sealed_class.il b/mono/tests/verifier/valid_call_to_virtual_method_on_sealed_class.il
new file mode 100644 (file)
index 0000000..f860467
--- /dev/null
@@ -0,0 +1,26 @@
+.assembly extern mscorlib
+{
+  .ver 2:0:0:0
+  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
+}
+.assembly 'cast'
+{
+  .hash algorithm 0x00008004
+  .ver  0:0:0:0
+}
+.module cast.exe // GUID = {9CC094E7-72A4-43FA-B1DD-E936A7B60966}
+
+.class private auto ansi beforefieldinit X extends [mscorlib]System.Object
+{
+       .method private static hidebysig default void Main ()  cil managed 
+       {
+               .entrypoint
+
+               ldstr "test"
+               call instance int32 [mscorlib]System.String::GetHashCode()
+               pop
+               ret
+       }
+
+}
+
diff --git a/mono/tests/verifier/valid_store_of_uint_to_int_array.il b/mono/tests/verifier/valid_store_of_uint_to_int_array.il
new file mode 100644 (file)
index 0000000..00d9e31
--- /dev/null
@@ -0,0 +1,34 @@
+.assembly extern mscorlib
+{
+  .ver 2:0:0:0
+  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
+}
+.assembly 'array'
+{
+  .hash algorithm 0x00008004
+  .ver  0:0:0:0
+}
+.module array.exe // GUID = {8AA4DE74-4ADB-4A6F-A49C-C71D067F856F}
+
+
+.class private auto ansi beforefieldinit Driver extends [mscorlib]System.Object
+ {
+
+       .method private static  hidebysig default void Main ()  cil managed 
+       {
+               .entrypoint
+               .maxstack 2
+               .locals init (int32[]   V_0, unsigned int32[]   V_1)
+               ldc.i4.1 
+               newarr [mscorlib]System.Int32
+               stloc.0 
+               ldc.i4.1 
+               newarr [mscorlib]System.UInt32
+               stloc.1 
+               ldloc.1 
+               stloc.0 
+               ret 
+       }
+
+  }
+
diff --git a/mono/tests/verifier/valid_switch_with_value_on_stack.il b/mono/tests/verifier/valid_switch_with_value_on_stack.il
new file mode 100644 (file)
index 0000000..9b03152
--- /dev/null
@@ -0,0 +1,47 @@
+.assembly extern mscorlib
+{
+  .ver 2:0:0:0
+  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
+}
+.assembly 'cast'
+{
+  .hash algorithm 0x00008004
+  .ver  0:0:0:0
+}
+.module cast.exe
+
+.class private auto ansi beforefieldinit Driver
+{
+       .method static default void Test ()  cil managed 
+       {
+               ret
+       }
+
+
+       .method private static hidebysig default void Main ()  cil managed 
+       {
+               .entrypoint
+
+               ldc.i4.1
+               ldc.i4.1
+               switch (LB_1)
+
+               ldc.i4.1
+               nop
+               br.s LB_2
+
+LB_1:
+               ldc.i4.2
+               nop
+
+LB_2:
+               pop
+               pop
+               nop
+
+               ret
+       }
+
+
+}
+
index 0dfa4388090ae720e1911974dcbd62f145ccd677..38cc368dc285a6ff28ed525643a83aeab25150d9 100644 (file)
@@ -5,3 +5,4 @@
 /*.la
 /*.lo
 /*.o
+/TAGS
index 6b7ad8fd0ac8bfaae568289d8c2d923e8df4688a..2e1b6172641c1011a083ff062a995398b6404578 100644 (file)
@@ -1,3 +1,107 @@
+2010-04-23  Geoff Norton  <gnorton@novell.com>
+
+       * mono-sigcontext.h: Darwin x86_64 support.
+
+2010-04-09 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * mono-semaphore.c: account for the time already spent in wait if
+       interrupted.
+
+2010-04-09  Zoltan Varga  <vargaz@gmail.com>
+
+       * mono-time.c (get_boot_time): Applied more openbsd changes from Robert Nagy
+       <robert@openbsd.org>.
+
+2010-04-09  Zoltan Varga  <vargaz@gmail.com>
+
+       * mono-proclib.c: Applied more openbsd changes from Robert Nagy
+       <robert@openbsd.org>.
+
+2010-04-08 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * mono-semaphore.c: set EINTR on windows too.
+
+2010-04-01 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * mono-semaphore.c: patch from Robert Nagy that makes this work in
+       OpenBSD.
+
+2010-04-01 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * mono-semaphore.[ch]: wait can be alertable now. Defaults to FALSE.
+
+2010-04-01  Sebastien Pouliot  <sebastien@ximian.com>
+
+       * mono-logger.c, mono-logger-internal.h: Add a new "security"
+       category to logging infrastructure.
+
+2010-03-31  Miguel de Icaza  <miguel@novell.com>
+
+       * mono-semaphore.h: Use Windows semaphores on Windows, patch
+       contributed by Vincent Povirk from bugzilla #531767
+
+2010-03-31  Miguel de Icaza  <miguel@novell.com>
+
+       * mono-hash.c (test_prime): Remove warnings
+
+2010-03-27  Zoltan Varga  <vargaz@gmail.com>
+
+       * mono-ehash.c: Rename this to mono-hash.c.
+
+2010-03-26  Zoltan Varga  <vargaz@gmail.com>
+
+       * mono-ehash.c (rehash): Avoid function calls as macro arguments.
+
+Fri Mar 26 19:44:40 CET 2010 Paolo Molaro <lupus@ximian.com>
+
+       * Makefile.am, mono-hash.c: removed mono-hash.c, since now
+       mono-ehash.c is GC-aware it doesn't make sense to keep two
+       implementations.
+
+2010-03-26  Mark Probst  <mark.probst@gmail.com>
+
+       * mono-semaphore.h (MONO_SEM_POST): Fix on Darwin.
+
+2010-03-26  Zoltan Varga  <vargaz@gmail.com>
+
+       * mono-proclib.c mono-semaphore.c: Apply some openbsd changes from openbsd
+       ports.
+
+2010-03-25 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * mono-semaphore.[hc]: make sure the semaphore calls are restarted if
+       interrupted. Return 0 on success and -1 on failure on windows.
+
+2010-03-25  Mark Probst  <mark.probst@gmail.com>
+
+       * mono-hash.c, mono-ehash.c: Fix rehashing with regard to moving
+       GC.  Register root for ehash.
+
+2010-03-24  Andrés G. Aragoneses  <knocte@gmail.com>
+
+       * mono-dl.c: (mono_dl_build_path) Take in account the suffix
+       variable assigned wrt the prefix comparison to concat the final
+       path for dlopen. Fixes BNC#588143. r:vargaz
+
+2010-03-23 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * mono-semaphore.h: MONO_SEM_WAIT() return value inverted when using
+       the windows API.
+       * mono-semaphore.c: handle INFINITE timeout.
+
+2010-03-22  Zoltan Varga  <vargaz@gmail.com>
+
+       * mono-sigcontext.h: Define UCONTEXT accessors for openbsd/amd64.
+
+2010-03-22  Zoltan Varga  <vargaz@gmail.com>
+
+       * mono-sigcontext.h: Applied patch from Robert Nagy (Robert@openbsd.org).
+       Add OpenBSD definitions.
+
+2010-03-17 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * mono-semaphore.c: _timedwait takes an absolute time.
+
 2010-03-04  Zoltan Varga  <vargaz@gmail.com>
 
        * strtod.c: Get rid of locking so this works with eglib.
index 32976d3649a8ffcdf89bb856a6029850e4e2d4a2..528876f4a717636db68c0202cd940094702c7a76 100644 (file)
@@ -11,14 +11,8 @@ mono-dtrace.h: $(top_srcdir)/data/mono.d
 
 endif
 
-if EGLIB_BUILD 
-hash_sources = mono-ehash.c
-else
-hash_sources = mono-hash.c
-endif
-
 libmonoutils_la_SOURCES = \
-       $(hash_sources)         \
+       mono-hash.c             \
        mono-md5.c              \
        mono-sha1.c             \
        mono-logger.c           \
@@ -92,4 +86,4 @@ libmonoutilsinclude_HEADERS = \
        mono-logger.h   \
        mono-publib.h
 
-EXTRA_DIST = ChangeLog mono-hash.c mono-hash.h mono-ehash.c
+EXTRA_DIST = ChangeLog
index 7b68e7aee24d4a4e4a70e108a9ff3b7ac4eb4e6f..9d45ddfc4982de1ad0e2ddc30f36f1d1ab2db0f6 100644 (file)
@@ -453,9 +453,9 @@ mono_dl_build_path (const char *directory, const char *name, void **iter)
        else
                suffix = suffixes [idx];
        if (directory && *directory)
-               res = g_strconcat (directory, G_DIR_SEPARATOR_S, prefix, name, suffixes [idx], NULL);
+               res = g_strconcat (directory, G_DIR_SEPARATOR_S, prefix, name, suffix, NULL);
        else
-               res = g_strconcat (prefix, name, suffixes [idx], NULL);
+               res = g_strconcat (prefix, name, suffix, NULL);
        ++idx;
        *iter = GUINT_TO_POINTER (idx);
        return res;
diff --git a/mono/utils/mono-ehash.c b/mono/utils/mono-ehash.c
deleted file mode 100644 (file)
index 1e6370c..0000000
+++ /dev/null
@@ -1,408 +0,0 @@
-/*
- * ghashtable.c: Hashtable implementation
- *
- * Author:
- *   Miguel de Icaza (miguel@novell.com)
- *
- * (C) 2006 Novell, Inc.
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- * "Software"), to deal in the Software without restriction, including
- * without limitation the rights to use, copy, modify, merge, publish,
- * distribute, sublicense, and/or sell copies of the Software, and to
- * permit persons to whom the Software is furnished to do so, subject to
- * the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
- * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-#include <config.h>
-#include <stdio.h>
-#include <math.h>
-#include <glib.h>
-#include "mono-hash.h"
-#include "metadata/gc-internal.h"
-
-#ifdef HAVE_BOEHM_GC
-#define mg_new0(type,n)  ((type *) GC_MALLOC(sizeof(type) * (n)))
-#define mg_new(type,n)   ((type *) GC_MALLOC(sizeof(type) * (n)))
-#define mg_free(x)       do { } while (0)
-#else
-#define mg_new0(x,n)     g_new0(x,n)
-#define mg_new(type,n)   g_new(type,n)
-#define mg_free(x)       g_free(x)
-#endif
-
-typedef struct _Slot Slot;
-
-struct _Slot {
-       gpointer key;
-       gpointer value;
-       Slot    *next;
-};
-
-static gpointer KEYMARKER_REMOVED = &KEYMARKER_REMOVED;
-
-struct _MonoGHashTable {
-       GHashFunc      hash_func;
-       GEqualFunc     key_equal_func;
-
-       Slot **table;
-       int   table_size;
-       int   in_use;
-       int   threshold;
-       int   last_rehash;
-       GDestroyNotify value_destroy_func, key_destroy_func;
-       MonoGHashGCType gc_type;
-};
-
-static const int prime_tbl[] = {
-       11, 19, 37, 73, 109, 163, 251, 367, 557, 823, 1237,
-       1861, 2777, 4177, 6247, 9371, 14057, 21089, 31627,
-       47431, 71143, 106721, 160073, 240101, 360163,
-       540217, 810343, 1215497, 1823231, 2734867, 4102283,
-       6153409, 9230113, 13845163
-};
-
-static gboolean
-test_prime (int x)
-{
-       if ((x & 1) != 0) {
-               int n;
-               for (n = 3; n< (int)sqrt (x); n += 2) {
-                       if ((x % n) == 0)
-                               return FALSE;
-               }
-               return TRUE;
-       }
-       // There is only one even prime - 2.
-       return (x == 2);
-}
-
-static int
-calc_prime (int x)
-{
-       int i;
-       
-       for (i = (x & (~1))-1; i< G_MAXINT32; i += 2) {
-               if (test_prime (i))
-                       return i;
-       }
-       return x;
-}
-
-MonoGHashTable *
-mono_g_hash_table_new_type (GHashFunc hash_func, GEqualFunc key_equal_func, MonoGHashGCType type)
-{
-       MonoGHashTable *hash = mono_g_hash_table_new (hash_func, key_equal_func);
-
-       hash->gc_type = type;
-       
-       return hash;
-}
-
-MonoGHashTable *
-mono_g_hash_table_new (GHashFunc hash_func, GEqualFunc key_equal_func)
-{
-       MonoGHashTable *hash;
-
-       if (hash_func == NULL)
-               hash_func = g_direct_hash;
-       if (key_equal_func == NULL)
-               key_equal_func = g_direct_equal;
-       hash = mg_new0 (MonoGHashTable, 1);
-
-       hash->hash_func = hash_func;
-       hash->key_equal_func = key_equal_func;
-
-       hash->table_size = g_spaced_primes_closest (1);
-       hash->table = mg_new0 (Slot *, hash->table_size);
-       hash->last_rehash = hash->table_size;
-       
-       return hash;
-}
-
-MonoGHashTable *
-mono_g_hash_table_new_full (GHashFunc hash_func, GEqualFunc key_equal_func,
-                           GDestroyNotify key_destroy_func, GDestroyNotify value_destroy_func)
-{
-       MonoGHashTable *hash = mono_g_hash_table_new (hash_func, key_equal_func);
-       if (hash == NULL)
-               return NULL;
-       
-       hash->key_destroy_func = key_destroy_func;
-       hash->value_destroy_func = value_destroy_func;
-       
-       return hash;
-}
-
-static void
-do_rehash (MonoGHashTable *hash)
-{
-       int current_size, i;
-       Slot **table;
-
-       /* printf ("Resizing diff=%d slots=%d\n", hash->in_use - hash->last_rehash, hash->table_size); */
-       hash->last_rehash = hash->table_size;
-       current_size = hash->table_size;
-       hash->table_size = g_spaced_primes_closest (hash->in_use);
-       /* printf ("New size: %d\n", hash->table_size); */
-       table = hash->table;
-       hash->table = mg_new0 (Slot *, hash->table_size);
-       
-       for (i = 0; i < current_size; i++){
-               Slot *s, *next;
-
-               for (s = table [i]; s != NULL; s = next){
-                       guint hashcode = ((*hash->hash_func) (s->key)) % hash->table_size;
-                       next = s->next;
-
-                       s->next = hash->table [hashcode];
-                       hash->table [hashcode] = s;
-               }
-       }
-       mg_free (table);
-}
-
-static void
-rehash (MonoGHashTable *hash)
-{
-       int diff = ABS (hash->last_rehash - hash->in_use);
-
-       /* These are the factors to play with to change the rehashing strategy */
-       /* I played with them with a large range, and could not really get */
-       /* something that was too good, maybe the tests are not that great */
-       if (!(diff * 0.75 > hash->table_size * 2))
-               return;
-       do_rehash (hash);
-}
-
-guint
-mono_g_hash_table_size (MonoGHashTable *hash)
-{
-       g_return_val_if_fail (hash != NULL, 0);
-       
-       return hash->in_use;
-}
-
-gpointer
-mono_g_hash_table_lookup (MonoGHashTable *hash, gconstpointer key)
-{
-       gpointer orig_key, value;
-       
-       if (mono_g_hash_table_lookup_extended (hash, key, &orig_key, &value))
-               return value;
-       else
-               return NULL;
-}
-
-gboolean
-mono_g_hash_table_lookup_extended (MonoGHashTable *hash, gconstpointer key, gpointer *orig_key, gpointer *value)
-{
-       GEqualFunc equal;
-       Slot *s;
-       guint hashcode;
-       
-       g_return_val_if_fail (hash != NULL, FALSE);
-       equal = hash->key_equal_func;
-
-       hashcode = ((*hash->hash_func) (key)) % hash->table_size;
-       
-       for (s = hash->table [hashcode]; s != NULL; s = s->next){
-               if ((*equal)(s->key, key)){
-                       *orig_key = s->key;
-                       *value = s->value;
-                       return TRUE;
-               }
-       }
-       return FALSE;
-}
-
-void
-mono_g_hash_table_foreach (MonoGHashTable *hash, GHFunc func, gpointer user_data)
-{
-       int i;
-       
-       g_return_if_fail (hash != NULL);
-       g_return_if_fail (func != NULL);
-
-       for (i = 0; i < hash->table_size; i++){
-               Slot *s;
-
-               for (s = hash->table [i]; s != NULL; s = s->next)
-                       (*func)(s->key, s->value, user_data);
-       }
-}
-
-gpointer
-mono_g_hash_table_find (MonoGHashTable *hash, GHRFunc predicate, gpointer user_data)
-{
-       int i;
-       
-       g_return_val_if_fail (hash != NULL, NULL);
-       g_return_val_if_fail (predicate != NULL, NULL);
-
-       for (i = 0; i < hash->table_size; i++){
-               Slot *s;
-
-               for (s = hash->table [i]; s != NULL; s = s->next)
-                       if ((*predicate)(s->key, s->value, user_data))
-                               return s->value;
-       }
-       return NULL;
-}
-
-gboolean
-mono_g_hash_table_remove (MonoGHashTable *hash, gconstpointer key)
-{
-       GEqualFunc equal;
-       Slot *s, *last;
-       guint hashcode;
-       
-       g_return_val_if_fail (hash != NULL, FALSE);
-       equal = hash->key_equal_func;
-
-       hashcode = ((*hash->hash_func)(key)) % hash->table_size;
-       last = NULL;
-       for (s = hash->table [hashcode]; s != NULL; s = s->next){
-               if ((*equal)(s->key, key)){
-                       if (hash->key_destroy_func != NULL)
-                               (*hash->key_destroy_func)(s->key);
-                       if (hash->value_destroy_func != NULL)
-                               (*hash->value_destroy_func)(s->value);
-                       if (last == NULL)
-                               hash->table [hashcode] = s->next;
-                       else
-                               last->next = s->next;
-                       mg_free (s);
-                       hash->in_use--;
-                       return TRUE;
-               }
-               last = s;
-       }
-       return FALSE;
-}
-
-guint
-mono_g_hash_table_foreach_remove (MonoGHashTable *hash, GHRFunc func, gpointer user_data)
-{
-       int i;
-       int count = 0;
-       
-       g_return_val_if_fail (hash != NULL, 0);
-       g_return_val_if_fail (func != NULL, 0);
-
-       for (i = 0; i < hash->table_size; i++){
-               Slot *s, *last;
-
-               last = NULL;
-               for (s = hash->table [i]; s != NULL; ){
-                       if ((*func)(s->key, s->value, user_data)){
-                               Slot *n;
-
-                               if (hash->key_destroy_func != NULL)
-                                       (*hash->key_destroy_func)(s->key);
-                               if (hash->value_destroy_func != NULL)
-                                       (*hash->value_destroy_func)(s->value);
-                               if (last == NULL){
-                                       hash->table [i] = s->next;
-                                       n = s->next;
-                               } else  {
-                                       last->next = s->next;
-                                       n = last->next;
-                               }
-                               mg_free (s);
-                               hash->in_use--;
-                               count++;
-                               s = n;
-                       } else {
-                               last = s;
-                               s = s->next;
-                       }
-               }
-       }
-       if (count > 0)
-               rehash (hash);
-       return count;
-}
-
-void
-mono_g_hash_table_destroy (MonoGHashTable *hash)
-{
-       int i;
-       
-       g_return_if_fail (hash != NULL);
-
-       for (i = 0; i < hash->table_size; i++){
-               Slot *s, *next;
-
-               for (s = hash->table [i]; s != NULL; s = next){
-                       next = s->next;
-                       
-                       if (hash->key_destroy_func != NULL)
-                               (*hash->key_destroy_func)(s->key);
-                       if (hash->value_destroy_func != NULL)
-                               (*hash->value_destroy_func)(s->value);
-                       mg_free (s);
-               }
-       }
-       mg_free (hash->table);
-       mg_free (hash);
-}
-
-void
-mono_g_hash_table_insert_replace (MonoGHashTable *hash, gpointer key, gpointer value, gboolean replace)
-{
-       guint hashcode;
-       Slot *s;
-       GEqualFunc equal;
-       
-       g_return_if_fail (hash != NULL);
-
-       equal = hash->key_equal_func;
-       if (hash->in_use >= hash->threshold)
-               rehash (hash);
-
-       hashcode = ((*hash->hash_func) (key)) % hash->table_size;
-       for (s = hash->table [hashcode]; s != NULL; s = s->next){
-               if ((*equal) (s->key, key)){
-                       if (replace){
-                               if (hash->key_destroy_func != NULL)
-                                       (*hash->key_destroy_func)(s->key);
-                               s->key = key;
-                       }
-                       if (hash->value_destroy_func != NULL)
-                               (*hash->value_destroy_func) (s->value);
-                       s->value = value;
-                       return;
-               }
-       }
-       s = mg_new (Slot, 1);
-       s->key = key;
-       s->value = value;
-       s->next = hash->table [hashcode];
-       hash->table [hashcode] = s;
-       hash->in_use++;
-}
-
-void
-mono_g_hash_table_insert (MonoGHashTable *h, gpointer k, gpointer v)
-{
-       mono_g_hash_table_insert_replace (h, k, v, FALSE);
-}
-
-void
-mono_g_hash_table_replace(MonoGHashTable *h, gpointer k, gpointer v)
-{
-       mono_g_hash_table_insert_replace (h, k, v, TRUE);
-}
-
index c6c947b9f2a72e38fb46165e4493669d20bd847d..84aac36dc8ccc98176d5e592681bd5dedc2e5d71 100644 (file)
-/* GLIB - Library of useful routines for C programming
- * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
+/*
+ * ghashtable.c: Hashtable implementation
  *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
+ * Author:
+ *   Miguel de Icaza (miguel@novell.com)
  *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.         See the GNU
- * Lesser General Public License for more details.
+ * (C) 2006 Novell, Inc.
  *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the
- * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- * Boston, MA 02111-1307, USA.
- */
-
-/*
- * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
- * file for a list of people on the GLib Team.  See the ChangeLog
- * files for a list of changes.  These files are distributed with
- * GLib at ftp://ftp.gtk.org/pub/gtk/. 
- */
-
-/* 
- * MT safe
- */
-
-/*
- * Imported in mono cvs from version 1.32 of gnome cvs.
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  */
-
-#ifdef HAVE_CONFIG_H
 #include <config.h>
-#endif
-
+#include <stdio.h>
+#include <math.h>
 #include <glib.h>
 #include "mono-hash.h"
 #include "metadata/gc-internal.h"
 
-#define HASH_TABLE_MIN_SIZE 11
-#define HASH_TABLE_MAX_SIZE 13845163
+#ifdef HAVE_BOEHM_GC
+#define mg_new0(type,n)  ((type *) GC_MALLOC(sizeof(type) * (n)))
+#define mg_new(type,n)   ((type *) GC_MALLOC(sizeof(type) * (n)))
+#define mg_free(x)       do { } while (0)
+#else
+#define mg_new0(x,n)     g_new0(x,n)
+#define mg_new(type,n)   g_new(type,n)
+#define mg_free(x)       g_free(x)
+#endif
 
-typedef struct _MonoGHashNode      MonoGHashNode;
+typedef struct _Slot Slot;
 
-struct _MonoGHashNode
-{
-  gpointer   key;
-  gpointer   value;
-  MonoGHashNode *next;
+struct _Slot {
+       gpointer key;
+       gpointer value;
+       Slot    *next;
 };
 
-struct _MonoGHashTable
-{
-  gint             size;
-  gint             nnodes;
-  MonoGHashNode      **nodes;
-  GHashFunc        hash_func;
-  GEqualFunc       key_equal_func;
-  GDestroyNotify   key_destroy_func;
-  GDestroyNotify   value_destroy_func;
-  MonoGHashGCType  gc_type;
+static gpointer KEYMARKER_REMOVED = &KEYMARKER_REMOVED;
+
+struct _MonoGHashTable {
+       GHashFunc      hash_func;
+       GEqualFunc     key_equal_func;
+
+       Slot **table;
+       int   table_size;
+       int   in_use;
+       int   threshold;
+       int   last_rehash;
+       GDestroyNotify value_destroy_func, key_destroy_func;
+       MonoGHashGCType gc_type;
 };
 
-#define G_HASH_TABLE_RESIZE(hash_table)                                \
-   G_STMT_START {                                              \
-     if ((hash_table->size >= 3 * hash_table->nnodes &&                \
-         hash_table->size > HASH_TABLE_MIN_SIZE) ||            \
-        (3 * hash_table->size <= hash_table->nnodes &&         \
-         hash_table->size < HASH_TABLE_MAX_SIZE))              \
-          g_hash_table_resize (hash_table);                    \
-   } G_STMT_END
-
-static void            g_hash_table_resize       (MonoGHashTable         *hash_table);
-static MonoGHashNode** g_hash_table_lookup_node  (MonoGHashTable     *hash_table,
-                                                   gconstpointer   key);
-static MonoGHashNode*  g_hash_node_new           (gint            gc_type);
-static void            g_hash_node_destroy       (MonoGHashNode          *hash_node,
-                                                  MonoGHashGCType type,
-                                                   GDestroyNotify  key_destroy_func,
-                                                   GDestroyNotify  value_destroy_func);
-static void            g_hash_nodes_destroy      (MonoGHashNode          *hash_node,
-                                                  MonoGHashGCType type,
-                                                 GDestroyNotify   key_destroy_func,
-                                                 GDestroyNotify   value_destroy_func);
-static guint g_hash_table_foreach_remove_or_steal (MonoGHashTable     *hash_table,
-                                                   GHRFunc        func,
-                                                   gpointer       user_data,
-                                                   gboolean        notify);
+static const int prime_tbl[] = {
+       11, 19, 37, 73, 109, 163, 251, 367, 557, 823, 1237,
+       1861, 2777, 4177, 6247, 9371, 14057, 21089, 31627,
+       47431, 71143, 106721, 160073, 240101, 360163,
+       540217, 810343, 1215497, 1823231, 2734867, 4102283,
+       6153409, 9230113, 13845163
+};
 
 #ifdef HAVE_SGEN_GC
-static void mono_g_hash_mark (void *addr, MonoGCCopyFunc mark_func);
-#endif
+static void *table_hash_descr = NULL;
 
-G_LOCK_DEFINE_STATIC (g_hash_global);
+static void mono_g_hash_mark (void *addr, MonoGCMarkFunc mark_func);
 
-#if defined(HAVE_NULL_GC)
-static GMemChunk *node_mem_chunk = NULL;
-static MonoGHashNode *node_free_list = NULL;
-#elif defined(HAVE_SGEN_GC)
-static MonoGHashNode *node_free_lists [4] = {NULL};
-static void *hash_descr = NULL;
-static GMemChunk *node_mem_chunk = NULL;
-#else
-static void *node_gc_descs [4] = {NULL};
-static MonoGHashNode *node_free_lists [4] = {NULL};
-#endif
-
-#define SET_NODE_KEY(node, gc_type, val) do { (node)->key = (val); } while (0)
-#define SET_NODE_VALUE(node, gc_type, val) do { (node)->value = (val); } while (0)
-
-/**
- * g_hash_table_new:
- * @hash_func: a function to create a hash value from a key.
- *   Hash values are used to determine where keys are stored within the
- *   #GHashTable data structure. The g_direct_hash(), g_int_hash() and 
- *   g_str_hash() functions are provided for some common types of keys. 
- *   If hash_func is %NULL, g_direct_hash() is used.
- * @key_equal_func: a function to check two keys for equality.  This is
- *   used when looking up keys in the #GHashTable.  The g_direct_equal(),
- *   g_int_equal() and g_str_equal() functions are provided for the most
- *   common types of keys. If @key_equal_func is %NULL, keys are compared
- *   directly in a similar fashion to g_direct_equal(), but without the
- *   overhead of a function call.
- *
- * Creates a new #GHashTable.
- * 
- * Return value: a new #GHashTable.
- **/
-MonoGHashTable*
-mono_g_hash_table_new (GHashFunc    hash_func,
-                 GEqualFunc   key_equal_func)
+static Slot*
+new_slot (MonoGHashTable *hash)
 {
-  return mono_g_hash_table_new_full (hash_func, key_equal_func, NULL, NULL);
+       if (hash->gc_type == MONO_HASH_CONSERVATIVE_GC)
+               return mono_gc_alloc_fixed (sizeof (Slot), NULL);
+       else
+               return mg_new (Slot, 1);
 }
 
-MonoGHashTable*
-mono_g_hash_table_new_type (GHashFunc    hash_func,
-                 GEqualFunc   key_equal_func,
-                 MonoGHashGCType type)
+static void
+free_slot (MonoGHashTable *hash, Slot *slot)
 {
-  MonoGHashTable *table = mono_g_hash_table_new_full (hash_func, key_equal_func, NULL, NULL);
-  if (type == MONO_HASH_KEY_GC || type == MONO_HASH_KEY_VALUE_GC)
-         g_assert (hash_func);
-  table->gc_type = type;
-#if defined(HAVE_SGEN_GC)
-  if (type < 0 || type > MONO_HASH_KEY_VALUE_GC)
-         g_error ("wrong type for gc hashtable");
-  /* 
-   * We use a user defined marking function to avoid having to register a GC root for
-   * each hash node.
-   */
-  if (!hash_descr)
-         hash_descr = mono_gc_make_root_descr_user (mono_g_hash_mark);
-  if (type != MONO_HASH_CONSERVATIVE_GC)
-         mono_gc_register_root_wbarrier ((char*)table, sizeof (MonoGHashTable), hash_descr);
-#elif defined(HAVE_BOEHM_GC)
-  if (type < 0 || type > MONO_HASH_KEY_VALUE_GC)
-         g_error ("wrong type for gc hashtable");
-  if (!node_gc_descs [type] && type > MONO_HASH_CONSERVATIVE_GC) {
-         gsize bmap = 0;
-         if (type & MONO_HASH_KEY_GC)
-                 bmap |= 1; /* the first field in the node is the key */
-         if (type & MONO_HASH_VALUE_GC)
-                 bmap |= 2; /* the second is the value */
-         bmap |= 4; /* next */
-         node_gc_descs [type] = mono_gc_make_descr_from_bitmap (&bmap, 3);
-
-         MONO_GC_REGISTER_ROOT (node_free_lists [type]);
-  }
-#endif
-  return table;
+       if (hash->gc_type == MONO_HASH_CONSERVATIVE_GC)
+               mono_gc_free_fixed (slot);
+       else
+               mg_free (slot);
 }
-
-
-
-/**
- * g_hash_table_new_full:
- * @hash_func: a function to create a hash value from a key.
- * @key_equal_func: a function to check two keys for equality.
- * @key_destroy_func: a function to free the memory allocated for the key 
- *   used when removing the entry from the #GHashTable or %NULL if you 
- *   don't want to supply such a function.
- * @value_destroy_func: a function to free the memory allocated for the 
- *   value used when removing the entry from the #GHashTable or %NULL if 
- *   you don't want to supply such a function.
- * 
- * Creates a new #GHashTable like g_hash_table_new() and allows to specify
- * functions to free the memory allocated for the key and value that get 
- * called when removing the entry from the #GHashTable.
- * 
- * Return value: a new #GHashTable.
- **/
-MonoGHashTable*
-mono_g_hash_table_new_full (GHashFunc       hash_func,
-                      GEqualFunc      key_equal_func,
-                      GDestroyNotify  key_destroy_func,
-                      GDestroyNotify  value_destroy_func)
-{
-  MonoGHashTable *hash_table;
-#if HAVE_BOEHM_GC
-  static gboolean inited = FALSE;
-  if (!inited) {
-         MONO_GC_REGISTER_ROOT (node_free_lists [0]);
-         inited = TRUE;
-  }
-  
-  hash_table = GC_MALLOC (sizeof (MonoGHashTable));
-#else
-  hash_table = g_new (MonoGHashTable, 1);
-#endif
-  hash_table->size               = HASH_TABLE_MIN_SIZE;
-  hash_table->nnodes             = 0;
-  hash_table->hash_func          = hash_func ? hash_func : g_direct_hash;
-  hash_table->key_equal_func     = key_equal_func == g_direct_equal ? NULL : key_equal_func;
-  hash_table->key_destroy_func   = key_destroy_func;
-  hash_table->value_destroy_func = value_destroy_func;
-#if HAVE_BOEHM_GC
-  hash_table->nodes              = GC_MALLOC (sizeof (MonoGHashNode*) * hash_table->size);
 #else
-  hash_table->nodes              = g_new0 (MonoGHashNode*, hash_table->size);
+#define new_slot(h)    mg_new(Slot,1)
+#define free_slot(h,s) mg_free((s))
 #endif
-  hash_table->gc_type            = 0;
-  
-  return hash_table;
-}
 
-/**
- * g_hash_table_destroy:
- * @hash_table: a #GHashTable.
- * 
- * Destroys the #GHashTable. If keys and/or values are dynamically 
- * allocated, you should either free them first or create the #GHashTable
- * using g_hash_table_new_full(). In the latter case the destroy functions 
- * you supplied will be called on all keys and values before destroying 
- * the #GHashTable.
- **/
-void
-mono_g_hash_table_destroy (MonoGHashTable *hash_table)
+#if UNUSED
+static gboolean
+test_prime (int x)
 {
-  guint i;
-  
-  g_return_if_fail (hash_table != NULL);
-  
-  for (i = 0; i < hash_table->size; i++)
-    g_hash_nodes_destroy (hash_table->nodes[i], hash_table->gc_type,
-                         hash_table->key_destroy_func,
-                         hash_table->value_destroy_func);
-
-#if HAVE_BOEHM_GC
-#else
-#if HAVE_SGEN_GC
-  mono_gc_deregister_root ((char*)hash_table);
-#endif
-  g_free (hash_table->nodes);
-  g_free (hash_table);
-#endif
+       if ((x & 1) != 0) {
+               int n;
+               for (n = 3; n< (int)sqrt (x); n += 2) {
+                       if ((x % n) == 0)
+                               return FALSE;
+               }
+               return TRUE;
+       }
+       // There is only one even prime - 2.
+       return (x == 2);
 }
 
-static inline MonoGHashNode**
-g_hash_table_lookup_node (MonoGHashTable       *hash_table,
-                         gconstpointer  key)
+static int
+calc_prime (int x)
 {
-  MonoGHashNode **node;
-  
-  node = &hash_table->nodes
-    [(* hash_table->hash_func) (key) % hash_table->size];
-  
-  /* Hash table lookup needs to be fast.
-   *  We therefore remove the extra conditional of testing
-   *  whether to call the key_equal_func or not from
-   *  the inner loop.
-   */
-  if (hash_table->key_equal_func)
-    while (*node && !(*hash_table->key_equal_func) ((*node)->key, key))
-      node = &(*node)->next;
-  else
-    while (*node && (*node)->key != key)
-      node = &(*node)->next;
-  
-  return node;
+       int i;
+       
+       for (i = (x & (~1))-1; i< G_MAXINT32; i += 2) {
+               if (test_prime (i))
+                       return i;
+       }
+       return x;
 }
+#endif
 
-/**
- * g_hash_table_lookup:
- * @hash_table: a #GHashTable.
- * @key: the key to look up.
- * 
- * Looks up a key in a #GHashTable.
- * 
- * Return value: the associated value, or %NULL if the key is not found.
- **/
-gpointer
-mono_g_hash_table_lookup (MonoGHashTable         *hash_table,
-                    gconstpointer key)
+MonoGHashTable *
+mono_g_hash_table_new_type (GHashFunc hash_func, GEqualFunc key_equal_func, MonoGHashGCType type)
 {
-  MonoGHashNode *node;
-  
-  g_return_val_if_fail (hash_table != NULL, NULL);
-  
-  node = *g_hash_table_lookup_node (hash_table, key);
-  
-  return node ? node->value : NULL;
-}
+       MonoGHashTable *hash = mono_g_hash_table_new (hash_func, key_equal_func);
 
-/**
- * g_hash_table_lookup_extended:
- * @hash_table: a #GHashTable.
- * @lookup_key: the key to look up.
- * @orig_key: returns the original key.
- * @value: returns the value associated with the key.
- * 
- * Looks up a key in the #GHashTable, returning the original key and the
- * associated value and a #gboolean which is %TRUE if the key was found. This 
- * is useful if you need to free the memory allocated for the original key, 
- * for example before calling g_hash_table_remove().
- * 
- * Return value: %TRUE if the key was found in the #GHashTable.
- **/
-gboolean
-mono_g_hash_table_lookup_extended (MonoGHashTable    *hash_table,
-                             gconstpointer  lookup_key,
-                             gpointer      *orig_key,
-                             gpointer      *value)
-{
-  MonoGHashNode *node;
-  
-  g_return_val_if_fail (hash_table != NULL, FALSE);
-  
-  node = *g_hash_table_lookup_node (hash_table, lookup_key);
-  
-  if (node)
-    {
-      if (orig_key)
-       *orig_key = node->key;
-      if (value)
-       *value = node->value;
-      return TRUE;
-    }
-  else
-    return FALSE;
-}
+       hash->gc_type = type;
 
-static inline MonoGHashNode*
-g_hash_node_new (gint gc_type)
-{
-  MonoGHashNode *hash_node = NULL;
-
-#if HAVE_BOEHM_GC
-  if (node_free_lists [gc_type]) {
-         G_LOCK (g_hash_global);
-
-         if (node_free_lists [gc_type]) {
-                 hash_node = node_free_lists [gc_type];
-                 node_free_lists [gc_type] = node_free_lists [gc_type]->next;
-         }
-         G_UNLOCK (g_hash_global);
-  }
-  if (!hash_node) {
-         if (gc_type != MONO_HASH_CONSERVATIVE_GC) {
-                 //hash_node = GC_MALLOC (sizeof (MonoGHashNode));
-                 hash_node = GC_MALLOC_EXPLICITLY_TYPED (sizeof (MonoGHashNode), (GC_descr)node_gc_descs [gc_type]);
-         } else {
-                 hash_node = GC_MALLOC (sizeof (MonoGHashNode));
-         }
-  }
-#elif defined(HAVE_SGEN_GC)
-  if (node_free_lists [gc_type]) {
-         G_LOCK (g_hash_global);
-
-         if (node_free_lists [gc_type]) {
-                 hash_node = node_free_lists [gc_type];
-                 node_free_lists [gc_type] = node_free_lists [gc_type]->next;
-         }
-         G_UNLOCK (g_hash_global);
-  }
-  if (!hash_node) {
-         if (gc_type != MONO_HASH_CONSERVATIVE_GC) {
-                 /* 
-                  * Marking is handled by the marker function, no need to allocate GC visible
-                  * memory.
-                  */
-                 if (!node_mem_chunk)
-                         node_mem_chunk = g_mem_chunk_new ("hash node mem chunk",
-                                                                                               sizeof (MonoGHashNode),
-                                                                                               1024, G_ALLOC_ONLY);
-                 hash_node = g_chunk_new (MonoGHashNode, node_mem_chunk);
-         } else {
-                 hash_node = mono_gc_alloc_fixed (sizeof (MonoGHashNode), NULL);
-         }
-  }
-#else
-#ifdef _EGLIB_MAJOR
-  G_LOCK (g_hash_global);
-  if (node_free_list)
-    {
-      hash_node = node_free_list;
-      node_free_list = node_free_list->next;
-    }
-  else
-    {
-      hash_node = g_new0 (MonoGHashNode, 1);
-    }
-  G_UNLOCK (g_hash_global);
-#else
-  G_LOCK (g_hash_global);
-  if (node_free_list)
-    {
-      hash_node = node_free_list;
-      node_free_list = node_free_list->next;
-    }
-  else
-    {
-      if (!node_mem_chunk)
-       node_mem_chunk = g_mem_chunk_new ("hash node mem chunk",
-                                         sizeof (MonoGHashNode),
-                                         1024, G_ALLOC_ONLY);
-      
-      hash_node = g_chunk_new (MonoGHashNode, node_mem_chunk);
-    }
-  G_UNLOCK (g_hash_global);
-  #endif
+#ifdef HAVE_SGEN_GC
+       if (type < 0 || type > MONO_HASH_KEY_VALUE_GC)
+               g_error ("wrong type for gc hashtable");
+       /*
+        * We use a user defined marking function to avoid having to register a GC root for
+        * each hash node.
+        */
+       if (!table_hash_descr)
+               table_hash_descr = mono_gc_make_root_descr_user (mono_g_hash_mark);
+       if (type != MONO_HASH_CONSERVATIVE_GC)
+               mono_gc_register_root_wbarrier ((char*)hash, sizeof (MonoGHashTable), table_hash_descr);
 #endif
 
-  hash_node->key = NULL;
-  hash_node->value = NULL;
-  hash_node->next = NULL;
-  
-  return hash_node;
+       return hash;
 }
 
-/**
- * g_hash_table_insert:
- * @hash_table: a #GHashTable.
- * @key: a key to insert.
- * @value: the value to associate with the key.
- * 
- * Inserts a new key and value into a #GHashTable.
- * 
- * If the key already exists in the #GHashTable its current value is replaced
- * with the new value. If you supplied a @value_destroy_func when creating the 
- * #GHashTable, the old value is freed using that function. If you supplied
- * a @key_destroy_func when creating the #GHashTable, the passed key is freed 
- * using that function.
- **/
-void
-mono_g_hash_table_insert (MonoGHashTable *hash_table,
-                    gpointer    key,
-                    gpointer    value)
+MonoGHashTable *
+mono_g_hash_table_new (GHashFunc hash_func, GEqualFunc key_equal_func)
 {
-  MonoGHashNode **node;
-  
-  g_return_if_fail (hash_table != NULL);
-  
-  node = g_hash_table_lookup_node (hash_table, key);
-  
-  if (*node)
-    {
-      /* do not reset node->key in this place, keeping
-       * the old key is the intended behaviour. 
-       * g_hash_table_replace() can be used instead.
-       */
-
-      /* free the passed key */
-      if (hash_table->key_destroy_func)
-       hash_table->key_destroy_func (key);
-      
-      if (hash_table->value_destroy_func)
-       hash_table->value_destroy_func ((*node)->value);
-
-         SET_NODE_VALUE ((*node), hash_table->gc_type, value);
-    }
-  else
-    {
-           gint gc_type = hash_table->gc_type;
-           *node = g_hash_node_new (gc_type);
-           SET_NODE_KEY (*node, gc_type, key);
-           SET_NODE_VALUE (*node, gc_type, value);
-           hash_table->nnodes++;
-           G_HASH_TABLE_RESIZE (hash_table);
-    }
+       MonoGHashTable *hash;
+
+       if (hash_func == NULL)
+               hash_func = g_direct_hash;
+       if (key_equal_func == NULL)
+               key_equal_func = g_direct_equal;
+       hash = mg_new0 (MonoGHashTable, 1);
+
+       hash->hash_func = hash_func;
+       hash->key_equal_func = key_equal_func;
+
+       hash->table_size = g_spaced_primes_closest (1);
+       hash->table = mg_new0 (Slot *, hash->table_size);
+       hash->last_rehash = hash->table_size;
+       
+       return hash;
 }
 
-/**
- * g_hash_table_replace:
- * @hash_table: a #GHashTable.
- * @key: a key to insert.
- * @value: the value to associate with the key.
- * 
- * Inserts a new key and value into a #GHashTable similar to 
- * g_hash_table_insert(). The difference is that if the key already exists 
- * in the #GHashTable, it gets replaced by the new key. If you supplied a 
- * @value_destroy_func when creating the #GHashTable, the old value is freed 
- * using that function. If you supplied a @key_destroy_func when creating the 
- * #GHashTable, the old key is freed using that function. 
- **/
-void
-mono_g_hash_table_replace (MonoGHashTable *hash_table,
-                     gpointer    key,
-                     gpointer    value)
+MonoGHashTable *
+mono_g_hash_table_new_full (GHashFunc hash_func, GEqualFunc key_equal_func,
+                           GDestroyNotify key_destroy_func, GDestroyNotify value_destroy_func)
 {
-  MonoGHashNode **node;
-  
-  g_return_if_fail (hash_table != NULL);
-  
-  node = g_hash_table_lookup_node (hash_table, key);
-  
-  if (*node)
-    {
-      if (hash_table->key_destroy_func)
-       hash_table->key_destroy_func ((*node)->key);
-      
-      if (hash_table->value_destroy_func)
-       hash_table->value_destroy_func ((*node)->value);
-
-         SET_NODE_KEY ((*node), hash_table->gc_type, key);
-         SET_NODE_VALUE ((*node), hash_table->gc_type, value);
-    }
-  else
-    {
-           gint gc_type = hash_table->gc_type;
-           *node = g_hash_node_new (gc_type);
-           SET_NODE_KEY (*node, gc_type, key);
-           SET_NODE_VALUE (*node, gc_type, value);
-           hash_table->nnodes++;
-           G_HASH_TABLE_RESIZE (hash_table);
-    }
+       MonoGHashTable *hash = mono_g_hash_table_new (hash_func, key_equal_func);
+       if (hash == NULL)
+               return NULL;
+       
+       hash->key_destroy_func = key_destroy_func;
+       hash->value_destroy_func = value_destroy_func;
+       
+       return hash;
 }
 
-/**
- * g_hash_table_remove:
- * @hash_table: a #GHashTable.
- * @key: the key to remove.
- * 
- * Removes a key and its associated value from a #GHashTable.
- *
- * If the #GHashTable was created using g_hash_table_new_full(), the
- * key and value are freed using the supplied destroy functions, otherwise
- * you have to make sure that any dynamically allocated values are freed 
- * yourself.
- * 
- * Return value: %TRUE if the key was found and removed from the #GHashTable.
- **/
-gboolean
-mono_g_hash_table_remove (MonoGHashTable          *hash_table,
-                    gconstpointer  key)
+typedef struct {
+       MonoGHashTable *hash;
+       int new_size;
+       Slot **table;
+} RehashData;
+
+static void*
+do_rehash (void *_data)
 {
-  MonoGHashNode **node, *dest;
-  
-  g_return_val_if_fail (hash_table != NULL, FALSE);
-  
-  node = g_hash_table_lookup_node (hash_table, key);
-  if (*node)
-    {
-      dest = *node;
-      (*node) = dest->next;
-      g_hash_node_destroy (dest, hash_table->gc_type,
-                          hash_table->key_destroy_func,
-                          hash_table->value_destroy_func);
-      hash_table->nnodes--;
-  
-      G_HASH_TABLE_RESIZE (hash_table);
-
-      return TRUE;
-    }
-
-  return FALSE;
+       RehashData *data = _data;
+       MonoGHashTable *hash = data->hash;
+       int current_size, i;
+       Slot **table;
+
+       /* printf ("Resizing diff=%d slots=%d\n", hash->in_use - hash->last_rehash, hash->table_size); */
+       hash->last_rehash = hash->table_size;
+       current_size = hash->table_size;
+       hash->table_size = data->new_size;
+       /* printf ("New size: %d\n", hash->table_size); */
+       table = hash->table;
+       hash->table = data->table;
+
+       for (i = 0; i < current_size; i++){
+               Slot *s, *next;
+
+               for (s = table [i]; s != NULL; s = next){
+                       guint hashcode = ((*hash->hash_func) (s->key)) % hash->table_size;
+                       next = s->next;
+
+                       s->next = hash->table [hashcode];
+                       hash->table [hashcode] = s;
+               }
+       }
+       return table;
 }
 
-/**
- * g_hash_table_steal:
- * @hash_table: a #GHashTable.
- * @key: the key to remove.
- * 
- * Removes a key and its associated value from a #GHashTable without
- * calling the key and value destroy functions.
- *
- * Return value: %TRUE if the key was found and removed from the #GHashTable.
- **/
-gboolean
-mono_g_hash_table_steal (MonoGHashTable    *hash_table,
-                    gconstpointer  key)
+static void
+rehash (MonoGHashTable *hash)
 {
-  MonoGHashNode **node, *dest;
-  
-  g_return_val_if_fail (hash_table != NULL, FALSE);
-  
-  node = g_hash_table_lookup_node (hash_table, key);
-  if (*node)
-    {
-      dest = *node;
-      (*node) = dest->next;
-      g_hash_node_destroy (dest, hash_table->gc_type, NULL, NULL);
-      hash_table->nnodes--;
-  
-      G_HASH_TABLE_RESIZE (hash_table);
-
-      return TRUE;
-    }
-
-  return FALSE;
+       int diff = ABS (hash->last_rehash - hash->in_use);
+       RehashData data;
+       void *old_table;
+
+       /* These are the factors to play with to change the rehashing strategy */
+       /* I played with them with a large range, and could not really get */
+       /* something that was too good, maybe the tests are not that great */
+       if (!(diff * 0.75 > hash->table_size * 2))
+               return;
+
+       data.hash = hash;
+       data.new_size = g_spaced_primes_closest (hash->in_use);
+       data.table = mg_new0 (Slot *, data.new_size);
+
+       old_table = mono_gc_invoke_with_gc_lock (do_rehash, &data);
+       mg_free (old_table);
 }
 
-/**
- * g_hash_table_foreach_remove:
- * @hash_table: a #GHashTable.
- * @func: the function to call for each key/value pair.
- * @user_data: user data to pass to the function.
- * 
- * Calls the given function for each key/value pair in the #GHashTable.
- * If the function returns %TRUE, then the key/value pair is removed from the
- * #GHashTable. If you supplied key or value destroy functions when creating
- * the #GHashTable, they are used to free the memory allocated for the removed
- * keys and values.
- * 
- * Return value: the number of key/value pairs removed.
- **/
 guint
-mono_g_hash_table_foreach_remove (MonoGHashTable       *hash_table,
-                            GHRFunc     func,
-                            gpointer    user_data)
+mono_g_hash_table_size (MonoGHashTable *hash)
 {
-  g_return_val_if_fail (hash_table != NULL, 0);
-  g_return_val_if_fail (func != NULL, 0);
-  
-  return g_hash_table_foreach_remove_or_steal (hash_table, func, user_data, TRUE);
+       g_return_val_if_fail (hash != NULL, 0);
+       
+       return hash->in_use;
 }
 
-/**
- * g_hash_table_foreach_steal:
- * @hash_table: a #GHashTable.
- * @func: the function to call for each key/value pair.
- * @user_data: user data to pass to the function.
- * 
- * Calls the given function for each key/value pair in the #GHashTable.
- * If the function returns %TRUE, then the key/value pair is removed from the
- * #GHashTable, but no key or value destroy functions are called.
- * 
- * Return value: the number of key/value pairs removed.
- **/
-guint
-mono_g_hash_table_foreach_steal (MonoGHashTable *hash_table,
-                            GHRFunc    func,
-                            gpointer   user_data)
+gpointer
+mono_g_hash_table_lookup (MonoGHashTable *hash, gconstpointer key)
 {
-  g_return_val_if_fail (hash_table != NULL, 0);
-  g_return_val_if_fail (func != NULL, 0);
-  
-  return g_hash_table_foreach_remove_or_steal (hash_table, func, user_data, FALSE);
+       gpointer orig_key, value;
+       
+       if (mono_g_hash_table_lookup_extended (hash, key, &orig_key, &value))
+               return value;
+       else
+               return NULL;
 }
 
-static guint
-g_hash_table_foreach_remove_or_steal (MonoGHashTable *hash_table,
-                                      GHRFunc    func,
-                                      gpointer   user_data,
-                                      gboolean    notify)
+gboolean
+mono_g_hash_table_lookup_extended (MonoGHashTable *hash, gconstpointer key, gpointer *orig_key, gpointer *value)
 {
-  MonoGHashNode *node, *prev;
-  guint i;
-  guint deleted = 0;
-  
-  for (i = 0; i < hash_table->size; i++)
-    {
-    restart:
-      
-      prev = NULL;
-      
-      for (node = hash_table->nodes[i]; node; prev = node, node = node->next)
-       {
-         if ((* func) (node->key, node->value, user_data))
-           {
-             deleted += 1;
-             
-             hash_table->nnodes -= 1;
-             
-             if (prev)
-               {
-                 prev->next = node->next;
-                 g_hash_node_destroy (node, hash_table->gc_type,
-                                      notify ? hash_table->key_destroy_func : NULL,
-                                      notify ? hash_table->value_destroy_func : NULL);
-                 node = prev;
-               }
-             else
-               {
-                 hash_table->nodes[i] = node->next;
-                 g_hash_node_destroy (node, hash_table->gc_type,
-                                      notify ? hash_table->key_destroy_func : NULL,
-                                      notify ? hash_table->value_destroy_func : NULL);
-                 goto restart;
+       GEqualFunc equal;
+       Slot *s;
+       guint hashcode;
+       
+       g_return_val_if_fail (hash != NULL, FALSE);
+       equal = hash->key_equal_func;
+
+       hashcode = ((*hash->hash_func) (key)) % hash->table_size;
+       
+       for (s = hash->table [hashcode]; s != NULL; s = s->next){
+               if ((*equal)(s->key, key)){
+                       *orig_key = s->key;
+                       *value = s->value;
+                       return TRUE;
                }
-           }
        }
-    }
-  
-  G_HASH_TABLE_RESIZE (hash_table);
-  
-  return deleted;
+       return FALSE;
 }
 
-/**
- * g_hash_table_foreach:
- * @hash_table: a #GHashTable.
- * @func: the function to call for each key/value pair.
- * @user_data: user data to pass to the function.
- * 
- * Calls the given function for each of the key/value pairs in the
- * #GHashTable.  The function is passed the key and value of each
- * pair, and the given @user_data parameter.  The hash table may not
- * be modified while iterating over it (you can't add/remove
- * items). To remove all items matching a predicate, use
- * g_hash_table_remove().
- **/
 void
-mono_g_hash_table_foreach (MonoGHashTable *hash_table,
-                     GHFunc      func,
-                     gpointer    user_data)
+mono_g_hash_table_foreach (MonoGHashTable *hash, GHFunc func, gpointer user_data)
 {
-  MonoGHashNode *node;
-  gint i;
-  
-  g_return_if_fail (hash_table != NULL);
-  g_return_if_fail (func != NULL);
-  
-  for (i = 0; i < hash_table->size; i++)
-    for (node = hash_table->nodes[i]; node; node = node->next)
-      (* func) (node->key, node->value, user_data);
+       int i;
+       
+       g_return_if_fail (hash != NULL);
+       g_return_if_fail (func != NULL);
+
+       for (i = 0; i < hash->table_size; i++){
+               Slot *s;
+
+               for (s = hash->table [i]; s != NULL; s = s->next)
+                       (*func)(s->key, s->value, user_data);
+       }
 }
 
 gpointer
-mono_g_hash_table_find (MonoGHashTable *hash_table, GHRFunc predicate, gpointer user_data)
+mono_g_hash_table_find (MonoGHashTable *hash, GHRFunc predicate, gpointer user_data)
 {
        int i;
-       MonoGHashNode *node;
        
-       g_return_val_if_fail (hash_table != NULL, NULL);
+       g_return_val_if_fail (hash != NULL, NULL);
        g_return_val_if_fail (predicate != NULL, NULL);
 
-       for (i = 0; i < hash_table->size; i++){
-               for (node = hash_table->nodes[i]; node; node = node->next)
-                       if ((*predicate)(node->key, node->value, user_data))
-                               return node->value;
+       for (i = 0; i < hash->table_size; i++){
+               Slot *s;
+
+               for (s = hash->table [i]; s != NULL; s = s->next)
+                       if ((*predicate)(s->key, s->value, user_data))
+                               return s->value;
        }
        return NULL;
 }
 
-/**
- * g_hash_table_size:
- * @hash_table: a #GHashTable.
- * 
- * Returns the number of elements contained in the #GHashTable.
- * 
- * Return value: the number of key/value pairs in the #GHashTable.
- **/
-guint
-mono_g_hash_table_size (MonoGHashTable *hash_table)
+gboolean
+mono_g_hash_table_remove (MonoGHashTable *hash, gconstpointer key)
 {
-  g_return_val_if_fail (hash_table != NULL, 0);
-  
-  return hash_table->nnodes;
+       GEqualFunc equal;
+       Slot *s, *last;
+       guint hashcode;
+       
+       g_return_val_if_fail (hash != NULL, FALSE);
+       equal = hash->key_equal_func;
+
+       hashcode = ((*hash->hash_func)(key)) % hash->table_size;
+       last = NULL;
+       for (s = hash->table [hashcode]; s != NULL; s = s->next){
+               if ((*equal)(s->key, key)){
+                       if (hash->key_destroy_func != NULL)
+                               (*hash->key_destroy_func)(s->key);
+                       if (hash->value_destroy_func != NULL)
+                               (*hash->value_destroy_func)(s->value);
+                       if (last == NULL)
+                               hash->table [hashcode] = s->next;
+                       else
+                               last->next = s->next;
+                       free_slot (hash, s);
+                       hash->in_use--;
+                       return TRUE;
+               }
+               last = s;
+       }
+       return FALSE;
 }
 
-/**
- * mono_g_hash_table_remap:
- * 
- *  Calls the given function for each key-value pair in the hash table, 
- * and replaces the value stored in the hash table by the value returned by 
- * the function.
- * 
- **/
-void        
-mono_g_hash_table_remap (MonoGHashTable *hash_table,
-                                                MonoGRemapperFunc func,
-                                                gpointer user_data)
+guint
+mono_g_hash_table_foreach_remove (MonoGHashTable *hash, GHRFunc func, gpointer user_data)
 {
-  MonoGHashNode *node;
-  gint i;
-  
-  g_return_if_fail (hash_table != NULL);
-  g_return_if_fail (func != NULL);
-  
-  for (i = 0; i < hash_table->size; i++)
-         for (node = hash_table->nodes[i]; node; node = node->next) {
-                 gpointer new_val = (* func) (node->key, node->value, user_data);
-                 SET_NODE_VALUE (node, hash_table->gc_type, new_val);
-         }
+       int i;
+       int count = 0;
+       
+       g_return_val_if_fail (hash != NULL, 0);
+       g_return_val_if_fail (func != NULL, 0);
+
+       for (i = 0; i < hash->table_size; i++){
+               Slot *s, *last;
+
+               last = NULL;
+               for (s = hash->table [i]; s != NULL; ){
+                       if ((*func)(s->key, s->value, user_data)){
+                               Slot *n;
+
+                               if (hash->key_destroy_func != NULL)
+                                       (*hash->key_destroy_func)(s->key);
+                               if (hash->value_destroy_func != NULL)
+                                       (*hash->value_destroy_func)(s->value);
+                               if (last == NULL){
+                                       hash->table [i] = s->next;
+                                       n = s->next;
+                               } else  {
+                                       last->next = s->next;
+                                       n = last->next;
+                               }
+                               free_slot (hash, s);
+                               hash->in_use--;
+                               count++;
+                               s = n;
+                       } else {
+                               last = s;
+                               s = s->next;
+                       }
+               }
+       }
+       if (count > 0)
+               rehash (hash);
+       return count;
 }
 
-static void
-g_hash_table_resize (MonoGHashTable *hash_table)
+void
+mono_g_hash_table_destroy (MonoGHashTable *hash)
 {
-  MonoGHashNode **new_nodes;
-  MonoGHashNode *node;
-  MonoGHashNode *next;
-  guint hash_val;
-  gint new_size;
-  gint i;
-
-  new_size = g_spaced_primes_closest (hash_table->nnodes);
-  new_size = CLAMP (new_size, HASH_TABLE_MIN_SIZE, HASH_TABLE_MAX_SIZE);
-#if HAVE_BOEHM_GC
-  new_nodes              = GC_MALLOC (sizeof (MonoGHashNode*) * new_size);
-#else
-  new_nodes              = g_new0 (MonoGHashNode*, new_size);
-#endif
-  
-  for (i = 0; i < hash_table->size; i++)
-    for (node = hash_table->nodes[i]; node; node = next)
-      {
-       next = node->next;
-
-       hash_val = (* hash_table->hash_func) (node->key) % new_size;
-
-       node->next = new_nodes[hash_val];
-       new_nodes[hash_val] = node;
-      }
-  
-#if HAVE_BOEHM_GC
-#else
-  g_free (hash_table->nodes);
+       int i;
+       
+       g_return_if_fail (hash != NULL);
+
+#ifdef HAVE_SGEN_GC
+       mono_gc_deregister_root ((char*)hash);
 #endif
-  hash_table->nodes = new_nodes;
-  hash_table->size = new_size;
+
+       for (i = 0; i < hash->table_size; i++){
+               Slot *s, *next;
+
+               for (s = hash->table [i]; s != NULL; s = next){
+                       next = s->next;
+                       
+                       if (hash->key_destroy_func != NULL)
+                               (*hash->key_destroy_func)(s->key);
+                       if (hash->value_destroy_func != NULL)
+                               (*hash->value_destroy_func)(s->value);
+                       free_slot (hash, s);
+               }
+       }
+       mg_free (hash->table);
+       mg_free (hash);
 }
 
 static void
-g_hash_node_destroy (MonoGHashNode      *hash_node,
-                    MonoGHashGCType type,
-                    GDestroyNotify  key_destroy_func,
-                    GDestroyNotify  value_destroy_func)
+mono_g_hash_table_insert_replace (MonoGHashTable *hash, gpointer key, gpointer value, gboolean replace)
 {
-  if (key_destroy_func)
-    key_destroy_func (hash_node->key);
-  if (value_destroy_func)
-    value_destroy_func (hash_node->value);
-  
-  hash_node->key = NULL;
-  hash_node->value = NULL;
-
-  G_LOCK (g_hash_global);
-#if defined(HAVE_SGEN_GC) || defined(HAVE_BOEHM_GC)
-  hash_node->next = node_free_lists [type];
-  node_free_lists [type] = hash_node;
-#else
-  hash_node->next = node_free_list;
-  node_free_list = hash_node;
-#endif
-  G_UNLOCK (g_hash_global);
+       guint hashcode;
+       Slot *s;
+       GEqualFunc equal;
+       
+       g_return_if_fail (hash != NULL);
+
+       equal = hash->key_equal_func;
+       if (hash->in_use >= hash->threshold)
+               rehash (hash);
+
+       hashcode = ((*hash->hash_func) (key)) % hash->table_size;
+       for (s = hash->table [hashcode]; s != NULL; s = s->next){
+               if ((*equal) (s->key, key)){
+                       if (replace){
+                               if (hash->key_destroy_func != NULL)
+                                       (*hash->key_destroy_func)(s->key);
+                               s->key = key;
+                       }
+                       if (hash->value_destroy_func != NULL)
+                               (*hash->value_destroy_func) (s->value);
+                       s->value = value;
+                       return;
+               }
+       }
+       s = new_slot (hash);
+       s->key = key;
+       s->value = value;
+       s->next = hash->table [hashcode];
+       hash->table [hashcode] = s;
+       hash->in_use++;
 }
 
-static void
-g_hash_nodes_destroy (MonoGHashNode *hash_node,
-                     MonoGHashGCType type,
-                     GFreeFunc  key_destroy_func,
-                     GFreeFunc  value_destroy_func)
+void
+mono_g_hash_table_insert (MonoGHashTable *h, gpointer k, gpointer v)
 {
-  if (hash_node)
-    {
-      MonoGHashNode *node = hash_node;
-  
-      while (node->next)
-       {
-         if (key_destroy_func)
-           key_destroy_func (node->key);
-         if (value_destroy_func)
-           value_destroy_func (node->value);
-
-         node->key = NULL;
-         node->value = NULL;
-
-         node = node->next;
-       }
+       mono_g_hash_table_insert_replace (h, k, v, FALSE);
+}
 
-  if (key_destroy_func)
-    key_destroy_func (node->key);
-  if (value_destroy_func)
-    value_destroy_func (node->value);
-
-      node->key = NULL;
-      node->value = NULL;
-      G_LOCK (g_hash_global);
-#if defined(HAVE_SGEN_GC) || defined(HAVE_BOEHM_GC)
-      node->next = node_free_lists [type];
-      node_free_lists [type] = hash_node;
-#else
-      node->next = node_free_list;
-      node_free_list = hash_node;
-#endif
-      G_UNLOCK (g_hash_global);
-    }
+void
+mono_g_hash_table_replace(MonoGHashTable *h, gpointer k, gpointer v)
+{
+       mono_g_hash_table_insert_replace (h, k, v, TRUE);
 }
 
 #ifdef HAVE_SGEN_GC
 
 /* GC marker function */
 static void
-mono_g_hash_mark (void *addr, MonoGCCopyFunc mark_func)
+mono_g_hash_mark (void *addr, MonoGCMarkFunc mark_func)
 {
        MonoGHashTable *table = (MonoGHashTable*)addr;
-       MonoGHashNode *node;
+       Slot *node;
        int i;
 
        if (table->gc_type == MONO_HASH_KEY_GC) {
-               for (i = 0; i < table->size; i++) {
-                       for (node = table->nodes [i]; node; node = node->next) {
+               for (i = 0; i < table->table_size; i++) {
+                       for (node = table->table [i]; node; node = node->next) {
                                if (node->key)
-                                       node->key = mark_func (node->key);
+                                       mark_func (&node->key);
                        }
                }
        } else if (table->gc_type == MONO_HASH_VALUE_GC) {
-               for (i = 0; i < table->size; i++) {
-                       for (node = table->nodes [i]; node; node = node->next) {
+               for (i = 0; i < table->table_size; i++) {
+                       for (node = table->table [i]; node; node = node->next) {
                                if (node->value)
-                                       node->value = mark_func (node->value);
+                                       mark_func (&node->value);
                        }
                }
        } else if (table->gc_type == MONO_HASH_KEY_VALUE_GC) {
-               for (i = 0; i < table->size; i++) {
-                       for (node = table->nodes [i]; node; node = node->next) {
+               for (i = 0; i < table->table_size; i++) {
+                       for (node = table->table [i]; node; node = node->next) {
                                if (node->key)
-                                       node->key = mark_func (node->key);
+                                       mark_func (&node->key);
                                if (node->value)
-                                       node->value = mark_func (node->value);
+                                       mark_func (&node->value);
                        }
                }
        }
index f9afdfb56bab25ee98d9d447bdde298e9c2fbe95..a705daf3caa56834bdfda14cbb0406c9124c31bb 100644 (file)
@@ -12,13 +12,15 @@ typedef enum {
        MONO_TRACE_DLLIMPORT            = (1<<2),
        MONO_TRACE_GC                   = (1<<3),
         MONO_TRACE_CONFIG              = (1<<4),
-       MONO_TRACE_AOT          = (1<<5),
+       MONO_TRACE_AOT                  = (1<<5),
+       MONO_TRACE_SECURITY             = (1<<6),
        MONO_TRACE_ALL                  = MONO_TRACE_ASSEMBLY |
                                          MONO_TRACE_TYPE |
                                          MONO_TRACE_DLLIMPORT |
                                          MONO_TRACE_GC |
-                         MONO_TRACE_CONFIG |
-                         MONO_TRACE_AOT
+                                         MONO_TRACE_CONFIG |
+                                         MONO_TRACE_AOT |
+                                         MONO_TRACE_SECURITY
 } MonoTraceMask;
 
 void 
index daa609bfb176c24b23f05558342725010151ffa4..2e6dedc77338d717e3853b508c0280653ebba516 100644 (file)
@@ -212,9 +212,10 @@ mono_trace_set_mask_string (const char *value)
        const char *tok;
        guint32 flags = 0;
 
-       const char *valid_flags[] = {"asm", "type", "dll", "gc", "cfg", "aot", "all", NULL};
+       const char *valid_flags[] = {"asm", "type", "dll", "gc", "cfg", "aot", "security", "all", NULL};
        const MonoTraceMask     valid_masks[] = {MONO_TRACE_ASSEMBLY, MONO_TRACE_TYPE, MONO_TRACE_DLLIMPORT,
-                                                 MONO_TRACE_GC, MONO_TRACE_CONFIG, MONO_TRACE_AOT, MONO_TRACE_ALL };
+                                                MONO_TRACE_GC, MONO_TRACE_CONFIG, MONO_TRACE_AOT, MONO_TRACE_SECURITY, 
+                                                MONO_TRACE_ALL };
 
        if(!value)
                return;
index 528330442490b3c5bff2a13fb66f588d5d60bb9a..a51e75ab552a36fb2414b63ce017ed2679b03e97 100644 (file)
@@ -14,6 +14,7 @@
 
 /* FIXME: bsds untested */
 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
+#include <sys/param.h>
 #include <sys/types.h>
 #include <sys/sysctl.h>
 #include <sys/proc.h>
 #include <sys/user.h>
 #endif
 #ifdef HAVE_STRUCT_KINFO_PROC_KP_PROC
-#define kinfo_pid_member kp_proc.p_pid
-#define kinfo_name_member kp_proc.p_comm
+#  ifdef KERN_PROC2
+#    define kinfo_pid_member p_pid
+#    define kinfo_name_member p_comm
+#  else
+#    define kinfo_pid_member kp_proc.p_pid
+#    define kinfo_name_member kp_proc.p_comm
+#  endif
 #else
 #define kinfo_pid_member ki_pid
 #define kinfo_name_member ki_comm
@@ -41,10 +47,16 @@ gpointer*
 mono_process_list (int *size)
 {
 #if USE_SYSCTL
-       int mib [4];
        int res, i;
+#ifdef KERN_PROC2
+       int mib [6];
+       size_t data_len = sizeof (struct kinfo_proc2) * 400;
+       struct kinfo_proc2 *processes = malloc (data_len);
+#else
+       int mib [4];
        size_t data_len = sizeof (struct kinfo_proc) * 400;
        struct kinfo_proc *processes = malloc (data_len);
+#endif /* KERN_PROC2 */
        void **buf = NULL;
 
        if (size)
@@ -52,17 +64,33 @@ mono_process_list (int *size)
        if (!processes)
                return NULL;
 
+#ifdef KERN_PROC2
+       mib [0] = CTL_KERN;
+       mib [1] = KERN_PROC2;
+       mib [2] = KERN_PROC_ALL;
+       mib [3] = 0;
+       mib [4] = sizeof(struct kinfo_proc2);
+       mib [5] = 400; /* XXX */
+
+       res = sysctl (mib, 6, processes, &data_len, NULL, 0);
+#else
        mib [0] = CTL_KERN;
        mib [1] = KERN_PROC;
        mib [2] = KERN_PROC_ALL;
        mib [3] = 0;
        
        res = sysctl (mib, 4, processes, &data_len, NULL, 0);
+#endif /* KERN_PROC2 */
+
        if (res < 0) {
                free (processes);
                return NULL;
        }
+#ifdef KERN_PROC2
+       res = data_len/sizeof (struct kinfo_proc2);
+#else
        res = data_len/sizeof (struct kinfo_proc);
+#endif /* KERN_PROC2 */
        buf = g_realloc (buf, res * sizeof (void*));
        for (i = 0; i < res; ++i)
                buf [i] = GINT_TO_POINTER (processes [i].kinfo_pid_member);
@@ -155,13 +183,33 @@ char*
 mono_process_get_name (gpointer pid, char *buf, int len)
 {
 #if USE_SYSCTL
-       int mib [4];
        int res;
+#ifdef KERN_PROC2
+       int mib [6];
+       size_t data_len = sizeof (struct kinfo_proc2);
+       struct kinfo_proc2 processi;
+#else
+       int mib [4];
        size_t data_len = sizeof (struct kinfo_proc);
        struct kinfo_proc processi;
+#endif /* KERN_PROC2 */
 
        memset (buf, 0, len);
 
+#ifdef KERN_PROC2
+       mib [0] = CTL_KERN;
+       mib [1] = KERN_PROC2;
+       mib [2] = KERN_PROC_PID;
+       mib [3] = GPOINTER_TO_UINT (pid);
+       mib [4] = sizeof(struct kinfo_proc2);
+       mib [5] = 400; /* XXX */
+
+       res = sysctl (mib, 6, &processi, &data_len, NULL, 0);
+
+       if (res < 0 || data_len != sizeof (struct kinfo_proc2)) {
+               return buf;
+       }
+#else
        mib [0] = CTL_KERN;
        mib [1] = KERN_PROC;
        mib [2] = KERN_PROC_PID;
@@ -171,6 +219,7 @@ mono_process_get_name (gpointer pid, char *buf, int len)
        if (res < 0 || data_len != sizeof (struct kinfo_proc)) {
                return buf;
        }
+#endif /* KERN_PROC2 */
        strncpy (buf, processi.kinfo_name_member, len - 1);
        return buf;
 #else
index dd60db469c043e8b34a1eab9e5c92165018b1b13..755166b00551eb9b4210cc668cca68b9da7d1f94 100644 (file)
  */
 
 #include <config.h>
+#include <errno.h>
 #include "utils/mono-semaphore.h"
+#ifdef HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
 
-#if defined(HAVE_SEMAPHORE_H) || defined(USE_MACH_SEMA)
+#if (defined(HAVE_SEMAPHORE_H) || defined(USE_MACH_SEMA))
 /* sem_* or semaphore_* functions in use */
 #  ifdef USE_MACH_SEMA
 #    define TIMESPEC mach_timespec_t
 #    define WAIT_BLOCK(a,b) semaphore_timedwait (*(a), *(b))
+#  elif defined(__OpenBSD__)
+#    define TIMESPEC struct timespec
+#    define WAIT_BLOCK(a) sem_trywait(a)
 #  else
 #    define TIMESPEC struct timespec
 #    define WAIT_BLOCK(a,b) sem_timedwait (a, b)
 #  endif
 
-gboolean
-mono_sem_timedwait (MonoSemType *sem, guint32 timeout_ms)
+#define NSEC_PER_SEC 1000000000
+int
+mono_sem_timedwait (MonoSemType *sem, guint32 timeout_ms, gboolean alertable)
 {
-       TIMESPEC tv;
+       TIMESPEC ts, copy;
+       struct timeval t;
+       int res = 0;
+#if defined(__OpenBSD__)
+       int timeout;
+#endif
 
 #ifndef USE_MACH_SEMA
        if (timeout_ms == 0)
                return (!sem_trywait (sem));
 #endif
+       if (timeout_ms == (guint32) 0xFFFFFFFF)
+               return mono_sem_wait (sem, alertable);
+
+       gettimeofday (&t, NULL);
+       ts.tv_sec = timeout_ms / 1000 + t.tv_sec;
+       ts.tv_nsec = (timeout_ms % 1000) * 1000000 + t.tv_usec * 1000;
+       while (ts.tv_nsec > NSEC_PER_SEC) {
+               ts.tv_nsec -= NSEC_PER_SEC;
+               ts.tv_sec++;
+       }
+#if defined(__OpenBSD__)
+       timeout = ts.tv_sec;
+       while (timeout) {
+               if ((res = WAIT_BLOCK (sem)) == 0)
+                       return res;
+
+               if (alertable)
+                       return -1;
+
+               usleep (ts.tv_nsec / 1000);
+               timeout--;
+       }
+#else
+       copy = ts;
+       while ((res = WAIT_BLOCK (sem, &ts) == -1) && errno == EINTR) {
+               struct timeval current;
+               if (alertable)
+                       return -1;
+               gettimeofday (&current, NULL);
+               ts = copy;
+               ts.tv_sec -= (current.tv_sec - t.tv_sec);
+               ts.tv_nsec -= (current.tv_usec - t.tv_usec) * 1000;
+               if (ts.tv_nsec < 0) {
+                       if (ts.tv_sec <= 0) {
+                               ts.tv_nsec = 0;
+                       } else {
+                               ts.tv_sec--;
+                               ts.tv_nsec += NSEC_PER_SEC;
+                       }
+               }
+               if (ts.tv_sec < 0) {
+                       ts.tv_sec = 0;
+                       ts.tv_nsec = 0;
+               }
+       }
+#endif
+       return res;
+}
+
+int
+mono_sem_wait (MonoSemType *sem, gboolean alertable)
+{
+       int res;
+#ifndef USE_MACH_SEMA
+       while ((res = sem_wait (sem) == -1) && errno == EINTR)
+#else
+       while ((res = semaphore_wait (*sem) == -1) && errno == EINTR)
+#endif
+       {
+               if (alertable)
+                       return -1;
+       }
+       return res;
+}
 
-       tv.tv_sec = timeout_ms / 1000;
-       tv.tv_nsec = (timeout_ms % 1000) * 1000000;
-       return (!WAIT_BLOCK (sem, &tv));
+int
+mono_sem_post (MonoSemType *sem)
+{
+       int res;
+#ifndef USE_MACH_SEMA
+       while ((res = sem_post (sem) == -1) && errno == EINTR);
+#else
+       while ((res = semaphore_signal (*sem) == -1) && errno == EINTR);
+#endif
+       return res;
 }
 
 #else
 /* Windows or io-layer functions in use */
-gboolean
-mono_sem_timedwait (MonoSemType *sem, guint32 timeout_ms)
+int
+mono_sem_wait (MonoSemType *sem, gboolean alertable)
 {
-       return WaitForSingleObjectEx (*sem, timeout_ms, TRUE);
+       return mono_sem_timedwait (sem, INFINITE, alertable);
 }
 
+int
+mono_sem_timedwait (MonoSemType *sem, guint32 timeout_ms, gboolean alertable)
+{
+       gboolean res;
+
+       res = WaitForSingleObjectEx (*sem, timeout_ms, alertable);
+       switch (res) {
+       case WAIT_OBJECT_0:
+               return 0;
+       case WAIT_IO_COMPLETION:
+               errno = EINTR;
+               return -1;            
+       // WAIT_TIMEOUT and WAIT_FAILED
+       default:
+               return -1;
+       }
+}
+
+int
+mono_sem_post (MonoSemType *sem)
+{
+       if (!ReleaseSemaphore (*sem, 1, NULL))
+               return -1;
+       return 0;
+}
 #endif
 
index 7218210ae5f944484173e234ae0cd1015fa4476b..d6be806efe5a2b14a52129a46b72745490d5413a 100644 (file)
 #    include <mach/semaphore.h>
 typedef semaphore_t MonoSemType;
 #    define MONO_SEM_INIT(addr,value) semaphore_create (current_task (), (addr), SYNC_POLICY_FIFO, (value))
-#    define MONO_SEM_WAIT(sem) semaphore_wait (*(sem))
-#    define MONO_SEM_POST(sem) semaphore_signal (*(sem))
 #    define MONO_SEM_DESTROY(sem) semaphore_destroy (current_task (), *(sem))
 #  else
 typedef sem_t MonoSemType;
 #    define MONO_SEM_INIT(addr,value) sem_init ((addr), 0, (value))
-#    define MONO_SEM_WAIT(sem) sem_wait ((sem))
-#    define MONO_SEM_POST(sem) sem_post ((sem))
 #    define MONO_SEM_DESTROY(sem) sem_destroy ((sem))
 #  endif
-#elif defined(HOST_WIN32) || defined(_WAPI_SEMAPHORES_H)
+#else
 #  define MONO_HAS_SEMAPHORES
 typedef HANDLE MonoSemType;
 #    define MONO_SEM_INIT(addr,initial) do {*(addr) = CreateSemaphore ( NULL,(initial),0x7FFFFFFF,NULL);} while(0)
-#    define MONO_SEM_WAIT(sem) WaitForSingleObjectEx (*(sem),INFINITE, TRUE)
-#    define MONO_SEM_POST(sem) (!(ReleaseSemaphore (*(sem),1,NULL)))
 #    define MONO_SEM_DESTROY(sem) CloseHandle (*(sem))
 #endif
 
-#define MONO_SEM_TIMEDWAIT(sem, timeout_ms) mono_sem_timedwait ((sem), (timeout_ms)) 
+#define MONO_SEM_WAIT(sem) MONO_SEM_WAIT_ALERTABLE(sem, FALSE)
+#define MONO_SEM_WAIT_ALERTABLE(sem,alertable) mono_sem_wait ((sem), alertable)
+#define MONO_SEM_POST(sem) mono_sem_post ((sem))
+#define MONO_SEM_TIMEDWAIT(sem, timeout_ms) MONO_SEM_TIMEDWAIT_ALERTABLE(sem, timeout_ms, FALSE)
+#define MONO_SEM_TIMEDWAIT_ALERTABLE(sem, timeout_ms, alertable) mono_sem_timedwait ((sem), (timeout_ms), alertable) 
 
 G_BEGIN_DECLS
 
-gboolean mono_sem_timedwait (MonoSemType *sem, guint32 timeout_ms);
+int mono_sem_wait (MonoSemType *sem, gboolean alertable);
+int mono_sem_timedwait (MonoSemType *sem, guint32 timeout_ms, gboolean alertable);
+int mono_sem_post (MonoSemType *sem);
 
 G_END_DECLS
 #endif /* _MONO_SEMAPHORE_H_ */
index 0a767dbc72f1debb0335e1b8213e32f9585369ce..3b839df896bceddd00d0b61022f8a77603a87bf0 100644 (file)
        #define UCONTEXT_REG_ESI(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs [_REG_ESI])
        #define UCONTEXT_REG_EDI(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs [_REG_EDI])
        #define UCONTEXT_REG_EIP(ctx) (((ucontext_t*)(ctx))->uc_mcontext.__gregs [_REG_EIP])
+#elif defined(__OpenBSD__)
+       #define UCONTEXT_REG_EAX(ctx) ((ctx)->sc_eax)
+       #define UCONTEXT_REG_EBX(ctx) ((ctx)->sc_ebx)
+       #define UCONTEXT_REG_ECX(ctx) ((ctx)->sc_ecx)
+       #define UCONTEXT_REG_EDX(ctx) ((ctx)->sc_edx)
+       #define UCONTEXT_REG_EBP(ctx) ((ctx)->sc_ebp)
+       #define UCONTEXT_REG_ESP(ctx) ((ctx)->sc_esp)
+       #define UCONTEXT_REG_ESI(ctx) ((ctx)->sc_esi)
+       #define UCONTEXT_REG_EDI(ctx) ((ctx)->sc_edi)
+       #define UCONTEXT_REG_EIP(ctx) ((ctx)->sc_eip)
 #else
        #define UCONTEXT_REG_EAX(ctx) (((ucontext_t*)(ctx))->uc_mcontext.gregs [REG_EAX])
        #define UCONTEXT_REG_EBX(ctx) (((ucontext_t*)(ctx))->uc_mcontext.gregs [REG_EBX])
 
 #elif defined(__x86_64__)
 
-#ifdef __FreeBSD__
+#if defined(__APPLE__)
+       #define UCONTEXT_REG_RAX(ctx) (((ucontext_t*)(ctx))->uc_mcontext->__ss.__rax)
+       #define UCONTEXT_REG_RBX(ctx) (((ucontext_t*)(ctx))->uc_mcontext->__ss.__rbx)
+       #define UCONTEXT_REG_RCX(ctx) (((ucontext_t*)(ctx))->uc_mcontext->__ss.__rcx)
+       #define UCONTEXT_REG_RDX(ctx) (((ucontext_t*)(ctx))->uc_mcontext->__ss.__rdx)
+       #define UCONTEXT_REG_RBP(ctx) (((ucontext_t*)(ctx))->uc_mcontext->__ss.__rbp)
+       #define UCONTEXT_REG_RSP(ctx) (((ucontext_t*)(ctx))->uc_mcontext->__ss.__rsp)
+       #define UCONTEXT_REG_RSI(ctx) (((ucontext_t*)(ctx))->uc_mcontext->__ss.__rsi)
+       #define UCONTEXT_REG_RDI(ctx) (((ucontext_t*)(ctx))->uc_mcontext->__ss.__rdi)
+       #define UCONTEXT_REG_RIP(ctx) (((ucontext_t*)(ctx))->uc_mcontext->__ss.__rip)
+       #define UCONTEXT_REG_R12(ctx) (((ucontext_t*)(ctx))->uc_mcontext->__ss.__r12)
+       #define UCONTEXT_REG_R13(ctx) (((ucontext_t*)(ctx))->uc_mcontext->__ss.__r13)
+       #define UCONTEXT_REG_R14(ctx) (((ucontext_t*)(ctx))->uc_mcontext->__ss.__r14)
+       #define UCONTEXT_REG_R15(ctx) (((ucontext_t*)(ctx))->uc_mcontext->__ss.__r15)
+#elif defined(__FreeBSD__)
 #define UCONTEXT_GREGS(ctx)    &(((ucontext_t*)(ctx))->uc_mcontext)
+#elif defined(__OpenBSD__)
+    /* OpenBSD/amd64 has no gregs array, ucontext_t == sigcontext */
+       #define UCONTEXT_REG_RAX(ctx) ((ctx)->sc_rax)
+       #define UCONTEXT_REG_RBX(ctx) ((ctx)->sc_rbx)
+       #define UCONTEXT_REG_RCX(ctx) ((ctx)->sc_rcx)
+       #define UCONTEXT_REG_RDX(ctx) ((ctx)->sc_rdx)
+       #define UCONTEXT_REG_RBP(ctx) ((ctx)->sc_rbp)
+       #define UCONTEXT_REG_RSP(ctx) ((ctx)->sc_rsp)
+       #define UCONTEXT_REG_RSI(ctx) ((ctx)->sc_rsi)
+       #define UCONTEXT_REG_RDI(ctx) ((ctx)->sc_rdi)
+       #define UCONTEXT_REG_RIP(ctx) ((ctx)->sc_rip)
+       #define UCONTEXT_REG_R12(ctx) ((ctx)->sc_r12)
+       #define UCONTEXT_REG_R13(ctx) ((ctx)->sc_r13)
+       #define UCONTEXT_REG_R14(ctx) ((ctx)->sc_r14)
+       #define UCONTEXT_REG_R15(ctx) ((ctx)->sc_r15)
 #else
 #define UCONTEXT_GREGS(ctx)    &(((ucontext_t*)(ctx))->uc_mcontext.gregs)
 #endif
index 72b569ca8ca38a596910cb92a25eb61bfcc8cf42..4e923e64b1176671177dc45482372ee00a0bd352 100644 (file)
@@ -57,12 +57,32 @@ mono_100ns_datetime (void)
 #include <sys/time.h>
 #endif
 
+#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
+#include <sys/param.h>
+#include <sys/sysctl.h>
+#endif
+
 #include <time.h>
 
 static gint64
 get_boot_time (void)
 {
-       /* FIXME: use sysctl (kern.boottime) on OSX */
+#if defined(PLATFORM_MACOSX) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
+       int mib [2];
+       size_t size;
+       time_t now;
+       struct timeval boottime;
+
+       (void)time(&now);
+
+       mib [0] = CTL_KERN;
+       mib [1] = KERN_BOOTTIME;
+
+       size = sizeof(boottime);
+
+       if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1)
+               return (gint64)((now - boottime.tv_sec) * MTICKS_PER_SEC);
+#else
        FILE *uptime = fopen ("/proc/uptime", "r");
        if (uptime) {
                double upt;
@@ -73,6 +93,7 @@ get_boot_time (void)
                }
                fclose (uptime);
        }
+#endif
        /* a made up uptime of 300 seconds */
        return (gint64)300 * MTICKS_PER_SEC;
 }
index 7f804f0250f9c0e9fac4cc058b7fd6004e3b20e8..8b1aa4bbfe398eb7cf0dfb6a50540bcdfeead1e1 100755 (executable)
@@ -1,3 +1,8 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * scripts/monowrap.cs, scripts/genproj.cs: rename
+       the net_2_1 profile to moonlight.
+
 2010-03-01  Robert Jordan  <robertj@gmx.net>
 
        * libmono.vcproj: Track changes.
index 92210d4c3a8890e23b30d8a029384309cd2cd403..d160f3d83a3732fa72ec605b0e1b60903afdd93b 100644 (file)
                                RelativePath="..\mono\utils\mono-error.h"\r
                                >\r
                        </File>\r
-                       <File\r
+      <File RelativePath="..\mono\utils\mono-semaphore.c"></File>\r
+      <File RelativePath="..\mono\utils\mono-semaphore.h"></File>\r
+      <File RelativePath="..\mono\metadata\mono-wsq.c"></File>\r
+      <File RelativePath="..\mono\metadata\mono-wsq.h"></File>\r
+      <File\r
                                RelativePath="..\mono\utils\mono-filemap.c"\r
                                >\r
                        </File>\r
index 856b0d008e9a3ef0c028bcf7e61de5443691ad8c..13900cc6ee7060a594c593182eb0bd8fa6e79a5a 100644 (file)
@@ -238,18 +238,15 @@ mono_free_verify_list
 mono_g_hash_table_destroy
 mono_g_hash_table_foreach
 mono_g_hash_table_foreach_remove
-mono_g_hash_table_foreach_steal
 mono_g_hash_table_insert
 mono_g_hash_table_lookup
 mono_g_hash_table_lookup_extended
 mono_g_hash_table_new
 mono_g_hash_table_new_full
 mono_g_hash_table_new_type
-mono_g_hash_table_remap
 mono_g_hash_table_remove
 mono_g_hash_table_replace
 mono_g_hash_table_size
-mono_g_hash_table_steal
 mono_gc_collect
 mono_gc_collection_count
 mono_gc_enable_events
@@ -366,7 +363,6 @@ mono_image_open_full
 mono_image_rva_map
 mono_image_strerror
 mono_image_strong_name_position
-mono_image_verify_tables
 mono_images_cleanup
 mono_images_init
 mono_init
index fd0f1b6c83aecc4fde96bf285ad5e8c664e0410f..fca1c3d1d9c09cfb2b76a2fac8804126d102934a 100644 (file)
@@ -92,4 +92,9 @@ Mono_Posix_ToSyslogLevel
 Mono_Posix_ToSyslogOptions\r
 Mono_Posix_ToWaitOptions\r
 Mono_Posix_ToXattrFlags\r
+CreateZStream\r
+CloseZStream\r
+ReadZStream\r
+WriteZStream\r
+Flush\r
 \r
index ad27791b0368e267275029de3775d48269481157..a42fb3ec64b0555121b171dfbaa496daa16a6ec9 100644 (file)
@@ -612,10 +612,10 @@ class MsbuildGenerator {
                        compiler = "net_2_0_bootstrap";
                else if (compiler.EndsWith ("mcs/gmcs.exe"))
                        compiler = "gmcs";
-               else if (compiler.EndsWith ("class/lib/net_2_1_bootstrap/smcs.exe"))
-                       compiler = "net_2_1_bootstrap";
-               else if (compiler.EndsWith ("class/lib/net_2_1_raw/smcs.exe"))
-                       compiler = "net_2_1_raw";
+               else if (compiler.EndsWith ("class/lib/moonlight_bootstrap/smcs.exe"))
+                       compiler = "moonlight_bootstrap";
+               else if (compiler.EndsWith ("class/lib/moonlight_raw/smcs.exe"))
+                       compiler = "moonlight_raw";
                else if (compiler.EndsWith ("class/lib/net_4_0_bootstrap/dmcs.exe"))
                        compiler = "net_4_0_bootstrap";
                else if (compiler.EndsWith ("class/lib/net_4_0/dmcs.exe"))
@@ -743,7 +743,7 @@ public class Driver {
                        // Do not do 2.1, it is not working yet
                        // Do not do basic, as there is no point (requires a system mcs to be installed).
                        //
-                       if (library.Contains ("net_2_1") || library.Contains ("-basic"))
+                       if (library.Contains ("moonlight") || library.Contains ("-basic"))
                                continue;
                        
                        var gen = new MsbuildGenerator (dir);
index dc0261231c211a50d0771b30721cfeced09bcc09..5b476832433169e16ecca284337b9e78da22ab42 100755 (executable)
 //    net_1_1           -> class/lib/net_1_1/mcs.exe
 //    net_2_0_bootstrap -> class/lib/net_2_0_bootstrap/gmcs.exe
 //    gmcs              -> mcs/gmcs.exe
-//    net_2_1_bootstrap -> class/lib/net_2_1_bootstrap/smcs.exe
-//    net_2_1_raw       -> class/lib/net_2_1_raw/smcs.exe
+//    moonlight_bootstrap -> class/lib/moonlight_bootstrap/smcs.exe
+//    moonlight_raw       -> class/lib/moonlight_raw/smcs.exe
 //
 // So for example:
-// net_2_1_bootstrap-net_2_0-net_2_1_bootstrap
+// moonlight_bootstrap-net_2_0-moonlight_bootstrap
 //
-// Will set MONO_PATH to "%MCS_ROOT%\class\lib\net_2_1_bootstrap;%MCS_ROOT\class\lib\net_2_0"
-// and run the compiler in %MCS_ROOT%\class\lib\net_2_1_bootstrap
+// Will set MONO_PATH to "%MCS_ROOT%\class\lib\moonlight_bootstrap;%MCS_ROOT\class\lib\net_2_0"
+// and run the compiler in %MCS_ROOT%\class\lib\moonlight_bootstrap
 //
 
 using System;
@@ -94,12 +94,12 @@ namespace csc
                                compiler = root_mcs + "\\mcs\\gmcs.exe";
                                break;
                                
-                       case "net_2_1_bootstrap":
-                               compiler = root_mcs + "\\class\\lib\\net_2_1_bootstrap\\smcs.exe";
+                       case "moonlight_bootstrap":
+                               compiler = root_mcs + "\\class\\lib\\moonlight_bootstrap\\smcs.exe";
                                break;
                                
-                       case "net_2_1_raw":
-                               compiler = root_mcs + "\\class\\lib\\net_2_1_raw\\smcs.exe";
+                       case "moonlight_raw":
+                               compiler = root_mcs + "\\class\\lib\\moonlight_raw\\smcs.exe";
                                break;
 
                        default:
index 133bc711940e19b16c0a1853d69c77fa001374b5..ce34aa1fccba7f130814966e3bd30df19bc3eda0 100644 (file)
                <References>\r
                        <Reference>mscorlib</Reference>\r
                        <Reference>System</Reference>\r
+                       <Reference>System.Core</Reference>\r
                        <Reference>System.Xml</Reference>\r
                        <Reference>Microsoft.Build.Framework</Reference>\r
                        <Reference>Microsoft.Build.Utilities</Reference>\r
       <Source type="list">Mono.Cecil.Mdb.dll.sources</Source>\r
     </Sources>\r
   </Assembly>\r
+  <Assembly name="Mono.Debugger.Soft" destination="{destdir}\lib\mono\2.0\Mono.Debugger.Soft.dll">\r
+    <References>\r
+      <Reference>mscorlib</Reference>\r
+      <Reference>System</Reference>\r
+      <Reference>System.Core</Reference>\r
+      <Reference>Mono.Cecil</Reference>\r
+    </References>\r
+    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\r
+    <OutputType>library</OutputType>\r
+    <KeyFile>{sourcedir}\mcs\class\mono.snk</KeyFile>\r
+    <SourcePath>{sourcedir}\mcs\class\Mono.Debugger.Soft\</SourcePath>\r
+    <DefineConstants>NET_1_1;NET_2_0;MONO_DATACONVERTER_STATIC_METHODS</DefineConstants>\r
+    <Sources>\r
+      <Source type="list">Mono.Debugger.Soft.dll.sources</Source>\r
+    </Sources>\r
+  </Assembly>\r
 \r
   <Sign assembly="{destdir}\lib\mono\2.0\I18N.dll" key="{sourcedir}\mcs\class\mono.snk" />\r
        <Sign assembly="{destdir}\lib\mono\2.0\I18N.West.dll" key="{sourcedir}\mcs\class\mono.snk" />\r
   <Sign assembly="{destdir}\lib\mono\2.0\Mono.Cecil.dll" key="{sourcedir}\mcs\class\mono.snk" />\r
   <Sign assembly="{destdir}\lib\mono\2.0\Mono.Cecil.Mdb.dll" key="{sourcedir}\mcs\class\mono.snk" />\r
   <Sign assembly="{destdir}\lib\mono\2.0\Mono.CompilerServices.SymbolWriter.dll" key="{sourcedir}\mcs\class\mono.snk" />\r
+  <Sign assembly="{destdir}\lib\mono\2.0\Mono.Debugger.Soft.dll" key="{sourcedir}\mcs\class\mono.snk" />\r
 \r
   <!-- GAC our assemblies -->\r
        <Gac>{destdir}\lib\mono\2.0\System.dll</Gac>\r
   <Gac>{destdir}\lib\mono\2.0\Mono.Cecil.dll</Gac>\r
   <Gac>{destdir}\lib\mono\2.0\Mono.Cecil.Mdb.dll</Gac>\r
   <Gac>{destdir}\lib\mono\2.0\Mono.CompilerServices.SymbolWriter.dll</Gac>\r
+  <Gac>{destdir}\lib\mono\2.0\Mono.Debugger.Soft.dll</Gac>\r
 \r
   <!-- Build some more tools -->\r
        <Assembly name="al" destination="{destdir}\lib\mono\2.0\al.exe">\r
index 9db9f74c8d86c8d46ea5e797795dd6b6879bff78..d542b32675ca62592966618695cfa9cd9c0fa937 100755 (executable)
@@ -1,3 +1,7 @@
+2010-03-16  Jb Evain  <jbevain@novell.com>
+
+       * setup-solution.bat: rename the net_2_1 profile to moonlight.
+
 2010-01-18  Bill Holmes  <billholmes54@gmail.com>
 
        * libmono.vcproj : Adding a link to Mswsock.lib and adding files
index e9f0ff0c80520868601b26a2799ab0985e90cf4f..2e7941a2cc68832f17980584e2afe23fc5e4a77e 100755 (executable)
@@ -2,7 +2,7 @@
 mkdir scripts\net_1_1_bootstrap > nul 2> nul\r
 mkdir scripts\net_1_1 > nul 2> nul\r
 mkdir scripts\net_2_0 > nul 2> nul\r
-mkdir scripts\net_2_1 > nul 2> nul\r
+mkdir scripts\moonlight > nul 2> nul\r
 \r
 csc -debug -out:scripts\monowrap.exe scripts\monowrap.cs \r
 copy scripts\monowrap.exe scripts\net_1_1_bootstrap\csc.exe\r
@@ -14,8 +14,8 @@ copy scripts\monowrap.pdb scripts\net_1_1\csc.pdb
 copy scripts\monowrap.exe scripts\net_2_0\csc.exe\r
 copy scripts\monowrap.pdb scripts\net_2_0\csc.pdb\r
 \r
-copy scripts\monowrap.exe scripts\net_2_1\csc.exe\r
-copy scripts\monowrap.pdb scripts\net_2_1\csc.pdb\r
+copy scripts\monowrap.exe scripts\moonlight\csc.exe\r
+copy scripts\monowrap.pdb scripts\moonlight\csc.pdb\r
 \r
 echo Setup complete, you can now use build the solution\r
 \r
index 71e3b83c799a7a51e2470bd7c869dbce06ab488e..24f9210dd845dda9e018b5de5276a1e1fbdd30bf 100644 (file)
@@ -24,12 +24,17 @@ $(symlinks):
 
 SUPPORT_FILES = $(symlinks) mono-wrapper etc/mono/config
 
-if MOONLIGHT
-build_profiles = net_2_1_raw
-test_profiles = net_2_1_raw
+if ONLY_MOONLIGHT
+build_profiles = moonlight_raw
+test_profiles = moonlight_raw
 else
+
 build_profiles = net_2_0 net_3_5
 test_profiles = $(build_profiles)
+
+if MOONLIGHT
+build_profiles += moonlight_raw
+test_profiles += moonlight_raw
 endif
 
 if INSTALL_4_0
@@ -41,6 +46,8 @@ if INSTALL_MONOTOUCH
 build_profiles += monotouch
 endif
 
+endif
+
 if BUILD_MCS
 
 # The write check is to foil 'make distcheck'
@@ -71,7 +78,7 @@ clean-local:
 
 endif BUILD_MCS
 
-TEST_SUPPORT_FILES = $(tmpinst)/bin/mono $(tmpinst)/bin/ilasm $(tmpinst)/bin/gmcs $(tmpinst)/bin/al2
+TEST_SUPPORT_FILES = $(tmpinst)/bin/mono $(tmpinst)/bin/ilasm $(tmpinst)/bin/gmcs $(tmpinst)/bin/dmcs $(tmpinst)/bin/al2
 
 # now a misnomer, but it'll go away soon enough.
 if ENABLE_NUNIT_TESTS
@@ -105,7 +112,7 @@ endif
 mcs-compileall: mono-wrapper etc/mono/config
        save_MONO_PATH=$$MONO_PATH; mcs_topdir=`cd $(mcs_topdir) && $(cur_dir_cmd)`; ok=:; \
        for profile in $(test_profiles); do \
-         if [ "net_2_1" = "$$profile" ]; then \
+         if [ "moonlight" = "$$profile" ]; then \
           break; \
       fi; \
          if [ "net_3_5" = "$$profile" ]; then \
@@ -149,6 +156,12 @@ $(tmpinst)/bin/gmcs: $(tmpinst)/bin/mono Makefile
        echo 'exec "'"$$r/$(tmpinst)/bin/mono"'" "'"$$m/class/lib/net_2_0/gmcs.exe"'" "$$@"' >> $@ ; \
        chmod +x $@
 
+$(tmpinst)/bin/dmcs: $(tmpinst)/bin/mono Makefile
+       echo '#! /bin/sh' > $@ ; \
+       r=`pwd`; m=`cd $(mcs_topdir) && pwd`; \
+       echo 'exec "'"$$r/$(tmpinst)/bin/mono"'" "'"$$m/class/lib/net_4_0/dmcs.exe"'" "$$@"' >> $@ ; \
+       chmod +x $@
+
 $(tmpinst)/bin/ilasm: $(tmpinst)/bin/mono Makefile
        echo '#! /bin/sh' > $@ ; \
        r=`pwd`; m=`cd $(mcs_topdir) && pwd`; \
index 974848b3c2f4f248d80e9b67e2f0d32c674774d3..bb5d74e214062fd3bf7034e1d8d4de6d247096df 100644 (file)
@@ -3,4 +3,4 @@ r='@mono_build_root@'
 MONO_CFG_DIR='@mono_cfg_dir@'
 MONO_SHARED_DIR=$r/runtime
 export MONO_CFG_DIR MONO_SHARED_DIR
-exec "$r/libtool" --mode=execute -dlopen "$r/mono/mini/libmono.la" "$r/mono/dis/monodis" "$@"
+exec "$r/libtool" --mode=execute -dlopen "$r/mono/mini/libmono-2.0.la" "$r/mono/dis/monodis" "$@"
index c0ae0ef4baf8f13b70384ad1ae0ff8bf64fd2782..cb8a034f977d72894dea262fab819c2be873928a 100755 (executable)
@@ -152,7 +152,9 @@ class DocHandler (saxutils.DefaultHandler):
             print ('<h1>%s collection %d</h1>' % (self.collection_kind, self.collection_num), file = self.collection_file)
             self.usage = {}
             self.los_usage = {}
+            self.pinned_usage = {}
             self.in_los = False
+            self.in_pinned = False
             self.heap_used = 0
             self.heap_size = 0
             self.los_size = 0
@@ -184,6 +186,11 @@ class DocHandler (saxutils.DefaultHandler):
             if self.in_los:
                 usage_dict = self.los_usage
                 self.los_size += size
+            elif self.in_pinned:
+                location = attrs.get('location', None)
+                if location not in self.pinned_usage:
+                    self.pinned_usage[location] = {}
+                usage_dict = self.pinned_usage[location]
             else:
                 usage_dict = self.usage
                 offset = int(attrs.get('offset', None))
@@ -202,6 +209,8 @@ class DocHandler (saxutils.DefaultHandler):
             self.heap_used += size
         elif name == 'los':
             self.in_los = True
+        elif name == 'pinned-objects':
+            self.in_pinned = True
 
     def dump_usage (self, usage_dict, limit):
         klasses = sorted (usage_dict.keys (), lambda x, y: usage_dict [y][1] - usage_dict [x][1])
@@ -229,12 +238,18 @@ class DocHandler (saxutils.DefaultHandler):
             self.dump_usage (self.usage, 10)
             print ('<h3>LOS</h3>', file = self.collection_file)
             self.dump_usage (self.los_usage, None)
+            print ('<h3>Pinned</h3>', file = self.collection_file)
+            for location in sorted (self.pinned_usage.keys ()):
+                print ('<h4>%s</h4>' % location, file = self.collection_file)
+                self.dump_usage (self.pinned_usage[location], None)
             print ('</body></html>', file = self.collection_file)
             print (' - %d kB / %d kB (%d%%) - %d kB LOS</a><br>' % (self.heap_used / 1024, self.heap_size / 1024, int(100.0 * self.heap_used / self.heap_size), self.los_size / 1024), file = self.index_file)
             self.collection_file.close ()
             self.collection_index += 1
         elif name == 'los':
             self.in_los = False
+        elif name == 'pinned-objects':
+            self.in_pinned = False
 
 def main ():
     usage = "usage: %prog [options]"
index 1eda6057a5a7e6cf3ef895b8af56747cfc205925..f659acd732bf4aeda966be89d34085c24d73de3a 100644 (file)
@@ -1,3 +1,49 @@
+2010-04-19 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * zlib-helper.c: don't call Z_FINISH if nothing has been written.
+
+2010-04-19  Jonathan Pryor  <jpryor@novell.com>
+
+       * dirent.c, grp.c, macros.c, pwd.c, signal.c, sys-statvfs.c, sys-time.c,
+         unistd.c: Add #if HAVE_XXX checks for functions which aren't
+         provided on Android.
+
+2010-04-15  Jonathan Pryor  <jpryor@novell.com>
+
+       * Makefile.am: Revert previous linkage against libmono.so, as lupus
+         mentioned that it's unacceptable for MonoPosixHelper to link against
+         libmono (e.g. when embedding mono, there might not be a libmono).
+       * map.h: Flush updated Mono_Unix_UnixSignal_SignalInfo prototype.
+       * signal.c: Don't use mono_runtime_is_shutting_down(). Instead, change
+         Mono_Unix_UnixSignal_WaitAny() to accept a function pointer argument,
+         which will return Environment.HasShutdownStarted in managed code (the 
+         moral equivalent of mono_runtime_is_shutting_down()).  This allows
+         us to avoid a libmono dependency w/o lots of rewriting. Fixes #592981.
+
+2010-04-07 Gonzalo Paniagua Javier <gonzalo@novell.com>
+
+       * zlib-helper.c: now that we don't use Z_SYNC_FLUSH, there might be
+       unflushed input in zstream, so always call Z_FINISH.
+
+2010-04-02  Jonathan Pryor  <jpryor@novell.com>
+
+       * Makefile.am: On non-Windows platforms, MonoPosixHelper now links
+         against libmono.so, for mono_runtime_is_shutting_down().
+       * signal.c: Only continue retrying system calls if Mono is NOT
+         attempting to shut down.  Fixes #592981.
+
+2010-03-29  Zoltan Varga  <vargaz@gmail.com>
+
+       * mph.h: Applied some changes from the openbsd ports tree to fix openbsd
+       support.
+
+2010-03-23  Andreas Faerber  <andreas.faerber@web.de>
+
+       * old-map.c (map_Mono_Posix_Signals): Fix build for platforms where
+       SIGIO is not defined (Haiku).
+       
+       Code is contributed under MIT/X11 license.
+
 2010-02-23  Carlos Alberto Cortez <calberto.cortez@gmail.com>
 
        * serial.cs: Add 921600 to the list of possible baud rates, and
index 4673ac51439cfeab01f3553fc5ebdc4691990d9d..939d915d949553729d64b6e89577b9152cc3aa54 100644 (file)
@@ -29,6 +29,7 @@
 
 G_BEGIN_DECLS
 
+#if HAVE_SEEKDIR
 gint32
 Mono_Posix_Syscall_seekdir (void *dir, mph_off_t offset)
 {
@@ -38,12 +39,15 @@ Mono_Posix_Syscall_seekdir (void *dir, mph_off_t offset)
 
        return 0;
 }
+#endif  /* def HAVE_SEEKDIR */
 
+#if HAVE_TELLDIR
 mph_off_t
 Mono_Posix_Syscall_telldir (void *dir)
 {
        return telldir ((DIR*) dir);
 }
+#endif  /* def HAVE_TELLDIR */
 
 static void
 copy_dirent (struct Mono_Posix_Syscall__Dirent *to, struct dirent *from)
index 2f9ff351cc5311c35f9787058038573bd8173c79..09aff343270d79148b7d626d06724e7b6bdac232 100644 (file)
@@ -226,6 +226,7 @@ Mono_Posix_Syscall_getgrgid_r (mph_gid_t gid,
 }
 #endif /* ndef HAVE_GETGRGID_R */
 
+#if HAVE_GETGRENT
 gint32
 Mono_Posix_Syscall_getgrent (struct Mono_Posix_Syscall__Group *grbuf)
 {
@@ -247,6 +248,7 @@ Mono_Posix_Syscall_getgrent (struct Mono_Posix_Syscall__Group *grbuf)
        }
        return 0;
 }
+#endif  /* def HAVE_GETGRENT */
 
 #ifdef HAVE_FGETGRENT
 gint32
@@ -272,13 +274,16 @@ Mono_Posix_Syscall_fgetgrent (void *stream, struct Mono_Posix_Syscall__Group *gr
 }
 #endif /* ndef HAVE_FGETGRENT */
 
+#if HAVE_SETGROUPS
 gint32
 Mono_Posix_Syscall_setgroups (mph_size_t size, mph_gid_t *list)
 {
        mph_return_if_size_t_overflow (size);
        return setgroups ((size_t) size, list);
 }
+#endif  /* def HAVE_SETGROUPS */
 
+#if HAVE_SETGRENT
 int
 Mono_Posix_Syscall_setgrent (void)
 {
@@ -289,13 +294,16 @@ Mono_Posix_Syscall_setgrent (void)
        mph_return_if_val_in_list5(errno, EIO, EMFILE, ENFILE, ENOMEM, ERANGE);
        return 0;
 }
+#endif  /* def HAVE_SETGRENT */
 
+#if HAVE_ENDGRENT
 int
 Mono_Posix_Syscall_endgrent (void)
 {
        endgrent();
        return 0;
 }
+#endif  /* def HAVE_ENDGRENT */
 
 
 G_END_DECLS
index 03f60745c5de388fbba0e6d6dbc8a6f352b07f01..d2cf5e7bcdbb95922b01c51f2200283350af380d 100644 (file)
@@ -99,6 +99,7 @@ char *helper_Mono_Posix_readdir(void *dir) {
        return strdup (e->d_name);
 }
 
+#if HAVE_GETPWNAM_R
 int helper_Mono_Posix_getpwnamuid (int mode, char *in_name, int in_uid,
        char **account,
        char **password,
@@ -145,3 +146,5 @@ int helper_Mono_Posix_getpwnamuid (int mode, char *in_name, int in_uid,
 
        return 0;
 }
+#endif  /* def HAVE_GETPWNAM_R */
+
index d35416392c9f0b2c4cde82ac826d2f51a1e5b7c4..a2e59fd9309929873655afc9a2e39175216f6832 100644 (file)
@@ -1401,6 +1401,7 @@ struct utimbuf;
  * Delegate Declarations
  */
 
+typedef int (*Mono_Posix_RuntimeIsShuttingDown) (void);
 
 /*
  * Structures
@@ -1743,7 +1744,7 @@ int Mono_Posix_Syscall_WTERMSIG (int status);
 int Mono_Posix_ToStatvfs (void* source, struct Mono_Posix_Statvfs* destination);
 void* Mono_Unix_UnixSignal_install (int signum);
 int Mono_Unix_UnixSignal_uninstall (void* info);
-int Mono_Unix_UnixSignal_WaitAny (void** infos, int count, int timeout);
+int Mono_Unix_UnixSignal_WaitAny (void** infos, int count, int timeout, Mono_Posix_RuntimeIsShuttingDown shutting_down);
 int wexitstatus (int status);
 int wifexited (int status);
 int wifsignaled (int status);
index db0324cc65139ef7a7e59b3b45843a72624c8176..8a61999942641e4e81bb5c953e5c04f494510c4f 100644 (file)
@@ -36,7 +36,7 @@
 #include <stdint.h>             /* for SIZE_MAX */
 #endif
 
-#if __APPLE__ || __BSD__ || __FreeBSD__
+#if __APPLE__ || __BSD__ || __FreeBSD__ || __OpenBSD__
 #define MPH_ON_BSD
 #endif
 
 #define MPH_INTERNAL
 #endif
 
-#if defined (HOST_WIN32) && !defined (EOVERFLOW)
-#define EOVERFLOW 75
-#endif /* def HOST_WIN32 && ndef EOVERFLOW */
+#if !defined(EOVERFLOW)
+#  if defined(HOST_WIN32)
+#    define EOVERFLOW 75
+#  elif defined(__OpenBSD__)
+#    define EOVERFLOW 87
+#  endif
+#endif /* !defined(EOVERFLOW) */
 
 #if !defined (HOST_WIN32)
 
index bd26a675c870c8e9924dda3f4b5a442ebf2902ee..9b2a2e907d775a3710f1d1cadefd514196d69cd8 100644 (file)
@@ -159,8 +159,10 @@ int map_Mono_Posix_Signals (int x)
                 return SIGPROF;
        if (x == Mono_Posix_Signals_SIGWINCH)
                 return SIGWINCH;
+#ifdef SIGIO
        if (x == Mono_Posix_Signals_SIGIO)
                 return SIGIO;
+#endif
        if (x == Mono_Posix_Signals_SIGSYS)
                 return SIGSYS;
        return -1;
index 13bccef9b559a9392c6787f8dc47c19ab485296b..4bb6ad6ca2b532e51f3e014cdcb6203b265ff339 100644 (file)
@@ -22,7 +22,9 @@ static const mph_string_offset_t
 passwd_offsets[] = {
        MPH_STRING_OFFSET (struct passwd, pw_name,    MPH_STRING_OFFSET_PTR),
        MPH_STRING_OFFSET (struct passwd, pw_passwd,  MPH_STRING_OFFSET_PTR),
+#if HAVE_STRUCT_PASSWD_PW_GECOS
        MPH_STRING_OFFSET (struct passwd, pw_gecos,   MPH_STRING_OFFSET_PTR),
+#endif  /* def HAVE_STRUCT_PASSWD_PW_GECOS */
        MPH_STRING_OFFSET (struct passwd, pw_dir,     MPH_STRING_OFFSET_PTR),
        MPH_STRING_OFFSET (struct passwd, pw_shell,   MPH_STRING_OFFSET_PTR)
 };
@@ -31,7 +33,9 @@ static const mph_string_offset_t
 mph_passwd_offsets[] = {
        MPH_STRING_OFFSET (struct Mono_Posix_Syscall__Passwd, pw_name,    MPH_STRING_OFFSET_PTR),
        MPH_STRING_OFFSET (struct Mono_Posix_Syscall__Passwd, pw_passwd,  MPH_STRING_OFFSET_PTR),
+#if HAVE_STRUCT_PASSWD_PW_GECOS
        MPH_STRING_OFFSET (struct Mono_Posix_Syscall__Passwd, pw_gecos,   MPH_STRING_OFFSET_PTR),
+#endif  /* def HAVE_STRUCT_PASSWD_PW_GECOS */
        MPH_STRING_OFFSET (struct Mono_Posix_Syscall__Passwd, pw_dir,     MPH_STRING_OFFSET_PTR),
        MPH_STRING_OFFSET (struct Mono_Posix_Syscall__Passwd, pw_shell,   MPH_STRING_OFFSET_PTR)
 };
@@ -187,6 +191,7 @@ Mono_Posix_Syscall_getpwuid_r (mph_uid_t uid,
 }
 #endif /* ndef HAVE_GETPWUID_R */
 
+#if HAVE_GETPWENT
 gint32
 Mono_Posix_Syscall_getpwent (struct Mono_Posix_Syscall__Passwd *pwbuf)
 {
@@ -208,6 +213,7 @@ Mono_Posix_Syscall_getpwent (struct Mono_Posix_Syscall__Passwd *pwbuf)
        }
        return 0;
 }
+#endif  /* def HAVE_GETPWENT */
 
 #ifdef HAVE_FGETPWENT
 gint32
@@ -233,6 +239,7 @@ Mono_Posix_Syscall_fgetpwent (void *stream, struct Mono_Posix_Syscall__Passwd *p
 }
 #endif /* ndef HAVE_FGETPWENT */
 
+#if HAVE_SETPWENT
 int
 Mono_Posix_Syscall_setpwent (void)
 {
@@ -243,7 +250,9 @@ Mono_Posix_Syscall_setpwent (void)
        mph_return_if_val_in_list5(errno, EIO, EMFILE, ENFILE, ENOMEM, ERANGE);
        return 0;
 }
+#endif  /* def HAVE_SETPWENT */
 
+#if HAVE_ENDPWENT
 int
 Mono_Posix_Syscall_endpwent (void)
 {
@@ -253,6 +262,7 @@ Mono_Posix_Syscall_endpwent (void)
                return -1;
        return 0;
 }
+#endif  /* def HAVE_ENDPWENT */
 
 G_END_DECLS
 
index 66f5c0ecb9045804f3283bb1b19d0adfd5947c63..c92bf3c69d3f3679e44cf6286b78b9b905935aa4 100644 (file)
@@ -24,6 +24,7 @@
 #include <string.h>
 #include <pthread.h>
 #include <mono/io-layer/atomic.h>
+#include <mono/metadata/appdomain.h>
 #endif
 
 G_BEGIN_DECLS
@@ -119,6 +120,7 @@ int Mono_Posix_FromRealTimeSignum (int offset, int *r)
        #define mph_int_set(p,o,n) do { *(p) = n; } while (0)
 #endif
 
+#if HAVE_PSIGNAL
 int
 Mono_Posix_Syscall_psignal (int sig, const char* s)
 {
@@ -126,6 +128,7 @@ Mono_Posix_Syscall_psignal (int sig, const char* s)
        psignal (sig, s);
        return errno == 0 ? 0 : -1;
 }
+#endif  /* def HAVE_PSIGNAL */
 
 #define NUM_SIGNALS 64
 static signal_info signals[NUM_SIGNALS];
@@ -151,6 +154,12 @@ static void release_mutex (pthread_mutex_t *mutex)
        }
 }
 
+static inline int
+keep_trying (int r)
+{
+       return r == -1 && errno == EINTR;
+}
+
 static void
 default_handler (int signum)
 {
@@ -168,7 +177,7 @@ default_handler (int signum)
                        pipecounter = mph_int_get (&h->pipecnt);
                        for (j = 0; j < pipecounter; ++j) {
                                int r;
-                               do { r = write (fd, &c, 1); } while (r == -1 && errno == EINTR);
+                               do { r = write (fd, &c, 1); } while (keep_trying (r));
                                fsync (fd); /* force */
                        }
                }
@@ -326,7 +335,7 @@ teardown_pipes (signal_info** signals, int count)
 }
 
 static int
-wait_for_any (signal_info** signals, int count, int *currfd, struct pollfd* fd_structs, int timeout)
+wait_for_any (signal_info** signals, int count, int *currfd, struct pollfd* fd_structs, int timeout, Mono_Posix_RuntimeIsShuttingDown shutting_down)
 {
        int r, idx;
        do {
@@ -338,7 +347,7 @@ wait_for_any (signal_info** signals, int count, int *currfd, struct pollfd* fd_s
                        ptv = &tv;
                }
                r = poll (fd_structs, count, timeout);
-       } while (r == -1 && errno == EINTR);
+       } while (keep_trying (r) && !shutting_down ());
 
        idx = -1;
        if (r == 0)
@@ -352,7 +361,7 @@ wait_for_any (signal_info** signals, int count, int *currfd, struct pollfd* fd_s
                                char c;
                                do {
                                        r = read (h->read_fd, &c, 1);
-                               } while (r == -1 && errno == EINTR);
+                               } while (keep_trying (r) && !shutting_down ());
                                if (idx == -1)
                                        idx = i;
                        }
@@ -368,7 +377,7 @@ wait_for_any (signal_info** signals, int count, int *currfd, struct pollfd* fd_s
  *          index into _signals array of signal that was generated on success
  */
 int
-Mono_Unix_UnixSignal_WaitAny (void** _signals, int count, int timeout /* milliseconds */)
+Mono_Unix_UnixSignal_WaitAny (void** _signals, int count, int timeout /* milliseconds */, Mono_Posix_RuntimeIsShuttingDown shutting_down)
 {
        int r;
        int currfd = 0;
@@ -387,7 +396,7 @@ Mono_Unix_UnixSignal_WaitAny (void** _signals, int count, int timeout /* millise
        release_mutex (&signals_mutex);
 
        if (r == 0) {
-               r = wait_for_any (signals, count, &currfd, &fd_structs[0], timeout);
+               r = wait_for_any (signals, count, &currfd, &fd_structs[0], timeout, shutting_down);
        }
 
        if (acquire_mutex (&signals_mutex) == -1)
index 60fecdd92c5a11832f12ae1ac9010aebf6831068..2096dcff251671ef4068bcba1c47b9f6558c4b19 100644 (file)
 #include "mph.h"
 #include "map.h"
 
+#ifdef HAVE_PATHCONF_H
+#include <pathconf.h>
+#endif
+
 #ifdef HAVE_SYS_STATVFS_H
 #include <sys/statvfs.h>
+#elif defined (HAVE_STATFS) || defined (HAVE_FSTATFS)
+#include <sys/vfs.h>
 #endif /* def HAVE_SYS_STATVFS_H */
 
 #ifdef HAVE_GETFSSTAT
@@ -142,8 +148,10 @@ Mono_Posix_ToStatvfs (void *_from, struct Mono_Posix_Statvfs *to)
        // so this shouldn't lose anything.
        memcpy (&to->f_fsid, &from->f_fsid, sizeof(to->f_fsid));
 
+#if HAVE_STRUCT_STATFS_F_FLAGS
        if (Mono_Posix_ToMountFlags (from->f_flags, &to->f_flag) != 0)
                return -1;
+#endif  /* def HAVE_STRUCT_STATFS_F_FLAGS */
 
        return 0;
 }
@@ -165,9 +173,11 @@ Mono_Posix_FromStatvfs (struct Mono_Posix_Statvfs *from, void *_to)
        // so this shouldn't lose anything.
        memcpy (&to->f_fsid, &from->f_fsid, sizeof(to->f_fsid));
 
+#if HAVE_STRUCT_STATFS_F_FLAGS
        if (Mono_Posix_FromMountFlags (from->f_flag, &flag) != 0)
                return -1;
        to->f_flags = flag;
+#endif  /* def HAVE_STRUCT_STATFS_F_FLAGS */
 
        return 0;
 }
index fdb8b63cd6ab5a6b61d8497fe0eb8acbc9866d98..1759ec0fcb8e23f2435d8cb45d0e846a53b9edcb 100644 (file)
@@ -124,6 +124,7 @@ Mono_Posix_Syscall_lutimes(const char *filename, struct Mono_Posix_Timeval *tv)
 }
 #endif /* def HAVE_LUTIMES */
 
+#if HAVE_FUTIMES
 gint32
 Mono_Posix_Syscall_futimes(int fd, struct Mono_Posix_Timeval *tv)
 {
@@ -134,6 +135,7 @@ Mono_Posix_Syscall_futimes(int fd, struct Mono_Posix_Timeval *tv)
 
        return futimes (fd, ptv);
 }
+#endif  /* def HAVE_FUTIMES */
 
 G_END_DECLS
 
index 209c0c1c450c1bae02b7fec90dbdcae168d1d94c..5652329e13ff78abe8ca97b54789c5ded2522e7e 100644 (file)
@@ -116,6 +116,7 @@ Mono_Posix_Syscall_sysconf (int name, int defaultError)
        return sysconf (name);
 }
 
+#if HAVE_CONFSTR
 mph_size_t
 Mono_Posix_Syscall_confstr (int name, char *buf, mph_size_t len)
 {
@@ -124,6 +125,7 @@ Mono_Posix_Syscall_confstr (int name, char *buf, mph_size_t len)
                return -1;
        return confstr (name, buf, (size_t) len);
 }
+#endif  /* def HAVE_CONFSTR */
 
 #ifdef HAVE_TTYNAME_R
 gint32
@@ -145,12 +147,14 @@ Mono_Posix_Syscall_readlink (const char *path, char *buf, mph_size_t len)
        return r;
 }
 
+#if HAVE_GETLOGIN_R
 gint32
 Mono_Posix_Syscall_getlogin_r (char *buf, mph_size_t len)
 {
        mph_return_if_size_t_overflow (len);
        return getlogin_r (buf, (size_t) len);
 }
+#endif  /* def HAVE_GETLOGIN_R */
 
 gint32
 Mono_Posix_Syscall_gethostname (char *buf, mph_size_t len)
@@ -159,18 +163,22 @@ Mono_Posix_Syscall_gethostname (char *buf, mph_size_t len)
        return gethostname (buf, (size_t) len);
 }
 
+#if HAVE_SETHOSTNAME
 gint32
 Mono_Posix_Syscall_sethostname (const char *name, mph_size_t len)
 {
        mph_return_if_size_t_overflow (len);
        return sethostname (name, (size_t) len);
 }
+#endif  /* def HAVE_SETHOSTNAME */
 
+#if HAVE_GETHOSTID
 gint64
 Mono_Posix_Syscall_gethostid (void)
 {
        return gethostid ();
 }
+#endif  /* def HAVE_GETHOSTID */
 
 #ifdef HAVE_SETHOSTID
 gint32
@@ -204,12 +212,17 @@ Mono_Posix_Syscall_setdomainname (const char *name, mph_size_t len)
 }
 #endif /* def HAVE_SETDOMAINNAME */
 
+/* Android implements truncate, but doesn't declare it.
+ * Result is a warning during compilation, so skip it.
+ */
+#ifndef PLATFORM_ANDROID
 gint32
 Mono_Posix_Syscall_truncate (const char *path, mph_off_t length)
 {
        mph_return_if_off_t_overflow (length);
        return truncate (path, (off_t) length);
 }
+#endif
 
 gint32
 Mono_Posix_Syscall_ftruncate (int fd, mph_off_t length)
@@ -218,6 +231,7 @@ Mono_Posix_Syscall_ftruncate (int fd, mph_off_t length)
        return ftruncate (fd, (off_t) length);
 }
 
+#if HAVE_LOCKF
 gint32
 Mono_Posix_Syscall_lockf (int fd, int cmd, mph_off_t len)
 {
@@ -226,7 +240,9 @@ Mono_Posix_Syscall_lockf (int fd, int cmd, mph_off_t len)
                return -1;
        return lockf (fd, cmd, (off_t) len);
 }
+#endif  /* def HAVE_LOCKF */
 
+#if HAVE_SWAB
 int
 Mono_Posix_Syscall_swab (void *from, void *to, mph_ssize_t n)
 {
@@ -235,20 +251,25 @@ Mono_Posix_Syscall_swab (void *from, void *to, mph_ssize_t n)
        swab (from, to, (ssize_t) n);
        return 0;
 }
+#endif  /* def HAVE_SWAB */
 
+#if HAVE_SETUSERSHELL
 int
 Mono_Posix_Syscall_setusershell (void)
 {
        setusershell ();
        return 0;
 }
+#endif  /* def HAVE_SETUSERSHELL */
 
+#if HAVE_ENDUSERSHELL
 int
 Mono_Posix_Syscall_endusershell (void)
 {
        endusershell ();
        return 0;
 }
+#endif  /* def HAVE_ENDUSERSHELL */
 
 int
 Mono_Posix_Syscall_sync (void)
index f8f1587ccd9be35960fa0b8cf285f07bfb3a786b..66b58663a5eb6beff5f7b34638bc2a01fbd65d3c 100644 (file)
@@ -103,7 +103,7 @@ CloseZStream (ZStream *zstream)
 
        status = 0;
        if (zstream->compress) {
-               if (zstream->stream->total_out) {
+               if (zstream->stream->total_in > 0) {
                        do {
                                status = deflate (zstream->stream, Z_FINISH);
                                flush_status = Flush (zstream);
index 7c5d00cb02623a1b4e4ab9e31757995aa548807b..cad06784fdbf7c15d6d157fc51bfc34f32487c6a 100644 (file)
        In each entry, strings are extracted to locale_strings table, and in each structure they are
        represented as an index to the string.
 
+* updating the data
+
+       Currently, when we need to fix or update data, we need to modify or
+       add the proper file in the supp directory (if it's a new file it must be added
+       in Makefile.am as well to supp_data_files).
+       To create the files used by the runtime after an update, run:
+               make culture-table
+               make install-culture-table
+       At the start of Makefile.am there are additional instructions for specific builds.
 
index 24b3575549c75875aebe87939c8ae9832d05141b..28a3ef12a77af37eb41da803198befc64de0b723 100644 (file)
@@ -1,3 +1,8 @@
+2010-03-23  Geoff Norton  <gnorton@novell.com>
+
+       * da_DK.xml: The short format is day. month, not 
+       day month.  Fixes #588165
+
 2008-09-18  Atsushi Enomoto  <atsushi@ximian.com>
 
        * sv_SE.xml : fix bug #426942 (sv-SE time format was old).
index 566be9f5f93d1cd859b4b3bfe5ca8b521600e181..80e784c6a6f8e358cb63e1b2a90f90de5910a13e 100755 (executable)
                                                        <pattern>dd-MM-yyyy</pattern>
                                                </dateFormat>
                                        </dateFormatLength >
+                                        <dateFormatLength type="month_day">
+                                                <dateFormat>
+                                                        <pattern>dd. MMMM</pattern>
+                                                </dateFormat>
+                                        </dateFormatLength>
                                </dateFormats>
                                <timeFormats>
                                        <timeFormatLength type="long">
@@ -29,4 +34,4 @@
                        </calendar>
                </calendars>
        </dates>
-</ldml>
\ No newline at end of file
+</ldml>
index f114ff8c4ddf07e697ecbc3a3cd72922814d1b11..67a9b3f211e54743ee69cd975c9bc0f11a852b5a 100644 (file)
@@ -20,6 +20,7 @@ read_entry (FILE *in, void **data)
        case SGEN_PROTOCOL_ALLOC: size = sizeof (SGenProtocolAlloc); break;
        case SGEN_PROTOCOL_COPY: size = sizeof (SGenProtocolCopy); break;
        case SGEN_PROTOCOL_PIN: size = sizeof (SGenProtocolPin); break;
+       case SGEN_PROTOCOL_MARK: size = sizeof (SGenProtocolMark); break;
        case SGEN_PROTOCOL_WBARRIER: size = sizeof (SGenProtocolWBarrier); break;
        case SGEN_PROTOCOL_GLOBAL_REMSET: size = sizeof (SGenProtocolGlobalRemset); break;
        case SGEN_PROTOCOL_PTR_UPDATE: size = sizeof (SGenProtocolPtrUpdate); break;
@@ -63,6 +64,11 @@ print_entry (int type, void *data)
                printf ("pin obj %p vtable %p size %d\n", entry->obj, entry->vtable, entry->size);
                break;
        }
+       case SGEN_PROTOCOL_MARK: {
+               SGenProtocolMark *entry = data;
+               printf ("mark obj %p vtable %p size %d\n", entry->obj, entry->vtable, entry->size);
+               break;
+       }
        case SGEN_PROTOCOL_WBARRIER: {
                SGenProtocolWBarrier *entry = data;
                printf ("wbarrier ptr %p value %p value_vtable %p\n", entry->ptr, entry->value, entry->value_vtable);
@@ -142,6 +148,10 @@ is_match (gpointer ptr, int type, void *data)
                SGenProtocolPin *entry = data;
                return matches_interval (ptr, entry->obj, entry->size);
        }
+       case SGEN_PROTOCOL_MARK: {
+               SGenProtocolMark *entry = data;
+               return matches_interval (ptr, entry->obj, entry->size);
+       }
        case SGEN_PROTOCOL_WBARRIER: {
                SGenProtocolWBarrier *entry = data;
                return ptr == entry->ptr || ptr == entry->value;